Exemplo n.º 1
0
def test_bids_path_inference(return_bids_test_dir):
    """Test usage of BIDSPath object and fpath."""
    bids_root = return_bids_test_dir

    # without providing all the entities, ambiguous when trying
    # to use fpath
    bids_path = BIDSPath(
        subject=subject_id, session=session_id, acquisition=acq,
        task=task, root=bids_root)
    with pytest.raises(RuntimeError, match='Found more than one'):
        bids_path.fpath

    # shouldn't error out when there is no uncertainty
    channels_fname = BIDSPath(subject=subject_id, session=session_id,
                              run=run, acquisition=acq, task=task,
                              root=bids_root, suffix='channels')
    channels_fname.fpath

    # create an extra file under 'eeg'
    extra_file = op.join(bids_root, f'sub-{subject_id}',
                         f'ses-{session_id}', 'eeg',
                         channels_fname.basename + '.tsv')
    Path(extra_file).parent.mkdir(exist_ok=True, parents=True)
    # Creates a new file and because of this new file, there is now
    # ambiguity
    with open(extra_file, 'w', encoding='utf-8'):
        pass
    with pytest.raises(RuntimeError, match='Found data of more than one'):
        channels_fname.fpath

    # if you set datatype, now there is no ambiguity
    channels_fname.update(datatype='eeg')
    assert str(channels_fname.fpath) == extra_file
    # set state back to original
    shutil.rmtree(Path(extra_file).parent)
Exemplo n.º 2
0
def test_make_folders(tmpdir):
    """Test that folders are created and named properly."""
    # Make sure folders are created properly
    bids_path = BIDSPath(subject='01', session='foo',
                         datatype='eeg', root=str(tmpdir))
    bids_path.mkdir().directory
    assert op.isdir(tmpdir / 'sub-01' / 'ses-foo' / 'eeg')

    # If we remove a kwarg the folder shouldn't be created
    bids_path = BIDSPath(subject='02', datatype='eeg',
                         root=tmpdir)
    bids_path.mkdir().directory
    assert op.isdir(tmpdir / 'sub-02' / 'eeg')

    # Check if a pathlib.Path bids_root works.
    bids_path = BIDSPath(subject='03', session='foo',
                         datatype='eeg', root=Path(tmpdir))
    bids_path.mkdir().directory
    assert op.isdir(tmpdir / 'sub-03' / 'ses-foo' / 'eeg')

    # Check if bids_root=None creates folders in the current working directory
    bids_root = tmpdir.mkdir("tmp")
    curr_dir = os.getcwd()
    os.chdir(bids_root)
    bids_path = BIDSPath(subject='04', session='foo',
                         datatype='eeg')
    bids_path.mkdir().directory
    assert op.isdir(op.join(os.getcwd(), 'sub-04', 'ses-foo', 'eeg'))
    os.chdir(curr_dir)
Exemplo n.º 3
0
def test_find_emptyroom_no_meas_date(tmpdir):
    """Test that we warn if measurement date can be read or inferred."""
    data_path = testing.data_path()
    raw_fname = op.join(data_path, 'MEG', 'sample',
                        'sample_audvis_trunc_raw.fif')

    bids_root = str(tmpdir)
    bids_path.update(root=bids_root)
    er_session = 'mysession'
    er_meas_date = None

    er_dir_path = BIDSPath(subject='emptyroom', session=er_session,
                           datatype='meg', root=bids_root)
    er_dir = er_dir_path.mkdir().directory

    er_bids_path = BIDSPath(subject='emptyroom', session=er_session,
                            task='noise', check=False)
    er_basename = er_bids_path.basename
    raw = _read_raw_fif(raw_fname)

    er_raw_fname = op.join(data_path, 'MEG', 'sample', 'ernoise_raw.fif')
    raw.copy().crop(0, 10).save(er_raw_fname, overwrite=True)
    er_raw = _read_raw_fif(er_raw_fname)
    er_raw.set_meas_date(er_meas_date)
    er_raw.save(op.join(er_dir, f'{er_basename}_meg.fif'), overwrite=True)

    # Write raw file data using mne-bids, and remove participants.tsv
    # as it's incomplete (doesn't contain the emptyroom subject we wrote
    # manually using MNE's Raw.save() above)
    raw = _read_raw_fif(raw_fname)
    write_raw_bids(raw, bids_path, overwrite=True)
    os.remove(op.join(bids_root, 'participants.tsv'))

    with pytest.warns(RuntimeWarning, match='Could not retrieve .* date'):
        bids_path.find_empty_room()
