Esempio n. 1
0
def plot_overlays_diff_group_window(condition,method,modality,hemi,window,azimuth,elevation):

    subject_id, surface = 'fsaverage', 'inflated'
    hemi = hemi
    brain = Brain(subject_id, hemi, surface, size=(600, 600))
    stc_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized'
                 + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method 
                 + '_ico-5-fwd-fsaverage.stc-'+ hemi +'.stc')
                 
    stcl_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized'
                 + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method 
                 + '_ico-5-fwd-fsaverage.stc-lh.stc')
    stcr_fname = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/BrainMaps/IcaCorr_Normalized'
                 + modality + '_' + condition[0] + '-' + condition[1] + '_pick_oriNone_' + method 
                 + '_ico-5-fwd-fsaverage.stc-rh.stc')    
                 
    stcl  = read_stc(stcl_fname)
    stcr  = read_stc(stcr_fname)
    datal = stcl['data']  
    datar = stcr['data']            
                 
    stc = read_stc(stc_fname)
    data = stc['data']
    vertices = stc['vertices']
    time = np.linspace(stc['tmin'], stc['tmin'] + data.shape[1] * stc['tstep'],
                       data.shape[1])
    winstart = np.where(time < window[0])[0][-1]
    winend   = np.where(time >= window[1])[0][0]
    
    meanval = np.mean(data[:,winstart:winend],1)   
    meanvalr = np.mean(datar[:,winstart:winend],1)   
    meanvall = np.mean(datal[:,winstart:winend],1)  
    maxval = np.max([np.max(meanvalr),np.max(meanvall)])
    minval = np.min([np.min(meanvalr),np.min(meanvall)])
    fmin = -np.max(np.abs([maxval,minval]))*0.8
    fmax = np.max(np.abs([maxval,minval]))*0.8
    
    colormap = mne.viz.mne_analyze_colormap(limits=[fmin, fmin/3, fmin/3.1, fmax/3.1, fmax/3, fmax], format='mayavi')
    #colormap = 'jet'
    
    time_label = lambda t: 'time=%0.2f ms' % (0)
    brain.add_data(meanval, colormap=colormap, vertices=vertices,
                   smoothing_steps=15, time=time, time_label=time_label,
                   hemi=hemi)
    brain.scale_data_colormap(fmin=fmin, fmid=0, fmax=fmax, transparent=False)
    brain.show_view(dict(azimuth=azimuth,elevation=elevation, distance=None))
    #    mayavi.mlab.view(azimuth=0, elevation=None, distance=None, focalpoint=None,
    #         roll=None, reset_roll=True, figure=None)
    
    PlotDir = []
    PlotDir = ('/neurospin/meg/meg_tmp/MTT_MEG_Baptiste/MEG/GROUP/mne_python/Plots/IcaCorr_Window_'  
               + condition[0] + '-' + condition[1]  + str(window[0]) + '-' + str(window[1])) 
    
    if not os.path.exists(PlotDir):
        os.makedirs(PlotDir)

    brain.save_image(PlotDir + '/IcaCorr_' + modality + '_' + method + '_'
                        + '_Normalized' + condition[0] + '-' + condition[1] + '_'
                        + str(window[0]) + '-' + str(window[1])
                        +  hemi + '_'+ str(azimuth)+ '_ico-5-fwd-fsaverage-'+'.png')       
Esempio n. 2
0
def test_brains():
    """Test plotting of Brain with different arguments
    """
    # testing backend breaks when passing in a figure, so we use 'auto' here
    # (shouldn't affect usability, but it makes testing more annoying)
    mlab.options.backend = 'auto'
    surfs = ['inflated', 'white']
    hemis = ['lh', 'rh']
    curvs = [True, False]
    titles = [None, 'Hello']
    cortices = ["low_contrast", ("Reds", 0, 1, False)]
    sizes = [500, (400, 300)]
    backgrounds = ["white", "blue"]
    foregrounds = ["black", "white"]
    figs = [None, mlab.figure()]
    subj_dirs = [None, subj_dir]
    for surf, hemi, curv, title, cort, s, bg, fg, fig, sd \
            in zip(surfs, hemis, curvs, titles, cortices, sizes,
                   backgrounds, foregrounds, figs, subj_dirs):
        brain = Brain(subject_id, hemi, surf, curv, title, cort, s, bg, fg,
                      fig, sd)
        brain.close()
    assert_raises(ValueError,
                  Brain,
                  subject_id,
                  'lh',
                  'inflated',
                  subjects_dir='')
