Beispiel #1
0
    def _plot_max_Value( self ):
        X = self.X_hf[:, 0]
        Y = self.Y_hf[:, 0]
        Z = self.Z_hf[:, 0]


        plot_col = getattr( self, self.plot_column )[:, 0]
        scale = 1 / max( plot_col )
#        if self.plot_column == 'n_tex':
#            plot_col = where( plot_col < 0, 0, plot_col )

        mlab.figure( figure = "SFB532Demo",
                     bgcolor = ( 1.0, 1.0, 1.0 ),
                     fgcolor = ( 0.0, 0.0, 0.0 ) )

        mlab.points3d( X, Y, ( -1.0 ) * Z, plot_col,
#                       colormap = "gist_rainbow",
#                       colormap = "Reds",
                       colormap = "copper",
                       mode = "cube",
                       scale_factor = scale )
        mlab.outline()

        mlab.scalarbar( title = self.plot_column, orientation = 'vertical' )

        mlab.show
def plot_XYZ():
    mlab.points3d( X, Y, Z_wf,
                   error_Z_abs,
                   colormap = "YlOrBr",
                   mode = "cube",
                   scale_factor = 100. )
    mlab.scalarbar( orientation = 'vertical' )
def plot_XYZ():
    mlab.points3d( X, Y, Z,
                   error_t_rel,
#                   error_t_abs,
                   colormap = "YlOrBr",
                   mode = "cube",
                   scale_factor = 0.015 )
    mlab.scalarbar( orientation = 'vertical' )
Beispiel #4
0
def plot_retino_image(mesh_path, name, tf=None, tex=None, curv=None, mask=None,
                     vmin=0, vmax=0):
    """Custom function to plot mesh in the case of retinotopic mapping  

    Parameters
    ----------
    mesh_path: string, path of the mesh to plot
    name: string, object identifier
    tf: (4, 4)  array
        affine transformation that has to be applied to the mesh
    tex: array of shape (mes.n_vertices),
         texture to plot on the surface
    curv: array of shape (mes.n_vertices),
          curvature texture to plot on the surface
    mask: array of shape (mes.n_vertices),
          A mask for functional regions of interest
    vmin, vmax: bounds for color clipping
    """
    vertices, triangles =  mesh_arrays(mesh_path)
    af_coord = np.hstack((vertices, np.ones((vertices.shape[0], 1))))
    if tf is not None:
        af_coord = np.dot(af_coord, tf.T)
    
    vertices = af_coord[:, :3]
    x, y, z = vertices.T

    # it is expected that the curvature takes values between 0 and 1
    if curv is not None:
        cmin = 2 * curv.min() - curv.max()
        cmax = 2 * curv.max() - curv.min()
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name, scalars=curv, colormap="bone",
                             vmin=cmin, vmax=cmax)
    else:
        mlab.triangular_mesh(x, y, z, triangles, transparent=False, opacity=1.,
                             name=name)
    if tex is not None:
        if mask is not None:
            tex[mask == 0] = vmin - 1

        func_mesh = mlab.pipeline.triangular_mesh_source(x, y, z,
                                                  triangles,
                                                  scalars=tex)
        thresh = mlab.pipeline.threshold(func_mesh, low=vmin)
        mlab.pipeline.surface(thresh, colormap="jet", vmin=vmin,
                              vmax=vmax, transparent=True,
                              opacity=.8)
        mlab.scalarbar(thresh)
Beispiel #5
0
    def getData(self, data_D, data_H, name):
        """
        plot passed in data as a surface
        """

        #plotting
        fig = mlab.figure(size=(512, 512))

        cl.enqueue_read_buffer(lbm.queue, data_D, data_H).wait()

        # retrieve mid cell points from cell node data
        Nx = lbm.X.size - 1
        Ny = lbm.Y.size - 1
        x = np.zeros((Nx))
        y = np.zeros((Ny))

        for i in range(1, lbm.X.size):
            x[i - 1] = (lbm.X[i] - lbm.X[i - 1]) / 2.0 + lbm.X[i - 1]

        for i in range(1, lbm.Y.size):
            y[i - 1] = (lbm.Y[i] - lbm.Y[i - 1]) / 2.0 + lbm.Y[i - 1]

        s = mlab.surf(x, y, data_H, warp_scale='auto', colormap="jet")
        mlab.axes(s)
        sb = mlab.scalarbar(s, title=name)

        self.s = s
        self.data_D = data_D
        self.data_H = data_H
