示例#1
0
    def get_objects_to_color(self, names, objects_indices):
        curves_num = 0
        for ind in range(min(self.topK, len(objects_indices))):
            orig_name = names[objects_indices[ind]]
            if 'unknown' not in orig_name:
                obj = bpy.data.objects.get(orig_name)
                if not obj is None and not obj.animation_data is None:
                    curves_num += len(obj.animation_data.action.fcurves)

        colors = cu.get_distinct_colors(curves_num)
        objects_names, objects_colors, objects_data = defaultdict(
            list), defaultdict(list), defaultdict(list)
        for ind in range(min(self.topK, len(objects_indices)) - 1, -1, -1):
            if bpy.data.objects.get(names[objects_indices[ind]]):
                orig_name = names[objects_indices[ind]]
                obj_type = mu.check_obj_type(orig_name)
                objects_names[obj_type].append(orig_name)
                objects_colors[obj_type].append(cu.name_to_rgb('green'))
                objects_data[obj_type].append(1.0)
                if 'unknown' not in orig_name:
                    filter_roi_func(orig_name)
                    for fcurve in bpy.data.objects[
                            orig_name].animation_data.action.fcurves:
                        fcurve.color_mode = 'CUSTOM'
                        fcurve.color = tuple(next(colors))
            else:
                print("Can't find {}!".format(names[objects_indices[ind]]))
        return objects_names, objects_colors, objects_data
示例#2
0
def plot_labels_probs(elc):
    _addon().init_activity_map_coloring('FMRI')
    if bpy.context.scene.electrodes_what_to_color == 'probs':
        if len(elc['cortical_rois']) > 0:
            hemi = mu.get_obj_hemi(elc['cortical_rois'][0])
            if not hemi is None:
                labels_data = dict(data=elc['cortical_probs'],
                                   names=elc['cortical_rois'])
                if not _addon().colorbar_values_are_locked():
                    _addon().set_colorbar_title('Electrodes probabilities')
                    _addon().set_colormap('YlOrRd')
                atlas = bpy.context.scene.electrodes_labeling_files.split(
                    '_')[1:-6][0]
                _addon().labels_coloring_hemi(labels_data,
                                              ElecsPanel.faces_verts,
                                              hemi,
                                              0,
                                              colors_min=0,
                                              colors_max=1,
                                              atlas=atlas)
                colors = mu.get_distinct_colors(len(elc['cortical_rois']))
                if bpy.context.scene.electrodes_label_contours:
                    _addon().color_contours(elc['cortical_rois'],
                                            specific_colors=colors)
            else:
                print("Can't get the rois hemi!")
        else:
            _addon().clear_cortex()
        _addon().clear_subcortical_regions()
        if len(elc['subcortical_rois']) > 0:
            cm = _addon().get_cm()
            colors = mu.calc_colors_from_cm(elc['subcortical_probs'], 0, 256,
                                            cm)
            for region, color in zip(elc['subcortical_rois'], colors):
                _addon().color_subcortical_region(region, color)

    elif bpy.context.scene.electrodes_what_to_color == 'verts':
        if len(elc['cortical_indices']) > 0:
            hemi = bpy.data.objects[elc['hemi']]
            if not hemi is None:
                _addon().init_activity_map_coloring('FMRI', subcorticals=True)
                vertices_num = np.max(elc['cortical_indices']) + 1
                activity = np.ones((vertices_num, 4))
                activity[:, 0] = 0
                activity[elc['cortical_indices'], 0] = 1
                activity[elc['cortical_indices'],
                         1:] = np.tile(cu.name_to_rgb('blue'),
                                       (len(elc['cortical_indices']), 1))
                print('Plot {} vertices with blue'.format(
                    len(elc['cortical_indices'])))
                _addon().activity_map_obj_coloring(
                    hemi, activity, ElecsPanel.faces_verts[elc['hemi']], 0,
                    True)
            else:
                print("Can't get the elec's hemi!")
        else:
            _addon().clear_cortex()
            print('No cortical vertices for {}'.format(elc['name']))
