Пример #1
0
def aseg_to_srf(subject, subjects_dir, output_fol, region_id, mask_fname, norm_fname,
                overwrite_subcortical_objs=False):
    ret = True
    tmp_fol = op.join(subjects_dir, subject, 'tmp', utils.rand_letters(6))
    utils.make_dir(tmp_fol)
    rs = utils.partial_run_script(locals())
    output_fname = op.join(output_fol, '{}.srf'.format(region_id))
    tmp_output_fname = op.join(tmp_fol, '{}.asc'.format(region_id))
    if overwrite_subcortical_objs:
        utils.remove_file(output_fname)
    try:
        rs(mri_pretess)
        rs(mri_tessellate)
        rs(mris_smooth)
        rs(mris_convert)
        if op.isfile(tmp_output_fname):
            shutil.move(tmp_output_fname, output_fname)
            shutil.rmtree(tmp_fol)
        else:
            ret = False
    except:
        print('Error in aseg_to_srf! subject: {}'.format(subject))
        print(traceback.format_exc())
        ret = False

    return ret
Пример #2
0
def create_aparc_aseg_file(subject, atlas, overwrite_aseg_file=False, print_only=False, args={}):
    if not utils.both_hemi_files_exist(op.join(SUBJECTS_DIR, subject, 'label', '{}.{}.annot'.format('{hemi}', atlas))):
        print('No annot file was found for {}!'.format(atlas))
        print('Run python -m src.preproc.anatomy -s {} -a {} -f create_surfaces,create_annotation'.format(subject, atlas))
        return False

    # aparc_aseg_fname
    ret = fu.create_aparc_aseg_file(
        subject, atlas, SUBJECTS_DIR, overwrite_aseg_file, print_only, mmvt_args=args)
    if isinstance(ret, Iterable):
        ret, aparc_aseg_fname = ret
    if not ret:
        return False

    aparc_aseg_file = utils.namebase_with_ext(aparc_aseg_fname)
    utils.make_dir(op.join(MMVT_DIR, subject, 'freeview'))
    blender_file = op.join(MMVT_DIR, subject, 'freeview', aparc_aseg_file)
    utils.remove_file(blender_file)
    shutil.copyfile(aparc_aseg_fname, blender_file)
    atlas_mat_fname = utils.change_fname_extension(blender_file, 'npy')
    if not op.isfile(atlas_mat_fname) or overwrite_aseg_file:
        d = nib.load(blender_file)
        x = d.get_data()
        np.save(atlas_mat_fname, x)
    return op.isfile(blender_file) and op.isfile(atlas_mat_fname)
Пример #3
0
def combine_two_images_and_add_colorbar(lh_figure_fname, rh_figure_fname, new_image_fname, data_max, data_min,
        colors_map, background_color='black', cb_ticks=[], cb_ticks_font_size=10, add_cb=True, crop_figures=True,
        remove_original_figures=False, cb_title='', **kargs):
    fol = utils.get_fname_folder(lh_figure_fname)
    if ',' in background_color:
        background_color = [float(x) for x in background_color.split(',')]
    if add_cb:
        if crop_figures:
            # crop_image(lh_figure_fname, lh_figure_fname, dx=150, dy=0, dw=50, dh=70)
            # crop_image(rh_figure_fname, rh_figure_fname, dx=150 + 50, dy=0, dw=0, dh=70)
            crop_image(lh_figure_fname, lh_figure_fname, dx=100, dy=0, dw=50, dh=0)
            crop_image(rh_figure_fname, rh_figure_fname, dx=100, dy=0, dw=0, dh=0)

        combine_two_images(lh_figure_fname, rh_figure_fname, new_image_fname, facecolor=background_color,
                           dpi=200, w_fac=1, h_fac=1)

        cb_fname = op.join(fol, '{}_colorbar.jpg'.format(colors_map))
        _, img_height = Image.open(lh_figure_fname).size
        plot_color_bar(data_max, data_min, colors_map, do_save=True, cb_ticks=cb_ticks, fol=fol,
                       facecolor=background_color, cb_ticks_font_size=cb_ticks_font_size, title=cb_title) # h=img_height*0.7, w=img_height*0.2
        cb_img = Image.open(cb_fname)

        combine_brain_with_color_bar(new_image_fname, cb_img, overwrite=True, cb_ticks=cb_ticks)
    else:
        if crop_figures:
            crop_image(lh_figure_fname, lh_figure_fname, dx=150, dy=0, dw=150, dh=0)
            crop_image(rh_figure_fname, rh_figure_fname, dx=150, dy=0, dw=150, dh=0)
        combine_two_images(lh_figure_fname, rh_figure_fname, new_image_fname, facecolor=background_color)
    if remove_original_figures:
        if lh_figure_fname != new_image_fname:
            utils.remove_file(lh_figure_fname)
        if rh_figure_fname != new_image_fname:
            utils.remove_file(rh_figure_fname)