Beispiel #6
0
    def show(self):
        """show Vm in a graph. Works for 1D projects only"""
        if self.Vm.ndim == 2:
            pylab.imshow(self.Vm,aspect='auto',cmap=cm.jet)
            pylab.show()
        elif self.Vm.ndim == 3:
            s = mlab.surf(self.Vm[...,0])
            raw_input("Press Enter to lauch the simulation...")
            for i in range(self.Vm.shape[-1]):
                s.mlab_source.scalars = self.Vm[...,i]
        elif self.Vm.ndim == 4:
            p = mlab.pipeline.scalar_field(self.Vm[...,0])
            s = mlab.pipeline.image_plane_widget( p,
                                        plane_orientation='x_axes',
                                        slice_index=self.mdl.stimCoord[0],
                                        vmin = self.Vm.min(),
                                        vmax = self.Vm.max()
                                    )

            s2 = mlab.pipeline.image_plane_widget(p,
                                        plane_orientation='y_axes',
                                        slice_index=self.mdl.stimCoord[2],
                                        vmin = self.Vm.min(),
                                        vmax = self.Vm.max()
                                    )
            s3 = mlab.pipeline.image_plane_widget( p,
                                        plane_orientation='z_axes',
                                        slice_index=self.mdl.stimCoord[4],
                                        vmin = self.Vm.min(),
                                        vmax = self.Vm.max()
                                    )
            mlab.scalarbar(s,orientation='vertical',nb_labels=4,label_fmt='%.3f')
            mlab.outline(color=(1,1,1))
            raw_input("Press Enter to lauch the simulation...")
            for i in range(self.Vm.shape[-1]):
                p.mlab_source.scalars = self.Vm[...,i]
Beispiel #7
0
    def add_data(self, array, min=None, max=None, colormap="blue-red"):
        """Display data from a numpy array on the surface.

        Parameters
        ----------
        array : numpy array
            data array (nvtx vector)
        min : float
            min value in colormap (uses real min if None)
        max : float
            max value in colormap (uses real max if None)
        colormap : str
            name of Mayavi colormap to use

        """
        from enthought.mayavi import mlab
        self._f.scene.disable_render = True
        view = mlab.view()

        # Possibly remove old data
        if hasattr(self, "data"):
            self.data["surface"].remove()
            self.data["colorbar"].remove()

        if min is None:
            min = array.min()
        if max is None:
            max = array.max()

        # Set up the visualization pipeline
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=array)
        surf = mlab.pipeline.surface(mesh, colormap=colormap,
                                     vmin=min, vmax=max)

        # Get the colorbar
        bar = mlab.scalarbar(surf)
        bar.scalar_bar_representation.position2 = .8, 0.09

        # Fil in the data dict
        self.data = dict(surface=surf, colorbar=bar)
        mlab.view(*view)
        self._f.scene.disable_render = False
Beispiel #8
0
    def getData(self, data_D, data_H, name):
        """
        plot passed in data as a surface
        """

        #plotting
        fig = mlab.figure(size=(512, 512))
        mlab.view(90, 0)

        cl.enqueue_read_buffer(lbm.queue, data_D, data_H).wait()

        rgrid = tvtk.RectilinearGrid()
        rgrid.cell_data.scalars = data_H.ravel()
        rgrid.cell_data.scalars.name = 'scalars'

        rgrid.dimensions = np.array((lbm.Ny + 1, lbm.Nx + 1, 1))
        rgrid.x_coordinates = lbm.Y
        rgrid.y_coordinates = lbm.X
        rgrid.z_coordinates = np.array([0.0])

        src = mlab.pipeline.add_dataset(rgrid)
        s = mlab.pipeline.cell_to_point_data(src)
        s = mlab.pipeline.surface(s)
        sb = mlab.scalarbar(s, title=name)

        #plot lines
        if 1:
            mlab.pipeline.surface(mlab.pipeline.extract_edges(src),
                                  color=(0, 0, 0),
                                  line_width=0.1,
                                  opacity=0.05)

        self.rgrid = rgrid
        self.src = src
        self.data_D = data_D
        self.data_H = data_H
