Ejemplo n.º 1
0
    def plot(self, Ps):
        from mayavi import mlab

        mlab.figure(mlab.figure(), bgcolor=(1, 1, 1))
        for s in range(len(Ps)):
            mlab.mesh(Ps[s][:, :, 0], Ps[s][:, :, 1], Ps[s][:, :, 2], color=(65 / 256, 105 / 256, 225 / 256))
        mlab.show()
Ejemplo n.º 2
0
    def test_close(self):
        """ Various tests for mlab.close().
        """
        f = mlab.figure()
        self.assertTrue(f.running)
        mlab.close(f)
        self.assertFalse(f.running)

        f = mlab.figure(314)
        self.assertTrue(f.running)
        mlab.close(314)
        self.assertFalse(f.running)

        f = mlab.figure('test_figure')
        self.assertTrue(f.running)
        mlab.close('test_figure')
        self.assertFalse(f.running)

        f = mlab.figure()
        self.assertTrue(f.running)
        mlab.close()
        self.assertFalse(f.running)

        figs = [mlab.figure() for i in range(5)]
        for f in figs:
            self.assertTrue(f.running)
        mlab.close(all=True)
        for f in figs:
            self.assertFalse(f.running)
Ejemplo n.º 3
0
def vis_voxels(model_id, edge_length_threshold, filled, shuffle=False):
    from mayavi import mlab
    from util3d.mayavi_vis import vis_voxels
    from shapenet.core import cat_desc_to_id
    from template_ffd.inference.voxels import get_voxel_dataset
    from template_ffd.data.voxels import get_gt_voxel_dataset
    from template_ffd.model import load_params
    from template_ffd.data.ids import get_example_ids
    cat_id = cat_desc_to_id(load_params(model_id)['cat_desc'])
    gt_ds = get_gt_voxel_dataset(cat_id, filled)
    inf_ds = get_voxel_dataset(model_id, edge_length_threshold)
    example_ids = get_example_ids(cat_id, 'eval')
    if shuffle:
        example_ids = list(example_ids)
        example_ids.shuffle

    with gt_ds:
        with inf_ds:
            for example_id in example_ids:
                gt = gt_ds[example_id].data
                inf = inf_ds[example_id].data
                vis_voxels(gt, color=(0, 0, 1))
                mlab.figure()
                vis_voxels(inf, color=(0, 1, 0))
                mlab.show()
Ejemplo n.º 4
0
    def testVisually(self):
        '''blocks selected visually.'''
#        if self.comm.rank == 0:
        g2z,zvec = PETSc.Scatter().toZero(self.bnd.gindBlockWBand)
        g2z.scatter(self.bnd.gindBlockWBand,zvec, PETSc.InsertMode.INSERT)
        x = self.bnd.BlockSub2CenterCarWithoutBand(\
                                                   self.bnd.BlockInd2SubWithoutBand(zvec.getArray()) )
        lx = self.bnd.BlockSub2CenterCarWithoutBand(\
                                                    self.bnd.BlockInd2SubWithoutBand(self.bnd.gindBlockWBand.getArray()))
        try:
            try:
                from mayavi import mlab
            except ImportError:
                from enthought.mayavi import mlab

            if self.comm.rank == 0:
                mlab.figure()
                mlab.points3d(x[:,0],x[:,1],x[:,2])
            mlab.figure()
            mlab.points3d(lx[:,0],lx[:,1],lx[:,2])
            mlab.show()
            #fig.add(pts1)
            #fig.add(pts2)
        except ImportError:
            import pylab as pl
            from mpl_toolkits.mplot3d import Axes3D #@UnusedImport
            fig = pl.figure()
            ax = fig.add_subplot(111, projection='3d')
            ax.scatter3D(x[:,0],x[:,1],x[:,2],c='blue',marker='o')
            ax.scatter3D(lx[:,0],lx[:,1],lx[:,2],c='red',marker='D')
            pl.savefig('testVis{0}.png'.format(self.comm.rank))
            pl.show()
def showDsweep():
    k_s_sweep = [10**(x-5) for x in range(10)]
    sl_div_diam_sweep = [5.0*(x+1)/1000 for x in range(20)]
    vol_ratio_sweep = [5.0*(x+1)/100 for x in range(10)]    
    
    Dmsd = numpy.load(data_dir + "/D_numpy.npy")
    kDa = 1.660538921e-30;
    mass = 40.0*kDa; 
    viscosity = 8.9e-4; 
    diameter = 5e-9; 
    T = 300.0; 
    Dbase = k_b*T/(3.0*numpy.pi*viscosity*diameter);
    Dmsd = Dmsd/Dbase
    
    mlab.figure(1, size=(800, 800), fgcolor=(1, 1, 1),
                                    bgcolor=(0.5, 0.5, 0.5))
    mlab.clf()
    contours = numpy.arange(0.01,2,0.2).tolist()
    obj = mlab.contour3d(Dmsd,contours=contours,transparent=True,vmin=contours[0],vmax=contours[-1])
    outline = mlab.outline(color=(.7, .7, .7),extent=(0,10,0,20,0,10))
    axes = mlab.axes(outline, color=(.7, .7, .7),
            nb_labels = 5,
            ranges=(k_s_sweep[0], k_s_sweep[-1], sl_div_diam_sweep[0], sl_div_diam_sweep[-1], vol_ratio_sweep[0], vol_ratio_sweep[-1]), 
            xlabel='spring stiffness', 
            ylabel='step length',
            zlabel='volume ratio')
    mlab.colorbar(obj,title='D',nb_labels=5)

    mlab.show()
Ejemplo n.º 6
0
def figure(size=None, zdown=True):
    """
    Create a default figure in Mayavi with white background

    Parameters:

    * size : tuple = (dx, dy)
        The size of the figure. If ``None`` will use the default size.
    * zdown : True or False
        If True, will turn the figure upside-down to make the z-axis point down

    Return:

    * fig : Mayavi figure object
        The figure

    """
    _lazy_import_mlab()
    if size is None:
        fig = mlab.figure(bgcolor=(1, 1, 1))
    else:
        fig = mlab.figure(bgcolor=(1, 1, 1), size=size)
    if zdown:
        fig.scene.camera.view_up = numpy.array([0., 0., -1.])
        fig.scene.camera.elevation(60.)
        fig.scene.camera.azimuth(180.)
    return fig
Ejemplo n.º 7
0
    def show_volume(self, bbox):
        """
        show the volume with the given bounding box
        """
        # load the data
        with h5py.File(self.h5fn, 'r') as f:
            seg1 = f["segmentation"]["labels"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
            raw = f["raw"]["volume"][bbox[2]:bbox[5],bbox[1]:bbox[4],bbox[0]:bbox[3]]
        
        print "Drawing volume"
        t0 = time.time()
        
        #draw everything
        fig1 = mlab.figure(1, size=(500,450))
        mlab.clf(fig1)
        visCell.drawImagePlane(fig1, raw, 'gist_ncar')
        visCell.drawVolumeWithoutReferenceCell(fig1, seg1, np.array((-1,)), (0,0,1),0.5)
        with h5py.File(self.h5fn, 'r') as f:
            visCell.drawLabels(fig1, f, seg1, bbox)

        fig2 = mlab.figure(2, size=(500,450))
        mlab.clf(fig2)

        visCell.draw2DView(fig2, raw[20:-20,:,:], seg1[20:-20,:,:], -1)
        
        t = time.time() - t0
        print "Time for drawing:",t
Ejemplo n.º 8
0
def plotSpherical(dataset, vertices, triangles, ptitle="", tsize=0.4, theight=0.95):
    """Plot the spherical data given a data set, triangle set and vertex set.

    The vertex set defines the direction cosines of the individual samples.
    The triangle set defines how the surfrace must be structured between the samples.
    The data set defines, for each direction cosine, the length of the vector.

    Args:
        | dataset(numpy.array(double)): array of data set values
        | vertices(numpy.array([])): array of direction cosine vertices as [x y z]
        | triangles(numpy.array([])): array of triangles as []
        | ptitle(string): title or header for this display
        | tsize(double): title size (units not quite clear)
        | theight(double): title height (y value) (units not quite clear)

    Returns:
        | provides and mlab figure.

    Raises:
        | No exception is raised.
"""

    # calculate a (x,y,z) data set from the direction vectors
    x = dataset * vertices[:, 0]
    y = dataset * vertices[:, 1]
    z = dataset * vertices[:, 2]

    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))

    # Visualize the points
    pts = mlab.triangular_mesh(x, y, z, triangles)  # z, scale_mode='none', scale_factor=0.2)
    mlab.title(ptitle, size=tsize, height=theight)
    mlab.show()
Ejemplo n.º 9
0
def m2screenshot(mayavi_fig=None, mpl_axes=None, autocrop=True):
    """ Capture a screeshot of the Mayavi figure and display it in the
        matplotlib axes.
    """
    import pylab as pl
    # Late import to avoid triggering wx imports before needed.
    try:
        from mayavi import mlab
    except ImportError:
        # Try out old install of Mayavi, with namespace packages
        from enthought.mayavi import mlab

    if mayavi_fig is None:
        mayavi_fig = mlab.gcf()
    else:
        mlab.figure(mayavi_fig)
    if mpl_axes is not None:
        pl.axes(mpl_axes)

    filename = tempfile.mktemp('.png')
    mlab.savefig(filename, figure=mayavi_fig)
    image3d = pl.imread(filename)
    if autocrop:
        bg_color = mayavi_fig.scene.background
        image3d = autocrop_img(image3d, bg_color)
    pl.imshow(image3d)
    pl.axis('off')
    os.unlink(filename)
Ejemplo n.º 10
0
 def draw_volume(self):
     if self.vector_field_visible or self.scalar_field_visible:
         coordinate_system = self.space.basis_in_global_coordinate_system()
         grid = coordinate_system.to_parent(self.grid.reshape(3, -1).T).T.reshape(self.grid.shape)
         if self.vector_field is None:
             mlab.figure(self.fig, bgcolor=self.fig.scene.background)
             self.vector_field = mlab.pipeline.vector_field(grid[0], grid[1], grid[2],
                                                            self.vector_data[0],
                                                            self.vector_data[1],
                                                            self.vector_data[2],
                                                            scalars=self.scalar_data,
                                                            name=self.space.name)
         else:
             origin = np.array([np.min(grid[0]), np.min(grid[1]), np.min(grid[2])])
             spacing = np.array([grid[0, 1, 0, 0] - grid[0, 0, 0, 0],
                                 grid[1, 0, 1, 0] - grid[1, 0, 0, 0],
                                 grid[2, 0, 0, 1] - grid[2, 0, 0, 0]])
             self.vector_field.spacing = spacing
             self.vector_field.origin = origin
             self.vector_field.vector_data = np.rollaxis(self.vector_data, 0, 4)
             self.vector_field.scalar_data = self.scalar_data
         if self.vector_volume is None and self.vector_field_visible:
             self.vector_volume = mlab.pipeline.vectors(self.vector_field)
         if self.scalar_volume is None and self.scalar_field_visible:
             self.scalar_volume = mlab.pipeline.volume(self.vector_field)
     if not self.vector_field_visible:
         self.remove_vector_field()
     if not self.scalar_field_visible:
         self.remove_scalar_field()
Ejemplo n.º 11
0
def zoncaview(m):
    """
    m is a healpix sky map, such as provided by WMAP or Planck.
    """

    nside = hp.npix2nside(len(m))
    vmin = -1e3; vmax = 1e3

    # Set up some grids:
    xsize = ysize = 1000
    theta = np.linspace(np.pi, 0, ysize)
    phi   = np.linspace(-np.pi, np.pi, xsize)
    longitude = np.radians(np.linspace(-180, 180, xsize))
    latitude = np.radians(np.linspace(-90, 90, ysize))

    # Project the map to a rectangular matrix xsize x ysize:
    PHI, THETA = np.meshgrid(phi, theta)
    grid_pix = hp.ang2pix(nside, THETA, PHI)
    grid_map = m[grid_pix]

    # Create a sphere:
    r = 0.3
    x = r*np.sin(THETA)*np.cos(PHI)
    y = r*np.sin(THETA)*np.sin(PHI)
    z = r*np.cos(THETA)

    # The figure:
    mlab.figure(1, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(400, 300))
    mlab.clf()

    mlab.mesh(x, y, z, scalars=grid_map, colormap="jet", vmin=vmin, vmax=vmax)

    mlab.draw()

    return
