Python mne.create_info() Examples

The following are 10 code examples of mne.create_info(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module mne , or try the search function .
Example #1
Source File: brainflow_to_mne.py    From OpenBCI_MNE with MIT License 6 votes vote down vote up
def main():
    BoardShim.enable_dev_board_logger ()
    # use synthetic board for demo
    params = BrainFlowInputParams ()
    board = BoardShim (BoardIds.SYNTHETIC_BOARD.value, params)
    board.prepare_session ()
    board.start_stream ()
    time.sleep (10)
    data = board.get_board_data ()
    board.stop_stream ()
    board.release_session ()

    eeg_channels = BoardShim.get_eeg_channels (BoardIds.SYNTHETIC_BOARD.value)
    eeg_data = data[eeg_channels, :]
    eeg_data = eeg_data / 1000000 # BrainFlow returns uV, convert to V for MNE

    # Creating MNE objects from brainflow data arrays
    ch_types = ['eeg', 'eeg', 'eeg', 'eeg', 'eeg', 'eeg', 'eeg', 'eeg']
    ch_names = ['T7', 'CP5', 'FC5', 'C3', 'C4', 'FC6', 'CP6', 'T8']
    sfreq = BoardShim.get_sampling_rate (BoardIds.SYNTHETIC_BOARD.value)
    info = mne.create_info (ch_names = ch_names, sfreq = sfreq, ch_types = ch_types)
    raw = mne.io.RawArray (eeg_data, info)
    # its time to plot something!
    raw.plot_psd (average = True)
    plt.savefig ('psd.png') 
Example #2
Source File: epoch.py    From alphacsc with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def make_epochs(z_hat, info, t_lim, n_times_atom=1):
    """Make Epochs on the activations of atoms.
    n_splits, n_atoms, n_times_valid = z_hat.shape
    n_trials, n_atoms, n_times_epoch = z_hat_epoch.shape
    """
    n_splits, n_atoms, n_times_valid = z_hat.shape
    n_times = n_times_valid + n_times_atom - 1
    # pad with zeros
    padding = np.zeros((n_splits, n_atoms, n_times_atom - 1))
    z_hat = np.concatenate([z_hat, padding], axis=2)
    # reshape into an unique time-serie per atom
    z_hat = np.reshape(z_hat.swapaxes(0, 1), (n_atoms, n_splits * n_times))

    # create trials around the events, using mne
    new_info = mne.create_info(ch_names=n_atoms, sfreq=info['sfreq'])
    rawarray = mne.io.RawArray(data=z_hat, info=new_info, verbose=False)
    t_min, t_max = t_lim
    epochs = mne.Epochs(rawarray, info['events'], info['event_id'], t_min,
                        t_max, verbose=False)
    z_hat_epoched = epochs.get_data()
    return z_hat_epoched 
Example #3
Source File: test_utils.py    From mne-bids with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_handle_kind():
    """Test the automatic extraction of kind from the data."""
    # Create a dummy raw
    n_channels = 1
    sampling_rate = 100
    data = random((n_channels, sampling_rate))
    channel_types = ['grad', 'eeg', 'ecog']
    expected_kinds = ['meg', 'eeg', 'ieeg']
    # do it once for each type ... and once for "no type"
    for chtype, kind in zip(channel_types, expected_kinds):
        info = mne.create_info(n_channels, sampling_rate, ch_types=[chtype])
        raw = mne.io.RawArray(data, info)
        assert _handle_kind(raw) == kind

    # if the situation is ambiguous (EEG and iEEG channels both), raise error
    with pytest.raises(ValueError, match='Both EEG and iEEG channels found'):
        info = mne.create_info(2, sampling_rate,
                               ch_types=['eeg', 'ecog'])
        raw = mne.io.RawArray(random((2, sampling_rate)), info)
        _handle_kind(raw)

    # if we cannot find a proper channel type, we raise an error
    with pytest.raises(ValueError, match='Neither MEG/EEG/iEEG channels'):
        info = mne.create_info(n_channels, sampling_rate, ch_types=['misc'])
        raw = mne.io.RawArray(data, info)
        _handle_kind(raw) 
Example #4
Source File: test_hypno.py    From yasa with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_raw(npts, ch_names=['F4-M1', 'F3-M2'], sf=100):
    """Utility function for test fit to data."""
    nchan = len(ch_names)
    info = mne.create_info(ch_names=ch_names, sfreq=sf,
                           ch_types=['eeg'] * nchan, verbose=0)
    data = np.random.rand(nchan, npts)
    raw = mne.io.RawArray(data, info, verbose=0)
    return raw 
Example #5
Source File: mnefiff.py    From wonambi with GNU General Public License v3.0 5 votes vote down vote up
def write_mnefiff(data, filename):
    """Export data to MNE using FIFF format.

    Parameters
    ----------
    data : instance of ChanTime
        data with only one trial
    filename : path to file
        file to export to (include '.mat')

    Notes
    -----
    It cannot store data larger than 2 GB.
    The data is assumed to have only EEG electrodes.
    It overwrites a file if it exists.
    """
    from mne import create_info, set_log_level
    from mne.io import RawArray

    set_log_level(WARNING)

    TRIAL = 0
    info = create_info(list(data.axis['chan'][TRIAL]), data.s_freq, ['eeg', ] *
                       data.number_of('chan')[TRIAL])

    UNITS = 1e-6  # mne wants data in uV
    fiff = RawArray(data.data[0] * UNITS, info)

    if data.attr['chan']:
        fiff.set_channel_positions(data.attr['chan'].return_xyz(),
                                   data.attr['chan'].return_label())

    fiff.save(filename, overwrite=True) 
Example #6
Source File: xdf.py    From mnelab with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def read_raw_xdf(fname, stream_id, *args, **kwargs):
    """Read XDF file.

    Parameters
    ----------
    fname : str
        Name of the XDF file.
    stream_id : int
        ID (number) of the stream to load.

    Returns
    -------
    raw : mne.io.Raw
        XDF file data.
    """
    from pyxdf import load_xdf, match_streaminfos, resolve_streams

    streams, header = load_xdf(fname)
    for stream in streams:
        if stream["info"]["stream_id"] == stream_id:
            break  # stream found

    n_chans = int(stream["info"]["channel_count"][0])
    fs = float(stream["info"]["nominal_srate"][0])
    labels, types, units = [], [], []
    try:
        for ch in stream["info"]["desc"][0]["channels"][0]["channel"]:
            labels.append(str(ch["label"][0]))
            if ch["type"]:
                types.append(ch["type"][0])
            if ch["unit"]:
                units.append(ch["unit"][0])
    except (TypeError, IndexError):  # no channel labels found
        pass
    if not labels:
        labels = [str(n) for n in range(n_chans)]
    if not units:
        units = ["NA" for _ in range(n_chans)]
    info = mne.create_info(ch_names=labels, sfreq=fs, ch_types="eeg")
    # convert from microvolts to volts if necessary
    scale = np.array([1e-6 if u == "microvolts" else 1 for u in units])
    raw = mne.io.RawArray((stream["time_series"] * scale).T, info)
    raw._filenames = [fname]
    first_samp = stream["time_stamps"][0]
    markers = match_streaminfos(resolve_streams(fname), [{"type": "Markers"}])
    for stream_id in markers:
        for stream in streams:
            if stream["info"]["stream_id"] == stream_id:
                break
        onsets = stream["time_stamps"] - first_samp
        descriptions = [item for sub in stream["time_series"] for item in sub]
        raw.annotations.append(onsets, [0] * len(onsets), descriptions)
    return raw 
Example #7
Source File: sleeploader.py    From AutoSleepScorer with GNU Affero General Public License v3.0 5 votes vote down vote up
def preprocess(self):
        # filtering
        self.eeg = butter_bandpass_filter(self.eeg, 0.15, self.sfreq)
        self.emg = butter_bandpass_filter(self.emg, 10.0, self.sfreq)
        self.eog = butter_bandpass_filter(self.eog, 0.15, self.sfreq)
        
        # resampling
        if not np.isclose(self.sfreq, 100): 
            print('resampling from {} Hz to {} Hz'.format(self.sfreq, 100))
            if self.use_mp and hasattr(SleepData,'pool') and type(SleepData.pool) is Pool:
                res_eeg = SleepData.pool.apply_async(mne.io.RawArray(np.stack([self.eeg]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample, args = (100.,))
                res_emg = SleepData.pool.apply_async(mne.io.RawArray(np.stack([self.emg]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample, args = (100.,))
                res_eog = SleepData.pool.apply_async(mne.io.RawArray(np.stack([self.eog]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample, args = (100.,))
                eeg,_ = res_eeg.get(timeout=30)[0,:]
                emg,_ = res_emg.get(timeout=30)[0,:]
                eog,_ = res_eog.get(timeout=30)[0,:]

            else:
                eeg,_ = mne.io.RawArray(np.stack([self.eeg]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample(100.)[0,:]
                emg,_ = mne.io.RawArray(np.stack([self.emg]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample(100.)[0,:]
                eog,_ = mne.io.RawArray(np.stack([self.eog]), mne.create_info(1, self.sfreq, 'eeg'), verbose=0).resample(100.)[0,:]
                  
            self.sfreq = 100
            self.eeg = eeg.squeeze()
            self.emg = emg.squeeze()
            self.eog = eog.squeeze() 
Example #8
Source File: test_mne_api.py    From pactools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_empty_raw():
    n_channels = 3
    n_points = 300
    data = np.empty([n_channels, n_points])
    fs = 200.
    info = mne.create_info(ch_names=n_channels, sfreq=fs)
    raw = mne.io.RawArray(data, info)
    return raw 
Example #9
Source File: test_connectivity.py    From conpy with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _simulate_data(fwd_fixed, source_vertno1, source_vertno2):
    """Simulate two oscillators on the cortex."""

    sfreq = 50.  # Hz.
    base_freq = 10
    t_rand = 0.001
    std = 0.1
    times = np.arange(10. * sfreq) / sfreq  # 10 seconds of data
    n_times = len(times)
    # Generate an oscillator with varying frequency and phase lag.
    iflaw = base_freq / sfreq + t_rand * np.random.randn(n_times)
    signal1 = np.exp(1j * 2.0 * np.pi * np.cumsum(iflaw))
    signal1 *= np.conj(signal1[0])
    signal1 = signal1.real

    # Add some random fluctuations to the signal.
    signal1 += std * np.random.randn(n_times)
    signal1 *= 1e-7

    # Make identical signal
    signal2 = signal1.copy()

    # Add random fluctuations
    signal1 += 1e-8 * np.random.randn(len(times))
    signal2 += 1e-8 * np.random.randn(len(times))

    # Construct a SourceEstimate object
    stc = mne.SourceEstimate(
        np.vstack((signal1[np.newaxis, :], signal2[np.newaxis, :])),
        vertices=[np.array([source_vertno1]), np.array([source_vertno2])],
        tmin=0,
        tstep=1 / sfreq,
        subject='sample',
    )

    # Create an info object that holds information about the sensors
    info = mne.create_info(fwd_fixed['info']['ch_names'], sfreq,
                           ch_types='grad')
    info.update(fwd_fixed['info'])  # Merge in sensor position information

    # Simulated sensor data.
    raw = mne.apply_forward_raw(fwd_fixed, stc, info)

    # Add noise
    noise = random.randn(*raw._data.shape) * 1e-14
    raw._data += noise

    # Define a single epoch
    epochs = mne.Epochs(raw, np.array([[0, 0, 1]]), event_id=1, tmin=0,
                        tmax=raw.times[-1], preload=True)

    # Compute the cross-spectral density matrix
    csd = csd_morlet(epochs, frequencies=[10, 20])

    return csd 
Example #10
Source File: stream.py    From rteeg with MIT License 4 votes vote down vote up
def _connect(self):
        """Connect to stream and record data to list."""
        self._stream_inlet = _get_stream_inlet(self.lsl_predicate)
        self._active = True

        # Extract stream info.
        info = self._stream_inlet.info()

        # Get sampling frequency.
        sfreq = float(info.nominal_srate())

        # Get channel names.
        ch_names = []
        this_child = info.desc().child('channel')
        for _ in range(info.channel_count()):
            ch_names.append(this_child.child_value('name'))
            this_child = this_child.next_sibling('channel')

        # Get the EEG measurement unit (e.g., microvolts).
        units = []
        this_child = info.desc().child('channel')
        for _ in range(info.channel_count()):
            units.append(this_child.child_value('unit'))
            this_child = this_child.next_sibling('channel')
        if all(units):
            self._eeg_unit = units[0]
        else:
            logger.warning("Could not find EEG measurement unit.")

        # Add stimulus channel.
        ch_types = ['eeg' for _ in ch_names] + ['stim']
        ch_names.append('STI 014')

        # Create mne.Info object.
        try:
            self.info = create_info(ch_names=ch_names,
                                    sfreq=sfreq, ch_types=ch_types,
                                    montage=self.key)
        except ValueError:
            self.info = create_info(ch_names=ch_names,
                                    sfreq=sfreq, ch_types=ch_types,
                                    montage=None)
            logger.warning("Could not find montage for '{}'"
                           "".format(self.key))

        # Add time of recording.
        dt = datetime.datetime.now()
        timestamp = time.mktime(dt.timetuple())
        self.info['meas_date'] = [timestamp, 0]

        # Record data in a while loop.
        self._record_data_indefinitely(self._stream_inlet)