Beispiel #9
0
    def __init__(self, scalar_data, geo, min, max, sign):
        """
        """
        from enthought.mayavi import mlab

        if scalar_data.min() >= 0:
            sign = "pos"
        elif scalar_data.max() <= 0:
            sign = "neg"
        self.sign = sign

        # Get data with a range that will make sense for automatic thresholding
        if sign == "neg":
            range_data = np.abs(scalar_data[np.where(scalar_data < 0)])
        elif sign == "pos":
            range_data = scalar_data[np.where(scalar_data > 0)]
        else:
            range_data = np.abs(scalar_data)

        if min is None:
            try:
                min = config.getfloat("overlay", "min_thresh")
            except ValueError:
                min_str = config.get("overlay", "min_thresh")
                if min_str == "robust_min":
                    min = stats.scoreatpercentile(range_data, 2)
                elif min_str == "actual_min":
                    min = range_data.min()
                else:
                    min = 2.0
                    warn("The 'min_thresh' value in your config value must be "
                "a float, 'robust_min', or 'actual_min', but it is %s. "
                "I'm setting the overlay min to the config default of 2" % min)

        if max is None:
            try:
                max = config.getfloat("overlay", "max_thresh")
            except ValueError:
                max_str = config.get("overlay", "max_thresh")
                if max_str == "robust_max":
                    max = stats.scoreatpercentile(range_data, 98)
                elif max_str == "actual_max":
                    max = range_data.max()
                else:
                    max = stats.scoreatpercentile(range_data, 98)
                    warn("The 'max_thresh' value in your config value must be "
                "a float, 'robust_min', or 'actual_min', but it is %s. "
                "I'm setting the overlay min to the config default "
                "of robust_max" % max)

        # Clean up range_data since we don't need it and it might be big
        del range_data

        # Byte swap inplace; due to mayavi bug
        mlab_data = scalar_data.copy()
        if scalar_data.dtype.byteorder == '>':
            mlab_data.byteswap(True)

        if sign in ["abs", "pos"]:
            pos_mesh = mlab.pipeline.triangular_mesh_source(geo.x,
                                                           geo.y,
                                                           geo.z,
                                                           geo.faces,
                                                           scalars=mlab_data)

            # Figure out the correct threshold to avoid TraitErrors
            # This seems like not the cleanest way to do this
            pos_data = scalar_data[np.where(scalar_data > 0)]
            try:
                pos_max = pos_data.max()
            except ValueError:
                pos_max = 0
            if pos_max < min:
                thresh_low = pos_max
            else:
                thresh_low = min
            pos_thresh = mlab.pipeline.threshold(pos_mesh, low=thresh_low)
            pos_surf = mlab.pipeline.surface(pos_thresh, colormap="YlOrRd",
                                             vmin=min, vmax=max)
            pos_bar = mlab.scalarbar(pos_surf)
            pos_bar.reverse_lut = True

            self.pos = pos_surf
            self.pos_bar = pos_bar

        if sign in ["abs", "neg"]:
            neg_mesh = mlab.pipeline.triangular_mesh_source(geo.x,
                                                           geo.y,
                                                           geo.z,
                                                           geo.faces,
                                                           scalars=mlab_data)

            # Figure out the correct threshold to avoid TraitErrors
            # This seems even less clean due to negative convolutedness
            neg_data = scalar_data[np.where(scalar_data < 0)]
            try:
                neg_min = neg_data.min()
            except ValueError:
                neg_min = 0
            if neg_min > -min:
                thresh_up = neg_min
            else:
                thresh_up = -min
            neg_thresh = mlab.pipeline.threshold(neg_mesh, up=thresh_up)
            neg_surf = mlab.pipeline.surface(neg_thresh, colormap="PuBu",
                                             vmin=-max, vmax=-min)
            neg_bar = mlab.scalarbar(neg_surf)

            self.neg = neg_surf
            self.neg_bar = neg_bar

        self.__format_colorbar()