Пример #4
0
def labels_to_annot(subject,
                    subjects_dir='',
                    aparc_name='aparc250',
                    labels_fol='',
                    overwrite=True,
                    labels=[],
                    fix_unknown=True):

    if subjects_dir == '':
        subjects_dir = os.environ['SUBJECTS_DIR']
    subject_dir = op.join(subjects_dir, subject)
    annot_files_exist = utils.both_hemi_files_exist(
        op.join(subject_dir, 'label',
                '{}.{}.annot'.format('{hemi}', aparc_name)))
    if annot_files_exist and not overwrite:
        return True
    if len(labels) == 0:
        labels_fol = op.join(subject_dir, 'label',
                             aparc_name) if labels_fol == '' else labels_fol
        labels_files = glob.glob(op.join(labels_fol, '*.label'))
        if len(labels_files) == 0:
            if not annot_files_exist:
                raise Exception('labels_to_annot: No labels files!')
            else:
                print("Can't find label files, using the annot files instead")
                return True
        for label_file in labels_files:
            if fix_unknown and 'unknown' in utils.namebase(label_file):
                continue
            label = mne.read_label(label_file)
            # print(label.name)
            label.name = get_label_hemi_invariant_name(label.name)
            labels.append(label)
        labels.sort(key=lambda l: l.name)
    if overwrite:
        for hemi in HEMIS:
            utils.remove_file(
                op.join(subject_dir, 'label',
                        '{}.{}.annot'.format(hemi, aparc_name)))
    try:
        mne.write_labels_to_annot(subject=subject,
                                  labels=labels,
                                  parc=aparc_name,
                                  overwrite=overwrite,
                                  subjects_dir=subjects_dir)
    except:
        print('Error in writing annot file!')
        # print(traceback.format_exc())
        return False
    return utils.both_hemi_files_exist(
        op.join(subject_dir, 'label',
                '{}.{}.annot'.format('{hemi}', aparc_name)))
Пример #5
0
def combine_movies(fol, movie_name, parts=(), movie_type='mp4'):
    # First convert the part to avi, because mp4 cannot be concat
    cmd = 'ffmpeg -i concat:"'
    if len(parts) == 0:
        parts = sorted(
            glob.glob(op.join(fol, '{}_*.{}'.format(movie_name, movie_type))))
    else:
        parts = [op.join(fol, p) for p in parts]
    for part_fname in parts:
        part_name, _ = op.splitext(part_fname)
        cmd = '{}{}.avi|'.format(cmd, op.join(fol, part_name))
        utils.remove_file('{}.avi'.format(part_name))
        utils.run_script('ffmpeg -i {} -codec copy {}.avi'.format(
            part_fname, op.join(fol, part_name)))
    # cmd = '{}" -c copy -bsf:a aac_adtstoasc {}'.format(cmd[:-1], op.join(fol, '{}.{}'.format(movie_name, movie_type)))
    cmd = '{}" -c copy {}'.format(
        cmd[:-1], op.join(fol, '{}.{}'.format(movie_name, movie_type)))
    print(cmd)
    utils.remove_file('{}.{}'.format(op.join(fol, movie_name), movie_type))
    utils.run_script(cmd)
    # clean up
    # todo: doesn't clean the part filess
    utils.remove_file('{}.avi'.format(op.join(fol, movie_name)))
    for part_fname in parts:
        part_name, _ = op.splitext(part_fname)
        utils.remove_file('{}.avi'.format(part_name))
