Beispiel #1
0
def display_tseries(tseries, vox_idx='all', fig=None, show_mean=True):
    """
    Display the voxel time-series of all voxels selected with vox_idx,
    along with the mean and sem.
    Currently, voxels must be along the zeroth dimension of TimeSeries object tseries
    """
    if fig is None:
        fig = plt.figure()

    TR = tseries.sampling_interval
    if vox_idx == 'all':
        vox_tseries = tseries
    else:
        vox_tseries = ts.TimeSeries(tseries.data[vox_idx],
                                    sampling_interval=TR)

    fig = viz.plot_tseries(vox_tseries, fig)
    if show_mean:
        fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data, 0),
                                             sampling_interval=TR),
                               yerror=ts.TimeSeries(stats.sem(
                                   vox_tseries.data, 0),
                                                    sampling_interval=TR),
                               fig=fig,
                               error_alpha=0.3,
                               linewidth=4,
                               color='r')
    return fig
Beispiel #2
0
def test_SeedCoherenceAnalyzer():
    """ Test the SeedCoherenceAnalyzer """
    methods = (None,
           {"this_method": 'welch', "NFFT": 256},
           {"this_method": 'multi_taper_csd'},
           {"this_method": 'periodogram_csd', "NFFT": 256})

    Fs = np.pi
    t = np.arange(256)
    seed1 = np.sin(10 * t) + np.random.rand(t.shape[-1])
    seed2 = np.sin(10 * t) + np.random.rand(t.shape[-1])
    target = np.sin(10 * t) + np.random.rand(t.shape[-1])
    T = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs)
    T_seed1 = ts.TimeSeries(seed1, sampling_rate=Fs)
    T_seed2 = ts.TimeSeries(np.vstack([seed1, seed2]), sampling_rate=Fs)
    T_target = ts.TimeSeries(np.vstack([seed1, target]), sampling_rate=Fs)
    for this_method in methods:
        if this_method is None or this_method['this_method'] == 'welch':
            C1 = nta.CoherenceAnalyzer(T, method=this_method)
            C2 = nta.SeedCoherenceAnalyzer(T_seed1, T_target,
                                           method=this_method)
            C3 = nta.SeedCoherenceAnalyzer(T_seed2, T_target,
                                           method=this_method)

            npt.assert_almost_equal(C1.coherence[0, 1], C2.coherence[1])
            npt.assert_almost_equal(C2.coherence[1], C3.coherence[0, 1])
            npt.assert_almost_equal(C1.phase[0, 1], C2.relative_phases[1])
            npt.assert_almost_equal(C1.delay[0, 1], C2.delay[1])

        else:
            with pytest.raises(ValueError) as e_info:
                nta.SeedCoherenceAnalyzer(T_seed1, T_target, this_method)
Beispiel #3
0
def test_FilterAnalyzer():
    """Testing the FilterAnalyzer """
    t = np.arange(np.pi / 100, 10 * np.pi, np.pi / 100)
    fast = np.sin(50 * t) + 10
    slow = np.sin(10 * t) - 20

    fast_mean = np.mean(fast)
    slow_mean = np.mean(slow)

    fast_ts = ts.TimeSeries(data=fast, sampling_rate=np.pi)
    slow_ts = ts.TimeSeries(data=slow, sampling_rate=np.pi)

    #Make sure that the DC is preserved
    f_slow = nta.FilterAnalyzer(slow_ts, ub=0.6)
    f_fast = nta.FilterAnalyzer(fast_ts, lb=0.6)

    npt.assert_almost_equal(f_slow.filtered_fourier.data.mean(),
                            slow_mean,
                            decimal=2)

    npt.assert_almost_equal(f_slow.filtered_boxcar.data.mean(),
                            slow_mean,
                            decimal=2)

    npt.assert_almost_equal(f_slow.fir.data.mean(), slow_mean)

    npt.assert_almost_equal(f_slow.iir.data.mean(), slow_mean)

    npt.assert_almost_equal(f_fast.filtered_fourier.data.mean(), 10)

    npt.assert_almost_equal(f_fast.filtered_boxcar.data.mean(), 10, decimal=2)

    npt.assert_almost_equal(f_fast.fir.data.mean(), 10)

    npt.assert_almost_equal(f_fast.iir.data.mean(), 10)

    #Check that things work with a two-channel time-series:
    T2 = ts.TimeSeries(np.vstack([fast, slow]), sampling_rate=np.pi)
    f_both = nta.FilterAnalyzer(T2, ub=1.0, lb=0.1)
    #These are rather basic tests:
    npt.assert_equal(f_both.fir.shape, T2.shape)
    npt.assert_equal(f_both.iir.shape, T2.shape)
    npt.assert_equal(f_both.filtered_boxcar.shape, T2.shape)
    npt.assert_equal(f_both.filtered_fourier.shape, T2.shape)

    # Check that t0 is propagated to the filtered time-series
    t0 = np.pi
    T3 = ts.TimeSeries(np.vstack([fast, slow]), sampling_rate=np.pi, t0=t0)
    f_both = nta.FilterAnalyzer(T3, ub=1.0, lb=0.1)
    # These are rather basic tests:
    npt.assert_equal(f_both.fir.t0, ts.TimeArray(t0, time_unit=T3.time_unit))
    npt.assert_equal(f_both.iir.t0, ts.TimeArray(t0, time_unit=T3.time_unit))
    npt.assert_equal(f_both.filtered_boxcar.t0,
                     ts.TimeArray(t0, time_unit=T3.time_unit))
    npt.assert_equal(f_both.filtered_fourier.t0,
                     ts.TimeArray(t0, time_unit=T3.time_unit))