Beispiel #10
0
    def add_contour_overlay(self, filepath, min=None, max=None,
                            n_contours=7, line_width=1.5):
        """Add a topographic contour overlay.

        Note: This visualization will look best when using the "low_contrast"
        cortical curvature colorscheme.

        Parameters
        ----------
        filepath : str
            path to the overlay file (must be readable by Nibabel, or .mgh)
        min : float
            threshold for overlay display
        max : float
            saturation point for overlay display
        n_contours : int
            number of contours to use in the display
        line_width : float
            width of contour lines

        """
        from enthought.mayavi import mlab

        # Read the scalar data
        scalar_data = io.read_scalar_data(filepath)

        #TODO find a better place for this; duplicates code in Overlay object
        if min is None:
            try:
                min = config.getfloat("overlay", "min_thresh")
            except ValueError:
                min_str = config.get("overlay", "min_thresh")
                if min_str == "robust_min":
                    min = stats.scoreatpercentile(scalar_data, 2)
                elif min_str == "actual_min":
                    min = scalar_data.min()
                else:
                    min = 2.0
                    warn("The 'min_thresh' value in your config value must be "
                "a float, 'robust_min', or 'actual_min', but it is %s. "
                "I'm setting the overlay min to the config default of 2" % min)

        if max is None:
            try:
                max = config.getfloat("overlay", "max_thresh")
            except ValueError:
                max_str = config.get("overlay", "max_thresh")
                if max_str == "robust_max":
                    max = stats.scoreatpercentile(scalar_data, 98)
                elif max_str == "actual_max":
                    max = scalar_data.max()
                else:
                    max = stats.scoreatpercentile(scalar_data, 98)
                    warn("The 'max_thresh' value in your config value must be "
                "a float, 'robust_min', or 'actual_min', but it is %s. "
                "I'm setting the overlay min to the config default "
                "of robust_max" % max)

        # Prep the viz
        self._f.scene.disable_render = True
        view = mlab.view()

        # Maybe get rid of an old overlay
        if hasattr(self, "contour"):
            self.contour['surface'].remove()
            self.contour['colorbar'].visible = False

        # Deal with Mayavi bug
        if scalar_data.dtype.byteorder == '>':
            scalar_data.byteswap(True)

        # Set up the pipeline
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x, self._geo.y,
                                                  self._geo.z, self._geo.faces,
                                                  scalars=scalar_data)
        thresh = mlab.pipeline.threshold(mesh, low=min)
        surf = mlab.pipeline.contour_surface(thresh, contours=n_contours,
                                             line_width=line_width)

        # Set the colorbar and range correctly
        bar = mlab.scalarbar(surf)
        bar.data_range = min, max
        bar.scalar_bar_representation.position2 = .8, 0.09

        # Set up a dict attribute with pointers at important things
        self.contour = dict(surface=surf, colorbar=bar)

        # Show the new overlay
        mlab.view(*view)
        self._f.scene.disable_render = False
# Remove close connections
con_nodes = list()
con_val = list()
for i, j in zip(ii, jj):
    if linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
        con_nodes.append((i, j))
        con_val.append(con[i, j])

con_val = np.array(con_val)

# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
for val, nodes in zip(con_val, con_nodes):
    x1, y1, z1 = sens_loc[nodes[0]]
    x2, y2, z2 = sens_loc[nodes[1]]
    mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val], vmin=vmin, vmax=vmax, tube_radius=0.002)

mlab.scalarbar(title="Phase Lag Index (PLI)", nb_labels=4)

# Add the sensor names for the connections shown
nodes_shown = list(set([n[0] for n in con_nodes] + [n[1] for n in con_nodes]))

for node in nodes_shown:
    x, y, z = sens_loc[node]
    mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005, color=(0, 0, 0))

view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
mlab.view(*view)
con_val = np.array(con_val)

# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
for val, nodes in zip(con_val, con_nodes):
    x1, y1, z1 = sens_loc[nodes[0]]
    x2, y2, z2 = sens_loc[nodes[1]]
    points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                         vmin=vmin,
                         vmax=vmax,
                         tube_radius=0.001,
                         colormap='RdBu')
    points.module_manager.scalar_lut_manager.reverse_lut = True

mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

# Add the sensor names for the connections shown
nodes_shown = list(set([n[0] for n in con_nodes] + [n[1] for n in con_nodes]))

for node in nodes_shown:
    x, y, z = sens_loc[node]
    mlab.text3d(x,
                y,
                z,
                raw.ch_names[picks[node]],
                scale=0.005,
                color=(0, 0, 0))

view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
mlab.view(*view)
Beispiel #13
0
                        )

s2 = mlab.pipeline.image_plane_widget(p,
                            plane_orientation='y_axes',
                            slice_index=ymax,
                            vmin = -60,
                            vmax = 10
                        )
s3 = mlab.pipeline.image_plane_widget( p,
                            plane_orientation='z_axes',
                            slice_index=zmax,
                            vmin = -60,
                            vmax = 10
                        )

mlab.scalarbar(s,orientation='vertical',nb_labels=4,label_fmt='%.3f')
mlab.outline(color=(1,1,1))

filename = str('png/2F_%04d' % i) + '.png'
mlab.savefig(filename)

for i in range(int(tstep/round(max(t)/len(t))),len(t),int(tstep/round(max(t)/len(t)))) :
    #
    # The next four lines are just like MATLAB.
    #
    p.mlab_source.scalars = Y[...,i]
    titl.text=str("Potential at time: %.0f ms."% t[i])
    filename = str('png/2F_%04d' % i) + '.png'
    mlab.savefig(filename)
    if showbar:
        pbar.update(i)
    ouput_data_thickness = 'RFEM_file_export/output_data_thickness_' + n_shells_str + '_' + scalefactor_delta_h_str + '02.csv'
    export_thickness_data( elem_no, X, Y, t, ouput_data_thickness )

    # 4) plot midsurface and thickness in mayavi
    #
    print '*** plotting data - thickness***'

    mlab.figure( figure = "elem_coords and thickness",
             bgcolor = ( 1.0, 1.0, 1.0 ),
             fgcolor = ( 0.0, 0.0, 0.0 ) )

    mlab.points3d( X, Y, z_middle, t,
                   colormap = "YlOrBr",
                   mode = "cube",
                   scale_factor = 0.50 )
    mlab.scalarbar( title = 'elem_coords and thickness', orientation = 'vertical' )
    mlab.axes()
    mlab.show()


    #------------------------------------------------------------------
    # MIDSURFACE
    # get a csv file with the nodal coords of the shell elements
    # in the order of the supplied csv coordinates (x,y) 
    # --> z_node in [m]
    #------------------------------------------------------------------
    print '\n'
    print '*** CALCULATE MIDSURFACE *** '

    # 1) read x,y coords from csv-file used to specify shell middle surface
    # (NOTE: the midsurface coordinates are defined at the nodes)  
Beispiel #15
0
tmdl.compute(tmax=10, stimCoord=stimCoord)


# mlab.contour3d(v[...,-1])

v = tmdl.Vm[..., 1:]

s = mlab.pipeline.image_plane_widget(
    mlab.pipeline.scalar_field(v[..., -2]), plane_orientation="z_axes", slice_index=3, vmin=v.min(), vmax=v.max()
)

# s2 = mlab.pipeline.image_plane_widget(mlab.pipeline.scalar_field(v[...,-2]),
#                            plane_orientation='y_axes',
#                            slice_index=round(Ny*2./10)+1,
#                            vmin = v.min(),
#                            vmax = v.max()
#                        )

mlab.scalarbar(s, orientation="vertical", nb_labels=4, label_fmt="%.3f")
mlab.outline()

##pour animation
for i in range(v.shape[-1]):
    s.mlab_source.scalars = v[..., i]
#    s2.mlab_source.scalars = v[...,i]


