Exemple #1
0
def transform_mni_to_subject(subject, subjects_dir, volue_fol, volume_fname='sig.mgz',
        subject_contrast_file_name='sig_subject.mgz', print_only=False):
    mni305_sig_file = os.path.join(volue_fol, volume_fname)
    subject_sig_file = os.path.join(volue_fol, subject_contrast_file_name)
    rs = utils.partial_run_script(locals(), print_only=print_only)
    rs(mni305_to_subject_reg)
    rs(mni305_to_subject)
    subject_fol = op.join(subjects_dir, subject, 'mmvt')
    utils.make_dir(subject_fol)
    shutil.move(op.join(utils.get_parent_fol(), 'mn305_to_{}.dat'.format(subject)),
                op.join(subject_fol, 'mn305_to_{}.dat'.format(subject)))
Exemple #2
0
def post_meg_preproc(args):
    inv_method, em = 'MNE', 'mean_flip'
    atlas = 'darpa_atlas'
    bands = dict(theta=[4, 8],
                 alpha=[8, 15],
                 beta=[15, 30],
                 gamma=[30, 55],
                 high_gamma=[65, 200])
    times = (-2, 4)

    subjects = args.subject
    res_fol = utils.make_dir(
        op.join(utils.get_parent_fol(MMVT_DIR), 'msit-ecr'))
    for subject in subjects:
        args.subject = subject
        for task in args.tasks:
            task = task.lower()
            if not utils.both_hemi_files_exist(
                    op.join(
                        MMVT_DIR, subject, 'meg',
                        'labels_data_{}_{}_{}_{}_lh.npz'.format(
                            task, atlas, inv_method, em, '{hemi}'))):
                print('label data can\'t be found for {} {}'.format(
                    subject, task))
                continue
            utils.make_dir(op.join(res_fol, subject))
            meg.calc_labels_func(subject,
                                 task,
                                 atlas,
                                 inv_method,
                                 em,
                                 tmin=0,
                                 tmax=0.5,
                                 times=times,
                                 norm_data=False)
            meg.calc_labels_mean_power_bands(subject,
                                             task,
                                             atlas,
                                             inv_method,
                                             em,
                                             tmin=times[0],
                                             tmax=times[1],
                                             overwrite=True)

        for fname in [
                f for f in glob.glob(
                    op.join(MMVT_DIR, subject, 'labels', 'labels_data', '*'))
                if op.isfile(f)
        ]:
            shutil.copyfile(
                fname, op.join(res_fol, subject,
                               utils.namebase_with_ext(fname)))
Exemple #3
0
def combine_two_figures_with_cb(fname1,
                                fname2,
                                data_max,
                                data_min,
                                cb_cm,
                                cb_ticks=[],
                                crop_figures=True,
                                background='black',
                                cb_ticks_font_size=10):
    if crop_figures:
        crop_image(fname1, fname1, dx=150, dy=0, dw=50, dh=70)
        crop_image(fname2, fname2, dx=150 + 50, dy=0, dw=0, dh=70)
    new_image_fname = op.join(
        utils.get_parent_fol(fname1),
        '{}_{}.{}'.format(utils.namebase(fname1), utils.namebase(fname2),
                          utils.file_type(fname1)))
    combine_two_images(fname1,
                       fname2,
                       new_image_fname,
                       facecolor=background,
                       dpi=400,
                       w_fac=1,
                       h_fac=1)
    if len(cb_ticks) == 0:
        cb_ticks = [data_min, data_max]
    fol = utils.get_parent_fol(fname1)
    plot_color_bar(data_max,
                   data_min,
                   cb_cm,
                   do_save=True,
                   cb_ticks=cb_ticks,
                   fol=fol,
                   background_color=background,
                   cb_ticks_font_size=cb_ticks_font_size)
    cb_fname = op.join(fol, '{}_colorbar.jpg'.format(cb_cm))
    cb_img = Image.open(cb_fname)
    return combine_brain_with_color_bar(new_image_fname,
                                        cb_img,
                                        overwrite=True)
Exemple #4
0
def call_script(script_fname,
                args,
                log_name='',
                blend_fname=None,
                call_args=None):
    if args.blender_fol == '':
        args.blender_fol = get_blender_dir()
    if not op.isdir(args.blender_fol):
        print('No Blender folder!')
        return

    logs_fol = utils.make_dir(
        op.join(utils.get_parent_fol(__file__, 4), 'logs'))
    if log_name == '':
        log_name = utils.namebase(script_fname)
    if len(args.subjects) == 0:
        args.subjects = [args.subject]
    for subject in args.subjects:
        args.subject = subject
        args.subjects = ''
        print('*********** {} ***********'.format(subject))
        if blend_fname is None:
            blend_fname = get_subject_fname(args)
        else:
            blend_fname = op.join(get_mmvt_dir(), blend_fname)
        if call_args is None:
            call_args = create_call_args(args)
        log_fname = op.join(logs_fol, '{}.log'.format(log_name))
        cmd = '{blender_exe} {blend_fname} --background --python "{script_fname}" {call_args}'.format(  # > {log_fname}
            blender_exe=op.join(args.blender_fol, 'blender'),
            blend_fname=blend_fname,
            script_fname=script_fname,
            call_args=call_args,
            log_fname=log_fname)
        mmvt_addon_fol = utils.get_parent_fol(__file__, 2)
        os.chdir(mmvt_addon_fol)
        print(cmd)
        utils.run_script(cmd)
    print('Finish! For more details look in {}'.format(log_fname))
Exemple #5
0
def project_on_surface(subject,
                       volume_file,
                       surf_output_fname,
                       target_subject=None,
                       overwrite_surf_data=False,
                       modality='fmri',
                       subjects_dir='',
                       mmvt_dir='',
                       **kargs):
    if target_subject is None:
        target_subject = subject
    if subjects_dir == '':
        subjects_dir = utils.get_link_dir(utils.get_links_dir(), 'subjects',
                                          'SUBJECTS_DIR')
    if mmvt_dir == '':
        mmvt_dir = utils.get_link_dir(utils.get_links_dir(), 'mmvt')
    utils.make_dir(op.join(mmvt_dir, subject, 'fmri'))
    os.environ['SUBJECTS_DIR'] = subjects_dir
    os.environ['SUBJECT'] = subject
    for hemi in utils.HEMIS:
        if not op.isfile(
                surf_output_fname.format(hemi=hemi)) or overwrite_surf_data:
            print('project {} to {}'.format(volume_file, hemi))
            if modality != 'pet':
                surf_data = project_volume_data(
                    volume_file,
                    hemi,
                    subject_id=subject,
                    surf="pial",
                    smooth_fwhm=3,
                    target_subject=target_subject,
                    output_fname=surf_output_fname.format(hemi=hemi))
            else:
                surf_data = project_pet_volume_data(
                    subject, volume_file, hemi,
                    surf_output_fname.format(hemi=hemi))
            nans = np.sum(np.isnan(surf_data))
            if nans > 0:
                print('there are {} nans in {} surf data!'.format(nans, hemi))
        surf_data = np.squeeze(
            nib.load(surf_output_fname.format(hemi=hemi)).get_data())
        output_fname = op.join(
            mmvt_dir, subject, modality,
            '{}_{}'.format(modality,
                           op.basename(surf_output_fname.format(hemi=hemi))))
        npy_output_fname = op.splitext(output_fname)[0]
        if not op.isfile(
                '{}.npy'.format(npy_output_fname)) or overwrite_surf_data:
            print('Saving surf data in {}.npy'.format(npy_output_fname))
            utils.make_dir(utils.get_parent_fol(npy_output_fname))
            np.save(npy_output_fname, surf_data)
