Ejemplo n.º 1
0
def run_ssp(subject):
    print("Processing subject: %s" % subject)
    meg_subject_dir = op.join(config.meg_dir, subject)

    print("  Loading one run to compute SSPs")

    # compute SSP on first run of raw
    run = config.runs[0]
    if config.use_maxwell_filter:
        extension = run + '_sss_raw'
    else:
        extension = run + '_filt_raw'
    raw_fname_in = op.join(meg_subject_dir,
                           config.base_fname.format(**locals()))

    extension = run + '_ssp-proj'
    proj_fname_out = op.join(meg_subject_dir,
                             config.base_fname.format(**locals()))

    print("Input: ", raw_fname_in)
    print("Output: ", proj_fname_out)

    raw = mne.io.read_raw_fif(raw_fname_in)
    # XXX : n_xxx should be options in config
    print("  Computing SSPs for ECG")
    ecg_projs, ecg_events = \
        compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
    print("  Computing SSPs for EOG")
    eog_projs, eog_events = \
        compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
def run_ssp(subject):
    print("processing subject: %s" % subject)
    meg_subject_dir = op.join(config.meg_dir, subject)

    print("  Loading runs")

    for run in config.runs:
        extension = run + '_sss_raw'
        raw_fname_in = op.join(meg_subject_dir,
                               config.base_fname.format(**locals()))
        proj_fname_out = op.splitext(raw_fname_in)[0] + '-proj.fif'
        eve_ecg_fname_out = op.splitext(raw_fname_in)[0] + '_ecg-eve.fif'
        eve_eog_fname_out = op.splitext(raw_fname_in)[0] + '_eog-eve.fif'
        print("Input: ", raw_fname_in)
        print("Output: ", proj_fname_out)
        print("Output: ", eve_ecg_fname_out)
        print("Output: ", eve_eog_fname_out)
        raw = mne.io.read_raw_fif(raw_fname_in)
        ecg_projs, ecg_events = \
            compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
        eog_projs, eog_events = \
            compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)

        mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
        mne.write_events(eve_ecg_fname_out, ecg_events)
        mne.write_events(eve_eog_fname_out, eog_events)
Ejemplo n.º 3
0
def run_ssp(subject, session=None):
    # compute SSP on first run of raw
    run = config.get_runs()[0]
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=config.get_task(),
                         acquisition=config.acq,
                         run=run,
                         recording=config.rec,
                         space=config.space,
                         extension='.fif',
                         datatype=config.get_datatype(),
                         root=config.deriv_root)

    # Prepare a name to save the data
    raw_fname_in = bids_path.copy().update(processing='filt',
                                           suffix='raw',
                                           check=False)

    # when saving proj, use run=None
    proj_fname_out = bids_path.copy().update(run=None,
                                             suffix='proj',
                                             check=False)

    msg = f'Input: {raw_fname_in}, Output: {proj_fname_out}'
    logger.info(
        gen_log_message(message=msg, step=4, subject=subject, session=session))

    if raw_fname_in.copy().update(split='01').fpath.exists():
        raw_fname_in.update(split='01')

    raw = mne.io.read_raw_fif(raw_fname_in)
    # XXX : n_xxx should be options in config
    msg = 'Computing SSPs for ECG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    ecg_projs, ecg_events = compute_proj_ecg(raw,
                                             n_grad=1,
                                             n_mag=1,
                                             n_eeg=0,
                                             average=True)
    msg = 'Computing SSPs for EOG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    if config.eog_channels:
        assert all(
            [ch_name in raw.ch_names for ch_name in config.eog_channels])
        ch_name = ','.join(config.eog_channels)
    else:
        ch_name = None

    eog_projs, eog_events = compute_proj_eog(raw,
                                             ch_name=ch_name,
                                             n_grad=1,
                                             n_mag=1,
                                             n_eeg=1,
                                             average=True)

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
Ejemplo n.º 4
0
def run_ssp(subject, session=None):
    print("Processing subject: %s" % subject)

    print("  Loading one run to compute SSPs")

    # Construct the search path for the data file. `sub` is mandatory
    subject_path = op.join('sub-{}'.format(subject))
    # `session` is optional
    if session is not None:
        subject_path = op.join(subject_path, 'ses-{}'.format(session))

    subject_path = op.join(subject_path, config.kind)

    # compute SSP on first run of raw
    run = config.runs[0]

    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.task,
                                       acquisition=config.acq,
                                       run=run,
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    # Prepare a name to save the data
    fpath_deriv = op.join(config.bids_root, 'derivatives',
                          config.PIPELINE_NAME, subject_path)

    raw_fname_in = \
        op.join(fpath_deriv, bids_basename + '_filt_raw.fif')

    # when saving proj, use bids_basename=None
    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.task,
                                       acquisition=config.acq,
                                       run=None,
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    proj_fname_out = op.join(fpath_deriv, bids_basename + '_ssp-proj.fif')

    print("Input: ", raw_fname_in)
    print("Output: ", proj_fname_out)

    raw = mne.io.read_raw_fif(raw_fname_in)
    # XXX : n_xxx should be options in config
    print("  Computing SSPs for ECG")
    ecg_projs, ecg_events = \
        compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
    print("  Computing SSPs for EOG")
    eog_projs, eog_events = \
        compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
Ejemplo n.º 5
0
def do_pca(raw, proj_nums):
    ecg_projs, ecg_events = compute_proj_ecg(raw_sss, n_grad=proj_nums[0][0],
                            n_mag=proj_nums[0][1],
                            average=True)

    eog_projs, eog_events = compute_proj_eog(raw_sss, n_grad=proj_nums[1][0],
                            n_mag=proj_nums[1][1],
                            average=True)
    raw_sss.info['projs'] += eog_projs + ecg_projs
    return raw_sss, (ecg_projs, eog_projs, ecg_events, eog_events)