# logY=open('save.npz','w')
# numpy.savez(logY,t=t,v=v)
# logY.close()
Beispiel #16
0
def sensor_connectivity_3d(raw, picks, con, idx, n_con=20, min_dist=0.05,
                           scale_factor=0.005, tube_radius=0.001):
    """ Function to plot sensor connectivity showing strongest
        connections(n_con) excluding sensors that are less than min_dist apart.
        https://github.com/mne-tools/mne-python/blob/master/examples/connectivity/plot_sensor_connectivity.py

    Parameters
    ----------
    raw : Raw object
        Instance of mne.io.Raw
    picks : list
        Picks to be included.
    con : ndarray (n_channels, n_channels)
        Connectivity matrix.
    idx : list
        List of indices of sensors of interest.
    n_con : int
        Number of connections of interest.
    min_dist : float
        Minimum distance between sensors allowed.

    Note: Please modify scale factor and tube radius to appropriate sizes
          if the plot looks scrambled.
    """

    # Now, visualize the connectivity in 3D
    try:
        from enthought.mayavi import mlab
    except:
        from mayavi import mlab

    mlab.figure(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))

    # Plot the sensor location
    sens_loc = [raw.info['chs'][picks[i]]['loc'][:3] for i in idx]
    sens_loc = np.array(sens_loc)

    pts = mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2],
                        color=(1, 1, 1), opacity=1, scale_factor=scale_factor)

    # Get the strongest connections
    threshold = np.sort(con, axis=None)[-n_con]
    ii, jj = np.where(con >= threshold)

    # Remove close connections
    con_nodes = list()
    con_val = list()
    for i, j in zip(ii, jj):
        if sci.linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
            con_nodes.append((i, j))
            con_val.append(con[i, j])

    con_val = np.array(con_val)

    # Show the connections as tubes between sensors
    vmax = np.max(con_val)
    vmin = np.min(con_val)
    for val, nodes in zip(con_val, con_nodes):
        x1, y1, z1 = sens_loc[nodes[0]]
        x2, y2, z2 = sens_loc[nodes[1]]
        points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                             vmin=vmin, vmax=vmax, tube_radius=tube_radius,
                             colormap='RdBu')
        points.module_manager.scalar_lut_manager.reverse_lut = True

    mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

    # Add the sensor names for the connections shown
    nodes_shown = list(set([n[0] for n in con_nodes] +
                           [n[1] for n in con_nodes]))

    for node in nodes_shown:
        x, y, z = sens_loc[node]
        mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005,
                    color=(0, 0, 0))

    view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
    mlab.view(*view)
Beispiel #17
0
    def __init__(self, subject_id, hemi, surf,
                 curv=True, title=None, config_opts={}):
        """Initialize a Brain object with Freesurfer-specific data.

        Parameters
        ----------
        subject_id : str
            subject name in Freesurfer subjects dir
        hemi : str
            hemisphere id (ie 'lh' or 'rh')
        surf :  geometry name
            freesurfer surface mesh name (ie 'white', 'inflated', etc.)
        curv : boolean
            if true, loads curv file and displays binary curvature
            (default: True)
        title : str
            title for the mayavi figure
        config_opts : dict
            options to override visual options in config file
        """
        from enthought.mayavi import mlab

        # Set the identifying info
        self.subject_id = subject_id
        self.hemi = hemi
        if self.hemi == 'lh':
            self.viewdict = lh_viewdict
        elif self.hemi == 'rh':
            self.viewdict = rh_viewdict
        self.surf = surf

        # Initialize an mlab figure
        bg_color_code, size = self.__get_scene_properties(config_opts)
        if title is None:
            title = subject_id
        self._f = mlab.figure(title,
                              bgcolor=bg_color_code,
                              size=size)
        mlab.clf()
        self._f.scene.disable_render = True

        # Initialize a Surface object as the geometry
        self._geo = Surface(subject_id, hemi, surf)

        # Load in the geometry and (maybe) curvature
        self._geo.load_geometry()
        if curv:
            self._geo.load_curvature()
            curv_data = self._geo.bin_curv
            meshargs = dict(scalars=curv_data)
        else:
            curv_data = None
            meshargs = dict()

        # mlab pipeline mesh for geomtery
        self._geo_mesh = mlab.pipeline.triangular_mesh_source(
                                        self._geo.x, self._geo.y, self._geo.z,
                                        self._geo.faces, **meshargs)

        # mlab surface for the geometry
        if curv:
            colormap, vmin, vmax, reverse = self.__get_geo_colors(config_opts)
            self._geo_surf = mlab.pipeline.surface(self._geo_mesh,
                                colormap=colormap, vmin=vmin, vmax=vmax)
            if reverse:
                curv_bar = mlab.scalarbar(self._geo_surf)
                curv_bar.reverse_lut = True
                curv_bar.visible = False
        else:
            self._geo_surf = mlab.pipeline.surface(self._geo_mesh,
                                                   color=(.5, .5, .5))

        # Initialize the overlay and label dictionaries
        self.overlays = dict()
        self.labels = dict()
        self.foci = dict()

        # Bring up the lateral view
        self.show_view(config.get("visual", "default_view"))

        # Turn disable render off so that it displays
        self._f.scene.disable_render = False
        con_nodes.append((i, j))
        con_val.append(con[i, j])