Exemple #6
0
def transform_mni_to_subject(subject,
                             subjects_dir,
                             volue_fol,
                             volume_fname='sig.mgz',
                             subject_contrast_file_name='sig_subject.mgz',
                             print_only=False):
    mni305_sig_file = os.path.join(volue_fol, volume_fname)
    subject_sig_file = os.path.join(volue_fol, subject_contrast_file_name)
    rs = utils.partial_run_script(locals(), print_only=print_only)
    rs(mni305_to_subject_reg)
    rs(mni305_to_subject)
    subject_fol = op.join(subjects_dir, subject, 'mmvt')
    utils.make_dir(subject_fol)
    shutil.move(
        op.join(utils.get_parent_fol(), 'mn305_to_{}.dat'.format(subject)),
        op.join(subject_fol, 'mn305_to_{}.dat'.format(subject)))
Exemple #7
0
def calc_linda_surf(subject, atlas):
    # Check for Linda's output fname
    if not utils.both_hemi_files_exist(op.join(fmri.MMVT_DIR, subject, 'fmri', 'fmri_linda_{}.npy'.format('{hemi}'))) \
            and not op.isfile(op.join(fmri.MMVT_DIR, subject, 'fmri', 'linda_minmax.pkl')):
        # Find Linda's files
        linda_volume_fnames = glob.glob(
            op.join(linda_fol.format(subject=subject),
                    linda_vol_template.format(subject=subject)))
        linda_volume_folder = utils.get_parent_fol(linda_volume_fnames[0])
        # project linda files on the surface
        args = fmri.read_cmd_args(
            dict(subject=subject,
                 function='project_volume_to_surface',
                 remote_fmri_dir=linda_volume_folder,
                 fmri_file_template=linda_vol_template.format(subject=subject),
                 overwrite_surf_data=True))
        pu.run_on_subjects(args, fmri.main)
        # rename Linda's files
        linda_fnames = glob.glob(
            op.join(
                fmri.MMVT_DIR, subject, 'fmri',
                'fmri_{}'.format(linda_template_npy.format(subject=subject))))
        for fname in linda_fnames:
            hemi = lu.get_label_hemi(utils.namebase(fname))
            target_file = op.join(fmri.MMVT_DIR, subject, 'fmri',
                                  'fmri_linda_{}.npy'.format(hemi))
            if not op.isfile(target_file):
                os.rename(fname, target_file)
        # rename minmax file
        linda_minmax_name = '{}.pkl'.format(
            utils.namebase(
                glob.glob(
                    op.join(
                        fmri.MMVT_DIR, subject, 'fmri', '{}_minmax.pkl'.format(
                            utils.namebase(
                                linda_vol_template.format(
                                    subject=subject)))))[0]))
        os.rename(op.join(fmri.MMVT_DIR, subject, 'fmri', linda_minmax_name),
                  op.join(fmri.MMVT_DIR, subject, 'fmri', 'linda_minmax.pkl'))
        # delete mgz files
        mgz_files = glob.glob(
            op.join(
                fmri.MMVT_DIR, subject, 'fmri', 'fmri_{}_?h.mgz'.format(
                    utils.namebase(
                        linda_vol_template.format(subject=subject)))))
        for mgz_file in mgz_files:
            os.remove(mgz_file)
Exemple #8
0
def fix_amplitude_fnames(subject, bands):
    stcs_files = glob.glob(op.join(MMVT_DIR, subject, 'meg', '{}-epilepsy-*-zvals-?h.stc'.format(subject))) + \
                 glob.glob(op.join(MMVT_DIR, subject, 'eeg', '{}-epilepsy-*-zvals-?h.stc'.format(subject)))
    for stc_fname in stcs_files:
        stc_name = utils.namebase(
            stc_fname)[len('{}-epilepsy-'.format(subject)):-len('-zvals-lh')]
        if stc_name.endswith('amplitude'):
            continue
        if not any([stc_name.endswith(band) for band in bands]):
            stc_name += '_amplitude'
            stc_end = '-zvals-lh.stc' if stc_fname.endswith(
                '-zvals-lh.stc') else '-zvals-rh.stc'
            new_stc_fname = op.join(
                utils.get_parent_fol(stc_fname),
                '{}-epilepsy-{}{}'.format(subject, stc_name, stc_end))
            print('{} -> {}'.format(stc_fname, new_stc_fname))
            utils.rename_files(stc_fname, new_stc_fname)
Exemple #9
0
def main(html_template_fname, scan_fol, patient_name, task_name, mrn, scan_date, img_prefix=None,
         report_name_suffix='', output_fname=''):
    if utils.get_parent_fol(html_template_fname) != scan_fol:
        shutil.copy(html_template_fname, scan_fol)
    if output_fname == '':
        output_fname = op.join(scan_fol, '{}{}.pdf'.format(mrn, '_{}'.format(report_name_suffix) \
            if report_name_suffix != '' else ''))
    new_html_fname =  utils.change_fname_extension(output_fname, 'html')
    if img_prefix == 'auto':
        img_prefix = utils.find_common_start([utils.namebase(f) for f in glob.glob(op.join(scan_fol, '*.png'))])
        img_prefix = img_prefix[:-1] if img_prefix[-1] == '_' else img_prefix
        img_prefix = img_prefix[:-2] if img_prefix[-2:] == '_l' else img_prefix
    html = read_html(html_template_fname)
    html = replace_fields(html, patient_name, task_name, mrn, scan_date, img_prefix)
    create_new_html(html, new_html_fname)
    create_pdf(new_html_fname, output_fname)
    os.remove(op.join(scan_fol, utils.namebase_with_ext(html_template_fname)))
Exemple #10
0
def prepare_files(args):
    # todo: should look in the dict for files locations
    ret = {}
    for subject in args.subject:
        ret[subject] = True
        for task in args.tasks:
            fol = utils.make_dir(op.join(MEG_DIR, task, subject))
            local_epo_fname = op.join(
                fol, '{}_{}_Onset-epo.fif'.format(subject, task))
            local_raw_fname = op.join(fol,
                                      '{}_{}-raw.fif'.format(subject, task))
            if not args.overwrite and (op.islink(local_epo_fname) or op.isfile(local_epo_fname)) and \
                    (op.islink(local_raw_fname) or op.isfile(local_raw_fname)):
                continue

            if op.islink(local_epo_fname) or op.isfile(local_epo_fname):
                os.remove(local_epo_fname)
            remote_epo_fname = op.join(
                args.meg_dir, subject,
                '{}_{}_meg_Onset-epo.fif'.format(subject, task))
            if not op.isfile(remote_epo_fname):
                print('{} does not exist!'.format(remote_epo_fname))
                ret[subject] = False
                continue
            print('Creating a local link to {}'.format(remote_epo_fname))
            utils.make_link(remote_epo_fname, local_epo_fname)
            if op.islink(local_raw_fname) or op.isfile(local_raw_fname):
                os.remove(local_raw_fname)
            remote_raw_fname = op.join(
                utils.get_parent_fol(args.meg_dir), 'raw_preprocessed',
                subject, '{}_{}_meg_ica-raw.fif'.format(subject, task))
            if not op.isfile(remote_epo_fname):
                print('{} does not exist!'.format(remote_raw_fname))
                ret[subject] = False
                continue
            print('Creating a local link to {}'.format(remote_raw_fname))
            utils.make_link(remote_raw_fname, local_raw_fname)
        ret[subject] = ret[subject] and (op.isfile(local_epo_fname) or op.islink(local_epo_fname)) and \
                       (op.isfile(local_raw_fname) or op.islink(local_raw_fname))
    print('Good subjects:')
    print([s for s, r in ret.items() if r])
    print('Bad subjects:')
    print([s for s, r in ret.items() if not r])