Exemplo n.º 4
0
def test_make_folders():
    """Test that folders are created and named properly."""
    # Make sure folders are created properly
    bids_root = _TempDir()
    bids_path = BIDSPath(subject='hi',
                         session='foo',
                         datatype='eeg',
                         root=bids_root)
    bids_path.mkdir().directory
    assert op.isdir(op.join(bids_root, 'sub-hi', 'ses-foo', 'eeg'))

    # If we remove a kwarg the folder shouldn't be created
    bids_root = _TempDir()
    bids_path = BIDSPath(subject='hi', datatype='eeg', root=bids_root)
    bids_path.mkdir().directory
    assert op.isdir(op.join(bids_root, 'sub-hi', 'eeg'))

    # Check if a pathlib.Path bids_root works.
    bids_root = Path(_TempDir())
    bids_path = BIDSPath(subject='hi',
                         session='foo',
                         datatype='eeg',
                         root=bids_root)
    bids_path.mkdir().directory
    assert op.isdir(op.join(bids_root, 'sub-hi', 'ses-foo', 'eeg'))

    # Check if bids_root=None creates folders in the current working directory
    bids_root = _TempDir()
    curr_dir = os.getcwd()
    os.chdir(bids_root)
    bids_path = BIDSPath(subject='hi', session='foo', datatype='eeg')
    bids_path.mkdir().directory
    assert op.isdir(op.join(os.getcwd(), 'sub-hi', 'ses-foo', 'eeg'))
    os.chdir(curr_dir)
Exemplo n.º 5
0
def test_find_emptyroom_ties(tmpdir):
    """Test that we receive a warning on a date tie."""
    data_path = testing.data_path()
    raw_fname = op.join(data_path, 'MEG', 'sample',
                        'sample_audvis_trunc_raw.fif')

    bids_root = str(tmpdir)
    bids_path.update(root=bids_root)
    session = '20010101'
    er_dir_path = BIDSPath(subject='emptyroom', session=session,
                           datatype='meg', root=bids_root)
    er_dir = er_dir_path.mkdir().directory

    meas_date = (datetime
                 .strptime(session, '%Y%m%d')
                 .replace(tzinfo=timezone.utc))

    raw = _read_raw_fif(raw_fname)

    er_raw_fname = op.join(data_path, 'MEG', 'sample', 'ernoise_raw.fif')
    raw.copy().crop(0, 10).save(er_raw_fname, overwrite=True)
    er_raw = _read_raw_fif(er_raw_fname)
    raw.set_meas_date(meas_date)
    er_raw.set_meas_date(meas_date)

    write_raw_bids(raw, bids_path, overwrite=True)
    er_bids_path = BIDSPath(subject='emptyroom', session=session)
    er_basename_1 = er_bids_path.basename
    er_basename_2 = BIDSPath(subject='emptyroom', session=session,
                             task='noise').basename
    er_raw.save(op.join(er_dir, f'{er_basename_1}_meg.fif'))
    er_raw.save(op.join(er_dir, f'{er_basename_2}_meg.fif'))

    with pytest.warns(RuntimeWarning, match='Found more than one'):
        bids_path.find_empty_room()