def draw_coordinate_system_axes(fig, coordinate_system, offset=0.0, scale=1.0, draw_labels=True):
    points, lengths = coordinate_system_arrows(coordinate_system, offset=offset, scale=scale)
    mlab.figure(fig, bgcolor=fig.scene.background)
    arrows = mlab.quiver3d(
        points[:, 0],
        points[:, 1],
        points[:, 2],
        lengths[0, :],
        lengths[1, :],
        lengths[2, :],
        scalars=np.array([3, 2, 1]),
        mode="arrow",
    )
    arrows.glyph.color_mode = "color_by_scalar"
    arrows.glyph.glyph.scale_factor = scale
    data = arrows.parent.parent
    data.name = coordinate_system.name
    glyph_scale = arrows.glyph.glyph.scale_factor * 1.1
    # label_col = [(1, 0, 0), (0, 1, 0), (0, 0, 1)]
    labels = []
    if draw_labels:
        for i in range(3):
            labels.append(
                mlab.text(
                    points[i, 0] + glyph_scale * coordinate_system.basis[i, 0],
                    points[i, 1] + glyph_scale * coordinate_system.basis[i, 1],
                    coordinate_system.labels[i],
                    z=points[i, 2] + glyph_scale * coordinate_system.basis[i, 2],
                    # color=label_col[i],
                    width=0.1 * scale,
                )
            )
    return arrows, labels
def plot3D(name, X, Y, Z, zlabel):
    """
    Plots a 3d surface plot of Z using the mayavi mlab.mesh function.

    Parameters
    ----------
    name: string
        The name of the figure.
    X: 2d ndarray
        The x-axis data.
    Y: 2d ndarray
        The y-axis data.
    Z: 2d nd array
        The z-axis data.
    zlabel: The title that appears on the z-axis.
    """
    mlab.figure(name)
    mlab.clf()
    plotData = mlab.mesh(X/(np.max(X) - np.min(X)),
                         Y/(np.max(Y) - np.min(Y)),
                         Z/(np.max(Z) - np.min(Z)))
    mlab.outline(plotData)
    mlab.axes(plotData, ranges=[np.min(X), np.max(X),
                                np.min(Y), np.max(Y),
                                np.min(Z), np.max(Z)])
    mlab.xlabel('Space ($x$)')
    mlab.ylabel('Time ($t$)')
    mlab.zlabel(zlabel)
Ejemplo n.º 14
0
def show_sensors(pth, red=None, green=None):
    """ 
    show sensors stored in a h5. 
    :param red: a list of labels to be shown in red    
    """
    if red is None:
        red = []
    if green is None:
        green = []

    mlab.figure()
    sensors = h5py.File(pth)
    d = numpy.array(sensors['locations'])    
    labels = list(sensors['labels'])    
    highlight = numpy.ones(d.shape[0])

    for i, l in enumerate(labels):
        if l in red:
            highlight[i] = 5.0
        elif l in green:
            highlight[i] = 7.0
        else:
            highlight[i] = 2.0    

    mlab.points3d(d[:,0], d[:,1], d[:,2], highlight, scale_mode='none')
    mlab.axes()
Ejemplo n.º 15
0
def test_surface_normals(plot=False, skip_asserts=False,
                         write_reference=False):
    "Test the surface normals of a horseshoe mesh"
    sim = openmodes.Simulation()
    mesh = sim.load_mesh(osp.join(mesh_dir, 'horseshoe_rect.msh'))
    part = sim.place_part(mesh)
    basis = sim.basis_container[part]

    r, rho = basis.integration_points(mesh.nodes, triangle_centres)
    normals = mesh.surface_normals
    r = r.reshape((-1, 3))

    if write_reference:
        write_2d_real(osp.join(reference_dir, 'surface_r.txt'), r)
        write_2d_real(osp.join(reference_dir, 'surface_normals.txt'), normals)

    r_ref = read_2d_real(osp.join(reference_dir, 'surface_r.txt'))
    normals_ref = read_2d_real(osp.join(reference_dir, 'surface_normals.txt'))

    if not skip_asserts:
        assert_allclose(r, r_ref)
        assert_allclose(normals, normals_ref)

    if plot:
        from mayavi import mlab
        mlab.figure()
        mlab.quiver3d(r[:, 0], r[:, 1], r[:, 2],
                      normals[:, 0], normals[:, 1], normals[:, 2],
                      mode='cone')
        mlab.view(distance='auto')
        mlab.show()
Ejemplo n.º 16
0
Archivo: sphere.py Proyecto: jstraub/js
def testQuaternion():
  dtheta = 30.0
  quat = Quaternion()
  print quat.q
  print quat.toRot()
  print det(quat.toRot())

  figm = mlab.figure(bgcolor=(1,1,1))
  for i in range(100):
    print quat.sampleUnif(0.5*np.pi)
    k,theta = quat.toAxisAngle()
    print theta*180.0/np.pi
    plotCosy(figm, quat.toRot())

  figm = mlab.figure(bgcolor=(1,1,1))
  for i in range(100):
    print quat.sample(dtheta)
    k,theta = quat.toAxisAngle()
    print theta*180.0/np.pi
    plotCosy(figm, quat.toRot())

  figm1 = mlab.figure(bgcolor=(1,1,0.0))
  for i in range(100):
    # sample rotation axis
    k = np.random.rand(3)-0.5
    # sample uiniformly from +- 5 degrees
    theta =  (np.asscalar(np.random.rand(1)) + dtheta - 0.5) *np.pi/180.0 # (np.a      sscalar(np.random.rand(1))-0.5)*np.pi/(180.0/(2.0*dtheta))
    print 'perturbation: {} theta={}'.format(k/norm(k),theta*180.0/np.pi)
    dR = RodriguesRotation(k/norm(k),theta)
    plotCosy(figm1, dR)
    
  mlab.show()
Ejemplo n.º 17
0
def plot3dformesh(x,cv,f):
    return
    cv = band.toZeroStatic(cv)
    if MPI.COMM_WORLD.rank == 0:
        v2 = cv.getArray()
        pl.figure(bgcolor=(1,1,1),fgcolor=(0.5,0.5,0.5))
        pl.triangular_mesh(x[:,0],x[:,1],x[:,2],f,scalars=v2)
    def test_empty(self):

        data=numpy.zeros((20,20,20))

        mlab.figure( bgcolor=(0,0,0), size=(1000,845) )
        ATMA.GUI.DataVisualizer.segmentation( data )
        mlab.close()
Ejemplo n.º 19
0
def make_montage(info, kind, check=False):
    from . import _reorder
    assert kind in ('mgh60', 'mgh70', 'uw_70', 'uw_60')
    picks = mne.pick_types(info, meg=False, eeg=True, exclude=())
    if kind in ('mgh60', 'mgh70'):
        ch_names = mne.utils._clean_names(
            [info['ch_names'][pick] for pick in picks], remove_whitespace=True)
        if kind == 'mgh60':
            assert len(ch_names) in (59, 60)
        else:
            assert len(ch_names) in (70,)
        montage = mne.channels.read_montage(kind, ch_names=ch_names)
    else:
        ch_names = getattr(_reorder, 'ch_names_' + kind)
        ch_names = ch_names
        montage = mne.channels.read_montage('standard_1020', ch_names=ch_names)
        assert len(montage.ch_names) == len(ch_names)
        montage.ch_names = ['EEG%03d' % ii for ii in range(1, 61)]
    sphere = mne.make_sphere_model('auto', 'auto', info)
    montage.pos /= np.linalg.norm(montage.pos, axis=-1, keepdims=True)
    montage.pos *= sphere.radius
    montage.pos += sphere['r0']
    info = mne.pick_info(info, picks)
    eeg_pos = np.array([ch['loc'][:3] for ch in info['chs']])
    assert len(eeg_pos) == len(montage.pos), (len(eeg_pos), len(montage.pos))
    if check:
        from mayavi import mlab
        mlab.figure(size=(800, 800))
        mlab.points3d(*sphere['r0'], scale_factor=2 * sphere.radius,
                      color=(0., 0., 1.), opacity=0.1, mode='sphere')
        mlab.points3d(*montage.pos.T, scale_factor=0.01,
                      color=(1, 0, 0), mode='sphere', opacity=0.5)
        mlab.points3d(*eeg_pos.T, scale_factor=0.005, color=(1, 1, 1),
                      mode='sphere', opacity=1)
    return montage, sphere
Ejemplo n.º 20
0
def plot_sphere_func(f, grid='Clenshaw-Curtis', theta=None, phi=None, colormap='jet', fignum=0):

    # Note: all grids except Clenshaw-Curtis have holes at the poles

    import matplotlib
    matplotlib.use('WxAgg')
    matplotlib.interactive(True)
    from mayavi import mlab

    if grid == 'Driscoll-Healy':
        b = f.shape[0] / 2
    elif grid == 'Clenshaw-Curtis':
        b = (f.shape[0] - 2) / 2
    elif grid == 'SOFT':
        b = f.shape[0] / 2
    elif grid == 'Gauss-Legendre':
        b = (f.shape[0] - 2) / 2

    if theta is None or phi is None:
        theta, phi = meshgrid(b=b, convention=grid)

    phi = np.r_[phi, phi[0, :][None, :]]
    theta = np.r_[theta, theta[0, :][None, :]]
    f = np.r_[f, f[0, :][None, :]]

    x = np.sin(theta) * np.cos(phi)
    y = np.sin(theta) * np.sin(phi)
    z = np.cos(theta)

    mlab.figure(fignum, bgcolor=(1, 1, 1), fgcolor=(0, 0, 0), size=(600, 400))
    mlab.clf()
    mlab.mesh(x, y, z, scalars=f, colormap=colormap)

    # mlab.view(90, 70, 6.2, (-1.3, -2.9, 0.25))
    mlab.show()
    def test_rawData(self):

        raw=numpy.uint32(numpy.random.rand(200,200,200)*255)

        mlab.figure( bgcolor=(0,0,0), size=(1000,845) )
        ATMA.GUI.DataVisualizer.rawSlider( raw )
        mlab.close()
Ejemplo n.º 22
0
def vis_mesh(model_id, edge_length_threshold, shuffle=False, wireframe=False):
    import numpy as np
    from mayavi import mlab
    from shapenet.core.meshes import get_mesh_dataset
    from shapenet.core import cat_desc_to_id
    from util3d.mayavi_vis import vis_mesh
    from template_ffd.inference.meshes import get_inferred_mesh_dataset
    from template_ffd.model import load_params
    import random

    def vis(mesh, **kwargs):
        v, f = (np.array(mesh[k]) for k in ('vertices', 'faces'))
        vis_mesh(v, f, include_wireframe=wireframe, **kwargs)

    cat_id = cat_desc_to_id(load_params(model_id)['cat_desc'])
    inf_mesh_dataset = get_inferred_mesh_dataset(
        model_id, edge_length_threshold)
    with inf_mesh_dataset:
        with get_mesh_dataset(cat_id) as gt_mesh_dataset:
            example_ids = list(inf_mesh_dataset.keys())
            if shuffle:
                random.shuffle(example_ids)

            for example_id in example_ids:
                inf = inf_mesh_dataset[example_id]
                gt = gt_mesh_dataset[example_id]
                mlab.figure()
                vis(inf, color=(0, 1, 0), opacity=0.2)
                mlab.figure()
                vis(gt, opacity=0.2)
                mlab.show()
Ejemplo n.º 23
0
def Main(outputFolder, isData, normalized = True):
    assert isinstance(outputFolder, str)
    min, max = 0., 1.
    if os.path.splitext(args.file)[1] == '.arff':
        datasets, targets, targetMap = loadFromArff(args.file)
    elif os.path.splitext(args.file)[1] == '.npy':
        datasets = numpy.load(args.file)
        min = -1.
    else:
        assert False

    datasets = (lambda x : histogramEqualization(x, min=min, max=max) if normalized else x)(datasets)
    if normalized : assert (datasets.min(), datasets.max()) == (min, max)

    if not os.path.isdir("%s/Pictures" % outputFolder):
        os.makedirs("%s/Pictures" % outputFolder)

    global listIndex
    if listIndex is None or (len(listIndex) >= len(datasets)):
        listIndex = xrange(len(datasets))

    for index in listIndex:
        assert 0 <= index < len(datasets)
        mlab.figure("Index : %d" % index, bgcolor=(1,1,1))
        showArray(datasets[index], isData)
        mlab.savefig("%s/Pictures/Index_%d.png" % (outputFolder, index))
        if isData:
            saveData('%s/Pictures/%s_Index_%d.txt' % (outputFolder, targetMap.reverse_mapping[targets[index]], index), datasets[index])
        else:
            saveData('%s/Pictures/Index_%d.txt' % (outputFolder, index), datasets[index])
        mlab.close()
