def analyze_rest(subject, args, hcp_params, run_index=0, calc_rest_from_raw=False, calc_rest_from_epochs=True):
    flags = {}
    if not op.isfile(meg.RAW):
        raw = read_raw_data(run_index, hcp_params, 1, 60)
        raw.save(meg.RAW)
    else:
        raw = mne.io.read_raw_fif(meg.RAW)
    meg.COR = op.join(op.join(HCP_DIR, 'hcp-meg', subject, '{}-head_mri-trans.fif'.format(subject)))
    epo_fname = meg.EPO.format(cond='all')
    evo_fname = meg.EVO.format(cond='all')
    if not op.isfile(epo_fname) or not op.isfile(evo_fname):
        epochs = hcp.read_epochs(run_index=run_index, **hcp_params)
        evoked = epochs.average()
        epochs.save(epo_fname)
        mne.write_evokeds(evo_fname, evoked)
    else:
        epochs = mne.read_epochs(epo_fname)
    meg.calc_fwd_inv_wrapper(subject, args)
    args.snr = 1.0  # use smaller SNR for raw data
    # args.overwrite_labels_data = True
    # args.n_jobs = 1
    if calc_rest_from_raw:
        meg.calc_labels_avg_for_rest_wrapper(args, raw)
    elif calc_rest_from_epochs:
        args.single_trial_stc = True
        flags, stcs_conds, stcs_num = meg.calc_stc_per_condition_wrapper(
            subject, None, args.inverse_method, args, flags, None, epochs)
        flags = meg.calc_labels_avg_per_condition_wrapper(
            subject, None, args.atlas, args.inverse_method, stcs_conds, args, flags, stcs_num, raw, epochs)

    print('sdf')
Exemple #2
0
def main(tup, remote_subject_dir, args, flags):
    (subject, mri_subject), inverse_method = tup
    evoked, epochs = None, None
    fname_format, fname_format_cond, conditions = meg.init_main(subject, mri_subject, args)
    meg.init_globals_args(subject, mri_subject, fname_format, fname_format_cond, SUBJECTS_EEG_DIR, SUBJECTS_MRI_DIR,
                     MMVT_DIR, args)
    meg.MEG_DIR = SUBJECTS_EEG_DIR
    meg.FWD = meg.FWD_EEG
    meg.INV = meg.INV_EEG
    stat = meg.STAT_AVG if len(conditions) == 1 else meg.STAT_DIFF

    if utils.should_run(args, 'read_eeg_sensors_layout'):
        flags['read_eeg_sensors_layout'] = read_eeg_sensors_layout(subject, mri_subject, args)

    flags = meg.calc_evoked_wrapper(subject, conditions, args, flags)

    if utils.should_run(args, 'create_eeg_mesh'):
        flags['create_eeg_mesh'] = create_eeg_mesh(mri_subject, args.eeg_electrodes_excluded_from_mesh)

    if utils.should_run(args, 'save_evoked_to_blender'):
        flags['save_evoked_to_blender'] = save_evoked_to_blender(mri_subject, conditions, args, evoked)
    if not op.isfile(meg.COR):
        eeg_cor = op.join(meg.SUBJECT_MEG_FOLDER, '{}-cor-trans.fif'.format(subject))
        if not op.isfile(eeg_cor):
            raise Exception("Can't find head-MRI transformation matrix. Should be in {} or in {}".format(meg.COR, eeg_cor))
        meg.COR = eeg_cor
    flags = meg.calc_fwd_inv_wrapper(subject, mri_subject, conditions, args, flags)
    flags = meg.calc_stc_per_condition_wrapper(subject, conditions, inverse_method, args, flags)
    return flags
Exemple #3
0
def analyze_task(subject, args, hcp_params):
    flags = {}
    events = dict(face=1, tools=2)
    baseline = (-0.5, 0)

    all_events = collect_events(hcp_params)
    files_exist = all([
        op.isfile(meg.get_cond_fname(meg.EPO, event))
        and op.isfile(meg.get_cond_fname(meg.EVO, event))
        for event in events.keys()
    ])
    if not files_exist:
        epochs_hcp, evokeds_from_epochs_hcp = using_preprocessed_epochs(
            all_events, events, baseline, hcp_params)
        for event in events.keys():
            epochs_hcp[event].save(meg.get_cond_fname(meg.EPO, event))
            mne.write_evokeds(meg.get_cond_fname(meg.EVO, event),
                              evokeds_from_epochs_hcp[event])

    flags = meg.calc_fwd_inv_wrapper(subject, args, events, flags)
    flags, stcs_conds, _ = meg.calc_stc_per_condition_wrapper(
        subject, events, args.inverse_method, args, flags)
    flags = meg.calc_labels_avg_per_condition_wrapper(subject, events,
                                                      args.atlas,
                                                      args.inverse_method,
                                                      stcs_conds, args, flags)
