Exemple #1
0
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]])
Exemple #2
0
def grow_a_label():
    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
    subject, atlas = mu.get_user(), bpy.context.scene.subject_annot_files
    label_name, label_r = bpy.context.scene.new_label_name, bpy.context.scene.new_label_r
    flags = '-a {} --vertice_indice {} --hemi {} --label_name {} --label_r {}'.format(
        atlas, vertex_ind, hemi, label_name, label_r)
    mu.run_mmvt_func('src.preproc.anatomy', 'grow_label', flags=flags)
def load_surf_files(nii_fname, run_fmri_preproc=True, user_fol='', debug=True):
    fmri_file_template = ''
    if user_fol == '':
        user_fol = mu.get_user_fol()
    nii_fol = mu.get_fname_folder(nii_fname)
    if debug:
        print('load_surf_files: nii_fol: {}'.format(nii_fol))
    hemi, fmri_hemis = mu.get_hemi_from_full_fname(nii_fname)
    if debug:
        print('load_surf_files: hemi, fmri_hemis: {}, {}'.format(
            hemi, fmri_hemis))
    if hemi == '':
        hemi = mu.find_hemi_using_vertices_num(nii_fname)
        if hemi == '':
            return ''
    # fmri_hemis = mu.get_both_hemis_files(nii_fname)
    local_fname = build_local_fname(nii_fname, user_fol)
    if debug:
        print('load_surf_files: local_fname: {}'.format(local_fname))
    mu.make_dir(op.join(user_fol, 'fmri'))
    if nii_fol != op.join(user_fol, 'fmri'):
        mu.make_link(nii_fname, local_fname, True)
    other_hemi = mu.other_hemi(hemi)
    if debug:
        print('load_surf_files: other_hemi: {}'.format(other_hemi))
    other_hemi_fname = fmri_hemis[other_hemi]
    if debug:
        print('load_surf_files: other_hemi_fname: {}'.format(other_hemi_fname))
    # todo: if the other hemi file doens't exist, just create an empty one
    output_fname_template = ''
    if op.isfile(other_hemi_fname):
        local_other_hemi_fname = build_local_fname(other_hemi_fname, user_fol)
        if nii_fol != op.join(user_fol, 'fmri'):
            mu.make_link(other_hemi_fname, local_other_hemi_fname, True)
        fmri_file_template = mu.get_template_hemi_label_name(
            mu.namebase_with_ext(local_fname))
        if run_fmri_preproc:
            mu.add_mmvt_code_root_to_path()
            from src.preproc import fMRI
            importlib.reload(fMRI)
            ret, npy_output_fname_template = fMRI.load_surf_files(
                mu.get_user(), fmri_file_template)
            output_fname_template = op.join(
                mu.get_parent_fol(npy_output_fname_template),
                mu.namebase_with_ext(npy_output_fname_template)[len('fmri_'):])
        else:
            mu.run_mmvt_func(
                'src.preproc.fMRI',
                'load_surf_files',
                flags='--fmri_file_template "{}"'.format(fmri_file_template))
            # todo: find what should be the output_fname_template
    else:
        print(
            "Couldn't find the other hemi file! ({})".format(other_hemi_fname))
    return output_fname_template  #, hemi, other_hemi