Beispiel #4
0
def test_masked_array_timeseries():
    # make sure masked arrays passed in stay as masked arrays
    masked = np.ma.masked_invalid([0,np.nan,2])
    t = ts.TimeSeries(masked, sampling_interval=1)
    npt.assert_equal(t.data.mask, [False, True, False])

    # make sure regular arrays passed don't become masked
    notmasked = np.array([0,np.nan,2])
    t2 = ts.TimeSeries(notmasked, sampling_interval=1)
    npt.assert_raises(AttributeError, t2.data.__getattribute__,'mask')
Beispiel #5
0
def test_SpectralAnalyzer():

    Fs = np.pi
    t = np.arange(1024)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])

    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)

    C = nta.SpectralAnalyzer(T)

    f, c = C.psd

    npt.assert_equal(f.shape, (33, ))  # This is the setting for this analyzer
    # (window-length of 64)
    npt.assert_equal(c.shape, (2, 33))

    f, c = C.cpsd
    npt.assert_equal(f.shape, (33, ))  # This is the setting for this analyzer
    # (window-length of 64)
    npt.assert_equal(c.shape, (2, 2, 33))

    f, c = C.cpsd
    npt.assert_equal(f.shape, (33, ))  # This is the setting for this analyzer
    # (window-length of 64)
    npt.assert_equal(c.shape, (2, 2, 33))

    f, c = C.spectrum_fourier

    npt.assert_equal(f.shape, (t.shape[0] / 2 + 1, ))
    npt.assert_equal(c.shape, (2, t.shape[0] / 2 + 1))

    f, c = C.spectrum_multi_taper

    npt.assert_equal(f.shape, (t.shape[0] / 2 + 1, ))
    npt.assert_equal(c.shape, (2, t.shape[0] / 2 + 1))

    f, c = C.periodogram

    npt.assert_equal(f.shape, (t.shape[0] / 2 + 1, ))
    npt.assert_equal(c.shape, (2, t.shape[0] / 2 + 1))

    # Test for data with only one channel
    T = ts.TimeSeries(x, sampling_rate=Fs)
    C = nta.SpectralAnalyzer(T)
    f, c = C.psd
    npt.assert_equal(f.shape, (33, ))  # Same length for the frequencies
    npt.assert_equal(c.shape, (33, ))  # 1-d spectrum for the single channels

    f, c = C.spectrum_multi_taper
    npt.assert_equal(f.shape,
                     (t.shape[0] / 2 + 1, ))  # Same length for the frequencies
    npt.assert_equal(
        c.shape,
        (t.shape[0] / 2 + 1, ))  # 1-d spectrum for the single channels
Beispiel #6
0
def test_NormalizationAnalyzer():
    """Testing the NormalizationAnalyzer """

    t1 = ts.TimeSeries(data=[[99, 100, 101], [99, 100, 101]], sampling_interval=1.)
    t2 = ts.TimeSeries(data=[[-1, 0, 1], [-1, 0, 1]], sampling_interval=1.)

    N1 = nta.NormalizationAnalyzer(t1)
    npt.assert_almost_equal(N1.percent_change[0], t2[0])

    t3 = ts.TimeSeries(data=[[100, 102], [1, 3]], sampling_interval=1.)
    t4 = ts.TimeSeries(data=[[-1, 1], [-1, 1]], sampling_interval=1.)

    N2 = nta.NormalizationAnalyzer(t3)
    npt.assert_almost_equal(N2.z_score[0], t4[0])