def combine_brain_with_color_bar(image_fname, cb_img=None, w_offset=10, overwrite=False, cb_max=None, cb_min=None,
                                 cb_cm=None, background='black', cb_ticks=[], cb_ticks_font_size=10):
    if cb_img is None:
        if len(cb_ticks) == 0:
            cb_ticks = [cb_min, cb_max]
        fol = utils.get_parent_fol(image_fname)
        cb_fname = op.join(fol, '{}_colorbar.jpg'.format(cb_cm))
        plot_color_bar(cb_max, cb_min, cb_cm, do_save=True, cb_ticks=cb_ticks, fol=fol, background_color=background,
                       cb_ticks_font_size=cb_ticks_font_size)
        cb_img = Image.open(cb_fname)

    background = Image.open(image_fname)
    bg_w, bg_h = background.size
    cb_w, cb_h = cb_img.size
    offset = (int((bg_w - cb_w)) - w_offset, int((bg_h - cb_h) / 2))
    background.paste(cb_img, offset)
    if not overwrite:
        image_fol = utils.get_fname_folder(image_fname)
        image_fname = op.join(image_fol, '{}_cb.{}'.format(image_fname[:-4], image_fname[-3:]))
    background.save(image_fname)
    return image_fname
def compute_noise_cov(subject, hcp_path, noise_cov_fname=''):
    if noise_cov_fname == '':
        noise_cov_fname = meg.NOISE_COV.format(cond='empty_room')
    if op.isfile(noise_cov_fname):
        noise_cov = mne.read_cov(noise_cov_fname)
        return noise_cov
    utils.make_dir(utils.get_parent_fol(noise_cov_fname))

    raw_noise = hcp.read_raw(subject=subject, hcp_path=hcp_path, data_type='noise_empty_room')
    raw_noise.load_data()
    # apply ref channel correction and drop ref channels
    preproc.apply_ref_correction(raw_noise)
    raw_noise.filter(0.50, None, method='iir',
                     iir_params=dict(order=4, ftype='butter'), n_jobs=1)
    raw_noise.filter(None, 60, method='iir',
                     iir_params=dict(order=4, ftype='butter'), n_jobs=1)
    ##############################################################################
    # Note that using the empty room noise covariance will inflate the SNR of the
    # evkoked and renders comparisons  to `baseline` rather uninformative.
    noise_cov = mne.compute_raw_covariance(raw_noise, method='empirical')
    noise_cov.save(noise_cov_fname)
    return noise_cov
Exemple #13
0
def project_and_calc_clusters(args):
    if not op.isdir(args.root_fol):
        print('You should first set args.root_fol!')
        return False
    img_files = [f for f in glob.glob(op.join(args.root_fol, '*.img')) if op.isfile(f)]
    for img_fname in img_files:
        mgz_fname = fu.mri_convert_to(img_fname, 'mgz', overwrite=False)
        if ' ' in utils.namebase(mgz_fname):
            mgz_new_fname = op.join(
                utils.get_parent_fol(mgz_fname),
                utils.namebase_with_ext(mgz_fname).replace(' ', '_').replace(',', '').lower())
            os.rename(mgz_fname, mgz_new_fname)
    nii_files = [f for f in glob.glob(op.join(args.root_fol, '*'))
                 if op.isfile(f) and utils.file_type(f) in ('nii', 'nii.gz', 'mgz')]
    for fname in nii_files:
        fmri_args = fmri.read_cmd_args(dict(
            subject=args.subject,
            function='project_volume_to_surface,find_clusters',
            fmri_file_template=fname,
            threshold=args.cluster_threshold
        ))
        pu.run_on_subjects(fmri_args, fmri.main)
Exemple #14
0
def trans_tal_coords(roi,
                     file_name,
                     subjects_dir,
                     template='colin27',
                     overwrite=False):
    subjects = {}
    output_fol = utils.make_dir(op.join(MMVT_DIR, template, 'rois_peaks'))
    csv_fname = op.join(output_fol, '{}.csv'.format(roi))
    pkl_fname = op.join(output_fol, '{}.pkl'.format(roi))
    if op.isfile(pkl_fname) and op.isfile(csv_fname) and not overwrite:
        print('Data already exist for {}'.format(roi))
        return
    driver = tu.yale_get_driver()
    files = list(utils.find_recursive(subjects_dir, file_name))
    for fname in tqdm(files):
        lines = list(utils.csv_file_reader(fname, delimiter=' '))
        subject = utils.namebase(utils.get_parent_fol(fname, 3))
        subjects[subject] = {}
        if len(lines) == 0:
            print()
            subjects[subject]['error'] = '{} is empty!'.format(fname)
            continue
        elif len(lines) > 1:
            print('More than one line in {}!'.format(fname))
            subjects[subject] = '>1'
            continue
        tal = [int(float(v)) for v in lines[0] if utils.is_float(v)]
        subjects[subject]['tal'] = tal
        subjects[subject]['mni'] = tu.yale_tal2mni(tal, driver)
    del driver
    print(subjects)
    with open(csv_fname, 'w') as csv_file:
        csv_writer = csv.writer(csv_file, delimiter=',')
        for subject, subject_data in subjects.items():
            if 'mni' in subject_data:
                csv_writer.writerow(subjects[subject]['mni'])
    utils.save(subjects, pkl_fname)
Exemple #15
0
def remove_large_negative_values_from_ct(ct_fname,
                                         new_ct_fname='',
                                         threshold=-200,
                                         overwrite=False):
    '''
    Opens the CT, checks for values less than threshold. Sets all values less than
    threshold to threshold instead. This is helpful for registration as extremely 
    large negative values present in the CT but not in the MR skew the mutual
    information algorithm.

    Parameters
    ----------
    ct_fname : Str
        The filename containing the CT scan
    new_ct_fname: Str
        The output fname
    '''
    if not op.isfile(ct_fname):
        print(f'The CT could not be found in {ct_fname}!')
        return ''
    if new_ct_fname == '':
        new_ct_fname = op.join(utils.get_parent_fol(ct_fname),
                               'ct_no_large_negative_values.mgz')
    if op.isfile(new_ct_fname):
        if overwrite:
            os.remove(new_ct_fname)
        else:
            return new_ct_fname
    h = nib.load(ct_fname)
    ct_data = h.get_data()
    ct_data[ct_data < threshold] = threshold
    ct_new = nib.Nifti1Image(ct_data,
                             header=h.get_header(),
                             affine=h.get_affine())
    nib.save(ct_new, new_ct_fname)
    return new_ct_fname