Esempio n. 3
0
def test_text():
    """Test plotting of text
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    brain.add_text(0.1, 0.1, 'Hello', 'blah')
    brain.close()
Esempio n. 4
0
def plot_single_roi(roi):
    fsaverage = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    t, p, str_names, labels = get_data()
    df = pd.DataFrame({'labs': str_names, 't': 0})
    df.loc[df.labs == roi, 't'] = -4
    data = df.t.values
    data = data[labels]
    brain = Brain(fsaverage,
                  hemi,
                  surf,
                  background="white",
                  views=['lateral', 'ventral', 'medial', 'frontal'])
    brain.add_data(data, -10, 11, thresh=None, colormap="RdBu_r", alpha=1)
    f = brain.save_montage(None,
                           [['lateral', 'parietal'], ['medial', 'frontal']],
                           border_size=0,
                           colorbar=None)
    fig, a = plt.subplots()
    im = plt.imshow(f, cmap='RdBu_r')
    a.set(xticks=[], yticks=[])
    sns.despine(bottom=True, left=True)
    cbar = fig.colorbar(im,
                        ticks=[f.min(), (f.min() + 255) / 2, 255],
                        orientation='horizontal',
                        drawedges=False)
    cbar.ax.set_xticklabels(['-10', '0', '10'])
    a.set_title(roi)
    return f, data
def plot_one_brain(dsignal,
                   signal,
                   lc,
                   cmap,
                   ex_sub='S04',
                   classifier='SCVlin',
                   epoch='response',
                   measure='auc',
                   views=[['par', 'fro'], ['lat', 'med']]):
    from surfer import Brain
    print('Creating Brain')
    brain = Brain(ex_sub, 'lh', 'inflated', views=['lat'], background='w')
    # subjects_dir='/Users/nwilming/u/freesurfer_subjects/')
    print('Created Brain')
    ms = dsignal.mean()
    if (signal == 'CONF_signed') and (measure == 'accuracy'):
        plot_labels_on_brain(brain, lc, ms, cmap)
    if (signal == 'SSD'):
        plot_labels_on_brain(brain, lc, ms, cmap)
    else:
        plot_labels_on_brain(brain, lc, ms, cmap)
    brain.save_montage(
        '/Users/nwilming/Desktop/%s_montage_%s_%s_%s.png' %
        (signal, measure, classifier, epoch), views)
    return brain
Esempio n. 6
0
def brain_plot(r_name, viewtimes, brain):
    views = {'rh': ['medial', 'parietal'], 'lh': ['parietal', 'medial']}

    if type(brain) is str:
        hemi = brain
        brain = Brain('fsaverage',
                      hemi,
                      'inflated',
                      cortex='low_contrast',
                      subjects_dir=sv.subjects_dir,
                      background='w',
                      foreground='k')
    else:
        hemi = brain.geo.keys()[0]

    sv.show_labels_as_data(src_df_masked.loc[r_name], show_measure, brain,
                           **colorinfo)

    filepat = os.path.join(
        figdir, filepat_base + '_{}_{}_%02d.png'.format(hemi, r_name))

    brain.save_image_sequence([times.get_loc(t) for t in viewtimes],
                              filepat,
                              montage=views[hemi])

    return brain
Esempio n. 7
0
def test_brains():
    """Test plotting of Brain with different arguments."""
    # testing backend breaks when passing in a figure, so we use 'auto' here
    # (shouldn't affect usability, but it makes testing more annoying)
    mlab.options.backend = 'auto'
    surfs = ['inflated', 'white', 'white', 'white', 'white', 'white', 'white']
    hemis = ['lh', 'rh', 'both', 'both', 'rh', 'both', 'both']
    titles = [None, 'Hello', 'Good bye!', 'lut test',
              'dict test', 'None test', 'RGB test']
    cortices = ["low_contrast", ("Reds", 0, 1, False), 'hotpink',
                ['yellow', 'blue'], dict(colormap='Greys'),
                None, (0.5, 0.5, 0.5)]
    sizes = [500, (400, 300), (300, 300), (300, 400), 500, 400, 300]
    backgrounds = ["white", "blue", "black", "0.75",
                   (0.2, 0.2, 0.2), "black", "0.75"]
    foregrounds = ["black", "white", "0.75", "red",
                   (0.2, 0.2, 0.2), "blue", "black"]
    figs = [None, mlab.figure(), None, None, mlab.figure(), None, None]
    subj_dirs = [None, subj_dir, subj_dir, subj_dir,
                 subj_dir, subj_dir, subj_dir]
    alphas = [1.0, 0.5, 0.25, 0.7, 0.5, 0.25, 0.7]
    for surf, hemi, title, cort, s, bg, fg, fig, sd, alpha \
            in zip(surfs, hemis, titles, cortices, sizes,
                   backgrounds, foregrounds, figs, subj_dirs, alphas):
        brain = Brain(subject_id, hemi, surf, title=title, cortex=cort,
                      alpha=alpha, size=s, background=bg, foreground=fg,
                      figure=fig, subjects_dir=sd)
        brain.close()
    assert_raises(ValueError, Brain, subject_id, 'lh', 'inflated',
                  subjects_dir='')
Esempio n. 8
0
def test_offscreen():
    """Test offscreen rendering
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, offscreen=True)
    shot = brain.screenshot()
    assert_array_equal(shot.shape, (800, 800, 3))
Esempio n. 9
0
def test_morphometry():
    """Test plotting of morphometry."""
    _set_backend()
    brain = Brain(*std_args)
    brain.add_morphometry("curv")
    brain.add_morphometry("sulc", grayscale=True)
    brain.add_morphometry("thickness")
    brain.close()
Esempio n. 10
0
def test_offscreen():
    """Test offscreen rendering."""
    _set_backend()
    brain = Brain(*std_args, offscreen=True)
    shot = brain.screenshot()
    assert_array_less((400, 400, 2), shot.shape)
    assert_array_less(shot.shape, (801, 801, 4))
    brain.close()
Esempio n. 11
0
def test_morphometry():
    """Test plotting of morphometry."""
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    brain.add_morphometry("curv")
    brain.add_morphometry("sulc", grayscale=True)
    brain.add_morphometry("thickness")
    brain.close()
Esempio n. 12
0
def test_data_limits():
    """Test handling of data limits."""
    _set_backend()
    brain = Brain(*std_args)
    surf_data = np.zeros(163842)
    pytest.raises(ValueError, brain.add_data, surf_data, 0, 0)
    brain.add_data(surf_data, 0, 1)
    brain.close()
Esempio n. 13
0
def test_offscreen():
    """Test offscreen rendering
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, offscreen=True)
    shot = brain.screenshot()
    assert_array_equal(shot.shape, (800, 800, 3))
    brain.close()
Esempio n. 14
0
def test_offscreen():
    """Test offscreen rendering."""
    _set_backend()
    brain = Brain(*std_args, offscreen=True)
    shot = brain.screenshot()
    assert_array_less((400, 400, 2), shot.shape)
    assert_array_less(shot.shape, (801, 801, 4))
    brain.close()
Esempio n. 15
0
def main(subid, overlay):
    _, fname = os.path.split(overlay)
    
    hemi = fname[:2]
    brain = Brain(subid, hemi, "pial",
                  config_opts=dict(cortex="low_contrast"))
    brain.add_overlay(overlay, min=0.4, max=4, sign="pos")
    brain.show_view('m')
Esempio n. 16
0
def test_data():
    """Test plotting of data
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
Esempio n. 17
0
 def make_brain(subject_id,image_path):
     from surfer import Brain
     hemi = 'lh'
     surface = 'inflated'
     brain = Brain(subject_id, hemi, surface)
     brain.add_overlay(image_path,min=thr)
     outpath = os.path.join(os.getcwd(),os.path.split(image_path)[1]+'_surf.png')
     brain.save_montage(outpath)
     return outpath
Esempio n. 18
0
def add_cluster(clustermap, hemi, fsaverage):
    brain = Brain(fsaverage,
                  hemi,
                  surface,
                  config_opts=dict(background="lightslategray",
                                   cortex="high_contrast"))
    brain.add_data(clustermap, colormap='spectral', alpha=.8)
    brain.data['colorbar'].number_of_colors = int(clustermap.max()) + 1
    brain.data['colorbar'].number_of_labels = int(clustermap.max(
    )) + 1  ##because -1 denotes masked regions, cluster labels start at 1