Exemplo n.º 6
0
def test_copyfile_kit(tmpdir):
    """Test copying and renaming KIT files to a new location."""
    output_path = str(tmpdir)
    data_path = op.join(base_path, 'kit', 'tests', 'data')
    raw_fname = op.join(data_path, 'test.sqd')
    hpi_fname = op.join(data_path, 'test_mrk.sqd')
    electrode_fname = op.join(data_path, 'test.elp')
    headshape_fname = op.join(data_path, 'test.hsp')
    subject_id = '01'
    session_id = '01'
    run = '01'
    acq = '01'
    task = 'testing'

    raw = mne.io.read_raw_kit(
        raw_fname, mrk=hpi_fname, elp=electrode_fname,
        hsp=headshape_fname)
    _, ext = _parse_ext(raw_fname, verbose=True)
    datatype = _handle_datatype(raw)

    bids_path = BIDSPath(
        subject=subject_id, session=session_id, run=run, acquisition=acq,
        task=task)
    kit_bids_path = bids_path.copy().update(acquisition=None,
                                            datatype=datatype,
                                            root=output_path)
    bids_fname = str(bids_path.copy().update(datatype=datatype,
                                             suffix=datatype,
                                             extension=ext,
                                             root=output_path))

    copyfile_kit(raw_fname, bids_fname, subject_id, session_id,
                 task, run, raw._init_kwargs)
    assert op.exists(bids_fname)
    _, ext = _parse_ext(hpi_fname, verbose=True)
    if ext == '.sqd':
        kit_bids_path.update(suffix='markers', extension='.sqd')
        assert op.exists(kit_bids_path)
    elif ext == '.mrk':
        kit_bids_path.update(suffix='markers', extension='.mrk')
        assert op.exists(kit_bids_path)

    if op.exists(electrode_fname):
        task, run, key = None, None, 'ELP'
        elp_ext = '.pos'
        elp_fname = BIDSPath(
            subject=subject_id, session=session_id, task=task, run=run,
            acquisition=key, suffix='headshape', extension=elp_ext,
            datatype='meg', root=output_path)
        assert op.exists(elp_fname)

    if op.exists(headshape_fname):
        task, run, key = None, None, 'HSP'
        hsp_ext = '.pos'
        hsp_fname = BIDSPath(
            subject=subject_id, session=session_id, task=task, run=run,
            acquisition=key, suffix='headshape', extension=hsp_ext,
            datatype='meg', root=output_path)
        assert op.exists(hsp_fname)
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())
Exemplo n.º 8
0
def test_bids_path_label_vs_index_entity():
    match = "subject must be an instance of None or str"
    with pytest.raises(TypeError, match=match):
        BIDSPath(subject=1)
    match = "root must be an instance of path-like or None"
    with pytest.raises(TypeError, match=match):
        BIDSPath(root=1, subject='01')
    BIDSPath(subject='01', run=1)  # ok as <index> entity
    BIDSPath(subject='01', split=1)  # ok as <index> entity
Exemplo n.º 9
0
def test_count_events_bids_path(tmpdir):
    """Test the event counts passing a BIDSPath."""
    root, events, event_id = \
        _make_dataset(tmpdir, subjects=['01', '02'], tasks=['task1'])

    with pytest.raises(ValueError, match='datatype .*anat.* is not supported'):
        bids_path = BIDSPath(root=root, subject='01', datatype='anat')
        count_events(bids_path)

    bids_path = BIDSPath(root=root, subject='01', datatype='meg')
    counts = count_events(bids_path)

    _check_counts(counts, events, event_id, subjects=['01'], tasks=['task1'])
Exemplo n.º 10
0
def test_get_head_mri_trans_ctf(fname):
    """Test getting a trans object from BIDS data in CTF."""
    import nibabel as nib

    ctf_data_path = op.join(testing.data_path(), 'CTF')
    raw_ctf_fname = op.join(ctf_data_path, fname)
    raw_ctf = _read_raw_ctf(raw_ctf_fname, clean_names=True)
    bids_root = _TempDir()
    bids_path = _bids_path.copy().update(root=bids_root)
    write_raw_bids(raw_ctf, bids_path, overwrite=False)

    # Take a fake trans
    trans = mne.read_trans(raw_fname.replace('_raw.fif', '-trans.fif'))

    # Get the T1 weighted MRI data file ... test write_anat with a nibabel
    # image instead of a file path
    t1w_mgh = op.join(data_path, 'subjects', 'sample', 'mri', 'T1.mgz')
    t1w_mgh = nib.load(t1w_mgh)

    t1w_bids_path = BIDSPath(subject=subject_id,
                             session=session_id,
                             acquisition=acq,
                             root=bids_root)
    write_anat(t1w_mgh, bids_path=t1w_bids_path, raw=raw_ctf, trans=trans)

    # Try to get trans back through fitting points
    estimated_trans = get_head_mri_trans(bids_path=bids_path,
                                         extra_params=dict(clean_names=True))

    assert_almost_equal(trans['trans'], estimated_trans['trans'])