Ejemplo n.º 24
0
def plot_matrix(connectmat_file, centers_file, threshold_pct=5, weight_edges=False,
                node_scale_factor=2, edge_radius=.5, resolution=8, name_scale_factor=1,
                names_file=None, node_indiv_colors=[], highlight_nodes=[], fliplr=False):
    """
    Given a connectivity matrix and a (x,y,z) centers file for each region, plot the 3D network
    """
    matrix = core.file_reader(connectmat_file)
    nodes = core.file_reader(centers_file)
    if names_file:
        names = core.file_reader(names_file,1)
    num_nodes = len(nodes)
    edge_thresh_pct = threshold_pct / 100.0
    matrix_flat = np.array(matrix).flatten()
    edge_thresh = np.sort(matrix_flat)[len(matrix_flat)-int(len(matrix_flat)*edge_thresh_pct)]
    
    matrix = core.file_reader(connectmat_file)
    ma = np.array(matrix)

    thresh = scipy.stats.scoreatpercentile(ma.ravel(),100-threshold_pct)
    ma_thresh = ma*(ma > thresh)
    
    if highlight_nodes:
        nr = ma.shape[0]
        subset_mat = np.zeros((nr, nr))
        for i in highlight_nodes:
            subset_mat[i,:] = 1
            subset_mat[:,i] = 1
        ma_thresh = ma_thresh * subset_mat
        
    if fliplr:
        new_nodes = []
        for node in nodes:
            new_nodes.append([45-node[0],node[1],node[2]]) # HACK
        nodes = new_nodes
    
    mlab.figure(bgcolor=(1, 1, 1), size=(400, 400))
    for count,(x,y,z) in enumerate(nodes):
        if node_indiv_colors:
            mlab.points3d(x,y,z, color=colors[node_indiv_colors[count]], scale_factor=node_scale_factor, resolution=resolution)
        else:
            mlab.points3d(x,y,z, color=(0,1,0), scale_factor=node_scale_factor, resolution=resolution)
        if names_file:
            width = .025*name_scale_factor*len(names[count])
            print width
            print names[count]
            mlab.text(x, y,names[count], z=z,width=.025*len(names[count]),color=(0,0,0))
    for i in range(num_nodes-1):    
        x0,y0,z0 = nodes[i]
        for j in range(i+1, num_nodes):
            #if matrix[i][j] > edge_thresh:
            if ma_thresh[i][j] > edge_thresh:
                x1,y1,z1 = nodes[j]
                if weight_edges:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=matrix[i][j]/matrix_flat.max(),
                            color=(1,1,1))
                else:
                    mlab.plot3d([x0,x1], [y0,y1], [z0,z1],
                            tube_radius=edge_radius,
                            color=(1,1,1))
Ejemplo n.º 25
0
def test_normals_new5 ():

#pts1 = clouds.downsample(pts1, 0.02).astype('float64')
    
#     pts1 = np.array([[0.,0.,0.], [0.,0.5,0.], [0.,1.,0.], [1.,0.,0.0], [1.,0.5,0.0], [1.,1.,0.25]])
#     pts2 = np.array([[0.,0.,0.], [0.,0.5,0.], [0.,1.,0.], [1.,0.,1.], [1.,0.5,1.], [1.,1.,1.25]])
#     e1 = np.array([[1.,0.,0.], [1.,0.,0.], [1.,0.,0.], [-1.,0.,0.], [-1.,0.,0.], [-1.,0.,0.]])
#     e2 = np.array([[1.,0.,0.], [1.,0.,0.], [1.,0.,0.], [-1.,0.,0.], [-1.,0.,0.], [-1.,0.,0.]])
    
    pts1, pts2, e1, e2 = create_flap_points_normals(3.0,1,dim=3)
    f1 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, use_cvx=True)
    #f2 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, use_cvx=True)
    f2 = te.tps_eval(pts1, pts2, e1, e2, bend_coef=0.01, rot_coef=1e-5, wt_n=None, nwsize=0.15, delta=0.0001)
    #f2 = te.tps_fit_normals_cvx(pts1, pts2, e1, e2, bend_coef=0.1, rot_coef=1e-5, normal_coef=0.1, wt_n=None, nwsize=0.15, delta=0.0001)
    #f2 = te.tps_fit_normals_exact_cvx(pts1, pts2, e1, e2, bend_coef=0.1, rot_coef=1e-5, normal_coef = 0.1, wt_n=None, nwsize=0.15, delta=0.002)
    
#    import IPython
#    IPython.embed()    
    mlab.figure(1, bgcolor=(0,0,0))
    mayavi_utils.plot_warping(f1, pts1, pts2, fine=False, draw_plinks=False)
    _,f1e2 = te.transformed_normal_direction(pts1, e1, f1, delta=0.0001)#np.asarray([tu.tps_jacobian(f2, pt, 2).dot(nm) for pt,nm in zip(pts1,e1)])
    test_normals_pts(f1.transform_points(pts1), f1e2, wsize=0.15,delta=0.15)
    test_normals_pts(pts2, e2, wsize=0.15,delta=0.15)
    #mlab.show()
    mlab.figure(2,bgcolor=(0,0,0))
    #mlab.clf()
    mayavi_utils.plot_warping(f2, pts1, pts2, fine=False, draw_plinks=False)
    _,f2e2 = te.transformed_normal_direction(pts1, e1, f2, delta=0.0001)#np.asarray([tu.tps_jacobian(f2, pt, 2).dot(nm) for pt,nm in zip(pts1,e1)])
    test_normals_pts(f2.transform_points(pts1), f2e2, wsize=0.15,delta=0.15)
    test_normals_pts(pts2, e2, wsize=0.15,delta=0.15)
    mlab.show()
Ejemplo n.º 26
0
def test_normals_new3 ():
    #pts1 = clouds.downsample(pts1, 0.02).astype('float64')
    
    pts1 = gen_circle_points(0.5, 30)
    pts2 = gen_circle_points_pulled_in(0.5,30,6,0.4)#gen_circle_points(0.5, 30) + np.array([0.1,0.1])
    wt_n = None#np.linalg.norm(pts1-pts2,axis=1)*2+1
    

    f1 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=wt_n, use_cvx=True)
    #f2 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, use_cvx=True)
    #f2 = te.tps_eval(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, nwsize=0.15, delta=0.0001)
    #f2 = te.tps_fit_normals_cvx(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, normal_coef=10, wt_n=wt_n, nwsize=0.15, delta=0.0001)
    #f2 = te.tps_fit_normals_cvx(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, normal_coef=0.1, wt_n=None, nwsize=0.15, delta=0.0001)
    f2 = te.tps_fit_normals_exact_cvx(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, normal_coef = 1, wt_n=None, nwsize=0.15, delta=0.0001)    
    mlab.figure(1, bgcolor=(0,0,0))
    mayavi_utils.plot_warping(f1, pts1, pts2, fine=False, draw_plinks=True)
    test_normals_pts(np.c_[f1.transform_points(pts1),np.zeros((pts2.shape[0],1))], wsize=0.15,delta=0.15)
    test_normals_pts(np.c_[pts2,np.zeros((pts2.shape[0],1))], wsize=0.15,delta=0.15)
    #mlab.show()
    mlab.figure(2,bgcolor=(0,0,0))
    #mlab.clf()
    mayavi_utils.plot_warping(f2, pts1, pts2, fine=False, draw_plinks=True)
    test_normals_pts(np.c_[f2.transform_points(pts1),np.zeros((pts2.shape[0],1))], wsize=0.15,delta=0.15)
    test_normals_pts(np.c_[pts2,np.zeros((pts2.shape[0],1))], wsize=0.15,delta=0.15)
    mlab.show()
Ejemplo n.º 27
0
def test_normals_new4 (n=2,l=0.5,dim=2):

    pts1, pts2, e1, e2 = create_flap_points_normals(n,l,dim)

    delta = 1e-2
    f1 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, use_cvx=True)
    #f1 = te.tps_fit_normals_cvx(pts1, pts2, e1, e2, bend_coef=0.1, rot_coef=1e-5, normal_coef=0.1, wt_n=None, nwsize=0.15, delta=0.0001)
    #f2 = fit_ThinPlateSpline(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, wt_n=None, use_cvx=True)
    #f2 = te.tps_eval(pts1, pts2, e1, e2, bend_coef=0.0, rot_coef=1e-5, wt_n=None, nwsize=0.15, delta=1e-8)
    #f2 = te.tps_fit_normals_cvx(pts1, pts2, bend_coef=0.1, rot_coef=1e-5, normal_coef=10, wt_n=None, nwsize=0.15, delta=1e-6)
    f2 = te.tps_fit_normals_cvx(pts1, pts2, e1, e2, bend_coef=0.0, rot_coef=1e-5, normal_coef=1, wt_n=None, nwsize=0.15, delta=delta)

    mlab.figure(1, bgcolor=(0,0,0))
    mayavi_utils.plot_warping(f1, pts1, pts2, fine=False, draw_plinks=False)
    _,f1e2 = te.transformed_normal_direction(pts1, e1, f1, delta=delta)#np.asarray([tu.tps_jacobian(f2, pt, 2).dot(nm) for pt,nm in zip(pts1,e1)])
    test_normals_pts(np.c_[f1.transform_points(pts1),np.zeros((pts2.shape[0],1))], np.c_[f1e2,np.zeros((f1e2.shape[0],1))], wsize=0.15,delta=0.15)
    test_normals_pts(np.c_[pts2,np.zeros((pts2.shape[0],1))], np.c_[e2,np.zeros((e2.shape[0],1))], wsize=0.15,delta=0.15)
    #mlab.show()
    mlab.figure(2,bgcolor=(0,0,0))
    #mlab.clf()
    mayavi_utils.plot_warping(f2, pts1, pts2, fine=False, draw_plinks=False)
    _,f2e2 = te.transformed_normal_direction(pts1, e1, f2, delta=delta)
    test_normals_pts(np.c_[f2.transform_points(pts1),np.zeros((pts2.shape[0],1))], np.c_[f2e2,np.zeros((f2e2.shape[0],1))], wsize=0.15,delta=0.15)
    test_normals_pts(np.c_[pts2,np.zeros((pts2.shape[0],1))], np.c_[e2,np.zeros((e2.shape[0],1))],  wsize=0.15,delta=0.15)
    mlab.show()
def short_branches():
    """
    Visualization of short branches of the skeleton.
    
    """
    data1_sk = glob.glob('/backup/yuliya/vsi05/skeletons_largdom/*.h5')
    data1_sk.sort()

    for i,j, k in zip(d[1][37:47], data1_sk[46:56], ell[1][37:47]):
        g = nx.read_gpickle(i)
        dat = tb.openFile(j)
        skel = np.copy(dat.root.skel)
        bra = np.copy(dat.root.branches)
        mask = np.zeros_like(skel)    
        dat.close()
    
        length = nx.get_edge_attributes(g, 'length')
        number = nx.get_edge_attributes(g, 'number')
        num_dict = {}
        for m in number:
            for v in number[m]:
                num_dict.setdefault(v, []).append(m)
        find_br = ndimage.find_objects(bra)
        for l in list(length.keys()):
            if length[l]<0.5*k: #Criteria
                for b in number[l]:
                    mask[find_br[b-1]] = bra[find_br[b-1]]==b
        mlab.figure(bgcolor=(1,1,1), size=(1200,1200))
        mlab.contour3d(skel, colormap='hot')
        mlab.contour3d(mask)
        mlab.savefig('/backup/yuliya/vsi05/skeletons/short_bran/'+ i[42:-10] + '.png')
        mlab.close()