示例#3
0
def save_colorbar(min_val=None,
                  max_val=None,
                  color_map=None,
                  ticks_num=None,
                  ticks_font_size=None,
                  prec=None,
                  title=None,
                  background_color_name=None,
                  colorbar_name='',
                  fol=''):
    org_colorbar_min, org_colorbar_max = (get_colorbar_min(),
                                          get_colorbar_max())
    org_background_color = _addon().get_panels_background_color()
    if min_val is None:
        min_val = get_colorbar_min()
    if max_val is None:
        max_val = get_colorbar_max()
    if color_map is None:
        color_map = get_colormap_name()
    if ticks_num is None:
        ticks_num = get_colorbar_ticks_num()
    if ticks_font_size is None:
        ticks_font_size = get_cb_ticks_font_size()
    if prec is None:
        prec = get_colorbar_prec()
    if title is None:
        title = get_colorbar_title()
    if background_color_name is None:
        background_color_rgb = _addon().get_background_rgb_string()
    else:
        background_color_rgb = ','.join(
            [str(x) for x in cu.name_to_rgb(background_color_name)])
    if colorbar_name == '':
        colorbar_name = '{}_colorbar.jpg'.format(color_map)
    else:
        if not colorbar_name.endswith('.jpg'):
            colorbar_name = '{}.jpg'.format(colorbar_name)
    if fol == '' or not op.isdir(fol):
        fol = _addon().get_output_path()
    cb_ticks = ','.join(get_colorbar_ticks(ticks_num, prec, min_val, max_val))
    cb_ticks = cb_ticks.replace(
        '-', '*')  # Bug in argparse. todo: change the , to space
    flags = '--colorbar_name "{}" --data_max "{}" --data_min "{}" --colors_map {} --background_color {} '.format(
        colorbar_name, max_val, min_val, color_map, background_color_rgb) + \
        '--cb_title "{}" --cb_ticks "{}" --cb_ticks_font_size {} --fol "{}"'.format(
            title, cb_ticks, ticks_font_size, fol)
    mu.run_mmvt_func('src.utils.figures_utils', 'plot_color_bar', flags=flags)

    set_colorbar_max_min(org_colorbar_max, org_colorbar_min, force_update=True)
    _addon().set_panels_background_color(org_background_color)
示例#4
0
def filter_electrode_func(elec_name):
    elec_obj = bpy.data.objects[elec_name]
    if bpy.context.scene.mark_filter_items:
        FilteringMakerPanel.electrodes_colors[elec_name] = FilteringMakerPanel.addon.get_obj_color(elec_obj)
        FilteringMakerPanel.addon.object_coloring(elec_obj, cu.name_to_rgb('green'))
    else:
        elec_obj.active_material.node_tree.nodes["Layer Weight"].inputs[0].default_value = 0.3

    # todo: selecting the electrode will show both of their conditions time series
    # We don't want it to happen if selection_type == 'conds'...
    if bpy.context.scene.selection_type == 'conds' or bpy.context.scene.filter_items_one_by_one:
        bpy.data.objects[elec_name].select = True
    bpy.context.scene.objects.active = bpy.data.objects[elec_name]
    bpy.types.Scene.filter_is_on = True