Exemple #4
0
def main(tup, remote_subject_dir, args, flags):
    (subject, mri_subject), inverse_method = tup
    evoked, epochs = None, None
    conditions, stat = init(subject, args, mri_subject, remote_subject_dir)

    if utils.should_run(args, 'read_sensors_layout'):
        flags['read_sensors_layout'] = read_sensors_layout_args(
            mri_subject, args)

    flags, evoked, epochs = meg.calc_evokes_wrapper(subject,
                                                    conditions,
                                                    args,
                                                    flags,
                                                    mri_subject=mri_subject)

    flags = meg.calc_fwd_inv_wrapper(subject, args, conditions, flags,
                                     mri_subject)

    flags, stcs_conds, stcs_num = meg.calc_stc_per_condition_wrapper(
        subject, conditions, inverse_method, args, flags)

    flags = meg.calc_labels_avg_per_condition_wrapper(subject, conditions,
                                                      args.atlas,
                                                      inverse_method,
                                                      stcs_conds, args, flags,
                                                      stcs_num, None, epochs)

    if 'calc_stc_zvals' in args.function:
        flags['calc_stc_zvals'] = meg.calc_stc_zvals(
            subject, args.stc_name, args.baseline_stc_name, 'eeg',
            args.use_abs, args.from_index, args.to_index, args.stc_zvals_name,
            False, args.overwrite_stc)

    if utils.should_run(args, 'create_helmet_mesh'):
        flags['create_helmet_mesh'] = create_helmet_mesh(
            mri_subject, args.eeg_electrodes_excluded_from_mesh)

    if utils.should_run(args, 'save_evoked_to_blender'):
        flags['save_evoked_to_blender'] = save_evoked_to_blender(
            mri_subject, conditions, args, evoked)

    if utils.should_run(args, 'calc_minmax'):
        flags['calc_minmax'] = calc_minmax(mri_subject, args)

    if 'plot_evoked' in args.function:
        flags['plot_evoked'], _ = plot_evoked(args.evo_fname, args.evoked_key,
                                              args.pick_meg, args.pick_eeg,
                                              args.pick_eog, args.ssp_proj,
                                              args.spatial_colors,
                                              args.window_title, args.hline,
                                              args.channels_to_exclude)

    if 'snap_sensors_to_outer_skin' in args.function:
        flags['snap_sensors_to_outer_skin'] = snap_sensors_to_outer_skin(
            mri_subject)

    return flags
Exemple #5
0
def main(tup, remote_subject_dir, args, flags):
    (subject, mri_subject), inverse_method = tup
    evoked, epochs = None, None
    conditions, stat = init(subject, args, mri_subject, remote_subject_dir)

    if utils.should_run(args, 'read_eeg_sensors_layout'):
        flags['read_eeg_sensors_layout'] = read_eeg_sensors_layout(
            subject, mri_subject, args)

    flags, evoked, epochs = meg.calc_evokes_wrapper(subject,
                                                    conditions,
                                                    args,
                                                    flags,
                                                    mri_subject=mri_subject)

    if utils.should_run(args, 'create_eeg_mesh'):
        flags['create_eeg_mesh'] = create_eeg_mesh(
            mri_subject, args.eeg_electrodes_excluded_from_mesh)

    if utils.should_run(args, 'save_evoked_to_blender'):
        flags['save_evoked_to_blender'] = save_evoked_to_blender(
            mri_subject, conditions, args, evoked)

    if utils.should_run(args, 'calc_minmax'):
        flags['calc_minmax'] = calc_minmax(mri_subject, args)

    if utils.should_run(args, 'make_forward_solution') or utils.should_run(args, 'calc_inverse_operator') or \
            utils.should_run(args, 'calc_stc'):
        if not op.isfile(meg.COR):
            eeg_cor = op.join(meg.SUBJECT_MEG_FOLDER,
                              '{}-cor-trans.fif'.format(subject))
            if op.isfile(eeg_cor):
                meg.COR = eeg_cor
                flags = meg.calc_fwd_inv_wrapper(subject, args, conditions,
                                                 flags, mri_subject)
                flags = meg.calc_stc_per_condition_wrapper(
                    subject, conditions, inverse_method, args, flags)
            else:
                print(
                    "Can't find head-MRI transformation matrix. Should be in {} or in {}"
                    .format(meg.COR, eeg_cor))

    return flags