Beispiel #7
0
    def xcorr(self):
        """The cross-correlation between every pairwise combination time-series
        in the object. Uses np.correlation('full').

        Returns
        -------

        TimeSeries: the time-dependent cross-correlation, with zero-lag
        at time=0

        """
        tseries_length = self.input.data.shape[0]
        t_points = self.input.data.shape[-1]
        xcorr = np.zeros((tseries_length, tseries_length, t_points * 2 - 1))
        data = self.input.data
        for i in xrange(tseries_length):
            data_i = data[i]
            for j in xrange(i, tseries_length):
                xcorr[i, j] = np.correlate(data_i, data[j], mode='full')

        idx = tril_indices(tseries_length, -1)
        xcorr[idx[0], idx[1], ...] = xcorr[idx[1], idx[0], ...]

        return ts.TimeSeries(xcorr,
                             sampling_interval=self.input.sampling_interval,
                             t0=-self.input.sampling_interval * t_points)
Beispiel #8
0
def test_HilbertAnalyzer():
    """Testing the HilbertAnalyzer (analytic signal)"""
    pi = np.pi
    Fs = np.pi
    t = np.arange(0, 2 * pi, pi / 256)

    a0 = np.sin(t)
    a1 = np.cos(t)
    a2 = np.sin(2 * t)
    a3 = np.cos(2 * t)

    T = ts.TimeSeries(data=np.vstack([a0, a1, a2, a3]), sampling_rate=Fs)

    H = nta.HilbertAnalyzer(T)

    h_abs = H.amplitude.data
    h_angle = H.phase.data
    h_real = H.real.data
    #The real part should be equal to the original signals:
    npt.assert_almost_equal(h_real, T.data)
    #The absolute value should be one everywhere, for this input:
    npt.assert_almost_equal(h_abs, np.ones(T.data.shape))
    #For the 'slow' sine - the phase should go from -pi/2 to pi/2 in the first
    #256 bins:
    npt.assert_almost_equal(h_angle[0, :256],
                            np.arange(-pi / 2, pi / 2, pi / 256))
    #For the 'slow' cosine - the phase should go from 0 to pi in the same
    #interval:
    npt.assert_almost_equal(h_angle[1, :256], np.arange(0, pi, pi / 256))
    #The 'fast' sine should make this phase transition in half the time:
    npt.assert_almost_equal(h_angle[2, :128],
                            np.arange(-pi / 2, pi / 2, pi / 128))
    #Ditto for the 'fast' cosine:
    npt.assert_almost_equal(h_angle[3, :128], np.arange(0, pi, pi / 128))
Beispiel #9
0
def test_SeedCoherenceAnalyzer_same_Fs():
    """

    Providing two time-series with different sampling rates throws an error

    """

    Fs1 = np.pi
    Fs2 = 2 * np.pi
    t = np.arange(256)

    T1 = ts.TimeSeries(np.random.rand(t.shape[-1]), sampling_rate=Fs1)

    T2 = ts.TimeSeries(np.random.rand(t.shape[-1]), sampling_rate=Fs2)

    npt.assert_raises(ValueError, nta.SeedCoherenceAnalyzer, T1, T2)
