def rename_events(raw, subject, session): # Check if the user requested to rename events that don't exist. # We don't want this to go unnoticed. event_names_set = set(raw.annotations.description) rename_events_set = set(config.rename_events.keys()) events_not_in_raw = rename_events_set - event_names_set if events_not_in_raw: msg = (f'You requested to rename the following events, but ' f'they are not present in the BIDS input data:\n' f'{", ".join(sorted(list(events_not_in_raw)))}') if config.on_rename_missing_events == 'warn': logger.warning(msg) else: raise ValueError(msg) # Do the actual event renaming. msg = 'Renaming events …' logger.info( gen_log_message(message=msg, step=1, subject=subject, session=session)) descriptions = list(raw.annotations.description) for old_event_name, new_event_name in config.rename_events.items(): msg = f'… {old_event_name} -> {new_event_name}' logger.info( gen_log_message(message=msg, step=1, subject=subject, session=session)) for idx, description in enumerate(descriptions.copy()): if description == old_event_name: descriptions[idx] = new_event_name descriptions = np.asarray(descriptions, dtype=str) raw.annotations.description = descriptions
def main(): """Run group average in source space""" msg = 'Running Step 13: Grand-average source estimates' logger.info(gen_log_message(step=13, message=msg)) if not config.run_source_estimation: msg = ' … skipping: run_source_estimation is set to False.' logger.info(gen_log_message(step=13, message=msg)) return mne.datasets.fetch_fsaverage(subjects_dir=config.get_fs_subjects_dir()) parallel, run_func, _ = parallel_func(morph_stc, n_jobs=config.N_JOBS) all_morphed_stcs = parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) all_morphed_stcs = [morphed_stcs for morphed_stcs, subject in zip(all_morphed_stcs, config.get_subjects())] mean_morphed_stcs = map(sum, zip(*all_morphed_stcs)) subject = 'average' # XXX to fix if config.get_sessions(): session = config.get_sessions()[0] else: session = None bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, processing=config.proc, recording=config.rec, space=config.space, datatype=config.get_datatype(), root=config.deriv_root, check=False) if isinstance(config.conditions, dict): conditions = list(config.conditions.keys()) else: conditions = config.conditions for condition, this_stc in zip(conditions, mean_morphed_stcs): this_stc /= len(all_morphed_stcs) method = config.inverse_method cond_str = config.sanitize_cond_name(condition) inverse_str = method hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'. morph_str = 'morph2fsaverage' fname_stc_avg = bids_path.copy().update( suffix=f'{cond_str}+{inverse_str}+{morph_str}+{hemi_str}') this_stc.save(fname_stc_avg) msg = 'Completed Step 13: Grand-average source estimates' logger.info(gen_log_message(step=13, message=msg))
def run_evoked(subject, session=None): bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, extension='.fif', datatype=config.get_datatype(), root=config.deriv_root) processing = None if config.use_ica or config.use_ssp: processing = 'clean' fname_in = bids_path.copy().update(processing=processing, suffix='epo', check=False) fname_out = bids_path.copy().update(suffix='ave', check=False) msg = f'Input: {fname_in}, Output: {fname_out}' logger.info(gen_log_message(message=msg, step=6, subject=subject, session=session)) epochs = mne.read_epochs(fname_in, preload=True) msg = 'Creating evoked data based on experimental conditions …' logger.info(gen_log_message(message=msg, step=6, subject=subject, session=session)) all_evoked = dict() if isinstance(config.conditions, dict): for new_cond_name, orig_cond_name in config.conditions.items(): evoked = epochs[orig_cond_name].average() evoked.comment = evoked.comment.replace(orig_cond_name, new_cond_name) all_evoked[new_cond_name] = evoked else: for condition in config.conditions: evoked = epochs[condition].average() all_evoked[condition] = evoked if config.contrasts: msg = 'Contrasting evoked responses …' logger.info(gen_log_message(message=msg, step=6, subject=subject, session=session)) for contrast in config.contrasts: cond_1, cond_2 = contrast evoked_diff = mne.combine_evoked([all_evoked[cond_1], all_evoked[cond_2]], weights=[1, -1]) all_evoked[contrast] = evoked_diff evokeds = list(all_evoked.values()) mne.write_evokeds(fname_out, evokeds) if config.interactive: for evoked in evokeds: evoked.plot()
def filter_for_ica(raw, subject, session): """Apply a high-pass filter if needed.""" if config.ica_l_freq <= config.l_freq or config.ica_l_freq is None: # Nothing to do here! msg = 'Not applying high-pass filter ' if config.ica_l_freq <= config.l_freq: msg += (f'(data is already filtered, ' f'cutoff: {raw.info["highpass"]} Hz).') else: msg = '(no filtering requested).' logger.info( gen_log_message(message=msg, step=4, subject=subject, session=session)) else: msg = f'Applying high-pass filter with {config.ica_l_freq} Hz cutoff …' logger.info( gen_log_message(message=msg, step=4, subject=subject, session=session)) raw.filter(l_freq=config.ica_l_freq, h_freq=None) return raw
def main(): """Run sliding estimator.""" msg = 'Running Step 7: Sliding estimator' logger.info(gen_log_message(step=7, message=msg)) if not config.contrasts: msg = 'No contrasts specified; not performing decoding.' logger.info(gen_log_message(step=7, message=msg)) return if not config.decode: msg = 'No decoding requested by user.' logger.info(gen_log_message(step=7, message=msg)) return # Here we go parallel inside the :class:`mne.decoding.SlidingEstimator` # so we don't dispatch manually to multiple jobs. for subject in config.get_subjects(): for session in config.get_sessions(): for contrast in config.contrasts: cond_1, cond_2 = contrast run_time_decoding(subject=subject, condition1=cond_1, condition2=cond_2, session=session) msg = 'Completed Step 7: Sliding estimator' logger.info(gen_log_message(step=7, message=msg))
def rename_events(raw, subject, session): # Check if the user requested to rename events that don't exist. # We don't want this to go unnoticed. event_names_set = set(raw.annotations.description) rename_events_set = set(config.rename_events.keys()) events_not_in_raw = rename_events_set - event_names_set if events_not_in_raw: msg = (f'You requested to rename the following events, but ' f'they are not present in the BIDS input data:\n' f'{", ".join(sorted(list(events_not_in_raw)))}') raise ValueError(msg) # Do the actual event renaming. msg = 'Renaming events …' logger.info( gen_log_message(message=msg, step=1, subject=subject, session=session)) description = raw.annotations.description for old_event_name, new_event_name in config.rename_events.items(): msg = f'… {old_event_name} -> {new_event_name}' logger.info( gen_log_message(message=msg, step=1, subject=subject, session=session)) description[description == old_event_name] = new_event_name
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)
def detect_ecg_artifacts(ica, raw, subject, session, report): # ECG either needs an ecg channel, or avg of the mags (i.e. MEG data) if ('ecg' in raw.get_channel_types() or 'meg' in config.ch_types or 'mag' in config.ch_types): msg = 'Performing automated ECG artifact detection …' logger.info( gen_log_message(message=msg, step=4, subject=subject, session=session)) # Do not reject epochs based on amplitude. ecg_epochs = create_ecg_epochs(raw, reject=None, baseline=(None, -0.2), tmin=-0.5, tmax=0.5) ecg_evoked = ecg_epochs.average() ecg_inds, scores = ica.find_bads_ecg( ecg_epochs, method='ctps', threshold=config.ica_ctps_ecg_threshold) ica.exclude = ecg_inds msg = (f'Detected {len(ecg_inds)} ECG-related ICs in ' f'{len(ecg_epochs)} ECG epochs.') logger.info( gen_log_message(message=msg, step=4, subject=subject, session=session)) del ecg_epochs # Plot scores fig = ica.plot_scores(scores, labels='ecg', show=config.interactive) report.add_figs_to_section(figs=fig, captions='Scores - ECG', section=f'sub-{subject}') # Plot source time course fig = ica.plot_sources(ecg_evoked, show=config.interactive) report.add_figs_to_section(figs=fig, captions='Source time course - ECG', section=f'sub-{subject}') # Plot original & corrected data fig = ica.plot_overlay(ecg_evoked, show=config.interactive) report.add_figs_to_section(figs=fig, captions='Corrections - ECG', section=f'sub-{subject}') else: ecg_inds = list() msg = ('No ECG or magnetometer channels are present. Cannot ' 'automate artifact detection for ECG') logger.info( gen_log_message(message=msg, step=4, subject=subject, session=session)) return ecg_inds
def average_evokeds(session): # Container for all conditions: all_evokeds = defaultdict(list) for subject in config.get_subjects(): fname_in = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, suffix='ave', extension='.fif', datatype=config.get_datatype(), root=config.deriv_root, check=False) msg = f'Input: {fname_in}' logger.info( gen_log_message(message=msg, step=9, subject=subject, session=session)) evokeds = mne.read_evokeds(fname_in) for idx, evoked in enumerate(evokeds): all_evokeds[idx].append(evoked) # Insert into the container for idx, evokeds in all_evokeds.items(): all_evokeds[idx] = mne.grand_average( evokeds, interpolate_bads=config.interpolate_bads_grand_average ) # Combine subjects subject = 'average' fname_out = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, processing=config.proc, recording=config.rec, space=config.space, suffix='ave', extension='.fif', datatype=config.get_datatype(), root=config.deriv_root, check=False) if not fname_out.fpath.parent.exists(): os.makedirs(fname_out.fpath.parent) msg = f'Saving grand-averaged evoked sensor data: {fname_out}' logger.info( gen_log_message(message=msg, step=9, subject=subject, session=session)) mne.write_evokeds(fname_out, list(all_evokeds.values())) return list(all_evokeds.values())
def run_evoked(subject, session=None): deriv_path = config.get_subject_deriv_path(subject=subject, session=session, kind=config.get_kind()) 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) if config.use_ica or config.use_ssp: extension = '_cleaned-epo' else: extension = '-epo' fname_in = op.join(deriv_path, bids_basename + '%s.fif' % extension) fname_out = op.join(deriv_path, bids_basename + '-ave.fif') msg = f'Input: {fname_in}, Output: {fname_out}' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) epochs = mne.read_epochs(fname_in, preload=True) msg = 'Creating evoked data based on experimental conditions …' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) evokeds = [] for condition in config.conditions: evoked = epochs[condition].average() evokeds.append(evoked) if config.contrasts: msg = 'Contrasting evoked responses …' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) for contrast in config.contrasts: cond_1, cond_2 = contrast evoked_1 = epochs[cond_1].average() evoked_2 = epochs[cond_2].average() evoked_diff = mne.combine_evoked([evoked_1, evoked_2], weights=[1, -1]) evokeds.append(evoked_diff) mne.evoked.write_evokeds(fname_out, evokeds) if config.interactive: for evoked in evokeds: evoked.plot()
def run_evoked(subject, session=None): bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, extension='.fif', datatype=config.get_datatype(), root=config.deriv_root) processing = None if config.use_ica or config.use_ssp: processing = 'clean' fname_in = bids_path.copy().update(processing=processing, suffix='epo', check=False) fname_out = bids_path.copy().update(suffix='ave', check=False) msg = f'Input: {fname_in}, Output: {fname_out}' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) epochs = mne.read_epochs(fname_in, preload=True) msg = 'Creating evoked data based on experimental conditions …' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) evokeds = [] for condition in config.conditions: evoked = epochs[condition].average() evokeds.append(evoked) if config.contrasts: msg = 'Contrasting evoked responses …' logger.info( gen_log_message(message=msg, step=6, subject=subject, session=session)) for contrast in config.contrasts: cond_1, cond_2 = contrast evoked_1 = epochs[cond_1].average() evoked_2 = epochs[cond_2].average() evoked_diff = mne.combine_evoked([evoked_1, evoked_2], weights=[1, -1]) evokeds.append(evoked_diff) mne.write_evokeds(fname_out, evokeds) if config.interactive: for evoked in evokeds: evoked.plot()
def main(): """Run BEM surface extraction.""" msg = 'Running Step 10: Create BEM surfaces' logger.info(gen_log_message(step=10, message=msg)) parallel, run_func, _ = parallel_func(make_bem, n_jobs=config.N_JOBS) parallel(run_func(subject) for subject in config.get_subjects()) msg = 'Completed Step 10: Create BEM surfaces' logger.info(gen_log_message(step=10, message=msg))
def main(): """Run evoked.""" msg = 'Running Step 6: Create evoked data' logger.info(gen_log_message(step=6, message=msg)) parallel, run_func, _ = parallel_func(run_evoked, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 6: Create evoked data' logger.info(gen_log_message(step=6, message=msg))
def main(): """Run inv.""" msg = 'Running Step 12: Compute and apply inverse solution' logger.info(gen_log_message(step=12, message=msg)) parallel, run_func, _ = parallel_func(run_inverse, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 12: Compute and apply inverse solution' logger.info(gen_log_message(step=12, message=msg))
def main(): """Run forward.""" msg = 'Running Step 10: Create forward solution' logger.info(gen_log_message(step=10, message=msg)) parallel, run_func, _ = parallel_func(run_forward, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 10: Create forward solution' logger.info(gen_log_message(step=10, message=msg))
def main(): """Run filter.""" msg = 'Running Step 2: Frequency filtering' logger.info(gen_log_message(step=2, message=msg)) parallel, run_func, _ = parallel_func(run_filter, n_jobs=config.N_JOBS) parallel(run_func(subject, run, session) for subject, run, session in itertools.product(config.get_subjects(), config.get_runs(), config.get_sessions())) msg = 'Completed 2: Frequency filtering' logger.info(gen_log_message(step=2, message=msg))
def main(): """Run tf.""" msg = 'Running Step 8: Time-frequency decomposition' logger.info(gen_log_message(message=msg, step=8)) parallel, run_func, _ = parallel_func(run_time_frequency, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 8: Time-frequency decomposition' logger.info(gen_log_message(message=msg, step=8))
def main(): """Run grp ave.""" msg = 'Running Step 13: Grand-average source estimates' logger.info(gen_log_message(step=13, message=msg)) mne.datasets.fetch_fsaverage(subjects_dir=config.get_fs_subjects_dir()) parallel, run_func, _ = parallel_func(morph_stc, n_jobs=config.N_JOBS) all_morphed_stcs = parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) all_morphed_stcs = [morphed_stcs for morphed_stcs, subject in zip(all_morphed_stcs, config.get_subjects())] mean_morphed_stcs = map(sum, zip(*all_morphed_stcs)) subject = 'average' # XXX to fix if config.get_sessions(): session = config.get_sessions()[0] else: session = None deriv_path = config.get_subject_deriv_path(subject=subject, session=session, kind=config.get_kind()) bids_basename = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, processing=config.proc, recording=config.rec, space=config.space, prefix=deriv_path, check=False) for condition, this_stc in zip(config.conditions, mean_morphed_stcs): this_stc /= len(all_morphed_stcs) method = config.inverse_method cond_str = condition.replace(op.sep, '').replace('_', '') inverse_str = method hemi_str = 'hemi' # MNE will auto-append '-lh' and '-rh'. morph_str = 'morph2fsaverage' fname_stc_avg = bids_basename.copy().update( kind=f'{cond_str}+{inverse_str}+{morph_str}+{hemi_str}') this_stc.save(fname_stc_avg) msg = 'Completed Step 13: Grand-average source estimates' logger.info(gen_log_message(step=13, message=msg))
def main(): """Run cov.""" msg = 'Running Step 11: Estimate noise covariance' logger.info(gen_log_message(step=11, message=msg)) parallel, run_func, _ = parallel_func(run_covariance, n_jobs=config.N_JOBS) parallel( run_func(subject, session) for subject, session in itertools.product( config.get_subjects(), config.get_sessions())) msg = 'Completed Step 11: Estimate noise covariance' logger.info(gen_log_message(step=11, message=msg))
def main(): """Run maxwell_filter.""" msg = 'Running Step 1: Data import and Maxwell filtering' logger.info(gen_log_message(step=1, message=msg)) parallel, run_func, _ = parallel_func(run_maxwell_filter, n_jobs=config.N_JOBS) parallel( run_func(subject, session) for subject, session in itertools.product( config.get_subjects(), config.get_sessions())) msg = 'Completed Step 1: Data import and Maxwell filtering' logger.info(gen_log_message(step=1, message=msg))
def main(): """Run epochs.""" msg = 'Running Step 3: Epoching' logger.info(gen_log_message(step=3, message=msg)) # Here we use fewer N_JOBS to prevent potential memory problems parallel, run_func, _ = parallel_func(run_epochs, n_jobs=max(config.N_JOBS // 4, 1)) parallel( run_func(subject, session) for subject, session in itertools.product( config.get_subjects(), config.get_sessions())) msg = 'Completed Step 3: Epoching' logger.info(gen_log_message(step=3, message=msg))
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)
def main(): """Run ICA.""" msg = 'Running Step 4: Compute ICA' logger.info(gen_log_message(step=4, message=msg)) if config.use_ica: parallel, run_func, _ = parallel_func(run_ica, n_jobs=config.N_JOBS) parallel( run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 4: Compute ICA' logger.info(gen_log_message(step=4, message=msg))
def main(): """Apply ssp.""" if not config.use_ssp: return msg = 'Running Step 5: Apply SSP' logger.info(gen_log_message(step=5, message=msg)) parallel, run_func, _ = parallel_func(apply_ssp, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 5: Apply SSP' logger.info(gen_log_message(step=5, message=msg))
def main(): """Run BEM surface extraction.""" msg = 'Running Step 10: Create BEM surfaces' logger.info(gen_log_message(step=10, message=msg)) if not config.run_source_estimation: msg = ' … skipping: run_source_estimation is set to False.' logger.info(gen_log_message(step=10, message=msg)) return parallel, run_func, _ = parallel_func(make_bem, n_jobs=config.N_JOBS) parallel(run_func(subject) for subject in config.get_subjects()) msg = 'Completed Step 10: Create BEM surfaces' logger.info(gen_log_message(step=10, message=msg))
def main(): """Initialize the output directories.""" msg = 'Running: Initializing output directories.' logger.info(gen_log_message(step=1, message=msg)) init_dataset() parallel, run_func, _ = parallel_func(init_subject_dirs, n_jobs=config.N_JOBS) parallel( run_func(subject=subject, session=session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed: Initializing output directories.' logger.info(gen_log_message(step=1, message=msg))
def compute_cov_from_empty_room(subject, session): deriv_path = config.get_subject_deriv_path(subject=subject, session=session, kind=config.get_kind()) 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) raw_er_fname = op.join(deriv_path, bids_basename + '_emptyroom_filt_raw.fif') cov_fname = op.join(deriv_path, bids_basename + '-cov.fif') extra_params = dict() if not config.use_maxwell_filter and config.allow_maxshield: extra_params['allow_maxshield'] = config.allow_maxshield msg = (f'Computing regularized covariance based on empty-room recording. ' f'Input: {raw_er_fname}, Output: {cov_fname}') logger.info( gen_log_message(message=msg, step=11, subject=subject, session=session)) raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params) cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info') cov.save(cov_fname)
def compute_cov_from_empty_room(subject, session): bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, recording=config.rec, space=config.space, extension='.fif', datatype=config.get_datatype(), root=config.deriv_root, check=False) raw_er_fname = bids_path.copy().update(processing='filt', task='noise', suffix='raw') cov_fname = bids_path.copy().update(suffix='cov') extra_params = dict() if not config.use_maxwell_filter and config.allow_maxshield: extra_params['allow_maxshield'] = config.allow_maxshield msg = (f'Computing regularized covariance based on empty-room recording. ' f'Input: {raw_er_fname}, Output: {cov_fname}') logger.info( gen_log_message(message=msg, step=11, subject=subject, session=session)) raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params) cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info') cov.save(cov_fname)
def compute_cov_from_epochs(subject, session, tmin, tmax): bids_path = BIDSPath(subject=subject, session=session, task=config.get_task(), acquisition=config.acq, run=None, processing=config.proc, recording=config.rec, space=config.space, extension='.fif', datatype=config.get_datatype(), root=config.deriv_root, check=False) processing = None if config.use_ica or config.use_ssp: processing = 'clean' epo_fname = bids_path.copy().update(processing=processing, suffix='epo') cov_fname = bids_path.copy().update(suffix='cov') msg = (f"Computing regularized covariance based on epochs' baseline " f"periods. Input: {epo_fname}, Output: {cov_fname}") logger.info( gen_log_message(message=msg, step=11, subject=subject, session=session)) epochs = mne.read_epochs(epo_fname, preload=True) cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk', rank='info') cov.save(cov_fname)
def main(): """Run forward.""" msg = 'Running Step 10: Create forward solution' logger.info(gen_log_message(step=10, message=msg)) if not config.run_source_estimation: msg = ' … skipping: run_source_estimation is set to False.' logger.info(gen_log_message(step=10, message=msg)) return parallel, run_func, _ = parallel_func(run_forward, n_jobs=config.N_JOBS) parallel(run_func(subject, session) for subject, session in itertools.product(config.get_subjects(), config.get_sessions())) msg = 'Completed Step 10: Create forward solution' logger.info(gen_log_message(step=10, message=msg))