Exemple #16
0
def ani_frame(time_range,
              xticks,
              images,
              dpi,
              fps,
              video_fname,
              cb_data_type,
              data_to_show_in_graph,
              fol,
              fol2,
              cb_title='',
              cb_min_max_eq=True,
              cb_norm_percs=None,
              color_map='jet',
              cb2_data_type='',
              cb2_title='',
              cb2_min_max_eq=True,
              color_map2='jet',
              bitrate=5000,
              images2=(),
              ylim=(),
              ylabels=(),
              xticklabels=(),
              xlabel='Time (ms)',
              show_first_pic=False,
              show_animation=False,
              overwrite=True):
    def two_brains_two_graphs():
        if cb2_data_type == '':
            brain_ax = plt.subplot(gs[:-g2, :g3])
        else:
            brain_ax = plt.subplot(gs[:-g2, 1:g3 + 1])
        brain_ax.set_aspect('equal')
        brain_ax.get_xaxis().set_visible(False)
        brain_ax.get_yaxis().set_visible(False)

        image = mpimg.imread(images[0])
        im = brain_ax.imshow(
            image, animated=True)  #, cmap='gray',interpolation='nearest')

        if cb2_data_type == '':
            brain_ax2 = plt.subplot(gs[:-g2, g3:-1])
        else:
            brain_ax2 = plt.subplot(gs[:-g2, g3 + 1:-1])
        brain_ax2.set_aspect('equal')
        brain_ax2.get_xaxis().set_visible(False)
        brain_ax2.get_yaxis().set_visible(False)

        image2 = mpimg.imread(images2[0])
        im2 = brain_ax2.imshow(
            image2, animated=True)  #, cmap='gray',interpolation='nearest')

        graph1_ax = plt.subplot(gs[-g2:, :])
        graph2_ax = graph1_ax.twinx()
        if cb_data_type != '':
            ax_cb = plt.subplot(gs[:-g2, -1])
        else:
            ax_cb = None
        if cb2_data_type != '':
            ax_cb2 = plt.subplot(gs[:-g2, -1])
            ax_cb = plt.subplot(gs[:-g2, 0])
        else:
            ax_cb2 = None
        plt.tight_layout()
        resize_and_move_ax(brain_ax, dx=0.04)
        resize_and_move_ax(brain_ax2, dx=-0.00)
        if cb2_data_type != '':
            resize_and_move_ax(ax_cb2, ddw=0.5, ddh=0.9, dx=-0.04, dy=0.03)
            resize_and_move_ax(ax_cb, ddw=0.5, ddh=0.9, dx=0.03, dy=0.03)
            resize_and_move_ax(brain_ax, dx=-0.03)
            resize_and_move_ax(brain_ax2, dx=-0.04)
        elif cb_data_type != '':
            resize_and_move_ax(ax_cb, ddw=0.5, ddh=0.8, dx=-0.01, dy=0.06)
        for graph_ax in [graph1_ax, graph2_ax]:
            resize_and_move_ax(graph_ax, dx=0.04, dy=0.03, ddw=0.89)
            # if cb2_data_type != '':
            #     resize_and_move_ax(graph_ax, ddh=1.2)
        return ax_cb, im, im2, graph1_ax, graph2_ax, ax_cb2

    def one_brain_one_graph(gs, g2, two_graphs=False):
        brain_ax = plt.subplot(gs[:-g2, :-1])
        brain_ax.set_aspect('equal')
        brain_ax.get_xaxis().set_visible(False)
        brain_ax.get_yaxis().set_visible(False)

        image = mpimg.imread(images[0])
        im = brain_ax.imshow(
            image, animated=True)  #, cmap='gray',interpolation='nearest')

        graph1_ax = plt.subplot(gs[-g2:, :])
        graph2_ax = graph1_ax.twinx() if two_graphs else None
        ax_cb = plt.subplot(gs[:-g2, -1])
        plt.tight_layout()
        # resize_and_move_ax(brain_ax, dx=0.03)
        resize_and_move_ax(ax_cb, ddw=1, dx=-0.06)
        resize_and_move_ax(graph1_ax, dx=0.05, dy=0.03, ddw=0.89)
        if not graph2_ax is None:
            resize_and_move_ax(graph2_ax, dx=0.05, dy=0.03, ddw=0.89)
        return ax_cb, im, graph1_ax, graph2_ax

    first_image = Image.open(images[0])
    img_width, img_height = first_image.size
    print('video: width {} height {} dpi {}'.format(img_width, img_height,
                                                    dpi))
    img_width_fac = 2 if fol2 != '' else 1.1
    w, h = img_width / dpi * img_width_fac, img_height / dpi * 3 / 2
    fig = plt.figure(figsize=(w, h), dpi=dpi, facecolor='white')
    fig.canvas.draw()
    g = 15
    g2 = int(g / 3)
    g3 = int((g - 1) / 2)
    gs = gridspec.GridSpec(g, g)  #, height_ratios=[3, 1])

    if fol2 != '':
        if cb2_data_type != '':
            gs = gridspec.GridSpec(g, g + 1)  # , height_ratios=[3, 1])
        ax_cb, im, im2, graph1_ax, graph2_ax, ax_cb2 = two_brains_two_graphs()
    else:
        two_graphes = len(data_to_show_in_graph) == 2
        ax_cb, im, graph1_ax, graph2_ax = one_brain_one_graph(
            gs, g2, two_graphes)
        im2, ax_cb2 = None, None

    # gs.update(left=0.05, right=0.48, wspace=0.05)
    # graph_data, graph_colors, t_line, ymin, ymax = plot_graph(
    #     graph1_ax, data_to_show_in_graph, fol, fol2, graph2_ax, ylabels)

    graph_data, graph_colors, t_line, ymin, ymax = plot_graph(
        graph1_ax, data_to_show_in_graph, time_range, xticks, fol, fol2,
        graph2_ax, xlabel, ylabels, xticklabels, ylim, images)

    if not ax_cb2 is None and fol2 != '':
        graph_data2, _ = utils.load(op.join(fol2, 'data.pkl'))
        plot_color_bar(ax_cb, graph_data, cb_title, cb_data_type,
                       cb_min_max_eq, cb_norm_percs, color_map, 'left')
        plot_color_bar(ax_cb2, graph_data2, cb2_title, cb2_data_type,
                       cb2_min_max_eq, cb_norm_percs, color_map2)
    else:
        plot_color_bar(ax_cb, graph_data, cb_title, cb_data_type,
                       cb_min_max_eq, cb_norm_percs, color_map)

    now = time.time()
    if show_first_pic:
        plt.show()

    def init_func():
        return update_img(0)

    def update_img(image_index):
        # print(image_fname)
        utils.time_to_go(now, image_index, len(images))
        image = mpimg.imread(images[image_index])
        im.set_data(image)
        if im2:
            image2 = mpimg.imread(images2[image_index])
            im2.set_data(image2)

        current_t = get_t(images, image_index, time_range)
        if not current_t is None:
            t_line.set_data([current_t, current_t], [ymin, ymax])
            # print('Reading image {}, current t {}'.format(images[image_index], current_t))
            return [im]
        else:
            return None

    if show_animation:
        ani = animation.FuncAnimation(fig,
                                      update_img,
                                      len(images),
                                      init_func=init_func,
                                      interval=1000,
                                      blit=True,
                                      repeat=False)
        plt.show()
        # Set up formatting for the movie files
        # Writer = animation.writers['ffmpeg'] #FFMpegWriter #
        # Writer = animation.AVConvWriter
        # writer = Writer(fps=fps, bitrate=1800) #, extra_args=['-vcodec', 'libx264'])
        # ani.save(op.join(fol, video_fname), writer=writer)
        # writer = animation.writers['ffmpeg'](fps=fps, bitrate=bitrate)
        # ani.save(op.join(fol, video_fname), writer=writer, dpi=dpi)
    else:
        images_fol = utils.get_parent_fol(images[0])
        new_images_fol = op.join(images_fol, 'movie_images')
        utils.make_dir(new_images_fol)
        images_nb = utils.namebase(images_fol)
        for image_index in range(len(images)):
            new_image_fname = op.join(new_images_fol,
                                      'mv_{}.png'.format(image_index))
            if not op.isfile(new_image_fname) or overwrite:
                img = update_img(image_index)
                if not img is None:
                    plt.savefig(new_image_fname,
                                facecolor=fig.get_facecolor(),
                                transparent=True)
        movie_fname = op.join(utils.get_parent_fol(images_fol), images_nb)
        if op.isfile('{}.mp4'.format(movie_fname)) and overwrite:
            utils.remove_file('{}.mp4'.format(movie_fname))
        mu.combine_images(new_images_fol,
                          movie_fname,
                          frame_rate=fps,
                          movie_name_full_path=True)