Beispiel #10
0
def test_GrangerAnalyzer():
    """
    Testing the GrangerAnalyzer class, which simplifies calculations of related
    quantities
    """

    # Start by generating some MAR processes (according to Ding and Bressler),
    a1 = np.array([[0.9, 0], [0.16, 0.8]])

    a2 = np.array([[-0.5, 0], [-0.2, -0.5]])

    am = np.array([-a1, -a2])

    x_var = 1
    y_var = 0.7
    xy_cov = 0.4
    cov = np.array([[x_var, xy_cov], [xy_cov, y_var]])

    L = 1024
    z, nz = utils.generate_mar(am, cov, L)

    # Move on to testing the Analyzer object itself:
    ts1 = ts.TimeSeries(data=z, sampling_rate=np.pi)
    g1 = gc.GrangerAnalyzer(ts1)

    # Check that things have the right shapes:
    npt.assert_equal(g1.frequencies.shape[-1], g1._n_freqs // 2 + 1)
    npt.assert_equal(g1.causality_xy[0, 1].shape, g1.causality_yx[0, 1].shape)

    # Test inputting ij:
    g2 = gc.GrangerAnalyzer(ts1, ij=[(0, 1), (1, 0)])

    # x => y for one is like y => x for the other:
    npt.assert_almost_equal(g1.causality_yx[1, 0], g2.causality_xy[0, 1])
Beispiel #11
0
def analyze_average(data,
                    onsets,
                    sampling_interval,
                    len_et=12,
                    offset=-2,
                    y_label="Bold signal",
                    time_unit='s'):

    # Times series initialization
    ts = timeseries.TimeSeries(data,
                               sampling_interval=sampling_interval,
                               time_unit=time_unit)

    # Events initialization
    events = timeseries.Events(onsets, time_unit=time_unit)

    # Timeseries analysis
    #len_et = numbre of TR what you want to see
    #offset = number of offset including in len_et
    analyzer = analysis.EventRelatedAnalyzer(ts,
                                             events,
                                             len_et=len_et,
                                             offset=offset)

    return analyzer
Beispiel #12
0
    def xcorr_norm(self):
        """The cross-correlation between every pairwise combination time-series
        in the object, where the zero lag correlation is normalized to be equal
        to the correlation coefficient between the time-series

        Returns
        -------

        TimeSeries: A TimeSeries object
            the time-dependent cross-correlation, with zero-lag at time=0

        """

        tseries_length = self.input.data.shape[0]
        t_points = self.input.data.shape[-1]
        xcorr = np.zeros((tseries_length, tseries_length, t_points * 2 - 1))
        data = self.input.data
        for i in xrange(tseries_length):
            data_i = data[i]
            for j in xrange(i, tseries_length):
                xcorr[i, j] = np.correlate(data_i, data[j], mode='full')
                xcorr[i, j] /= (xcorr[i, j, t_points])
                xcorr[i, j] *= self.corrcoef[i, j]

        idx = tril_indices(tseries_length, -1)
        xcorr[idx[0], idx[1], ...] = xcorr[idx[1], idx[0], ...]

        return ts.TimeSeries(xcorr,
                             sampling_interval=self.input.sampling_interval,
                             t0=-self.input.sampling_interval * t_points)
Beispiel #13
0
    def eta(self):
        """The event-triggered average activity.
        """
        #Make a list for the output
        h = [0] * self._len_h

        if self._is_ts:
            # Loop over channels
            for i in xrange(self._len_h):
                data = self.data[i]
                u = np.unique(self.events[i])
                event_types = u[np.unique(self.events[i]) != 0]
                h[i] = np.empty((event_types.shape[0], self.len_et),
                                dtype=complex)

                # This offset is used to pull the event indices below, but we
                # have to broadcast it so the shape of the resulting idx+offset
                # operation below gives us the (nevents, len_et) array we want,
                # per channel.
                offset = np.arange(self.offset,
                                   self.offset + self.len_et)[:, np.newaxis]
                # Loop over event types
                for e_idx in xrange(event_types.shape[0]):
                    idx = np.where(self.events[i] == event_types[e_idx])[0]
                    event_trig = data[idx + offset]
                    #Correct baseline by removing the first point in the series
                    #for each channel:
                    if self._correct_baseline:
                        event_trig -= event_trig[0]

                    h[i][e_idx] = np.mean(event_trig, -1)

        #In case the input events are an Events:
        else:
            #Get the indices necessary for extraction of the eta:
            add_offset = np.arange(self.offset,
                                   self.offset + self.len_et)[:, np.newaxis]

            idx = (self.events.time / self.sampling_interval).astype(int)

            #Make a list for the output
            h = [0] * self._len_h

            # Loop over channels
            for i in xrange(self._len_h):
                #If this is a list with one element:
                if self._len_h == 1:
                    event_trig = self.data[0][idx + add_offset]
                #Otherwise, you need to index straight into the underlying data
                #array:
                else:
                    event_trig = self.data.data[i][idx + add_offset]

                h[i] = np.mean(event_trig, -1)

        h = np.array(h).squeeze()
        return ts.TimeSeries(data=h,
                             sampling_interval=self.sampling_interval,
                             t0=self.offset * self.sampling_interval,
                             time_unit=self.time_unit)
Beispiel #14
0
    def filtered_boxcar(self):
        """
        Filter the time-series by a boxcar filter.

        The low pass filter is implemented by convolving with a boxcar function
        of the right length and amplitude and the high-pass filter is
        implemented by subtracting a low-pass version (as above) from the
        signal
        """

        if self.ub is not None:
            ub = self.ub / self.sampling_rate
        else:
            ub = 1.0

        lb = self.lb / self.sampling_rate

        data_out = tsa.boxcar_filter(np.copy(self.data),
                                     lb=lb,
                                     ub=ub,
                                     n_iterations=self._boxcar_iterations)

        return ts.TimeSeries(data=data_out,
                             sampling_rate=self.sampling_rate,
                             time_unit=self.time_unit)
Beispiel #15
0
    def analytic(self):
        """The natural output for this analyzer is the analytic signal """
        data = self.input.data
        sampling_rate = self.input.sampling_rate
        hilbert = signal.hilbert

        return ts.TimeSeries(data=hilbert(data), sampling_rate=sampling_rate)
Beispiel #16
0
def line_broadening(ts, width):
    """
    Apply line-broadening to a time-series

    Parameters
    ----------
    ts : a nitime.TimeSeries class instance

    width : float
        The exponential decay time-constant (in seconds)

    Returns
    -------
    A nitime.TimeSeries class instance with windowed data

    Notes
    -----

    For details, see page 92 of Keeler2005_.

    .. [Keeler2005] Keeler, J (2005). Understanding NMR spectroscopy, second
       edition. Wiley (West Sussex, UK).

    """
    # We'll need to broadcast into this many dims:
    n_dims = len(ts.shape)
    # We use the information in the TimeSeries.time attribute to get it:
    win = np.exp(-width * ts.time / np.float(ts.time._conversion_factor))

    new_data = ts.data * win
    return nts.TimeSeries(new_data, sampling_rate=ts.sampling_rate)
Beispiel #17
0
def test_SparseCoherenceAnalyzer():
    Fs = np.pi
    t = np.arange(256)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])
    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)
    C1 = nta.SparseCoherenceAnalyzer(T, ij=((0, 1), (1, 0)))
    C2 = nta.CoherenceAnalyzer(T)

    # Coherence symmetry:
    npt.assert_almost_equal(np.abs(C1.coherence[0, 1]),
                            np.abs(C1.coherence[1, 0]))
    npt.assert_almost_equal(np.abs(C1.coherency[0, 1]),
                            np.abs(C1.coherency[1, 0]))

    # Make sure you get the same answers as you would from the standard
    # CoherenceAnalyzer:

    npt.assert_almost_equal(C2.coherence[0, 1], C1.coherence[0, 1])
    # This is the PSD (for the first time-series in the object):
    npt.assert_almost_equal(C2.spectrum[0, 0], C1.spectrum[0])
    # And the second (for good measure):
    npt.assert_almost_equal(C2.spectrum[1, 1], C1.spectrum[1])

    # The relative phases should be equal
    npt.assert_almost_equal(C2.phase[0, 1], C1.relative_phases[0, 1])
    # But not the absolute phases (which have the same shape):
    npt.assert_equal(C1.phases[0].shape, C1.relative_phases[0, 1].shape)

    # The delay is equal:
    npt.assert_almost_equal(C2.delay[0, 1], C1.delay[0, 1])
    # Make sure that you would get an error if you provided a method other than
    # 'welch':
    with pytest.raises(ValueError) as e_info:
        nta.SparseCoherenceAnalyzer(T, method=dict(this_method='foo'))