示例#5
0
    def filter_rois(self, current_file_to_upload):
        print('filter_ROIs')
        _addon().show_rois()
        source_files = [
            op.join(self.current_activity_path,
                    current_file_to_upload.format(hemi=hemi))
            for hemi in mu.HEMIS
        ]
        objects_indices, names, self.filter_values = self.get_object_to_filter(
            source_files)
        Filtering.objects_indices, Filtering.filter_objects = objects_indices, names
        deselect_all_objects()

        if bpy.context.scene.selection_type == 'diff':
            filter_obj_names = [names[ind] for ind in objects_indices]
            brain_obj = bpy.data.objects['Brain']
            for fcurve in brain_obj.animation_data.action.fcurves:
                con_name = mu.get_fcurve_name(fcurve)
                fcurve.hide = con_name not in filter_obj_names
                fcurve.select = not fcurve.hide
            brain_obj.select = True

        curves_num = 0
        for ind in range(min(self.topK, len(objects_indices))):
            orig_name = names[objects_indices[ind]]
            if 'unknown' not in orig_name:
                obj = bpy.data.objects.get(orig_name)
                if not obj is None and not obj.animation_data is None:
                    curves_num += len(obj.animation_data.action.fcurves)

        colors = cu.get_distinct_colors(curves_num)
        objects_names, objects_colors, objects_data = defaultdict(
            list), defaultdict(list), defaultdict(list)
        for ind in range(min(self.topK, len(objects_indices)) - 1, -1, -1):
            if bpy.data.objects.get(names[objects_indices[ind]]):
                orig_name = names[objects_indices[ind]]
                obj_type = mu.check_obj_type(orig_name)
                objects_names[obj_type].append(orig_name)
                objects_colors[obj_type].append(cu.name_to_rgb('green'))
                objects_data[obj_type].append(1.0)
                if 'unknown' not in orig_name:
                    filter_roi_func(orig_name)
                    for fcurve in bpy.data.objects[
                            orig_name].animation_data.action.fcurves:
                        fcurve.color_mode = 'CUSTOM'
                        fcurve.color = tuple(next(colors))
            else:
                print("Can't find {}!".format(names[objects_indices[ind]]))

        _addon().color_objects(objects_names, objects_colors, objects_data)
示例#6
0
def filter_electrode_func(elec_name):
    elec_obj = bpy.data.objects[elec_name]
    if bpy.context.scene.mark_filter_items:
        FilteringMakerPanel.electrodes_colors[elec_name] = _addon(
        ).get_obj_color(elec_obj)
        _addon().object_coloring(elec_obj, cu.name_to_rgb('green'))
    else:
        elec_obj.active_material.node_tree.nodes["Layer Weight"].inputs[
            0].default_value = 0.3

    # todo: selecting the electrode will show both of their conditions time series
    # We don't want it to happen if selection_type == 'conds'...
    if bpy.context.scene.selection_type == 'conds' or bpy.context.scene.filter_items_one_by_one:
        bpy.data.objects[elec_name].select = True
    bpy.context.scene.objects.active = bpy.data.objects[elec_name]
    bpy.types.Scene.filter_is_on = True
示例#7
0
def create_vertices(d, mask, verts_color='pink'):
    layers = [False] * 20
    layers[_addon().CONNECTIONS_LAYER] = True
    vert_color = np.hstack((cu.name_to_rgb(verts_color), [0.]))
    parent_name = 'connections_vertices'
    parent_obj = mu.create_empty_if_doesnt_exists(parent_name, _addon().BRAIN_EMPTY_LAYER, None, get_connections_parent_name())
    for vertice in ConnectionsPanel.vertices:
    # for ind in range(len(d.names[mask])):
    # for indice in indices:
        p1 = d.locations[vertice, :] * 0.1
        vert_name = '{}_vertice'.format(d.labels[vertice])
        mu.create_ico_sphere(p1, layers, vert_name)
        mu.create_material('{}_mat'.format(vert_name), vert_color, 1)
        cur_obj = bpy.context.active_object
        cur_obj.name = vert_name
        cur_obj.parent = parent_obj