Exemplo n.º 11
0
def plot_er_psd(subject, session):
    deriv_path = config.get_subject_deriv_path(subject=subject,
                                               session=session,
                                               kind=config.get_kind())

    bids_basename = BIDSPath(subject=subject,
                             session=session,
                             acquisition=config.acq,
                             run=None,
                             recording=config.rec,
                             space=config.space,
                             prefix=deriv_path,
                             kind=config.get_kind(),
                             task='noise',
                             processing='filt',
                             extension='.fif')

    extra_params = dict()
    if not config.use_maxwell_filter and config.allow_maxshield:
        extra_params['allow_maxshield'] = config.allow_maxshield

    raw_er_filtered = mne.io.read_raw_fif(bids_basename, preload=True,
                                          **extra_params)

    fmax = 1.5 * config.h_freq if config.h_freq is not None else np.inf
    fig = raw_er_filtered.plot_psd(fmax=fmax, show=False)
    return fig
Exemplo n.º 12
0
def convert_fedele_bids(source_path, root):
    # get all patients
    patients = sorted(
        [x for x in Path(source_path).glob('pat*') if x.is_dir()])

    for subject_path in patients:
        data_path = subject_path / 'mat'
        mat_fpaths = sorted(data_path.glob('*.mat'))
        subject = subject_path.name

        for fpath in mat_fpaths:
            subj, _, _, nightnum, _, run = fpath.name.split('_')

            # load the matlab data
            mat_dict = _load_mat_file(fpath)

            # create BIDS path
            bids_path = BIDSPath(subject=subject,
                                 session='presurgery',
                                 task='interictal',
                                 run=run,
                                 datatype='ieeg',
                                 suffix='ieeg',
                                 extension='.vhdr')

            _write_bids(mat_dict, bids_path)
Exemplo n.º 13
0
def plot_auto_scores(cfg, subject, session):
    """Plot automated bad channel detection scores.
    """
    import json_tricks

    fname_scores = BIDSPath(subject=subject,
                            session=session,
                            task=cfg.task,
                            acquisition=cfg.acq,
                            run=None,
                            processing=cfg.proc,
                            recording=cfg.rec,
                            space=cfg.space,
                            suffix='scores',
                            extension='.json',
                            datatype=cfg.datatype,
                            root=cfg.deriv_root,
                            check=False)

    all_figs = []
    all_captions = []
    for run in cfg.runs:
        with open(fname_scores.update(run=run), 'r') as f:
            auto_scores = json_tricks.load(f)

        figs = config.plot_auto_scores(auto_scores)
        all_figs.extend(figs)

        # Could be more than 1 fig, e.g. "grad" and "mag"
        captions = [f'Run {run}'] * len(figs)
        all_captions.extend(captions)

    return all_figs, all_captions
Exemplo n.º 14
0
def plot_events(cfg, subject, session):
    raws_filt = []
    raw_fname = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         recording=cfg.rec,
                         space=cfg.space,
                         processing='filt',
                         suffix='raw',
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    for run in cfg.runs:
        this_raw_fname = raw_fname.copy().update(run=run)

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

        raw_filt = mne.io.read_raw_fif(this_raw_fname)
        raws_filt.append(raw_filt)
        del this_raw_fname

    # Concatenate the filtered raws and extract the events.
    raw_filt_concat = mne.concatenate_raws(raws_filt, on_mismatch='warn')
    events, event_id = mne.events_from_annotations(raw=raw_filt_concat)
    fig = mne.viz.plot_events(events=events,
                              event_id=event_id,
                              first_samp=raw_filt_concat.first_samp,
                              sfreq=raw_filt_concat.info['sfreq'],
                              show=False)
    return fig
