Exemplo n.º 1
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.º 2
0
def test_count_no_events_file(tmpdir):
    """Test count_events with no event present."""
    data_path = testing.data_path()
    raw_fname = \
        Path(data_path) / 'MEG' / 'sample' / 'sample_audvis_trunc_raw.fif'
    raw = mne.io.read_raw(raw_fname)
    raw.info['line_freq'] = 60.
    root = str(tmpdir)

    bids_path = BIDSPath(
        subject='01', task='task1', root=root,
    )
    write_raw_bids(raw, bids_path, overwrite=True, verbose=False)

    with pytest.raises(ValueError, match='No events files found.'):
        count_events(root)
Exemplo n.º 3
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.º 4
0
def run():
    """Run the raw_to_bids command."""
    import pandas as pd
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__, usage="usage: %prog options args",
                           prog_prefix='mne_bids',
                           version=mne_bids.__version__)

    parser.add_option('--bids_root', dest='bids_root',
                      help='The path of the BIDS compatible folder.')

    parser.add_option('--datatype', dest='datatype', default='auto',
                      help='The datatype to consider.')

    parser.add_option('--describe', dest='describe', action="store_true",
                      help=('If set print the descriptive statistics '
                            '(min, max, etc.).'))

    parser.add_option('--output', dest='output', default=None,
                      help='Path to the CSV file where to store the results.')

    parser.add_option('--overwrite', dest='overwrite', action='store_true',
                      help='If set, overwrite an existing output file.')

    parser.add_option('--silent', dest='silent', action='store_true',
                      help='Whether to print the event counts on the screen.')

    opt, args = parser.parse_args()

    if len(args) > 0:
        parser.print_help()
        parser.error('Do not specify arguments without flags. Found: "{}".\n'
                     .format(args))

    if not all([opt.bids_root]):
        parser.print_help()
        parser.error('Arguments missing. You need to specify the '
                     '--bids_root parameter.')

    if opt.output and Path(opt.output).exists() and not opt.overwrite:
        parser.error('Output file exists. To overwrite, pass --overwrite')

    counts = count_events(opt.bids_root, datatype=opt.datatype)

    if opt.describe:
        counts = counts.describe()

    if not opt.silent:
        with pd.option_context(
            'display.max_rows', 1000,
            'display.max_columns', 80,
            'display.width', 1000
        ):
            print(counts)

    if opt.output:
        counts.to_csv(opt.output)
        print(f'\nOutput stored in {opt.output}')
Exemplo n.º 5
0
def test_count_events(tmpdir, subjects, tasks, runs, sessions):
    """Test the event counts."""
    root, events, event_id = _make_dataset(tmpdir, subjects, tasks, runs,
                                           sessions)

    counts = count_events(root)

    _check_counts(counts, events, event_id, subjects, tasks, runs, sessions)
Exemplo n.º 6
0
def test_count_no_events_column(tmpdir):
    """Test case where events.tsv doesn't contain [stim,trial]_type column."""
    subject, task, run, session, datatype = '01', 'task1', '01', '01', 'meg'
    root, events, event_id = _make_dataset(tmpdir, [subject], [task], [run],
                                           [session])

    # Delete the `stim_type` column.
    events_tsv_fpath = BIDSPath(root=root, subject=subject, task=task, run=run,
                                session=session, datatype=datatype,
                                suffix='events', extension='.tsv').fpath
    events_tsv = _from_tsv(events_tsv_fpath)
    events_tsv['stim_type'] = events_tsv['trial_type']
    del events_tsv['trial_type']
    _write_tsv(fname=events_tsv_fpath, dictionary=events_tsv, overwrite=True)

    counts = count_events(root)
    _check_counts(counts, events, event_id, [subject], [task], [run],
                  [session])
Exemplo n.º 7
0
def run():
    """Run the raw_to_bids command."""
    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__,
                           usage="usage: %prog options args",
                           prog_prefix='mne_bids',
                           version=mne_bids.__version__)

    parser.add_option('--bids_root',
                      dest='bids_root',
                      help='The path of the BIDS compatible folder.')

    parser.add_option('--datatype',
                      dest='datatype',
                      default='auto',
                      help='The datatype to consider.')

    parser.add_option('--describe',
                      dest='describe',
                      action="store_true",
                      help=('If set print the descriptive statistics '
                            '(min, max, etc.).'))

    opt, args = parser.parse_args()

    if len(args) > 0:
        parser.print_help()
        parser.error(
            'Do not specify arguments without flags. Found: "{}".\n'.format(
                args))

    if not all([opt.bids_root]):
        parser.print_help()
        parser.error('Arguments missing. You need to specify the '
                     '--bids_root parameter.')

    counts = count_events(opt.bids_root, datatype=opt.datatype)

    if opt.describe:
        counts = counts.describe()

    print(counts)
Exemplo n.º 8
0
print(raw.annotations)

# %%
# Finally, let's write the BIDS data!

bids_path = BIDSPath(subject=subject_id, task=task, root=bids_root)
write_raw_bids(raw, bids_path, overwrite=True)

# %%
# What does our fresh BIDS directory look like?
print_dir_tree(bids_root)

# %%
# Finally let's get an overview of the events on the whole dataset

counts = count_events(bids_root)
counts

# %%
# We can see that MNE-BIDS wrote several important files related to subject 1
# for us:
#
# * ``optodes.tsv`` containing the optode coordinates and
#   ``coordsystem.json``, which contains the metadata about the optode
#   coordinates.
# * The actual SNIRF data file (with a proper BIDS name) and an accompanying
#   ``*_nirs.json`` file that contains metadata about the NIRS recording.
# * The ``*scans.json`` file lists all data recordings with their acquisition
#   date. This file becomes more handy once there are multiple sessions and
#   recordings to keep track of.
# * And finally, ``channels.tsv`` and ``events.tsv`` which contain even further
Exemplo n.º 9
0
cal_fname = op.join(data_path, 'SSS', 'sss_cal_mgh.dat')
ct_fname = op.join(data_path, 'SSS', 'ct_sparse_mgh.fif')

write_meg_calibration(cal_fname, bids_path)
write_meg_crosstalk(ct_fname, bids_path)

###############################################################################
# Now let's see the structure of the BIDS folder we created.

print_dir_tree(output_path)

###############################################################################
# Now let's get an overview of the events on the whole dataset

counts = count_events(output_path)
counts

###############################################################################
# A big advantage of having data organized according to BIDS is that software
# packages can automate your workflow. For example, reading the data back
# into MNE-Python can easily be done using :func:`read_raw_bids`.

raw = read_raw_bids(bids_path=bids_path)

###############################################################################
# The resulting data is already in a convenient form to create epochs and
# evoked data.

events, event_id = mne.events_from_annotations(raw)
epochs = mne.Epochs(raw, events, event_id)