Esempio n. 19
0
def test_annot():
    """Test plotting of annot
    """
    mlab.options.backend = 'test'
    annots = ['aparc', 'aparc.a2005s']
    borders = [True, False]
    alphas = [1, 0.5]
    brain = Brain(*std_args)
    for a, b, p in zip(annots, borders, alphas):
        brain.add_annotation(a, b, p)
Esempio n. 20
0
def get_hemi_data(subject, hemi, source, surf_name="pial", name=None, sign="abs", min=None, max=None):
    brain = Brain(subject, hemi, surf_name, curv=False)
    hemi = brain._check_hemi(hemi)
    # load data here
    scalar_data, name = brain._read_scalar_data(source, hemi, name=name)
    min, max = brain._get_display_range(scalar_data, min, max, sign)
    if sign not in ["abs", "pos", "neg"]:
        raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
    old = viz.OverlayData(scalar_data, brain.geo[hemi], min, max, sign)
    return old.mlab_data, brain
Esempio n. 21
0
def test_brain_separate():
    """Test that Brain does not reuse existing figures by default."""
    _set_backend('auto')
    brain = Brain(*std_args)
    assert brain.brain_matrix.size == 1
    brain_2 = Brain(*std_args)
    assert brain_2.brain_matrix.size == 1
    assert brain._figures[0][0] is not brain_2._figures[0][0]
    brain_3 = Brain(*std_args, figure=brain._figures[0][0])
    assert brain._figures[0][0] is brain_3._figures[0][0]
Esempio n. 22
0
def contrast_loop(subj, contrasts, stat_temp, mask_temp, png_temp, args,
                  z_thresh, sign):
    """Iterate over contrasts and make surface images."""
    for contrast in contrasts:

        # Calculate where the overlay should saturate
        z_max = calculate_sat_point(stat_temp, contrast, sign, subj)
        panels = []
        for hemi in ["lh", "rh"]:

            # Initialize the brain object
            b_subj = subj if args.regspace == "epi" else "fsaverage"

            try:
                b = Brain(b_subj, hemi, args.geometry, background="white")
            except TypeError:
                # PySurfer <= v0.5
                b = Brain(b_subj,
                          hemi,
                          args.geometry,
                          config_opts={"background": "white"})

            # Plot the mask
            mask_file = mask_temp.format(contrast=contrast,
                                         hemi=hemi,
                                         subj=subj)
            add_mask_overlay(b, mask_file)

            # Plot the overlay
            stat_file = stat_temp.format(contrast=contrast,
                                         hemi=hemi,
                                         subj=subj)
            add_stat_overlay(b,
                             stat_file,
                             z_thresh,
                             z_max,
                             sign,
                             sig_to_z=args.regspace == "fsaverage")

            # Take screenshots
            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                sleep(.1)
                panels.append(crop(b.screenshot()))
            b.close()

        # Make a single figure with all the panels
        f = multi_panel_brain_figure(panels)
        kwargs = {}
        if sign in ["pos", "abs"]:
            kwargs["pos_cmap"] = "Reds_r"
        if sign in ["neg", "abs"]:
            kwargs["neg_cmap"] = "Blues"
        add_colorbars(f, z_thresh, z_max, **kwargs)

        # Save the figure in both hemisphere outputs
        for hemi in ["lh", "rh"]:
            png_file = png_temp.format(hemi=hemi, contrast=contrast, subj=subj)
            f.savefig(png_file, bbox_inches="tight")
        plt.close(f)
Esempio n. 23
0
def surface_images(out_dir, subj):
    """Plot the white, pial, and inflated surfaces to look for defects."""
    for surf in ["white", "pial", "inflated"]:
        panels = []
        for hemi in ["lh", "rh"]:

            try:
                b = Brain(subj, hemi, surf, curv=False, background="white")
            except TypeError:
                # PySurfer <= 0.5
                b = Brain(subj,
                          hemi,
                          surf,
                          curv=False,
                          config_opts=dict(background="white"))

            for view in ["lat", "med", "ven"]:
                b.show_view(view, distance="auto")
                panels.append(crop(b.screenshot()))
            b.close()

        # Make and save a figure
        f = multi_panel_brain_figure(panels)
        fname = op.join(out_dir, "{}_surface.png".format(surf))
        f.savefig(fname, bbox_inches="tight")
        plt.close(f)
Esempio n. 24
0
def make_brain_figures(srcdf, measure, cinfo, filepat_base, top=5):
    views = {'rh': ['medial', 'lateral'],
             'lh': ['lateral', 'medial']}
    
    toplabels = {}
    
    for hemi in ['lh', 'rh']:
        brain = Brain('fsaverage', hemi, 'inflated', cortex='low_contrast',
                      subjects_dir=sv.subjects_dir, background='w', 
                      foreground='k')
            
        sv.show_labels_as_data(srcdf, measure, brain, 
                               time_label=None, parc=parc, **cinfo)
        
        if top:
            ind = srcdf.index.get_level_values('label').map(
                    lambda x: x.startswith(hemi[0].upper()))
            
            topl = srcdf[ind].abs().sort_values(
                    measure, ascending=False).head(top)
            topl = (
                    topl[(topl[measure] != 0) 
                              & topl[measure].notna()]
                    .index.droplevel('time'))
            toplabels[hemi] = topl
            
            alllabels = mne.read_labels_from_annot(
                    'fsaverage', parc=parc, hemi=hemi)
            
            brain.remove_labels()
            for label in alllabels:
                if label.name in topl:
                    brain.add_label(label, borders=1, hemi=hemi, alpha=0.8, 
                                    color='k')
        
        # increase font size of colorbar - this only works by increasing the 
        # colorbar itself and setting the ratio of colorbar to text
        brain.data['colorbar'].scalar_bar.bar_ratio = 0.35
        brain.data['colorbar'].scalar_bar_representation.position = [0.075, 0.01]
        brain.data['colorbar'].scalar_bar_representation.position2 = [0.85, 0.12]
        
        filepat = os.path.join(figdir, filepat_base + '_{}.png'.format(hemi))
        
        brain.save_montage(filepat, views[hemi], colorbar=0)
        
        brain.close()
        
    infiles = [
            os.path.join(figdir, filepat_base + '_{}.png'.format(hemi))
            for hemi in ['lh', 'rh']]
    outfile = os.path.join(figdir, filepat_base + '.png')
    os.system("montage -tile 2x1 -geometry +0+0 {} {}".format(
            ' '.join(infiles), outfile))
    
    return toplabels