Exemple #17
0
import glob
import os.path as op
import importlib
import sys
import nibabel as nib
import numpy as np
from scipy.spatial.distance import pdist, cdist

from src.utils import utils
from src.utils import preproc_utils as pu
from src.utils import labels_utils as lu
from src.preproc import anatomy as anat

mmvt_code_fol = utils.get_mmvt_code_root()
ela_code_fol = op.join(utils.get_parent_fol(mmvt_code_fol), 'electrodes_rois')
if ela_code_fol not in sys.path:
    sys.path.append(ela_code_fol)

from find_rois import find_rois
from find_rois import freesurfer_utils as fu
importlib.reload(find_rois)

SUBJECTS_DIR, MMVT_DIR, FREESURFER_HOME = pu.get_links()
WHITES = set([
    'Left-Cerebral-White-Matter', 'Left-Cerebellum-White-Matter',
    'Right-Cerebral-White-Matter', 'Right-Cerebellum-White-Matter'
])

mri_robust_register = 'mri_robust_register --mov {subjects_dir}/{subject_from}/mri/T1.mgz --dst {subjects_dir}/{subject_to}/mri/T1.mgz --lta {subjects_dir}/{subject_from}/mri/{lta_name}.lta --satit --mapmov {subjects_dir}/{subject_from}/mri/T1_to_{subject_to}.mgz --cost nmi'

Exemple #18
0
def post_analysis(args):
    import matplotlib.pyplot as plt
    from collections import defaultdict
    atlas = 'darpa_atlas'
    res_fol = utils.make_dir(
        op.join(utils.get_parent_fol(MMVT_DIR), 'msit-ecr'))
    bands = dict(theta=[4, 8],
                 alpha=[8, 15],
                 beta=[15, 30],
                 gamma=[30, 55],
                 high_gamma=[65, 200])
    data_dic = np.load(op.join(res_fol, 'data_dictionary.npz'))
    meta_data = data_dic['noam_dict'].tolist()
    # brain_overall_res_fname = op.join(res_fol, 'brain_overall_res.npz')
    subjects1 = set(meta_data[0]['MSIT'].keys())
    subjects2 = set(meta_data[1]['MSIT'].keys())
    subjects_with_data = defaultdict(list)
    mean_evo = {group_id: defaultdict(list) for group_id in range(2)}
    mean_power = {group_id: {} for group_id in range(2)}
    power = {group_id: {} for group_id in range(2)}
    for group_id in range(2):
        for task in args.tasks:
            mean_power[group_id][task] = defaultdict(list)
            power[group_id][task] = {band: None for band in bands.keys()}
        for subject in meta_data[group_id]['ECR'].keys():
            if not op.isdir(op.join(res_fol, subject)):
                print('No folder data for {}'.format(subject))
                continue
            for task in args.tasks:
                mean_fname = op.join(
                    res_fol, subject,
                    '{}_{}_mean.npz'.format(task.lower(), atlas))
                if op.isfile(mean_fname):
                    d = utils.Bag(np.load(mean_fname))
                    mean_evo[group_id][task].append(d.data.mean())
                for band in bands.keys():
                    if power[group_id][task][band] is None:
                        power[group_id][task][band] = defaultdict(list)
                    mean_power_fname = op.join(
                        res_fol, subject,
                        '{}_power_{}.npz'.format(task.lower(), band))
                    if op.isfile(mean_power_fname):
                        d = utils.Bag(np.load(mean_power_fname))
                        mean_power[group_id][task][band].append(d.data.mean())
                        for label_id, label in enumerate(d.names):
                            power[group_id][task][band][label].append(
                                d.data[label_id])

    for group_id in range(2):
        x = [np.array(mean_evo[group_id][task]) for task in args.tasks]
        # x = [_x[_x < np.percentile(_x, 90)] for _x in x]
        ttest(x[0], x[1])

    for band in bands.keys():
        # fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
        for group_id in range(2):  #, ax in zip(range(2), [ax1, ax2]):
            subjects_with_data[group_id] = np.array(
                subjects_with_data[group_id])
            print()
            x = [
                np.array(mean_power[group_id][task][band])
                for task in args.tasks
            ]
            x = [_x[_x < np.percentile(_x, 90)] for _x in x]
            # ttest(x[0], x[1], title='group {} band {}'.format(group_id, band))

            for label_id, label in enumerate(d.names):
                x = [
                    np.array(power[group_id][task][band][label])
                    for task in args.tasks
                ]
                x = [_x[_x < np.percentile(_x, 95)] for _x in x]
                ttest(x[0],
                      x[1],
                      alpha=0.01,
                      title='group {} band {} label {}'.format(
                          group_id, band, label))
