Exemplo n.º 1
0
def _channels_tsv(raw, fname, verbose):
    """Create a channels.tsv file and save it.

    Parameters
    ----------
    raw : instance of Raw
        The data as MNE-Python Raw object.
    fname : str
        Filename to save the channels.tsv to.
    verbose : bool
        Set verbose output to true or false.

    """
    map_chs = defaultdict(lambda: 'OTHER')
    map_chs.update(grad='MEGGRAD', mag='MEGMAG', stim='TRIG', eeg='EEG',
                   ecog='ECOG', seeg='SEEG', eog='EOG', ecg='ECG', misc='MISC',
                   resp='RESPONSE', ref_meg='REFMEG')
    map_desc = defaultdict(lambda: 'Other type of channel')
    map_desc.update(grad='Gradiometer', mag='Magnetometer',
                    stim='Trigger',
                    eeg='ElectroEncephaloGram',
                    ecog='Electrocorticography',
                    seeg='StereoEEG',
                    ecg='ElectroCardioGram',
                    eog='ElectrOculoGram', misc='Miscellaneous',
                    ref_meg='Reference channel')

    status, ch_type, description = list(), list(), list()
    for idx, ch in enumerate(raw.info['ch_names']):
        status.append('bad' if ch in raw.info['bads'] else 'good')
        ch_type.append(map_chs[channel_type(raw.info, idx)])
        description.append(map_desc[channel_type(raw.info, idx)])
    low_cutoff, high_cutoff = (raw.info['highpass'], raw.info['lowpass'])
    units = [_unit2human.get(ch_i['unit'], 'n/a') for ch_i in raw.info['chs']]
    n_channels = raw.info['nchan']
    sfreq = raw.info['sfreq']

    df = pd.DataFrame(OrderedDict([
                      ('name', raw.info['ch_names']),
                      ('type', ch_type),
                      ('units', units),
                      ('description', description),
                      ('sampling_frequency', ['%.2f' % sfreq] * n_channels),
                      ('low_cutoff', ['%.2f' % low_cutoff] * n_channels),
                      ('high_cutoff', ['%.2f' % high_cutoff] * n_channels),
                      ('status', status)]))
    df.to_csv(fname, sep='\t', index=False)

    if verbose:
        print(os.linesep + "Writing '%s'..." % fname + os.linesep)
        print(df.head())

    return fname