Beispiel #18
0
    def ets(self):
        """The event-triggered standard error of the mean """
        #Make a list for the output
        h = [0] * self._len_h

        for i in xrange(self._len_h):
            data = self.data[i]
            u = np.unique(self.events[i])
            event_types = u[np.unique(self.events[i]) != 0]
            h[i] = np.empty((event_types.shape[0], self.len_et), dtype=complex)
            for e_idx in xrange(event_types.shape[0]):
                idx = np.where(self.events[i] == event_types[e_idx])
                idx_w_len = np.array([
                    idx[0] + count + self.offset
                    for count in range(self.len_et)
                ])
                event_trig = data[idx_w_len]
                #Correct baseline by removing the first point in the series for
                #each channel:
                if self._correct_baseline:
                    event_trig -= event_trig[0]

                h[i][e_idx] = stats.sem(event_trig, axis=-1)

        h = np.array(h).squeeze()

        return ts.TimeSeries(data=h,
                             sampling_interval=self.sampling_interval,
                             t0=self.offset * self.sampling_interval,
                             time_unit=self.time_unit)
Beispiel #19
0
def get_timeseries_from_file(bold, mask, TR, **kwargs):
    """
    Given a bold file and roi mask, return a nitime TimeSeries object
    """
    masker = NiftiMasker(mask_img=mask, t_r=TR, **kwargs)
    return masker, ts.TimeSeries(data=masker.fit_transform(bold).T,
                                 sampling_interval=TR)
Beispiel #20
0
    def analytic(self):
        """The natural output for this analyzer is the analytic signal"""
        data = self.input.data
        sampling_rate = self.input.sampling_rate

        a_signal =\
    ts.TimeSeries(data=np.zeros(self.freqs.shape + data.shape,
                                dtype='D'), sampling_rate=sampling_rate)
        if self.freqs.ndim == 0:
            w = self.wavelet(self.freqs,
                             self.sd,
                             sampling_rate=sampling_rate,
                             ns=5,
                             normed='area')

            # nd = (w.shape[0] - 1) / 2
            a_signal.data[...] = (
                np.convolve(data, np.real(w), mode='same') +
                1j * np.convolve(data, np.imag(w), mode='same'))
        else:
            for i, (f, sd) in enumerate(zip(self.freqs, self.sd)):
                w = self.wavelet(f,
                                 sd,
                                 sampling_rate=sampling_rate,
                                 ns=5,
                                 normed='area')

                # nd = (w.shape[0] - 1) / 2
                a_signal.data[i, ...] = (
                    np.convolve(data, np.real(w), mode='same') +
                    1j * np.convolve(data, np.imag(w), mode='same'))

        return a_signal