Exemple #19
0
def meg_preproc_power(args):
    inv_method, em, atlas = 'dSPM', 'mean_flip', 'laus125'  # 'darpa_atlas'
    # bands = dict(theta=[4, 8], alpha=[8, 15], beta=[15, 30], gamma=[30, 55], high_gamma=[65, 200])
    times = (-2, 4)
    subjects_with_error = []
    good_subjects = get_good_subjects(args)
    args.subject = good_subjects
    prepare_files(args)

    for subject in good_subjects:
        args.subject = subject
        empty_fnames, cors, days = get_empty_fnames(subject, args.tasks, args)
        input_fol = utils.make_dir(
            op.join(MEG_DIR, subject, 'labels_induced_power'))
        for task in args.tasks:

            # output_fname = op.join(
            #     MMVT_DIR, subject, 'meg', '{}_{}_{}_power_spectrum.npz'.format(task.lower(), inv_method, em))
            # if op.isfile(output_fname) and args.check_file_modification_time:
            #     file_mod_time = utils.file_modification_time_struct(output_fname)
            #     if file_mod_time.tm_year >= 2018 and (file_mod_time.tm_mon == 9 and file_mod_time.tm_mday >= 21) or \
            #             (file_mod_time.tm_mon > 9):
            #         print('{} already exist!'.format(output_fname))
            #         continue

            input_fnames = glob.glob(
                op.join(
                    input_fol, '{}_*_{}_{}_{}_induced_power.npz'.format(
                        task.lower(), atlas, inv_method, em)))
            if len(input_fnames) == 28:
                print('{} has already all the results for {}'.format(
                    subject, task))
                continue

            remote_epo_fname = op.join(
                args.meg_dir, subject,
                args.epo_template.format(subject=subject, task=task))
            local_epo_fname = op.join(
                MEG_DIR, task, subject,
                args.epo_template.format(subject=subject, task=task))
            if not op.isfile(local_epo_fname) and not op.isfile(
                    remote_epo_fname):
                print('Can\'t find {}!'.format(local_epo_fname))
                continue
            if not op.isfile(local_epo_fname):
                utils.make_link(remote_epo_fname, local_epo_fname)

            meg_args = meg.read_cmd_args(
                dict(
                    subject=args.subject,
                    mri_subject=args.subject,
                    task=task,
                    inverse_method=inv_method,
                    extract_mode=em,
                    atlas=atlas,
                    # meg_dir=args.meg_dir,
                    remote_subject_dir=args.
                    remote_subject_dir,  # Needed for finding COR
                    get_task_defaults=False,
                    fname_format='{}_{}_Onset'.format('{subject}', task),
                    raw_fname=op.join(MEG_DIR, task, subject,
                                      '{}_{}-raw.fif'.format(subject, task)),
                    epo_fname=local_epo_fname,
                    empty_fname=empty_fnames[task]
                    if empty_fnames != '' else '',
                    function=
                    'make_forward_solution,calc_inverse_operator,calc_labels_induced_power',  #,
                    conditions=task.lower(),
                    cor_fname=cors[task].format(
                        subject=subject) if cors != '' else '',
                    average_per_event=False,
                    data_per_task=True,
                    pick_ori=
                    'normal',  # very important for calculation of the power spectrum
                    # fmin=4, fmax=120, bandwidth=2.0,
                    max_epochs_num=args.max_epochs_num,
                    ica_overwrite_raw=False,
                    normalize_data=False,
                    fwd_recreate_source_space=True,
                    t_min=times[0],
                    t_max=times[1],
                    read_events_from_file=False,
                    stim_channels='STI001',
                    use_empty_room_for_noise_cov=True,
                    read_only_from_annot=False,
                    # pick_ori='normal',
                    overwrite_labels_power_spectrum=args.
                    overwrite_labels_power_spectrum,
                    overwrite_evoked=args.overwrite,
                    overwrite_fwd=args.overwrite,
                    overwrite_inv=args.overwrite,
                    overwrite_stc=args.overwrite,
                    overwrite_labels_data=args.overwrite,
                    n_jobs=args.n_jobs))
            ret = meg.call_main(meg_args)
            output_fol = utils.make_dir(
                op.join(MMVT_DIR, subject, 'labels', 'labels_data'))
            join_res_fol = utils.make_dir(
                op.join(utils.get_parent_fol(MMVT_DIR), 'msit-ecr', subject))
            for res_fname in glob.glob(
                    op.join(
                        output_fol, '{}_labels_{}_{}_*_power.npz'.format(
                            task.lower(), inv_method, em))):
                shutil.copyfile(
                    res_fname,
                    op.join(join_res_fol, utils.namebase_with_ext(res_fname)))
            if not ret:
                if args.throw:
                    raise Exception("errors!")
                else:
                    subjects_with_error.append(subject)

    good_subjects = [
        s for s in good_subjects if op.isfile(
            op.join(
                MMVT_DIR, subject, 'meg',
                'labels_data_msit_{}_{}_{}_minmax.npz'.format(
                    atlas, inv_method, em)))
        and op.isfile(
            op.join(
                MMVT_DIR, subject, 'meg', 'labels_data_ecr_{}_{}_{}_minmax.npz'
                .format(atlas, inv_method, em)))
    ]
    print('Good subjects:')
    print(good_subjects)
    print('subjects_with_error:')
    print(subjects_with_error)
Exemple #20
0
def post_meg_preproc(args):
    inv_method, em, atlas = 'dSPM', 'mean_flip', 'darpa_atlas'
    bands = dict(theta=[4, 8],
                 alpha=[8, 15],
                 beta=[15, 30],
                 gamma=[30, 55],
                 high_gamma=[65, 200])
    norm_times = (500, 2500)
    do_plot = False

    subjects = args.subject
    res_fol = utils.make_dir(
        op.join(utils.get_parent_fol(MMVT_DIR), 'msit-ecr'))
    subjects_with_results = {}
    labels = lu.read_labels(subjects[0], SUBJECTS_DIR, atlas)
    labels_names = [l.name for l in labels]
    labels_num = len(labels_names)
    epochs_max_num = 50
    template_brain = 'colin27'

    now = time.time()
    bands_power_mmvt_all = []
    for subject_ind, subject in enumerate(subjects):
        utils.time_to_go(now, subject_ind, len(subjects), runs_num_to_print=1)
        subjects_with_results[subject] = {}
        input_fol = utils.make_dir(
            op.join(MEG_DIR, subject, 'labels_induced_power'))
        plots_fol = utils.make_dir(op.join(input_fol, 'plots'))
        args.subject = subject
        bands_power_mmvt = {'rh': {}, 'lh': {}}
        for task_ind, task in enumerate(args.tasks):
            task = task.lower()
            input_fnames = glob.glob(
                op.join(
                    input_fol, '{}_*_{}_{}_induced_power.npz'.format(
                        task, inv_method, em)))
            if len(input_fnames) < 1:  # labels_num:
                print('No enough files for {} {}!'.format(subject, task))
                subjects_with_results[subject][task] = False
                continue
            # input_dname = ecr_caudalanteriorcingulate-lh_dSPM_mean_flip_induced_power
            # if not do_plot:
            #     continue
            bands_power = np.empty((len(bands), labels_num, epochs_max_num))
            for input_fname in input_fnames:
                d = utils.Bag(np.load(input_fname))  # label_name, atlas, data
                # label_power = np.empty((len(bands), epochs_num, T)) (5, 50, 3501)
                label_power, label_name = d.data, d.label_name
                # for band_ind in range(len(bands)):
                #     label_power[band_ind] /= label_power[band_ind][:, norm_times[0]:norm_times[1]].mean()
                label_ind = labels_names.index(label_name)
                hemi = labels[label_ind].hemi
                for band_ind, band in enumerate(bands.keys()):
                    label_power_norm = label_power[
                        band_ind][:, norm_times[0]:norm_times[1]].mean(
                            axis=1)[:epochs_max_num]
                    if len(label_power_norm) != epochs_max_num:
                        print('{} does have {} epochs!'.format(
                            input_fname, len(label_power_norm)))
                        break
                    bands_power[band_ind, label_ind] = label_power_norm
                    if band not in bands_power_mmvt[hemi]:
                        bands_power_mmvt[hemi][band] = np.empty(
                            (len(labels_names), label_power[band_ind].shape[1],
                             1, len(args.tasks)))
                    bands_power_mmvt[hemi][band][
                        label_ind, :, 0,
                        task_ind] = label_power[band_ind].mean(axis=0)
                fig_fname = op.join(plots_fol,
                                    'power_{}_{}.jpg'.format(label_name, task))
                if do_plot:  # not op.isfile(fig_fname) and
                    times = np.arange(
                        0,
                        label_power.shape[2]) if 'times' not in d else d.times
                    plot_label_power(label_power, times, label_name, bands,
                                     task, fig_fname)
            for band_ind, band in enumerate(bands.keys()):
                power_fname = op.join(
                    res_fol, subject, '{}_labels_{}_{}_{}_power.npz'.format(
                        task.lower(), inv_method, em, band))
                np.savez(power_fname,
                         data=np.array(bands_power[band_ind]),
                         names=labels_names)
            subjects_with_results[subject][task] = True

        if all(subjects_with_results[subject].values()):
            bands_power_mmvt_all.append(bands_power_mmvt)
        else:
            print('{} does not have both tasks data!'.format(subject))

    labels_data_template = op.join(MMVT_DIR, template_brain, 'meg',
                                   'labels_data_power_{}_{}_{}_{}_{}.npz'
                                   )  # task, atlas, extract_method, hemi
    for hemi in utils.HEMIS:
        for band_ind, band in enumerate(bands.keys()):
            power = np.array([x[hemi][band]
                              for x in bands_power_mmvt_all]).mean(axis=0)
            labels_output_fname = meg.get_labels_data_fname(
                labels_data_template, inv_method, band, atlas, em, hemi)
            utils.make_dir(utils.get_parent_fol(labels_output_fname))
            np.savez(labels_output_fname,
                     data=power,
                     names=labels_names,
                     conditions=args.tasks)

    have_all = len([
        subject for subject, results in subjects_with_results.items()
        if all(results.values())
    ])
    print('{}/{} with all files'.format(have_all, len(subjects)))
    print(subjects_with_results)