Ejemplo n.º 29
0
def test_base_line2 (pts1, pts2):
    pts1 = clouds.downsample(pts1, 0.02)
    pts2 = clouds.downsample(pts2, 0.02)
    print pts1.shape
    print pts2.shape

    #plotter = PlotterInit()

    def plot_cb(src, targ, xtarg_nd, corr, wt_n, f):
        plot_requests = plot_warping(f.transform_points, src, targ, fine=False)
        for req in plot_requests:
            plotter.request(req)

    f1,_ = tps_rpm_bij(pts1, pts2, reg_init=10, reg_final=1, rot_reg=np.r_[1e-3,1e-3,1e-1], n_iter=50, plot_cb=plot_cb, plotting=0)
    #raw_input("Done with tps_rpm_bij")
    #plotter.request(gen_mlab_request(mlab.clf))
    f2,_ = tps_rpm_bij_normals(pts1, pts2, reg_init=10, reg_final=01, n_iter=50, rot_reg=np.r_[1e-3,1e-3,1e-1], normal_coeff = 0.01,  
                                    nwsize = 0.07, plot_cb=plot_cb, plotting =0)
    #raw_input('abcd')

    from tn_rapprentice import tps
    #print tps.tps_cost(f1.lin_ag, f1.trans_g, f1.w_ng, pts1, pts2, 1)
    #print tps.tps_cost(f2.lin_ag, f2.trans_g, f2.w_ng, pts1, pts2, 1)
    #plotter.request(gen_mlab_request(mlab.clf))
    mlab.figure(1)
    mayavi_utils.plot_warping(f1, pts1, pts2, fine=False, draw_plinks=True)
    #mlab.show()
    mlab.figure(2)
    #mlab.clf()
    mayavi_utils.plot_warping(f2, pts1, pts2, fine=False, draw_plinks=True)
    mlab.show()
Ejemplo n.º 30
0
def main():
    fileDir='./ascfiles2'
    mapFile = './maps/worldmap.png'
    colorFile = './colormaps/color1.txt'

    # color map used for test
    color1 = [[0,0,0,0,0],
        [1,255,255,0,10],
        [10,255,255,0,50],
        [100,255,100,0,150],
        [1000,255,0,0,255]]
    
    color2 = [[0,0,0,0,0],
        [100,0,255,255,10],
        [1000,0,255,255,50],
        [10000,0,100,255,150],
        [100000,0,0,255,255]]

    s = loadData(fileDir)
    mlab.figure(bgcolor=(0,0,0), size=(800,800) )
    vol = drawVolume(mlab,s)
    colormap = readColorFile(colorFile)
    changeVolumeColormap(vol,colormap)
    drawMap(mlab, s, mapFile)
    changeToBestView(mlab)
Ejemplo n.º 31
0
    #refine graph
    refine = RefineGraph(gc)
    refine.Update(AreaParam=area_param, PolyParam=poly_param)
    gr = refine.GetOutput()

    #gr=FullyConnectedGraph(gr) # uncomment to get only fully connected components of the graph
    gr = fixG(
        gr, copy=True
    )  # this is to fix nodes indixing to be starting from 0 (important for visualization)

    #-------------------------------------------------------------------------#
    # read/ write
    #-------------------------------------------------------------------------#

    #    # save graph
    WritePajek(path='', name='mygraph.pajek', graph=fixG(gc))

    #    #load graph
    loaded_g = ReadPajek('mygraph.pajek').GetOutput()

    #-------------------------------------------------------------------------#
    # Visulaize
    #-------------------------------------------------------------------------#

    #from VascGraph.GraphLab import GraphPlot, StackPlot, MainDialogue
    mlab.figure()
    stack_plot = StackPlot()
    stack_plot.Update(s)
    graph_plot = GraphPlot()
    graph_plot.Update(loaded_g)
Ejemplo n.º 32
0
#!/usr/local/bin/ipython --gui=wx
from mayavi.mlab import triangular_mesh, figure
import numpy as np
from os.path import join
fig = figure()
data_path = './data/'
smpl_v = np.load(join(data_path, 'verts.npy'))
verts = smpl_v.T
faces = np.load(join(data_path, 'faces.npy'))
tm = triangular_mesh(verts[0],
                     verts[1],
                     verts[2],
                     faces,
                     color=(.7, .7, .9),
                     figure=fig)
fig.scene.reset_zoom()
import ipdb
ipdb.set_trace()
Ejemplo n.º 33
0
 def setUp(self, figure=None):
     self.engine = mlab.get_engine()
     fig = mlab.figure()
     mlab.pipeline.surface(BuiltinImage(), figure=fig)
     self.camera = self.engine.current_scene.scene.camera
Ejemplo n.º 34
0
def demo():
    import mayavi.mlab as mlab
    from viz_util import draw_lidar, draw_lidar_simple, draw_gt_boxes3d
    dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'))
    data_idx = 0

    # Load data from dataset
    objects = dataset.get_label_objects(data_idx)
    objects[0].print_object()
    img = dataset.get_image(data_idx)
    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
    img_height, img_width, img_channel = img.shape
    print(('Image shape: ', img.shape))
    pc_velo = dataset.get_lidar(data_idx)[:, 0:3]

    # COMMENT finally --> done for visualization
    pc_velo[0, 2] = pc_velo[0, 2] - 5

    calib = dataset.get_calibration(data_idx)

    # Draw raw lidar in KITTI velo  coord
    print(' -------- Raw LiDAR points in KITTI velo coordination --------')
    fig = draw_lidar(pc_velo)
    raw_input()

    # Draw lidar in rect camera coord
    print(' -------- LiDAR points in rect camera coordination --------')
    pc_rect = calib.project_velo_to_rect(pc_velo)
    fig = draw_lidar_simple(pc_rect)
    raw_input()

    # Draw 2d and 3d boxes on image
    print(' -------- 2D/3D bounding boxes in images --------')
    show_image_with_boxes(img, objects, calib)
    raw_input()

    # Show all LiDAR points. Draw 3d box in LiDAR point cloud
    print(
        ' -------- LiDAR points and 3D boxes in velodyne coordinate --------')
    # show_lidar_with_boxes(pc_velo, objects, calib)
    # raw_input()

    # Change False to True
    show_lidar_with_boxes(pc_velo, objects, calib, True, img_width, img_height)
    raw_input()

    # Visualize LiDAR points on images
    print(' -------- LiDAR points projected to image plane --------')
    show_lidar_on_image(pc_velo, img, calib, img_width, img_height)
    raw_input()

    # Show LiDAR points that are in the 3d box
    print(' -------- LiDAR points in a 3D bounding box --------')
    box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(objects[0], calib.P)
    box3d_pts_3d_velo = calib.project_rect_to_velo(box3d_pts_3d)
    box3droi_pc_velo, _ = extract_pc_in_box3d(pc_velo, box3d_pts_3d_velo)
    print(('Number of points in 3d box: ', box3droi_pc_velo.shape[0]))

    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(1000, 500))
    draw_lidar(box3droi_pc_velo, fig=fig)
    draw_gt_boxes3d([box3d_pts_3d_velo], fig=fig)
    mlab.show(1)
    raw_input()

    # UVDepth Image and its backprojection to point clouds
    print(' -------- LiDAR points in a frustum from a 2D box --------')
    imgfov_pc_velo, pts_2d, fov_inds = get_lidar_in_image_fov(
        pc_velo, calib, 0, 0, img_width, img_height, True)
    imgfov_pts_2d = pts_2d[fov_inds, :]
    imgfov_pc_rect = calib.project_velo_to_rect(imgfov_pc_velo)

    cameraUVDepth = np.zeros_like(imgfov_pc_rect)
    cameraUVDepth[:, 0:2] = imgfov_pts_2d
    cameraUVDepth[:, 2] = imgfov_pc_rect[:, 2]

    # Show that the points are exactly the same
    backprojected_pc_velo = calib.project_image_to_velo(cameraUVDepth)
    print(imgfov_pc_velo[0:20])
    print(backprojected_pc_velo[0:20])

    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(1000, 500))
    draw_lidar(backprojected_pc_velo, fig=fig)
    raw_input()

    # Only display those points that fall into 2d box
    print(' -------- LiDAR points in a frustum from a 2D box --------')
    xmin,ymin,xmax,ymax = \
        objects[0].xmin, objects[0].ymin, objects[0].xmax, objects[0].ymax
    boxfov_pc_velo = \
        get_lidar_in_image_fov(pc_velo, calib, xmin, ymin, xmax, ymax)
    print(('2d box FOV point num: ', boxfov_pc_velo.shape[0]))

    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(1000, 500))
    draw_lidar(boxfov_pc_velo, fig=fig)
    mlab.show(1)
    raw_input()
Ejemplo n.º 35
0
def extract_frustum_data_rgb_detection(det_filename,
                                       split,
                                       output_filename,
                                       viz=False,
                                       type_whitelist=['Car'],
                                       img_height_threshold=25,
                                       lidar_point_threshold=5):
    ''' Extract point clouds in frustums extruded from 2D detection boxes.
        Update: Lidar points and 3d boxes are in *rect camera* coord system
            (as that in 3d box label files)
        
    Input:
        det_filename: string, each line is
            img_path typeid confidence xmin ymin xmax ymax
        split: string, either trianing or testing
        output_filename: string, the name for output .pickle file
        type_whitelist: a list of strings, object types we are interested in.
        img_height_threshold: int, neglect image with height lower than that.
        lidar_point_threshold: int, neglect frustum with too few points.
    Output:
        None (will write a .pickle file to the disk)
    '''
    dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'),
                           split)
    det_id_list, det_type_list, det_box2d_list, det_prob_list = \
        read_det_file(det_filename)
    cache_id = -1
    cache = None

    id_list = []
    type_list = []
    box2d_list = []
    prob_list = []
    input_list = []  # channel number = 4, xyz,intensity in rect camera coord
    frustum_angle_list = []  # angle of 2d box center from pos x-axis

    for det_idx in range(len(det_id_list)):
        data_idx = det_id_list[det_idx]
        print('det idx: %d/%d, data idx: %d' % \
            (det_idx, len(det_id_list), data_idx))
        if cache_id != data_idx:
            calib = dataset.get_calibration(data_idx)  # 3 by 4 matrix
            pc_velo = dataset.get_lidar(data_idx)
            pc_rect = np.zeros_like(pc_velo)
            pc_rect[:, 0:3] = calib.project_velo_to_rect(pc_velo[:, 0:3])
            pc_rect[:, 3] = pc_velo[:, 3]
            img = dataset.get_image(data_idx)
            img_height, img_width, img_channel = img.shape
            _, pc_image_coord, img_fov_inds = get_lidar_in_image_fov(\
                pc_velo[:,0:3], calib, 0, 0, img_width, img_height, True)
            cache = [calib, pc_rect, pc_image_coord, img_fov_inds]
            cache_id = data_idx
        else:
            calib, pc_rect, pc_image_coord, img_fov_inds = cache

        if det_type_list[det_idx] not in type_whitelist: continue

        # 2D BOX: Get pts rect backprojected
        xmin, ymin, xmax, ymax = det_box2d_list[det_idx]
        box_fov_inds = (pc_image_coord[:,0]<xmax) & \
            (pc_image_coord[:,0]>=xmin) & \
            (pc_image_coord[:,1]<ymax) & \
            (pc_image_coord[:,1]>=ymin)
        box_fov_inds = box_fov_inds & img_fov_inds
        pc_in_box_fov = pc_rect[box_fov_inds, :]
        # Get frustum angle (according to center pixel in 2D BOX)
        box2d_center = np.array([(xmin + xmax) / 2.0, (ymin + ymax) / 2.0])
        uvdepth = np.zeros((1, 3))
        uvdepth[0, 0:2] = box2d_center
        uvdepth[0, 2] = 20  # some random depth
        box2d_center_rect = calib.project_image_to_rect(uvdepth)
        frustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2],
                                        box2d_center_rect[0, 0])

        # Pass objects that are too small
        if ymax-ymin<img_height_threshold or \
            len(pc_in_box_fov)<lidar_point_threshold:
            continue

        id_list.append(data_idx)
        type_list.append(det_type_list[det_idx])
        box2d_list.append(det_box2d_list[det_idx])
        prob_list.append(det_prob_list[det_idx])
        input_list.append(pc_in_box_fov)
        frustum_angle_list.append(frustum_angle)

    with open(output_filename, 'wb') as fp:
        pickle.dump(id_list, fp)
        pickle.dump(box2d_list, fp)
        pickle.dump(input_list, fp)
        pickle.dump(type_list, fp)
        pickle.dump(frustum_angle_list, fp)
        pickle.dump(prob_list, fp)

    if viz:
        import mayavi.mlab as mlab
        for i in range(10):
            p1 = input_list[i]
            fig = mlab.figure(figure=None,
                              bgcolor=(0.4, 0.4, 0.4),
                              fgcolor=None,
                              engine=None,
                              size=(500, 500))
            mlab.points3d(p1[:, 0],
                          p1[:, 1],
                          p1[:, 2],
                          p1[:, 1],
                          mode='point',
                          colormap='gnuplot',
                          scale_factor=1,
                          figure=fig)
            fig = mlab.figure(figure=None,
                              bgcolor=(0.4, 0.4, 0.4),
                              fgcolor=None,
                              engine=None,
                              size=(500, 500))
            mlab.points3d(p1[:, 2],
                          -p1[:, 0],
                          -p1[:, 1],
                          seg,
                          mode='point',
                          colormap='gnuplot',
                          scale_factor=1,
                          figure=fig)
            raw_input()