Beispiel #21
0
    def filtered_fourier(self):
        """

        Filter the time-series by passing it to the Fourier domain and null
        out the frequency bands outside of the range [lb,ub]

        """

        freqs = tsu.get_freqs(self.sampling_rate, self.data.shape[-1])

        if self.ub is None:
            self.ub = freqs[-1]

        power = fftpack.fft(self.data)
        idx_0 = np.hstack(
            [np.where(freqs < self.lb)[0],
             np.where(freqs > self.ub)[0]])

        #Make sure that you keep the DC component:
        keep_dc = np.copy(power[..., 0])
        power[..., idx_0] = 0
        power[..., -1 * idx_0] = 0  # Take care of the negative frequencies
        power[..., 0] = keep_dc  # And put the DC back in when you're done:

        data_out = fftpack.ifft(power)

        data_out = np.real(data_out)  # In order to make sure that you are not
        # left with float-precision residual
        # complex parts

        return ts.TimeSeries(data=data_out,
                             sampling_rate=self.sampling_rate,
                             time_unit=self.time_unit)
Beispiel #22
0
def convert(sid, period, attr='train'):
    subject_id = sid
    # have to change the data_folder here to make it run.
    data_folder = 'data'
    if attr == 'train':
        filename = os.path.join(data_folder,
                                'train/{:d}.mat'.format(subject_id))
    elif attr == 'test':
        filename = os.path.join(data_folder,
                                'test/{:d}.mat'.format(subject_id))
    else:
        sys.exit('choose attribution to be either test or train')
    data_set = load_bbci_data(filename, 0, period)
    #print (type(train_set.X),train_set.X.shape)
    #print (train_set.y,len(train_set.y))
    tr, elc, ts_n = data_set.X.shape

    target_dir = 'converted_data/' + attr + '/' + str(subject_id)
    if not os.path.exists(target_dir):
        os.makedirs(target_dir)

    slices_ = []
    labels_ = []
    for t in range(tr):
        #print (train_set.X[t,:,:])
        #print (data_set.X[t,:,:].shape)
        time_series = ts.TimeSeries(data_set.X[t, :, :],
                                    sampling_rate=250.0,
                                    time_unit='ms')

        NW = 3.5
        bw = NW * 2.0 * time_series.sampling_rate / float(
            time_series.shape[-1])

        #print ('length of time series',time_series.shape[-1])
        #print ('sampling rate',time_series.sampling_rate)
        #print ('bandwidth of tapers',bw)
        C = nta.coherence.MTCoherenceAnalyzer(time_series, bandwidth=bw)

        #print (C.df)

        C.df = int(
            C.df
        )  #It looks like df is used as index, but it does allow df to be float in nitime (raising error). This trick semes to work.

        #print ('done and now printing frequencies')
        freq = C.frequencies
        coh_val = C.coherence
        #print (coh_val.shape)
        #print (freq)

        coh_slice, label = split_power(freq, coh_val, t, sid, attr,
                                       data_set.y[t], period)
        slices_.append(coh_slice)
        labels_.append(data_set.y[t])
    slices_ = np.array(slices_)
    labels_ = np.array(labels_)
    print('slices_', slices_.shape, 'labels', labels_.shape)
    return slices_, labels_
Beispiel #23
0
def test_SNRAnalyzer():
    Fs = np.pi
    t = np.arange(1024)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])

    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)

    MT = nta.MTCoherenceAnalyzer(T)
    SNR = nta.SNRAnalyzer(T)
    MT_signal = nta.SpectralAnalyzer(
        ts.TimeSeries(np.mean(T.data, 0), sampling_rate=Fs))

    npt.assert_equal(SNR.mt_frequencies, MT.frequencies)
    npt.assert_equal(SNR.signal, np.mean(T.data, 0))
    f, c = MT_signal.spectrum_multi_taper
    npt.assert_equal(SNR.mt_signal_psd, c)