Esempio n. 25
0
def curvature_normalization(data_dir, subj, close=True):
    """Normalize the curvature map and plot contour over fsaverage."""
    surf_dir = op.join(data_dir, subj, "surf")
    snap_dir = op.join(data_dir, subj, "snapshots")
    for hemi in ["lh", "rh"]:

        cmd = ["mri_surf2surf",
               "--srcsubject", subj,
               "--trgsubject", "fsaverage",
               "--hemi", hemi,
               "--sval", op.join(surf_dir, "%s.curv" % hemi),
               "--tval", op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi)]

        sub.check_output(cmd)

        b = Brain("fsaverage", hemi, "inflated",
                  config_opts=dict(background="white",
                                   width=700, height=500))
        curv = nib.load(op.join(surf_dir, "%s.curv.fsaverage.mgz" % hemi))
        curv = (curv.get_data() > 0).squeeze()
        b.add_contour_overlay(curv, min=0, max=1.5, n_contours=2, line_width=4)
        b.contour["colorbar"].visible = False
        for view in ["lat", "med"]:
            b.show_view(view)
            mlab.view(distance=330)
            png = op.join(snap_dir, "%s.surf_warp_%s.png" % (hemi, view))
            b.save_image(png)

        if close:
            b.close()
def plot_group(hub,num_nodes,hemi='lh'):
    from surfer import Brain, io
    brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white"))
    if hub == 'pc' or hub =='wmd':
        image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_%s.nii'%(num_nodes,hub),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20)
        brain.add_data(image,colormap = "Reds", colorbar= True)
    else:
        pc_image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_pc.nii'%(num_nodes),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20)
        wmd_image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/group_wmd.nii'%(num_nodes),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 20) 
        wmd_thresh = np.nanmean(wmd_image[wmd_image>0])
        pc_thresh = np.nanmean(pc_image[pc_image >0])
        #find connetor hub activity
        connector_hub_image = pc_image.copy()
        connector_hub_image[pc_image < pc_thresh] = 0.
        connector_hub_image[wmd_image < wmd_thresh] = 0.
        #find sattelite connector activty
        satellite_image = pc_image.copy()
        satellite_image[pc_image < pc_thresh] = 0.
        satellite_image[wmd_image > wmd_thresh] = 0.
        # find provincial hub activity
        provincial_hub_image = wmd_image.copy()
        provincial_hub_image[pc_image > pc_thresh] = 0.
        provincial_hub_image[wmd_image < wmd_thresh] = 0.

        node_image = pc_image.copy()
        node_image[provincial_hub_image > 0] = 0
        node_image[connector_hub_image > 0] = 0
        node_image[satellite_image > 0] = 0
        node_image[node_image > 0] = 1

        # brain.add_data(node_image,thresh= 0, max = 2, colormap = 'gray',hemi=hemi,smoothing_steps = 0)
        brain.add_data(connector_hub_image,thresh= np.nanmin(pc_image),max=pc_thresh + np.std(pc_image), colormap = 'Reds',hemi=hemi,smoothing_steps = 0)
        brain.add_data(satellite_image,thresh= np.nanmin(pc_image),max=pc_thresh + np.std(pc_image),colormap = 'autumn',hemi=hemi,smoothing_steps = 0)
        brain.add_data(provincial_hub_image,thresh=np.nanmin(wmd_image),max=wmd_thresh +np.std(wmd_image),colormap = 'Blues',hemi=hemi,smoothing_steps = 0)
Esempio n. 27
0
def test_annot():
    """Test plotting of annot."""
    mlab.options.backend = 'test'
    annots = ['aparc', 'aparc.a2005s']
    borders = [True, False, 2]
    alphas = [1, 0.5]
    brain = Brain(*std_args)
    for a, b, p in zip(annots, borders, alphas):
        brain.add_annotation(a, b, p)
    assert_raises(ValueError, brain.add_annotation, 'aparc', borders=-1)
    brain.close()
Esempio n. 28
0
def test_contour():
    """Test plotting of contour overlay
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    overlay_file = pjoin(data_dir, "lh.sig.nii.gz")
    brain.add_contour_overlay(overlay_file)
    brain.add_contour_overlay(overlay_file, max=20, n_contours=9,
                              line_width=2)
    brain.contour['surface'].actor.property.line_width = 1
    brain.contour['surface'].contour.number_of_contours = 10
Esempio n. 29
0
def test_animate(tmpdir):
    """Test animation."""
    _set_backend('auto')
    brain = Brain(*std_args, size=100)
    brain.add_morphometry('curv')
    tmp_name = str(tmpdir.join('test.avi'))
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    pytest.raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
Esempio n. 30
0
def test_animate():
    """Test animation."""
    _set_backend('auto')
    brain = Brain(*std_args, size=100)
    brain.add_morphometry('curv')
    tmp_name = mktemp() + '.avi'
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    assert_raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
Esempio n. 31
0
def test_data():
    """Test plotting of data."""
    _set_backend()
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
    brain.set_surf('white')
    brain.add_data([], vertices=np.array([], int))
    brain.close()
Esempio n. 32
0
def test_morphometry():
    """Test plotting of morphometry."""
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    brain.add_morphometry("curv")
    brain.add_morphometry("sulc", grayscale=True)
    brain.add_morphometry("thickness")
    brain.close()
Esempio n. 33
0
def test_morphometry():
    """Test plotting of morphometry."""
    _set_backend()
    brain = Brain(*std_args)
    brain.add_morphometry("curv")
    brain.add_morphometry("sulc", grayscale=True)
    brain.add_morphometry("thickness")
    brain.close()
Esempio n. 34
0
def get_hemi_data(subject, hemi, source, surf_name="pial", name=None, sign="abs", min=None, max=None):
    brain = Brain(subject, hemi, surf_name, curv=False, offscreen=True)
    print("Brain {} verts: {}".format(hemi, brain.geo[hemi].coords.shape[0]))
    hemi = brain._check_hemi(hemi)
    # load data here
    scalar_data, name = brain._read_scalar_data(source, hemi, name=name)
    print("fMRI constrast map vertices: {}".format(len(scalar_data)))
    min, max = brain._get_display_range(scalar_data, min, max, sign)
    if sign not in ["abs", "pos", "neg"]:
        raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
    old = viz.OverlayData(scalar_data, brain.geo[hemi], min, max, sign)
    return old, brain
Esempio n. 35
0
def test_animate():
    """Test animation
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, config_opts=small_brain)
    brain.add_morphometry('curv')
    tmp_name = mktemp() + '.avi'
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    assert_raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
def visualise_surface(zstat,
                      hemi,
                      surface='inflated',
                      min_val=None,
                      max_val=None,
                      thr_val=0,
                      cmap='autumn'):
    '''
    VERY helpfully taken from the Pysurfer example gallery
    http://pysurfer.github.io/examples/plot_fmri_activation_volume.html
    
    Parameters
    ----------
    zstat   : pysurfer surface
                Surface projection of result_file to fsaverage
                brain
    prefix  : save
    hemi    : {'lh', 'rh'}
                string indicating left or right hemisphere
    surface : {'inflated', 'pial', 'white'}    
                string indicating surface view
    min_val : minimum value to be shown 
                (default is to calculate it from the data)
    max_val : maximum value to be shown
                (default is to calculate it from the data)
    thr_val : threshold value
                zero everything below this number
                (default is 0)        
    cmap    : matplotlib colormap
                (default is autumn)
                
    Returns
    ----------
    brain   : current pysurfer visualization window
    '''
    """
    Bring up the visualization window.
    """
    brain = Brain("fsaverage",
                  hemi,
                  surface,
                  config_opts={'background': 'white'})
    """
    Add zstat as an overlay
    """
    brain.add_data(zstat,
                   min=min_val,
                   max=max_val,
                   thresh=thr_val,
                   colormap=cmap,
                   colorbar=True)

    return brain