Ejemplo n.º 36
0
def extract_frustum_data(idx_filename,
                         split,
                         output_filename,
                         viz=False,
                         perturb_box2d=False,
                         augmentX=1,
                         type_whitelist=['Car']):
    ''' Extract point clouds and corresponding annotations in frustums
        defined generated from 2D bounding boxes
        Lidar points and 3d boxes are in *rect camera* coord system
        (as that in 3d box label files)
        
    Input:
        idx_filename: string, each line of the file is a sample ID
        split: string, either trianing or testing
        output_filename: string, the name for output .pickle file
        viz: bool, whether to visualize extracted data
        perturb_box2d: bool, whether to perturb the box2d
            (used for data augmentation in train set)
        augmentX: scalar, how many augmentations to have for each 2D box.
        type_whitelist: a list of strings, object types we are interested in.
    Output:
        None (will write a .pickle file to the disk)
    '''
    dataset = kitti_object(os.path.join(ROOT_DIR, 'dataset/KITTI/object'),
                           split)
    data_idx_list = [int(line.rstrip()) for line in open(idx_filename)]

    id_list = []  # int number
    box2d_list = []  # [xmin,ymin,xmax,ymax]
    box3d_list = []  # (8,3) array in rect camera coord
    input_list = []  # channel number = 4, xyz,intensity in rect camera coord
    label_list = []  # 1 for roi object, 0 for clutter
    type_list = []  # string e.g. Car
    heading_list = []  # ry (along y-axis in rect camera coord) radius of
    # (cont.) clockwise angle from positive x axis in velo coord.
    box3d_size_list = []  # array of l,w,h
    frustum_angle_list = []  # angle of 2d box center from pos x-axis

    pos_cnt = 0
    all_cnt = 0
    for data_idx in data_idx_list:
        print('------------- ', data_idx)
        calib = dataset.get_calibration(data_idx)  # 3 by 4 matrix
        objects = dataset.get_label_objects(data_idx)
        pc_velo = dataset.get_lidar(data_idx)
        pc_rect = np.zeros_like(pc_velo)
        pc_rect[:, 0:3] = calib.project_velo_to_rect(pc_velo[:, 0:3])
        pc_rect[:, 3] = pc_velo[:, 3]

        fig_path = str(data_idx) + ".png"
        x = pc_rect[:, 0]
        y = pc_rect[:, 1]
        plt.scatter(x, y, marker=".", color='k')
        plt.savefig(fig_path)

        img = dataset.get_image(data_idx)
        img_height, img_width, img_channel = img.shape
        _, pc_image_coord, img_fov_inds = get_lidar_in_image_fov(
            pc_velo[:, 0:3], calib, 0, 0, img_width, img_height, True)

        for obj_idx in range(len(objects)):
            if objects[obj_idx].type not in type_whitelist: continue

            # 2D BOX: Get pts rect backprojected
            box2d = objects[obj_idx].box2d

            for _ in range(augmentX):

                # Augment data by box2d perturbation
                if perturb_box2d:
                    xmin, ymin, xmax, ymax = random_shift_box2d(box2d)
                    print(box2d)
                    print(xmin, ymin, xmax, ymax)
                else:
                    xmin, ymin, xmax, ymax = box2d

                box_fov_inds = (pc_image_coord[:,0]<xmax) & \
                    (pc_image_coord[:,0]>=xmin) & \
                    (pc_image_coord[:,1]<ymax) & \
                    (pc_image_coord[:,1]>=ymin)

                box_fov_inds = box_fov_inds & img_fov_inds
                pc_in_box_fov = pc_rect[box_fov_inds, :]

                #                fig_path = str(data_idx) + ".png"
                #                x = pc_in_box_fov[:, 0]
                #                y = pc_in_box_fov[:, 1]
                #                plt.scatter(x, y, marker = ".", color='k')
                #                plt.savefig(fig_path)

                # Get frustum angle (according to center pixel in 2D BOX)
                box2d_center = np.array([(xmin + xmax) / 2.0,
                                         (ymin + ymax) / 2.0])
                uvdepth = np.zeros((1, 3))
                uvdepth[0, 0:2] = box2d_center
                uvdepth[0, 2] = 20  # some random depth
                box2d_center_rect = calib.project_image_to_rect(uvdepth)
                frustum_angle = -1 * np.arctan2(box2d_center_rect[0, 2],
                                                box2d_center_rect[0, 0])

                # 3D BOX: Get pts velo in 3d box
                obj = objects[obj_idx]
                box3d_pts_2d, box3d_pts_3d = utils.compute_box_3d(obj, calib.P)
                _, inds = extract_pc_in_box3d(pc_in_box_fov, box3d_pts_3d)

                label = np.zeros((pc_in_box_fov.shape[0]))
                label[inds] = 1

                # Get 3D BOX heading
                heading_angle = obj.ry

                # Get 3D BOX size
                box3d_size = np.array([obj.l, obj.w, obj.h])

                # Reject too far away object or object without points
                #                if ymax-ymin<25 or np.sum(label)==0:
                #                    continue

                id_list.append(data_idx)
                box2d_list.append(np.array([xmin, ymin, xmax, ymax]))
                box3d_list.append(box3d_pts_3d)
                input_list.append(pc_in_box_fov)
                label_list.append(label)
                type_list.append(objects[obj_idx].type)
                heading_list.append(heading_angle)
                box3d_size_list.append(box3d_size)
                frustum_angle_list.append(frustum_angle)

                # collect statistics
                pos_cnt += np.sum(label)
                all_cnt += pc_in_box_fov.shape[0]

    #print("length:", len(id_list))
    print('Average pos ratio: %f' % (pos_cnt / float(all_cnt)))
    print('Average npoints: %f' % (float(all_cnt) / len(id_list)))

    with open(output_filename, 'wb') as fp:
        pickle.dump(id_list, fp)
        pickle.dump(box2d_list, fp)
        pickle.dump(box3d_list, fp)
        pickle.dump(input_list, fp)
        pickle.dump(label_list, fp)
        pickle.dump(type_list, fp)
        pickle.dump(heading_list, fp)
        pickle.dump(box3d_size_list, fp)
        pickle.dump(frustum_angle_list, fp)

    if viz:
        import mayavi.mlab as mlab
        for i in range(10):
            p1 = input_list[i]
            seg = label_list[i]
            fig = mlab.figure(figure=None,
                              bgcolor=(0.4, 0.4, 0.4),
                              fgcolor=None,
                              engine=None,
                              size=(500, 500))
            mlab.points3d(p1[:, 0],
                          p1[:, 1],
                          p1[:, 2],
                          seg,
                          mode='point',
                          colormap='gnuplot',
                          scale_factor=1,
                          figure=fig)
            fig = mlab.figure(figure=None,
                              bgcolor=(0.4, 0.4, 0.4),
                              fgcolor=None,
                              engine=None,
                              size=(500, 500))
            mlab.points3d(p1[:, 2],
                          -p1[:, 0],
                          -p1[:, 1],
                          seg,
                          mode='point',
                          colormap='gnuplot',
                          scale_factor=1,
                          figure=fig)
            raw_input()
Ejemplo n.º 37
0
def sv_user_traj_3d_interactive(gps_ds, sv_pos, user_pos, ele=10., azim=20.):
    """
    This method will provide an interactive 3d model plotted using mayavi to show all trajectories.
    :param gps_ds:
    :param sv_pos:
    :param user_pos:
    :return:
    """
    mlab.figure(1,
                bgcolor=(0.48, 0.48, 0.48),
                fgcolor=(0, 0, 0),
                size=(400, 400))
    mlab.clf()
    ##########################################################################
    # Display continents outline, using the VTK Builtin surface 'Earth'
    continents_src = BuiltinSurface(source='earth', name='Continents')
    # The on_ratio of the Earth source controls the level of detail of the
    # continents outline.
    continents_src.data_source.on_ratio = 1
    continents = mlab.pipeline.surface(continents_src, color=(0, 0, 0))

    for svn in range(0, len(sv_pos)):
        mlab.plot3d(sv_pos[svn, 0, :] / radius,
                    sv_pos[svn, 1, :] / radius,
                    sv_pos[svn, 2, :] / radius,
                    color=(1, 1, 0.5),
                    opacity=0.5,
                    tube_radius=None)
        xml = len(sv_pos[svn, 0, :]) / 2
        yml = len(sv_pos[svn, 1, :]) / 2
        zml = len(sv_pos[svn, 2, :]) / 2
        xm, ym, zm = sv_pos[svn, 0, int(xml)] / radius, sv_pos[
            svn, 1, int(yml)] / radius, sv_pos[svn, 2, int(zml)] / radius
        label = mlab.text(xm,
                          ym,
                          gps_ds.Rx_sv_list[svn],
                          z=zm,
                          width=0.0155 * len(gps_ds.Rx_sv_list[svn]))
        label.property.shadow = True
    mlab.plot3d(user_pos[:, 0] / radius,
                user_pos[:, 1] / radius,
                user_pos[:, 2] / radius,
                color=(1, 1, 1),
                opacity=0.5,
                tube_radius=None)
    xml = len(user_pos[:, 0]) / 2
    yml = len(user_pos[:, 1]) / 2
    zml = len(user_pos[:, 2]) / 2
    xm, ym, zm = user_pos[int(xml), 0] / radius, user_pos[
        int(yml), 1] / radius, user_pos[int(zml), 2] / radius
    label = mlab.text(xm, ym, "User", z=zm, width=0.077)
    label.property.shadow = True
    ###############################################################################
    # Display a semi-transparent sphere, for the surface of the Earth

    # We use a sphere Glyph, throught the points3d mlab function, rather than
    # building the mesh ourselves, because it gives a better transparent
    # rendering.
    ocean_blue = (0.4, 0.5, 1.0)
    sphere = mlab.points3d(
        0,
        0,
        0,
        scale_mode='none',
        scale_factor=2,
        # color=(0.67, 0.77, 0.93),
        color=ocean_blue,
        resolution=50,
        opacity=.85,
        name='Earth')
    #
    # These parameters, as well as the color, where tweaked through the GUI,
    # with the record mode to produce lines of code usable in a script.
    sphere.actor.property.specular = 0.45
    sphere.actor.property.specular_power = 5
    # Backface culling is necessary for more a beautiful transparent
    # rendering.
    sphere.actor.property.backface_culling = True

    # Plot the equator and the tropiques
    theta = np.linspace(0, 2 * np.pi, 100)
    for angle in (-np.pi / 6, 0, np.pi / 6):
        x = np.cos(theta) * np.cos(angle)
        y = np.sin(theta) * np.cos(angle)
        z = np.ones_like(theta) * np.sin(angle)
        print(x)
        mlab.plot3d(x, y, z, color=(1, 1, 1), opacity=0.2, tube_radius=None)

    mlab.view(azim, ele)
    mlab.show()
Ejemplo n.º 38
0
    coords.append((float(long_), float(lat)))

########## 坐标转换##########
# 将经纬度的位置转换为三维坐标
import numpy as np

coords = np.array(coords)
lat, long = coords.T * np.pi / 180
x = np.cos(long) * np.cos(lat)
y = np.cos(long) * np.sin(lat)
z = np.sin(long)

##########建立窗口##########
from mayavi import mlab

mlab.figure(bgcolor=(0.48, 0.48, 0.48), size=(400, 400))

##########绘制地球##########
# 绘制半透明球体表示地球
sphere = mlab.points3d(0, 0, 0, scale_factor=2,
                       color=(0.67, 0.77, 0.93),
                       resolution=50,
                       opacity=0.7,
                       name='Earth')