Exemple #4
0
def open_freeview():
    root = mu.get_user_fol()
    sig_cmd = ''
    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 ''
    ct_cmd = ''
    if bpy.context.scene.freeview_load_CT:
        mmvt_ct_fname = op.join(root, 'ct', 'ct_reg_to_mr.mgz')
        if FreeviewPanel.CT_files_exist:
            ct_cmd = '-v "{}":opacity=0 '.format(mmvt_ct_fname)
        else:
            print("Can't find CT {}!".format(mmvt_ct_fname))
    dura_cmd = ''
    if bpy.context.scene.freeview_load_dura:
        dura_fname = FreeviewPanel.dura_srf_fname
        if FreeviewPanel.dura_srf_exist:
            dura_cmd = '-f "{}":edgecolor=blue "{}":edgecolor=blue '.format(
                dura_fname.format(hemi='rh'), dura_fname.format(hemi='lh'))
    T1 = op.join(root, 'freeview', 'T1.mgz')  # sometimes 'orig.mgz' is better
    if not op.isfile(T1):
        T1 = op.join(root, 'freeview', 'orig.mgz')
    if not op.isfile(T1):
        print(
            'No T1 / orig files in freeview folder. Running preproc.freeview')
        bpy.context.scene.freeview_messages = 'Preparing... Try to run again'
        cmd = '{} -m src.preproc.freeview -s {} -a {} -b {} --ignore_missing 1'.format(
            bpy.context.scene.python_cmd, mu.get_user(),
            bpy.context.scene.atlas, bpy.context.scene.bipolar)
        mu.run_command_in_new_thread(cmd, False)
        return {'RUNNING_MODAL'}
    bpy.context.scene.freeview_messages = ''
    aseg = op.join(root, 'freeview',
                   '{}+aseg.mgz'.format(bpy.context.scene.atlas))
    if op.isfile(aseg):
        lut = op.join(root, 'freeview',
                      '{}ColorLUT.txt'.format(bpy.context.scene.atlas))
        aseg_cmd = '"{}":opacity=0.05:colormap=lut:lut="{}"'.format(aseg, lut)
    else:
        aseg_cmd = ''
    electrodes_cmd = get_electrodes_command(root)
    cmd = '{} "{}":opacity=0.5 {}{}{}{}{}{}{}'.format(
        FreeviewPanel.addon_prefs.freeview_cmd, T1, aseg_cmd, electrodes_cmd,
        sig_cmd, ct_cmd, dura_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
    )  #, read_stderr=reading_freeview_stderr_func, read_stdin=reading_freeview_stdin_func,
Exemple #5
0
def grow_a_label():
    closest_mesh_name, vertex_ind, _, _ = \
        _addon().find_vertex_index_and_mesh_closest_to_cursor(use_shape_keys=True)
    hemi = closest_mesh_name[len('infalted_'):] if _addon().is_inflated(
    ) else closest_mesh_name
    subject, atlas = mu.get_user(), bpy.context.scene.subject_annot_files
    label_name, label_r = bpy.context.scene.new_label_name, bpy.context.scene.new_label_r
    cmd = '{} -m src.preproc.anatomy -s {} -a {} -f grow_label '.format(
        bpy.context.scene.python_cmd, subject, atlas)
    cmd += '--vertice_indice {} --hemi {} --label_name {} --label_r {}'.format(
        vertex_ind, hemi, label_name, label_r)
    mu.run_command_in_new_thread(cmd, False)