def analyze(subject, raw_files_template, inverse_method, conditions, sessions,
            args):
    overwrite_raw = False
    only_examine_ica = False
    plot_evoked = False
    calc_stc_per_session = True
    look_for_ica_eog_file = True
    filter_raw_data = True
    raw_data_filter_freqs = (int(args.l_freq), int(args.h_freq))
    eog_inds_fname = op.join(MEG_DIR, subject, 'ica_eog_comps.txt')
    # args.noise_cov_fname = op.join(MEG_DIR, subject, 'noise-cov.fif')
    freqs_str = '-{}-{}'.format(
        raw_data_filter_freqs[0],
        raw_data_filter_freqs[1]) if filter_raw_data else ''
    if op.isfile(eog_inds_fname):
        all_eog_inds = np.genfromtxt(eog_inds_fname,
                                     dtype=np.str,
                                     delimiter=',',
                                     autostrip=True)
    else:
        if look_for_ica_eog_file:
            raise Exception(
                "Can't find the ICA eog file! {}".format(eog_inds_fname))
        all_eog_inds = []
    for cond, cond_key in conditions.items():
        args.inv_fname = op.join(MEG_DIR, subject, '{}-inv.fif'.format(cond))
        args.fwd_fname = op.join(MEG_DIR, subject, '{}-fwd.fif'.format(cond))
        args.evo_fname = op.join(MEG_DIR, subject,
                                 '{}{}-ave.fif'.format(cond, freqs_str))
        meg.calc_fwd_inv_wrapper(subject, args, cond)
        raw_files_cond = raw_files_template.format(cond=cond)
        raw_files = glob.glob(raw_files_cond)
        args.conditions = condition = {cond: cond_key}
        for ctf_raw_data in raw_files:
            calc_per_session(subject, condition, ctf_raw_data, inverse_method,
                             args, all_eog_inds, eog_channel,
                             calc_stc_per_session, only_examine_ica,
                             overwrite_raw, plot_evoked, filter_raw_data,
                             raw_data_filter_freqs)
        combine_evokes(subject, cond, sessions, filter_raw_data,
                       raw_data_filter_freqs)

    for session in sessions:
        args.evo_fname = op.join(
            MEG_DIR, subject,
            '{}-session{}{}-ave.fif'.format('{cond}', session, freqs_str))
        args.inv_fname = op.join(
            MEG_DIR, subject, '{}-session{}-inv.fif'.format('{cond}', session))
        args.stc_template = op.join(
            MEG_DIR, subject,
            '{}-session{}-{}{}.stc'.format('{cond}', session, '{method}',
                                           freqs_str))
        args.labels_data_template = op.join(
            MEG_DIR, subject,
            'labels_data_session' + session + freqs_str + '_{}_{}_{}.npz')
        stc_hemi_template = meg.get_stc_hemi_template(args.stc_template)
        meg.calc_stc_diff_both_hemis(conditions, stc_hemi_template,
                                     inverse_method)
        meg.calc_labels_avg_per_condition_wrapper(subject, conditions,
                                                  args.atlas, inverse_method,
                                                  None, args)

    args.evo_fname = op.join(MEG_DIR, subject,
                             '{}{}-ave.fif'.format('{cond}', freqs_str))
    args.inv_fname = op.join(MEG_DIR, subject, '{cond}-inv.fif')
    args.stc_template = op.join(
        MEG_DIR, subject, '{}-{}{}.stc'.format('{cond}', '{method}',
                                               freqs_str))
    args.labels_data_template = op.join(
        MEG_DIR, subject, 'labels_data' + freqs_str + '_{}_{}_{}.npz')
    _, stcs_conds, _ = meg.calc_stc_per_condition_wrapper(
        subject, conditions, inverse_method, args)
    meg.calc_labels_avg_per_condition_wrapper(subject, conditions, args.atlas,
                                              inverse_method, stcs_conds, args)
