当前位置: 首页>>代码示例>>Python>>正文


Python Raw.time_as_index方法代码示例

本文整理汇总了Python中mne.fiff.Raw.time_as_index方法的典型用法代码示例。如果您正苦于以下问题:Python Raw.time_as_index方法的具体用法?Python Raw.time_as_index怎么用?Python Raw.time_as_index使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在mne.fiff.Raw的用法示例。


在下文中一共展示了Raw.time_as_index方法的12个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_io_complex

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_io_complex():
    """Test IO with complex data types
    """
    dtypes = [np.complex64, np.complex128]

    raw = Raw(fif_fname, preload=True)
    picks = np.arange(5)
    start, stop = raw.time_as_index([0, 5])

    data_orig, _ = raw[picks, start:stop]

    for di, dtype in enumerate(dtypes):
        imag_rand = np.array(1j * np.random.randn(data_orig.shape[0],
                             data_orig.shape[1]), dtype)

        raw_cp = raw.copy()
        raw_cp._data = np.array(raw_cp._data, dtype)
        raw_cp._data[picks, start:stop] += imag_rand
        # this should throw an error because it's complex
        with warnings.catch_warnings(record=True) as w:
            raw_cp.save(op.join(tempdir, 'raw.fif'), picks, tmin=0, tmax=5)
            # warning only gets thrown on first instance
            assert_equal(len(w), 1 if di == 0 else 0)

        raw2 = Raw(op.join(tempdir, 'raw.fif'))
        raw2_data, _ = raw2[picks, :]
        n_samp = raw2_data.shape[1]
        assert_array_almost_equal(raw2_data[:, :n_samp],
                                  raw_cp._data[picks, :n_samp])
        # with preloading
        raw2 = Raw(op.join(tempdir, 'raw.fif'), preload=True)
        raw2_data, _ = raw2[picks, :]
        n_samp = raw2_data.shape[1]
        assert_array_almost_equal(raw2_data[:, :n_samp],
                                  raw_cp._data[picks, :n_samp])
开发者ID:mshamalainen,项目名称:mne-python,代码行数:37,代码来源:test_raw.py

示例2: test_io_raw

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_io_raw():
    """Test IO for raw data (Neuromag + CTF + gz)
    """
    fnames_in = [fif_fname, fif_gz_fname, ctf_fname]
    fnames_out = ["raw.fif", "raw.fif.gz", "raw.fif"]
    for fname_in, fname_out in zip(fnames_in, fnames_out):
        raw = Raw(fname_in)

        nchan = raw.info["nchan"]
        ch_names = raw.info["ch_names"]
        meg_channels_idx = [k for k in range(nchan) if ch_names[k][0] == "M"]
        n_channels = 100
        meg_channels_idx = meg_channels_idx[:n_channels]
        start, stop = raw.time_as_index([0, 5])
        data, times = raw[meg_channels_idx, start : (stop + 1)]
        meg_ch_names = [ch_names[k] for k in meg_channels_idx]

        # Set up pick list: MEG + STI 014 - bad channels
        include = ["STI 014"]
        include += meg_ch_names
        picks = pick_types(
            raw.info, meg=True, eeg=False, stim=True, misc=True, include=include, exclude=raw.info["bads"]
        )
        print "Number of picked channels : %d" % len(picks)

        # Writing with drop_small_buffer True
        raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3, drop_small_buffer=True)
        raw2 = Raw(fname_out, preload=True)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]
        assert_true(times2.max() <= 3)

        # Writing
        raw.save(fname_out, picks, tmin=0, tmax=5)

        if fname_in == fif_fname or fname_in == fif_fname + ".gz":
            assert_true(len(raw.info["dig"]) == 146)

        raw2 = Raw(fname_out)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]

        assert_array_almost_equal(data, data2)
        assert_array_almost_equal(times, times2)
        assert_array_almost_equal(raw.info["dev_head_t"]["trans"], raw2.info["dev_head_t"]["trans"])
        assert_array_almost_equal(raw.info["sfreq"], raw2.info["sfreq"])

        if fname_in == fif_fname or fname_in == fif_fname + ".gz":
            assert_array_almost_equal(raw.info["dig"][0]["r"], raw2.info["dig"][0]["r"])
开发者ID:starzynski,项目名称:mne-python,代码行数:53,代码来源:test_raw.py