Exemple #6
0
def init(modality, modality_data=None, colormap=None, subject='', mmvt_dir=''):
    if subject == '':
        subject = mu.get_user()
    if mmvt_dir == '':
        mmvt_dir = mu.file_fol()
    if modality_data is None:
        if modality == 'mri':
            fname = op.join(mmvt_dir, subject, 'freeview', 'mri_data.npz')
        elif modality == 't2':
            fname = op.join(mmvt_dir, subject, 'freeview', 't2_data.npz')
        elif modality == 'ct':
            fname = op.join(mmvt_dir, subject, 'ct', 'ct_data.npz'.format(modality))
        if op.isfile(fname):
            modality_data = mu.Bag(np.load(fname))
        else:
            print('To see the slices the following command is being called:'.format(modality))
            print('python -m src.preproc.anatomy -s {} -f save_images_data_and_header'.format(mu.get_user()))
            mu.run_mmvt_func('src.preproc.anatom', 'save_subject_orig_trans,save_images_data_and_header')
            # cmd = '{} -m src.preproc.anatomy -s {} -f save_subject_orig_trans,save_images_data_and_header --ignore_missing 1'.format(
            #     bpy.context.scene.python_cmd, mu.get_user())
            # mu.run_command_in_new_thread(cmd, False, cwd=mu.get_mmvt_code_root())
            return None
    if colormap is None:
        if op.isfile(op.join(mmvt_dir, 'color_maps', 'gray.npy')):
            colormap_fname = op.join(mmvt_dir, 'color_maps', 'gray.npy')
            print("Can't find The gray colormap!")
        else:
            colormap_fname = glob.glob(op.join(mmvt_dir, 'color_maps', '*.npy'))[0]
        colormap = np.load(colormap_fname)
    affine = np.array(modality_data.affine, float)
    data = modality_data.data
    clim = modality_data.precentiles
    if IN_BLENDER:
        bpy.context.scene.slices_x_min, bpy.context.scene.slices_x_max = clim
    colors_ratio = modality_data.colors_ratio
    codes = axcodes2ornt(aff2axcodes(affine))
    order = np.argsort([c[0] for c in codes])
    print(modality, order)
    flips = np.array([c[1] < 0 for c in codes])[order]
    flips[0] = not flips[0]
    sizes = [data.shape[order] for order in order]
    scalers = voxel_sizes(affine)
    r = [scalers[order[2]] / scalers[order[1]],
         scalers[order[2]] / scalers[order[0]],
         scalers[order[1]] / scalers[order[0]]]
    extras = [0] * 3
    pial_vol_mask_fname = op.join(mmvt_dir, subject, 'freeview', 'pial_vol_mask.npy')
    pial_vol_mask = np.load(pial_vol_mask_fname) if op.isfile(pial_vol_mask_fname) else None
    self = mu.Bag(dict(
        data=data, affine=affine, order=order, sizes=sizes, flips=flips, clim=clim, r=r, colors_ratio=colors_ratio,
        colormap=colormap, coordinates=[], modality=modality, extras=extras, pial_vol_mask=pial_vol_mask))
    return self
Exemple #7
0
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())
Exemple #8
0
def export_electrodes():
    import csv
    output_fol = op.join(mu.get_user_fol(), 'electrodes')
    subject = mu.get_user()
    csv_fname = op.join(output_fol, '{}_RAS.csv'.format(subject))
    with open(csv_fname, 'w') as csv_file:
        wr = csv.writer(csv_file, quoting=csv.QUOTE_NONE)
        wr.writerow(['Electrode Name', 'R', 'A', 'S'])
        for group, electrodes  in ElecsPanel.groups_electrodes.items():
            for elc_name in electrodes:
                coords = get_elc_pos(elc_name) * 10
                wr.writerow([elc_name, *['{:.2f}'.format(loc) for loc in coords]])
    print('The electrodes file was exported to {}'.format(csv_fname))
Exemple #9
0
 def invoke(self, context, event=None):
     subject = mu.get_user()
     threshold = bpy.context.scene.fmri_clustering_threshold
     contrast = bpy.context.scene.fmri_clusters_labels_files
     atlas = bpy.context.scene.atlas
     task = contrast.split('_')[0]
     context.window_manager.modal_handler_add(self)
     self._timer = context.window_manager.event_timer_add(0.1, context.window)
     mu.change_fol_to_mmvt_root()
     cmd = '{} -m src.preproc.fMRI_preproc -s {} -T {} -c {} -t {} -a {} -f find_clusters'.format(
         bpy.context.scene.python_cmd, subject, task, contrast, threshold, atlas)
     print('Running {}'.format(cmd))
     self.in_q, self.out_q = mu.run_command_in_new_thread(cmd)
     return {'RUNNING_MODAL'}
Exemple #10
0
 def invoke(self, context, event=None):
     subject = mu.get_user()
     threshold = bpy.context.scene.fmri_clustering_threshold
     contrast = bpy.context.scene.fmri_clusters_labels_files
     atlas = bpy.context.scene.atlas
     task = contrast.split('_')[0]
     context.window_manager.modal_handler_add(self)
     self._timer = context.window_manager.event_timer_add(0.1, context.window)
     mu.change_fol_to_mmvt_root()
     cmd = '{} -m src.preproc.fMRI_preproc -s {} -T {} -c {} -t {} -a {} -f find_clusters'.format(
         bpy.context.scene.python_cmd, subject, task, contrast, threshold, atlas)
     print('Running {}'.format(cmd))
     self.in_q, self.out_q = mu.run_command_in_new_thread(cmd)
     return {'RUNNING_MODAL'}