Beispiel #24
0
def test_index_at_20101206():
    """Test for incorrect handling of negative t0 for time.index_at

    https://github.com/nipy/nitime/issues#issue/35

    bug reported by Jonathan Taylor on 2010-12-06
    """
    A = np.random.standard_normal(40)
    #negative t0
    TS_A = ts.TimeSeries(A, t0=-20, sampling_interval=2)
    npt.assert_equal(TS_A.time.index_at(TS_A.time), np.arange(40))
    #positive t0
    TS_A = ts.TimeSeries(A, t0=15, sampling_interval=2)
    npt.assert_equal(TS_A.time.index_at(TS_A.time), np.arange(40))
    #no t0
    TS_A = ts.TimeSeries(A, sampling_interval=2)
    npt.assert_equal(TS_A.time.index_at(TS_A.time), np.arange(40))
Beispiel #25
0
def _tseries_from_nifti_helper(coords, data, TR, filter, normalize, average):
    """

    Helper function for the function time_series_from_nifti, which does the
    core operations of pulling out data from a data array given coords and then
    normalizing and averaging if needed

    """
    if coords is not None:
        out_data = np.asarray(data[coords[0], coords[1], coords[2]])
    else:
        out_data = data

    tseries = ts.TimeSeries(out_data, sampling_interval=TR)

    if filter is not None:
        if filter['method'] not in ('boxcar', 'fourier', 'fir', 'iir'):
            e_s = "Filter method %s is not recognized" % filter['method']
            raise ValueError(e_s)
        else:
            #Construct the key-word arguments to FilterAnalyzer:
            kwargs = dict(lb=filter.get('lb', 0),
                          ub=filter.get('ub', None),
                          boxcar_iterations=filter.get('boxcar_iterations', 2),
                          filt_order=filter.get('filt_order', 64),
                          gpass=filter.get('gpass', 1),
                          gstop=filter.get('gstop', 60),
                          iir_ftype=filter.get('iir_ftype', 'ellip'),
                          fir_win=filter.get('fir_win', 'hamming'))

            F = tsa.FilterAnalyzer(tseries, **kwargs)

        if filter['method'] == 'boxcar':
            tseries = F.filtered_boxcar
        elif filter['method'] == 'fourier':
            tseries = F.filtered_fourier
        elif filter['method'] == 'fir':
            tseries = F.fir
        elif filter['method'] == 'iir':
            tseries = F.iir

    if normalize == 'percent':
        tseries = tsa.NormalizationAnalyzer(tseries).percent_change
    elif normalize == 'zscore':
        tseries = tsa.NormalizationAnalyzer(tseries).z_score

    if average:
        if coords is None:
            tseries.data = np.mean(
                np.reshape(
                    tseries.data,
                    (np.array(tseries.shape[:-1]).prod(), tseries.shape[-1])),
                0)
        else:
            tseries.data = np.mean(tseries.data, 0)

    return tseries
Beispiel #26
0
def ts_glm(pupilts,
           con_onsets,
           incon_onsets,
           neut_onsets,
           blinks,
           sampling_rate=30.):
    """
    Currently runs the following contrasts:
        Incongruent: [0,1,0,0,0]
        Congruent:   [0,0,1,0,0]
        Neutral:     [0,0,0,1,0]  
        Incon-Neut:  [0,1,0,-1,0]
        Con-Neut:    [0,0,1,-1,0]
        Incon-Con:   [0,1,-1,0,0]
    """
    signal_filt = ts.TimeSeries(pupilts, sampling_rate=sampling_rate)
    con_ts = get_event_ts(pupilts, con_onsets)
    incon_ts = get_event_ts(pupilts, incon_onsets)
    neut_ts = get_event_ts(pupilts, neut_onsets)
    kernel_end_sec = 3.
    kernel_length = kernel_end_sec / (1 / sampling_rate)
    kernel_x = np.linspace(0, kernel_end_sec, int(kernel_length))
    con_reg, con_td_reg = pupil_utils.regressor_tempderiv(con_ts,
                                                          kernel_x,
                                                          s1=1000.,
                                                          tmax=1.30)
    incon_reg, incon_td_reg = pupil_utils.regressor_tempderiv(incon_ts,
                                                              kernel_x,
                                                              s1=1000.,
                                                              tmax=1.30)
    neut_reg, neut_td_reg = pupil_utils.regressor_tempderiv(neut_ts,
                                                            kernel_x,
                                                            s1=1000.,
                                                            tmax=1.30)
    #kernel = pupil_utils.pupil_irf(kernel_x, s1=1000., tmax=1.30)
    #plot_event(signal_filt, con_ts, incon_ts, neut_ts, kernel, pupil_fname)
    intercept = np.ones_like(signal_filt.data)
    X = np.array(
        np.vstack((intercept, incon_reg, con_reg, neut_reg, blinks.values)).T)
    Y = np.atleast_2d(signal_filt).T
    model = ARModel(X, rho=1.).fit(Y)
    tIncon = float(model.Tcontrast([0, 1, 0, 0, 0]).t)
    tCon = float(model.Tcontrast([0, 0, 1, 0, 0]).t)
    tNeut = float(model.Tcontrast([0, 0, 0, 1, 0]).t)
    tIncon_Neut = float(model.Tcontrast([0, 1, 0, -1, 0]).t)
    tCon_Neut = float(model.Tcontrast([0, 0, 1, -1, 0]).t)
    tIncon_Con = float(model.Tcontrast([0, 1, -1, 0, 0]).t)
    resultdict = {
        'Incon_t': tIncon,
        'Con_t': tCon,
        'Neut_t': tNeut,
        'Incon_Neut_t': tIncon_Neut,
        'Con_Neut_t': tCon_Neut,
        'Incon_Con_t': tIncon_Con
    }
    return resultdict