Exemplo n.º 2
0
def _channels_tsv(raw, fname, overwrite=False, verbose=True):
    """Create a channels.tsv file and save it.

    Parameters
    ----------
    raw : instance of Raw
        The data as MNE-Python Raw object.
    fname : str
        Filename to save the channels.tsv to.
    overwrite : bool
        Whether to overwrite the existing file.
        Defaults to False.
    verbose : bool
        Set verbose output to true or false.

    """
    map_chs = defaultdict(lambda: 'OTHER')
    map_chs.update(meggradaxial='MEGGRADAXIAL',
                   megrefgradaxial='MEGREFGRADAXIAL',
                   meggradplanar='MEGGRADPLANAR',
                   megmag='MEGMAG',
                   megrefmag='MEGREFMAG',
                   eeg='EEG',
                   misc='MISC',
                   stim='TRIG',
                   emg='EMG',
                   ecog='ECOG',
                   seeg='SEEG',
                   eog='EOG',
                   ecg='ECG')
    map_desc = defaultdict(lambda: 'Other type of channel')
    map_desc.update(meggradaxial='Axial Gradiometer',
                    megrefgradaxial='Axial Gradiometer Reference',
                    meggradplanar='Planar Gradiometer',
                    megmag='Magnetometer',
                    megrefmag='Magnetometer Reference',
                    stim='Trigger',
                    eeg='ElectroEncephaloGram',
                    ecog='Electrocorticography',
                    seeg='StereoEEG',
                    ecg='ElectroCardioGram',
                    eog='ElectroOculoGram',
                    emg='ElectroMyoGram',
                    misc='Miscellaneous')
    get_specific = ('mag', 'ref_meg', 'grad')

    # get the manufacturer from the file in the Raw object
    manufacturer = None
    if hasattr(raw, 'filenames'):
        # XXX: Hack for EEGLAB bug in MNE-Python 0.16; fixed in MNE-Python
        # 0.17, ... remove the hack after upgrading dependencies in MNE-BIDS
        if raw.filenames[0] is None:  # hack
            ext = '.set'  # hack
        else:
            _, ext = _parse_ext(raw.filenames[0], verbose=verbose)
            manufacturer = MANUFACTURERS[ext]

    ignored_indexes = [
        raw.ch_names.index(ch_name) for ch_name in raw.ch_names
        if ch_name in IGNORED_CHANNELS.get(manufacturer, list())
    ]

    status, ch_type, description = list(), list(), list()
    for idx, ch in enumerate(raw.info['ch_names']):
        status.append('bad' if ch in raw.info['bads'] else 'good')
        _channel_type = channel_type(raw.info, idx)
        if _channel_type in get_specific:
            _channel_type = coil_type(raw.info, idx)
        ch_type.append(map_chs[_channel_type])
        description.append(map_desc[_channel_type])
    low_cutoff, high_cutoff = (raw.info['highpass'], raw.info['lowpass'])
    units = [_unit2human.get(ch_i['unit'], 'n/a') for ch_i in raw.info['chs']]
    units = [u if u not in ['NA'] else 'n/a' for u in units]
    n_channels = raw.info['nchan']
    sfreq = raw.info['sfreq']

    df = pd.DataFrame(
        OrderedDict([('name', raw.info['ch_names']), ('type', ch_type),
                     ('units', units), ('description', description),
                     ('sampling_frequency', np.full((n_channels), sfreq)),
                     ('low_cutoff', np.full((n_channels), low_cutoff)),
                     ('high_cutoff', np.full((n_channels), high_cutoff)),
                     ('status', status)]))
    df.drop(ignored_indexes, inplace=True)

    _write_tsv(fname, df, overwrite, verbose)

    return fname
Exemplo n.º 3
0
def _channels_tsv(raw, fname, overwrite=False, verbose=True):
    """Create a channels.tsv file and save it.

    Parameters
    ----------
    raw : instance of Raw
        The data as MNE-Python Raw object.
    fname : str
        Filename to save the channels.tsv to.
    overwrite : bool
        Whether to overwrite the existing file.
        Defaults to False.
    verbose : bool
        Set verbose output to true or false.

    """
    # Get channel type mappings between BIDS and MNE nomenclatures
    map_chs = _get_ch_type_mapping(fro='mne', to='bids')

    # Prepare the descriptions for each channel type
    map_desc = defaultdict(lambda: 'Other type of channel')
    map_desc.update(meggradaxial='Axial Gradiometer',
                    megrefgradaxial='Axial Gradiometer Reference',
                    meggradplanar='Planar Gradiometer',
                    megmag='Magnetometer',
                    megrefmag='Magnetometer Reference',
                    stim='Trigger',
                    eeg='ElectroEncephaloGram',
                    ecog='Electrocorticography',
                    seeg='StereoEEG',
                    ecg='ElectroCardioGram',
                    eog='ElectroOculoGram',
                    emg='ElectroMyoGram',
                    misc='Miscellaneous')
    get_specific = ('mag', 'ref_meg', 'grad')

    # get the manufacturer from the file in the Raw object
    manufacturer = None

    _, ext = _parse_ext(raw.filenames[0], verbose=verbose)
    manufacturer = MANUFACTURERS[ext]

    ignored_channels = IGNORED_CHANNELS.get(manufacturer, list())

    status, ch_type, description = list(), list(), list()
    for idx, ch in enumerate(raw.info['ch_names']):
        status.append('bad' if ch in raw.info['bads'] else 'good')
        _channel_type = channel_type(raw.info, idx)
        if _channel_type in get_specific:
            _channel_type = coil_type(raw.info, idx, _channel_type)
        ch_type.append(map_chs[_channel_type])
        description.append(map_desc[_channel_type])
    low_cutoff, high_cutoff = (raw.info['highpass'], raw.info['lowpass'])
    if raw._orig_units:
        units = [raw._orig_units.get(ch, 'n/a') for ch in raw.ch_names]
    else:
        units = [_unit2human.get(ch_i['unit'], 'n/a')
                 for ch_i in raw.info['chs']]
        units = [u if u not in ['NA'] else 'n/a' for u in units]
    n_channels = raw.info['nchan']
    sfreq = raw.info['sfreq']

    ch_data = OrderedDict([
        ('name', raw.info['ch_names']),
        ('type', ch_type),
        ('units', units),
        ('low_cutoff', np.full((n_channels), low_cutoff)),
        ('high_cutoff', np.full((n_channels), high_cutoff)),
        ('description', description),
        ('sampling_frequency', np.full((n_channels), sfreq)),
        ('status', status)])
    ch_data = _drop(ch_data, ignored_channels, 'name')

    _write_tsv(fname, ch_data, overwrite, verbose)

    return fname