示例3: test_raw_index_as_time

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_raw_index_as_time():
    """ Test index as time conversion"""
    raw = Raw(fif_fname, preload=True)
    t0 = raw.index_as_time([0], True)[0]
    t1 = raw.index_as_time([100], False)[0]
    t2 = raw.index_as_time([100], True)[0]
    assert_true((t2 - t1) == t0)
    # ensure we can go back and forth
    t3 = raw.index_as_time(raw.time_as_index([0], True), True)
    assert_array_almost_equal(t3, [0.0], 2)
    t3 = raw.index_as_time(raw.time_as_index(raw.info['sfreq'], True), True)
    assert_array_almost_equal(t3, [raw.info['sfreq']], 2)
    t3 = raw.index_as_time(raw.time_as_index(raw.info['sfreq'], False), False)
    assert_array_almost_equal(t3, [raw.info['sfreq']], 2)
    i0 = raw.time_as_index(raw.index_as_time([0], True), True)
    assert_true(i0[0] == 0)
    i1 = raw.time_as_index(raw.index_as_time([100], True), True)
    assert_true(i1[0] == 100)
    # Have to add small amount of time because we truncate via int casting
    i1 = raw.time_as_index(raw.index_as_time([100.0001], False), False)
    assert_true(i1[0] == 100)
开发者ID:mshamalainen,项目名称:mne-python,代码行数:23,代码来源:test_raw.py

示例4: test_raw_time_as_index

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_raw_time_as_index():
    """ Test index as time conversion"""
    raw = Raw(fif_fname, preload=True)
    first_samp = raw.time_as_index([0], True)[0]
    assert_true(raw.first_samp == -first_samp)
开发者ID:mshamalainen,项目名称:mne-python,代码行数:7,代码来源:test_raw.py

示例5: test_io_raw

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_io_raw():
    """Test IO for raw data (Neuromag + CTF + gz)
    """
    fnames_in = [fif_fname, fif_gz_fname, ctf_fname]
    fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif']
    for fname_in, fname_out in zip(fnames_in, fnames_out):
        fname_out = op.join(tempdir, fname_out)
        raw = Raw(fname_in)

        nchan = raw.info['nchan']
        ch_names = raw.info['ch_names']
        meg_channels_idx = [k for k in range(nchan)
                            if ch_names[k][0] == 'M']
        n_channels = 100
        meg_channels_idx = meg_channels_idx[:n_channels]
        start, stop = raw.time_as_index([0, 5])
        data, times = raw[meg_channels_idx, start:(stop + 1)]
        meg_ch_names = [ch_names[k] for k in meg_channels_idx]

        # Set up pick list: MEG + STI 014 - bad channels
        include = ['STI 014']
        include += meg_ch_names
        picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
                           misc=True, include=include, exclude='bads')

        # Writing with drop_small_buffer True
        raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3,
                 drop_small_buffer=True)
        raw2 = Raw(fname_out, preload=True)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]
        assert_true(times2.max() <= 3)

        # Writing
        raw.save(fname_out, picks, tmin=0, tmax=5)

        if fname_in == fif_fname or fname_in == fif_fname + '.gz':
            assert_true(len(raw.info['dig']) == 146)

        raw2 = Raw(fname_out)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]

        assert_array_almost_equal(data, data2)
        assert_array_almost_equal(times, times2)
        assert_array_almost_equal(raw.info['sfreq'], raw2.info['sfreq'])

        # check transformations
        for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']:
            if raw.info[trans] is None:
                assert_true(raw2.info[trans] is None)
            else:
                assert_array_equal(raw.info[trans]['trans'],
                                   raw2.info[trans]['trans'])

                # check transformation 'from' and 'to'
                if trans.startswith('dev'):
                    from_id = FIFF.FIFFV_COORD_DEVICE
                else:
                    from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD
                if trans[4:8] == 'head':
                    to_id = FIFF.FIFFV_COORD_HEAD
                else:
                    to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD
                for raw_ in [raw, raw2]:
                    assert_true(raw_.info[trans]['from'] == from_id)
                    assert_true(raw_.info[trans]['to'] == to_id)

        if fname_in == fif_fname or fname_in == fif_fname + '.gz':
            assert_array_almost_equal(raw.info['dig'][0]['r'],
                                      raw2.info['dig'][0]['r'])
开发者ID:mshamalainen,项目名称:mne-python,代码行数:75,代码来源:test_raw.py