Exemple #11
0
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)
Exemple #12
0
def render_image(image_name='',
                 image_fol='',
                 quality=0,
                 use_square_samples=None,
                 render_background=None):
    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

    # print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
    print('use_square_samples: {}'.format(use_square_samples))
    # print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')

    cur_frame = bpy.context.scene.frame_current
    if image_name == '':
        image_name = 't{}'.format(cur_frame)
    image_fol = bpy.path.abspath(
        bpy.context.scene.output_path) if image_fol == '' else image_fol
    print('file name: {}'.format(op.join(image_fol, image_name)))
    bpy.context.scene.render.filepath = op.join(image_fol, image_name)
    # Render and save the rendered scene to file. ------------------------------
    print('Image quality:')
    print(bpy.context.scene.render.resolution_percentage)
    print("Rendering...")
    if not bpy.context.scene.render_background:
        bpy.ops.render.render(write_still=True)
    else:
        grab_camera()
        mu.change_fol_to_mmvt_root()
        electrode_marked = RenderingMakerPanel.addon.is_current_electrode_marked(
        )
        script = 'src.mmvt_addon.scripts.render_image'
        cmd = '{} -m {} -s {} -a {} -q {} -b {} '.format(
            bpy.context.scene.python_cmd, script, mu.get_user(), bpy.context.scene.atlas,
            bpy.context.scene.render.resolution_percentage, bpy.context.scene.bipolar) + \
            '--hide_lh {} --hide_rh {} --hide_subs {} --show_elecs {} --curr_elec {} --show_only_lead {} '.format(
            bpy.context.scene.objects_show_hide_lh, bpy.context.scene.objects_show_hide_rh,
            bpy.context.scene.objects_show_hide_sub_cortical, bpy.context.scene.appearance_show_electrodes_layer,
            bpy.context.scene.electrodes if electrode_marked else None,
            bpy.context.scene.show_only_lead if electrode_marked else None) + \
            '--show_connections {}'.format(
            RenderingMakerPanel.addon.connections_visible())
        print('Running {}'.format(cmd))
        mu.save_blender_file()
        mu.run_command_in_new_thread(cmd, queues=False)

    print("Finished")