Exemplo n.º 4
0
def _export_mne_raw(*, raw, fname, events=None, overwrite=False):
    """Export raw data from MNE-Python.

    Parameters
    ----------
    raw : mne.io.Raw
        The raw data to export.
    fname : str | pathlib.Path
        The name of the file where raw data will be exported to. Must end with
        ``".vhdr"``, and accompanying *.vmrk* and *.eeg* files will be written
        inside the same directory.
    events : np.ndarray | None
        Events to be written to the marker file (*.vmrk*). When array, must be in
        `MNE-Python format <https://mne.tools/stable/glossary.html#term-events>`_.
        When ``None`` (default), events will be written based on ``raw.annotations``.
    overwrite : bool
        Whether or not to overwrite existing data. Defaults to ``False``.
    """
    # Prepare file location
    if not str(fname).endswith(".vhdr"):
        raise ValueError(
            "`fname` must have the '.vhdr' extension for BrainVision.")
    fname = Path(fname)
    folder_out = fname.parents[0]
    fname_base = fname.stem

    # Prepare data from raw
    data = raw.get_data()  # gets data starting from raw.first_samp
    sfreq = raw.info["sfreq"]  # in Hz
    meas_date = raw.info["meas_date"]  # datetime.datetime
    ch_names = raw.ch_names

    # write voltage units as micro-volts and all other units without
    # scaling
    # We write units that we don't know as n/a
    unit = []
    for ch in raw.info["chs"]:
        if ch["unit"] == FIFF.FIFF_UNIT_V:
            unit.append("µV")
        elif ch["unit"] == FIFF.FIFF_UNIT_CEL:
            unit.append("°C")
        else:
            unit.append(_unit2human.get(ch["unit"], "n/a"))
    unit = [u if u != "NA" else "n/a" for u in unit]

    # We enforce conversion to float32 format
    # XXX: Could add a feature that checks data and optimizes `unit`, `resolution`,
    #      and `format` so that raw.orig_format could be retained if reasonable.
    if raw.orig_format != "single":
        warn(
            f"Encountered data in '{raw.orig_format}' format. "
            "Converting to float32.",
            RuntimeWarning,
        )

    fmt = "binary_float32"
    resolution = 0.1

    # Handle events
    # if we got an ndarray, this is in MNE-Python format
    msg = "`events` must be None or array in MNE-Python format."
    if events is not None:
        # Subtract raw.first_samp because brainvision marks events starting from
        # the first available data point and ignores the raw.first_samp
        assert isinstance(events, np.ndarray), msg
        assert events.ndim == 2, msg
        assert events.shape[-1] == 3, msg
        events[:, 0] -= raw.first_samp
        events = events[:, [0, 2]]  # reorder for pybv required order

    # else, prepare pybv style events from raw.annotations
    else:
        events = _mne_annots2pybv_events(raw)

    # no information about reference channels in mne currently
    ref_ch_names = None

    # write to BrainVision
    write_brainvision(
        data=data,
        sfreq=sfreq,
        ch_names=ch_names,
        ref_ch_names=ref_ch_names,
        fname_base=fname_base,
        folder_out=folder_out,
        overwrite=overwrite,
        events=events,
        resolution=resolution,
        unit=unit,
        fmt=fmt,
        meas_date=meas_date,
    )