Ejemplo n.º 1
0
def copyfile_kit(src, dest, subject_id, session_id, task, run, _init_kwargs):
    """Copy and rename KIT files to a new location.

    Parameters
    ----------
    src : str
        Path to the source raw .con or .sqd folder.
    dest : str
        Path to the destination of the new bids folder.
    subject_id : str | None
        The subject ID. Corresponds to "sub".
    session_id : str | None
        The session identifier. Corresponds to "ses".
    task : str | None
        The task identifier. Corresponds to "task".
    run : int | None
        The run number. Corresponds to "run".
    _init_kwargs : dict
        Extract information of marker and headpoints

    """
    from mne_bids.write import make_bids_basename
    # KIT data requires the marker file to be copied over too
    sh.copyfile(src, dest)
    data_path = op.split(dest)[0]
    if 'mrk' in _init_kwargs:
        hpi = _init_kwargs['mrk']
        acq_map = dict()
        if isinstance(hpi, list):
            if _get_mrk_meas_date(hpi[0]) > _get_mrk_meas_date(hpi[1]):
                raise ValueError('Markers provided in incorrect order.')
            _, marker_ext = _parse_ext(hpi[0])
            acq_map = dict(zip(['pre', 'post'], hpi))
        else:
            _, marker_ext = _parse_ext(hpi)
            acq_map[None] = hpi
        for key, value in acq_map.items():
            marker_fname = make_bids_basename(subject=subject_id,
                                              session=session_id,
                                              task=task,
                                              run=run,
                                              acquisition=key,
                                              suffix='markers%s' % marker_ext,
                                              prefix=data_path)
            sh.copyfile(value, marker_fname)
    for acq in ['elp', 'hsp']:
        if acq in _init_kwargs:
            position_file = _init_kwargs[acq]
            task, run, acq = None, None, acq.upper()
            position_ext = '.pos'
            position_fname = make_bids_basename(subject=subject_id,
                                                session=session_id,
                                                task=task,
                                                run=run,
                                                acquisition=acq,
                                                suffix='headshape%s' %
                                                position_ext,
                                                prefix=data_path)
            sh.copyfile(position_file, position_fname)
Ejemplo n.º 2
0
def test_handle_info_reading():
    """Test reading information from a BIDS sidecar.json file."""
    bids_root = _TempDir()

    # read in USA dataset, so it should find 50 Hz
    raw = mne.io.read_raw_fif(raw_fname)
    raw.info['line_freq'] = 60

    # write copy of raw with line freq of 60
    # bids basename and fname
    bids_basename = make_bids_basename(subject='01',
                                       session='01',
                                       task='audiovisual',
                                       run='01')
    kind = "meg"
    bids_fname = bids_basename + '_{}.fif'.format(kind)
    write_raw_bids(raw, bids_basename, bids_root, overwrite=True)

    # find sidecar JSON fname
    sidecar_fname = _find_matching_sidecar(bids_fname,
                                           bids_root,
                                           '{}.json'.format(kind),
                                           allow_fail=True)

    # assert that we get the same line frequency set
    raw = mne_bids.read_raw_bids(bids_fname, bids_root)
    assert raw.info['line_freq'] == 60

    # 2. if line frequency is not set in raw file, then default to sidecar
    raw.info['line_freq'] = None
    write_raw_bids(raw, bids_basename, bids_root, overwrite=True)
    _update_sidecar(sidecar_fname, "PowerLineFrequency", 55)
    raw = mne_bids.read_raw_bids(bids_fname, bids_root)
    assert raw.info['line_freq'] == 55

    # make a copy of the sidecar in "derivatives/"
    # to check that we make sure we always get the right sidecar
    # in addition, it should not break the sidecar reading
    # in `read_raw_bids`
    deriv_dir = op.join(bids_root, "derivatives")
    sidecar_copy = op.join(deriv_dir, op.basename(sidecar_fname))
    os.mkdir(deriv_dir)
    with open(sidecar_fname, "r") as fin:
        sidecar_json = json.load(fin)
        sidecar_json["PowerLineFrequency"] = 45
    _write_json(sidecar_copy, sidecar_json)
    raw = mne_bids.read_raw_bids(bids_fname, bids_root)
    assert raw.info['line_freq'] == 55

    # 3. if line frequency is set in raw file, but not sidecar
    raw.info['line_freq'] = 60
    write_raw_bids(raw, bids_basename, bids_root, overwrite=True)
    _update_sidecar(sidecar_fname, "PowerLineFrequency", "n/a")
    raw = mne_bids.read_raw_bids(bids_fname, bids_root)
    assert raw.info['line_freq'] == 60

    # 4. assert that we get an error when sidecar json doesn't match
    _update_sidecar(sidecar_fname, "PowerLineFrequency", 55)
    with pytest.raises(ValueError, match="Line frequency in sidecar json"):
        raw = mne_bids.read_raw_bids(bids_fname, bids_root)