Пример #6
0
def example6():
    figures_fol = '/home/npeled/mmvt/nmr01216/figures'
    colors_map = 'RdOrYl'
    data_max, data_min = 2, 6
    background = '#393939'

    files = glob.glob(op.join(figures_fol, '*.png'))
    images_hemi_inv_list = set([
        utils.namebase(fname)[3:] for fname in files
        if utils.namebase(fname)[:2] in ['rh', 'lh']
    ])
    files = [[
        fname for fname in files if utils.namebase(fname)[3:] == img_hemi_inv
    ] for img_hemi_inv in images_hemi_inv_list]
    for files_coup in files:
        hemi = 'rh' if utils.namebase(files_coup[0]).startswith('rh') else 'lh'
        coup_template = files_coup[0].replace(hemi, '{hemi}')
        coup = {}
        for hemi in utils.HEMIS:
            coup[hemi] = coup_template.format(hemi=hemi)
        new_image_fname = op.join(utils.get_fname_folder(files_coup[0]),
                                  utils.namebase_with_ext(files_coup[0])[3:])

        fu.crop_image(coup['lh'], coup['lh'], dx=150, dy=0, dw=150, dh=0)
        fu.crop_image(coup['rh'], coup['rh'], dx=150, dy=0, dw=0, dh=0)
        fu.combine_two_images(coup['lh'],
                              coup['rh'],
                              new_image_fname,
                              facecolor=background)
        fu.combine_brain_with_color_bar(data_max,
                                        data_min,
                                        new_image_fname,
                                        colors_map,
                                        dpi=200,
                                        overwrite=True,
                                        w_fac=1.2,
                                        h_fac=1.2,
                                        ddh=0.7,
                                        dy=0.13,
                                        ddw=0.4,
                                        dx=-0.08)
        for hemi in utils.HEMIS:
            utils.remove_file(coup[hemi])
Пример #7
0
def labels_to_annot(subject,
                    subjects_dir='',
                    aparc_name='aparc250',
                    labels_fol='',
                    overwrite=True,
                    labels=[]):
    from src.utils import labels_utils as lu
    if subjects_dir == '':
        subjects_dir = os.environ['SUBJECTS_DIR']
    subject_dir = op.join(subjects_dir, subject)
    if utils.both_hemi_files_exist(op.join(subject_dir, 'label', '{}.{}.annot'.format('{hemi}', aparc_name))) \
            and not overwrite:
        return True
    if len(labels) == 0:
        labels_fol = op.join(subject_dir, 'label',
                             aparc_name) if labels_fol == '' else labels_fol
        labels = []
        labels_files = glob.glob(op.join(labels_fol, '*.label'))
        if len(labels_files) == 0:
            raise Exception('labels_to_annot: No labels files!')
        for label_file in labels_files:
            label = mne.read_label(label_file)
            # print(label.name)
            label.name = lu.get_label_hemi_invariant_name(label.name)
            labels.append(label)
        labels.sort(key=lambda l: l.name)
    if overwrite:
        for hemi in HEMIS:
            utils.remove_file(
                op.join(subject_dir, 'label',
                        '{}.{}.annot'.format(hemi, aparc_name)))
    mne.write_labels_to_annot(subject=subject,
                              labels=labels,
                              parc=aparc_name,
                              overwrite=overwrite,
                              subjects_dir=subjects_dir)
    return len(labels) > 0
Пример #8
0
def combine_movies(fol, movie_name, movie_type='mp4'):
    # First convert the part to avi, because mp4 cannot be concat
    cmd = 'ffmpeg -i concat:"'
    parts = sorted(glob.glob(op.join(fol, '{}_*.{}'.format(movie_name, movie_type))))
    for part_fname in parts:
        part_name, _ = op.splitext(part_fname)
        cmd = '{}{}.avi|'.format(cmd, op.join(fol, part_name))
        utils.remove_file('{}.avi'.format(part_name))
        utils.run_script('ffmpeg -i {} -codec copy {}.avi'.format(part_fname, op.join(fol, part_name)))
    # cmd = '{}" -c copy -bsf:a aac_adtstoasc {}'.format(cmd[:-1], op.join(fol, '{}.{}'.format(movie_name, movie_type)))
    cmd = '{}" -c copy {}'.format(cmd[:-1], op.join(fol, '{}.{}'.format(movie_name, movie_type)))
    print(cmd)
    utils.remove_file('{}.{}'.format(op.join(fol, movie_name), movie_type))
    utils.run_script(cmd)
    # clean up
    # todo: doesn't clean the part filess
    utils.remove_file('{}.avi'.format(op.join(fol, movie_name)))
    for part_fname in parts:
        part_name, _ = op.splitext(part_fname)
        utils.remove_file('{}.avi'.format(part_name))