Esempio n. 37
0
def get_hemi_data(subject, hemi, source, surf_name='pial', name=None, sign="abs", min=None, max=None):
    brain = Brain(subject, hemi, surf_name, curv=False, offscreen=True)
    print('Brain {} verts: {}'.format(hemi, brain.geo[hemi].coords.shape[0]))
    hemi = brain._check_hemi(hemi)
    # load data here
    scalar_data, name = brain._read_scalar_data(source, hemi, name=name)
    print('fMRI constrast map vertices: {}'.format(len(scalar_data)))
    min, max = brain._get_display_range(scalar_data, min, max, sign)
    if sign not in ["abs", "pos", "neg"]:
        raise ValueError("Overlay sign must be 'abs', 'pos', or 'neg'")
    old = viz.OverlayData(scalar_data, brain.geo[hemi], min, max, sign)
    return old, brain
Esempio n. 38
0
def corr_image(resting_image,fwhm):
    """This function makes correlation image on brain surface"""
    import numpy as np
    import nibabel as nb
    import matplotlib.pyplot as plt
    from surfer import Brain, Surface
    import os

    img = nb.load(resting_image)
    corrmat = np.corrcoef(np.squeeze(img.get_data()))
    corrmat[np.isnan(corrmat)] = 0
    corrmat_npz = os.path.abspath('corrmat.npz')
    np.savez(corrmat_npz,corrmat=corrmat)

    br = Brain('fsaverage5', 'lh', 'smoothwm')

    #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True)
    lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot')
    values = nb.freesurfer.read_annot(lh_aparc_annot_file)

    #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True)


    data = img.get_data()

    data = np.squeeze(img.get_data())

    #
    precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0)
    precuneus = np.corrcoef(precuneus_signal, data)
    #precuneus.shape

    #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True)

    br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    plt.hist(precuneus[0,1:], 128)
    plt.savefig(os.path.abspath("histogram.png"))
    plt.close()

    corr_image = os.path.abspath("corr_image%s.png"%fwhm)
    br.save_montage(corr_image)
    ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral'])
    br.close()
    print ims
    #precuneus[np.isnan(precuneus)] = 0
    #plt.hist(precuneus[0,1:])

    roitable = [['Region','Mean Correlation']]
    for i, roi in enumerate(np.unique(values[2])):
        roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])])

        #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable]
    roitable=[roitable]
    histogram = os.path.abspath("histogram.png")

    return corr_image, ims, roitable, histogram, corrmat_npz