Ejemplo n.º 3
0
def test_get_matched_empty_room():
    """Test reading of empty room data."""
    bids_root = _TempDir()

    raw = mne.io.read_raw_fif(raw_fname)
    bids_basename = make_bids_basename(subject='01',
                                       session='01',
                                       task='audiovisual',
                                       run='01')
    write_raw_bids(raw, bids_basename, bids_root, overwrite=True)

    er_fname = get_matched_empty_room(bids_basename + '_meg.fif', bids_root)
    assert er_fname is None

    # testing data has no noise recording, so save the actual data
    # as if it were noise
    er_raw_fname = op.join(data_path, 'MEG', 'sample', 'ernoise_raw.fif')
    raw.crop(0, 10).save(er_raw_fname, overwrite=True)

    er_raw = mne.io.read_raw_fif(er_raw_fname)
    er_date = er_raw.info['meas_date']
    if not isinstance(er_date, datetime):
        # mne < v0.20
        er_date = datetime.fromtimestamp(er_raw.info['meas_date'][0])
    er_date = er_date.strftime('%Y%m%d')
    er_bids_basename = make_bids_basename(subject='emptyroom',
                                          task='noise',
                                          session=er_date)
    write_raw_bids(er_raw, er_bids_basename, bids_root, overwrite=True)

    er_fname = get_matched_empty_room(bids_basename + '_meg.fif', bids_root)
    assert er_bids_basename in er_fname

    # assert that we get best emptyroom if there are multiple available
    sh.rmtree(op.join(bids_root, 'sub-emptyroom'))
    dates = ['20021204', '20021201', '20021001']
    for date in dates:
        er_bids_basename = make_bids_basename(subject='emptyroom',
                                              task='noise',
                                              session=date)
        er_meas_date = datetime.strptime(date, '%Y%m%d')
        if check_version('mne', '0.20'):
            er_raw.set_meas_date(er_meas_date.replace(tzinfo=timezone.utc))
        else:
            er_raw.info['meas_date'] = (er_meas_date.timestamp(), 0)
        write_raw_bids(er_raw, er_bids_basename, bids_root)

    best_er_fname = get_matched_empty_room(bids_basename + '_meg.fif',
                                           bids_root)
    assert '20021204' in best_er_fname

    # assert that we get error if meas_date is not available.
    raw = mne_bids.read_raw_bids(bids_basename + '_meg.fif', bids_root)
    if check_version('mne', '0.20'):
        raw.set_meas_date(None)
    else:
        raw.info['meas_date'] = None
        raw.annotations.orig_time = None
    anonymize_info(raw.info)
    write_raw_bids(raw, bids_basename, bids_root, overwrite=True)
    with pytest.raises(ValueError, match='Measurement date not available'):
        get_matched_empty_room(bids_basename + '_meg.fif', bids_root)
Ejemplo n.º 4
0
from mne_bids.read import (read_raw_bids, _read_raw, get_head_mri_trans,
                           _handle_events_reading, _handle_info_reading)
from mne_bids.tsv_handler import _to_tsv, _from_tsv
from mne_bids.utils import (_find_matching_sidecar, _update_sidecar,
                            _write_json)
from mne_bids.write import write_anat, write_raw_bids, make_bids_basename

subject_id = '01'
session_id = '01'
run = '01'
acq = '01'
task = 'testing'

bids_basename = make_bids_basename(subject=subject_id,
                                   session=session_id,
                                   run=run,
                                   acquisition=acq,
                                   task=task)

# Get the MNE testing sample data - USA
data_path = testing.data_path()
raw_fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')

# Get the MNE somato data - EU
somato_path = somato.data_path()
somato_raw_fname = op.join(somato_path, 'sub-01', 'meg',
                           'sub-01_task-somato_meg.fif')


def test_read_raw():
    """Test the raw reading."""
Ejemplo n.º 5
0
def test_copyfile_kit():
    """Test copying and renaming KIT files to a new location."""
    output_path = _TempDir()
    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'

    bids_basename = make_bids_basename(subject=subject_id,
                                       session=session_id,
                                       run=run,
                                       acquisition=acq,
                                       task=task)

    kit_bids_basename = bids_basename.replace('_acq-01', '')

    raw = mne.io.read_raw_kit(raw_fname,
                              mrk=hpi_fname,
                              elp=electrode_fname,
                              hsp=headshape_fname)
    _, ext = _parse_ext(raw_fname, verbose=True)
    kind = _handle_kind(raw)
    bids_fname = bids_basename + '_%s%s' % (kind, ext)
    bids_fname = op.join(output_path, bids_fname)

    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':
        assert op.exists(
            op.join(output_path, kit_bids_basename + '_markers.sqd'))
    elif ext == '.mrk':
        assert op.exists(
            op.join(output_path, kit_bids_basename + '_markers.mrk'))

    if op.exists(electrode_fname):
        task, run, key = None, None, 'ELP'
        elp_ext = '.pos'
        elp_fname = make_bids_basename(subject=subject_id,
                                       session=session_id,
                                       task=task,
                                       run=run,
                                       acquisition=key,
                                       suffix='headshape%s' % elp_ext,
                                       prefix=output_path)
        assert op.exists(elp_fname)

    if op.exists(headshape_fname):
        task, run, key = None, None, 'HSP'
        hsp_ext = '.pos'
        hsp_fname = make_bids_basename(subject=subject_id,
                                       session=session_id,
                                       task=task,
                                       run=run,
                                       acquisition=key,
                                       suffix='headshape%s' % hsp_ext,
                                       prefix=output_path)
        assert op.exists(hsp_fname)