Exemplo n.º 15
0
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)
Exemplo n.º 16
0
def plot_events(subject, session):
    raws_filt = []
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=config.get_task(),
                         acquisition=config.acq,
                         recording=config.rec,
                         space=config.space,
                         processing='filt',
                         suffix='raw',
                         extension='.fif',
                         datatype=config.get_datatype(),
                         root=config.deriv_root,
                         check=False)

    for run in config.get_runs():
        fname = bids_path.copy().update(run=run)
        raw_filt = mne.io.read_raw_fif(fname)
        raws_filt.append(raw_filt)
        del fname

    # Concatenate the filtered raws and extract the events.
    raw_filt_concat = mne.concatenate_raws(raws_filt)
    events, event_id = mne.events_from_annotations(raw=raw_filt_concat)
    fig = mne.viz.plot_events(events=events,
                              event_id=event_id,
                              first_samp=raw_filt_concat.first_samp,
                              sfreq=raw_filt_concat.info['sfreq'],
                              show=False)
    return fig
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()
Exemplo n.º 18
0
def compute_cov_from_empty_room(cfg, subject, session):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.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')

    msg = (f'Computing regularized covariance based on empty-room recording. '
           f'Input: {raw_er_fname}, Output: {cov_fname}')
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True)
    cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info')
    cov.save(cov_fname)
Exemplo n.º 19
0
def test_update_fail_check_no_change():
    bids_path = BIDSPath(subject='test')
    try:
        bids_path.update(suffix='ave')
    except Exception:
        pass
    assert bids_path.suffix is None
Exemplo n.º 20
0
def _match_dig_sidecars(bids_path):
    """Match the sidecar files that define iEEG montage.

    Returns the filepath to ``electrodes.tsv`` and
    ``coordsystem.json`` files.
    """
    electrodes_fnames = BIDSPath(
        subject=bids_path.subject,
        session=bids_path.session,
        space=bids_path.space,
        suffix="electrodes",
        extension=".tsv",
        root=bids_path.root,
    ).match()

    if len(electrodes_fnames) != 1:
        raise ValueError(f"Trying to load electrodes.tsv "
                         f"file using {bids_path}, but there "
                         f"are multiple files "
                         f"electrodes.tsv. Please "
                         f"uniquely specify it using additional "
                         f"BIDS entities.")
    elec_fname = electrodes_fnames[0]
    coord_fname = elec_fname.copy().update(suffix="coordsystem",
                                           extension=".json")
    if not coord_fname.fpath.exists():
        raise ValueError(f"Corresponding coordsystem.json file does not exist "
                         f"for {elec_fname}. Please check BIDS dataset.")
    return elec_fname, coord_fname
Exemplo n.º 21
0
def test_handle_chpi_reading(tmp_path):
    """Test reading of cHPI information."""
    raw = _read_raw_fif(raw_fname_chpi, allow_maxshield=True)
    root = tmp_path / 'chpi'
    root.mkdir()
    bids_path = BIDSPath(subject='01', session='01',
                         task='audiovisual', run='01',
                         root=root, datatype='meg')
    bids_path = write_raw_bids(raw, bids_path)

    raw_read = read_raw_bids(bids_path)
    assert raw_read.info['hpi_subsystem'] is not None

    # cause conflicts between cHPI info in sidecar and raw data
    meg_json_path = bids_path.copy().update(suffix='meg', extension='.json')
    with open(meg_json_path, 'r', encoding='utf-8') as f:
        meg_json_data = json.load(f)

    # cHPI frequency mismatch
    meg_json_data_freq_mismatch = meg_json_data.copy()
    meg_json_data_freq_mismatch['HeadCoilFrequency'][0] = 123
    _write_json(meg_json_path, meg_json_data_freq_mismatch, overwrite=True)

    with pytest.warns(RuntimeWarning, match='Defaulting to .* mne.Raw object'):
        raw_read = read_raw_bids(bids_path)

    # cHPI "off" according to sidecar, but present in the data
    meg_json_data_chpi_mismatch = meg_json_data.copy()
    meg_json_data_chpi_mismatch['ContinuousHeadLocalization'] = False
    _write_json(meg_json_path, meg_json_data_chpi_mismatch, overwrite=True)

    raw_read = read_raw_bids(bids_path)
    assert raw_read.info['hpi_subsystem'] is None
    assert raw_read.info['hpi_meas'] == []
