def init(addon): RenderingMakerPanel.addon = addon bpy.data.objects['Target'].rotation_euler.x = 0 bpy.data.objects['Target'].rotation_euler.y = 0 bpy.data.objects['Target'].rotation_euler.z = 0 bpy.data.objects['Target'].location.x = 0 bpy.data.objects['Target'].location.y = 0 bpy.data.objects['Target'].location.z = 0 mu.make_dir(op.join(mu.get_user_fol(), 'camera')) grab_camera(overwrite=False) update_camera_files() bpy.context.scene.in_camera_view = False bpy.context.scene.save_selected_view = False bpy.context.scene.view_distance = 17.36 bpy.context.scene.render.resolution_percentage = 100 bpy.context.scene.render.image_settings.file_format = 'JPEG' # bpy.context.scene.lighting = 1.0 RenderingMakerPanel.queue = PriorityQueue() mu.make_dir(op.join(mu.get_user_fol(), 'logs')) logging.basicConfig( filename=op.join(mu.get_user_fol(), 'logs', 'reander_panel.log'), level=logging.DEBUG, format='%(asctime)-15s %(levelname)8s %(name)s %(message)s') RenderingMakerPanel.init = True register()
def load_connections_file(): d, vertices, vertices_lookup = None, None, None conn_file_name = bpy.context.scene.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 grab_camera(self=None, do_save=True, overwrite=True): RenderFigure.update_camera = False bpy.context.scene.X_rotation = X_rotation = math.degrees( bpy.data.objects['Camera'].rotation_euler.x) bpy.context.scene.Y_rotation = Y_rotation = math.degrees( bpy.data.objects['Camera'].rotation_euler.y) bpy.context.scene.Z_rotation = Z_rotation = math.degrees( bpy.data.objects['Camera'].rotation_euler.z) bpy.context.scene.X_location = X_location = bpy.data.objects[ 'Camera'].location.x bpy.context.scene.Y_location = Y_location = bpy.data.objects[ 'Camera'].location.y bpy.context.scene.Z_location = Z_location = bpy.data.objects[ 'Camera'].location.z if do_save: if op.isdir(op.join(mu.get_user_fol(), 'camera')): camera_fname = op.join(mu.get_user_fol(), 'camera', 'camera.pkl') if not op.isfile(camera_fname) or overwrite: mu.save((X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location), camera_fname) # print('Camera location was saved to {}'.format(camera_fname)) print((X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location)) else: mu.message( self, "Can't find the folder {}".format(mu.get_user_fol(), 'camera')) RenderFigure.update_camera = True
def find_fmri_files_min_max(): _addon().lock_colorbar_values() abs_values = [] for constrast_name in fMRIPanel.clusters_labels_file_names: constrast = {} constrasts_found = True for hemi in mu.HEMIS: contrast_fname = op.join(mu.get_user_fol(), 'fmri', 'fmri_{}_{}.npy'.format(constrast_name, hemi)) if not op.isfile(contrast_fname): # Remove the atlas from the contrast name new_constrast_name = '_'.join(constrast_name.split[:-1]) contrast_fname = op.join(mu.get_user_fol(), 'fmri', 'fmri_{}_{}.npy'.format(new_constrast_name, hemi)) if not op.isfile(contrast_fname): constrasts_found = False print("Can't find find_fmri_files_min_max for constrast_name!") constrast[hemi] = np.load(contrast_fname) if constrasts_found: clusters_labels_filtered = filter_clusters(constrast_name) blobs_activity, _ = calc_blobs_activity(constrast, clusters_labels_filtered) data_max, data_min = get_activity_max_min(blobs_activity) abs_values.extend([abs(data_max), abs(data_min)]) data_max = max(abs_values) _addon().set_colorbar_max_min(data_max, -data_max) cm_name = _addon().get_colormap() output_fname = op.join(mu.get_user_fol(), 'fmri', 'fmri_files_minmax_cm.pkl') mu.save((data_min, data_max, cm_name), output_fname)
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 create_inflated_curv_coloring(): def color_obj_curvs(cur_obj, curv, lookup): mesh = cur_obj.data scn = bpy.context.scene verts_colors = np.zeros((curv.shape[0], 3)) verts_colors[np.where(curv == 1)] = [1, 1, 1] verts_colors[np.where(curv == 0)] = [0.3, 0.3, 0.3] scn.objects.active = cur_obj cur_obj.select = True bpy.ops.mesh.vertex_color_remove() vcol_layer = mesh.vertex_colors.new('curve') for vert in range(curv.shape[0]): x = lookup[vert] for loop_ind in x[x>-1]: d = vcol_layer.data[loop_ind] d.color = verts_colors[vert] # todo: check not to overwrite for hemi in mu.HEMIS: cur_obj = bpy.data.objects['inflated_{}'.format(hemi)] curv = np.load(op.join(mu.get_user_fol(), 'surf', '{}.curv.npy'.format(hemi))) lookup = np.load(op.join(mu.get_user_fol(), 'faces_verts_{}.npy'.format(hemi))) color_obj_curvs(cur_obj, curv, lookup) for hemi in mu.HEMIS: curvs_fol = op.join(mu.get_user_fol(), 'surf', '{}_{}_curves'.format(bpy.context.scene.atlas, hemi)) lookup_fol = op.join(mu.get_user_fol(), '{}.pial.{}'.format(bpy.context.scene.atlas, hemi)) for cur_obj in bpy.data.objects['Cortex-{}'.format(hemi)].children: label = cur_obj.name inflated_cur_obj = bpy.data.objects['inflated_{}'.format(label)] curv = np.load(op.join(curvs_fol, '{}_curv.npy'.format(label))) lookup = np.load(op.join(lookup_fol, '{}_faces_verts.npy'.format(label))) color_obj_curvs(inflated_cur_obj, curv, lookup)
def init(addon): SlicerPanel.addon = addon bpy.context.scene.show_full_slice = False create_joint_brain_obj() # print('init slicer') # bpy.context.scene.is_sliced_ind = -1 # bpy.context.scene.last_cursor_location = [0.0, 0.0, 0.0] bpy.types.Scene.last_cursor_location = bpy.props.FloatVectorProperty( default=(0.0, 0.0, 0.0), size=3) bpy.types.Scene.is_sliced_ind = bpy.props.IntProperty(default=-1) bpy.context.scene.last_cursor_location = (0.0, 0.0, 0.0) bpy.context.scene.is_sliced_ind = -1 bpy.context.scene.slicer_cut_type = 'coronal' ct_trans_fname = op.join(mu.get_user_fol(), 'ct', 'ct_trans.npz') t2_trans_fname = op.join(mu.get_user_fol(), 't2_trans.npz') if op.isfile(ct_trans_fname) or op.isfile(t2_trans_fname): items_ind = 1 items = [('mri', 'MRI', '', items_ind)] if op.isfile(t2_trans_fname): SlicerPanel.t2_exist = True items_ind += 1 items.append(('t2', 'T2', '', items_ind)) if op.isfile(ct_trans_fname): items_ind += 1 SlicerPanel.ct_exist = True items.append(('ct', 'CT', '', items_ind)) if op.isfile(op.join(mu.get_user_fol(), 'ct', 't1_ct.mgz')): items_ind += 1 SlicerPanel.t1_ct_exist = True items.append(('t1_ct', 'T1&CT', '', items_ind)) bpy.types.Scene.slices_modality = bpy.props.EnumProperty( items=items, update=slices_modality_update) pial_vol_mask_fname = op.join(mu.get_user_fol(), 'freeview', 'pial_vol_mask.npy') dural_vol_mask_fname = op.join(mu.get_user_fol(), 'freeview', 'dural_vol_mask.npy') bpy.context.scene.pial_vol_mask_exist = op.isfile(pial_vol_mask_fname) bpy.context.scene.dural_vol_mask_exist = op.isfile(dural_vol_mask_fname) bpy.context.scene.slices_show_pial = False bpy.context.scene.slices_show_dural = False bpy.context.scene.slices_modality_mix = 0 bpy.context.scene.slices_zoom = 1 bpy.context.scene.new_electrode_num = 1 bpy.context.scene.slices_zoom_around_voxel = False bpy.context.scene.slices_zoom_voxels_num = 30 bpy.context.scene.slices_zoom_interpolate = False bpy.context.scene.slices_plot_cross = True bpy.context.scene.slices_mark_voxel = True bpy.context.scene.slices_modality = 'mri' empty_brain_path = op.join(mu.get_mmvt_code_root(), 'resources', 'empty_subject.blend', 'Material') for slice_str in ['coronal', 'sagital', 'axial']: cur_mat_name = '{}_plane_mat'.format(slice_str) if bpy.data.materials.get(cur_mat_name) is None: print('Importing {} from empty_brain file'.format(cur_mat_name)) bpy.ops.wm.append(filename=cur_mat_name, directory=empty_brain_path) # bpy.context.scene['slice_plane_flipped'] = {'coronal': False, 'axial': False, 'sagital': False} SlicerPanel.init = True register()
def draw(self, context): layout = self.layout root = mu.get_user_fol() # row = layout.row(align=0) if bpy.data.objects.get('Deep_electrodes'): layout.prop(context.scene, 'freeview_load_electrodes', text="Load electrodes") all_electrodes_exist = True if bpy.data.objects.get('Deep_electrodes'): all_electrodes_exist = all([op.isfile(op.join(root, 'freeview', '{}.dat'.format(group))) for group in FreeviewPanel.electrodes_groups]) if not all_electrodes_exist and bpy.context.scene.freeview_load_electrodes: layout.operator(CreateFreeviewFiles.bl_idname, text='Create Freeview files', icon='PARTICLES') else: text = 'Close Freeview' if FreeviewPanel.freeview_is_open else 'Open Freeview' layout.operator(FreeviewOpen.bl_idname, text=text, icon='PARTICLES') fmri_files_template = op.join(mu.get_user_fol(), 'freeview','*{}*.{}'.format(bpy.context.scene.fmri_files, '{format}')) fmri_vol_files = glob.glob(fmri_files_template.format(format='mgz')) + \ glob.glob(fmri_files_template.format(format='nii')) if bpy.context.scene.fMRI_files_exist and len(fmri_vol_files) > 0: layout.prop(context.scene, 'freeview_load_fMRI', text="Load fMRI") if FreeviewPanel.CT_files_exist: layout.prop(context.scene, 'freeview_load_CT', text="Load CT") row = layout.row(align=0) row.operator(FreeviewGotoCursor.bl_idname, text="Goto Cursor", icon='HAND') row.operator(FreeviewSaveCursor.bl_idname, text="Save Cursor", icon='FORCE_CURVE') if bpy.context.scene.freeview_messages != '': layout.label(text=context.scene.freeview_messages)
def init(addon, addon_prefs=None): FreeviewPanel.addon = addon # print('freeview command: {}'.format(addon_prefs.freeview_cmd)) # print('Use -verbose? {}'.format(addon_prefs.freeview_cmd_verbose)) # print('Use -stdin? {}'.format(addon_prefs.freeview_cmd_stdin)) FreeviewPanel.addon_prefs = addon_prefs bpy.context.scene.freeview_listen_to_keyboard = False bpy.context.scene.freeview_listener_is_running = False bpy.context.scene.fMRI_files_exist = len(glob.glob(op.join(mu.get_user_fol(), 'fmri', '*_lh.npy'))) > 0 #mu.hemi_files_exists(op.join(mu.get_user_fol(), 'fmri_{hemi}.npy')) bpy.context.scene.electrodes_exist = bpy.data.objects.get('Deep_electrodes', None) is not None if bpy.context.scene.electrodes_exist: FreeviewPanel.electrodes_groups = set([mu.elec_group(obj.name, bpy.context.scene.bipolar) for obj in bpy.data.objects['Deep_electrodes'].children]) else: FreeviewPanel.electrodes_groups = [] bpy.context.scene.freeview_messages = '' root = mu.get_user_fol() mmvt_ct_fname = op.join(root, 'ct', 'ct_reg_to_mr.mgz') # if not op.isfile(mmvt_ct_fname): # subjects_ct_fname = op.join(mu.get_subjects_dir(), mu.get_user(), 'mri', 'ct_nas.nii.gz') # if op.isfile(subjects_ct_fname): # shutil.copy(subjects_ct_fname, mmvt_ct_fname) FreeviewPanel.CT_files_exist = op.isfile(mmvt_ct_fname) FreeviewPanel.init = True FreeviewPanel.freeview_is_open = False register()
def get_deep_electrodes_data(): # todo: should be called once (maybe those files are already loaded? fol = op.join(mu.get_user_fol(), 'electrodes') bip = 'bipolar_' if bpy.context.scene.bipolar else '' meta_files = glob.glob(op.join(fol, 'electrodes_{}meta*.npz'.format(bip))) if len(meta_files) > 0: data_files = glob.glob( op.join(fol, 'electrodes_{}data*.npy'.format(bip))) print('Loading data file: {}'.format(data_files[0])) print('Loading meta data file: {}'.format(meta_files[0])) data = np.load(data_files[0]) meta = np.load(meta_files[0]) else: data_files = glob.glob( op.join(mu.get_user_fol(), 'electrodes', 'electrodes_{}data*.npz'.format(bip))) print('Loading data file: {}'.format(data_files[0])) meta = np.load(data_files[0]) data = meta['data'] # todo: check if this part is needed if len(data_files) == 0: print('No data files!') elif len(data_files) == 1: current_file_to_upload = data_files[0] else: print('More the one data file!') current_file_to_upload = data_files[0] # todo: should decide which one to pick # current_file_to_upload = current_file_to_upload.format( # stat='avg' if bpy.context.scene.selection_type == 'conds' else 'diff') return data, meta
def invoke(self, context, event=None): self._first_time = True StreamingPanel.is_streaming = not StreamingPanel.is_streaming if StreamingPanel.first_time: StreamingPanel.first_time = False try: context.window_manager.event_timer_remove(self._timer) except: pass context.window_manager.modal_handler_add(self) self._timer = context.window_manager.event_timer_add( 0.01, context.window) if StreamingPanel.is_streaming: init_electrodes_fcurves(bpy.context.scene.streaming_window_length) show_electrodes_fcurves() self._first_timer = True # print('Setting _first_timer to True!') # _addon().set_colorbar_max_min(StreamingPanel.data_max, StreamingPanel.data_min) if not _addon().colorbar_values_are_locked(): _addon().set_colorbar_title('Electrodes Streaming Data') mu.show_only_render(True) bpy.context.scene.frame_current = 0 args = dict(buffer_size=bpy.context.scene.streaming_buffer_size, server=bpy.context.scene.streaming_server, multicast_group=bpy.context.scene.multicast_group, port=bpy.context.scene.streaming_server_port, timeout=bpy.context.scene.timeout, multicast=bpy.context.scene.multicast, mat_len=len( bpy.data.objects['Deep_electrodes'].children)) if bpy.context.scene.stream_type == 'offline': config = mu.read_config_ini( op.join(mu.get_user_fol(), 'electrodes', 'streaming', bpy.context.scene.logs_folders)) else: config = mu.read_config_ini( op.join(mu.get_user_fol(), 'electrodes', 'streaming')) if 'STREAMING' in config.sections(): args['good_channels'] = config['STREAMING'].get( 'good_electrodes', '') args['bad_channels'] = config['STREAMING'].get( 'bad_electrodes', '') args['no_channels'] = config['STREAMING'].get( 'no_electrodes', '') StreamButton._channels_names = config['STREAMING'].get( 'electrodes_names', '').split(',') StreamButton._stim_channels = config['STREAMING'].get( 'stim_electrodes', '').split(',') if bpy.context.scene.stream_type == 'offline': args['data'] = copy.deepcopy(StreamingPanel.offline_data) StreamingPanel.udp_queue = mu.run_thread( offline_logs_reader, reading_from_udp_while_termination_func, **args) else: StreamingPanel.udp_queue = mu.run_thread( udp_reader, reading_from_udp_while_termination_func, **args) return {'RUNNING_MODAL'}
def invoke(self, context, event=None): with open(op.join(mu.get_user_fol(), 'search_panel.txt'), 'w') as text_file: for obj_name in SearchPanel.marked_objects: print(obj_name, file=text_file) print('List was saved to {}'.format( op.join(mu.get_user_fol(), 'search_panel.txt'))) return {"FINISHED"}
def _connections_origin_update(): if bpy.context.scene.connections_origin == 'rois': bpy.context.scene.connections_file = op.join(mu.get_user_fol(), 'rois_con.npz') elif bpy.context.scene.connections_origin == 'electrodes': bpy.context.scene.connections_file = op.join(mu.get_user_fol(), 'electrodes', 'electrodes_con.npz') else: print('Wrong connection type!!!') if ConnectionsPanel.d == {}: load_connections_file()
def export_electrodes(): import csv mu.make_dir(op.join(mu.get_user_fol(), 'electrodes')) csv_fname = op.join(mu.get_user_fol(), 'electrodes', '{}_RAS.csv'.format(mu.get_user())) electrodes = [e for e in bpy.data.objects[_addon().electrodes_panel_parent].children] with open(csv_fname, 'w') as csv_file: wr = csv.writer(csv_file, quoting=csv.QUOTE_ALL) wr.writerow(['Electrode Name','R','A','S']) for elc in electrodes: wr.writerow([elc.name, *['{:.2f}'.format(loc * 10) for loc in elc.location]])
def eeg_data_and_meta(): if DataMakerPanel.eeg_data is None: data_fname = op.join(mu.get_user_fol(), 'eeg', 'eeg_data.npy') meta_fname = op.join(mu.get_user_fol(), 'eeg', 'eeg_data_meta.npz') if op.isfile(data_fname) and op.isfile(meta_fname): DataMakerPanel.eeg_data = np.load(data_fname, mmap_mode='r') DataMakerPanel.eeg_meta = np.load(meta_fname) else: DataMakerPanel.eeg_data = DataMakerPanel.eeg_meta = None return DataMakerPanel.eeg_data, DataMakerPanel.eeg_meta
def invoke(self, context, event=None): parent_obj = bpy.data.objects['EEG_electrodes'] source_file = op.join(mu.get_user_fol(), 'eeg', 'eeg_data.npy') meta_file = op.join(mu.get_user_fol(), 'eeg', 'eeg_data_meta.npz') add_data_to_electrodes(source_file, meta_file) add_data_to_electrodes_parent_obj(parent_obj, source_file, meta_file) bpy.types.Scene.eeg_data_exist = True if bpy.data.objects.get(' '): bpy.context.scene.objects.active = bpy.data.objects[' '] return {"FINISHED"}
def init(addon): import shutil ElecsPanel.addon = addon ElecsPanel.parent = bpy.data.objects.get('Deep_electrodes') if ElecsPanel.parent is None or len(ElecsPanel.parent.children) == 0: print("Can't register electrodes panel, no Deep_electrodes object") return mu.make_dir(op.join(mu.get_user_fol(), 'electrodes')) sorted_groups_fname = op.join(mu.get_user_fol(), 'electrodes', 'sorted_groups.pkl') if not op.isfile(sorted_groups_fname): # Try to get the file from the subject's root folder if op.isfile(op.join(mu.get_user_fol(), 'sorted_groups.pkl')): shutil.move(op.join(mu.get_user_fol(), 'sorted_groups.pkl'), sorted_groups_fname) else: print("Can't register electrodes panel, no sorted groups file") return # show_hide_electrodes(True) ElecsPanel.sorted_groups = mu.load(sorted_groups_fname) ElecsPanel.groups_hemi = create_groups_hemi_lookup( ElecsPanel.sorted_groups) ElecsPanel.all_electrodes = [el.name for el in ElecsPanel.parent.children] ElecsPanel.groups = create_groups_lookup_table(ElecsPanel.all_electrodes) ElecsPanel.groups_first_electrode = find_first_electrode_per_group( ElecsPanel.all_electrodes) ElecsPanel.groups_electrodes = create_groups_electrodes_lookup( ElecsPanel.all_electrodes) init_leads_list() init_electrodes_list() ret = init_electrodes_labeling(addon) if not ret: print('No electrodes labeling files.') return # addon.clear_colors_from_parent_childrens('Deep_electrodes') # addon.clear_cortex() bpy.context.scene.show_only_lead = False bpy.context.scene.listen_to_keyboard = False bpy.context.scene.listener_is_running = False bpy.context.scene.show_lh_electrodes = True bpy.context.scene.show_rh_electrodes = True _electrodes_labeling_files_update() if not ElecsPanel.electrodes_locs or not ElecsPanel.lookup: if not ElecsPanel.electrodes_locs: print( "!!! Can't find electrodes labeling files in user/electrdes!") if not ElecsPanel.lookup: print('No electrodes lookup table!') print("!!! Can't plot electrodes' probabilties !!!") if not ElecsPanel.groups or not ElecsPanel.groups_first_electrode or not ElecsPanel.sorted_groups or \ not ElecsPanel.groups_hemi or not ElecsPanel.groups_electrodes: print('Error in electrodes panel init!') else: register() ElecsPanel.init = True
def init(addon): DataInVertMakerPanel.addon = addon lookup_files = glob.glob(op.join(mu.get_user_fol(), 'activity_map_*_verts_lookup.npy')) if len(lookup_files) == 0: print('No lookup files for vertex_data_panel') DataInVertMakerPanel.init = False DataInVertMakerPanel.activity_maps_exist = \ op.isdir(op.join(mu.get_user_fol(), 'activity_map_rh')) and \ op.isdir(op.join(mu.get_user_fol(), 'activity_map_lh')) DataInVertMakerPanel.init = True register()
def template_draw(self, context): layout = self.layout if MNE_EXIST: layout.operator(ChooseSTCFile.bl_idname, text="Load stc file", icon='LOAD_FACTORY').filepath=op.join( mu.get_user_fol(), 'meg', '*.stc') if bpy.context.scene.nii_label_output == '': layout.operator(ChooseNiftiiFile.bl_idname, text="Load surface nii file", icon='LOAD_FACTORY').filepath = op.join( mu.get_user_fol(), 'fmri', '*.nii*') if bpy.context.scene.nii_label_prompt != '': layout.label(text=bpy.context.scene.nii_label_prompt) else: layout.label(text=bpy.context.scene.nii_label_output)
def init_sorted_groups(): import shutil sorted_groups_fname = op.join(mu.get_user_fol(), 'electrodes', 'sorted_groups.pkl') if not op.isfile(sorted_groups_fname): # Try to get the file from the subject's root folder if op.isfile(op.join(mu.get_user_fol(), 'sorted_groups.pkl')): shutil.move(op.join(mu.get_user_fol(), 'sorted_groups.pkl'), sorted_groups_fname) else: print("electrodes_panel: no sorted groups file") # return if op.isfile(sorted_groups_fname): ElecsPanel.sorted_groups = mu.load(sorted_groups_fname)
def init(addon): try: trans_fname = op.join(mu.get_user_fol(), 'orig_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(trans_fname): WhereAmIPanel.subject_orig_trans = mu.Bag(np.load(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) subjects_dir = mu.get_link_dir(mu.get_links_dir(), 'subjects') annot_files = glob.glob( op.join(subjects_dir, mu.get_user(), 'label', 'rh.*.annot')) if len(annot_files) > 0: files_names = [mu.namebase(fname)[3:] for fname in annot_files] items = [(c, c, '', ind) for ind, c in enumerate(files_names)] bpy.types.Scene.subject_annot_files = bpy.props.EnumProperty( items=items) bpy.context.scene.subject_annot_files = files_names[0] else: bpy.types.Scene.subject_annot_files = bpy.props.EnumProperty( items=[]) # bpy.context.scene.subject_annot_files = '' bpy.context.scene.closest_label_output = '' bpy.context.scene.new_label_r = 5 mri_data_fname = op.join(mu.get_user_fol(), 'freeview', '{}_data.npz'.format('mri')) 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 = slicer.init('mri') create_slices('mri', bpy.context.scene.cursor_location) save_slices_cursor_pos() register() except: print("Can't init where-am-I panel!") print(traceback.format_exc())
def fmri_files_update(self, context): #todo: there are two frmi files list (the other one in fMRI panel) user_fol = mu.get_user_fol() for hemi in mu.HEMIS: fname = op.join(user_fol, 'fmri', 'fmri_{}_{}.npy'.format(bpy.context.scene.fmri_files, hemi)) ColoringMakerPanel.fMRI[hemi] = np.load(fname) fmri_data_maxmin_fname = op.join(mu.get_user_fol(), 'fmri', 'fmri_activity_map_minmax_{}.pkl'.format( bpy.context.scene.fmri_files)) 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
def import_brain(context=None): # self.brain_layer = DataMakerPanel.addon.BRAIN_EMPTY_LAYER # self.current_root_path = mu.get_user_fol() # bpy.path.abspath(bpy.context.scene.conf_path) user_fol = mu.get_user_fol() print("importing ROIs") import_rois(user_fol) import_hemis_for_functional_maps(user_fol) import_subcorticals(op.join(user_fol, 'subcortical')) if context: last_obj = context.active_object.name print('last obj is -' + last_obj) if bpy.data.objects.get(' '): bpy.data.objects[' '].select = True if context: context.scene.objects.active = bpy.data.objects[' '] if context: bpy.data.objects[last_obj].select = False DataMakerPanel.addon.show_rois() bpy.types.Scene.brain_imported = True print('cleaning up') for obj in bpy.data.objects['Subcortical_structures'].children: # print(obj.name) if obj.name[-1] == '1': obj.name = obj.name[0:-4] print('Brain importing is Finished ')
def invoke(self, context, event=None): input_file = op.join(mu.get_user_fol(), 'electrodes', '{}.npz'.format(bpy.context.scene.electrodes_positions_files)) import_electrodes(input_file, _addon().ELECTRODES_LAYER) bpy.types.Scene.electrodes_imported = True print('Electrodes importing is Finished ') return {"FINISHED"}
def invoke(self, context, event=None): # self.current_root_path = bpy.path.abspath(bpy.context.scene.conf_path) parent_obj = bpy.data.objects['Deep_electrodes'] base_path = mu.get_user_fol() data, meta = None, None source_file = op.join(base_path, 'electrodes', 'electrodes{}_data_diff.npz'.format( '_bipolar' if bpy.context.scene.bipolar else '')) # 'avg' if bpy.context.scene.selection_type == 'conds' else 'diff')) if op.isfile(source_file): meta = np.load(source_file) data = meta['data'] else: source_file = op.join(base_path, 'electrodes', 'electrodes{}_data_{}_data.npy'.format( '_bipolar' if bpy.context.scene.bipolar else '', 'avg' if bpy.context.scene.selection_type == 'conds' else 'diff')) meta_file = op.join(base_path, 'electrodes', 'electrodes{}_data_{}_meta.npz'.format( '_bipolar' if bpy.context.scene.bipolar else '', 'avg' if bpy.context.scene.selection_type == 'conds' else 'diff')) if op.isfile(source_file) and op.isfile(meta_file): data = np.load(source_file) meta = np.load(meta_file) else: print('No electrodes data file!') if not data is None and not meta is None: print('Loading electordes data from {}'.format(source_file)) conditions = add_data_to_electrodes(data, meta) selection_panel.set_conditions_enum(conditions) add_data_to_electrodes_parent_obj(parent_obj, data, meta) bpy.types.Scene.electrodes_data_exist = True if bpy.data.objects.get(' '): bpy.context.scene.objects.active = bpy.data.objects[' '] return {"FINISHED"}
def import_brain(context=None): # self.brain_layer = DataMakerPanel.addon.BRAIN_EMPTY_LAYER # self.current_root_path = mu.get_user_fol() # bpy.path.abspath(bpy.context.scene.conf_path) if _addon() is None: print('addon is None!') return user_fol = mu.get_user_fol() print("importing ROIs") import_rois(user_fol) import_hemis_for_functional_maps(user_fol) import_subcorticals(op.join(user_fol, 'subcortical')) # if op.isdir(op.join(user_fol, 'cerebellum')): # import_subcorticals(op.join(user_fol, 'cerebellum'), 'Cerebellum') if context: last_obj = context.active_object.name print('last obj is -' + last_obj) # create_inflating_morphing() if bpy.data.objects.get(' '): bpy.data.objects[' '].select = True if context: context.scene.objects.active = bpy.data.objects[' '] if context: bpy.data.objects[last_obj].select = False DataMakerPanel.addon.show_rois() bpy.types.Scene.brain_imported = True print('cleaning up') for obj in bpy.data.objects['Subcortical_structures'].children: # print(obj.name) if obj.name[-1] == '1': obj.name = obj.name[0:-4] bpy.ops.object.select_all(action='DESELECT') print('Brain importing is Finished ')
def combine_four_brain_perspectives(): data_min, data_max = _addon().get_colorbar_max_min() background = bpy.context.scene.background_color figure_name = 'splitted_lateral_medial_{}_{}.png'.format( 'inflated' if _addon().is_inflated() else 'pial', background) figure_fname = op.join(mu.get_user_fol(), 'figures', figure_name) colors_map = _addon().get_colormap_name().replace('-', '_') x_left_crop, x_right_crop, y_top_crop, y_buttom_crop = (300, 300, 0, 0) w_fac, h_fac = (1.5, 1) cmd = '{} -m src.utils.figures_utils '.format(bpy.context.scene.python_cmd) + \ '-f combine_four_brain_perspectives,combine_brain_with_color_bar --fol {} --data_max {} --data_min {} '.format( op.join(mu.get_user_fol(), 'figures'), data_max, data_min) + \ '--figure_fname {} --colors_map {} --x_left_crop {} --x_right_crop {} --y_top_crop {} --y_buttom_crop {} '.format( figure_fname, colors_map, x_left_crop, x_right_crop, y_top_crop, y_buttom_crop) + \ '--w_fac {} --h_fac {} --facecolor {}'.format(w_fac, h_fac, background) mu.run_command_in_new_thread(cmd, False)
def load_faces_verts(): faces_verts = {} current_root_path = mu.get_user_fol() faces_verts['lh'] = np.load(op.join(current_root_path, 'faces_verts_lh.npy')) faces_verts['rh'] = np.load(op.join(current_root_path, 'faces_verts_rh.npy')) # faces_verts['cortex'] = np.load(op.join(current_root_path, 'faces_verts_cortex.npy')) return faces_verts
def invoke(self, context, event=None): closest_mesh_name, vertex_ind, vertex_co = self.find_vertex_index_and_mesh_closest_to_cursor() print(vertex_co) self.create_empty_in_vertex_location(vertex_co) data_path = mu.get_user_fol() self.keyframe_empty_test('Activity_in_vertex', closest_mesh_name, vertex_ind, data_path) return {"FINISHED"}
def draw(self, context): layout = self.layout # layout.prop(context.scene, 'conf_path') col = self.layout.column(align=True) col.prop(context.scene, 'atlas', text="Atlas") # if not bpy.types.Scene.brain_imported: # col.operator("ohad.anatomy_preproc", text="Run Preporc", icon='BLENDER') col.operator("ohad.brain_importing", text="Import Brain", icon='MATERIAL_DATA') # if not bpy.types.Scene.electrodes_imported: electrodes_positions_files = glob.glob(op.join(mu.get_user_fol(), 'electrodes', 'electrodes*positions*.npz')) if len(electrodes_positions_files) > 0: col.prop(context.scene, 'bipolar', text="Bipolar") col.prop(context.scene, 'electrodes_radius', text="Electrodes' radius") col.prop(context.scene, 'electrodes_positions_files', text="") col.operator("ohad.electrodes_importing", text="Import Electrodes", icon='COLOR_GREEN') # if bpy.types.Scene.brain_imported and (not bpy.types.Scene.brain_data_exist): col = self.layout.column(align=True) col.operator(AddDataToBrain.bl_idname, text="Add data to Brain", icon='FCURVE') col.prop(context.scene, 'brain_no_conds_stat', text="") col.operator(AddDataNoCondsToBrain.bl_idname, text="Add no conds data to Brain", icon='FCURVE') col.prop(context.scene, 'import_unknown', text="Import unknown") # if bpy.types.Scene.electrodes_imported and (not bpy.types.Scene.electrodes_data_exist): col.operator("ohad.electrodes_add_data", text="Add data to Electrodes", icon='FCURVE') if len(DataMakerPanel.evoked_files) > 0: layout.label(text='External MEG evoked files:') layout.prop(context.scene, 'meg_evoked_files', text="") layout.operator(AddOtherSubjectMEGEvokedResponse.bl_idname, text="Add MEG evoked response", icon='FCURVE') if len(DataMakerPanel.externals) > 0: layout.prop(context.scene, 'evoked_objects', text="") select_text = 'Deselect' if get_external_meg_evoked_selected() else 'Select' select_icon = 'BORDER_RECT' if select_text == 'Select' else 'PANEL_CLOSE' layout.operator(SelectExternalMEGEvoked.bl_idname, text=select_text, icon=select_icon)
def plot_activity(map_type, faces_verts, threshold, meg_sub_activity=None, plot_subcorticals=True, override_current_mat=True, clusters=False): current_root_path = mu.get_user_fol() # bpy.path.abspath(bpy.context.scene.conf_path) not_hiden_hemis = [hemi for hemi in HEMIS if not bpy.data.objects[hemi].hide] frame_str = str(bpy.context.scene.frame_current) loop_indices = {} for hemi in not_hiden_hemis: colors_ratio, data_min = None, None if map_type == 'MEG': fname = op.join(current_root_path, 'activity_map_' + hemi, 't' + frame_str + '.npy') if op.isfile(fname): f = np.load(fname) if _addon().colorbar_values_are_locked(): data_max, data_min = _addon().get_colorbar_max_min() colors_ratio = 256 / (data_max - data_min) else: colors_ratio = ColoringMakerPanel.meg_activity_colors_ratio data_min = ColoringMakerPanel.meg_activity_data_min data_max = ColoringMakerPanel.meg_activity_data_max _addon().set_colorbar_max_min(data_max, data_min) _addon().set_colorbar_title('MEG') else: print("Can't load {}".format(fname)) return False elif map_type == 'FMRI': if not ColoringMakerPanel.fmri_activity_data_min is None and \ not ColoringMakerPanel.fmri_activity_data_max is None: if _addon().colorbar_values_are_locked(): data_max, data_min = _addon().get_colorbar_max_min() colors_ratio = 256 / (data_max - data_min) else: colors_ratio = ColoringMakerPanel.fmri_activity_colors_ratio data_min = ColoringMakerPanel.fmri_activity_data_min data_max = ColoringMakerPanel.fmri_activity_data_max _addon().set_colorbar_max_min(data_max, data_min) _addon().set_colorbar_title('fMRI') if clusters: f = [c for h, c in ColoringMakerPanel.fMRI_clusters.items() if h == hemi] else: f = ColoringMakerPanel.fMRI[hemi] if bpy.context.scene.coloring_both_pial_and_inflated: for cur_obj in [bpy.data.objects[hemi], bpy.data.objects['inflated_{}'.format(hemi)]]: activity_map_obj_coloring(cur_obj, f, faces_verts[hemi], threshold, override_current_mat, data_min, colors_ratio) else: if _addon().is_pial(): cur_obj = bpy.data.objects[hemi] elif _addon().is_inflated(): cur_obj = bpy.data.objects['inflated_{}'.format(hemi)] activity_map_obj_coloring(cur_obj, f, faces_verts[hemi], threshold, override_current_mat, data_min, colors_ratio) if plot_subcorticals and not bpy.context.scene.objects_show_hide_sub_cortical and not meg_sub_activity is None: if map_type == 'MEG': if not bpy.data.objects['Subcortical_meg_activity_map'].hide: color_object_homogeneously(meg_sub_activity, '_meg_activity', threshold) if map_type == 'FMRI': fmri_subcortex_activity_color(threshold, override_current_mat) return True
def load_meg_subcortical_activity(): meg_sub_activity = None current_root_path = mu.get_user_fol() # bpy.path.abspath(bpy.context.scene.conf_path) subcortical_activity_file = op.join(current_root_path,'subcortical_meg_activity.npz') if op.isfile(subcortical_activity_file): meg_sub_activity = np.load(subcortical_activity_file) return meg_sub_activity
def init_logo(): import bpy.utils.previews pcoll = bpy.utils.previews.new() hnn_icons_dir = op.join(mu.get_parent_fol(mu.get_user_fol()), 'icons') # load a preview thumbnail of a file and store in the previews collection pcoll.load("hnn_icon", os.path.join(hnn_icons_dir, "hnn.png"), 'IMAGE') preview_collections["main"] = pcoll
def plot_activity(map_type, faces_verts, threshold, meg_sub_activity=None, plot_subcorticals=True, override_current_mat=True, clusters=False): current_root_path = mu.get_user_fol() # bpy.path.abspath(bpy.context.scene.conf_path) hemispheres = [hemi for hemi in HEMIS if not bpy.data.objects[hemi].hide] frame_str = str(bpy.context.scene.frame_current) # loop_indices = {} for hemi in hemispheres: if map_type == 'MEG': fname = op.join(current_root_path, 'activity_map_' + hemi, 't' + frame_str + '.npy') if op.isfile(fname): f = np.load(fname) else: print("Can't load {}".format(fname)) return False elif map_type == 'FMRI': # fname = op.join(current_root_path, 'fmri_{}{}.npy'.format('clusters_' if clusters else '', hemi)) # f = np.load(fname) if clusters: f = [c for h, c in ColoringMakerPanel.fMRI_clusters.items() if h == hemi] else: f = ColoringMakerPanel.fMRI[hemi] cur_obj = bpy.data.objects[hemi] # loop_indices[hemi] = activity_map_obj_coloring(cur_obj, f, faces_verts[hemi], threshold, override_current_mat) if plot_subcorticals and not bpy.context.scene.objects_show_hide_sub_cortical: if map_type == 'MEG': if not bpy.data.objects['Subcortical_meg_activity_map'].hide: color_object_homogeneously(meg_sub_activity, '_meg_activity', threshold) if map_type == 'FMRI': fmri_subcortex_activity_color(threshold, override_current_mat) return True
def grab_camera(self=None, do_save=True): RenderFigure.update_camera = False bpy.context.scene.X_rotation = X_rotation = math.degrees(bpy.data.objects['Camera'].rotation_euler.x) bpy.context.scene.Y_rotation = Y_rotation = math.degrees(bpy.data.objects['Camera'].rotation_euler.y) bpy.context.scene.Z_rotation = Z_rotation = math.degrees(bpy.data.objects['Camera'].rotation_euler.z) bpy.context.scene.X_location = X_location = bpy.data.objects['Camera'].location.x bpy.context.scene.Y_location = Y_location = bpy.data.objects['Camera'].location.y bpy.context.scene.Z_location = Z_location = bpy.data.objects['Camera'].location.z if do_save: if op.isdir(op.join(mu.get_user_fol(), 'camera')): camera_fname = op.join(mu.get_user_fol(), 'camera', 'camera.pkl') mu.save((X_rotation, Y_rotation, Z_rotation, X_location, Y_location, Z_location), camera_fname) print('Camera location was saved to {}'.format(camera_fname)) else: mu.message(self, "Can't find the folder {}".format(mu.get_user_fol(), 'camera')) RenderFigure.update_camera = True
def fmri_files_update(self, context): #todo: there are two frmi files list (the other one in fMRI panel) user_fol = mu.get_user_fol() # fmri_files = glob.glob(op.join(user_fol, 'fmri', '*_lh.npy')) for hemi in mu.HEMIS: fname = op.join(user_fol, 'fmri', 'fmri_{}_{}.npy'.format(bpy.context.scene.fmri_files, hemi)) ColoringMakerPanel.fMRI[hemi] = np.load(fname)
def init(addon): LoadResultsPanel.addon = addon mu.make_dir(op.join(mu.get_user_fol(), 'meg')) bpy.context.scene.nii_label_prompt = '' bpy.context.scene.nii_label_output = '' register() LoadResultsPanel.init = True
def invoke(self, context, event=None): root = mu.get_user_fol() if bpy.context.scene.fMRI_files_exist and bpy.context.scene.freeview_load_fMRI: sig_fnames = glob.glob(op.join(root, 'freeview', '*{}*.mgz'.format(bpy.context.scene.fmri_files))) + \ glob.glob(op.join(root, 'freeview', '*{}*.nii'.format(bpy.context.scene.fmri_files))) if len(sig_fnames) > 0: sig_fname = sig_fnames[0] sig_cmd = '-v "{}":colormap=heat:heatscale=2,3,6'.format(sig_fname) if op.isfile(sig_fname) else '' else: sig_cmd = '' else: sig_cmd = '' T1 = op.join(root, 'freeview', 'T1.mgz') # sometimes 'orig.mgz' is better aseg = op.join(root, 'freeview', '{}+aseg.mgz'.format(bpy.context.scene.atlas)) lut = op.join(root, 'freeview', '{}ColorLUT.txt'.format(bpy.context.scene.atlas)) electrodes_cmd = self.get_electrodes_command(root) cmd = '{} {} "{}":opacity=0.3 "{}":opacity=0.05:colormap=lut:lut="{}"{}{}{}'.format( FreeviewPanel.addon_prefs.freeview_cmd, sig_cmd, T1, aseg, lut, electrodes_cmd, ' -verbose' if FreeviewPanel.addon_prefs.freeview_cmd_verbose else '', ' -stdin' if FreeviewPanel.addon_prefs.freeview_cmd_stdin else '') print(cmd) FreeviewPanel.freeview_in_queue, FreeviewPanel.freeview_out_queue = mu.run_command_in_new_thread(cmd) context.window_manager.modal_handler_add(self) self._updating = False self._timer = context.window_manager.event_timer_add(0.1, context.window) return {'RUNNING_MODAL'}
def find_closest_label(atlas=None, plot_contour=True): subjects_dir = mu.get_link_dir(mu.get_links_dir(), 'subjects') if bpy.context.scene.cursor_is_snapped: vertex_ind, hemi = _addon().get_closest_vertex_and_mesh_to_cursor() else: closest_mesh_name, vertex_ind, _ = \ _addon().find_closest_vertex_index_and_mesh(use_shape_keys=True) hemi = closest_mesh_name[len('infalted_'):] if _addon().is_inflated() else closest_mesh_name if vertex_ind == -1: print("find_closest_label: Can't find the closest vertex") return hemi = 'rh' if 'rh' in hemi else 'lh' if atlas is None: atlas = bpy.context.scene.subject_annot_files annot_fname = op.join(subjects_dir, mu.get_user(), 'label', '{}.{}.annot'.format(hemi, atlas)) if not op.isfile(annot_fname): annot_fname = op.join(mu.get_user_fol(), 'labels', '{}.{}.annot'.format(hemi, atlas)) if op.isfile(annot_fname): labels = mu.read_labels_from_annot(annot_fname) vert_labels = [l for l in labels if vertex_ind in l.vertices] if len(vert_labels) > 0: label = vert_labels[0] bpy.context.scene.closest_label_output = label.name if plot_contour: plot_closest_label_contour(label, hemi) return label.name else: print("Can't find the annotation file for atlas {}!".format(atlas))
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 run_ela_alg(): mmvt_code_fol = mu.get_mmvt_code_root() ela_code_fol = op.join(mu.get_parent_fol(mmvt_code_fol), 'electrodes_rois') if not op.isdir(ela_code_fol) or not op.isfile(op.join(ela_code_fol, 'find_rois', 'find_rois.py')): print("Can't find ELA folder!") return import importlib import sys if ela_code_fol not in sys.path: sys.path.append(ela_code_fol) from find_rois import find_rois importlib.reload(find_rois) args = find_rois.get_args(['-s', mu.get_user(), '-a', bpy.context.scene.ela_atlas, '-b', str(bpy.context.scene.ela_bipolar)]) find_rois.run_for_all_subjects(args) import shutil ela_output_fname_template = op.join( ela_code_fol, 'electrodes', '{}_{}_electrodes_cigar_r_*_l_*{}.pkl'.format( mu.get_user(), bpy.context.scene.ela_atlas, '_bipolar' if bpy.context.scene.ela_bipolar else '' )) ela_output_fnames = glob.glob(ela_output_fname_template) if len(ela_output_fnames) > 0: for ela_output_fname in ela_output_fnames: shutil.copyfile(ela_output_fname, op.join( mu.get_user_fol(), 'electrodes', mu.namebase_with_ext(ela_output_fname))) else: print('couldn\'t find any ELA output! ({})'.format(ela_output_fname_template)) init(_addon(), False)
def init_plotting(): stat = 'avg' if bpy.context.scene.selection_type == 'conds' else 'diff' fol = op.join(mu.get_user_fol(), 'electrodes') bip = 'bipolar_' if bpy.context.scene.bipolar else '' data_meta_fname = op.join(fol, 'electrodes_{}data.npz'.format(bip)) data_fname = op.join(fol, 'electrodes_{}data.npy'.format(bip)) meta_fname = op.join(fol, 'electrodes_{}meta_data.npz'.format(bip)) d = None if op.isfile(data_meta_fname): d = np.load(data_meta_fname) PlayPanel.electrodes_data = d['data'] # if 'colors' in d: # PlayPanel.electrodes_colors = d['colors'] elif op.isfile(meta_fname) and op.isfile(data_fname): d = np.load(meta_fname) PlayPanel.electrodes_data = np.load(data_fname) # PlayPanel.electrodes_colors = np.load(colors_fname) else: print('No electrodes data file!') if not d is None: PlayPanel.electrodes_names = [elc.astype(str) for elc in d['names']] data_min = np.mean(PlayPanel.electrodes_data) data_max = np.max(PlayPanel.electrodes_data) data_minmax = max(map(abs, [data_max, data_min])) PlayPanel.electrodes_data_max = data_minmax PlayPanel.electrodes_data_min = -data_minmax PlayPanel.electrodes_colors_ratio = 256 / (2 * data_minmax) # Warning: Not sure why we call this line, it changes the brain to the rendered brain # _addon().init_activity_map_coloring('MEG') PlayPanel.faces_verts = _addon().get_faces_verts() PlayPanel.meg_sub_activity = _addon().load_meg_subcortical_activity() bpy.context.scene.save_images = False bpy.context.scene.render_movie = False
def _electrodes_labeling_files_update(): labeling_fname = op.join( mu.get_user_fol(), 'electrodes', '{}.pkl'.format(bpy.context.scene.electrodes_labeling_files)) ElecsPanel.electrodes_locs = mu.load(labeling_fname) ElecsPanel.lookup = create_lookup_table(ElecsPanel.electrodes_locs, ElecsPanel.all_electrodes)
def create_slices(modality=None, pos=None, zoom_around_voxel=None, zoom_voxels_num=-1, smooth=None, clim=None, plot_cross=None, mark_voxel=None, pos_in_vox=False): if zoom_around_voxel is None: zoom_around_voxel = bpy.context.scene.slices_zoom_around_voxel if zoom_voxels_num == -1: zoom_voxels_num = bpy.context.scene.slices_zoom_voxels_num if smooth is None: smooth = bpy.context.scene.slices_zoom_interpolate if clim is None: clim = (bpy.context.scene.slices_x_min, bpy.context.scene.slices_x_max) if plot_cross is None: plot_cross = bpy.context.scene.slices_plot_cross if mark_voxel is None: mark_voxel = bpy.context.scene.slices_mark_voxel if WhereAmIPanel.slicer_state.mri is None: return if modality is None: modality = bpy.context.scene.slices_modality pos_was_none = pos is None if pos is None: pos = bpy.context.scene.cursor_location * 10 # if bpy.context.scene.cursor_is_snapped and pos_was_none: # pos = calc_tkreg_ras_from_snapped_cursor() if pos_was_none: pos = calc_tkreg_ras_from_cursor() if pos is None: print("Can't calc slices if the cursor isn't snapped and the brain is inflated!") return # pos = np.array(pos) * 10 if WhereAmIPanel.run_slices_listener: init_listener() xyz = ','.join(map(str, pos)) ret = mu.conn_to_listener.send_command(dict(cmd='slice_viewer_change_pos', data=dict( subject=mu.get_user(), xyz=xyz, modalities=modality, coordinates_system='tk_ras'))) flag_fname = op.join(mu.get_user_fol(), 'figures', 'slices', '{}_slices.txt'.format( '_'.join(modality.split(',')))) bpy.ops.mmvt.wait_for_slices() return if WhereAmIPanel.mri_data is None or WhereAmIPanel.gray_colormap is None: print('To be able to see the slices, you need to do the following:') if WhereAmIPanel.mri_data is None: print('python -m src.preproc.anatomy -s {} -f save_images_data_and_header'.format(mu.get_user())) if WhereAmIPanel.gray_colormap is None: print('python -m src.setup -f copy_resources_files') return if modality in ('mri', 't1_ct'): x, y, z = np.rint(apply_trans(t1_trans().ras_tkr2vox, np.array([pos]))[0]).astype(int) if not pos_in_vox else pos elif modality == 't2': x, y, z = np.rint(apply_trans(t2_trans().ras_tkr2vox, np.array([pos]))[0]).astype(int) if not pos_in_vox else pos elif modality == 'ct': vox = apply_trans(t1_trans().ras_tkr2vox, np.array([pos]))[0] if not pos_in_vox else pos ras = apply_trans(t1_trans().vox2ras, np.array([vox]))[0] x, y, z = np.rint(apply_trans(_ct_trans().ras2vox, np.array([ras]))[0]).astype(int) xyz = [x, y, z] # print('Create slices, slicer_state.coordinates: {}'.format(WhereAmIPanel.slicer_state.coordinates)) create_slices_from_vox_coordinates(xyz, modality, zoom_around_voxel, zoom_voxels_num, smooth, clim, plot_cross, mark_voxel)
def update_slices(modality='mri', ratio=1, images=None): screen = bpy.data.screens['Neuro'] perspectives = ['sagital', 'coronal', 'axial'] images_names = ['{}.{}'.format(pres, _addon().get_figure_format()) for pres in perspectives] images_fol = op.join(mu.get_user_fol(), 'figures', 'slices') ind = 0 for area in screen.areas: if area.type == 'IMAGE_EDITOR': override = bpy.context.copy() override['area'] = area override["screen"] = screen if images is None: if images_names[ind] not in bpy.data.images: bpy.data.images.load(op.join(images_fol, images_names[ind]), check_existing=False) area.spaces.active.mode = 'MASK' # bpy.data.images[images_names[ind]].reload() image = bpy.data.images[images_names[ind]] image.reload() else: image = images[perspectives[ind]] if area.spaces.active.mode != 'MASK': area.spaces.active.mode = 'MASK' area.spaces.active.image = image # bpy.ops.image.replace(override, filepath=op.join(images_fol, images_names[ind])) # Takes ~1s, should find a better way to do it (if at all) # bpy.ops.image.view_zoom_ratio(override, ratio=ratio) ind += 1
def save_cycle(): if bpy.context.scene.save_streaming: streaming_fol = datetime.strftime(datetime.now(), '%Y-%m-%d') output_fol = op.join(mu.get_user_fol(), 'electrodes', 'streaming', streaming_fol) output_fname = 'streaming_data_{}.npy'.format(datetime.strftime(datetime.now(), '%H-%M-%S')) mu.make_dir(output_fol) np.save(op.join(output_fol, output_fname), StreamingPanel.cycle_data)
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 draw(self, context): layout = self.layout user_fol = mu.get_user_fol() aparc_name = bpy.context.scene.atlas faces_verts_exist = mu.hemi_files_exists(op.join(user_fol, 'faces_verts_{hemi}.npy')) fmri_files = glob.glob(op.join(user_fol, 'fmri', '*_lh.npy')) # mu.hemi_files_exists(op.join(user_fol, 'fmri_{hemi}.npy')) # fmri_clusters_files_exist = mu.hemi_files_exists(op.join(user_fol, 'fmri', 'fmri_clusters_{hemi}.npy')) meg_files_exist = mu.hemi_files_exists(op.join(user_fol, 'activity_map_{hemi}', 't0.npy')) meg_labels_files_exist = op.isfile(op.join(user_fol, 'labels_vertices_{}.pkl'.format(aparc_name))) and \ mu.hemi_files_exists(op.join(user_fol, 'meg_labels_coloring_{hemi}.npz')) electrodes_files_exist = op.isfile(op.join(mu.get_user_fol(), 'electrodes', 'electrodes_data_{}.npz'.format( 'avg' if bpy.context.scene.selection_type == 'conds' else 'diff'))) electrodes_stim_files_exist = len(glob.glob(op.join( mu.get_user_fol(), 'electrodes', 'stim_electrodes_*.npz'))) > 0 electrodes_labels_files_exist = len(glob.glob(op.join( mu.get_user_fol(), 'electrodes', '*_labels_*.npz'))) > 0 and \ len(glob.glob(op.join(mu.get_user_fol(), 'electrodes', '*_subcortical_*.npz'))) > 0 manually_color_files_exist = len(glob.glob(op.join(user_fol, 'coloring', '*.csv'))) > 0 manually_groups_file_exist = op.isfile(op.join(mu.get_parent_fol(user_fol), '{}_groups.csv'.format(bpy.context.scene.atlas))) volumetric_coloring_files_exist = len(glob.glob(op.join(user_fol, 'coloring', 'volumetric', '*.csv'))) layout.prop(context.scene, 'coloring_threshold', text="Threshold") if faces_verts_exist: if meg_files_exist: layout.operator(ColorMeg.bl_idname, text="Plot MEG ", icon='POTATO') # if meg_labels_files_exist: # layout.operator(ColorMegLabels.bl_idname, text="Plot MEG Labels ", icon='POTATO') if len(fmri_files) > 0: layout.prop(context.scene, "fmri_files", text="") layout.operator(ColorFmri.bl_idname, text="Plot fMRI ", icon='POTATO') if manually_color_files_exist: layout.prop(context.scene, "coloring_files", text="") layout.operator(ColorManually.bl_idname, text="Color Manually", icon='POTATO') if manually_groups_file_exist: layout.prop(context.scene, 'labels_groups', text="") layout.operator(ColorGroupsManually.bl_idname, text="Color Groups", icon='POTATO') if volumetric_coloring_files_exist: layout.prop(context.scene, "vol_coloring_files", text="") layout.operator(ColorVol.bl_idname, text="Color Volumes", icon='POTATO') if electrodes_files_exist: layout.operator(ColorElectrodes.bl_idname, text="Plot Electrodes", icon='POTATO') if electrodes_labels_files_exist: layout.prop(context.scene, "electrodes_sources_files", text="") layout.operator(ColorElectrodesLabels.bl_idname, text="Plot Electrodes Sources", icon='POTATO') if electrodes_stim_files_exist: layout.operator(ColorElectrodesStim.bl_idname, text="Plot Electrodes Stimulation", icon='POTATO') layout.operator(ClearColors.bl_idname, text="Clear", icon='PANEL_CLOSE')
def get_meg_labels_data(): meg_data, meg_colors = OrderedDict(), OrderedDict() for hemi in HEMIS: labels_data = np.load(os.path.join(mu.get_user_fol(), 'meg_labels_coloring_{}.npz'.format(hemi))) for label_data, label_colors, label_name in zip(labels_data['data'], labels_data['colors'], labels_data['names']): meg_data[label_name] = label_data meg_colors[label_name] = label_colors return meg_data, meg_colors
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 get_elecctrodes_sources(): labels_fname = op.join(mu.get_user_fol(), 'electrodes', '{}-{}.npz'.format( bpy.context.scene.electrodes_sources_files, '{hemi}')) subcorticals_fname = labels_fname.replace('labels', 'subcortical').replace('-{hemi}', '') electrodes_sources_labels_data = \ {hemi:np.load(labels_fname.format(hemi=hemi)) for hemi in mu.HEMIS} electrodes_sources_subcortical_data = np.load(subcorticals_fname) return electrodes_sources_labels_data, electrodes_sources_subcortical_data
def electrodes_labeling_files_update(self, context): # if ElecsPanel.init: # todo: How to get the other file names? # list(bpy.types.Scene.electrodes_labeling_files[1].items())[3][1] labeling_fname = op.join(mu.get_user_fol(), 'electrodes', '{}.pkl'.format( bpy.context.scene.electrodes_labeling_files)) ElecsPanel.electrodes_locs = mu.load(labeling_fname) ElecsPanel.lookup = create_lookup_table(ElecsPanel.electrodes_locs, ElecsPanel.all_electrodes)
def invoke(self, context, event=None): mri_fname = op.join(mu.get_user_fol(), 'freeview', 'orig.mgz') cursor_position = np.array(bpy.context.scene.cursor_location) * 10.0 ret = mu.conn_to_listener.send_command(dict(cmd='open_slice_viewer',data=dict( mri_fname=mri_fname, position=cursor_position))) if not ret: mu.message(self, 'Listener was stopped! Try to restart') return {"FINISHED"}
def render_lateral_medial_split_brain(data_type='', quality=20, overwrite=True): image_name = ['lateral_lh', 'lateral_rh', 'medial_lh', 'medial_rh'] camera = [op.join(mu.get_user_fol(), 'camera', 'camera_{}{}.pkl'.format( camera_name, '_inf' if _addon().is_inflated() else '')) for camera_name in image_name] image_name = ['{}{}_{}_{}'.format('{}_'.format(data_type) if data_type != '' else '', name, 'inflated_{}'.format( _addon().get_inflated_ratio()) if _addon().is_inflated() else 'pial', bpy.context.scene.background_color) for name in image_name] render_image(image_name, quality=quality, camera_fname=camera, hide_subcorticals=True, overwrite=overwrite)
def add_data_to_brain(base_path='', files_prefix='', objs_prefix=''): if base_path == '': base_path = mu.get_user_fol() source_files = [op.join(base_path, '{}labels_data_lh.npz'.format(files_prefix)), op.join(base_path, '{}labels_data_rh.npz'.format(files_prefix)), op.join(base_path, '{}sub_cortical_activity.npz'.format(files_prefix))] print('Adding data to Brain') number_of_maximal_time_steps = -1 obj_counter = 0 conditions = [] for input_file in source_files: if not op.isfile(input_file): mu.message(None, '{} does not exist!'.format(input_file)) continue f = np.load(input_file) print('{} loaded'.format(input_file)) number_of_maximal_time_steps = max(number_of_maximal_time_steps, len(f['data'][0])) for obj_name, data in zip(f['names'], f['data']): # print('in label loop') obj_name = obj_name.astype(str) if not bpy.context.scene.import_unknown and 'unknown' in obj_name: continue obj_name = '{}{}'.format(objs_prefix, obj_name) print(obj_name) cur_obj = bpy.data.objects[obj_name] # print('cur_obj name = '+cur_obj.name) for cond_ind, cond_str in enumerate(f['conditions']): # cond_str = str(cond_str) # if cond_str[1] == "'": # cond_str = cond_str[2:-1] cond_str = cond_str.astype(str) # Set the values to zeros in the first and last frame for current object(current label) mu.insert_keyframe_to_custom_prop(cur_obj, obj_name + '_' + cond_str, 0, 1) mu.insert_keyframe_to_custom_prop(cur_obj, obj_name + '_' + cond_str, 0, len(f['data'][0]) + 2) print('keyframing ' + obj_name + ' object') # For every time point insert keyframe to current object for ind, timepoint in enumerate(data[:, cond_ind]): # print('keyframing '+obj_name+' object') mu.insert_keyframe_to_custom_prop(cur_obj, obj_name + '_' + cond_str, timepoint, ind + 2) # remove the orange keyframe sign in the fcurves window fcurves = bpy.data.objects[obj_name].animation_data.action.fcurves[cond_ind] mod = fcurves.modifiers.new(type='LIMITS') conditions.extend(f['conditions']) try: bpy.ops.graph.previewrange_set() except: pass bpy.types.Scene.maximal_time_steps = number_of_maximal_time_steps for obj in bpy.data.objects: obj.select = False if bpy.data.objects.get(' '): bpy.context.scene.objects.active = bpy.data.objects[' '] selection_panel.set_conditions_enum(conditions) print('Finished keyframing!!')
def init(addon): import shutil ElecsPanel.addon = addon ElecsPanel.parent = bpy.data.objects.get('Deep_electrodes') if ElecsPanel.parent is None or len(ElecsPanel.parent.children) == 0: print("!!!! Can't register electrodes panel, no Deep_electrodes object!!!!") return mu.make_dir(op.join(mu.get_user_fol(), 'electrodes')) sorted_groups_fname = op.join(mu.get_user_fol(), 'electrodes', 'sorted_groups.pkl') if not op.isfile(sorted_groups_fname): # Try to get the file from the subject's root folder if op.isfile(op.join(mu.get_user_fol(), 'sorted_groups.pkl')): shutil.move(op.join(mu.get_user_fol(), 'sorted_groups.pkl'), sorted_groups_fname) else: print("!!!! Can't register electrodes panel, no sorted groups file!!!!") return ElecsPanel.sorted_groups = mu.load(sorted_groups_fname) ElecsPanel.groups_hemi = create_groups_hemi_lookup(ElecsPanel.sorted_groups) ElecsPanel.all_electrodes = [el.name for el in ElecsPanel.parent.children] ElecsPanel.groups = create_groups_lookup_table(ElecsPanel.all_electrodes) ElecsPanel.groups_first_electrode = find_first_electrode_per_group(ElecsPanel.all_electrodes) ElecsPanel.groups_electrodes = create_groups_electrodes_lookup(ElecsPanel.all_electrodes) init_leads_list() init_electrodes_list() init_electrodes_labeling(addon) addon.clear_colors_from_parent_childrens('Deep_electrodes') addon.clear_cortex() bpy.context.scene.show_only_lead = False bpy.context.scene.listen_to_keyboard = False bpy.context.scene.listener_is_running = False bpy.context.scene.show_lh_electrodes = True bpy.context.scene.show_rh_electrodes = True _electrodes_labeling_files_update() if not ElecsPanel.electrodes_locs or not ElecsPanel.lookup: if not ElecsPanel.electrodes_locs: print("!!! Can't find electrodes labeling files in user/electrdes!") if not ElecsPanel.lookup: print('No electrodes lookup table!') print("!!! Can't plot electrodes' probabilties !!!") if not ElecsPanel.groups or not ElecsPanel.groups_first_electrode or not ElecsPanel.sorted_groups or \ not ElecsPanel.groups_hemi or not ElecsPanel.groups_electrodes: print('Error in electrodes panel init!') else: register() ElecsPanel.init = True
def color_electrodes_stim(): ColoringMakerPanel.what_is_colored.add(WIC_ELECTRODES_STIM) threshold = bpy.context.scene.coloring_threshold stim_fname = 'stim_electrodes_{}.npz'.format(bpy.context.scene.stim_files.replace(' ', '_')) stim_data_fname = op.join(mu.get_user_fol(), 'electrodes', stim_fname) data = np.load(stim_data_fname) color_object_homogeneously(data, threshold=threshold) ColoringMakerPanel.addon.show_electrodes() ColoringMakerPanel.addon.change_to_rendered_brain()
def load_stim_data(): stim_fname = 'stim_electrodes_{}.npz'.format(bpy.context.scene.stim_files.replace(' ', '_')) stim_data_fname = op.join(mu.get_user_fol(), 'electrodes', stim_fname) # todo: maybe create new electrodes in a different layer try: data_panel.add_data_to_electrodes([stim_data_fname]) except: print("Can't load the stim data!") load_conditions()
def init(addon): RenderingMakerPanel.addon = addon bpy.data.objects['Target'].rotation_euler.x = 0 bpy.data.objects['Target'].rotation_euler.y = 0 bpy.data.objects['Target'].rotation_euler.z = 0 bpy.data.objects['Target'].location.x = 0 bpy.data.objects['Target'].location.y = 0 bpy.data.objects['Target'].location.z = 0 mu.make_dir(op.join(mu.get_user_fol(), 'camera')) grab_camera() update_camera_files() # bpy.context.scene.lighting = 1.0 RenderingMakerPanel.queue = PriorityQueue() mu.make_dir(op.join(mu.get_user_fol(), 'logs')) logging.basicConfig( filename=op.join(mu.get_user_fol(), 'logs', 'reander_panel.log'), level=logging.DEBUG, format='%(asctime)-15s %(levelname)8s %(name)s %(message)s') register()