def init(addon): from random import shuffle ColoringMakerPanel.addon = addon user_fol = mu.get_user_fol() ColoringMakerPanel.faces_verts = None labels_vertices_fname = op.join(user_fol, 'labels_vertices_{}.pkl'.format(bpy.context.scene.atlas)) if not op.isfile(labels_vertices_fname): print("!!! Can't find {}!".format('labels_vertices_{}.pkl'.format(bpy.context.scene.atlas))) return None labels_names, labels_vertices = mu.load(labels_vertices_fname) ColoringMakerPanel.labels_vertices = dict(labels_names=labels_names, labels_vertices=labels_vertices) fmri_files = glob.glob(op.join(user_fol, 'fmri', 'fmri_*_lh.npy')) if len(fmri_files) > 0: files_names = [mu.namebase(fname)[5:-3] for fname in fmri_files] clusters_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.fmri_files = bpy.props.EnumProperty( items=clusters_items, description="fMRI files", update=fmri_files_update) bpy.context.scene.fmri_files = files_names[0] for hemi in mu.HEMIS: ColoringMakerPanel.fMRI[hemi] = np.load('{}_{}.npy'.format(fmri_files[0][:-7], hemi)) electrodes_source_files = glob.glob(op.join(user_fol, 'electrodes', '*_labels_*-rh.npz')) if len(electrodes_source_files) > 0: files_names = [mu.namebase(fname)[:-len('-rh')] for fname in electrodes_source_files] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_sources_files = bpy.props.EnumProperty( items=items, description="electrodes sources", update=electrodes_sources_files_update) bpy.context.scene.electrodes_sources_files = files_names[0] mu.make_dir(op.join(user_fol, 'coloring')) manually_color_files = glob.glob(op.join(user_fol, 'coloring', '*.csv')) if len(manually_color_files) > 0: files_names = [mu.namebase(fname) for fname in manually_color_files] coloring_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.coloring_files = bpy.props.EnumProperty(items=coloring_items, description="Coloring files") bpy.context.scene.coloring_files = files_names[0] vol_color_files = glob.glob(op.join(user_fol, 'coloring', 'volumetric', '*.csv')) if len(vol_color_files) > 0: files_names = [mu.namebase(fname) for fname in vol_color_files] coloring_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.vol_coloring_files = bpy.props.EnumProperty( items=coloring_items, description="Volumetric Coloring files") bpy.context.scene.vol_coloring_files = files_names[0] ColoringMakerPanel.colors = list(set(list(cu.NAMES_TO_HEX.keys())) - set(['black'])) shuffle(ColoringMakerPanel.colors) ColoringMakerPanel.labels_groups = read_groups_labels(ColoringMakerPanel.colors) if len(ColoringMakerPanel.labels_groups) > 0: groups_items = [(gr, gr, '', ind) for ind, gr in enumerate(list(ColoringMakerPanel.labels_groups.keys()))] bpy.types.Scene.labels_groups = bpy.props.EnumProperty( items=groups_items, description="Groups") ColoringMakerPanel.faces_verts = load_faces_verts() register()
def import_hemis_for_functional_maps(base_path): mu.change_layer(_addon().BRAIN_EMPTY_LAYER) layers_array = bpy.context.scene.layers emptys_names = ['Functional maps', 'Subcortical_meg_activity_map', 'Subcortical_fmri_activity_map'] for name in emptys_names: create_empty_if_doesnt_exists(name, _addon().BRAIN_EMPTY_LAYER, layers_array, 'Functional maps') # for ii in range(len(bpy.context.scene.layers)): # bpy.context.scene.layers[ii] = (ii == brain_layer) print("importing Hemispheres") # # for cur_val in bpy.context.scene.layers: # # print(cur_val) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") now = time.time() ply_files = glob.glob(op.join(base_path, 'surf', '*.ply')) N = len(ply_files) for ind, ply_fname in enumerate(ply_files): try: mu.time_to_go(now, ind, N, 10) bpy.ops.object.select_all(action='DESELECT') obj_name = mu.namebase(ply_fname).split(sep='.')[0] surf_name = mu.namebase(ply_fname).split(sep='.')[1] if surf_name == 'inflated': obj_name = '{}_{}'.format(surf_name, obj_name) mu.change_layer(_addon().INFLATED_ACTIVITY_LAYER) elif surf_name == 'pial': mu.change_layer(_addon().ACTIVITY_LAYER) else: raise Exception('The surface type {} is not supported!'.format(surf_name)) if bpy.data.objects.get(obj_name) is None: bpy.ops.import_mesh.ply(filepath=op.join(base_path, 'surf', ply_fname)) cur_obj = bpy.context.selected_objects[0] cur_obj.select = True bpy.ops.object.shade_smooth() cur_obj.scale = [0.1] * 3 cur_obj.hide = False cur_obj.name = obj_name if surf_name == 'inflated': cur_obj.active_material = bpy.data.materials['Inflated_Activity_map_mat'] cur_obj.location[0] += 5.5 if obj_name == 'inflated_rh' else -5.5 else: cur_obj.active_material = bpy.data.materials['Activity_map_mat'] cur_obj.parent = bpy.data.objects["Functional maps"] cur_obj.hide_select = True cur_obj.data.vertex_colors.new() # else: # print('{} already exists'.format(ply_fname)) except: print('Error in importing {}'.format(ply_fname)) _addon().create_inflated_curv_coloring() bpy.ops.object.select_all(action='DESELECT')
def import_rois(base_path): anatomy_inputs = {'Cortex-rh': op.join(base_path, '{}.pial.rh'.format(bpy.context.scene.atlas)), 'Cortex-lh': op.join(base_path, '{}.pial.lh'.format(bpy.context.scene.atlas)), 'Cortex-inflated-rh': op.join(base_path, '{}.inflated.rh'.format(bpy.context.scene.atlas)), 'Cortex-inflated-lh': op.join(base_path, '{}.inflated.lh'.format(bpy.context.scene.atlas)), 'Subcortical_structures': op.join(base_path, 'subcortical'), 'Cerebellum': op.join(base_path, 'cerebellum')} brain_layer = _addon().BRAIN_EMPTY_LAYER bpy.context.scene.layers = [ind == brain_layer for ind in range(len(bpy.context.scene.layers))] layers_array = bpy.context.scene.layers emptys_names = ['Brain'] + list(anatomy_inputs.keys()) # ["Brain", "Subcortical_structures", "Cortex-lh", "Cortex-rh", 'Cortex-inflated-rh', 'Cortex-inflated-rh'] for name in emptys_names: create_empty_if_doesnt_exists(name, brain_layer, layers_array) bpy.context.scene.layers = [ind == DataMakerPanel.addon.ROIS_LAYER for ind in range(len(bpy.context.scene.layers))] # todo: check each hemi inflated_imported = False for anatomy_name, anatomy_input_base_path in anatomy_inputs.items(): if not op.isdir(anatomy_input_base_path): print('The anatomy folder {} does not exist'.format(anatomy_input_base_path)) continue current_mat = bpy.data.materials['unselected_label_Mat_cortex'] if anatomy_name in ['Subcortical_structures', 'Cerebellum']: current_mat = bpy.data.materials['unselected_label_Mat_subcortical'] print('importing from {}'.format(anatomy_input_base_path)) for ply_fname in glob.glob(op.join(anatomy_input_base_path, '*.ply')): try: new_obj_name = mu.namebase(ply_fname) fol_name = anatomy_input_base_path.split(op.sep)[-1] surf_name = 'pial' if fol_name == 'subcortical' or len(fol_name.split('.')) == 1 else fol_name.split('.')[-2] if surf_name == 'inflated': new_obj_name = '{}_{}'.format(surf_name, new_obj_name) mu.change_layer(_addon().INFLATED_ROIS_LAYER) elif surf_name == 'pial': mu.change_layer(_addon().ROIS_LAYER) if not bpy.data.objects.get(new_obj_name) is None: # print('{} was already imported'.format(new_obj_name)) continue if 'inflated' in new_obj_name: inflated_imported = True bpy.ops.object.select_all(action='DESELECT') # print(ply_fname) bpy.ops.import_mesh.ply(filepath=op.join(anatomy_input_base_path, ply_fname)) cur_obj = bpy.context.selected_objects[0] cur_obj.select = True bpy.ops.object.shade_smooth() cur_obj.parent = bpy.data.objects[anatomy_name] cur_obj.scale = [0.1] * 3 cur_obj.active_material = current_mat cur_obj.hide = False cur_obj.name = new_obj_name except: print('Error in importing {}'.format(ply_fname)) # cur_obj.location[0] += 5.5 if 'rh' in anatomy_name else -5.5 # time.sleep(0.3) if inflated_imported: bpy.data.objects['Cortex-inflated-rh'].location[0] += 5.5 bpy.data.objects['Cortex-inflated-lh'].location[0] -= 5.5 bpy.ops.object.select_all(action='DESELECT')
def init(addon): if not bpy.data.objects.get("full_colorbar", None): return ColorbarPanel.addon = addon colorbar_files = glob.glob(op.join(mu.file_fol(), "color_maps", "*.npy")) if len(colorbar_files) == 0: return None files_names = [mu.namebase(fname).replace("_", "-") for fname in colorbar_files] colorbar_items = [(c, c, "", ind) for ind, c in enumerate(files_names)] bpy.types.Scene.colorbar_files = bpy.props.EnumProperty( items=colorbar_items, description="colormaps files", update=colormap_update ) bpy.context.scene.colorbar_files = files_names[0] for space in mu.get_3d_spaces(): if space.lock_object and space.lock_object.name == "full_colorbar": space.show_only_render = True register() ColorbarPanel.init = True bpy.context.scene.show_cb_in_render = False mu.select_hierarchy("colorbar_camera", False, False) if not ColorbarPanel.colorbar_updated: bpy.context.scene.colorbar_min = -1 bpy.context.scene.colorbar_max = 1 bpy.context.scene.colorbar_title = "MEG" bpy.context.scene.colorbar_files = "BuPu-YlOrRd" bpy.context.scene.colorbar_y = 0.18 bpy.context.scene.colorbar_text_y = -1.53
def init(addon): user_fol = mu.get_user_fol() clusters_labels_files = glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_*.pkl')) # old code was saving those files as npy instead of pkl clusters_labels_files.extend(glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_*.npy'))) # fmri_blobs = glob.glob(op.join(user_fol, 'fmri', 'blobs_*_rh.npy')) fMRI_clusters_files_exist = len(clusters_labels_files) > 0 # and len(fmri_blobs) > 0 if not fMRI_clusters_files_exist: return None fMRIPanel.addon = addon fMRIPanel.lookup, fMRIPanel.clusters_labels = {}, {} fMRIPanel.cluster_labels = {} files_names = [mu.namebase(fname)[len('clusters_labels_'):] for fname in clusters_labels_files] clusters_labels_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.fmri_clusters_labels_files = bpy.props.EnumProperty( items=clusters_labels_items, description="fMRI files", update=fmri_clusters_labels_files_update) bpy.context.scene.fmri_clusters_labels_files = files_names[0] for file_name, clusters_labels_file in zip(files_names, clusters_labels_files): fMRIPanel.clusters_labels[file_name] = np.load(clusters_labels_file) fMRIPanel.clusters_labels[file_name] = support_old_verions(fMRIPanel.clusters_labels[file_name]) fMRIPanel.lookup[file_name] = create_lookup_table(fMRIPanel.clusters_labels[file_name]) bpy.context.scene.fmri_cluster_val_threshold = 3 bpy.context.scene.fmri_cluster_size_threshold = 50 bpy.context.scene.search_closest_cluster_only_in_filtered = True bpy.context.scene.fmri_what_to_plot = 'blob' bpy.context.scene.fmri_how_to_sort = 'tval' update_clusters() # addon.clear_cortex() register() fMRIPanel.init = True
def import_rois(base_path): anatomy_inputs = {'Cortex-rh': op.join(base_path, '{}.pial.rh'.format(bpy.context.scene.atlas)), 'Cortex-lh': op.join(base_path, '{}.pial.lh'.format(bpy.context.scene.atlas)), 'Subcortical_structures': op.join(base_path, 'subcortical')} brain_layer = DataMakerPanel.addon.BRAIN_EMPTY_LAYER bpy.context.scene.layers = [ind == brain_layer for ind in range(len(bpy.context.scene.layers))] layers_array = bpy.context.scene.layers emptys_names = ["Brain", "Subcortical_structures", "Cortex-lh", "Cortex-rh"] for name in emptys_names: create_empty_if_doesnt_exists(name, brain_layer, layers_array) bpy.context.scene.layers = [ind == DataMakerPanel.addon.ROIS_LAYER for ind in range(len(bpy.context.scene.layers))] for anatomy_name, base_path in anatomy_inputs.items(): current_mat = bpy.data.materials['unselected_label_Mat_cortex'] if anatomy_name == 'Subcortical_structures': current_mat = bpy.data.materials['unselected_label_Mat_subcortical'] for ply_fname in glob.glob(op.join(base_path, '*.ply')): new_obj_name = mu.namebase(ply_fname) if not bpy.data.objects.get(new_obj_name) is None: continue bpy.ops.object.select_all(action='DESELECT') print(ply_fname) bpy.ops.import_mesh.ply(filepath=op.join(base_path, ply_fname)) cur_obj = bpy.context.selected_objects[0] cur_obj.select = True bpy.ops.object.shade_smooth() cur_obj.parent = bpy.data.objects[anatomy_name] cur_obj.scale = [0.1] * 3 cur_obj.active_material = current_mat cur_obj.hide = False cur_obj.name = new_obj_name # time.sleep(0.3) bpy.ops.object.select_all(action='DESELECT')
def load_meg_evoked(): evoked_fol = op.join(mu.get_user_fol(), 'meg_evoked_files') if op.isdir(evoked_fol): DataMakerPanel.evoked_files = evoked_files = glob.glob(op.join(evoked_fol, '*_labels_data_rh.npz')) basenames = [mu.namebase(fname).split('_')[0] for fname in evoked_files] files_items = [(name, name, '', ind) for ind, name in enumerate(basenames)] bpy.types.Scene.meg_evoked_files = bpy.props.EnumProperty( items=files_items, description="meg_evoked_files", update=meg_evoked_files_update)
def import_subcorticals(base_path, parent_name='Subcortical'): empty_layer = DataMakerPanel.addon.BRAIN_EMPTY_LAYER brain_layer = DataMakerPanel.addon.ACTIVITY_LAYER bpy.context.scene.layers = [ind == empty_layer for ind in range(len(bpy.context.scene.layers))] layers_array = bpy.context.scene.layers emptys_names = ['Functional maps', '{}_meg_activity_map'.format(parent_name), '{}_fmri_activity_map'.format(parent_name)] for name in emptys_names: create_empty_if_doesnt_exists(name, empty_layer, layers_array, 'Functional maps') bpy.context.scene.layers = [ind == brain_layer for ind in range(len(bpy.context.scene.layers))] print("importing Subcortical structures") # for cur_val in bpy.context.scene.layers: # print(cur_val) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") base_paths = [base_path] * 2 # Read the bast_path twice, for meg and fmri PATH_TYPE_SUB_MEG, PATH_TYPE_SUB_FMRI = range(2) for path_type, base_path in enumerate(base_paths): for ply_fname in glob.glob(op.join(base_path, '*.ply')): try: obj_name = mu.namebase(ply_fname) if path_type==PATH_TYPE_SUB_MEG and not bpy.data.objects.get('{}_meg_activity'.format(obj_name)) is None: continue if path_type==PATH_TYPE_SUB_FMRI and not bpy.data.objects.get('{}_fmri_activity'.format(obj_name)) is None: continue bpy.ops.object.select_all(action='DESELECT') print(ply_fname) bpy.ops.import_mesh.ply(filepath=op.join(base_path, ply_fname)) cur_obj = bpy.context.selected_objects[0] cur_obj.select = True bpy.ops.object.shade_smooth() cur_obj.scale = [0.1] * 3 cur_obj.hide = False cur_obj.name = obj_name if path_type == PATH_TYPE_SUB_MEG: cur_obj.name = '{}_meg_activity'.format(obj_name) curMat = bpy.data.materials.get('{}_mat'.format(cur_obj.name)) if curMat is None: # todo: Fix the succortical_activity_Mat to succortical_activity_mat curMat = bpy.data.materials['succortical_activity_Mat'].copy() curMat.name = '{}_mat'.format(cur_obj.name) cur_obj.active_material = bpy.data.materials[curMat.name] cur_obj.parent = bpy.data.objects['{}_meg_activity_map'.format(parent_name)] elif path_type == PATH_TYPE_SUB_FMRI: cur_obj.name = '{}_fmri_activity'.format(obj_name) if 'cerebellum' in cur_obj.name.lower(): cur_obj.active_material = bpy.data.materials['Activity_map_mat'] else: cur_obj.active_material = bpy.data.materials['subcortical_activity_mat'] cur_obj.parent = bpy.data.objects['{}_fmri_activity_map'.format(parent_name)] else: print('import_subcorticals: Wrong path_type! Nothing to do...') cur_obj.hide_select = True except: print('Error in importing {}!'.format(ply_fname)) bpy.ops.object.select_all(action='DESELECT')
def render_all_images(): camera_files = glob.glob(op.join(bpy.path.abspath(bpy.context.scene.output_path), 'camera_*.pkl')) for camera_file in camera_files: load_camera(camera_file) camera_name = mu.namebase(camera_file) for hemi in mu.HEMIS: if hemi in camera_name: RenderingMakerPanel.addon.show_hide_hemi(False, hemi) RenderingMakerPanel.addon.show_hide_hemi(True, mu.other_hemi(hemi)) render_image('{}_fig'.format(camera_name[len('camera') + 1:]))
def execute(self, context): stc_fname = self.filepath user_fol = mu.get_user_fol() stc_fol = mu.get_fname_folder(stc_fname) if stc_fol != op.join(user_fol, 'meg'): other_hemi_stc_fname = op.join(stc_fol, '{}.stc'.format(mu.get_other_hemi_label_name(mu.namebase(stc_fname)))) shutil.copy(stc_fname, op.join(user_fol, 'meg', mu.namesbase_with_ext(stc_fname))) shutil.copy(other_hemi_stc_fname, op.join(user_fol, 'meg', mu.namesbase_with_ext(other_hemi_stc_fname))) _addon().init_meg_activity_map() _, _, label, hemi = mu.get_hemi_delim_and_pos(mu.namebase(stc_fname)) bpy.context.scene.meg_files = label return {'FINISHED'}
def init_contours_coloring(): user_fol = mu.get_user_fol() contours_files = glob.glob(op.join(user_fol, 'labels', '*contours*lh.npz')) if len(contours_files) > 0: LabelsPanel.contours_coloring_exist = True LabelsPanel.existing_contoures = files_names = \ [mu.namebase(fname)[:-len('_contours_lh')] for fname in contours_files] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.contours_coloring = bpy.props.EnumProperty(items=items, update=contours_coloring_update, description='Selects the atlas to plot the labels contour\n\nCurrent atlas') bpy.context.scene.contours_coloring = files_names[0] bpy.context.scene.cumulate_contours = False
def init(addon, first=True): ScriptsPanel.addon = addon user_fol = mu.get_user_fol() scripts_files = glob.glob( op.join(mu.get_mmvt_code_root(), 'src', 'examples', 'scripts', '*.py')) scripts_files_names = [mu.namebase(f) for f in scripts_files] scripts_files += [ f for f in glob.glob( op.join(mu.get_parent_fol(user_fol), 'scripts', '*.py')) if mu.namebase(f) not in scripts_files_names ] if len(scripts_files) == 0: return None sys.path.append( op.join(mu.get_mmvt_code_root(), 'src', 'examples', 'scripts')) sys.path.append(op.join(mu.get_parent_fol(user_fol), 'scripts')) scripts_files = sorted( [f for f in scripts_files if check_script(mu.namebase(f))])[::-1] ScriptsPanel.scripts_names = files_names = [ mu.namebase(fname).replace('_', ' ') for fname in scripts_files ] scripts_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.scripts_files = bpy.props.EnumProperty( items=scripts_items, update=scripts_items_update, description= 'List of script in the folder:\n..\mmvt_root\mmvtcode\src\examples\scripts\n\nCurrent script' ) bpy.context.scene.scripts_files = files_names[0] bpy.context.scene.scripts_overwrite = True try: bpy.context.scene.report_use_script = bpy.context.scene.reports_files in ScriptsPanel.scripts_names except: pass # bpy.context.scene.scripts_threshold = 2 # bpy.context.scene.scripts_cb_min = 2 # bpy.context.scene.scripts_cb_max = 6 if first: register() ScriptsPanel.init = True
def init(addon): TempaltePanel.addon = addon user_fol = mu.get_user_fol() template_files = glob.glob(op.join(user_fol, 'template', 'template*.npz')) if len(template_files) == 0: return None files_names = [mu.namebase(fname)[len('template'):].replace('_', ' ') for fname in template_files] template_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.template_files = bpy.props.EnumProperty( items=template_items, description="tempalte files",update=template_files_update) bpy.context.scene.template_files = files_names[0] register() TempaltePanel.init = True
def render_all_images(): camera_files = glob.glob( op.join(bpy.path.abspath(bpy.context.scene.output_path), 'camera_*.pkl')) for camera_file in camera_files: load_camera(camera_file) camera_name = mu.namebase(camera_file) for hemi in mu.HEMIS: if hemi in camera_name: RenderingMakerPanel.addon.show_hide_hemi(False, hemi) RenderingMakerPanel.addon.show_hide_hemi( True, mu.other_hemi(hemi)) render_image('{}_fig'.format(camera_name[len('camera') + 1:]))
def modal(self, context, event): if event.type == 'TIMER': output_file = op.join(bpy.context.scene.output_path, 'combine_images_cmd.txt') if op.isfile(output_file): movies = glob.glob(op.join(bpy.context.scene.output_path, '**', '*.mp4'), recursive=True) if len(movies) > 0: os.rename(movies[0], op.join(mu.get_user_fol(), 'figures', '{}.mp4'.format( mu.namebase(bpy.context.scene.output_path)))) temp_fol = op.join(bpy.context.scene.output_path, 'new_images') if op.isdir(temp_fol): shutil.rmtree(temp_fol) self.cancel(context) return {'PASS_THROUGH'}
def init(addon): DataMakerPanel.addon = addon bpy.context.scene.electrodes_radius = 0.15 load_meg_evoked() _meg_evoked_files_update() electrodes_positions_files = glob.glob(op.join(mu.get_user_fol(), 'electrodes', 'electrodes*positions*.npz')) if len(electrodes_positions_files) > 0: files_names = [mu.namebase(fname) for fname in electrodes_positions_files] positions_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_positions_files = bpy.props.EnumProperty( items=positions_items,description="Electrodes positions") bpy.context.scene.electrodes_positions_files = files_names[0] register()
def update_camera_files(): camera_files = glob.glob(op.join(mu.get_user_fol(), 'camera', '*camera*.pkl')) if len(camera_files) > 0: files_names = [mu.namebase(fname) for fname in camera_files] if _addon().is_inflated(): files_names = [name for name in files_names if 'inf' in name] files_names.append('camera') else: files_names = [name for name in files_names if 'inf' not in name] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.camera_files = bpy.props.EnumProperty( items=items, description="electrodes sources", update=camera_files_update) bpy.context.scene.camera_files = 'camera'
def play_panel_draw(context, layout): play_type = bpy.context.scene.play_type if play_type in ['meg', 'meg_elecs', 'meg_elecs_coh']: layout.prop(context.scene, "meg_threshold", text="MEG threshold") if play_type in ['elecs', 'meg_elecs', 'elecs_act_coh', 'meg_elecs_coh']: layout.prop(context.scene, "electrodes_threshold", text="Electrodes threshold") if play_type in ['elecs_coh', 'elecs_act_coh', 'meg_elecs_coh']: layout.prop(context.scene, "connectivity_threshold", text="Conectivity threshold") row = layout.row(align=0) row.prop(context.scene, "play_from", text="From") row.operator(GrabFromPlay.bl_idname, text="", icon='BORDERMOVE') row.prop(context.scene, "play_to", text="To") row.operator(GrabToPlay.bl_idname, text="", icon='BORDERMOVE') row = layout.row(align=0) row.prop(context.scene, "play_dt", text="dt") row.prop(context.scene, "play_time_step", text="time step") layout.prop(context.scene, "play_type", text="") row = layout.row(align=True) # row.operator(Play.bl_idname, text="", icon='PLAY' if not PlayPanel.is_playing else 'PAUSE') row.operator(PrevKeyFrame.bl_idname, text="", icon='PREV_KEYFRAME') row.operator(Reverse.bl_idname, text="", icon='PLAY_REVERSE') row.operator(Pause.bl_idname, text="", icon='PAUSE') row.operator(Play.bl_idname, text="", icon='PLAY') row.operator(NextKeyFrame.bl_idname, text="", icon='NEXT_KEYFRAME') layout.prop(context.scene, 'render_movie', text="Render to a movie") layout.prop(context.scene, 'save_images', text="Save images") layout.prop(context.scene, 'rotate_brain_while_playing', text='Rotate the brain while playing') layout.operator(ExportGraph.bl_idname, text="Export graph", icon='SNAP_NORMAL') files_with_numbers = sum([len(re.findall('\d+', mu.namebase(f))) for f in glob.glob(op.join(bpy.context.scene.output_path, '*.png'))]) if files_with_numbers > 0: if not CreateMovie.running: layout.operator(CreateMovie.bl_idname, text="Create Movie", icon='RENDER_ANIMATION') layout.label(text='From images in {}'.format(mu.namebase(bpy.context.scene.output_path))) layout.prop(context.scene, 'frames_num', text="frames per second") else: layout.label(text='Rendering the movie...')
def init_hnn_files(): hnn_folder = bpy.path.abspath(bpy.context.scene.hnn_folder) HNNPanel.data_files_names = [ mu.namebase(fname) for fname in glob.glob(op.join(hnn_folder, 'data', '*.txt')) ] if len(HNNPanel.data_files_names) > 0: hnn_items = [(c, c, '', ind) for ind, c in enumerate(HNNPanel.data_files_names)] bpy.types.Scene.hnn_data_files = bpy.props.EnumProperty( items=hnn_items, description="data files") bpy.context.scene.hnn_data_files = HNNPanel.data_files_names[0] HNNPanel.params_files_names = [ mu.namebase(fname) for fname in glob.glob(op.join(hnn_folder, 'param', '*.param')) ] if len(HNNPanel.params_files_names) > 0: hnn_items = [(c, c, '', ind) for ind, c in enumerate(HNNPanel.params_files_names)] bpy.types.Scene.hnn_param_files = bpy.props.EnumProperty( items=hnn_items, description="param files") bpy.context.scene.hnn_param_files = HNNPanel.params_files_names[0]
def load_meg_evoked(): evoked_fol = op.join(mu.get_user_fol(), 'meg_evoked_files') if op.isdir(evoked_fol): DataMakerPanel.evoked_files = evoked_files = glob.glob( op.join(evoked_fol, '*_labels_data_rh.npz')) basenames = [ mu.namebase(fname).split('_')[0] for fname in evoked_files ] files_items = [(name, name, '', ind) for ind, name in enumerate(basenames)] bpy.types.Scene.meg_evoked_files = bpy.props.EnumProperty( items=files_items, description="meg_evoked_files", update=meg_evoked_files_update)
def update_camera_files(): if not RenderingMakerPanel.init: return camera_files = glob.glob(op.join(mu.get_user_fol(), 'camera', '*camera*.pkl')) if len(camera_files) > 0: files_names = [mu.namebase(fname) for fname in camera_files] if _addon().is_inflated(): files_names = [name for name in files_names if 'inf' in name] files_names.append('camera') else: files_names = [name for name in files_names if 'inf' not in name] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.camera_files = bpy.props.EnumProperty( items=items, description="electrodes sources", update=camera_files_update) bpy.context.scene.camera_files = 'camera'
def save_image(image_type='image', view_selected=None, index=-1, zoom_val=0, add_index_to_name=True, add_colorbar=None, cb_ticks_num=None, cb_ticks_font_size=None): if add_colorbar is None: add_colorbar = bpy.context.scene.save_views_with_cb if cb_ticks_num is None: cb_ticks_num = bpy.context.scene.cb_ticks_num if cb_ticks_font_size is None: cb_ticks_font_size = bpy.context.scene.cb_ticks_font_size if view_selected is None: view_selected = bpy.context.scene.save_selected_view if index == -1: fol = bpy.path.abspath(bpy.context.scene.output_path) files = [mu.namebase(f) for f in glob.glob(op.join(fol, '{}*.{}'.format(image_type, get_figure_format())))] files_with_numbers = sum([len(re.findall('\d+', f)) for f in files]) if files_with_numbers > 0: index = max([int(re.findall('\d+', f)[0]) for f in files]) + 1 if len(files) > 0 else 0 else: index = 0 switch_to_object_mode() index = bpy.context.scene.frame_current if index == -1 else index mu.show_only_render(True) fol = bpy.path.abspath(bpy.context.scene.output_path) if add_index_to_name: image_name = op.join(fol, '{}_{}.{}'.format(image_type, index, get_figure_format())) else: image_name = op.join(fol, '{}.{}'.format(image_type, get_figure_format())) print('Image saved in {}'.format(image_name)) bpy.context.scene.render.filepath = image_name view3d_context = mu.get_view3d_context() if view_selected: _addon().view_all() # todo: Understand when zoom(-1) is needed # if not _addon().subcorticals_are_hiding(): # _addon().zoom(-1) # mu.select_all_brain(True) # bpy.ops.view3d.camera_to_view_selected(view3d_context) # mu.view_selected() if zoom_val != 0: _addon().zoom(zoom_val) # _addon().zoom(1) # mu.center_view() bpy.ops.render.opengl(view3d_context, write_still=True) if add_colorbar: add_colorbar_to_image(image_name, cb_ticks_num, cb_ticks_font_size) # if view_selected: # _addon().zoom(1) return image_name
def init_labels_data_files(): user_fol = mu.get_user_fol() mu.make_dir(op.join(user_fol, 'labels', 'labels_data')) LabelsPanel.labels_data_files = labels_data_files = \ glob.glob(op.join(user_fol, 'labels', 'labels_data', '*.npz')) + \ glob.glob(op.join(user_fol, 'labels', 'labels_data', '*.mat')) if len(labels_data_files) > 0: files_names = [ mu.namebase(fname).replace('_', ' ') for fname in labels_data_files ] labels_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.labels_data_files = bpy.props.EnumProperty( items=labels_items, description="label files", update=labels_data_files_update) bpy.context.scene.labels_data_files = files_names[0]
def init(addon): user_fol = mu.get_user_fol() stim_files = glob.glob(op.join(user_fol, 'electrodes', 'stim_electrodes_*.npz')) stim_files = [sf for sf in stim_files if 'positions' not in sf] # stim_positions_files = glob.glob(op.join(user_fol, 'electrodes', 'stim_electrodes*positions.npz')) if len(stim_files) == 0: return None StimPanel.addon = addon files_names = [mu.namebase(fname)[len('stim_electrodes_'):].replace('_', ' ') for fname in stim_files] stim_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.stim_files = bpy.props.EnumProperty( items=stim_items, description='stim files', update=stim_files_update) bpy.context.scene.stim_files = files_names[0] load_conditions() register() StimPanel.init = True
def init(addon): if not bpy.data.objects.get('full_colorbar', None): print("No full_colorbar object, Can't load the colorbar panel") return ColorbarPanel.addon = addon colorbar_files_fol = mu.make_dir(op.join(mu.get_parent_fol(mu.get_user_fol()), 'color_maps')) colorbar_files_code_fol = op.join(mu.get_resources_dir(), 'color_maps') colorbar_files_template = op.join(colorbar_files_fol, '*.npy') colorbar_files_code_template = op.join(colorbar_files_code_fol, '*.npy') # colorbar_files_template = op.join(mu.file_fol(), 'color_maps', '*.npy') colorbar_files = glob.glob(colorbar_files_template) colorbar_code_files = glob.glob(colorbar_files_code_template) extra_files = list(set([mu.namebase_with_ext(f) for f in colorbar_code_files]) - set([mu.namebase_with_ext(f) for f in colorbar_files])) for extra_file in extra_files: print('Coping missing cb file: {}'.format(mu.namebase_with_ext(extra_file))) shutil.copyfile(op.join(colorbar_files_code_fol, extra_file), op.join(colorbar_files_fol, mu.namebase_with_ext(extra_file))) if len(colorbar_files) == 0: print("No colorbar files ({}), Can't load the colorbar panel".format(colorbar_files_template)) return None colorbar_files = glob.glob(colorbar_files_template) files_names = [mu.namebase(fname) for fname in colorbar_files] # .replace('_', '-') ColorbarPanel.maps_names = files_names colorbar_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.colorbar_files = bpy.props.EnumProperty( items=colorbar_items,update=colormap_update, description='Selects the colorbar color palette.\n\nCurrent palette') if not colorbar_values_are_locked(): bpy.context.scene.colorbar_files = files_names[0] else: load_colormap() for space in mu.get_3d_spaces(): if space.lock_object and space.lock_object.name == 'full_colorbar': space.show_only_render = True register() ColorbarPanel.init = True bpy.context.scene.show_cb_in_render = False mu.select_hierarchy('colorbar_camera', False, False) if not ColorbarPanel.colorbar_updated and not colorbar_values_are_locked(): ColorbarPanel.should_not_lock_values = True # bpy.context.scene.colorbar_min = -1 # bpy.context.scene.colorbar_max = 1 # bpy.context.scene.colorbar_title = ' MEG' bpy.context.scene.colorbar_y = 0.18 bpy.context.scene.colorbar_text_y = -1.53 bpy.context.scene.colorbar_prec = 2 ColorbarPanel.should_not_lock_values = False
def init(addon): DataMakerPanel.addon = addon bpy.context.scene.electrodes_radius = 0.15 load_meg_evoked() _meg_evoked_files_update() electrodes_positions_files = glob.glob( op.join(mu.get_user_fol(), 'electrodes', 'electrodes*positions*.npz')) if len(electrodes_positions_files) > 0: files_names = [ mu.namebase(fname) for fname in electrodes_positions_files ] positions_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_positions_files = bpy.props.EnumProperty( items=positions_items, description="Electrodes positions") bpy.context.scene.electrodes_positions_files = files_names[0] register()
def init_labels_data_files(): user_fol = mu.get_user_fol() mu.make_dir(op.join(user_fol, 'labels', 'labels_data')) LabelsPanel.labels_data_files = labels_data_files = \ glob.glob(op.join(user_fol, 'labels', 'labels_data', '*.npz')) + \ glob.glob(op.join(user_fol, 'labels', 'labels_data', '*.mat')) try: if len(labels_data_files) > 0: files_names = [mu.namebase(fname).replace('_', ' ') for fname in labels_data_files] labels_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.labels_data_files = bpy.props.EnumProperty( items=labels_items, update=labels_data_files_update, description='Selects labels file from the subject’s labels folder:' '\n../mmvt_root/mmvt_blend/colin27/labels/labels_data\n\nCurrent file') bpy.context.scene.labels_data_files = files_names[0] except: print('init_labels_data_files: Error!')
def init_electrodes_labeling(addon): #todo: this panel should work also without labeling file labling_files = find_elecrode_labeling_files() if len(labling_files) > 0: files_names = [ mu.namebase(fname) for fname in labling_files if mu.load(fname) ] labeling_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_labeling_files = bpy.props.EnumProperty( items=labeling_items, description='Labeling files', update=electrodes_labeling_files_update) bpy.context.scene.electrodes_labeling_files = files_names[0] # ElecsPanel.electrodes_locs = mu.load(labling_files[0]) # ElecsPanel.lookup = create_lookup_table(ElecsPanel.electrodes_locs, ElecsPanel.electrodes) ElecsPanel.faces_verts = addon.get_faces_verts() return len(labling_files) > 0
def init(addon): if not bpy.data.objects.get('full_colorbar', None): print("No full_colorbar object, Can't load the colorbar panel") return ColorbarPanel.addon = addon colorbar_files_template = op.join(mu.get_resources_dir(), 'color_maps', '*.npy') # colorbar_files_template = op.join(mu.file_fol(), 'color_maps', '*.npy') colorbar_files = glob.glob(colorbar_files_template) if len(colorbar_files) == 0: print("No colorbar files ({}), Can't load the colorbar panel".format( colorbar_files_template)) return None files_names = [ mu.namebase(fname).replace('_', '-') for fname in colorbar_files ] ColorbarPanel.maps_names = files_names colorbar_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.colorbar_files = bpy.props.EnumProperty( items=colorbar_items, description="colormaps files", update=colormap_update) if not colorbar_values_are_locked(): bpy.context.scene.colorbar_files = files_names[0] else: load_colormap() for space in mu.get_3d_spaces(): if space.lock_object and space.lock_object.name == 'full_colorbar': space.show_only_render = True register() ColorbarPanel.init = True bpy.context.scene.show_cb_in_render = False mu.select_hierarchy('colorbar_camera', False, False) if not ColorbarPanel.colorbar_updated and not colorbar_values_are_locked(): # bpy.context.scene.colorbar_min = -1 # bpy.context.scene.colorbar_max = 1 # bpy.context.scene.colorbar_title = ' MEG' bpy.context.scene.colorbar_y = 0.18 bpy.context.scene.colorbar_text_y = -1.53 bpy.context.scene.colorbar_prec = 2 if not colorbar_values_are_locked(): if 'fMRI' in bpy.context.scene.colorbar_title: bpy.context.scene.colorbar_files = 'PuBu-RdOrYl' else: bpy.context.scene.colorbar_files = 'BuPu-YlOrRd'
def init(addon): TemplatePanel.addon = addon user_fol = mu.get_user_fol() template_files = glob.glob(op.join(user_fol, 'template', 'template*.npz')) if len(template_files) == 0: return None files_names = [ mu.namebase(fname)[len('template'):].replace('_', ' ') for fname in template_files ] template_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.template_files = bpy.props.EnumProperty( items=template_items, description="template files", update=template_files_update) bpy.context.scene.template_files = files_names[0] register() TemplatePanel.init = True
def load_connections_file(connectivity_files=''): if connectivity_files == '': connectivity_files = bpy.context.scene.connectivity_files d, vertices, vertices_lookup = None, None, None conn_file_name = connectivity_files.replace(' ', '_') connectivity_file = op.join(mu.get_user_fol(), 'connectivity', '{}.npz'.format(conn_file_name)) vertices_file = op.join( mu.get_user_fol(), 'connectivity', '{}_vertices.pkl'.format(conn_file_name.replace('_static', ''))) if op.isfile(connectivity_file): print('loading connectivity: {}'.format(connectivity_file)) d = mu.Bag(np.load(connectivity_file)) d.labels = [l.astype(str) for l in d.labels] d.hemis = [l.astype(str) for l in d.hemis] d.con_names = np.array([l.astype(str) for l in d.con_names], dtype=np.str) d.conditions = [l.astype(str) for l in d.conditions] if d.con_values.ndim == 2: d.con_values = d.con_values[:, :, np.newaxis] conditions_items = [(cond, cond, '', cond_ind) for cond_ind, cond in enumerate(d.conditions)] if len(d.conditions) > 1: diff_cond = '{}-{} difference'.format(d.conditions[0], d.conditions[1]) conditions_items.append( (diff_cond, diff_cond, '', len(d.conditions))) bpy.types.Scene.conditions = bpy.props.EnumProperty( items=conditions_items, description="Conditions") # bpy.context.scene.connections_max, bpy.context.scene.connections_min = d['data_max'], d['data_min'] else: print('No connections file! {}'.format(connectivity_file)) if op.isfile(vertices_file): vertices, vertices_lookup = mu.load(vertices_file) else: name_parts = mu.namebase(vertices_file).split('_') vertices_files = glob.glob( op.join(mu.get_parent_fol(vertices_file), '{}*_{}.pkl'.format(name_parts[0], name_parts[-1]))) if len(vertices_files) == 1: vertices, vertices_lookup = mu.load(vertices_files[0]) else: print('No vertices file! ({})'.format(vertices_file)) ConnectionsPanel.d, ConnectionsPanel.vertices, ConnectionsPanel.vertices_lookup = d, vertices, vertices_lookup
def init_electrodes_labeling(addon): #todo: this panel should work also without labeling file labeling_fname = '{}_{}_electrodes_cigar_r_*_l_*{}*.pkl'.format(mu.get_user(), bpy.context.scene.atlas, '_bipolar' if bpy.context.scene.bipolar else '') labling_files = glob.glob(op.join(mu.get_user_fol(), 'electrodes', labeling_fname)) if not bpy.context.scene.bipolar: labling_files = [fname for fname in labling_files if 'bipolar' not in fname] if len(labling_files) == 0: print("!!! Can't find any electrodes labeling file in {} !!!".format( op.join(mu.get_user_fol(), 'electrodes', labeling_fname))) else: files_names = [mu.namebase(fname) for fname in labling_files if mu.load(fname)] labeling_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_labeling_files = bpy.props.EnumProperty( items=labeling_items, description='Labeling files', update=electrodes_labeling_files_update) bpy.context.scene.electrodes_labeling_files = files_names[0] # ElecsPanel.electrodes_locs = mu.load(labling_files[0]) # ElecsPanel.lookup = create_lookup_table(ElecsPanel.electrodes_locs, ElecsPanel.electrodes) ElecsPanel.faces_verts = addon.get_faces_verts()
def init(addon): user_fol = mu.get_user_fol() # clusters_labels_files = glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_*.pkl')) # old code was saving those files as npy instead of pkl # clusters_labels_files.extend(glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_*.npy'))) # fmri_blobs = glob.glob(op.join(user_fol, 'fmri', 'blobs_*_rh.npy')) fMRIPanel.addon = addon fMRIPanel.lookup, fMRIPanel.clusters_labels = {}, {} fMRIPanel.cluster_labels = {} files_names, clusters_labels_files = get_clusters_files(user_fol) fMRIPanel.fMRI_clusters_files_exist = len(files_names) > 0 # and len(fmri_blobs) > 0 if not fMRIPanel.fMRI_clusters_files_exist: return None # files_names = [mu.namebase(fname)[len('clusters_labels_'):] for fname in clusters_labels_files] fMRIPanel.clusters_labels_file_names = files_names clusters_labels_items = [(c, c, '', ind) for ind, c in enumerate(list(set(files_names)))] bpy.types.Scene.fmri_clusters_labels_files = bpy.props.EnumProperty( items=clusters_labels_items, description="fMRI files", update=fmri_clusters_labels_files_update) bpy.context.scene.fmri_clusters_labels_files = files_names[0] for file_name, clusters_labels_file in zip(files_names, clusters_labels_files): # Check if the constrast files exist if mu.hemi_files_exists(op.join(user_fol, 'fmri', 'fmri_{}_{}.npy'.format(file_name, '{hemi}'))): perc = mu.namebase(clusters_labels_file).split('_')[-1] key = '{}_{}'.format(file_name, perc) fMRIPanel.clusters_labels[key] = np.load(clusters_labels_file) # fMRIPanel.clusters_labels[key] = support_old_verions(fMRIPanel.clusters_labels[file_name]) fMRIPanel.lookup[key] = create_lookup_table(fMRIPanel.clusters_labels[key]) # bpy.context.scene.fmri_cluster_val_threshold = 2 # bpy.context.scene.fmri_cluster_size_threshold = 20 bpy.context.scene.search_closest_cluster_only_in_filtered = True bpy.context.scene.fmri_what_to_plot = 'blob' bpy.context.scene.fmri_how_to_sort = 'tval' update_clusters() fMRIPanel.blobs_activity, _ = calc_blobs_activity( fMRIPanel.constrast, fMRIPanel.clusters_labels_filtered, fMRIPanel.colors_in_hemis) bpy.context.scene.plot_fmri_cluster_per_click = False fMRIPanel.dont_show_clusters_info = True # addon.clear_cortex() register() fMRIPanel.init = True
def load_fmri_volume(nii_fname): import importlib mu.add_mmvt_code_root_to_path() from src.preproc import fMRI importlib.reload(fMRI) fmri_file_template = mu.namebase(nii_fname) subject = mu.get_user() flag, fmri_contrast_file_template = fMRI.project_volume_to_surface( subject, fmri_file_template, remote_fmri_dir=mu.get_parent_fol(nii_fname)) if not flag: print('load_fmri_volume: Error in fMRI.project_volume_to_surface!') return False flag = fMRI.calc_fmri_min_max(subject, fmri_contrast_file_template) if not flag: print('load_fmri_volume: Error in fMRI.calc_fmri_min_max!') return False # _addon().coloring.init(_addon(), register=False) fMRI_file_name = fmri_contrast_file_template.replace('fmri_', '') _addon().coloring.plot_fmri_file(fMRI_file_name) return True
def load_camera(camera_fname=''): if camera_fname == '': camera_fname = op.join(mu.get_user_fol(), 'camera', '{}.pkl'.format(bpy.context.scene.camera_files)) if op.isfile(camera_fname): camera_name = mu.namebase(camera_fname) for hemi in mu.HEMIS: if hemi in camera_name: _addon().show_hide_hemi(False, hemi) _addon().show_hide_hemi(True, mu.other_hemi(hemi)) X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location = mu.load(camera_fname) RenderFigure.update_camera = False bpy.context.scene.X_rotation = X_rotation bpy.context.scene.Y_rotation = Y_rotation bpy.context.scene.Z_rotation = Z_rotation bpy.context.scene.X_location = X_location bpy.context.scene.Y_location = Y_location bpy.context.scene.Z_location = Z_location RenderFigure.update_camera = True update_camera() else: print('No camera file was found in {}!'.format(camera_fname))
def execute(self, context): _addon().clear_colors() self.fmri_file_template, hemi, other_hemi = load_surf_files( self.filepath[:-2]) if hemi == '': bpy.context.scene.nii_label_prompt = "Can't determine the hemi!" return {'RUNNING_MODAL'} self.fmri_npy_template_fname = op.join( mu.get_user_fol(), 'fmri', 'fmri_{}.npy'.format(mu.namebase(self.fmri_file_template))) print('Waiting for both hemi files to be created ({})'.format( self.fmri_npy_template_fname)) if self.fmri_file_template != '': bpy.context.scene.nii_label_output = 'Loading nii file...' ChooseNiftiiFile.running = True context.window_manager.modal_handler_add(self) self._timer = context.window_manager.event_timer_add( 0.1, context.window) else: bpy.context.scene.nii_label_prompt = 'Please select the nii file for the {} hemi'.format( 'right' if hemi == 'lh' else 'left') return {'RUNNING_MODAL'}
def render_image(image_name='', image_fol='', quality=20, use_square_samples=None, render_background=None, camera_fname='', hide_subcorticals=False, overwrite=True): bpy.context.scene.render.resolution_percentage = bpy.context.scene.quality if quality == 0 else quality bpy.context.scene.cycles.use_square_samples = bpy.context.scene.smooth_figure if use_square_samples is None \ else use_square_samples if not render_background is None: bpy.context.scene.render_background = render_background if camera_fname == '': camera_fname = op.join(mu.get_user_fol(), 'camera', '{}.pkl'.format(bpy.context.scene.camera_files)) camera_fnames = [camera_fname] if isinstance(camera_fname, str) else camera_fname images_names = [image_name] if isinstance(image_name, str) else image_name for camera_fname in camera_fnames: if image_name == '': cur_frame = bpy.context.scene.frame_current camera_name = mu.namebase(camera_fname) images_names.append('{}_{}'.format(camera_name[len('camera') + 1:], cur_frame)) image_fol = bpy.path.abspath(bpy.context.scene.output_path) if image_fol == '' else image_fol print('Image quality: {}'.format(bpy.context.scene.render.resolution_percentage)) print("Rendering...") if not bpy.context.scene.render_background: for image_name, camera_fname in zip(images_names, camera_fnames): print('file name: {}'.format(op.join(image_fol, image_name))) bpy.context.scene.render.filepath = op.join(image_fol, image_name) if overwrite or len(glob.glob('{}.*'.format(bpy.context.scene.render.filepath))) == 0: _addon().load_camera(camera_fname) _addon().change_to_rendered_brain() if hide_subcorticals: _addon().show_hide_sub_corticals() bpy.ops.render.render(write_still=True) print("Finished") else: camera_fnames = ','.join(camera_fnames) images_names = ','.join(images_names) render_func = partial(render_in_background, image_name=images_names, image_fol=image_fol, camera_fname=camera_fnames, hide_subcorticals=hide_subcorticals, overwrite=overwrite) put_func_in_queue(render_func) if queue_len() == 1: run_func_in_queue()
def init_electrodes_labeling(addon): ela_code_fol = op.join(mu.get_parent_fol(mu.get_mmvt_code_root()), 'electrodes_rois') ElecsPanel.ela_code_exist = op.isfile(op.join(ela_code_fol, 'find_rois', 'find_rois.py')) ElecsPanel.labling_files = labling_files = find_elecrode_labeling_files() if len(labling_files) > 0: files_names = [mu.namebase(fname) for fname in labling_files if mu.load(fname)] labeling_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_labeling_files = bpy.props.EnumProperty( items=labeling_items, update=electrodes_labeling_files_update, description='List of electrodes labeling type.\n\nCurrent') bpy.context.scene.electrodes_labeling_files = files_names[0] # ElecsPanel.electrodes_locs = mu.load(labling_files[0]) # ElecsPanel.lookup = create_lookup_table(ElecsPanel.electrodes_locs, ElecsPanel.electrodes) ElecsPanel.faces_verts = addon.get_faces_verts() atlases = mu.get_annot_files() if len(atlases) > 0: ElecsPanel.atlases_exist = True atlases_items = [(c, c, '', ind) for ind, c in enumerate(atlases)] bpy.types.Scene.ela_atlas = bpy.props.EnumProperty(items=atlases_items, description='atlases') bpy.context.scene.ela_atlas = atlases[0] bpy.context.scene.ela_bipolar = bpy.context.scene.bipolar return len(labling_files) > 0
def import_hemis_for_functional_maps(current_root_path): brain_layer = DataMakerPanel.addon.BRAIN_EMPTY_LAYER bpy.context.scene.layers = [ind == brain_layer for ind in range(len(bpy.context.scene.layers))] layers_array = bpy.context.scene.layers emptys_names = ['Functional maps', 'Subcortical_meg_activity_map', 'Subcortical_fmri_activity_map'] for name in emptys_names: create_empty_if_doesnt_exists(name, brain_layer, layers_array, 'Functional maps') brain_layer = DataMakerPanel.addon.ACTIVITY_LAYER bpy.context.scene.layers = [ind == brain_layer for ind in range(len(bpy.context.scene.layers))] # for ii in range(len(bpy.context.scene.layers)): # bpy.context.scene.layers[ii] = (ii == brain_layer) print("importing Hemispheres") # # for cur_val in bpy.context.scene.layers: # # print(cur_val) # print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") base_path = current_root_path for ply_fname in glob.glob(op.join(base_path, '*.ply')): bpy.ops.object.select_all(action='DESELECT') print(ply_fname) obj_name = mu.namebase(ply_fname).split(sep='.')[0] if bpy.data.objects.get(obj_name) is None: bpy.ops.import_mesh.ply(filepath=op.join(base_path, ply_fname)) cur_obj = bpy.context.selected_objects[0] cur_obj.select = True bpy.ops.object.shade_smooth() cur_obj.scale = [0.1] * 3 cur_obj.hide = False cur_obj.name = obj_name cur_obj.active_material = bpy.data.materials['Activity_map_mat'] cur_obj.parent = bpy.data.objects["Functional maps"] cur_obj.hide_select = True cur_obj.data.vertex_colors.new() print('did hide_select') bpy.ops.object.select_all(action='DESELECT')
def load_camera(camera_fname=''): if camera_fname == '': camera_fname = op.join(mu.get_user_fol(), 'camera', '{}.pkl'.format(bpy.context.scene.camera_files)) if op.isfile(camera_fname): camera_name = mu.namebase(camera_fname) for hemi in mu.HEMIS: if hemi in camera_name: _addon().show_hide_hemi(False, hemi) _addon().show_hide_hemi(True, mu.other_hemi(hemi)) X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location = mu.load(camera_fname) RenderFigure.update_camera = False bpy.context.scene.X_rotation = X_rotation bpy.context.scene.Y_rotation = Y_rotation bpy.context.scene.Z_rotation = Z_rotation bpy.context.scene.X_location = X_location bpy.context.scene.Y_location = Y_location bpy.context.scene.Z_location = Z_location # print('Camera loaded: rotation: {},{},{} locatioin: {},{},{}'.format( # X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location)) # print('Camera loaded: {}'.format(camera_fname)) RenderFigure.update_camera = True update_camera() else: pass
def get_parcs_files(user_fol, fmri_file_name): fMRIPanel.clusters_labels_files = clusters_labels_files = \ glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_{}*.pkl'.format(fmri_file_name))) return list(set([mu.namebase(fname).split('_')[-1] for fname in clusters_labels_files]))
def init(addon): try: t1_trans_fname = op.join(mu.get_user_fol(), 't1_trans.npz') if not op.isfile(t1_trans_fname): # backward compatibility t1_trans_fname = op.join(mu.get_user_fol(), 'orig_trans.npz') t2_trans_fname = op.join(mu.get_user_fol(), 't2_trans.npz') ct_trans_fname = op.join(mu.get_user_fol(), 'ct', 'ct_trans.npz') volumes = glob.glob(op.join(mu.get_user_fol(), 'freeview', '*+aseg.npy')) luts = glob.glob(op.join(mu.get_user_fol(), 'freeview', '*ColorLUT.npz')) if op.isfile(t1_trans_fname): WhereAmIPanel.subject_t1_trans = mu.Bag(np.load(t1_trans_fname)) if op.isfile(t2_trans_fname): WhereAmIPanel.subject_t2_trans = mu.Bag(np.load(t2_trans_fname)) if op.isfile(ct_trans_fname): WhereAmIPanel.subject_ct_trans = mu.Bag(np.load(ct_trans_fname)) for atlas_vol_fname, atlas_vol_lut_fname in zip(volumes, luts): atlas = mu.namebase(atlas_vol_fname)[:-len('+aseg')] WhereAmIPanel.vol_atlas[atlas] = np.load(atlas_vol_fname) WhereAmIPanel.vol_atlas_lut[atlas] = np.load(atlas_vol_lut_fname) try: subjects_dir = mu.get_link_dir(mu.get_links_dir(), 'subjects') annot_files = [mu.namebase(fname)[3:] for fname in glob.glob( op.join(subjects_dir, mu.get_user(), 'label', 'rh.*.annot'))] annot_files += [mu.namebase(fname)[3:] for fname in glob.glob( op.join(mu.get_user_fol(), 'labels', 'rh.*.annot'))] WhereAmIPanel.annot_files = annot_files = list(set(annot_files)) if len(annot_files) > 0: items = [(c, c, '', ind) for ind, c in enumerate(annot_files)] bpy.types.Scene.subject_annot_files = bpy.props.EnumProperty( items=items, update=subject_annot_files_update, description='List of different atlases.\n\nCurrent atlas') ind = mu.index_in_list(bpy.context.scene.atlas, annot_files, 0) bpy.context.scene.subject_annot_files = annot_files[ind] else: bpy.types.Scene.subject_annot_files = bpy.props.EnumProperty(items=[]) # bpy.context.scene.subject_annot_files = '' except: bpy.types.Scene.subject_annot_files = bpy.props.EnumProperty(items=[]) bpy.context.scene.closest_label_output = '' bpy.context.scene.new_label_r = 5 bpy.context.scene.find_closest_label_on_click = False bpy.context.scene.plot_closest_label_contour = False mri_data_fname = op.join(mu.get_user_fol(), 'freeview', 'mri_data.npz') if op.isfile(mri_data_fname): WhereAmIPanel.mri_data = mu.Bag(np.load(mri_data_fname)) gray_colormap_fname = op.join(mu.file_fol(), 'color_maps', 'gray.npy') if op.isfile(gray_colormap_fname): WhereAmIPanel.gray_colormap = np.load(gray_colormap_fname) WhereAmIPanel.addon = addon WhereAmIPanel.init = True WhereAmIPanel.run_slices_listener = False init_slices() if WhereAmIPanel.run_slices_listener: start_slicer_server() else: WhereAmIPanel.slicer_state = mu.Bag({}) WhereAmIPanel.slicer_state['mri'] = slicer.init(_addon(), 'mri') create_slices(None, bpy.context.scene.cursor_location) save_slices_cursor_pos() register() except: print("Can't init where-am-I panel!") print(traceback.format_exc())
def save_all_views(views=None, inflated_ratio_in_file_name=False, rot_lh_axial=None, render_images=False, quality=0, img_name_prefix='', add_colorbar=None, cb_ticks_num=None, cb_ticks_font_size=None, overwrite=True): if not render_images: _addon().change_to_solid_brain() if add_colorbar is None: add_colorbar = bpy.context.scene.save_views_with_cb if cb_ticks_num is None: cb_ticks_num = bpy.context.scene.cb_ticks_num if cb_ticks_font_size is None: cb_ticks_font_size = bpy.context.scene.cb_ticks_font_size _addon().show_hemis() if not bpy.context.scene.save_split_views: rot_lh_axial = False if rot_lh_axial is None else rot_lh_axial _save_all_views(views, inflated_ratio_in_file_name, rot_lh_axial, render_images, quality, img_name_prefix, add_colorbar, cb_ticks_num, cb_ticks_font_size, overwrite) else: if views is None: views = list( set(_addon().ANGLES_DICT.keys()) - set([_addon().ROT_MEDIAL_LEFT, _addon().ROT_MEDIAL_RIGHT])) images_names = [] rot_lh_axial = True if rot_lh_axial is None else rot_lh_axial org_hide = {hemi: mu.get_hemi_obj(hemi).hide for hemi in mu.HEMIS} for hemi in mu.HEMIS: mu.get_hemi_obj(hemi).hide = False mu.get_hemi_obj(mu.other_hemi(hemi)).hide = True images_names.extend( _save_all_views(views, inflated_ratio_in_file_name, rot_lh_axial, render_images, quality, img_name_prefix, False, overwrite=overwrite)) for hemi in mu.HEMIS: mu.get_hemi_obj(hemi).hide = org_hide[hemi] images_hemi_inv_list = set([ mu.namebase(fname)[3:] for fname in images_names if mu.namebase(fname)[:2] in ['rh', 'lh'] ]) files = [[ fname for fname in images_names if mu.namebase(fname)[3:] == img_hemi_inv ] for img_hemi_inv in images_hemi_inv_list] fol = mu.get_fname_folder(files[0][0]) for files_coup in files: hemi = 'rh' if mu.namebase( files_coup[0]).startswith('rh') else 'lh' coup_template = files_coup[0].replace(hemi, '{hemi}') coup = {hemi: coup_template.format(hemi=hemi) for hemi in mu.HEMIS} new_image_fname = op.join(fol, mu.namebase_with_ext(files_coup[0])[3:]) combine_two_images_and_add_colorbar(coup['lh'], coup['rh'], new_image_fname, cb_ticks_num, cb_ticks_font_size) _addon().show_hemis()
def render_image(image_name='', image_fol='', quality=0, use_square_samples=None, render_background=None, camera_fname='', hide_subcorticals=False, overwrite=True, set_to_camera_mode=True): if not is_camera_view() and set_to_camera_mode: set_to_camera_view() bpy.context.scene.render.resolution_percentage = bpy.context.scene.quality if quality == 0 else quality bpy.context.scene.cycles.use_square_samples = bpy.context.scene.smooth_figure if use_square_samples is None \ else use_square_samples if not render_background is None: bpy.context.scene.render_background = render_background if camera_fname == '': camera_fname = op.join(mu.get_user_fol(), 'camera', '{}.pkl'.format(bpy.context.scene.camera_files)) current_frame = bpy.context.scene.frame_current camera_fnames = [camera_fname] if isinstance(camera_fname, str) else camera_fname if image_name == '': images_names = [ '{}_{}.{}'.format( mu.namebase(camera_fname).replace('camera', ''), current_frame, _addon().get_figure_format()) for camera_fname in camera_fnames ] images_names = [ n[1:] if n.startswith('_') else n for n in images_names ] else: images_names = [image_name] if isinstance(image_name, str) else image_name image_fol = bpy.path.abspath( bpy.context.scene.output_path) if image_fol == '' else image_fol image_fname = op.join(image_fol, '{}.{}'.format(images_names[0], get_figure_format())) if op.isfile(image_fname): files = glob.glob( op.join( image_fol, '{}_*.{}'.format(mu.namebase(image_fname), get_figure_format()))) image_fname = op.join( image_fol, '{}_{}.{}'.format(mu.namebase(image_fname), len(files), get_figure_format())) if op.isfile(image_fname): print('{} already exist!'.format(image_fname)) return '' print('Image quality: {}'.format( bpy.context.scene.render.resolution_percentage)) print("Rendering...") if not bpy.context.scene.render_background: for image_name, camera_fname in zip(images_names, camera_fnames): print('file name: {}'.format(image_fname)) bpy.context.scene.render.filepath = image_fname if overwrite or len( glob.glob('{}.*'.format( bpy.context.scene.render.filepath))) == 0: # _addon().load_camera(camera_fname) _addon().change_to_rendered_brain() if hide_subcorticals: _addon().show_hide_sub_corticals() bpy.ops.render.render(write_still=True) print("Finished") return image_fname else: camera_fnames = ','.join(camera_fnames) images_names = ','.join(images_names) render_func = partial(render_in_background, image_name=images_names, image_fol=image_fol, camera_fname=camera_fnames, hide_subcorticals=hide_subcorticals, overwrite=overwrite) put_func_in_queue(render_func) if queue_len() == 1: run_func_in_queue() return bpy.context.scene.render.filepath
def init(addon): from random import shuffle ColoringMakerPanel.addon = addon user_fol = mu.get_user_fol() ColoringMakerPanel.faces_verts = None labels_vertices_fname = op.join(user_fol, 'labels_vertices_{}.pkl'.format(bpy.context.scene.atlas)) if not op.isfile(labels_vertices_fname): print("!!! Can't find {}!".format('labels_vertices_{}.pkl'.format(bpy.context.scene.atlas))) return None labels_names, labels_vertices = mu.load(labels_vertices_fname) ColoringMakerPanel.labels_vertices = dict(labels_names=labels_names, labels_vertices=labels_vertices) ColoringMakerPanel.max_labels_vertices_num = {} meg_files_exist = mu.hemi_files_exists(op.join(user_fol, 'activity_map_{hemi}', 't0.npy')) meg_data_maxmin_fname = op.join(mu.get_user_fol(), 'meg_activity_map_minmax.pkl') if meg_files_exist and op.isfile(meg_data_maxmin_fname): data_min, data_max = mu.load(meg_data_maxmin_fname) ColoringMakerPanel.meg_activity_colors_ratio = 256 / (data_max - data_min) ColoringMakerPanel.meg_activity_data_min = data_min ColoringMakerPanel.meg_activity_data_max = data_max print('data meg: {}-{}'.format(data_min, data_max)) _addon().set_colorbar_max_min(data_max, data_min, True) _addon().set_colorbar_title('MEG') fmri_files = glob.glob(op.join(user_fol, 'fmri', 'fmri_*_lh.npy')) if len(fmri_files) > 0: files_names = [mu.namebase(fname)[5:-3] for fname in fmri_files] clusters_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.fmri_files = bpy.props.EnumProperty( items=clusters_items, description="fMRI files", update=fmri_files_update) bpy.context.scene.fmri_files = files_names[0] for hemi in mu.HEMIS: ColoringMakerPanel.fMRI[hemi] = np.load('{}_{}.npy'.format(fmri_files[0][:-7], hemi)) # Check separately for each contrast fmri_data_maxmin_fname = op.join(mu.get_user_fol(), 'fmri', 'fmri_activity_map_minmax.pkl') if op.isfile(fmri_data_maxmin_fname): data_min, data_max = mu.load(fmri_data_maxmin_fname) ColoringMakerPanel.fmri_activity_colors_ratio = 256 / (data_max - data_min) ColoringMakerPanel.fmri_activity_data_min = data_min ColoringMakerPanel.fmri_activity_data_max = data_max electrodes_source_files = glob.glob(op.join(user_fol, 'electrodes', '*_labels_*-rh.npz')) if len(electrodes_source_files) > 0: files_names = [mu.namebase(fname)[:-len('-rh')] for fname in electrodes_source_files] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.electrodes_sources_files = bpy.props.EnumProperty( items=items, description="electrodes sources", update=electrodes_sources_files_update) bpy.context.scene.electrodes_sources_files = files_names[0] mu.make_dir(op.join(user_fol, 'coloring')) manually_color_files = glob.glob(op.join(user_fol, 'coloring', '*.csv')) if len(manually_color_files) > 0: files_names = [mu.namebase(fname) for fname in manually_color_files] coloring_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.coloring_files = bpy.props.EnumProperty(items=coloring_items, description="Coloring files") bpy.context.scene.coloring_files = files_names[0] vol_color_files = glob.glob(op.join(user_fol, 'coloring', 'volumetric', '*.csv')) if len(vol_color_files) > 0: files_names = [mu.namebase(fname) for fname in vol_color_files] coloring_items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.vol_coloring_files = bpy.props.EnumProperty( items=coloring_items, description="Volumetric Coloring files") bpy.context.scene.vol_coloring_files = files_names[0] ColoringMakerPanel.colors = list(set(list(cu.NAMES_TO_HEX.keys())) - set(['black'])) shuffle(ColoringMakerPanel.colors) ColoringMakerPanel.labels_groups = read_groups_labels(ColoringMakerPanel.colors) if len(ColoringMakerPanel.labels_groups) > 0: groups_items = [(gr, gr, '', ind) for ind, gr in enumerate(list(ColoringMakerPanel.labels_groups.keys()))] bpy.types.Scene.labels_groups = bpy.props.EnumProperty( items=groups_items, description="Groups") ColoringMakerPanel.faces_verts = load_faces_verts() bpy.context.scene.coloring_meg_subcorticals = False # ColoringMakerPanel.cm = np.load(op.join(mu.file_fol(), 'color_maps', 'BuPu_YlOrRd.npy')) register()
def set_electrodes_labeling_file(fname): bpy.context.scene.electrodes_labeling_files = mu.namebase(fname)
def get_group_name(pkl_fname): pathway = mu.namebase(pkl_fname) pathway = pathway[:-len(TRACULA_POSTFIX)] return pathway
def get_clusters_files(user_fol=''): clusters_labels_files = glob.glob(op.join(user_fol, 'fmri', 'clusters_labels_*.pkl')) files_names = [mu.namebase(fname)[len('clusters_labels_'):] for fname in clusters_labels_files] clusters_labels_items = [(c, c, '', ind) for ind, c in enumerate(list(set(files_names)))] return files_names, clusters_labels_files, clusters_labels_items