con_val = np.array(con_val)

# Show the connections as tubes between sensors
vmax = np.max(con_val)
vmin = np.min(con_val)
for val, nodes in zip(con_val, con_nodes):
    x1, y1, z1 = sens_loc[nodes[0]]
    x2, y2, z2 = sens_loc[nodes[1]]
    points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                         vmin=vmin, vmax=vmax, tube_radius=0.001,
                         colormap='RdBu')
    points.module_manager.scalar_lut_manager.reverse_lut = True


mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

# Add the sensor names for the connections shown
nodes_shown = list(set([n[0] for n in con_nodes] +
                       [n[1] for n in con_nodes]))

for node in nodes_shown:
    x, y, z = sens_loc[node]
    mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005,
                color=(0, 0, 0))

view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
mlab.view(*view)
Beispiel #19
0
    def add_morphometry(self, measure, grayscale=False):
        """Add a morphometry overlay to the image.

        Parameters
        ----------
        measure : {'area' | 'curv' | 'jacobian_white' | 'sulc' | 'thickness'}
            which measure to load
        grayscale : bool
            whether to load the overlay with a grayscale colormap

        """
        from enthought.mayavi import mlab

        # Find the source data
        surf_dir = pjoin(os.environ['SUBJECTS_DIR'], self.subject_id, 'surf')
        morph_file = pjoin(surf_dir, '.'.join([self.hemi, measure]))
        if not os.path.exists(morph_file):
            raise ValueError(
                'Could not find %s in subject directory' % morph_file)

        # Preset colormaps
        cmap_dict = dict(area="pink",
                         curv="RdBu",
                         jacobian_white="pink",
                         sulc="RdBu",
                         thickness="pink")

        self._f.scene.disable_render = True

        # Maybe get rid of an old overlay
        if hasattr(self, "morphometry"):
            self.morphometry['surface'].remove()
            self.morphometry['colorbar'].visible = False

        # Save the inital view
        view = mlab.view()

        # Read in the morphometric data
        morph_data = io.read_morph_data(morph_file)

        # Get a cortex mask for robust range
        self._geo.load_label("cortex")
        ctx_idx = self._geo.labels["cortex"]

        # Get the display range
        if measure == "thickness":
            min, max = 1, 4
        else:
            min, max = stats.describe(morph_data[ctx_idx])[1]

        # Set up the Mayavi pipeline
        if morph_data.dtype.byteorder == '>':
            morph_data.byteswap(True)  # byte swap inplace; due to mayavi bug
        mesh = mlab.pipeline.triangular_mesh_source(self._geo.x,
                                                    self._geo.y,
                                                    self._geo.z,
                                                    self._geo.faces,
                                                    scalars=morph_data)
        if grayscale:
            colormap = "gray"
        else:
            colormap = cmap_dict[measure]
        surf = mlab.pipeline.surface(mesh, colormap=colormap,
                                     vmin=min, vmax=max,
                                     name=measure)

        # Get the colorbar
        bar = mlab.scalarbar(surf)
        bar.scalar_bar_representation.position2 = .8, 0.09

        # Fil in the morphometry dict
        self.morphometry = dict(surface=surf,
                                colorbar=bar,
                                measure=measure)
        mlab.view(*view)
        self._f.scene.disable_render = False