Ejemplo n.º 6
0
def run_ssp(subject, session=None):
    deriv_path = config.get_subject_deriv_path(subject=subject,
                                               session=session,
                                               kind=config.get_kind())

    # compute SSP on first run of raw
    run = config.get_runs()[0]

    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.get_task(),
                                       acquisition=config.acq,
                                       run=run,
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    # Prepare a name to save the data
    raw_fname_in = op.join(deriv_path, bids_basename + '_filt_raw.fif')

    # when saving proj, use bids_basename=None
    bids_basename = make_bids_basename(subject=subject,
                                       session=session,
                                       task=config.get_task(),
                                       acquisition=config.acq,
                                       run=None,
                                       processing=config.proc,
                                       recording=config.rec,
                                       space=config.space)

    proj_fname_out = op.join(deriv_path, bids_basename + '_ssp-proj.fif')

    msg = f'Input: {raw_fname_in}, Output: {proj_fname_out}'
    logger.info(
        gen_log_message(message=msg, step=4, subject=subject, session=session))

    raw = mne.io.read_raw_fif(raw_fname_in)
    # XXX : n_xxx should be options in config
    msg = 'Computing SSPs for ECG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    ecg_projs, ecg_events = \
        compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
    msg = 'Computing SSPs for EOG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    eog_projs, eog_events = \
        compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
Ejemplo n.º 7
0
def run_ssp(subject, session=None):
    deriv_path = config.get_subject_deriv_path(subject=subject,
                                               session=session,
                                               kind=config.get_kind())

    # compute SSP on first run of raw
    run = config.get_runs()[0]
    bids_basename = BIDSPath(subject=subject,
                             session=session,
                             task=config.get_task(),
                             acquisition=config.acq,
                             run=run,
                             recording=config.rec,
                             space=config.space,
                             prefix=deriv_path)

    # Prepare a name to save the data
    raw_fname_in = bids_basename.copy().update(processing='filt',
                                               kind=config.get_kind(),
                                               extension='.fif')

    # when saving proj, use run=None
    proj_fname_out = bids_basename.copy().update(run=None,
                                                 kind='proj',
                                                 extension='.fif',
                                                 check=False)

    msg = f'Input: {raw_fname_in}, Output: {proj_fname_out}'
    logger.info(
        gen_log_message(message=msg, step=4, subject=subject, session=session))

    raw = mne.io.read_raw_fif(raw_fname_in)
    # XXX : n_xxx should be options in config
    msg = 'Computing SSPs for ECG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    ecg_projs, ecg_events = \
        compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
    msg = 'Computing SSPs for EOG'
    logger.debug(
        gen_log_message(message=msg, step=4, subject=subject, session=session))
    eog_projs, eog_events = \
        compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
def run_ssp(subject):
    print("processing subject: %s" % subject)
    meg_subject_dir = op.join(config.meg_dir, subject)
    raw_fnames_in = op.join(meg_subject_dir, '%s_audvis_filt_raw.fif' % subject)
    proj_fnames_out = op.join(meg_subject_dir, '%s_audvis_filt-proj.fif' % subject)

    print("  Loading runs")
    for raw_fname_in, proj_fname_out in zip(raw_fnames_in, proj_fnames_out):
        # XXX TODO
        raw = mne.io.read_raw_fif(raw_fnames_in)
        projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
        ecg_projs = projs[-2:]
        projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)
        eog_projs = projs[-3:]

        raw.info['projs'] += eog_projs + ecg_projs
        raw.apply_proj()
        raw.save(proj_fnames_out, overwrite=True)
Ejemplo n.º 9
0
def compute_ecg_eog_proj(raw,
                         ecg=True,
                         eog=True,
                         n_grad_ecg=1,
                         n_grad_eog=1,
                         n_mag_ecg=1,
                         n_mag_eog=1,
                         average=True,
                         vis=False,
                         add_proj=True):

    if ecg:
        projs, events_ecg = compute_proj_ecg(raw,
                                             n_grad=n_grad_ecg,
                                             n_mag=n_mag_ecg,
                                             average=average)
        ecg_projs = projs[-(n_mag_ecg + n_grad_ecg):]
        if add_proj:
            raw.info['projs'] += ecg_projs
        if vis:
            layout = mne.channels.read_layout('Vectorview-all')
            names = [name.replace(' ', '') for name in layout.names]
            layout.names = names
            mne.viz.plot_projs_topomap(ecg_projs, layout=layout)

    # Now for EOG
    if eog:
        projs, events_eog = compute_proj_eog(raw,
                                             n_grad=n_grad_eog,
                                             n_mag=n_mag_eog,
                                             average=average)
        eog_projs = projs[-(n_mag_eog + n_grad_eog):]
        if add_proj:
            raw.info['projs'] += eog_projs
        if vis:
            layout = mne.channels.read_layout('Vectorview-all')
            names = [name.replace(' ', '') for name in layout.names]
            layout.names = names
            mne.viz.plot_projs_topomap(eog_projs, layout=layout)

    return ecg_projs, eog_projs, events_ecg, events_eog
Ejemplo n.º 10
0
def preproc_gen_ssp(subj_fold, raw, hcp_params, annots):
    """Helper to apply artifact removal on raw data

    NOTE: Only use this on one run of data to create projectors. Subsequent
    runs should load and apply the same projectors. This is required to make
    sure machine learning algorithm isn't classifying differences in projectors
    (like the ICA projectors shipped with HCP) instead of differences in
    activity."""

    proj_dir = op.join(hcp_path, subj_fold, 'ssp_pca_fif')
    check_and_create_dir(proj_dir)

    # Compute EOG and ECG projectors
    # XXX Note: do not add these to raw obj, as all raw files need to use the
    #     same projectors. Instead, save and then reapply later
    preproc.set_eog_ecg_channels(raw)

    proj_eog1, eog_events1 = compute_proj_eog(raw, ch_name='HEOG', n_jobs=-1)
    proj_eog2, eog_events2 = compute_proj_eog(raw, ch_name='VEOG', n_jobs=-1)
    proj_ecg, ecg_events = compute_proj_ecg(raw, ch_name='ECG', n_jobs=-1)

    # Save to disk so these can be used in future processing
    all_projs = proj_eog1 + proj_eog2 + proj_ecg
    write_proj(op.join(proj_dir, 'preproc_all-proj.fif'), all_projs)