# 调整镜面反射参数
sphere.actor.property.specular = 0.45
sphere.actor.property.specular_power = 5
# 设置背面剔除,以更好的显示透明效果
sphere.actor.property.backface_culling = True
Ejemplo n.º 39
0
def plot_graphs(locs, stations, nbsta, CLUSTER, nbmin, threshold):
    """
    Displays two figures.
    On the first plot, all events are represented. Those belonging to a cluster are color-coded 
    and labelled with the cluster index.
    On the second plot, all events are also represented, but those belonging to a cluster are 
    colored in black. The links between events of a same cluster are also plotted and color-coded 
    in function of the number of stations where the correlation value exceeds the threshold.
    Uses mlab from mayavi

    :param locs: list of the whole Waveloc locations (each element of the list is a dictionary)
    :param stations: dictionary of stations
    :param nbsta:2-D matrix containing the number of stations where the cross-correlation value 
    is greater than a given threshold for all possible event pairs
    :param CLUSTER: dictionary containing the indexes of the events for each cluster
    :param nbmin: minimum number of stations where the cross-correlation value should be greater 
    than a given threshold to form a cluster
    :param threshold: correlation value threshold set to form a cluster

    :type locs: dictionary
    :type stations: dictionary
    :type nbsta: matrix
    :type CLUSTER: dictionary
    :type nbmin: integer
    :type threshold: float
    """
    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...")
    mlab.figure(1, 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 i_ev in range(len(nbsta)):
        for i_c in range(1, len(CLUSTER) + 1):
            if i_ev + 1 in CLUSTER[i_c]:
                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))))
                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...")
    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))
    print nbsta
    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)
                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')
    logging.info("Done!")
    mlab.show()
                                       0), np.full(len(y_ob),
                                                   0), np.full(len(z_ob), 0)

for o in range(len(x_ob)):
    x_ob_map[o] = int(round(float(x_ob[o]) / binSize)) + w
    y_ob_map[o] = int(round(float(y_ob[o]) / binSize)) + w
    z_ob_map[o] = int(round(float(z_ob[o]) / binSize)) + z_height

print('Smoothing')
gaussian = gf(a, sigma=sigma, truncate=3)
b = 2 * (expit(spread * gaussian) - 0.5)

from mayavi import mlab
import moviepy.editor as mpy

fig_myv = mlab.figure(size=(750, 700), bgcolor=(1, 1, 1), fgcolor=(0, 0, 0))
fig_myv.scene.disable_render = True
#duration = 9
mlab.clf()
src = mlab.pipeline.scalar_field(b)
m = mlab.pipeline.iso_surface(
    src,
    #contours = [0.2, 0.3, 0.5],
    contours=[0.1, 0.2, .3],
    opacity=0.3,
    colormap='Reds',
    figure=fig_myv)