def calc_per_session(subject, condition, ctf_raw_data, inverse_method, args,
                     all_eog_inds, eog_channel, calc_stc_per_session,
                     only_examine_ica, overwrite_raw, plot_evoked,
                     filter_raw_data, raw_data_filter_freqs):
    session = ctf_raw_data[-4]
    cond = list(condition.keys())[0]
    freqs_str = '-{}-{}'.format(
        raw_data_filter_freqs[0],
        raw_data_filter_freqs[1]) if filter_raw_data else ''
    args.raw_fname = op.join(MEG_DIR, subject,
                             '{}-session{}-raw.fif'.format(cond, session))
    new_raw_no_filter_fname = op.join(
        MEG_DIR, subject, '{}-session{}-ica-raw.fif'.format(cond, session))
    new_raw_fname = op.join(
        MEG_DIR, subject,
        '{}-session{}{}-ica-raw.fif'.format(cond, session, freqs_str))
    args.epo_fname = op.join(
        MEG_DIR, subject,
        '{}-session{}{}-epo.fif'.format(cond, session, freqs_str))
    args.evo_fname = op.join(
        MEG_DIR, subject,
        '{}-session{}{}-ave.fif'.format(cond, session, freqs_str))
    args.inv_fname = op.join(MEG_DIR, subject,
                             '{}-session{}-inv.fif'.format(cond, session))
    args.fwd_fname = op.join(MEG_DIR, subject,
                             '{}-session{}-fwd.fif'.format(cond, session))
    args.noise_cov_fname = op.join(
        MEG_DIR, subject, '{}-session{}-noise-cov.fif'.format(cond, session))
    args.stc_template = op.join(
        MEG_DIR, subject,
        '{cond}-session' + session + '-{method}' + freqs_str + '.stc')
    stc_hemi_template = meg.get_stc_hemi_template(args.stc_template)
    if check_if_all_done(new_raw_fname, cond, inverse_method,
                         calc_stc_per_session, stc_hemi_template,
                         args.labels_data_template, args):
        return
    ica_fname = op.join(MEG_DIR, subject,
                        '{}-session{}-ica.fif'.format(cond, session))
    if len(all_eog_inds) > 0:
        session_ind = np.where(
            all_eog_inds[:, 0] == utils.namebase_with_ext(ica_fname))[0][0]
        eog_inds = [int(all_eog_inds[session_ind, 1])]
    else:
        eog_inds = []
    if only_examine_ica:
        meg.fit_ica(ica_fname=ica_fname,
                    do_plot=True,
                    examine_ica=True,
                    n_jobs=args.n_jobs)
        return
    if not op.isfile(new_raw_fname) or overwrite_raw or not op.isfile(
            ica_fname):
        if not op.isfile(args.raw_fname):
            raw = mne.io.read_raw_ctf(op.join(MEG_DIR, subject, 'raw',
                                              ctf_raw_data),
                                      preload=True)
            raw.save(args.raw_fname)
        if not op.isfile(new_raw_no_filter_fname):
            raw = mne.io.read_raw_fif(args.raw_fname, preload=True)
            raw = meg.remove_artifacts(raw,
                                       remove_from_raw=True,
                                       overwrite_ica=args.overwrite_ica,
                                       save_raw=True,
                                       raw_fname=new_raw_fname,
                                       new_raw_fname=new_raw_no_filter_fname,
                                       ica_fname=ica_fname,
                                       do_plot=args.do_plot_ica,
                                       eog_inds=eog_inds,
                                       eog_channel=eog_channel,
                                       n_jobs=args.n_jobs)
        else:
            raw = mne.io.read_raw_fif(new_raw_no_filter_fname, preload=True)
        meg.calc_noise_cov(None, args.noise_t_min, args.noise_t_max,
                           args.noise_cov_fname, args, raw)
        if filter_raw_data:
            raw.filter(raw_data_filter_freqs[0],
                       raw_data_filter_freqs[1],
                       h_trans_bandwidth='auto',
                       filter_length='auto',
                       phase='zero')
        print('Saving new raw file in {}'.format(new_raw_fname))
        if overwrite_raw or not op.isfile(new_raw_fname):
            raw.save(new_raw_fname, overwrite=True)
    else:
        raw = mne.io.read_raw_fif(new_raw_fname, preload=True)
    evoked, epochs = None, None
    if not op.isfile(args.epo_fname) or not op.isfile(args.evo_fname):
        _, evoked, epochs = meg.calc_evokes_wrapper(subject,
                                                    condition,
                                                    args,
                                                    raw=raw)
    if evoked is not None and plot_evoked:
        fig = evoked[0].plot_joint(times=[-0.5, 0.05, 0.150, 0.250, 0.6])
        plt.show()
    if calc_stc_per_session:
        meg.calc_fwd_inv_wrapper(subject, args, condition)
        # stcs_conds = None
        if not utils.both_hemi_files_exist(
                stc_hemi_template.format(
                    cond=cond, method=inverse_method, hemi='{hemi}')):
            _, stcs_conds, stcs_num = meg.calc_stc_per_condition_wrapper(
                subject, condition, inverse_method, args)