Exemple #13
0
def create_slices(modalities='mri', pos=None):
    if WhereAmIPanel.slicer_state is None:
        return
    if pos is None:
        pos = bpy.context.scene.cursor_location
    if WhereAmIPanel.run_slices_listener:
        init_listener()
        xyz = ','.join(map(str, pos * 10))
        ret = mu.conn_to_listener.send_command(
            dict(cmd='slice_viewer_change_pos',
                 data=dict(subject=mu.get_user(),
                           xyz=xyz,
                           modalities=modalities,
                           coordinates_system='tk_ras')))
        flag_fname = op.join(
            mu.get_user_fol(), 'figures', 'slices',
            '{}_slices.txt'.format('_'.join(modalities.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

    pos = np.array(pos) * 10
    x, y, z = apply_trans(_trans().ras_tkr2vox,
                          np.array([pos])).astype(np.int)[0]
    xyz = [x, y, z]
    images = slicer.create_slices(xyz, WhereAmIPanel.slicer_state, 'mri')
    update_slices(modality='mri', ratio=1, images=images)
Exemple #14
0
def find_closest_label():
    subjects_dir = mu.get_link_dir(mu.get_links_dir(), 'subjects')
    closest_mesh_name, vertex_ind, vertex_co, _ = \
        _addon().find_vertex_index_and_mesh_closest_to_cursor(use_shape_keys=True)
    hemi = closest_mesh_name[len('infalted_'):] if _addon().is_inflated(
    ) else closest_mesh_name
    annot_fname = op.join(
        subjects_dir, mu.get_user(), 'label',
        '{}.{}.annot'.format(hemi, bpy.context.scene.subject_annot_files))
    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
        return label.name, hemi
    else:
        return 'unknown', hemi
Exemple #15
0
def init(modality, modality_data=None, colormap=None):
    if modality_data is None:
        fname = op.join(mu.get_user_fol(), 'freeview',
                        '{}_data.npz'.format(modality))
        if op.isfile(fname):
            modality_data = mu.Bag(np.load(fname))
        else:
            print(
                'To see the slices you need to create the file {}_data.npz by calling:'
                .format(modality))
            print(
                'python -m src.preproc.anatomy -s {} -f save_images_data_and_header'
                .format(mu.get_user()))
            return None
    if colormap is None:
        colormap_fname = op.join(mu.file_fol(), 'color_maps', 'gray.npy')
        colormap = np.load(colormap_fname)
    affine = np.array(modality_data.affine, float)
    data = modality_data.data
    clim = modality_data.precentiles
    colors_ratio = modality_data.colors_ratio
    codes = axcodes2ornt(aff2axcodes(affine))
    order = np.argsort([c[0] for c in codes])
    flips = np.array([c[1] < 0 for c in codes])[order]
    flips[0] = not flips[0]
    sizes = [data.shape[order] for order in order]
    scalers = voxel_sizes(affine)
    r = [
        scalers[order[2]] / scalers[order[1]],
        scalers[order[2]] / scalers[order[0]],
        scalers[order[1]] / scalers[order[0]]
    ]
    self = mu.Bag(
        dict(data=data,
             affine=affine,
             order=order,
             sizes=sizes,
             flips=flips,
             clim=clim,
             r=r,
             colors_ratio=colors_ratio,
             colormap=colormap))
    return self
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()
Exemple #17
0
def find_elecrode_labeling_files():
    files = []
    blender_electrodes_names = set([o.name for o in bpy.data.objects['Deep_electrodes'].children])
    # labeling_template = '{}_{}_electrodes_cigar_r_*_l_*.pkl'.format(mu.get_user(), bpy.context.scene.atlas)
    labeling_template = '{}_*_electrodes_cigar_r_*_l_*.pkl'.format(mu.get_user(), bpy.context.scene.atlas)
    labling_files = glob.glob(op.join(mu.get_user_fol(), 'electrodes', labeling_template))
    for labling_file in labling_files:
        try:
            d = mu.load(labling_file)
            electrodes_names = set([e['name'] for e in d])
            # todo: find what is the problem... (mg96)
            # if len(electrodes_names - blender_electrodes_names) == 0:
            files.append(labling_file)
        except:
            print('Error reading {}'.format(labling_file))
            continue
    if len(files) == 0:
        print("Can't find any labeling file that match the electrodes names in{}!".format(
            op.join(mu.get_user_fol(), 'electrodes')))
    return files
Exemple #18
0
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
Exemple #19
0
def render_in_background(image_name, image_fol, camera_fname, hide_subcorticals, overwrite=True):
    hide_subs_in_background = True if hide_subcorticals else bpy.context.scene.objects_show_hide_sub_cortical
    mu.change_fol_to_mmvt_root()
    electrode_marked = _addon().is_current_electrode_marked()
    script = 'src.mmvt_addon.scripts.render_image'
    cmd = '{} -m {} -s {} -a {} -i {} -o {} -q {} -b {} -c "{}"'.format(
        bpy.context.scene.python_cmd, script, mu.get_user(), bpy.context.scene.atlas,
        image_name, image_fol, bpy.context.scene.render.resolution_percentage,
        bpy.context.scene.bipolar, camera_fname) + \
        ' --hide_lh {} --hide_rh {} --hide_subs {} --show_elecs {} --curr_elec {} --show_only_lead {}'.format(
        bpy.context.scene.objects_show_hide_lh, bpy.context.scene.objects_show_hide_rh,
        hide_subs_in_background, bpy.context.scene.show_hide_electrodes,
        bpy.context.scene.electrodes if electrode_marked else None,
        bpy.context.scene.show_only_lead if electrode_marked else None) + \
        ' --show_connections {}  --interactive 0  --overwrite {}'.format(
            _addon().connections_visible(), overwrite)
    print('Running {}'.format(cmd))
    RenderingMakerPanel.background_rendering = True
    mu.save_blender_file()
    _, RenderingMakerPanel.render_in_queue = mu.run_command_in_new_thread(
        cmd, read_stderr=False, read_stdin=False, stdout_func=reading_from_rendering_stdout_func)
Exemple #20
0
def load_surf_files(nii_fname):
    fmri_file_template = ''
    user_fol = mu.get_user_fol()
    nii_fol = mu.get_fname_folder(nii_fname)
    fmri_hemis = mu.get_both_hemis_files(nii_fname)
    hemi = mu.get_hemi_from_full_fname(nii_fname)
    local_fname = build_local_fname(nii_fname, user_fol)
    mu.make_dir(op.join(user_fol, 'fmri'))
    if nii_fol != op.join(user_fol, 'fmri'):
        mu.make_link(nii_fname, local_fname, True)
    other_hemi = mu.other_hemi(hemi)
    other_hemi_fname = fmri_hemis[other_hemi]
    if op.isfile(other_hemi_fname):
        local_other_hemi_fname = build_local_fname(other_hemi_fname, user_fol)
        if nii_fol != op.join(user_fol, 'fmri'):
            mu.make_link(other_hemi_fname, local_other_hemi_fname, True)
        fmri_file_template = mu.get_template_hemi_label_name(mu.namesbase_with_ext(local_fname))
        cmd = '{} -m src.preproc.fMRI -s {} -f load_surf_files --fmri_file_template "{}"'.format(
            bpy.context.scene.python_cmd, mu.get_user(), fmri_file_template)
        mu.run_command_in_new_thread(cmd, False)
    return fmri_file_template, hemi
Exemple #21
0
def render_in_background(image_name, image_fol, camera_fname, hide_subcorticals, overwrite=True):
    hide_subs_in_background = True if hide_subcorticals else bpy.context.scene.objects_show_hide_sub_cortical
    mu.change_fol_to_mmvt_root()
    electrode_marked = _addon().is_current_electrode_marked()
    script = 'src.mmvt_addon.scripts.render_image'
    cmd = '{} -m {} -s {} -a {} -i {} -o {} -q {} -b {} -c "{}"'.format(
        bpy.context.scene.python_cmd, script, mu.get_user(), bpy.context.scene.atlas,
        image_name, image_fol, bpy.context.scene.render.resolution_percentage,
        bpy.context.scene.bipolar, camera_fname) + \
        ' --hide_lh {} --hide_rh {} --hide_subs {} --show_elecs {} --curr_elec {} --show_only_lead {}'.format(
        bpy.context.scene.objects_show_hide_lh, bpy.context.scene.objects_show_hide_rh,
        hide_subs_in_background, bpy.context.scene.show_hide_electrodes,
        bpy.context.scene.electrodes if electrode_marked else None,
        bpy.context.scene.show_only_lead if electrode_marked else None) + \
        ' --show_connections {}  --interactive 0  --overwrite {}'.format(
            _addon().connections_visible(), overwrite)
    print('Running {}'.format(cmd))
    RenderingMakerPanel.background_rendering = True
    mu.save_blender_file()
    _, RenderingMakerPanel.render_in_queue = mu.run_command_in_new_thread(
        cmd, read_stderr=False, read_stdin=False, stdout_func=reading_from_rendering_stdout_func)
Exemple #22
0
def render_image(image_name='', image_fol='', quality=0, use_square_samples=None, render_background=None):
    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

    # print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')
    print('use_square_samples: {}'.format(use_square_samples))
    # print('@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@')

    cur_frame = bpy.context.scene.frame_current
    if image_name == '':
        image_name = 't{}'.format(cur_frame)
    image_fol = bpy.path.abspath(bpy.context.scene.output_path) if image_fol == '' else image_fol
    print('file name: {}'.format(op.join(image_fol, image_name)))
    bpy.context.scene.render.filepath = op.join(image_fol, image_name)
    # Render and save the rendered scene to file. ------------------------------
    print('Image quality:')
    print(bpy.context.scene.render.resolution_percentage)
    print("Rendering...")
    if not bpy.context.scene.render_background:
        bpy.ops.render.render(write_still=True)
    else:
        mu.change_fol_to_mmvt_root()
        electrode_marked = RenderingMakerPanel.addon.is_current_electrode_marked()
        script = 'src.mmvt_addon.scripts.render_image'
        cmd = '{} -m {} -s {} -a {} -q {} -b {} --hide_lh {} --hide_rh {} --hide_subs {} --show_elecs {} --curr_elec {} --show_only_lead {}'.format(
            bpy.context.scene.python_cmd, script, mu.get_user(), bpy.context.scene.atlas,
            bpy.context.scene.render.resolution_percentage, bpy.context.scene.bipolar,
            bpy.context.scene.objects_show_hide_lh, bpy.context.scene.objects_show_hide_rh,
            bpy.context.scene.objects_show_hide_sub_cortical, bpy.context.scene.appearance_show_electrodes_layer,
            bpy.context.scene.electrodes if electrode_marked else None,
            bpy.context.scene.show_only_lead if electrode_marked else None)
        print('Running {}'.format(cmd))
        mu.save_blender_file()
        mu.run_command_in_new_thread(cmd, queues=False)

    print("Finished")
Exemple #23
0
def color_manually():
    ColoringMakerPanel.what_is_colored.add(WIC_MANUALLY)
    init_activity_map_coloring('FMRI')
    subject_fol = mu.get_user_fol()
    objects_names, colors, data = defaultdict(list), defaultdict(list), defaultdict(list)
    for line in mu.csv_file_reader(op.join(subject_fol, 'coloring', '{}.csv'.format(bpy.context.scene.coloring_files))):
        obj_name, color_name = line[0], line[1:]
        if obj_name[0] == '#':
            continue
        if isinstance(color_name, list) and len(color_name) == 1:
            color_name = color_name[0]
        obj_type = mu.check_obj_type(obj_name)
        if isinstance(color_name, str) and color_name.startswith('mark'):
            import filter_panel
            filter_panel.filter_roi_func(obj_name, mark=color_name)
        else:
            if isinstance(color_name, str):
                color_rgb = cu.name_to_rgb(color_name)
            # Check if the color is already in RBG
            elif len(color_name) == 3:
                color_rgb = color_name
            else:
                print('Unrecognize color! ({})'.format(color_name))
                continue
            color_rgb = list(map(float, color_rgb))
            if obj_type is not None:
                objects_names[obj_type].append(obj_name)
                colors[obj_type].append(color_rgb)
                data[obj_type].append(1.)

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

    color_objects(objects_names, colors, data)
    if op.isfile(op.join(subject_fol, 'coloring', '{}_legend.jpg'.format(bpy.context.scene.coloring_files))):
        cmd = '{} -m src.preproc.electrodes_preproc -s {} -a {} -f show_labeling_coloring'.format(
            bpy.context.scene.python_cmd, mu.get_user(), bpy.context.scene.atlas)
        print('Running {}'.format(cmd))
        mu.run_command_in_new_thread(cmd, False)
Exemple #25
0
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())
Exemple #26
0
 def invoke(self, context, event=None):
     cmd = '{} -m src.preproc.anatomy_preproc -s {} -a {}'.format(
         bpy.context.scene.python_cmd, mu.get_user(), bpy.context.scene.atlas)
     print('Running {}'.format(cmd))
     mu.run_command_in_new_thread(cmd, False)
     return {"FINISHED"}
Exemple #27
0
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):
    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 == 'mri':
        x, y, z = np.rint(
            apply_trans(t1_trans().ras_tkr2vox,
                        np.array([pos]))[0]).astype(int)
    elif modality == 't2':
        x, y, z = np.rint(
            apply_trans(t2_trans().ras_tkr2vox,
                        np.array([pos]))[0]).astype(int)
    elif modality == 'ct':
        vox = apply_trans(t1_trans().ras_tkr2vox, np.array([pos]))[0]
        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)