Exemplo n.º 22
0
def plot_er_psd(subject, session):
    raw_fname = BIDSPath(subject=subject,
                         session=session,
                         acquisition=config.acq,
                         run=None,
                         recording=config.rec,
                         space=config.space,
                         task='noise',
                         processing='filt',
                         suffix='raw',
                         extension='.fif',
                         datatype=config.get_datatype(),
                         root=config.deriv_root,
                         check=False)

    extra_params = dict()
    if not config.use_maxwell_filter and config.allow_maxshield:
        extra_params['allow_maxshield'] = config.allow_maxshield

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

    raw_er_filtered = mne.io.read_raw_fif(raw_fname,
                                          preload=True,
                                          **extra_params)

    fmax = 1.5 * config.h_freq if config.h_freq is not None else np.inf
    fig = raw_er_filtered.plot_psd(fmax=fmax, show=False)
    return fig
Exemplo n.º 23
0
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)
Exemplo n.º 24
0
def compute_cov_from_epochs(cfg, subject, session, tmin, tmax):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         processing=cfg.proc,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    processing = None
    if cfg.spatial_filter is not None:
        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_kwargs(message=msg, 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, overwrite=True)
def run_average(cfg, session, mean_morphed_stcs):
    subject = 'average'
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         processing=cfg.proc,
                         recording=cfg.rec,
                         space=cfg.space,
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    if isinstance(cfg.conditions, dict):
        conditions = list(cfg.conditions.keys())
    else:
        conditions = cfg.conditions

    for condition, stc in zip(conditions, mean_morphed_stcs):
        method = cfg.inverse_method
        cond_str = 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}')
        stc.save(fname_stc_avg)
Exemplo n.º 26
0
def test_count_events(tmpdir):
    """Test mne_bids count_events."""

    # Check that help is printed
    check_usage(mne_bids_count_events)

    # Create test dataset.
    output_path = str(tmpdir)
    data_path = testing.data_path()
    raw_fname = op.join(data_path, 'MEG', 'sample',
                        'sample_audvis_trunc_raw.fif')

    raw = mne.io.read_raw(raw_fname)
    raw.info['line_freq'] = 60.
    events = mne.find_events(raw)
    event_id = {'auditory/left': 1, 'auditory/right': 2, 'visual/left': 3,
                'visual/right': 4, 'face': 5, 'button': 32}

    bids_path = BIDSPath(subject='01', root=output_path)
    write_raw_bids(raw, bids_path, events, event_id, overwrite=True,
                   verbose=False)

    with ArgvSetter(('--bids_root', output_path)):
        mne_bids_count_events.run()

    with ArgvSetter(('--bids_root', output_path, '--describe')):
        mne_bids_count_events.run()
Exemplo n.º 27
0
def add_event_counts(*, cfg, session: str, report: mne.Report) -> None:
    try:
        df_events = count_events(BIDSPath(root=cfg.bids_root, session=session))
    except ValueError:
        logger.warning('Could not read events.')
        df_events = None

    if df_events is not None:
        css_classes = ('table', 'table-striped', 'table-borderless',
                       'table-hover')
        report.add_htmls_to_section(
            f'<div class="event-counts">\n'
            f'{df_events.to_html(classes=css_classes, border=0)}\n'
            f'</div>',
            captions='Event counts',
            section='events')
        css = ('.event-counts {\n'
               '  display: -webkit-box;\n'
               '  display: -ms-flexbox;\n'
               '  display: -webkit-flex;\n'
               '  display: flex;\n'
               '  justify-content: center;\n'
               '  text-align: center;\n'
               '}\n\n'
               'th, td {\n'
               '  text-align: center;\n'
               '}\n')
        report.add_custom_css(css)