Пример #9
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)
Пример #10
0

if __name__ == '__main__':
    subject = 'mg106'
    frames_fol = 'MG106_HGP_sess2_4'
    fname = 'MG106_HGP_sess2_2'
    times_per_frame = 0.1
    cut_in_break = False
    # last_frame_len = 5 * 60
    times_field = 'time2'

    times = load_times(subject, '{}.mat'.format(fname), times_field)
    last_frame_len = np.diff(times)[0]
    frames = load_frames(subject, frames_fol_name=frames_fol)
    break_ind = get_breakind(times) if cut_in_break else len(times)
    print('max time: {} minutes'.format(
        times[break_ind if cut_in_break else len(times) - 1] / 60))
    new_frames = duplicate_frames(frames,
                                  times,
                                  times_per_frame,
                                  last_frame_len,
                                  max_frames_num=break_ind)
    dup_fol = create_dup_frames_links(subject, new_frames,
                                      '{}_dup'.format(frames_fol))
    movie_fname = movu.combine_images(dup_fol,
                                      frames_fol,
                                      frame_rate=int(1 / times_per_frame))
    new_movie_fname = op.join(MMVT_DIR, subject, 'figures',
                              utils.namebase_with_ext(movie_fname))
    utils.remove_file(new_movie_fname)
    shutil.move(movie_fname, new_movie_fname)
Пример #11
0
def post_blender_call(args):
    if not args.add_cb and not args.join_hemis:
        return

    from src.utils import figures_utils as fu
    from src.utils import utils
    from PIL import Image

    if args.call_mmvt_calls:
        su.waits_for_file(args.log_fname)
    with open(args.images_log_fname, 'r') as text_file:
        images_names = text_file.readlines()
    images_names = [l.strip() for l in images_names]
    data_max, data_min = list(map(float, args.cb_vals))
    ticks = list(map(float,
                     args.cb_ticks)) if args.cb_ticks is not None else None
    background = args.background_color  # '#393939'
    if args.join_hemis:
        images_hemi_inv_list = set([
            utils.namebase(fname)[3:] for fname in images_names
            if utils.namebase(fname)[:2] in ['rh', 'lh']
        ])
        files = [[
            fname for fname in images_names
            if utils.namebase(fname)[3:] == img_hemi_inv
        ] for img_hemi_inv in images_hemi_inv_list]
        fol = utils.get_fname_folder(files[0][0])
        cb_fname = op.join(fol, '{}_colorbar.jpg'.format(args.cb_cm))
        # if not op.isfile(cb_fname):
        fu.plot_color_bar(data_max,
                          data_min,
                          args.cb_cm,
                          do_save=True,
                          ticks=ticks,
                          fol=fol,
                          background_color=background,
                          cb_ticks_font_size=args.cb_ticks_font_size)
        cb_img = Image.open(cb_fname)
        for files_coup in files:
            hemi = 'rh' if utils.namebase(
                files_coup[0]).startswith('rh') else 'lh'
            coup_template = files_coup[0].replace(hemi, '{hemi}')
            coup = {
                hemi: coup_template.format(hemi=hemi)
                for hemi in utils.HEMIS
            }
            new_image_fname = op.join(
                fol,
                utils.namebase_with_ext(files_coup[0])[3:])
            if args.add_cb:
                if args.crop_figures:
                    fu.crop_image(coup['lh'],
                                  coup['lh'],
                                  dx=150,
                                  dy=0,
                                  dw=50,
                                  dh=70)
                    fu.crop_image(coup['rh'],
                                  coup['rh'],
                                  dx=150 + 50,
                                  dy=0,
                                  dw=0,
                                  dh=70)
                fu.combine_two_images(coup['lh'],
                                      coup['rh'],
                                      new_image_fname,
                                      facecolor=background,
                                      dpi=200,
                                      w_fac=1,
                                      h_fac=1)
                fu.combine_brain_with_color_bar(new_image_fname,
                                                cb_img,
                                                overwrite=True)
            else:
                if args.crop_figures:
                    fu.crop_image(coup['lh'],
                                  coup['lh'],
                                  dx=150,
                                  dy=0,
                                  dw=150,
                                  dh=0)
                    fu.crop_image(coup['rh'],
                                  coup['rh'],
                                  dx=150,
                                  dy=0,
                                  dw=150,
                                  dh=0)
                fu.combine_two_images(coup['lh'],
                                      coup['rh'],
                                      new_image_fname,
                                      facecolor=background)
            if args.remove_temp_figures:
                for hemi in utils.HEMIS:
                    utils.remove_file(coup[hemi])
    elif args.add_cb and not args.join_hemis:
        fol = utils.get_fname_folder(images_names[0])
        cb_fname = op.join(fol, '{}_colorbar.jpg'.format(args.cb_cm))
        if not op.isfile(cb_fname):
            fu.plot_color_bar(data_max,
                              data_min,
                              args.cb_cm,
                              do_save=True,
                              ticks=ticks,
                              fol=fol,
                              background_color=background)
        cb_img = Image.open(cb_fname)
        for fig_name in images_names:
            fu.combine_brain_with_color_bar(fig_name, cb_img, overwrite=True)
