Ejemplo n.º 1
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))
Ejemplo n.º 2
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
Ejemplo n.º 3
0
def get_spectra(data,
                filt_method=dict(lb=0.1, filt_order=256),
                spect_method=dict(NFFT=1024, n_overlap=1023, BW=2),
                phase_zero=None,
                line_broadening=None,
                zerofill=None):
    """
    Derive the spectra from MRS data

    Parameters
    ----------
    data : nitime TimeSeries class instance or array
        Time-series object with data of shape (echos, transients, time-points),
        containing the FID data. If an array is provided, we will assume that a
        sampling rate of 5000.0 Hz was used

    filt_method : dict
        Details for the filtering method. A FIR zero phase-delay method is used
        with parameters set according to these parameters
        
    spect_method : dict
        Details for the spectral analysis. Per default, we use 

    line_broadening : float
        Linewidth for apodization (in Hz).

    zerofill : int
        Number of bins to zero fill with.
        
    Returns
    -------
    f : 
         the center frequency of the frequencies represented in the
        spectra

     spectrum_water, spectrum_water_suppressed: 
        The first spectrum is for the data with water not suppressed and
        the second spectrum is for the water-suppressed data.

    Notes
    -----
    This function performs the following operations:

    1. Filtering.
    2. Apodizing/windowing. Optionally, this is done with line-broadening (see
    page 92 of Keeler2005_.
    3. Spectral analysis.
        
    .. [Keeler2005] Keeler, J (2005). Understanding NMR spectroscopy, second
       edition. Wiley (West Sussex, UK).

    """
    if not isinstance(data, nt.TimeSeries):
        data = nt.TimeSeries(data, sampling_rate=5000.0)
    if filt_method is not None:
        filtered = nta.FilterAnalyzer(data, **filt_method).fir
    else:
        filtered = data
    if line_broadening is not None:
        lbr_time = line_broadening * np.pi  # Conversion from Hz to
        # time-constant, see Keeler page 94
    else:
        lbr_time = 0

    apodized = ut.line_broadening(filtered, lbr_time)

    if zerofill is not None:
        new_apodized = np.concatenate(
            [apodized.data,
             np.zeros(apodized.shape[:-1] + (zerofill, ))], -1)

        apodized = nt.TimeSeries(new_apodized,
                                 sampling_rate=apodized.sampling_rate)

    S = nta.SpectralAnalyzer(apodized,
                             method=dict(NFFT=spect_method['NFFT'],
                                         n_overlap=spect_method['n_overlap']),
                             BW=spect_method['BW'])

    f, c = S.spectrum_fourier

    return f, c