Exemple #21
0
def post_analysis(args):
    import matplotlib.pyplot as plt
    from collections import defaultdict

    inv_method, em = 'dSPM', 'mean_flip'
    res_fol = utils.make_dir(
        op.join(utils.get_parent_fol(MMVT_DIR), 'msit-ecr'))
    plot_fol = utils.make_dir(op.join(res_fol, 'plots'))
    bands = dict(theta=[4, 8],
                 alpha=[8, 15],
                 beta=[15, 30],
                 gamma=[30, 55],
                 high_gamma=[65, 200])
    data_dic = np.load(op.join(res_fol, 'data_dictionary.npz'))
    meta_data = data_dic['noam_dict'].tolist()
    # brain_overall_res_fname = op.join(res_fol, 'brain_overall_res.npz')
    msit_subjects = set(meta_data[0]['MSIT'].keys())
    ecr_subjects = set(meta_data[1]['ECR'].keys())
    subjects_with_data = defaultdict(list)
    mean_evo = {group_id: defaultdict(list) for group_id in range(2)}
    mean_power_power_emotion_reactivit = {
        group_id: {}
        for group_id in range(2)
    }
    power_emotion_reactivit = {group_id: {} for group_id in range(2)}

    mean_power_power_task = {}
    power_task = {}
    for task in args.tasks:
        mean_power_power_task[task] = defaultdict(list)
        power_task[task] = {band: None for band in bands.keys()}
    for subject in args.subject:
        if not op.isdir(op.join(res_fol, subject)):
            print('No folder data for {}'.format(subject))
            continue
        for task in args.tasks:
            # mean_fname = op.join(res_fol, subject, '{}_{}_mean.npz'.format(task.lower(), args.atlas))
            # if op.isfile(mean_fname):
            #     d = utils.Bag(np.load(mean_fname))
            #     mean_evo[group_id][task].append(d.data.mean())
            for band in bands.keys():
                if power_task[task][band] is None:
                    power_task[task][band] = defaultdict(list)
                power_fname = op.join(
                    res_fol, subject, '{}_labels_{}_{}_{}_power.npz'.format(
                        task.lower(), inv_method, em, band))
                if op.isfile(power_fname):
                    d = utils.Bag(np.load(power_fname))
                    mean_power_power_task[task][band].append(d.data.mean())
                    for label_id, label in enumerate(d.names):
                        power_task[task][band][label].append(
                            d.data[label_id].mean())

    # for group_id in range(2):
    #     for task in args.tasks:
    #         mean_power_power_emotion_reactivit[group_id][task] = defaultdict(list)
    #         power_emotion_reactivit[group_id][task] = {band: None for band in bands.keys()}
    #     for subject in meta_data[group_id]['ECR'].keys():
    #         if not op.isdir(op.join(res_fol, subject)):
    #             print('No folder data for {}'.format(subject))
    #             continue
    #         for task in args.tasks:
    #             mean_fname = op.join(res_fol, subject, '{}_{}_mean.npz'.format(task.lower(), args.atlas))
    #             if op.isfile(mean_fname):
    #                 d = utils.Bag(np.load(mean_fname))
    #                 mean_evo[group_id][task].append(d.data.mean())
    #             for band in bands.keys():
    #                 if power_emotion_reactivit[group_id][task][band] is None:
    #                     power_emotion_reactivit[group_id][task][band] = defaultdict(list)
    #                 power_fname = op.join(
    #                     res_fol, subject, '{}_labels_{}_{}_{}_power.npz'.format(task.lower(), inv_method, em, band))
    #                 if op.isfile(power_fname):
    #                     d = utils.Bag(np.load(power_fname))
    #                     mean_power_power_emotion_reactivit[group_id][task][band].append(d.data.mean())
    #                     for label_id, label in enumerate(d.names):
    #                         power_emotion_reactivit[group_id][task][band][label].append(d.data[label_id].mean())

    do_plot = False
    percentile = 90
    alpha = 0.05
    for band in bands.keys():

        x = [
            np.array(mean_power_power_task[task][band]) for task in args.tasks
        ]
        x[0] = x[0][x[0] < np.percentile(x[0], percentile)]
        x[1] = x[1][x[1] < np.percentile(x[1], percentile)]
        sig = ttest(x[0],
                    x[1],
                    title='MSIT vs ECR band {}'.format(band),
                    alpha=alpha,
                    always_print=False)
        if do_plot or sig:
            f, (ax1, ax2) = plt.subplots(2, 1)
            ax1.hist(x[0], bins=80)
            ax1.set_title('{} {}'.format(band, args.tasks[0]))
            ax2.hist(x[1], bins=80)
            ax2.set_title('{} {}'.format(band, args.tasks[1]))
            # plt.title('{} mean power'.format(band))
            plt.show()
            # plt.savefig(op.join(plot_fol, '{}_group_{}.jpg'.format(band, group_id)))

        for label_id, label in enumerate(d.names):
            x = [
                np.array(power_task[task][band][label]) for task in args.tasks
            ]
            x[0] = x[0][x[0] < np.percentile(x[0], percentile)]
            x[1] = x[1][x[1] < np.percentile(x[1], percentile)]
            sig = ttest(x[0],
                        x[1],
                        alpha=alpha,
                        title='band {} label {}'.format(band, label))
            if do_plot or sig:
                f, (ax1, ax2) = plt.subplots(2, 1)
                ax1.hist(x[0], bins=80)
                ax2.hist(x[1], bins=80)
                plt.title('{} mean power'.format(band))
                plt.show()
                # plt.savefig(op.join(plot_fol, '{}_group_{}.jpg'.format(band, group_id)))

        continue
        for group_id in range(2):  #, ax in zip(range(2), [ax1, ax2]):
            # subjects_with_data[group_id] = np.array(subjects_with_data[group_id])
            # print()
            x = [
                np.array(
                    mean_power_power_emotion_reactivit[group_id][task][band])
                for task in args.tasks
            ]
            # x = [_x[_x < np.percentile(_x, 90)] for _x in x]
            x[0] = x[0][x[0] < np.percentile(x[0], percentile)]
            x[1] = x[1][x[1] < np.percentile(x[1], percentile)]
            print('band {}, group {}, {} for {}, {} for {}'.format(
                band, group_id, len(x[0]), args.tasks[0], len(x[1]),
                args.tasks[1]))
            ttest(x[0],
                  x[1],
                  title='group {} band {}'.format(group_id, band),
                  alpha=alpha)
            if do_plot:
                f, (ax1, ax2) = plt.subplots(2, 1)
                ax1.hist(x[0], bins=80)
                ax2.hist(x[1], bins=80)
                plt.title('{} mean power'.format(band))
                plt.savefig(
                    op.join(plot_fol, '{}_group_{}.jpg'.format(band,
                                                               group_id)))

            for label_id, label in enumerate(d.names):
                x = [
                    np.array(
                        power_emotion_reactivit[group_id][task][band][label])
                    for task in args.tasks
                ]
                # x = [_x[_x < np.percentile(_x, 90)] for _x in x]
                x[0] = x[0][x[0] < np.percentile(x[0], percentile)]
                x[1] = x[1][x[1] < np.percentile(x[1], percentile)]
                ttest(x[0],
                      x[1],
                      alpha=alpha,
                      title='group {} band {} label {}'.format(
                          group_id, band, label))
                if do_plot:
                    f, (ax1, ax2) = plt.subplots(2, 1)
                    ax1.hist(x[0], bins=80)
                    ax2.hist(x[1], bins=80)
                    plt.title('{} {} power'.format(band, label))
                    plt.savefig(
                        op.join(
                            plot_fol, '{}_group_{}_label_{}.jpg'.format(
                                band, group_id, label)))