Beispiel #20
0
def sensor_connectivity_3d(raw, picks, con, idx, n_con=20, min_dist=0.05, scale_factor=0.005, tube_radius=0.001):
    """ Function to plot sensor connectivity showing strongest connections(n_con)
        excluding sensors that are less than min_dist apart.
        https://github.com/mne-tools/mne-python/blob/master/examples/connectivity/plot_sensor_connectivity.py

    Parameters
    ----------
    raw : Raw object
        Instance of mne.io.Raw
    picks : list
        Picks to be included.
    con : ndarray (n_channels, n_channels)
        Connectivity matrix.
    idx : list
        List of indices of sensors of interest.
    n_con : int
        Number of connections of interest.
    min_dist : float
        Minimum distance between sensors allowed.

    Note: Please modify scale factor and tube radius to appropriate sizes if the plot looks scrambled.
    """

    # Now, visualize the connectivity in 3D
    try:
        from enthought.mayavi import mlab
    except:
        from mayavi import mlab

    mlab.figure(size=(600, 600), bgcolor=(0.5, 0.5, 0.5))

    # Plot the sensor location
    sens_loc = [raw.info['chs'][picks[i]]['loc'][:3] for i in idx]
    sens_loc = np.array(sens_loc)

    pts = mlab.points3d(sens_loc[:, 0], sens_loc[:, 1], sens_loc[:, 2],
                        color=(1, 1, 1), opacity=1, scale_factor=scale_factor)

    # Get the strongest connections
    threshold = np.sort(con, axis=None)[-n_con]
    ii, jj = np.where(con >= threshold)

    # Remove close connections
    con_nodes = list()
    con_val = list()
    for i, j in zip(ii, jj):
        if sci.linalg.norm(sens_loc[i] - sens_loc[j]) > min_dist:
            con_nodes.append((i, j))
            con_val.append(con[i, j])

    con_val = np.array(con_val)

    # Show the connections as tubes between sensors
    vmax = np.max(con_val)
    vmin = np.min(con_val)
    for val, nodes in zip(con_val, con_nodes):
        x1, y1, z1 = sens_loc[nodes[0]]
        x2, y2, z2 = sens_loc[nodes[1]]
        points = mlab.plot3d([x1, x2], [y1, y2], [z1, z2], [val, val],
                             vmin=vmin, vmax=vmax, tube_radius=tube_radius,
                             colormap='RdBu')
        points.module_manager.scalar_lut_manager.reverse_lut = True

    mlab.scalarbar(title='Phase Lag Index (PLI)', nb_labels=4)

    # Add the sensor names for the connections shown
    nodes_shown = list(set([n[0] for n in con_nodes] +
                           [n[1] for n in con_nodes]))

    for node in nodes_shown:
        x, y, z = sens_loc[node]
        mlab.text3d(x, y, z, raw.ch_names[picks[node]], scale=0.005,
                    color=(0, 0, 0))

    view = (-88.7, 40.8, 0.76, np.array([-3.9e-4, -8.5e-3, -1e-2]))
    mlab.view(*view)
Beispiel #21
0
        X = lcc_list[0].ls_table.X[:, 0]
        Y = lcc_list[0].ls_table.Y[:, 0]
        Z = lcc_list[0].ls_table.Z[:, 0]
        plot_col = n_tex_max[:, 0]

        # if n_tex is negative plot 0 instead:
        #
        plot_col = where( plot_col < 0, 0, plot_col )

        mlab.figure( figure = "SFB532Demo",
                     bgcolor = ( 1.0, 1.0, 1.0 ),
                     fgcolor = ( 0.0, 0.0, 0.0 ) )

        mlab.points3d( X, Y, ( -1.0 ) * Z, plot_col,
                       colormap = "YlOrBr",
                       mode = "cube",
                       scale_factor = 0.10 )

        mlab.scalarbar( title = 'n_tex (all LCs)', orientation = 'vertical' )

        mlab.show()



#    print 'lc_arr', lct.lc_arr
#    print 'lc_list[0].sr_arr.shape[0]', lct.lc_list[0].sr_arr.shape[0]
#    print 'lc_arr.shape', lct.lc_arr.shape
#    print 'combi_arr', lct.combi_arr
#    print 'combi_arr.shape', lct.combi_arr.shape
#    print 'lcc_arr', lct.lcc_arr