示例#8
0
def plot_labels_probs(elc):
    _addon().init_activity_map_coloring('FMRI')
    if bpy.context.scene.electrodes_what_to_color == 'probs':
        if len(elc['cortical_rois']) > 0:
            hemi = mu.get_obj_hemi(elc['cortical_rois'][0])
            if not hemi is None:
                labels_data = dict(data=elc['cortical_probs'],
                                   names=elc['cortical_rois'])
                _addon().set_colorbar_title('Electrodes probabilities')
                _addon().set_colormap('YlOrRd')
                _addon().labels_coloring_hemi(labels_data,
                                              ElecsPanel.faces_verts,
                                              hemi,
                                              0,
                                              colors_min=0,
                                              colors_max=1)
            else:
                print("Can't get the rois hemi!")
        else:
            _addon().clear_cortex()
        _addon().clear_subcortical_regions()
        if len(elc['subcortical_rois']) > 0:
            for region, color in zip(elc['subcortical_rois'],
                                     elc['subcortical_colors'][:, :3]):
                _addon().color_subcortical_region(region, color)
    elif bpy.context.scene.electrodes_what_to_color == 'verts':
        if len(elc['cortical_indices']) > 0:
            hemi = bpy.data.objects[elc['hemi']]
            if not hemi is None:
                _addon().init_activity_map_coloring('FMRI', subcorticals=True)
                vertices_num = np.max(elc['cortical_indices']) + 1
                activity = np.ones((vertices_num, 4))
                activity[:, 0] = 0
                activity[elc['cortical_indices'], 0] = 1
                activity[elc['cortical_indices'],
                         1:] = np.tile(cu.name_to_rgb('blue'),
                                       (len(elc['cortical_indices']), 1))
                print('Plot {} vertices with blue'.format(
                    len(elc['cortical_indices'])))
                _addon().activity_map_obj_coloring(
                    hemi, activity, ElecsPanel.faces_verts[elc['hemi']], 0,
                    True)
            else:
                print("Can't get the elec's hemi!")
        else:
            _addon().clear_cortex()
            print('No cortical vertices for {}'.format(elc['name']))
示例#9
0
def create_vertices(d, mask, verts_color='pink'):
    indices = set()
    layers = [False] * 20
    layers[_addon().CONNECTIONS_LAYER] = True
    vert_color = np.hstack((cu.name_to_rgb(verts_color), [0.]))
    parent_name = 'connections_vertices'
    parent_obj = mu.create_empty_if_doesnt_exists(parent_name, _addon().BRAIN_EMPTY_LAYER, None, PARENT_OBJ)
    for (i, j) in d.con_indices[mask]:
        indices.add(i)
        indices.add(j)
    for indice in indices:
        p1 = d.locations[indice, :] * 0.1
        vert_name = 'connection_{}'.format(indice)
        mu.create_ico_sphere(p1, layers, vert_name)
        mu.create_material('{}_mat'.format(vert_name), vert_color, 1)
        cur_obj = bpy.context.active_object
        cur_obj.name = vert_name
        cur_obj.parent = parent_obj
示例#10
0
def plot_labels_probs(elc):
    ElecsPanel.addon.init_activity_map_coloring('FMRI')
    if bpy.context.scene.electrodes_what_to_color == 'probs':
        if len(elc['cortical_rois']) > 0:
            hemi = mu.get_obj_hemi(elc['cortical_rois'][0])
            if not hemi is None:
                # if no matplotlib should calculate the colors offline :(
                labels_data = dict(data=elc['cortical_probs'],
                                   colors=elc['cortical_colors'][:, :3],
                                   names=elc['cortical_rois'])
                ElecsPanel.addon.meg_labels_coloring_hemi(
                    labels_data, ElecsPanel.faces_verts, hemi, 0)
            else:
                print("Can't get the rois hemi!")
        else:
            ElecsPanel.addon.clear_cortex()
        ElecsPanel.addon.clear_subcortical_regions()
        if len(elc['subcortical_rois']) > 0:
            for region, color in zip(elc['subcortical_rois'],
                                     elc['subcortical_colors'][:, :3]):
                ElecsPanel.addon.color_subcortical_region(region, color)
    elif bpy.context.scene.electrodes_what_to_color == 'verts':
        if len(elc['cortical_indices']) > 0:
            hemi = bpy.data.objects[elc['hemi']]
            if not hemi is None:
                ElecsPanel.addon.init_activity_map_coloring('FMRI',
                                                            subcorticals=True)
                vertices_num = np.max(elc['cortical_indices']) + 1
                activity = np.ones((vertices_num, 4))
                activity[:, 0] = 0
                activity[elc['cortical_indices'], 0] = 1
                activity[elc['cortical_indices'],
                         1:] = np.tile(cu.name_to_rgb('blue'),
                                       (len(elc['cortical_indices']), 1))
                print('Plot {} vertices with blue'.format(
                    len(elc['cortical_indices'])))
                ElecsPanel.addon.activity_map_obj_coloring(
                    hemi, activity, ElecsPanel.faces_verts[elc['hemi']], 0,
                    True)
            else:
                print("Can't get the elec's hemi!")
        else:
            ElecsPanel.addon.clear_cortex()
            print('No cortical vertices for {}'.format(elc['name']))