Esempio n. 39
0
def test_image():
    """Test image saving
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, config_opts=small_brain)
    tmp_name = mktemp() + '.png'
    brain.save_image(tmp_name)
    brain.save_imageset(tmp_name, ['med', 'lat'], 'jpg')
    brain.save_montage(tmp_name, ['l', 'v', 'm'], orientation='v')
    brain.screenshot()
Esempio n. 40
0
def visMontage(pathToSurface, overlay, outputPath, hemi, type='white'):
    brain = Brain(pathToSurface, hemi, type)
    brain.add_overlay(overlay, -5, 3)
    brain.save_montage(outputPath, ['l', 'm'], orientation='v')
    brain.close()

    return outputPath
Esempio n. 41
0
def plot_ctx():
# Visualize the left or right hemisphere activation map per run with Yeo 2011 overlay of functional connectivity maps
# State path to statistical mask files generated by freesurfer processes
    path = "/home/lauri/Documents/temp/"
    statpath = os.listdir(path)
    statfile = []
    hemispheres = ['lh','rh']
# Creates a function to grab all cortical statistical files 
    for h in hemispheres:
        for s in statpath:
            if s.startswith(h) and s.endswith("gz"):
                statfile.append(s)
    print('Making images for:')
    statfile.sort()
    print(statfile)
# Create the image using pysurfer with backend function initialized
    for h in hemispheres:
        for f in statfile:
            sig = os.path.join(path,f)
            sub = "fsaverage"
            hemi = h
            surf = "inflated"
            view_types = ['lat','med']
            brain = Brain(sub, hemi, surf, cortex=None, background="midnightblue", views=view_types)
            overlay_file = sig
            brain.add_overlay(sig, min=1, max=3, name="ovrlay")
# To change colour of activations: note replace pos or neg: brain.overlays["ovrlay"].neg_bar.lut_mode = "winter"
            subjects_dir = os.environ["SUBJECTS_DIR"]
            annot_path = os.path.join(subjects_dir, sub, "label", "lh.Yeo2011_7Networks_N1000.annot")
            brain.add_annotation(annot_path, hemi=h, borders=False, alpha=.33)
            brain.save_image(os.path.join(path,f + ".jpeg"))
Esempio n. 42
0
def plot_y_pred_true_parcels(subject_name,
                             labels_pred,
                             labels_true,
                             colors={
                                 'pred': 'y',
                                 'true': 'b',
                                 'overlap': 'g'
                             }):
    # fig_name = (subject_name + '_' + str(len(parcels_subject)) + '_' +
    #            str(n_parcels_max))
    # TODO: make the switch automatic depending on who/where it runs
    data_path = 'mne_data/MNE-sample-data'  # Maja
    # mne_dir = mne.get_config('MNE_DATASETS_SAMPLE_PATH')  # Alex
    # data_path = mne_dir + '/MNE-sample-data'
    subjects_dir = os.path.join(data_path, 'subjects')
    hemi = 'both'
    brain = Brain(subject_name,
                  hemi,
                  'inflated',
                  subjects_dir=subjects_dir,
                  cortex='low_contrast',
                  background='white')

    for parcel in labels_pred:
        brain.add_label(parcel, alpha=1, color=colors['pred'])
    for parcel in labels_true:
        brain.add_label(parcel, alpha=1, color=colors['true'])
    for parcel in set(labels_pred) & set(labels_true):
        brain.add_label(parcel, alpha=1, color=colors['overlap'])
    import pdb
    pdb.set_trace()
Esempio n. 43
0
def plot_distance(subject, data_dir, parcels, parcel_name='1-lh'):
    print('displaying brain of subject {}, distances from label {}'.format(
        subject, parcel_name))
    data_path = 'mne_data/MNE-sample-data'  # Maja
    subjects_dir = os.path.join(data_path, 'subjects')

    hemi = 'both'
    brain = Brain(subject,
                  hemi,
                  'inflated',
                  subjects_dir=subjects_dir,
                  cortex='low_contrast',
                  background='white')

    dist_path_lh = os.path.join(data_dir, subject + '_dist_matrix_lh.csv')
    dist_matrix_lh = pd.read_csv(dist_path_lh, index_col=0)
    dist_matrix_lh_norm = dist_matrix_lh.divide(dist_matrix_lh.max().max())

    if 'lh' in parcel_name:
        hemi = 'lh'
    elif 'rh' in parcel_name:
        hemi = 'rh'
    for parcel in parcels:
        if parcel_name == parcel.name:
            brain.add_label(parcel, alpha=1, color='blue')
        elif hemi in parcel.name:
            dist = dist_matrix_lh_norm.loc[parcel_name][parcel.name]
            brain.add_label(parcel, alpha=1, color=str(1 - dist))
    import pdb
    pdb.set_trace()
    cm = parcel.center_of_mass(subject, subjects_dir=subjects_dir)

    brain.add_foci(cm, coords_as_verts=True, hemi='lh', color='blue')
Esempio n. 44
0
def montage_plot(parameter, in_dir, task, fdr_correct=True, hemi='lh', input_hemisphere='', annot=None):
    '''
    Make plots for parameter on the cortical surface using pysurf module

    - Arguments:
        a) parameter
        b) output directory
        c) task (inference or instructed)
        d) FDR correction (boolean)
    '''
    out_dir = join(in_dir, 'pysurf_plots')
    slu.mkdir_p(out_dir)
    fsaverage = "fsaverage"
    surf = "inflated"
    t_data, p_data, str_names, labels = get_data(task, in_dir, input_hemisphere, hemi)
    if fdr_correct is True:
        data = fdr_filter(t_data, p_data, parameter)
    else:
        data = t_data[parameter].values
    data = data[labels]
    brain = Brain(fsaverage, hemi, surf,
                  background="white", title=parameter + task)
    brain.add_data(data, -10, 10, thresh=None, colormap="RdBu_r", alpha=.8)
    if annot is not None:
        brain.add_annotation(annot, color='white', alpha=1)
    brain.save_imageset(join(out_dir, parameter + '_' + task + input_hemisphere),
                        ['lateral', 'medial', 'par'], colorbar=None)
Esempio n. 45
0
def test_animate():
    """Test animation."""
    _set_backend('auto')
    brain = Brain(*std_args, size=100)
    brain.add_morphometry('curv')
    tmp_name = mktemp() + '.avi'
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    assert_raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
Esempio n. 46
0
def test_data():
    """Test plotting of data."""
    _set_backend()
    brain = Brain(*std_args)
    mri_file = pjoin(data_dir, 'resting_corr.nii.gz')
    reg_file = pjoin(data_dir, 'register.dat')
    surf_data = io.project_volume_data(mri_file, "lh", reg_file)
    brain.add_data(surf_data, -.7, .7, colormap="jet", alpha=.7)
    brain.set_surf('white')
    brain.add_data([], vertices=np.array([], int))
    brain.close()
Esempio n. 47
0
def test_animate(tmpdir):
    """Test animation."""
    _set_backend('auto')
    brain = Brain(*std_args, size=100)
    brain.add_morphometry('curv')
    tmp_name = str(tmpdir.join('test.avi'))
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    pytest.raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
Esempio n. 48
0
def load_fmri(subject, input_file, hemi='both'):
    brain = Brain(subject, hemi, "pial", curv=False)
    brain.toggle_toolbars(True)
    if hemi == 'both':
        for hemi in ['rh', 'lh']:
            brain.add_overlay(input_file.format(hemi), hemi=hemi)
    else:
        brain.add_overlay(input_file.format(hemi), hemi=hemi)
Esempio n. 49
0
def montage_plot(parameter, fdr_correct=True):
    fsaverage = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    t_data, p_data, str_names, labels = get_data()
    if fdr_correct is True:
        data = fdr_filter(t_data, p_data, parameter)
    else:
        data = t_data[parameter].values
    data = data[labels]
    brain = Brain(fsaverage, hemi, surf, background="white")
    brain.add_data(data, -10, 10, thresh=None, colormap="RdBu_r", alpha=.8)
    montage = brain.save_montage(
        None, [['lateral', 'parietal'], ['medial', 'frontal']],
        border_size=0,
        colorbar=None)
    fig, a = plt.subplots(figsize=(24, 24))
    im = plt.imshow(montage, cmap='RdBu_r')
    a.set(xticks=[], yticks=[])
    sns.despine(bottom=True, left=True)
    cbar = fig.colorbar(im,
                        ticks=[montage.min(), (montage.min() + 255) / 2, 255],
                        orientation='horizontal',
                        drawedges=False)
    cbar.ax.set_xticklabels(['-10', '0', '10'])
    plt.rcParams['pdf.fonttype'] = 3
    plt.rcParams['ps.fonttype'] = 3
    sns.set(style='ticks',
            font_scale=1,
            rc={
                'axes.labelsize': 6,
                'axes.titlesize': 40,
                'xtick.labelsize': 40,
                'ytick.labelsize': 5,
                'legend.fontsize': 250,
                'axes.linewidth': 0.25,
                'xtick.major.width': 0.25,
                'ytick.major.width': 0.25,
                'ytick.major.width': 0.25,
                'ytick.major.width': 0.25,
                'ytick.major.pad': 2.0,
                'ytick.minor.pad': 2.0,
                'xtick.major.pad': 2.0,
                'xtick.minor.pad': 2.0,
                'axes.labelpad': 4.0,
            })
    a.set_title(parameter)
    return fig
Esempio n. 50
0
def curvature_normalization(data_dir, subj):
    """Normalize the curvature map and plot contour over fsaverage."""
    surf_dir = op.join(data_dir, subj, "surf")
    snap_dir = op.join(data_dir, subj, "snapshots")
    panels = []
    for hemi in ["lh", "rh"]:

        # Load the curv values and apply registration to fsaverage
        curv_fname = op.join(surf_dir, "{}.curv".format(hemi))
        curv_vals = nib.freesurfer.read_morph_data(curv_fname)
        subj_curv_vals = apply_surface_warp(data_dir, subj,
                                            hemi, curv_vals)
        subj_curv_binary = (subj_curv_vals > 0)

        # Load the template curvature
        norm_fname = op.join(data_dir, "fsaverage", "surf",
                             "{}.curv".format(hemi))
        norm_curv_vals = nib.freesurfer.read_morph_data(norm_fname)
        norm_curv_binary = (norm_curv_vals > 0)

        # Compute the curvature overlap image
        curv_overlap = np.zeros_like(norm_curv_binary, np.int)
        curv_overlap[norm_curv_binary & subj_curv_binary] = 1
        curv_overlap[norm_curv_binary ^ subj_curv_binary] = 2

        # Mask out the medial wall
        cortex_fname = op.join(data_dir, "fsaverage", "label",
                               "{}.cortex.label".format(hemi))
        cortex = nib.freesurfer.read_label(cortex_fname)
        medial_wall = ~np.in1d(np.arange(curv_overlap.size), cortex)
        curv_overlap[medial_wall] = 1

        # Plot the curvature overlap image
        try:
            b = Brain("fsaverage", hemi, "inflated", background="white")
        except TypeError:
            # PySurfer <= 0.5
            b = Brain("fsaverage", hemi, "inflated",
                      config_opts=dict(background="white"))

        b.add_data(curv_overlap, min=0, max=2,
                   colormap=[".9", ".45", "indianred"], colorbar=False)

        for view in ["lat", "med", "ven"]:
            b.show_view(view, distance="auto")
            panels.append(crop(b.screenshot()))
        b.close()

    # Make and save a figure
    f = multi_panel_brain_figure(panels)
    fname = op.join(snap_dir, "surface_registration.png")
    f.savefig(fname, bbox_inches="tight")
    plt.close(f)
Esempio n. 51
0
def test_animate():
    """Test animation
    """
    mlab.options.backend = 'auto'
    brain = Brain(*std_args, config_opts=small_brain)
    brain.add_morphometry('curv')
    tmp_name = mktemp() + '.avi'
    brain.animate(["m"] * 3, n_steps=2)
    brain.animate(['l', 'l'], n_steps=2, fname=tmp_name)
    # can't rotate in axial plane
    assert_raises(ValueError, brain.animate, ['l', 'd'])
    brain.close()
Esempio n. 52
0
def display_matrices(filenames, target, hemi, surface):
    from mayavi import mlab
    from surfer import Brain
    print '\n'.join(filenames)
    for name in filenames:
        try:
            corrmat = sio.loadmat(name)['corrmat']
        except:
            try:
                corrmat = np.load(name)['corrmat']
            except:
                try:
                    corrmat = np.load(name)['arr_0']
                except:
                    try:
                        corrmat = np.load(name)['avgcorr']
                    except:
                        h5file = openFile(name, 'r')
                        corrmat = h5file.root.corrmat
        corrmats.append(corrmat)
    for idx, name in enumerate(filenames):
        path, name = os.path.split(name)
        br = Brain(target, hemi, surface, title=name + '-%d' % idx)
        brains.append(br)
        for brain in brains[:-1]:
            mlab.sync_camera(br._f, brain._f)
            mlab.sync_camera(brain._f, br._f)
        br._f.on_mouse_pick(picker_callback)
    mlab.show()
Esempio n. 53
0
def translate_electrodes_onto_the_brain_surface(subject_name, subjects_dir,
                                                elec_sorted):
    #find brain surface points
    brain = Brain(subject_id=subject_name,
                  subjects_dir=subjects_dir,
                  surf='pial',
                  hemi='lh',
                  offscreen=True)
    surf = brain.geo['lh']
    src = np.array([surf.x, surf.y, surf.z]).T
    #use ConvexHull to chek if a point is inside the brain or not
    elec_up = np.zeros([64, 3])
    hull = ConvexHull(src)
    for i, e in enumerate(elec_sorted):
        a = 1
        n = deepcopy(e)
        while a == 1:
            new_hull = ConvexHull(np.concatenate((hull.points, [e])))
            if np.array_equal(new_hull.vertices, hull.vertices):
                a = 1
                e += n * 0.01
            else:
                a = 0
        elec_up[i] = e
    return elec_up
Esempio n. 54
0
def corr_image(resting_image,fwhm):
    """This function makes correlation image on brain surface"""
    import numpy as np
    import nibabel as nb
    import matplotlib.pyplot as plt
    from surfer import Brain, Surface
    import os

    img = nb.load(resting_image)
    corrmat = np.corrcoef(np.squeeze(img.get_data()))
    corrmat[np.isnan(corrmat)] = 0
    corrmat_npz = os.path.abspath('corrmat.npz')
    np.savez(corrmat_npz,corrmat=corrmat)

    br = Brain('fsaverage5', 'lh', 'smoothwm')

    #br.add_overlay(corrmat[0,:], min=0.2, name=0, visible=True)
    lh_aparc_annot_file = os.path.join(os.environ["FREESURFER_HOME"],'/subjects/label/lh.aparc.annot')
    values = nb.freesurfer.read_annot(lh_aparc_annot_file)

    #br.add_overlay(np.mean(corrmat[values[0]==5,:], axis=0), min=0.8, name='mean', visible=True)


    data = img.get_data()

    data = np.squeeze(img.get_data())

    #
    precuneus_signal = np.mean(data[values[0]==np.nonzero(np.array(values[2])=='precuneus')[0][0],:], axis=0)
    precuneus = np.corrcoef(precuneus_signal, data)
    #precuneus.shape

    #br.add_overlay(precuneus[0,1:], min=0.3, sign='pos', name='mean', visible=True)

    br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    #br.add_overlay(precuneus[0,1:], min=0.2, name='mean')#, visible=True)
    plt.hist(precuneus[0,1:], 128)
    plt.savefig(os.path.abspath("histogram.png"))
    plt.close()

    corr_image = os.path.abspath("corr_image%s.png"%fwhm)
    br.save_montage(corr_image)
    ims = br.save_imageset(prefix=os.path.abspath('fwhm_%s'%str(fwhm)),views=['medial','lateral','caudal','rostral','dorsal','ventral'])
    br.close()
    print ims
    #precuneus[np.isnan(precuneus)] = 0
    #plt.hist(precuneus[0,1:])

    roitable = [['Region','Mean Correlation']]
    for i, roi in enumerate(np.unique(values[2])):
        roitable.append([roi,np.mean(precuneus[values[0]==np.nonzero(np.array(values[2])==roi)[0][0]])])

        #images = [corr_fimage]+ims+[os.path.abspath("histogram.png"), roitable]
    roitable=[roitable]
    histogram = os.path.abspath("histogram.png")

    return corr_image, ims, roitable, histogram, corrmat_npz
Esempio n. 55
0
def make_pysurfer_images_lh_rh(folder,suffix='cope1',hemi='lh',threshold=0.9499,coords=(),surface='inflated',fwhm=0,filename='',saveFolder=[],vmax=5.0,bsize=5):
    from surfer import Brain, io
    TFCEposImg,posImg,TFCEnegImg,negImg=getFileNamesfromFolder(folder,suffix)

    pos=image.math_img("np.multiply(img1,img2)",
                         img1=image.threshold_img(TFCEposImg,threshold=threshold),img2=posImg)
    neg=image.math_img("np.multiply(img1,img2)",
                         img1=image.threshold_img(TFCEnegImg,threshold=threshold),img2=negImg)
    fw=image.math_img("img1-img2",img1=pos,img2=neg)

    if fwhm==0:
        smin=np.min(np.abs(fw.get_data()[fw.get_data()!=0]))
    else:
        smin=2

    mri_file = "%s/thresholded_posneg.nii.gz" % folder
    fw.to_filename(mri_file)

    """Bring up the visualization"""
    brain = Brain("fsaverage",hemi,surface, offscreen=True , background="white")

    """Project the volume file and return as an array"""

    reg_file = os.path.join("/opt/freesurfer","average/mni152.register.dat")
    surf_data = io.project_volume_data(mri_file, hemi, reg_file,smooth_fwhm=fwhm)
    #  surf_data_rh = io.project_volume_data(mri_file, "rh", reg_file,smooth_fwhm=fwhm)


    """
    You can pass this array to the add_overlay method for a typical activation
    overlay (with thresholding, etc.).
    """
    brain.add_overlay(surf_data, min=smin, max=vmax, name="activation", hemi=hemi)
    # brain.overlays["activation"]
    # brain.add_overlay(surf_data_rh, min=smin, max=5, name="ang_corr_rh", hemi='rh')

    if len(coords)>0:
        if coords[0]>0:
            hemi2='rh'
        else:
            hemi2='lh'
        brain.add_foci(coords, map_surface="pial", color="gold",hemi=hemi2)

    if len(saveFolder)>0:
        folder=saveFolder
        image_out=brain.save_montage('%s/%s-%s.png' % (folder,hemi,filename),order=['l','m'],orientation='h',border_size=bsize,colorbar=None)

    else:
        image_out=brain.save_image('%s/surfaceplot.jpg' % folder)
    brain.close()
    return image_out
Esempio n. 56
0
def test_foci():
    """Test plotting of foci
    """
    mlab.options.backend = 'test'
    brain = Brain(*std_args)
    coords = [[-36, 18, -3],
          [-43, 25, 24],
          [-48, 26, -2]]
    brain.add_foci(coords, map_surface="white", color="gold")

    annot_path = pjoin(subj_dir, subject_id, 'label', 'lh.aparc.a2009s.annot')
    ids, ctab, names = nib.freesurfer.read_annot(annot_path)
    verts = np.arange(0, len(ids))
    coords = np.random.permutation(verts[ids == 74])[:10]
    scale_factor = 0.7
    brain.add_foci(coords, coords_as_verts=True,
                   scale_factor=scale_factor, color="#A52A2A")
def plot_surface(vtx_data, subject_id, subjects_dir, hemi, surface, output_dir, prefix, l, u, cmap, center, thresh):
    # Open up a brain in pysurfer
    brain = Brain(
        subject_id,
        hemi,
        surface,
        subjects_dir=subjects_dir,
        config_opts=dict(background="white", height=665, width=800),
    )

    if center:
        # Make sure the colorbar is centered
        if l ** 2 < u ** 2:
            l = u * -1
        else:
            u = l * -1

    # Create an empty brain if the values are all below threshold
    if np.max(vtx_data) < thresh:
        # Add your data to the brain
        brain.add_data(vtx_data * 0, l, u, thresh=thresh, colormap=cmap, alpha=0.0)

    # Otherwise, add the data appropriately!
    else:
        # Add your data to the brain
        brain.add_data(vtx_data, l, u, thresh=thresh, colormap=cmap, alpha=0.8)

    # Save the images for medial and lateral
    # putting a color bar on all of them
    brain.save_imageset(prefix=os.path.join(output_dir, prefix), views=views_list, colorbar=range(len(views_list)))
def plot_parcel(num_nodes=600,numbers=[1],hemi='lh'):
    from surfer import Brain, io
    for n in numbers:
        brain = Brain("fsaverage", "%s" %(hemi), "pial",config_opts=dict(background="white"))
        image = io.project_volume_data('/home/despo/mb3152/random_nodes/%s/parcel_%s.nii'%(num_nodes,n),hemi, subject_id="fsaverage", projsum = 'max', smooth_fwhm = 0)
        brain.add_data(image,thresh=1,colormap = "spectral")
        brain.save_imageset('/home/despo/mb3152/random_nodes/%s/parcel_%s' %(num_nodes,n),['med','lat'],'jpg',colorbar= None)
        brain.close()
Esempio n. 59
0
def inflated_surfaces(out_dir, subj, close=True):
    """Native inflated surfaces with cortical label."""
    for hemi in ["lh", "rh"]:
        b = Brain(subj, hemi, "inflated", curv=False,
                  config_opts=dict(background="white",
                                   width=800, height=500))
        b.add_label("cortex", color="#6B6B6B")

        for view in ["lat", "med"]:
            b.show_view(view)
            mlab.view(distance=400)
            png = op.join(out_dir, "%s.surface_%s.png" % (hemi, view))
            b.save_image(png)
        if close:
            b.close()