Exemplo n.º 28
0
def test_inspect(tmp_path):
    """Test mne_bids inspect."""

    # Check that help is printed
    check_usage(mne_bids_inspect)

    # Create test dataset.
    bids_root = str(tmp_path)
    data_path = testing.data_path()
    subject = '01'
    task = 'test'
    datatype = 'meg'
    raw_fname = op.join(data_path, 'MEG', 'sample',
                        'sample_audvis_trunc_raw.fif')

    raw = mne.io.read_raw(raw_fname)
    raw.info['line_freq'] = 60.

    bids_path = BIDSPath(subject=subject, task=task, datatype=datatype,
                         root=bids_root)
    write_raw_bids(raw, bids_path, overwrite=True, verbose=False)

    import matplotlib
    matplotlib.use('agg')

    h_freqs = (30.0, 30, '30')
    for h_freq in h_freqs:
        args = ('--bids_root', bids_root, '--h_freq', h_freq,
                '--find_flat', 0)
        with ArgvSetter(args):
            mne_bids_inspect.run()
Exemplo n.º 29
0
def run_forward(*, cfg, subject, session=None):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    fname_info = bids_path.copy().update(**cfg.source_info_path_update)
    fname_trans = bids_path.copy().update(suffix='trans')
    fname_fwd = bids_path.copy().update(suffix='fwd')

    if cfg.use_template_mri:
        src, trans, bem_sol = _prepare_forward_fsaverage(cfg)
    else:
        src, trans, bem_sol = _prepare_forward(cfg, bids_path, fname_trans)

    # Finally, calculate and save the forward solution.
    msg = 'Calculating forward solution'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))
    info = mne.io.read_info(fname_info)
    fwd = mne.make_forward_solution(info,
                                    trans=trans,
                                    src=src,
                                    bem=bem_sol,
                                    mindist=cfg.mindist)

    mne.write_trans(fname_trans, fwd['mri_head_t'], overwrite=True)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Exemplo n.º 30
0
def create_bids_path(setup=None):
    '''Create paths for BIDS.

    Args:
        setup : array
            The setup of each recording. Template available in README.
    Returns:
        Array containing the BIDS paths as MNE-BIDS BIDSPath instances.
    Raises:
        ValueError: if no setup is specified.
    '''
    if setup is None:
        raise (ValueError('Enter BIDS setup parameter array.'))

    setup = [setup] if not isinstance(setup, list) else setup

    bids_paths = []

    # Iterate over the recordings setup
    for config in setup:
        root_folder = r'%s' % config['root']
        if system() == 'Windows':
            if root_folder[-1] == '\\':
                root_folder = root_folder + 'dataset_description.json'
            else:
                root_folder = root_folder + '\\dataset_description.json'
        else:
            if root_folder[-1] == '/':
                root_folder = root_folder + 'dataset_description.json'
            else:
                root_folder = root_folder + '/dataset_description.json'

        if not path.exists(root_folder):
            warn(
                'This is the first time you create a dataset in this folder. Add a detailed description with mne-bids.make_dataset_description. A generic description was created in: '
                + root_folder)

        # Add a BIDS path for each setup
        bids_paths.append(
            BIDSPath(
                subject=(config['subject'] if 'subject' in config else None),
                session=(config['session'] if 'session' in config else None),
                task=(config['task'] if 'task' in config else None),
                acquisition=(config['acquisition']
                             if 'acquisition' in config else None),
                run=(config['run'] if 'run' in config else None),
                processing=(config['processing']
                            if 'processing' in config else None),
                recording=(config['recording']
                           if 'recording' in config else None),
                space=(config['space'] if 'space' in config else None),
                split=(config['split'] if 'split' in config else None),
                suffix=(config['suffix'] if 'suffix' in config else None),
                extension=(config['extension']
                           if 'extension' in config else None),
                root=(config['root'] if 'root' in config else None),
                datatype='eeg',
                check=True))

    return bids_paths