示例6: test_io_raw

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
def test_io_raw():
    """Test IO for raw data (Neuromag + CTF + gz)
    """
    # Let's construct a simple test for IO first
    raw = Raw(fif_fname, preload=True)
    raw.crop(0, 3.5)
    # put in some data that we know the values of
    data = np.random.randn(raw._data.shape[0], raw._data.shape[1])
    raw._data[:, :] = data
    # save it somewhere
    fname = op.join(tempdir, 'test_copy_raw.fif')
    raw.save(fname, buffer_size_sec=1.0)
    # read it in, make sure the whole thing matches
    raw = Raw(fname)
    assert_true(np.allclose(data, raw[:, :][0], 1e-6, 1e-20))
    # let's read portions across the 1-sec tag boundary, too
    inds = raw.time_as_index([1.75, 2.25])
    sl = slice(inds[0], inds[1])
    assert_true(np.allclose(data[:, sl], raw[:, sl][0], 1e-6, 1e-20))

    # now let's do some real I/O
    fnames_in = [fif_fname, fif_gz_fname, ctf_fname]
    fnames_out = ['raw.fif', 'raw.fif.gz', 'raw.fif']
    for fname_in, fname_out in zip(fnames_in, fnames_out):
        fname_out = op.join(tempdir, fname_out)
        raw = Raw(fname_in)

        nchan = raw.info['nchan']
        ch_names = raw.info['ch_names']
        meg_channels_idx = [k for k in range(nchan)
                            if ch_names[k][0] == 'M']
        n_channels = 100
        meg_channels_idx = meg_channels_idx[:n_channels]
        start, stop = raw.time_as_index([0, 5])
        data, times = raw[meg_channels_idx, start:(stop + 1)]
        meg_ch_names = [ch_names[k] for k in meg_channels_idx]

        # Set up pick list: MEG + STI 014 - bad channels
        include = ['STI 014']
        include += meg_ch_names
        picks = pick_types(raw.info, meg=True, eeg=False, stim=True,
                           misc=True, ref_meg=True, include=include,
                           exclude='bads')

        # Writing with drop_small_buffer True
        raw.save(fname_out, picks, tmin=0, tmax=4, buffer_size_sec=3,
                 drop_small_buffer=True, overwrite=True)
        raw2 = Raw(fname_out, preload=True)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]
        assert_true(times2.max() <= 3)

        # Writing
        raw.save(fname_out, picks, tmin=0, tmax=5, overwrite=True)

        if fname_in == fif_fname or fname_in == fif_fname + '.gz':
            assert_true(len(raw.info['dig']) == 146)

        raw2 = Raw(fname_out)

        sel = pick_channels(raw2.ch_names, meg_ch_names)
        data2, times2 = raw2[sel, :]

        assert_true(np.allclose(data, data2, 1e-6, 1e-20))
        assert_allclose(times, times2)
        assert_allclose(raw.info['sfreq'], raw2.info['sfreq'], rtol=1e-5)

        # check transformations
        for trans in ['dev_head_t', 'dev_ctf_t', 'ctf_head_t']:
            if raw.info[trans] is None:
                assert_true(raw2.info[trans] is None)
            else:
                assert_array_equal(raw.info[trans]['trans'],
                                   raw2.info[trans]['trans'])

                # check transformation 'from' and 'to'
                if trans.startswith('dev'):
                    from_id = FIFF.FIFFV_COORD_DEVICE
                else:
                    from_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD
                if trans[4:8] == 'head':
                    to_id = FIFF.FIFFV_COORD_HEAD
                else:
                    to_id = FIFF.FIFFV_MNE_COORD_CTF_HEAD
                for raw_ in [raw, raw2]:
                    assert_true(raw_.info[trans]['from'] == from_id)
                    assert_true(raw_.info[trans]['to'] == to_id)

        if fname_in == fif_fname or fname_in == fif_fname + '.gz':
            assert_allclose(raw.info['dig'][0]['r'], raw2.info['dig'][0]['r'])
开发者ID:TalLinzen,项目名称:mne-python,代码行数:93,代码来源:test_raw.py

示例7: range

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
# plot spatial sensitivities of EOG and ECG ICA components
title = 'Spatial patterns of ICA components for ECG+EOG (Magnetometers)'
source_idx = range(15)
ica.plot_topomap([ecg_source_idx, eog_source_idx], ch_type='mag')
plt.suptitle(title, fontsize=12)