mlab.axes(  #ranges = [-1300, 1300, -1300, 1300, -3500, 3500],
    ranges=[-500, 500, -500, 500, -350, 350],
    color=(0, 0, 0),
    nb_labels=5,
Ejemplo n.º 41
0
import rasterio
from mayavi import mlab
from tvtk.api import tvtk
import numpy as np

# Use gadalwarp or qgis to reproject to utm 17N
filenames = ['be.tif', 'raw.tif']
outnames = ['be.png', 'raw.png']

for i in range(2):

    dataset = rasterio.open(filenames[i])

    surface = dataset.read()[0]
    dataset.close()

    # Get rid of any nodata values
    surface[surface == np.min(surface)] = np.nan

    mlab.figure(size=(640, 640), bgcolor=(1., 1., 1.))

    surf = mlab.surf(surface, colormap='gist_earth', warp_scale=1)

    mlab.savefig(outnames[i])
    mlab.clf()
Ejemplo n.º 42
0
def draw_network_3D(graph, nodes_membership, **kwargs):
    ''' Draw the graph with its labels '''
    from mayavi import mlab
    plot_prop = {}
    plot_prop['nodes_size'] = kwargs.get('nodes_size', 10)
    plot_prop['edges_width'] = kwargs.get('edges_width', 1)
    plot_prop['color_map'] = kwargs.get('color_map', plt.cm.Spectral)
    plot_prop['font_size'] = kwargs.get('font_size', 15)
    plot_prop['layout_method'] = kwargs.get('layout_method', 'neato')
    plot_prop['node_alpha'] = kwargs.get('node_alpha', 0.8)
    plot_prop['draw_edges'] = kwargs.get('draw_edges', False)
    plot_prop['draw_edges_weights'] = kwargs.get('draw_edges_weights', False)
    plot_prop['axisX'] = kwargs.get('axisX', 0)
    plot_prop['axisY'] = kwargs.get('axisY', 2)
    plot_prop['mst_sparsification'] = kwargs.get('mst_sparsification', False)
    plot_prop['highlight_comm'] = kwargs.get('highlight_comm', None)

    plot_prop['v_min'] = kwargs.get('v_min', np.min(nodes_membership.values()))
    plot_prop['v_max'] = kwargs.get('v_max', np.max(nodes_membership.values()))
    # http://colorbrewer2.org/index.html?type=qualitative&scheme=Paired&n=12
    import brewer2mpl
    # Generates perceptually diverging maps to better see differences of
    # sequential data
    lut = np.array(brewer2mpl.get_map('Paired', 'Qualitative', 12).mpl_colors)
    # Add the alpha channel
    lut = np.hstack((lut, np.ones((lut.shape[0], 1)))) * 255
    # Reduce the alpha of non highlighted community
    if plot_prop['highlight_comm'] is not None:
        for i, colorRGB in enumerate(lut):
            if i != plot_prop['highlight_comm']:
                lut[i, :] = desaturate(colorRGB,
                                       kwargs.get('desat_scale', 0.8),
                                       alpha=kwargs.get('alpha', 1))

    xyz = kwargs.get('node_pos', None)

    #output_file_name = kwargs.get('output_file_name', None)
    #xyz=np.array([node_pos[v] for v in sorted(graph.nodes())])
    scalars = nodes_membership.values()
    #mlab.options.backend = 'envisage'
    mlab.figure(1, bgcolor=(0, 0, 0))
    # mlab.clf()
    # http://docs.enthought.com/mayavi/mayavi/auto/mlab_helper_functions.html
    pts = mlab.points3d(xyz[:, 0],
                        xyz[:, 1],
                        xyz[:, 2],
                        scalars,
                        scale_factor=plot_prop['nodes_size'],
                        scale_mode='none',
                        colormap='Set2',
                        resolution=12,
                        reset_zoom=True,
                        vmax=plot_prop['v_max'],
                        vmin=plot_prop['v_min'])

    # Set the new colormap look-up-table
    pts.module_manager.scalar_lut_manager.lut.table = lut

    if plot_prop['draw_edges'] is not None:
        if plot_prop['highlight_comm'] is not None:
            highlight_subgraph = list(
                community_subgraphs(
                    graph, nodes_membership))[plot_prop['highlight_comm']]
            if plot_prop['mst_sparsification']:
                el = nx.minimum_spanning_tree(highlight_subgraph).edges()
            else:
                el = highlight_subgraph.edges()
        else:
            if plot_prop['mst_sparsification']:
                el = nx.minimum_spanning_tree(graph).edges()
            else:
                el = graph.edges()

        pts.mlab_source.dataset.lines = np.array(el)
        tube = mlab.pipeline.tube(pts, tube_radius=plot_prop['edges_width'])
        tube.filter.radius_factor = 1.0
        tube.filter.vary_radius = 'vary_radius_by_scalar'

        if plot_prop['highlight_comm'] is not None:
            tubecolor = tuple(lut[plot_prop['highlight_comm'], 0:3] / 255.0)
            mlab.pipeline.surface(tube, color=tubecolor)

    mlab.show()
    ''' RISPOSTA DI AESTRIVEX CHE USA ANCHE LUI QUESTI DATI
    http://stackoverflow.com/questions/22253298/mayavi-points3d-with-different-size-and-colors/
    nodes = points3d(x,y,z)
    nodes.glyph.scale_mode = 'scale_by_vector'

    #this sets the vectors to be a 3x5000 vector showing some random scalars
    nodes.mlab_source.dataset.point_data.vectors = np.tile( np.random.random((5000,)), (3,1))

    nodes.mlab_source.dataset.point_data.scalars = np.random.random((5000,))
    '''
    '''
Ejemplo n.º 43
0
#PbBrF_lat = rsp.lattice.lattice_from_cif('/home/finn/Documents/eclipse_workspace/2017_MA3074/preparation/structure_simulation/PbBrF.cif', HKL_normal = [0,0,1], HKL_para_x=[0,1,0], energy=25)

from mayavi import mlab


try:
    engine = mayavi.engine
except NameError:
    from mayavi.api import Engine
    engine = Engine()
    engine.start()
if len(engine.scenes) == 0:
    engine.new_scene(size=(600, 800))
scene = engine.scenes[0]
fig = mlab.gcf(engine)
mlab.figure(figure=fig, bgcolor=(1.0, 1.0, 1.0), fgcolor=(0.0, 0.0, 0.0), engine=engine)


Au_lat = rsp.lattice(
                 a          = 4.0782, 
                 b          = 4.0782, 
                 c          = 4.0782,
                 alpha      = 90,     
                  beta       = 90,     
                  gamma      = 90,     
                  basis      = [['Au', 0,0,0],['Au', 0.5,0.5,0],['Au', 0,0.5,0.5],['Au', 0.5,0,0.5]], 
                  HKL_normal = [0,0,1],
                  HKL_para_x = [1,1,0]
                  )

Ejemplo n.º 44
0
index2 = struct1.get_rel_index(43900000)
comps1 = comps1[index1:index2 + 1]
comps2 = comps2[index1:index2 + 1]

index1 = struct1.chrom.getAbsoluteIndex(41900000)
index2 = struct1.chrom.getAbsoluteIndex(43900000)
struct1.subsamplePoints(index1, index2)
struct2.subsamplePoints(index1, index2)

colors = np.zeros_like(struct1.getPoints(), dtype=int)
index1 = struct1.get_rel_index(42700000)
index2 = struct1.get_rel_index(42900000)
colors[index1:index2] = -1

mlab.close(all=True)
mlab.figure(bgcolor=(1, 1, 1))
coords1 = np.array(struct1.getCoords())
mlab.plot3d(coords1[:, 0],
            coords1[:, 1],
            coords1[:, 2],
            colors,
            colormap="RdYlBu")
coords2 = np.array(struct2.getCoords())
mlab.plot3d(coords2[:, 0],
            coords2[:, 1],
            coords2[:, 2],
            colors,
            colormap="RdYlGn")
mlab.savefig("sup11a.png")

mlab.close(all=True)
Ejemplo n.º 45
0
        if show_boundary:
            xix_boundary_r_vals_t = xix_boundary_r_vals
            xix_boundary_l_vals_t = xix_boundary_l_vals

        if show_density or show_density_pert:
            rho_vals_t = rho_vals

# ================================
# Starting figure and visualisation modules
# ================================

        zgrid_zy, ygrid_zy = np.mgrid[0:nz:(nz) * 1j, 0:ny:(ny) * 1j]

        fig = mlab.figure(
            size=res
        )  # (1920, 1080) for 1080p , tuple(101 * np.array((16,9))) #16:9 aspect ratio for video upload

        # Spacing of grid so that we can display a visualisation cube without having the same number of grid points in each dimension
        spacing = np.array([x_spacing, z_spacing, y_spacing])

        if show_density or show_density_pert:
            # Scalar field density
            rho = mlab.pipeline.scalar_field(rho_vals_t,
                                             name="density",
                                             figure=fig)
            rho.spacing = spacing
            mpf.volume_red_blue(rho, rho_vals_t)

        #Masking points
        if show_mag_front:
Ejemplo n.º 46
0
#w = pl.log(pdata['snr'])
#title = "log(snr)"
#fn = "log_snr"

# driven rate
#xs = pdata['ml']
#ys = pdata['ap']
#zs = pdata['dv']
xs = pdata['dv']
ys = pdata['ml']
zs = pdata['ap']
ws = pdata['drate'] - pdata['brate']
title = "driven rate"
fn = "driven_rate"

figure = mlab.figure(fgcolor=(1, 1, 1), size=(800, 600))
figure.scene.disable_render = True
#mlab.points3d(pdata['ml'],pdata['ap'],pdata['dv'],pl.log(pdata['snr']))
#glyphs = mlab.points3d(pdata['ml'],pdata['ap'],pdata['dv'],w)
glyphs = mlab.points3d(xs, ys, zs, ws)
mlab.scalarbar(orientation='vertical', title=title)
#mlab.axes(xlabel='ML',ylabel='AP',zlabel='DV',color=(1,1,1))
mlab.axes(xlabel='DV', ylabel='ML', zlabel='AP', color=(1, 1, 1))
#mlab.view(azimuth=270,reset_roll=True)

loffset = 0.05
pid = ws.argmax()
session = pdata['session'][pid]
ch = pdata['ch'][pid]
cl = pdata['cl'][pid]
w = ws[pid]
Ejemplo n.º 47
0
    def plot(self, labels=False, show=True):
        '''
        This function plots 2D and 3D models
        :param labels:
        :param show: If True, the plots are displayed at the end of this call. If False, plt.show() should be called outside this function
        :return:
        '''
        if self.k == 3:
            import mayavi.mlab as mlab

            predictFig = mlab.figure(figure='predict')
            # errorFig = mlab.figure(figure='error')
            if self.testfunction:
                truthFig = mlab.figure(figure='test')
            dx = 1
            pts = 25j
            X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts]
            scalars = np.zeros(X.shape)
            errscalars = np.zeros(X.shape)
            for i in range(X.shape[0]):
                for j in range(X.shape[1]):
                    for k1 in range(X.shape[2]):
                        # errscalars[i][j][k1] = self.predicterr_normalized([X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                        scalars[i][j][k1] = self.predict_normalized(
                            [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])

            if self.testfunction:
                tfscalars = np.zeros(X.shape)
                for i in range(X.shape[0]):
                    for j in range(X.shape[1]):
                        for k1 in range(X.shape[2]):
                            tfplot = tfscalars[i][j][k1] = self.testfunction(
                                [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                plot = mlab.contour3d(tfscalars,
                                      contours=15,
                                      transparent=True,
                                      figure=truthFig)
                plot.compute_normals = False

            # obj = mlab.contour3d(scalars, contours=10, transparent=True)
            plot = mlab.contour3d(scalars,
                                  contours=15,
                                  transparent=True,
                                  figure=predictFig)
            plot.compute_normals = False
            # errplt = mlab.contour3d(errscalars, contours=15, transparent=True, figure=errorFig)
            # errplt.compute_normals = False
            if show:
                mlab.show()

        if self.k == 2:

            fig = pylab.figure(figsize=(8, 6))
            samplePoints = list(zip(*self.X))
            # Create a set of data to plot
            plotgrid = 61
            x = np.linspace(self.normRange[0][0],
                            self.normRange[0][1],
                            num=plotgrid)
            y = np.linspace(self.normRange[1][0],
                            self.normRange[1][1],
                            num=plotgrid)

            # x = np.linspace(0, 1, num=plotgrid)
            # y = np.linspace(0, 1, num=plotgrid)
            X, Y = np.meshgrid(x, y)

            # Predict based on the optimized results

            zs = np.array([
                self.predict([x, y]) for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Z = zs.reshape(X.shape)
            # Z = (Z*(self.ynormRange[1]-self.ynormRange[0]))+self.ynormRange[0]

            #Calculate errors
            zse = np.array([
                self.predict_var([x, y])
                for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Ze = zse.reshape(X.shape)

            spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0])
                   ) + self.normRange[0][0]
            spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0])
                   ) + self.normRange[1][0]
            contour_levels = 25

            ax = fig.add_subplot(222)
            CS = pylab.contourf(X, Y, Ze, contour_levels)
            pylab.colorbar()
            pylab.plot(spx, spy, 'ow')

            ax = fig.add_subplot(221)
            if self.testfunction:
                # Setup the truth function
                zt = self.testfunction(
                    np.array(list(zip(np.ravel(X), np.ravel(Y)))))
                ZT = zt.reshape(X.shape)
                CS = pylab.contour(X,
                                   Y,
                                   ZT,
                                   contour_levels,
                                   colors='k',
                                   zorder=2)

            # contour_levels = np.linspace(min(zt), max(zt),50)
            if self.testfunction:
                contour_levels = CS.levels
                delta = np.abs(contour_levels[0] - contour_levels[1])
                contour_levels = np.insert(contour_levels, 0,
                                           contour_levels[0] - delta)
                contour_levels = np.append(contour_levels,
                                           contour_levels[-1] + delta)

            CS = plt.contourf(X, Y, Z, contour_levels, zorder=1)
            pylab.plot(spx, spy, 'ow', zorder=3)
            pylab.colorbar()

            ax = fig.add_subplot(212, projection='3d')
            # fig = plt.gcf()
            #ax = fig.gca(projection='3d')
            ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4)
            if self.testfunction:
                ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3)
            if show:
                pylab.show()
        if gid % 2 == 1 and gid >= params.gid_granule_begin + granules.ngranule:
            ggid = gd.gid_dict[gid + 1][3]
            w_new = weights[gid]
            if gcol.has_key(ggid):
                w_old = gcol[ggid]
                if w_old < w_new:
                    gcol[ggid] = w_new
            else:
                gcol.update({ggid: w_new})
    return gcol


import bindict as gd
gd.load(filedict)
from mayavi.mlab import figure, text
fig = figure(bgcolor=(0, 0, 0))

from mayavi import mlab
points3d = mlab.points3d
import params
import granules


class GranulesManager:
    def __init__(self):
        self.gran = set()
        self.actor1 = None
        self.gran_color = (0., 157 / 255., 157 / 255.)
        self.mitrals = None
        self.colors = None
        self.projected = False
Ejemplo n.º 49
0
def apply_transform_to_points(points, trans_mat):
    """a function that applies a 4x4 transformation matrix to an of
        homogeneous points. The array of points should have shape Nx4"""

    if not trans_mat.shape == (4, 4):
        raise ValueError('transform matrix must be 4x4')

    if not points.shape[1] == 4:
        raise ValueError('point array must have shape Nx4')

    return np.dot(trans_mat, points.T).T


if __name__ == '__main__':
    f = mlab.figure()

    N = 4

    # create a few points in 3-space
    X = np.random.random_integers(-3, 3, N)
    Y = np.random.random_integers(-3, 3, N)
    Z = np.random.random_integers(-3, 3, N)

    # plot the points with mlab
    pts = mlab.points3d(X, Y, Z)

    # now were going to create a single N x 4 array of our points
    # adding a fourth column of ones expresses the world points in
    # homogenous coordinates
    W = np.ones(X.shape)
Ejemplo n.º 50
0
    def saveFigure(self, name=None):
        '''
        Similar to plot, except that figures are saved to file
        :param name: the file name of the plot image
        '''
        if self.k == 3:
            import mayavi.mlab as mlab

            mlab.options.offscreen = True
            predictFig = mlab.figure(figure='predict')
            mlab.clf(figure='predict')
            errorFig = mlab.figure(figure='error')
            mlab.clf(figure='error')
            if self.testfunction:
                truthFig = mlab.figure(figure='test')
                mlab.clf(figure='test')
            dx = 1
            pts = 75j
            X, Y, Z = np.mgrid[0:dx:pts, 0:dx:pts, 0:dx:pts]
            scalars = np.zeros(X.shape)
            errscalars = np.zeros(X.shape)
            for i in range(X.shape[0]):
                for j in range(X.shape[1]):
                    for k1 in range(X.shape[2]):
                        errscalars[i][j][k1] = self.predicterr_normalized(
                            [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                        scalars[i][j][k1] = self.predict_normalized(
                            [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])

            if self.testfunction:
                tfscalars = np.zeros(X.shape)
                for i in range(X.shape[0]):
                    for j in range(X.shape[1]):
                        for k1 in range(X.shape[2]):
                            tfscalars[i][j][k1] = self.testfunction(
                                [X[i][j][k1], Y[i][j][k1], Z[i][j][k1]])
                mlab.contour3d(tfscalars,
                               contours=15,
                               transparent=True,
                               figure=truthFig,
                               compute_normals=False)

            # obj = mlab.contour3d(scalars, contours=10, transparent=True)
            pred = mlab.contour3d(scalars,
                                  contours=15,
                                  transparent=True,
                                  figure=predictFig)
            pred.compute_normals = False
            errpred = mlab.contour3d(errscalars,
                                     contours=15,
                                     transparent=True,
                                     figure=errorFig)
            errpred.compute_normals = False
            mlab.savefig('%s_prediction.wrl' % name, figure=predictFig)
            mlab.savefig('%s_error.wrl' % name, figure=errorFig)
            if self.testfunction:
                mlab.savefig('%s_actual.wrl' % name, figure=truthFig)
            mlab.close(all=True)
        if self.k == 2:
            samplePoints = list(zip(*self.X))
            # Create a set of data to plot
            plotgrid = 61
            x = np.linspace(0, 1, num=plotgrid)
            y = np.linspace(0, 1, num=plotgrid)
            X, Y = np.meshgrid(x, y)

            # Predict based on the optimized results

            zs = np.array([
                self.predict_normalized([x, y])
                for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Z = zs.reshape(X.shape)
            Z = (
                Z *
                (self.ynormRange[1] - self.ynormRange[0])) + self.ynormRange[0]

            # Calculate errors
            zse = np.array([
                self.predicterr_normalized([x, y])
                for x, y in zip(np.ravel(X), np.ravel(Y))
            ])
            Ze = zse.reshape(X.shape)

            if self.testfunction:
                # Setup the truth function
                zt = self.testfunction(
                    np.array(
                        list(
                            zip(
                                np.ravel((X * (self.normRange[0][1] -
                                               self.normRange[0][0])) +
                                         self.normRange[0][0]),
                                np.ravel((Y * (self.normRange[1][1] -
                                               self.normRange[1][0])) +
                                         self.normRange[1][0])))))
                ZT = zt.reshape(X.shape)

            # Plot real world values
            X = (X * (self.normRange[0][1] - self.normRange[0][0])
                 ) + self.normRange[0][0]
            Y = (Y * (self.normRange[1][1] - self.normRange[1][0])
                 ) + self.normRange[1][0]
            spx = (self.X[:, 0] * (self.normRange[0][1] - self.normRange[0][0])
                   ) + self.normRange[0][0]
            spy = (self.X[:, 1] * (self.normRange[1][1] - self.normRange[1][0])
                   ) + self.normRange[1][0]
            fig = plt.figure(figsize=(8, 6))
            # contour_levels = np.linspace(min(zt), max(zt),50)
            contour_levels = 15
            plt.plot(spx, spy, 'ow')
            cs = plt.colorbar()

            if self.testfunction:
                pass
            plt.plot(spx, spy, 'ow')

            cs = plt.colorbar()
            plt.plot(spx, spy, 'ow')

            ax = fig.add_subplot(212, projection='3d')
            ax.plot_surface(X, Y, Z, rstride=3, cstride=3, alpha=0.4)

            if self.testfunction:
                ax.plot_wireframe(X, Y, ZT, rstride=3, cstride=3)
        if name:
            plt.savefig(name)
        else:
            plt.savefig('pyKrigingResult.png')
Ejemplo n.º 51
0
if __name__ == '__main__':

    lidar_dir = '/root/share/project/didi/data/didi/didi-2/Out/1/15/lidar'
    gt_boxes3d_dir = '/root/share/project/didi/data/didi/didi-2/Out/1/15/processed/gt_boxes3d'
    lidar_top_dir = '/root/share/project/didi/data/didi/didi-2/Out/1/15/processed/lidar_top'
    lidar_top_img_dir = '/root/share/project/didi/data/didi/didi-2/Out/1/15/processed/lidar_top_img'
    mark_dir = '/root/share/project/didi/data/didi/didi-2/Out/1/15/processed/mark-top-box'
    avi_file = '/root/share/project/didi/data/didi/didi-2/Out/1/15/processed/mark-top-box.avi'
    os.makedirs(mark_dir, exist_ok=True)
    os.makedirs(lidar_top_dir, exist_ok=True)
    os.makedirs(lidar_top_img_dir, exist_ok=True)

    fig = mlab.figure(figure=None,
                      bgcolor=(0, 0, 0),
                      fgcolor=None,
                      engine=None,
                      size=(500, 500))
    for file in sorted(glob.glob(lidar_dir + '/*.npy')):
        name = os.path.basename(file).replace('.npy', '')

        lidar_file = lidar_dir + '/' + name + '.npy'
        top_file = lidar_top_dir + '/' + name + '.npy'
        top_img_file = lidar_top_img_dir + '/' + name + '.png'
        mark_file = mark_dir + '/' + name + '.png'
        boxes3d_file = gt_boxes3d_dir + '/' + name + '.npy'

        lidar = np.load(lidar_file)
        top, top_img = lidar_to_top(lidar)
        boxes3d = np.load(boxes3d_file)
Ejemplo n.º 52
0
def draw_lidar(pc,
               color=None,
               fig=None,
               bgcolor=(0, 0, 0),
               pts_scale=1,
               pts_mode='point',
               pts_color=None):
    """
    Add lidar points
    Args:
        pc: point cloud xyz [npoints, 3]
        color:
        fig: fig handler
    Returns:

    """
    ''' Draw lidar points
    Args:
        pc: numpy array (n,3) of XYZ
        color: numpy array (n) of intensity or whatever
        fig: mayavi figure handler, if None create new one otherwise will use it
    Returns:
        fig: created or used fig
    '''
    if fig is None:
        fig = mlab.figure(figure=None,
                          bgcolor=bgcolor,
                          fgcolor=None,
                          engine=None,
                          size=(1600, 1000))
    if color is None:
        color = pc[:, 2]

    # add points
    mlab.points3d(pc[:, 0],
                  pc[:, 1],
                  pc[:, 2],
                  color,
                  color=pts_color,
                  mode=pts_mode,
                  colormap='gnuplot',
                  scale_factor=pts_scale,
                  figure=fig)

    # # draw origin
    # mlab.points3d(0, 0, 0, color=(1, 1, 1), mode='sphere', scale_factor=0.2)

    # draw axis
    axes = np.array([
        [2., 0., 0., 0.],
        [0., 2., 0., 0.],
        [0., 0., 2., 0.],
    ],
                    dtype=np.float64)
    mlab.plot3d([0, axes[0, 0]], [0, axes[0, 1]], [0, axes[0, 2]],
                color=(1, 0, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[1, 0]], [0, axes[1, 1]], [0, axes[1, 2]],
                color=(0, 1, 0),
                tube_radius=None,
                figure=fig)
    mlab.plot3d([0, axes[2, 0]], [0, axes[2, 1]], [0, axes[2, 2]],
                color=(0, 0, 1),
                tube_radius=None,
                figure=fig)

    return fig
Ejemplo n.º 53
0
import numpy as np
from mayavi import mlab
import pickle
import scipy.io
import glob
import os
import sys
print(sys.argv)
k = sys.argv[1]
#mlab.options.backend = 'envisage'
mlab.figure(figure=None,
            bgcolor=None,
            fgcolor=None,
            engine=None,
            size=(1000, 800))
#list_of_files = glob.glob('./mats_8_neuru/*.mat') # * means all if need specific format then *.csv
list_of_files = glob.glob(
    f'./mats_{k}/*.mat')  # * means all if need specific format then *.csv
latest_file = max(list_of_files, key=os.path.getctime)

#fname = 'data/sim_2400_normal_q.npy'

#P = scipy.io.loadmat('mats/t10.mat');
if len(sys.argv) == 3:
    n = sys.argv[2]
    P = scipy.io.loadmat(f'./mats_{k}/t{n}.mat')
else:
    P = scipy.io.loadmat(latest_file)
    print(latest_file)

#P = P['p']
Ejemplo n.º 54
0
    pairs1_ = (np.dot(R, pairs1.T) + T.reshape(3, 1)).T

    Colors0 = np.ones((PC0.shape[0], 1), dtype=np.float32) * 1.0
    KeyColors0 = np.ones((KeyPts0.shape[0], 1), dtype=np.float32) * 0.5
    KeyColors0_ = np.ones((KeyPts0.shape[0], 1), dtype=np.float32) * 0.8

    Colors1 = np.ones((PC1.shape[0], 1), dtype=np.float32) * 0.0
    KeyColors1 = np.ones((KeyPts1.shape[0], 1), dtype=np.float32) * 0.5
    KeyColors1_ = np.ones((KeyPts1.shape[0], 1), dtype=np.float32) * 0.2

    Colors4FusedPC = np.r_[Colors0, Colors1]
    #    Colors4FusedPC=np.r_[SingleColor0, SingleColor1]
    Colors4FusedPC = Colors4FusedPC.reshape(Colors4FusedPC.shape[0], )

    shift4Show = 12
    fig = mlab.figure(bgcolor=(0, 0, 0), size=(1500, 900))
    PtSize = 0.4

    node = mlab.points3d(PC0[:, 0],
                         PC0[:, 1],
                         PC0[:, 2],
                         mode="point",
                         figure=fig)
    node.glyph.scale_mode = 'scale_by_vector'
    node.mlab_source.dataset.point_data.scalars = Colors0
    #node.mlab_source.dataset.point_data.scalars = SingleColor0

    node = mlab.points3d(PC1[:, 0],
                         PC1[:, 1],
                         PC1[:, 2] + shift4Show,
                         mode="point",
Ejemplo n.º 55
0
def draw_lidar(
    pc,
    color=None,
    fig=None,
    bgcolor=(0, 0, 0),
    pts_scale=0.3,
    pts_mode="sphere",
    pts_color=None,
    color_by_intensity=False,
    pc_label=False,
):
    """ Draw lidar points
    Args:
        pc: numpy array (n,3) of XYZ
        color: numpy array (n) of intensity or whatever
        fig: mayavi figure handler, if None create new one otherwise will use it
    Returns:
        fig: created or used fig
    """
    # ind = (pc[:,2]< -1.65)
    # pc = pc[ind]
    pts_mode = "point"
    print("====================", pc.shape)
    if fig is None:
        fig = mlab.figure(figure=None,
                          bgcolor=bgcolor,
                          fgcolor=None,
                          engine=None,
                          size=(1600, 1000))
    if color is None:
        color = pc[:, 2]
    if pc_label:
        color = pc[:, 4]
    if color_by_intensity:
        color = pc[:, 2]

    mlab.points3d(
        pc[:, 0],
        pc[:, 1],
        pc[:, 2],
        color,
        color=pts_color,
        mode=pts_mode,
        colormap="gnuplot",
        scale_factor=pts_scale,
        figure=fig,
    )

    # draw origin
    mlab.points3d(0, 0, 0, color=(1, 1, 1), mode="sphere", scale_factor=0.2)

    # draw axis
    axes = np.array(
        [[2.0, 0.0, 0.0, 0.0], [0.0, 2.0, 0.0, 0.0], [0.0, 0.0, 2.0, 0.0]],
        dtype=np.float64,
    )
    mlab.plot3d(
        [0, axes[0, 0]],
        [0, axes[0, 1]],
        [0, axes[0, 2]],
        color=(1, 0, 0),
        tube_radius=None,
        figure=fig,
    )
    mlab.plot3d(
        [0, axes[1, 0]],
        [0, axes[1, 1]],
        [0, axes[1, 2]],
        color=(0, 1, 0),
        tube_radius=None,
        figure=fig,
    )
    mlab.plot3d(
        [0, axes[2, 0]],
        [0, axes[2, 1]],
        [0, axes[2, 2]],
        color=(0, 0, 1),
        tube_radius=None,
        figure=fig,
    )

    # draw fov (todo: update to real sensor spec.)
    fov = np.array(
        [[20.0, 20.0, 0.0, 0.0], [20.0, -20.0, 0.0, 0.0]],
        dtype=np.float64  # 45 degree
    )

    mlab.plot3d(
        [0, fov[0, 0]],
        [0, fov[0, 1]],
        [0, fov[0, 2]],
        color=(1, 1, 1),
        tube_radius=None,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [0, fov[1, 0]],
        [0, fov[1, 1]],
        [0, fov[1, 2]],
        color=(1, 1, 1),
        tube_radius=None,
        line_width=1,
        figure=fig,
    )

    # draw square region
    TOP_Y_MIN = -20
    TOP_Y_MAX = 20
    TOP_X_MIN = 0
    TOP_X_MAX = 40
    TOP_Z_MIN = -2.0
    TOP_Z_MAX = 0.4

    x1 = TOP_X_MIN
    x2 = TOP_X_MAX
    y1 = TOP_Y_MIN
    y2 = TOP_Y_MAX
    mlab.plot3d(
        [x1, x1],
        [y1, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x2, x2],
        [y1, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x1, x2],
        [y1, y1],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )
    mlab.plot3d(
        [x1, x2],
        [y2, y2],
        [0, 0],
        color=(0.5, 0.5, 0.5),
        tube_radius=0.1,
        line_width=1,
        figure=fig,
    )

    # mlab.orientation_axes()
    mlab.view(
        azimuth=180,
        elevation=70,
        focalpoint=[12.0909996, -1.04700089, -2.03249991],
        distance=62.0,
        figure=fig,
    )
    return fig
Ejemplo n.º 56
0
A = A.tocsr()

# create the right-hand-side vector, consisting of the forcing term
# for the interior nodes and zeros for the boundary nodes
d = np.zeros(N)
d[interior] = forcing(nodes[interior, 0], nodes[interior, 1], nodes[interior,
                                                                    2])
d[boundary] = true_soln(nodes[boundary, 0], nodes[boundary, 1], nodes[boundary,
                                                                      2])

# find the solution at the nodes
u = scipy.sparse.linalg.spsolve(A, d)
utrue = true_soln(nodes[:, 0], nodes[:, 1], nodes[:, 2])
err = u - utrue

mlab.figure(1)
mlab.triangular_mesh(vert[:, 0],
                     vert[:, 1],
                     vert[:, 2],
                     smp,
                     color=(1.0, 1.0, 1.0),
                     opacity=0.1)
scatter_contour(nodes, err, contours=8, opacity=0.3)
mlab.points3d(nodes[:, 0],
              nodes[:, 1],
              nodes[:, 2],
              color=(0.0, 0.0, 0.0),
              scale_factor=0.01)
mlab.title('error')
mlab.figure(2)
mlab.triangular_mesh(vert[:, 0],
# -*- coding: utf-8 -*-
from mayavi import mlab
from figure_imagedata import plot_cell

if __name__ == "__main__":
    from tvtk.api import tvtk
    import numpy as np

    x = np.array([0, 3, 9, 15])
    y = np.array([0, 1, 5])
    z = np.array([0, 2, 3])
    r = tvtk.RectilinearGrid()
    r.x_coordinates = x
    r.y_coordinates = y
    r.z_coordinates = z
    r.dimensions = len(x), len(y), len(z)

    r.point_data.scalars = np.arange(0.0, r.number_of_points)
    r.point_data.scalars.name = 'scalars'

    mlab.figure(1, fgcolor=(0, 0, 0), bgcolor=(1, 1, 1))
    mlab.clf()
    mlab.pipeline.surface(mlab.pipeline.extract_edges(r), color=(0, 0, 0))
    mlab.pipeline.glyph(r, mode='sphere', scale_factor=0.5, scale_mode='none')
    plot_cell(r.get_cell(1))
    mlab.text(0.01, 0.9, "get_cell(1)", width=0.25)
    axes = mlab.orientation_axes()
    mlab.show()
Ejemplo n.º 58
0
m4 = 1
m5 = 2
m6 = 2
m7 = 4
s = sin(m0 * phi)**m1 + cos(m2 * phi)**m3 + sin(m4 * theta)**m5 + cos(
    m6 * theta)**m7
x = sin(phi) * cos(theta)
y = cos(phi)
z = sin(phi) * sin(theta)

################################################################################
# Plot the data
from mayavi import mlab

# A first plot in 3D
fig = mlab.figure(1)
mlab.clf()
mesh = mlab.mesh(x, y, z, scalars=s)
cursor3d = mlab.points3d(0.,
                         0.,
                         0.,
                         mode='axes',
                         color=(0, 0, 0),
                         scale_factor=0.5)
mlab.title('Click on the ball')

# A second plot, flat
fig2d = mlab.figure(2)
mlab.clf()
im = mlab.imshow(s)
cursor = mlab.points3d(0,
Ejemplo n.º 59
0
def plot3dformesh(x, cv, f):
    cv = band.toZeroStatic(cv)
    if MPI.COMM_WORLD.rank == 0:
        v2 = cv.getArray()
        pl.figure(bgcolor=(1, 1, 1), fgcolor=(0.5, 0.5, 0.5))
        pl.triangular_mesh(x[:, 0], x[:, 1], x[:, 2], f, scalars=v2)
Ejemplo n.º 60
0
lower_thr = sorted_data[int(0.2 * l)]
upper_thr = sorted_data[int(0.8 * l)]

# The white matter boundary: find the densest part of the upper half
# of histogram, and take a value 10% higher, to cut _in_ the white matter
hist, bins = np.histogram(data[data > np.mean(data)], bins=50)
brain_thr_idx = np.argmax(hist)
brain_thr = bins[brain_thr_idx + 4]

del hist, bins, brain_thr_idx

# Display the data #############################################################
from mayavi import mlab
from tvtk.api import tvtk

fig = mlab.figure(bgcolor=(0, 0, 0), size=(400, 500))
# to speed things up
fig.scene.disable_render = True

src = mlab.pipeline.scalar_field(data)
# Our data is not equally spaced in all directions:
src.spacing = [1, 1, 1.5]
src.update_image_data = True

#----------------------------------------------------------------------
# Brain extraction pipeline

# In the following, we create a Mayavi pipeline that strongly
# relies on VTK filters. For this, we make heavy use of the
# mlab.pipeline.user_defined function, to include VTK filters in
# the Mayavi pipeline.