import mne
from mne.preprocessing import compute_proj_ecg

sample_data_folder = mne.datasets.sample.data_path()
sample_data_raw_file = os.path.join(sample_data_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')

raw = mne.io.read_raw_fif(sample_data_raw_file)

###############################################################################
# For this tutorial we'll crop and resample the raw data to a manageable size
# for our web server to handle, ignore EEG channels, and remove the heartbeat
# artifact so we don't get spurious correlations just because of that.

raw.crop(tmax=150).resample(100).pick('meg')
ecg_proj, _ = compute_proj_ecg(raw, ch_name='MEG 0511')  # No ECG chan
raw.add_proj(ecg_proj)
raw.apply_proj()

###############################################################################
# To create fixed length epochs, we simply call the function and provide it
# with the appropriate parameters indicating the desired duration of epochs in
# seconds, whether or not to preload data, whether or not to reject epochs that
# overlap with raw data segments annotated as bad, whether or not to include
# projectors, and finally whether or not to be verbose. Here, we choose a long
# epoch duration (30 seconds). To conserve memory, we set ``preload`` to
# ``False``.

epochs = mne.make_fixed_length_epochs(raw, duration=30, preload=False)

###############################################################################
Ejemplo n.º 12
0
all_epochs = []
event_dict = {'300': 300, '800': 800, '1300': 1300}
reject_criteria = dict(mag=3000e-15,  # 3000 fT
                       grad=3000e-13)  # 3000 fT/cm

tmin, tmax = (-0.2, 1.1)  # epoch from 200 ms before event to 1000 ms after it
baseline = (None, 0)  # baseline period from start of epoch to time=0

raws = []

for index, meg_file in enumerate(meg_files):
    raw = mne.io.read_raw(op.join(subject_meg_dir, meg_file))
    raws.append(raw)

raw = mne.concatenate_raws(raws)
projs_ecg, ecg_events = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog = mne.read_proj(proj_file)
cov = mne.compute_raw_covariance(raw, tmin=0, tmax=None)

for index, meg_file in enumerate(meg_files):
    raw = mne.io.read_raw(op.join(subject_meg_dir, meg_file), preload=True)
    raw.info['projs'] += projs_ecg
    raw.info['projs'] += projs_eog
    raw.apply_proj()
    events = mne.read_events(events_files[index])
    raw = raw.filter(0.1, 110, l_trans_bandwidth='auto', h_trans_bandwidth='auto',
                     filter_length='auto', phase='zero', fir_window='hann')
    epochs = mne.Epochs(raw, events, event_dict, tmin, tmax, proj=True,
                        baseline=baseline, reject=reject_criteria, preload=True)
    epochs.resample(330.)
    all_epochs.append(epochs)
Ejemplo n.º 13
0
            '''

            # EOG and ECG artifact repair

            # pick some channels that clearly show heartbeats and blinks
            regexp = 'EEG'
            artifact_picks = mne.pick_channels_regexp(raw.ch_names,
                                                      regexp=regexp)
            # raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
            # ECG artifact repair

            ecg_evoked = create_ecg_epochs(raw, ch_name='ECG').average()
            ecg_evoked.apply_baseline((None, None))
            # ecg_evoked.plot_joint()
            ecg_projs, events = compute_proj_ecg(raw,
                                                 n_eeg=1,
                                                 ch_name='ECG',
                                                 reject=None)
            '''for title in ('Without', 'With'):
                if title == 'With':
                    raw.add_proj(ecg_projs)
                fig = raw.plot(order=artifact_picks, n_channels=len(artifact_picks))
                fig.subplots_adjust(top=0.9)  # make room for title
                fig.suptitle('{} ECG projectors'.format(title), size='xx-large',
                             weight='bold')
            '''
            #EOG artifact repair
            eog_evoked = create_eog_epochs(raw).average()
            eog_evoked.apply_baseline((None, None))
            # eog_evoked.plot_joint()
            eog_projs, _ = compute_proj_eog(raw,
                                            n_eeg=1,
from mne.datasets import sample
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname, preload=True)

##############################################################################
# Compute SSP projections
# -----------------------
#
# First let's do ECG.

projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
print(projs)

ecg_projs = projs[-2:]
mne.viz.plot_projs_topomap(ecg_projs)

###############################################################################
# Now let's do EOG. Here we compute an EEG projector, and need to pass
# the measurement info so the topomap coordinates can be created.

projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)
print(projs)

eog_projs = projs[-3:]
mne.viz.plot_projs_topomap(eog_projs, info=raw.info)
Ejemplo n.º 15
0
    def raw_preprocessing(self, raw, use_ica=True, use_ssp=True):

        # Filter

        raw.info['bads'] = self.bad_channels

        # Remove power-line noise
        raw.notch_filter(np.arange(60, 241, 60),
                         picks=self.picks,
                         filter_length='auto',
                         phase=self.phase)
        raw.filter(l_freq=self.l_freq,
                   h_freq=self.h_freq,
                   phase=self.phase,
                   fir_window=self.fir_window,
                   fir_design=self.fir_design)

        # Add EEG reference
        raw.set_eeg_reference(projection=True)

        # TODO: some mechanism to control this
        if use_ica:
            # supported ica_channels = ['mag', 'grad', 'eeg', 'seeg', 'ecog', 'hbo', 'hbr', 'eog']
            ica_picks = mne.pick_types(raw.info,
                                       meg=True,
                                       eeg=False,
                                       eog=False,
                                       stim=False,
                                       exclude='bads')
            n_components = 25
            decim = 3

            # maximum number of components to reject
            n_max_ecg, n_max_eog = 3, 1  # here we don't expect horizontal EOG components

            # ica = run_ica(raw, n_components=0.95)

            ica = ICA(n_components=n_components,
                      method='fastica',
                      noise_cov=None)
            ica.fit(raw, decim=decim, picks=ica_picks, reject=self.reject)

            # generate ECG epochs use detection via phase statistics

            ecg_epochs = create_ecg_epochs(raw, reject=self.reject)

            ecg_inds, scores = ica.find_bads_ecg(ecg_epochs, method='ctps')

            ecg_inds = ecg_inds[:n_max_ecg]
            ica.exclude += ecg_inds

            # detect EOG by correlation

            eog_inds, scores = ica.find_bads_eog(raw)

            eog_inds = eog_inds[:n_max_eog]
            ica.exclude += eog_inds

            ica.apply(raw)

        if use_ssp:
            if self.ecg:
                ecg_projs, _ = compute_proj_ecg(raw)
                raw.info['projs'] += ecg_projs
            if self.blink:
                eog_projs, _ = compute_proj_eog(raw)
                raw.info['projs'] += eog_projs

        raw.apply_proj()
        return raw
def run_correlation(subjects_dir, subject, volume_spacing, freq):

    num_threads(8)
    frequency = str(freq)
    DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files')
    eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz'
    eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz'
    fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif'
    t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
    heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz'
    fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd-label.fif.gz'
    src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src-label.fif.gz'
    cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}-label.fif.gz'
    raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}-label.fif.gz'
    raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj-label.fif.gz'
    source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl'
    freesurfer_label = f'{DATA_DIR}/{subject}_freesurferlabel_{volume_spacing}-label.pkl'
    corr_true_file_label = f'{DATA_DIR}/{subject}_corr_ortho_true_{volume_spacing}_{frequency}_label.npy'

    check_for_files = []
    check_for_files.append(corr_true_file_label)


    file_exist = [f for f in check_for_files if os.path.isfile(f)]
    file_not_exist = list(set(file_exist) ^ set(check_for_files))

    if not file_not_exist:
        print('correlation files exists...')

    else:
        trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration
        file_trans = pathlib.Path(trans)
        file_ss = pathlib.Path(src_fname)
        file_fm = pathlib.Path(fwd_fname)
        file_proj = pathlib.Path(raw_proj)
        file_cov = pathlib.Path(cov_fname)
        file_rawcov = pathlib.Path(raw_cov_fname)
        t1 = nib.load(t1_fname)

        if not file_trans.exists():
            print (f'{trans} File doesnt exist...')
            sys.exit(0)

        info = mne.io.read_info(fname_meg)
        # plot_registration(info, trans, subject, subjects_dir)

        print(file_ss)
        if not file_ss.exists():

            src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', 
                                volume_spacing=volume_spacing)

            src.save(src_fname, overwrite=True)
        src = mne.read_source_spaces(src_fname)
        #view_SS_brain(subject, subjects_dir, src)

        if not file_fm.exists():
            forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname)
        fwd = mne.read_forward_solution(fwd_fname)


       
        # sensitivty_plot(subject, subjects_dir, fwd)
        raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True)

        srate = raw.info['sfreq']
        n_time_samps = raw.n_times
        time_secs = raw.times
        ch_names = raw.ch_names
        n_chan = len(ch_names)
        freq_res =  srate/n_time_samps
        print('\n')
        print('-------------------------- Data summary-------------------------------')
        print(f'Subject {subject}')
        print(f"Frequency resolution {freq_res} Hz")
        print(f"The first few channel names are {ch_names[:3]}")
        print(f"The last time sample at {time_secs[-1]} seconds.")
        print(f"Sampling Frequency (No of time points/sec) {srate} Hz")
        print(f"Miscellaneous acquisition info {raw.info['description']}")
        print(f"Bad channels marked during data acquisition {raw.info['bads']}")
        print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices
        print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.")
        print('------------------------------------------------------------------------')
        print('\n')
        # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True)
        if not file_proj.exists():
            projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063')
            projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061')
            projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062')
            if projs_ecg is not None:
                mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors
                raw.info['projs'] += projs_ecg
            if projs_eog1 is not None:
                mne.write_proj(eye_proj1, projs_eog1)
                raw.info['projs'] += projs_eog1
            if projs_eog2 is not None:
                mne.write_proj(eye_proj2, projs_eog2)
                raw.info['projs'] += projs_eog2
            raw.apply_proj()
            raw.save(raw_proj, proj=True, overwrite=True)
        print(raw_proj)
        raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True)


        print(f'High-pass filtering data at 0.5 Hz')
        raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir')

        if not file_cov.exists():
            cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest
            mne.write_cov(cov_fname, cov)
        cov = mne.read_cov(cov_fname) 

        # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False
        # raw_proj_applied.crop(tmax=10)
        
        do_epochs = False

        l_freq = freq-2.0
        h_freq = freq+2.0
        print(f'Band pass filter data [{l_freq}, {h_freq}]')
        raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq)

        if do_epochs:
            print('Segmenting raw data...')
            events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.)
            raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5.,
                                            baseline=None, preload=True)
            data_cov = mne.compute_covariance(raw_proj_filtered)         
        else:
            if not file_rawcov.exists():
                data_cov = mne.compute_raw_covariance(raw_proj_filtered)
                mne.write_cov(raw_cov_fname, data_cov)
            else:
                data_cov = mne.read_cov(file_rawcov)

        filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov,
                            pick_ori='max-power', weight_norm='nai')
        raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert()

        if do_epochs:
            stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False)
        else:
            stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True)
        
        print('Extracting label time course...')
        atlas = f'{subjects_dir}/{subject}/mri/aparc.a2009s+aseg.mgz'
        label_ts = mne.extract_label_time_course(stcs, atlas, fwd['src'], return_generator=False)
        label_ts = [label_ts]

        # Power Envelope Correlation
        print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize True')

        all_corr = envelope_correlation(label_ts, combine=None, orthogonalize="pairwise",
                    log=True, absolute=True, verbose=None)

        print(f'Correlation saved to {corr_true_file_label}')
        np.save(corr_true_file_label, all_corr)

        del stcs
ecg_evoked.apply_baseline((None, None))
ecg_evoked.plot_joint()

###############################################################################
# To compute SSP projectors for the heartbeat artifact, you can use
# `~mne.preprocessing.compute_proj_ecg`, which takes a
# `~mne.io.Raw` object as input and returns the requested number of
# projectors for magnetometers, gradiometers, and EEG channels (default is two
# projectors for each channel type).
# `~mne.preprocessing.compute_proj_ecg` also returns an :term:`events`
# array containing the sample numbers corresponding to the peak of the
# `R wave <https://en.wikipedia.org/wiki/QRS_complex>`__ of each detected
# heartbeat.

projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=1, reject=None)

###############################################################################
# The first line of output tells us that
# `~mne.preprocessing.compute_proj_ecg` found three existing projectors
# already in the `~mne.io.Raw` object, and will include those in the
# list of projectors that it returns (appending the new ECG projectors to the
# end of the list). If you don't want that, you can change that behavior with
# the boolean ``no_proj`` parameter. Since we've already run the computation,
# we can just as easily separate out the ECG projectors by indexing the list of
# projectors:

ecg_projs = projs[3:]
print(ecg_projs)

###############################################################################
Ejemplo n.º 18
0
def run_ssp(*, cfg, subject, session=None):
    # compute SSP on first run of raw
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=cfg.runs[0],
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root)

    # Prepare a name to save the data
    raw_fname_in = bids_path.copy().update(processing='filt', suffix='raw',
                                           check=False)

    # when saving proj, use run=None
    proj_fname_out = bids_path.copy().update(run=None, suffix='proj',
                                             check=False)

    msg = f'Input: {raw_fname_in}, Output: {proj_fname_out}'
    logger.info(**gen_log_kwargs(message=msg, subject=subject,
                                 session=session))

    if raw_fname_in.copy().update(split='01').fpath.exists():
        raw_fname_in.update(split='01')

    raw = mne.io.read_raw_fif(raw_fname_in)
    msg = 'Computing SSPs for ECG'
    logger.debug(**gen_log_kwargs(message=msg, subject=subject,
                                  session=session))

    ecg_projs = []
    ecg_epochs = create_ecg_epochs(raw)
    if len(ecg_epochs) >= config.min_ecg_epochs:
        if cfg.ssp_reject_ecg == 'autoreject_global':
            reject_ecg_ = config.get_ssp_reject(
                ssp_type='ecg',
                epochs=ecg_epochs)
            ecg_projs, _ = compute_proj_ecg(raw,
                                            average=cfg.ecg_proj_from_average,
                                            reject=reject_ecg_,
                                            **cfg.n_proj_ecg)
        else:
            reject_ecg_ = config.get_ssp_reject(
                    ssp_type='ecg',
                    epochs=None)
            ecg_projs, _ = compute_proj_ecg(raw,
                                            average=cfg.ecg_proj_from_average,
                                            reject=reject_ecg_,
                                            **cfg.n_proj_ecg)

    if not ecg_projs:
        msg = ('Not enough ECG events could be found. No ECG projectors are '
               'computed.')
        logger.info(**gen_log_kwargs(message=msg, subject=subject,
                                     session=session))

    msg = 'Computing SSPs for EOG'
    logger.debug(**gen_log_kwargs(message=msg, subject=subject,
                                  session=session))
    if cfg.eog_channels:
        ch_names = cfg.eog_channels
        assert all([ch_name in raw.ch_names for ch_name in ch_names])
    else:
        ch_names = None

    eog_projs = []
    eog_epochs = create_eog_epochs(raw)
    if len(eog_epochs) >= config.min_eog_epochs:
        if cfg.ssp_reject_eog == 'autoreject_global':
            reject_eog_ = config.get_ssp_reject(
                ssp_type='eog',
                epochs=eog_epochs)
            eog_projs, _ = compute_proj_eog(raw,
                                            average=cfg.eog_proj_from_average,
                                            reject=reject_eog_,
                                            **cfg.n_proj_eog)
        else:
            reject_eog_ = config.get_ssp_reject(
                    ssp_type='eog',
                    epochs=None)
            eog_projs, _ = compute_proj_eog(raw,
                                            average=cfg.eog_proj_from_average,
                                            reject=reject_eog_,
                                            **cfg.n_proj_eog)

    if not eog_projs:
        msg = ('Not enough EOG events could be found. No EOG projectors are '
               'computed.')
        logger.info(**gen_log_kwargs(message=msg, subject=subject,
                                     session=session))

    mne.write_proj(proj_fname_out, eog_projs + ecg_projs)
Ejemplo n.º 19
0
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
                    'subj002_spontaneous_20111102_01_AUX.ds')
crop_to = 60.

##############################################################################
# Here we do some things in the name of speed, such as crop (which will
# hurt SNR) and downsample. Then we compute SSP projectors and apply them.

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, crop_to).pick_types(meg=True, eeg=False).load_data().resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest

##############################################################################
# Now we band-pass filter our data and create epochs.

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw,
                    events=events,
                    tmin=0,
                    tmax=5.,
Ejemplo n.º 20
0
                            destination=raw.info['dev_head_t'],
                            info=raw.info,
                            show=True)
# Denoise
if not op.isfile(raw_fname[:-4] + '_sss.fif'):
    raw = mne.chpi.filter_chpi(raw)
    raw.fix_mag_coil_types()
    raw_sss = maxwell_filter(raw, head_pos=head_pos, st_duration=300)
    raw_sss.save(raw_fname[:-4] + '_sss.fif')
else:
    raw_sss = mne.io.read_raw_fif(raw_fname[:-4] + '_sss.fif', preload=True)

# artifact correction
ecg_projs, events = compute_proj_ecg(raw_sss,
                                     n_grad=3,
                                     n_mag=3,
                                     n_eeg=0,
                                     average=True)
print(ecg_projs)
mne.viz.plot_projs_topomap(ecg_projs)
eog_projs, events = compute_proj_eog(raw_sss,
                                     n_grad=3,
                                     n_mag=3,
                                     n_eeg=0,
                                     average=True)
print(eog_projs)
mne.viz.plot_projs_topomap(eog_projs)
raw_sss.info['projs'] += eog_projs + ecg_projs
picks = pick_types(raw.info,
                   meg=True,
                   eeg=False,
Ejemplo n.º 21
0
 subject_files = os.listdir(subject_folder)
 ssp_file_count = processedcount(subject_files)
 # if both (speech and rest) _ssp.fif exist already in subjects folder,
 # then don't process the subject again
 if ssp_file_count == 2:
     continue
 for pieces in subject_files:
     if pieces[-15:] == 'tsss_mc_EOG.fif':
         final_path = subject_folder + pieces
         print(final_path)
         raw = mne.io.read_raw_fif(final_path, preload=True)
         projection_ecg, ecg_events = compute_proj_ecg(raw,
                                                       reject=reject,
                                                       l_freq=1,
                                                       h_freq=100,
                                                       tstart=5,
                                                       ecg_h_freq=25,
                                                       ecg_l_freq=1,
                                                       average=True,
                                                       ch_name='MEG1541')
         projection_eog, eog_events = compute_proj_eog(raw,
                                                       reject=reject,
                                                       l_freq=1,
                                                       h_freq=40,
                                                       average=True)
         raw_ecg_removed = raw.add_proj(projection_ecg,
                                        remove_existing=True)
         raw_all_removed = raw_ecg_removed.add_proj(projection_eog)
         save_path = subject_folder + pieces[:-4] + '_ssp.fif'
         print(save_path)
         raw_all_removed.apply_proj().save(save_path, overwrite=True)
subjects_dir = op.join(data_path, 'subjects')
subject = 'bst_resting'
trans = op.join(data_path, 'MEG', 'bst_resting', 'bst_resting-trans.fif')
bem = op.join(subjects_dir, subject, 'bem', subject + '-5120-bem-sol.fif')
raw_fname = op.join(data_path, 'MEG', 'bst_resting',
                    'subj002_spontaneous_20111102_01_AUX.ds')
crop_to = 60.

##############################################################################
# Here we do some things in the name of speed, such as crop (which will
# hurt SNR) and downsample. Then we compute SSP projectors and apply them.

raw = mne.io.read_raw_ctf(raw_fname, verbose='error')
raw.crop(0, crop_to).load_data().pick_types(meg=True, eeg=False).resample(80)
raw.apply_gradient_compensation(3)
projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2)
projs_eog, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='MLT31-4407')
raw.info['projs'] += projs_ecg
raw.info['projs'] += projs_eog
raw.apply_proj()
cov = mne.compute_raw_covariance(raw)  # compute before band-pass of interest

##############################################################################
# Now we band-pass filter our data and create epochs.

raw.filter(14, 30)
events = mne.make_fixed_length_events(raw, duration=5.)
epochs = mne.Epochs(raw, events=events, tmin=0, tmax=5.,
                    baseline=None, reject=dict(mag=8e-13), preload=True)
del raw
from mne.datasets import sample
from mne.preprocessing import compute_proj_ecg, compute_proj_eog

# getting some data ready
data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname, preload=True)

##############################################################################
# Compute SSP projections
# -----------------------
#
# First let's do ECG.

projs, events = compute_proj_ecg(raw, n_grad=1, n_mag=1, n_eeg=0, average=True)
print(projs)

ecg_projs = projs[-2:]
mne.viz.plot_projs_topomap(ecg_projs)

###############################################################################
# Now let's do EOG. Here we compute an EEG projector, and need to pass
# the measurement info so the topomap coordinates can be created.

projs, events = compute_proj_eog(raw, n_grad=1, n_mag=1, n_eeg=1, average=True)
print(projs)

eog_projs = projs[-3:]
mne.viz.plot_projs_topomap(eog_projs, info=raw.info)
Ejemplo n.º 24
0
def run_correlation(subjects_dir, subject, volume_spacing, freq, ortho_bool):

    num_threads(8)
    ortho_flag = str(ortho_bool)
    frequency = str(freq)
    DATA_DIR = Path(f'{subjects_dir}', f'{subject}', 'mne_files')
    eye_proj1 = f'{DATA_DIR}/{subject}_eyes1-proj.fif.gz'
    eye_proj2 = f'{DATA_DIR}/{subject}_eyes2-proj.fif.gz'
    fname_meg = f'{DATA_DIR}/{subject}_ses-rest_task-rest.fif'
    t1_fname = os.path.join(subjects_dir, subject, 'mri', 'T1.mgz')
    heartbeat_proj = f'{DATA_DIR}/{subject}_heartbeat-proj.fif.gz'
    fwd_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-fwd.fif.gz'
    src_fname = f'{DATA_DIR}/{subject}_{volume_spacing}-src.fif.gz'
    cov_fname = f'{DATA_DIR}/{subject}-cov_{volume_spacing}.fif.gz'
    raw_cov_fname = f'{DATA_DIR}/{subject}-rawcov_{volume_spacing}.fif.gz'
    raw_proj = f'{DATA_DIR}/{subject}_ses-rest_task-rest_proj.fif.gz'
    source_voxel_coords = f'{DATA_DIR}/{subject}_coords_{volume_spacing}.pkl'
    corr_file_acLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acLeft.npy'
    corr_file_scLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scLeft.npy'
    corr_file_vcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcLeft.npy'
    corr_file_mtLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtLeft.npy'
    corr_file_mtlLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlLeft.npy'
    corr_file_smcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcLeft.npy'
    corr_file_lpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcLeft.npy'
    corr_file_dpfcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcLeft.npy'
    corr_file_tmpcLeft = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcLeft.npy'

    corr_file_acRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_acRight.npy'
    corr_file_scRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_scRight.npy'
    corr_file_vcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_vcRight.npy'
    corr_file_mtRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtRight.npy'
    corr_file_mtlRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mtlRight.npy'
    corr_file_smcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_smcRight.npy'
    corr_file_lpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_lpcRight.npy'
    corr_file_dpfcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_dpfcRight.npy'
    corr_file_tmpcRight = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_tmpcRight.npy'

    corr_file_mpfc = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_mpfc.npy'
    corr_file_sma = f'{DATA_DIR}/{subject}_{ortho_flag}_{volume_spacing}_{frequency}_sma.npy'

    check_for_files = []
    check_for_files.append(corr_file_acLeft)
    check_for_files.append(corr_file_scLeft)
    check_for_files.append(corr_file_vcLeft)
    check_for_files.append(corr_file_mtLeft)
    check_for_files.append(corr_file_mtlLeft)
    check_for_files.append(corr_file_smcLeft)
    check_for_files.append(corr_file_lpcLeft)
    check_for_files.append(corr_file_dpfcLeft)
    check_for_files.append(corr_file_tmpcLeft)

    check_for_files.append(corr_file_acRight)
    check_for_files.append(corr_file_scRight)
    check_for_files.append(corr_file_vcRight)
    check_for_files.append(corr_file_mtRight)
    check_for_files.append(corr_file_mtlRight)
    check_for_files.append(corr_file_smcRight)
    check_for_files.append(corr_file_lpcRight)
    check_for_files.append(corr_file_dpfcRight)
    check_for_files.append(corr_file_tmpcRight)

    check_for_files.append(corr_file_mpfc)
    check_for_files.append(corr_file_sma)


    file_exist = [f for f in check_for_files if os.path.isfile(f)]
    file_not_exist = list(set(file_exist) ^ set(check_for_files))

    if not file_not_exist:
        print('SC, AC, VC correlation files exists...')

    else:
        trans = f'/home/senthilp/caesar/camcan/cc700/camcan_coreg-master/trans/{subject}-trans.fif' # The transformation file obtained by coregistration
        file_trans = pathlib.Path(trans)
        file_ss = pathlib.Path(src_fname)
        file_fm = pathlib.Path(fwd_fname)
        file_proj = pathlib.Path(raw_proj)
        file_cov = pathlib.Path(cov_fname)
        file_rawcov = pathlib.Path(raw_cov_fname)
        t1 = nib.load(t1_fname)

        if not file_trans.exists():
            print (f'{trans} File doesnt exist...')
            sys.exit(0)

        #info = mne.io.read_info(fname_meg)
        # plot_registration(info, trans, subject, subjects_dir)
        if not file_ss.exists():

            src = compute_SourceSpace(subject, subjects_dir, src_fname, source_voxel_coords, plot=True, ss='volume', 
                                volume_spacing=volume_spacing)
            seed_l_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Left'])
            seed_r_sc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SSC_Right'])
            seed_l_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Left'])
            seed_r_ac = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['AC_Right'])
            seed_l_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Left'])
            seed_r_vc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['VC_Right'])
            seed_l_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Left'])
            seed_r_mt = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MT+_Right'])
            seed_l_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Left'])
            seed_r_mtl = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MTL_Right'])
            seed_l_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Left'])
            seed_r_smc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMC_Right'])
            seed_l_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Left'])
            seed_r_lpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['LPC_Right'])
            seed_l_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Left'])
            seed_r_dpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['DPFC_Right'])
            seed_l_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Left'])
            seed_r_tmpc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['TMPC_Right'])

            seed_mpfc = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['MPFC_MidBrain'])
            seed_sma = MNI_to_MRI(subject, subjects_dir, t1, ROI_mni['SMA_MidBrain'])

            src_inuse = np.where(src[0]['inuse'] == 1)
            loc_l_sc = src_inuse[0][0]
            loc_r_sc = src_inuse[0][1]
            loc_l_ac = src_inuse[0][2]
            loc_r_ac = src_inuse[0][3]
            loc_l_vc = src_inuse[0][4]
            loc_r_vc = src_inuse[0][5]
            loc_l_mt = src_inuse[0][6]
            loc_r_mt = src_inuse[0][7]
            loc_l_mtl = src_inuse[0][8]
            loc_r_mtl = src_inuse[0][9]
            loc_l_smc = src_inuse[0][10]
            loc_r_smc = src_inuse[0][11]
            loc_l_lpc = src_inuse[0][12]
            loc_r_lpc = src_inuse[0][13]
            loc_l_dpfc = src_inuse[0][14]
            loc_r_dpfc = src_inuse[0][15]
            loc_l_tmpc = src_inuse[0][16]
            loc_r_tmpc = src_inuse[0][17]
            loc_mpfc = src_inuse[0][18]
            loc_sma = src_inuse[0][19]
            src[0]['rr'][loc_l_sc] = seed_l_sc
            src[0]['rr'][loc_r_sc] = seed_r_sc
            src[0]['rr'][loc_l_ac] = seed_l_ac
            src[0]['rr'][loc_r_ac] = seed_r_ac
            src[0]['rr'][loc_l_vc] = seed_l_vc
            src[0]['rr'][loc_r_vc] = seed_r_vc
            src[0]['rr'][loc_l_mt] = seed_l_mt
            src[0]['rr'][loc_r_mt] = seed_r_mt
            src[0]['rr'][loc_l_mtl] = seed_l_mtl
            src[0]['rr'][loc_r_mtl] = seed_r_mtl
            src[0]['rr'][loc_l_smc] = seed_l_smc
            src[0]['rr'][loc_r_smc] = seed_r_smc
            src[0]['rr'][loc_l_lpc] = seed_l_lpc
            src[0]['rr'][loc_r_lpc] = seed_r_lpc
            src[0]['rr'][loc_l_dpfc] = seed_l_dpfc
            src[0]['rr'][loc_r_dpfc] = seed_r_dpfc
            src[0]['rr'][loc_l_tmpc] = seed_l_tmpc
            src[0]['rr'][loc_r_tmpc] = seed_r_tmpc
            src[0]['rr'][loc_mpfc] = seed_mpfc
            src[0]['rr'][loc_sma] = seed_sma
            src.save(src_fname, overwrite=True)
        src = mne.read_source_spaces(src_fname)
        #view_SS_brain(subject, subjects_dir, src)

        if not file_fm.exists():
            forward_model(subject, subjects_dir, fname_meg, trans, src, fwd_fname)
        fwd = mne.read_forward_solution(fwd_fname)

        # sensitivty_plot(subject, subjects_dir, fwd)
        raw = mne.io.read_raw_fif(fname_meg, verbose='error', preload=True)

        srate = raw.info['sfreq']
        n_time_samps = raw.n_times
        time_secs = raw.times
        ch_names = raw.ch_names
        n_chan = len(ch_names)
        freq_res =  srate/n_time_samps
        print('\n')
        print('-------------------------- Data summary-------------------------------')
        print(f'Subject {subject}')
        print(f"Frequency resolution {freq_res} Hz")
        print(f"The first few channel names are {ch_names[:3]}")
        print(f"The last time sample at {time_secs[-1]} seconds.")
        print(f"Sampling Frequency (No of time points/sec) {srate} Hz")
        print(f"Miscellaneous acquisition info {raw.info['description']}")
        print(f"Bad channels marked during data acquisition {raw.info['bads']}")
        print(f"Convert time in sec ( 60s ) to ingeter index {raw.time_as_index(60)}") # Convert time to indices
        print(f"The raw data object has {n_time_samps} time samples and {n_chan} channels.")
        print('------------------------------------------------------------------------')
        print('\n')
        # raw.plot(n_channels=10, scalings='auto', title='Data from arrays', show=True, block=True)
        if not file_proj.exists():
            projs_ecg, _ = compute_proj_ecg(raw, n_grad=1, n_mag=2, ch_name='ECG063')
            projs_eog1, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG061')
            projs_eog2, _ = compute_proj_eog(raw, n_grad=1, n_mag=2, ch_name='EOG062')
            if projs_ecg is not None:
                mne.write_proj(heartbeat_proj, projs_ecg) # Saving projectors
                raw.info['projs'] += projs_ecg
            if projs_eog1 is not None:
                mne.write_proj(eye_proj1, projs_eog1)
                raw.info['projs'] += projs_eog1
            if projs_eog2 is not None:
                mne.write_proj(eye_proj2, projs_eog2)
                raw.info['projs'] += projs_eog2
            raw.apply_proj()
            raw.save(raw_proj, proj=True, overwrite=True)
        print(raw_proj)
        raw_proj_applied = mne.io.read_raw_fif(raw_proj, verbose='error', preload=True)


        print(f'High-pass filtering data at 0.5 Hz')
        raw_proj_applied.filter(l_freq=0.5, h_freq=None, method='iir')

        if not file_cov.exists():
            cov = mne.compute_raw_covariance(raw_proj_applied) # compute before band-pass of interest
            mne.write_cov(cov_fname, cov)
        cov = mne.read_cov(cov_fname) 

        # cov.plot(raw.info, proj=True, exclude='bads', show_svd=False
        # raw_proj_applied.crop(tmax=10)
        
        do_epochs = False

        l_freq = freq-2.0
        h_freq = freq+2.0
        print(f'Band pass filter data [{l_freq}, {h_freq}]')
        raw_proj_filtered = raw_proj_applied.filter(l_freq=l_freq, h_freq=h_freq)

        if do_epochs:
            print('Segmenting raw data...')
            events = mne.make_fixed_length_events(raw_proj_filtered, duration=5.)
            raw_proj_filtered = mne.Epochs(raw_proj_filtered, events=events, tmin=0, tmax=5.,
                                            baseline=None, preload=True)
            data_cov = mne.compute_covariance(raw_proj_filtered)         
        else:
            if not file_rawcov.exists():
                data_cov = mne.compute_raw_covariance(raw_proj_filtered)
                mne.write_cov(raw_cov_fname, data_cov)
            else:
                data_cov = mne.read_cov(file_rawcov)

        filters = make_lcmv(raw_proj_filtered.info, fwd, data_cov, 0.05, cov,
                            pick_ori='max-power', weight_norm='nai')
        raw_proj_filtered_comp = raw_proj_filtered.apply_hilbert()

        if do_epochs:
            stcs = apply_lcmv_epochs(raw_proj_filtered_comp, filters, return_generator=False)
        else:
            stcs = apply_lcmv_raw(raw_proj_filtered_comp, filters, verbose=True)
            stcs = [stcs]
        # Power Envelope Correlation
        print(f'Computing Power Envelope Correlation for {subject}....Orthogonalize {ortho_flag}')

        all_corr = envelope_correlation(stcs, combine=None, orthogonalize=False,
                    log=False, absolute=True, verbose=None)

        np.save(corr_file_scLeft, all_corr[seed_left_sc])
        np.save(corr_file_acLeft, all_corr[seed_left_ac])
        np.save(corr_file_vcLeft, all_corr[seed_left_vc])
        np.save(corr_file_mtLeft, all_corr[seed_left_mt])
        np.save(corr_file_mtlLeft, all_corr[seed_left_mtl])
        np.save(corr_file_smcLeft, all_corr[seed_left_smc])
        np.save(corr_file_lpcLeft, all_corr[seed_left_lpc])
        np.save(corr_file_dpfcLeft, all_corr[seed_left_dpfc])
        np.save(corr_file_tmpcLeft, all_corr[seed_left_tmpc])

        np.save(corr_file_scRight, all_corr[seed_right_sc])
        np.save(corr_file_acRight, all_corr[seed_right_ac])
        np.save(corr_file_vcRight, all_corr[seed_right_vc])
        np.save(corr_file_mtRight, all_corr[seed_right_mt])
        np.save(corr_file_mtlRight, all_corr[seed_right_mtl])
        np.save(corr_file_smcRight, all_corr[seed_right_smc])
        np.save(corr_file_lpcRight, all_corr[seed_right_lpc])
        np.save(corr_file_dpfcRight, all_corr[seed_right_dpfc])
        np.save(corr_file_tmpcRight, all_corr[seed_right_tmpc])

        np.save(corr_file_mpfc, all_corr[seed_mpfc_index])
        np.save(corr_file_sma, all_corr[seed_sma_index])

        del stcs