示例#11
0
def read_groups_labels(colors):
    groups_fname = op.join(mu.get_parent_fol(mu.get_user_fol()), '{}_groups.csv'.format(bpy.context.scene.atlas))
    if not op.isfile(groups_fname):
        return {}
    groups = defaultdict(list) # OrderedDict() # defaultdict(list)
    color_ind = 0
    for line in mu.csv_file_reader(groups_fname):
        group_name = line[0]
        group_color = line[1]
        labels = line[2:]
        if group_name[0] == '#':
            continue
        groups[group_name] = []
        for label in labels:
            # group_color = cu.name_to_rgb(colors[color_ind])
            groups[group_name].append(dict(name=label, color=cu.name_to_rgb(group_color)))
            color_ind += 1
    order_groups = OrderedDict()
    groups_names = sorted(list(groups.keys()))
    for group_name in groups_names:
        order_groups[group_name] = groups[group_name]
    return order_groups
示例#12
0
def read_groups_labels(colors):
    groups_fname = op.join(mu.get_parent_fol(mu.get_user_fol()), '{}_groups.csv'.format(bpy.context.scene.atlas))
    if not op.isfile(groups_fname):
        return {}
    groups = defaultdict(list) # OrderedDict() # defaultdict(list)
    color_ind = 0
    for line in mu.csv_file_reader(groups_fname):
        group_name = line[0]
        group_color = line[1]
        labels = line[2:]
        if group_name[0] == '#':
            continue
        groups[group_name] = []
        for label in labels:
            # group_color = cu.name_to_rgb(colors[color_ind])
            groups[group_name].append(dict(name=label, color=cu.name_to_rgb(group_color)))
            color_ind += 1
    order_groups = OrderedDict()
    groups_names = sorted(list(groups.keys()))
    for group_name in groups_names:
        order_groups[group_name] = groups[group_name]
    return order_groups
示例#13
0
def plot_labels_probs(elc):
    ElecsPanel.addon.init_activity_map_coloring('FMRI')
    if bpy.context.scene.electrodes_what_to_color == 'probs':
        if len(elc['cortical_rois']) > 0:
            hemi = mu.get_obj_hemi(elc['cortical_rois'][0])
            if not hemi is None:
                # if no matplotlib should calculate the colors offline :(
                labels_data = dict(data=elc['cortical_probs'], colors=elc['cortical_colors'][:, :3],
                                   names=elc['cortical_rois'])
                ElecsPanel.addon.meg_labels_coloring_hemi(labels_data, ElecsPanel.faces_verts, hemi, 0)
            else:
                print("Can't get the rois hemi!")
        else:
            ElecsPanel.addon.clear_cortex()
        ElecsPanel.addon.clear_subcortical_regions()
        if len(elc['subcortical_rois']) > 0:
            for region, color in zip(elc['subcortical_rois'], elc['subcortical_colors'][:, :3]):
                ElecsPanel.addon.color_subcortical_region(region, color)
    elif bpy.context.scene.electrodes_what_to_color == 'verts':
        if len(elc['cortical_indices']) > 0:
            hemi = bpy.data.objects[elc['hemi']]
            if not hemi is None:
                ElecsPanel.addon.init_activity_map_coloring('FMRI', subcorticals=True)
                vertices_num = np.max(elc['cortical_indices']) + 1
                activity = np.ones((vertices_num, 4))
                activity[:, 0] = 0
                activity[elc['cortical_indices'], 0] = 1
                activity[elc['cortical_indices'], 1:] = np.tile(
                    cu.name_to_rgb('blue'), (len(elc['cortical_indices']), 1))
                print('Plot {} vertices with blue'.format(len(elc['cortical_indices'])))
                ElecsPanel.addon.activity_map_obj_coloring(hemi, activity, ElecsPanel.faces_verts[elc['hemi']], 0, True)
            else:
                print("Can't get the elec's hemi!")
        else:
            ElecsPanel.addon.clear_cortex()
            print('No cortical vertices for {}'.format(elc['name']))