Пример #12
0
def meg_calc_labels_ts(subject,
                       inv_method='MNE',
                       em='mean_flip',
                       atlas='electrodes_labels',
                       remote_subject_dir='',
                       meg_remote_dir='',
                       meg_epochs_dir='',
                       empty_fname='',
                       cor_fname='',
                       use_demi_events=True,
                       n_jobs=-1):
    functions = 'make_forward_solution,calc_inverse_operator,calc_stc,calc_labels_avg_per_condition'

    epochs_files = glob.glob(
        op.join(meg_epochs_dir, '**',
                '{}_*_Resting_eeg_meg_Demi_ar-epo.fif'.format(subject)))
    output_files = glob.glob(
        op.join(MMVT_DIR, subject, 'meg',
                'labels_data_rest_electrodes_labels_dSPM_mean_flip_*.npz'))
    for output_fname in output_files:
        utils.remove_file(output_fname)

    for ind, epo_fname in enumerate(epochs_files):
        # Remove  '/autofs/space/karima_002/users/Machine_Learning_Clinical_MEG_EEG_Resting/epochs/nmr00479_4994627_vef',
        fol = utils.make_dir(
            op.join(MMVT_DIR, subject, 'meg', utils.namebase(epo_fname)))
        overwrite_source_bem = args.overwrite_source_bem if ind == 0 else False

        meg_args = meg.read_cmd_args(
            dict(
                subject=subject,
                mri_subject=subject,
                task='rest',
                inverse_method=inv_method,
                extract_mode=em,
                atlas=atlas,
                single_trial_stc=True,
                recreate_src_spacing='ico5',
                fwd_recreate_source_space=overwrite_source_bem,
                recreate_bem_solution=overwrite_source_bem,
                remote_subject_meg_dir=meg_remote_dir,
                remote_subject_dir=remote_subject_dir,
                epo_fname=epo_fname,
                empty_fname=empty_fname,
                cor_fname=cor_fname,
                function=functions,
                use_demi_events=use_demi_events,
                stc_template=utils.namebase(epo_fname)[:-4],
                # windows_length=10000,
                # windows_shift=5000,
                # overwrite_fwd=True,
                # overwrite_inv=True,
                # overwrite_labels_data=True,
                using_auto_reject=False,
                use_empty_room_for_noise_cov=True,
                read_only_from_annot=False,
                n_jobs=n_jobs))
        meg.call_main(meg_args)

        output_files = glob.glob(
            op.join(MMVT_DIR, subject, 'meg',
                    'labels_data_rest_electrodes_labels_dSPM_mean_flip_*.npz'))
        for output_fname in output_files:
            utils.move_file(output_fname, fol, overwrite=True)