Esempio n. 1
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    view = get_view(brain)

    extra, subj_dir = _get_extra()
    brain.add_label("BA1" + extra)
    check_view(brain, view)
    brain.add_label("BA1" + extra, color="blue", scalar_thresh=.5)
    label_file = pjoin(subj_dir, subject_id, "label",
                       "%s.MT%s.label" % (hemi, extra))
    brain.add_label(label_file)
    brain.add_label("BA44" + extra, borders=True)
    brain.add_label("BA6" + extra, alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1" + extra, color="steelblue", alpha=.6)
    brain.add_label("V2" + extra, color="#FF6347", alpha=.6)
    brain.add_label("entorhinal" + extra, color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')
    brain.show_view(dict(elevation=40, distance=430), distance=430)
    with pytest.raises(ValueError, match='!='):
        brain.show_view(dict(elevation=40, distance=430), distance=431)

    # remove labels
    brain.remove_labels('V1' + extra)
    assert 'V2' + extra in brain.labels_dict
    assert 'V1' + extra not in brain.labels_dict
    brain.remove_labels()
    assert 'V2' + extra not in brain.labels_dict

    brain.close()
Esempio n. 2
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    brain.add_label("BA1")
    brain.add_label("BA1", color="blue", scalar_thresh=.5)
    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, subject_id, "label", "%s.MT.label" % hemi)
    brain.add_label(label_file)
    brain.add_label("BA44", borders=True)
    brain.add_label("BA6", alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1", color="steelblue", alpha=.6)
    brain.add_label("V2", color="#FF6347", alpha=.6)
    brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')

    # remove labels
    brain.remove_labels('V1')
    assert_in('V2', brain.labels_dict)
    assert_not_in('V1', brain.labels_dict)
    brain.remove_labels()
    assert_not_in('V2', brain.labels_dict)

    brain.close()
Esempio n. 3
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    brain.add_label("BA1")
    brain.add_label("BA1", color="blue", scalar_thresh=.5)
    subj_dir = utils._get_subjects_dir()
    label_file = pjoin(subj_dir, subject_id,
                       "label", "%s.MT.label" % hemi)
    brain.add_label(label_file)
    brain.add_label("BA44", borders=True)
    brain.add_label("BA6", alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1", color="steelblue", alpha=.6)
    brain.add_label("V2", color="#FF6347", alpha=.6)
    brain.add_label("entorhinal", color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')

    # remove labels
    brain.remove_labels('V1')
    assert_in('V2', brain.labels_dict)
    assert_not_in('V1', brain.labels_dict)
    brain.remove_labels()
    assert_not_in('V2', brain.labels_dict)

    brain.close()
Esempio n. 4
0
def test_label():
    """Test plotting of label."""
    _set_backend()
    subject_id = "fsaverage"
    hemi = "lh"
    surf = "inflated"
    brain = Brain(subject_id, hemi, surf)
    view = get_view(brain)

    extra, subj_dir = _get_extra()
    brain.add_label("BA1" + extra)
    check_view(brain, view)
    brain.add_label("BA1" + extra, color="blue", scalar_thresh=.5)
    label_file = pjoin(subj_dir, subject_id,
                       "label", "%s.MT%s.label" % (hemi, extra))
    brain.add_label(label_file)
    brain.add_label("BA44" + extra, borders=True)
    brain.add_label("BA6" + extra, alpha=.7)
    brain.show_view("medial")
    brain.add_label("V1" + extra, color="steelblue", alpha=.6)
    brain.add_label("V2" + extra, color="#FF6347", alpha=.6)
    brain.add_label("entorhinal" + extra, color=(.2, 1, .5), alpha=.6)
    brain.set_surf('white')
    brain.show_view(dict(elevation=40, distance=430), distance=430)
    with pytest.raises(ValueError, match='!='):
        brain.show_view(dict(elevation=40, distance=430), distance=431)

    # remove labels
    brain.remove_labels('V1' + extra)
    assert 'V2' + extra in brain.labels_dict
    assert 'V1' + extra not in brain.labels_dict
    brain.remove_labels()
    assert 'V2' + extra not in brain.labels_dict

    brain.close()
Esempio n. 5
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. 6
0
def save_groups_labels_figures():
    labels, groups = get_groups()
    for group in groups:
        print(group)
        if len(get_group_labels(group)) < 4:
            group_label = [l for l in labels if group in l]
            colors = get_spaced_colors(len(group_label))
        brain = Brain(subject, hemi, surf, offscreen=False)
        for label_id, label in enumerate(group_label):
            print(label)
            brain.add_label(label, color=colors[label_id])
        fol = os.path.join(subjects_dir, subject, 'label', '{}_figures'.format(aparc_name))
        if not os.path.isdir(fol):
            os.mkdir(fol)
        brain.save_imageset(os.path.join(fol, group), get_views(), 'jpg')
        brain.remove_labels()
        brain.close()
Esempio n. 7
0
    def show_labels(srcfile,
                    measure,
                    brain=None,
                    r_name=None,
                    src_df=None,
                    transform=None,
                    surface='white',
                    time=0.17,
                    labels=None):
        parc = re.match('source_(\w+)_allsubs_\d+_slabs_\w+.h5',
                        srcfile).group(1)
        if labels is None:
            labels = mne.read_labels_from_annot('fsaverage',
                                                parc=parc,
                                                hemi='both')
            labels = {l.name: l for l in labels}

        file = os.path.join(bem_dir, srcfile)

        if srcfile.find('_slabs_') >= 0:
            slabsi = file.find('slabs_')
            r_n = file[slabsi + 6:-3]
            if r_name is None:
                r_name = r_n
            elif r_name != r_n:
                raise ValueError(
                    "Provided source file name and name of desired "
                    "regressor are not compatible!")

        if src_df is None:
            src_df = pd.read_hdf(file, 'second_level_src')

        if brain is None:
            brain = Brain('fsaverage',
                          'both',
                          surface,
                          cortex='low_contrast',
                          subjects_dir=subjects_dir)
        else:
            brain.remove_labels(hemi='rh')
            brain.remove_labels(hemi='lh')

        data = src_df.loc[(slice(None), time), measure]

        if transform is not None:
            data = transform(data)

        vmin = 0.9

        norm = matplotlib.colors.Normalize(vmin, 1, clip=True)
        alpha = matplotlib.colors.Normalize(vmin, (1 - vmin) / 2 + vmin,
                                            clip=True)

        data = data[data > vmin]

        cmap = matplotlib.cm.hot

        print(data)

        for index, value in data.iteritems():
            if index[0].startswith('L'):
                hemi = 'left'
            else:
                hemi = 'right'

            print(index[0])
            brain.add_label(labels[index[0]],
                            color=cmap(norm(value)),
                            alpha=alpha(value),
                            hemi=hemi)

        return brain
Esempio n. 8
0
surf = "pial"
subjects_dir = os.environ.get('SUBJECTS_DIR', '/home/noam/subjects/mri')

# x=range(15)
# cm = plt.get_cmap('jet')
# cNorm = matplotlib.colors.Normalize(vmin=min(x) vmax=max(x))
# return cmx.ScalarMappable(norm=cNorm, cmap=cm)


def get_spaced_colors(n):
    HSV_tuples = [(x * 1.0 / n, 0.5, 0.5) for x in range(n)]
    RGB_tuples = map(lambda x: colorsys.hsv_to_rgb(*x), HSV_tuples)
    return RGB_tuples


labels = glob.glob(
    os.path.join(subjects_dir, subject_id, 'label', 'aparc250',
                 '*{}.label'.format(hemi)))
groups = set([l.split('/')[-1].split('_')[0] for l in labels])
brain = Brain(subject_id, hemi, surf, offscreen=True)
for group in groups:
    group_label = [l for l in labels if group in l]
    colors = get_spaced_colors(len(group_label))
    for label_id, label in enumerate(group_label):
        print(label)
        brain.add_label(label, color=colors[label_id])
    brain.save_imageset('{}-{}'.format(subject_id, group),
                        ['med', 'lat', 'ros', 'caud'], 'jpg')
    break
brain.remove_labels()
print('sdf')
def brain_plot(brain,
               wname,
               toplabels=False,
               save=False,
               backface_culling=True):
    if r_name in ['dot_x', 'dot_y', 'dot_x_sign']:
        views = {
            'rh':
            ['medial',
             'parietal'],  #{'azimuth': -20, 'elevation': 62, 'roll': -68}], 
            'lh': ['parietal', 'medial']
        }
    elif r_name in ['sum_dot_x', 'response']:
        views = {'rh': ['medial', 'lateral'], 'lh': ['lateral', '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]

    if common_color_scale:
        cinfo = get_colorinfo(avsrcdf)
    else:
        cinfo = get_colorinfo(results[wname]['avsrcdf'])

    sv.show_labels_as_data(results[wname]['avsrcdf'],
                           show_measure,
                           brain,
                           time_label=None,
                           parc=parc,
                           **cinfo)

    if backface_culling:
        brain.data['surfaces'][0].actor.property.backface_culling = True

    if toplabels:
        brain.remove_labels()

        alllabels = mne.read_labels_from_annot('fsaverage',
                                               parc=parc,
                                               hemi=hemi)
        for label in alllabels:
            if label.name in results[wname]['toplabels'][hemi]:
                brain.add_label(label,
                                borders=1,
                                hemi=hemi,
                                alpha=0.8,
                                color='k')

        if backface_culling:
            for ldict in brain._label_dicts.values():
                ldict['surfaces'][0].actor.property.backface_culling = True

    # 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]

    if save:
        filepat = os.path.join(figdir,
                               filepat_base + '_{}_{}.png'.format(wname, hemi))

        brain.save_montage(filepat, views[hemi], colorbar=0)

    return brain