示例#14
0
def color_manually():
    ColoringMakerPanel.what_is_colored.add(WIC_MANUALLY)
    init_activity_map_coloring('FMRI')
    subject_fol = mu.get_user_fol()
    objects_names, colors, data = defaultdict(list), defaultdict(list), defaultdict(list)
    for line in mu.csv_file_reader(op.join(subject_fol, 'coloring', '{}.csv'.format(bpy.context.scene.coloring_files))):
        obj_name, color_name = line[0], line[1:]
        if obj_name[0] == '#':
            continue
        if isinstance(color_name, list) and len(color_name) == 1:
            color_name = color_name[0]
        obj_type = mu.check_obj_type(obj_name)
        if isinstance(color_name, str) and color_name.startswith('mark'):
            import filter_panel
            filter_panel.filter_roi_func(obj_name, mark=color_name)
        else:
            if isinstance(color_name, str):
                color_rgb = cu.name_to_rgb(color_name)
            # Check if the color is already in RBG
            elif len(color_name) == 3:
                color_rgb = color_name
            else:
                print('Unrecognize color! ({})'.format(color_name))
                continue
            color_rgb = list(map(float, color_rgb))
            if obj_type is not None:
                objects_names[obj_type].append(obj_name)
                colors[obj_type].append(color_rgb)
                data[obj_type].append(1.)

    color_objects(objects_names, colors, data)
    if op.isfile(op.join(subject_fol, 'coloring', '{}_legend.jpg'.format(bpy.context.scene.coloring_files))):
        cmd = '{} -m src.preproc.electrodes_preproc -s {} -a {} -f show_labeling_coloring'.format(
            bpy.context.scene.python_cmd, mu.get_user(), bpy.context.scene.atlas)
        print('Running {}'.format(cmd))
        mu.run_command_in_new_thread(cmd, False)
示例#15
0
def color_manually():
    ColoringMakerPanel.what_is_colored.add(WIC_MANUALLY)
    init_activity_map_coloring('FMRI')
    subject_fol = mu.get_user_fol()
    objects_names, colors, data = defaultdict(list), defaultdict(list), defaultdict(list)
    for line in mu.csv_file_reader(op.join(subject_fol, 'coloring', '{}.csv'.format(bpy.context.scene.coloring_files))):
        obj_name, color_name = line[0], line[1:]
        if obj_name[0] == '#':
            continue
        if isinstance(color_name, list) and len(color_name) == 1:
            color_name = color_name[0]
        obj_type = mu.check_obj_type(obj_name)
        if isinstance(color_name, str) and color_name.startswith('mark'):
            import filter_panel
            filter_panel.filter_roi_func(obj_name, mark=color_name)
        else:
            if isinstance(color_name, str):
                color_rgb = cu.name_to_rgb(color_name)
            # Check if the color is already in RBG
            elif len(color_name) == 3:
                color_rgb = color_name
            else:
                print('Unrecognize color! ({})'.format(color_name))
                continue
            color_rgb = list(map(float, color_rgb))
            if obj_type is not None:
                objects_names[obj_type].append(obj_name)
                colors[obj_type].append(color_rgb)
                data[obj_type].append(1.)

    color_objects(objects_names, colors, data)
    if op.isfile(op.join(subject_fol, 'coloring', '{}_legend.jpg'.format(bpy.context.scene.coloring_files))):
        cmd = '{} -m src.preproc.electrodes_preproc -s {} -a {} -f show_labeling_coloring'.format(
            bpy.context.scene.python_cmd, mu.get_user(), bpy.context.scene.atlas)
        print('Running {}'.format(cmd))
        mu.run_command_in_new_thread(cmd, False)
示例#16
0
def set_colorbar_background_color(color_name):
    color_rgb = cu.name_to_rgb(color_name)
    _addon().set_panels_background_color(color_rgb)