import numpy as np
import scipy.io as sio

from src.utils import labels_utils as lu
from src.utils import matlab_utils
from src.utils import utils
from src.utils import freesurfer_utils as fu
from src.mmvt_addon import colors_utils as cu


LINKS_DIR = utils.get_links_dir()
SUBJECTS_DIR = utils.get_link_dir(LINKS_DIR, 'subjects', 'SUBJECTS_DIR')
FREE_SURFER_HOME = utils.get_link_dir(LINKS_DIR, 'freesurfer', 'FREESURFER_HOME')
MMVT_DIR = op.join(LINKS_DIR, 'mmvt')
os.environ['SUBJECTS_DIR'] = SUBJECTS_DIR
BRAINDER_SCRIPTS_DIR = op.join(utils.get_parent_fol(utils.get_parent_fol()), 'brainder_scripts')
ASEG_TO_SRF = op.join(BRAINDER_SCRIPTS_DIR, 'aseg2srf -s "{}"') # -o {}'
HEMIS = ['rh', 'lh']


def subcortical_segmentation(subject, overwrite_subcortical_objs=False):
    # Must source freesurfer. You need to have write permissions on SUBJECTS_DIR
    script_fname = op.join(BRAINDER_SCRIPTS_DIR, 'aseg2srf')
    if not op.isfile(script_fname):
        raise Exception('The subcortical segmentation script is missing! {}'.format(script_fname))
    if not utils.is_exe(script_fname):
        utils.set_exe_permissions(script_fname)

    # aseg2srf: For every subcortical region (8 10 11 12 13 16 17 18 26 47 49 50 51 52 53 54 58):
    # 1) mri_pretess: Changes region segmentation so that the neighbors of all voxels have a face in common
    # 2) mri_tessellate: Creates surface by tessellating
Exemple #23
0
import scipy.io as sio
import nibabel as nib

from src.utils import labels_utils as lu
from src.utils import matlab_utils
from src.utils import utils
from src.utils import freesurfer_utils as fu
from src.mmvt_addon import colors_utils as cu


LINKS_DIR = utils.get_links_dir()
SUBJECTS_DIR = utils.get_link_dir(LINKS_DIR, 'subjects', 'SUBJECTS_DIR')
FREE_SURFER_HOME = utils.get_link_dir(LINKS_DIR, 'freesurfer', 'FREESURFER_HOME')
MMVT_DIR = op.join(LINKS_DIR, 'mmvt')
os.environ['SUBJECTS_DIR'] = SUBJECTS_DIR
BRAINDER_SCRIPTS_DIR = op.join(utils.get_parent_fol(utils.get_parent_fol()), 'brainder_scripts')
ASEG_TO_SRF = op.join(BRAINDER_SCRIPTS_DIR, 'aseg2srf -s "{}"') # -o {}'
HEMIS = ['rh', 'lh']


def subcortical_segmentation(subject, overwrite_subcortical_objs=False):
    # Must source freesurfer. You need to have write permissions on SUBJECTS_DIR
    if not op.isfile(op.join(SUBJECTS_DIR, subject, 'mri', 'norm.mgz')):
        return False
    script_fname = op.join(BRAINDER_SCRIPTS_DIR, 'aseg2srf')
    if not op.isfile(script_fname):
        raise Exception('The subcortical segmentation script is missing! {}'.format(script_fname))
    if not utils.is_exe(script_fname):
        utils.set_exe_permissions(script_fname)

    # aseg2srf: For every subcortical region (8 10 11 12 13 16 17 18 26 47 49 50 51 52 53 54 58):
Exemple #24
0
def register_ct_to_mr_using_mutual_information(subject,
                                               subjects_dir,
                                               ct_fname,
                                               output_fname='',
                                               lta_name='',
                                               overwrite=False,
                                               cost_function='nmi',
                                               print_only=False):
    '''
    Performs the registration between CT and MR using the normalized mutual
    information cost option in freesurfer's mri_robust_register. Saves the
    output to a temporary file which is subsequently examined and the
    linear registration is returned.

    Freesurfer should already be sourced.

    Parameters
    ----------
    ct_fname : Str
        The filename containing the CT scan
    subject : Str
        The freesurfer subject.
    subjects_dir : Str
        The freesurfer subjects_dir.
    overwrite : Bool
        When true, will do the computation and not search for a saved value.
        Defaults to false.
    cost_function : Enum
        uses mi or nmi or blank cost function. If blank, then its not actually
        using MI at all, just rigid 6 parameter dof registration (with resampling
        tricks and so on)

    Returns
    -------
    affine : 4x4 np.ndarray
        The matrix containing the affine transformation from CT to MR space.
    '''

    xfms_dir = utils.make_dir(
        op.join(subjects_dir, subject, 'mri', 'transforms'))
    if lta_name == '':
        lta_name = 'ct2mr.lta'
    lta_fname = op.join(xfms_dir, lta_name)
    if op.isfile(lta_fname) and op.isfile(output_fname):
        if overwrite:
            os.remove(lta_fname)
            os.remove(output_fname)
        else:
            return True

    rawavg = op.join(subjects_dir, subject, 'mri', 'T1.mgz')  #''rawavg.mgz')
    if output_fname == '':
        output_fname = op.join(utils.get_parent_fol(ct_fname),
                               'ct_reg_to_mr.mgz')

    fu.robust_register(subject, subjects_dir, ct_fname, rawavg, output_fname,
                       lta_name, cost_function, print_only)
    if print_only:
        return True
    else:
        return op.isfile(lta_fname) and op.isfile(output_fname)