Beispiel #27
0
def display_vox(tseries, vox_idx, fig=None):
    """
    Display the voxel time-series
    """
    if fig is None:
        fig = plt.figure()

    vox_tseries = ts.TimeSeries(tseries.data[vox_idx], sampling_interval=TR)

    fig = viz.plot_tseries(vox_tseries, fig)
    fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data, 0),
                                         sampling_interval=TR),
                           yerror=ts.TimeSeries(stats.sem(vox_tseries.data, 0),
                                                sampling_interval=TR),
                           fig=fig,
                           error_alpha=0.3,
                           ylabel='% signal change',
                           linewidth=4,
                           color='r')
    return fig
Beispiel #28
0
def test_CorrelationAnalyzer():

    Fs = np.pi
    t = np.arange(1024)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])

    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)

    C = nta.CorrelationAnalyzer(T)

    # Test the symmetry: correlation(x,y)==correlation(y,x)
    npt.assert_equal(C.corrcoef[0, 1], C.corrcoef[1, 0])
    # Test the self-sameness: correlation(x,x)==1
    npt.assert_equal(C.corrcoef[0, 0], 1)
    npt.assert_equal(C.corrcoef[1, 1], 1)

    # Test the cross-correlation:
    # First the symmetry:
    npt.assert_array_almost_equal(C.xcorr.data[0, 1], C.xcorr.data[1, 0])

    # Test the normalized cross-correlation
    # The cross-correlation should be equal to the correlation at time-lag 0
    npt.assert_equal(C.xcorr_norm.data[0, 1, C.xcorr_norm.time == 0],
                     C.corrcoef[0, 1])

    # And the auto-correlation should be equal to 1 at 0 time-lag:
    npt.assert_equal(C.xcorr_norm.data[0, 0, C.xcorr_norm.time == 0], 1)

    # Does it depend on having an even number of time-points?
    # make another time-series with an odd number of items:
    t = np.arange(1023)
    x = np.sin(10 * t) + np.random.rand(t.shape[-1])
    y = np.sin(10 * t) + np.random.rand(t.shape[-1])

    T = ts.TimeSeries(np.vstack([x, y]), sampling_rate=Fs)

    C = nta.CorrelationAnalyzer(T)

    npt.assert_equal(C.xcorr_norm.data[0, 1, C.xcorr_norm.time == 0],
                     C.corrcoef[0, 1])
Beispiel #29
0
def test_SeedCorrelationAnalyzer():

    targ = ts.TimeSeries(np.random.rand(10, 10), sampling_interval=1)

    # Test single source case
    seed = ts.TimeSeries(np.random.rand(10), sampling_interval=1)
    corr = nta.SeedCorrelationAnalyzer(seed, targ)
    our_coef_array = corr.corrcoef
    np_coef_array = np.array(
        [np.corrcoef(seed.data, a)[0, 1] for a in targ.data])

    npt.assert_array_almost_equal(our_coef_array, np_coef_array)

    # Test multiple sources
    seed = ts.TimeSeries(np.random.rand(2, 10), sampling_interval=1)
    corr = nta.SeedCorrelationAnalyzer(seed, targ)
    our_coef_array = corr.corrcoef
    for source in [0, 1]:
        np_coef_array = np.array(
            [np.corrcoef(seed.data[source], a)[0, 1] for a in targ.data])
        npt.assert_array_almost_equal(our_coef_array[source], np_coef_array)
Beispiel #30
0
    def analytic(self):
        """The natural output for this analyzer is the analytic signal """
        data = self.input.data
        sampling_rate = self.input.sampling_rate
        #If you have scipy with the fixed scipy.signal.hilbert (r6205 and
        #later)
        if scipy.__version__ >= '0.9':
            hilbert = signal.hilbert
        else:
            hilbert = tsu.hilbert_from_new_scipy

        return ts.TimeSeries(data=hilbert(data), sampling_rate=sampling_rate)