###############################################################################
# Show MEG data before and after ICA cleaning.

# We now add the eog artifacts to the ica.exclusion list
ica.exclude += [eog_source_idx]

# Restore sensor space data
raw_ica = ica.pick_sources_raw(raw, include=None)

start_compare, stop_compare = raw.time_as_index([100, 106])

data, times = raw[picks, start_compare:stop_compare]
data_clean, _ = raw_ica[picks, start_compare:stop_compare]

plt.figure()
plt.plot(times, data.T)
plt.xlabel('time (s)')
plt.xlim(100, 106)
plt.ylabel('Raw MEG data (T)')
y0, y1 = plt.ylim()

plt.figure()
plt.plot(times, data_clean.T)
plt.xlabel('time (s)')
plt.xlim(100, 106)
开发者ID:dichaelen,项目名称:mne-python,代码行数:33,代码来源:plot_ica_from_raw.py

示例8: method

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
data_path = sample.data_path('..')
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

snr = 1.0  # use smaller SNR for raw data
lambda2 = 1.0 / snr ** 2
method = "sLORETA"  # use sLORETA method (could also be MNE or dSPM)

# Load data
raw = Raw(fname_raw)
inverse_operator = read_inverse_operator(fname_inv)
label = mne.read_label(fname_label)

start, stop = raw.time_as_index([0, 15])  # read the first 15s of data

# Compute inverse solution
stc = apply_inverse_raw(raw, inverse_operator, lambda2, method, label,
                        start, stop, pick_normal=False)

# Save result in stc files
stc.save('mne_%s_raw_inverse_%s' % (method, label_name))

###############################################################################
# View activation time-series
pl.plot(1e3 * stc.times, stc.data[::100, :].T)
pl.xlabel('time (ms)')
pl.ylabel('%s value' % method)
pl.show()
开发者ID:starzynski,项目名称:mne-python,代码行数:32,代码来源:plot_compute_mne_inverse_raw_in_label.py

示例9: ICA

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
# explained variance.

ica = ICA(n_components=0.90, max_pca_components=100, noise_cov=None,
          random_state=0)

# For maximum rejection performance we will compute the decomposition on
# the entire time range

# decompose sources for raw data, select n_components by explained variance
ica.decompose_raw(raw, start=None, stop=None, picks=picks)
print ica

sources = ica.get_sources_raw(raw)

# setup reasonable time window for inspection
start_plot, stop_plot = raw.time_as_index([100, 103])

# plot components
ica.plot_sources_raw(raw, start=start_plot, stop=stop_plot)

###############################################################################
# Automatically find the ECG component using correlation with ECG signal

# As we don't have an ECG channel we use one that correlates a lot with heart
# beats: 'MEG 1531'. We can directly pass the name to the find_sources method.
# We select the pearson correlation from scipy stats via string label.
# The function is internally modified to be applicable to 2D arrays and,
# hence, returns product-moment correlation scores for each ICA source.

eog_scores = ica.find_sources_raw(raw, target='EOG 061',
                                  score_func='pearsonr')
开发者ID:OliverWS,项目名称:mne-python,代码行数:33,代码来源:plot_eog_artifacts_from_ica.py

示例10: __call__

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]

#.........这里部分代码省略.........

	    logger.error('step 1.2.7')
	    metadata_dump['channel_names'] = "".join(raw.ch_names)
	   
            #STI
            numberOfSTI = 0
            for term in raw.ch_names:
                if term.startswith('STI'):
                        numberOfSTI += 1

            metadata_dump['numberOfSTI'] = numberOfSTI
	
	    #EOG
	    numberOfEOG = 0
	    for term2 in raw.ch_names:
		if term2.startswith('EOG'):
			numberOfEOG += 1

	    metadata_dump['numberOfEOG'] = numberOfEOG

	   #EEG
            numberOfEEG = 0
            for term3 in raw.ch_names:
                if term3.startswith('EEG'):
                        numberOfEEG += 1

            metadata_dump['numberOfEEG'] = numberOfEEG

 	    #MEG
	    numberOfMEG = 0
            for term4 in raw.ch_names:
                if term4.startswith('MEG'):
                        numberOfMEG += 1

            metadata_dump['numberOfMEG'] = numberOfMEG

            # get duration
            #metadata_dump['duration'] = raw.duration

            # get sample duration (sampling interval)
            #metadata_dump['sampling_interval'] = raw.info['sampling_interval']

            # get exported raw information
            #metadata_dump['raw_info'] = raw.metadata.keys()

            # get channel names (attribute added during export)
	    #logger.error('step 1.2.10')
            #metadata_dump['channel_names'] = raw.ch_names
            #logger.error(raw.ch_names)
	    #metadata_dump['channel_names'] = raw_ts.ch_names[:3]

            # get The width of the transition band of the highpass filter
            metadata_dump['highpass'] = raw.info['highpass']
	
            # get The width of the transition band of the lowpass filter
            metadata_dump['lowpass'] = raw.info['lowpass']

            logger.error('step 2')
            ###############################################################################

            #Plot graph 
            want_meg = True
            want_eeg = False
            want_stim = False
            include = []
            exclude = raw.info['bads']
            logger.error('step 2.1')

            picks = mne.fiff.pick_types(raw.info, meg=want_meg, eeg=want_eeg,stim=want_stim, include=include, exclude=exclude)
            some_picks = picks[:5]  # take 5 first
            start, stop = raw.time_as_index([0, 15])  # read the first 15s of data
            data, times = raw[some_picks, start:(stop + 1)]
            logger.error('step 2.2')

            import matplotlib.pyplot as pl
            pl.close('all')
            pl.plot(times, data.T)
            pl.xlabel('time (s)')
            pl.ylabel('MEG data (T)')
            logger.error('step 2.3')

            #outputextension = "png"
            #tf = tempfile.TemporaryFile(delete=False)
            #outputfilename = tf.name

            pl.savefig('/opt/mytardis/data/staging/test1.png')
            #tf.close()
            logger.error('step 2.4')

            previewImage64 = self.base64_encode_file('/opt/mytardis/data/staging/test1.png')
            #os.remove(outputfilename)
            logger.error('step 2.5')
            if previewImage64:
                metadata_dump['previewImage'] = previewImage64               
  
            self.saveMetadata(instance, schema, metadata_dump)

        except Exception, e:
            logger.debug(e)
            return None
开发者ID:cyruskeong,项目名称:mytardis-mne-filter,代码行数:104,代码来源:mneimage.py

示例11: ICA

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
# Instead of the actual number of components here we pass a float value
# between 0 and 1 to select n_components by a percentage of
# explained variance. Also we decide to use 64 PCA components before mixing
# back to sensor space. These include the PCA components supplied to ICA plus
# additional PCA components up to rank 64 of the MEG data.
# This allows to control the trade-off between denoising and preserving signal.

ica = ICA(n_components=0.90, n_pca_components=64, max_pca_components=100,
          noise_cov=None, random_state=0)
print ica

# 1 minute exposure should be sufficient for artifact detection.
# However, rejection performance may significantly improve when using
# the entire data range
start, stop = raw.time_as_index([100, 160])

# decompose sources for raw data
ica.decompose_raw(raw, start=start, stop=stop, picks=picks)
print ica

sources = ica.get_sources_raw(raw, start=start, stop=stop)

# setup reasonable time window for inspection
start_plot, stop_plot = raw.time_as_index([100, 103])

# plot components
ica.plot_sources_raw(raw, start=start_plot, stop=stop_plot)

###############################################################################
# Automatically find the ECG component using correlation with ECG signal.
开发者ID:OliverWS,项目名称:mne-python,代码行数:32,代码来源:plot_ica_from_raw.py

示例12: Raw

# 需要导入模块: from mne.fiff import Raw [as 别名]
# 或者: from mne.fiff.Raw import time_as_index [as 别名]
from mne.fiff import Raw
from mne.datasets import sample

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

###############################################################################
# get raw data
raw = Raw(raw_fname)

# set picks
picks = mne.fiff.pick_types(raw.info, meg=True, eeg=False, eog=False,
                            stim=False, exclude='bads')

# pick times relative to the onset of the MEG measurement.
start, stop = raw.time_as_index([100, 115], use_first_samp=False)

# export to nitime using a copy of the data
raw_ts = raw.to_nitime(start=start, stop=stop, picks=picks, copy=True)

###############################################################################
# explore some nitime timeseries features

# get start
print raw_ts.t0

# get duration
print raw_ts.duration

# get sample duration (sampling interval)
print raw_ts.sampling_interval
开发者ID:dichaelen,项目名称:mne-python,代码行数:33,代码来源:plot_raw_to_nitime.py


注:本文中的mne.fiff.Raw.time_as_index方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。