Example #1
0
def time_series_from_file(nifti_files,
                          coords=None,
                          TR=None,
                          normalize=None,
                          average=False,
                          filter=None,
                          verbose=False):
    """ Make a time series from a Analyze file, provided coordinates into the
            file

    Parameters
    ----------

    nifti_files: a string or a list/tuple of strings.
        The full path(s) to the file(s) from which the time-series is (are)
        extracted

    coords: ndarray or list/tuple of ndarray, optional.
        x,y,z (inplane,inplane,slice) coordinates of the ROI(s) from which the
        time-series is (are) derived. If coordinates are provided, the
        resulting time-series object will have 2 dimentsions. The first is the
        coordinate dimension, in order of the provided coordinates and the
        second is time. If set to None, all the coords in the volume will be
        used and the coordinate system will be preserved - the output will be 4
        dimensional, with time as the last dimension.

    TR: float or TimeArray, optional
        The TR of the fmri measurement. The units are seconds, if provided as a float
        argument. Otherwise, in the units of the TimeArray object
        provided. Default: 1 second.

    normalize: bool, optional
        Whether to normalize the activity in each voxel, defaults to
        None, in which case the original fMRI signal is used. Other options
        are: 'percent': the activity in each voxel is converted to percent
        change, relative to this scan. 'zscore': the activity is converted to a
        zscore relative to the mean and std in this voxel in this scan.

    average: bool, optional whether to average the time-series across the
        voxels in the ROI (assumed to be the first dimension). In which
        case, TS.data will be 1-d

    filter: dict, optional
       If provided with a dict of the form:

       {'lb':float or 0, 'ub':float or None, 'method':'fourier','boxcar' 'fir'
       or 'iir' }

       each voxel's data will be filtered into the frequency range [lb,ub] with
       nitime.analysis.FilterAnalyzer, using the method chosen here (defaults
       to 'fir')

    verbose: Whether to report on ROI and file being read.

    Returns
    -------

    time-series object

    Note
    ----

    Normalization occurs before averaging on a voxel-by-voxel basis, followed
    by the averaging.

    """

    # The default behavior is to assume that the TR is one second:
    if TR is None:
        TR = 1.0

    if normalize is not None:
        if normalize not in ('percent', 'zscore'):
            e_s = "Normalization of fMRI time-series can only be done"
            e_s += " using 'percent' or 'zscore' as input"
            raise ValueError(e_s)
    #If just one string was provided:
    if isinstance(nifti_files, str):
        if verbose:
            print "Reading %s" % nifti_files
        im = load(nifti_files)
        data = im.get_data()
        # If coordinates are provided as input, read data only from these coordinates:
        if coords is not None:
            #If the input is the coords of several ROIs
            if isinstance(coords, tuple) or isinstance(coords, list):
                n_roi = len(coords)
                tseries = [[]] * n_roi
                for i in xrange(n_roi):
                    tseries[i] = _tseries_from_nifti_helper(
                        np.array(coords[i]).astype(int), data, TR, filter,
                        normalize, average)
            else:
                tseries = _tseries_from_nifti_helper(coords.astype(int), data,
                                                     TR, filter, normalize,
                                                     average)

        # The default behavior reads in all the coordinates in the volume:
        else:
            tseries = _tseries_from_nifti_helper(coords, data, TR, filter,
                                                 normalize, average)
    #Otherwise loop over the files and concatenate:
    elif isinstance(nifti_files, tuple) or isinstance(nifti_files, list):
        tseries_list = []
        for f in nifti_files:
            if verbose:
                print "Reading %s" % f
            im = load(f)
            data = im.get_data()
            if coords is not None:
                #If the input is the coords of several ROIs
                if isinstance(coords, tuple) or isinstance(coords, list):
                    n_roi = len(coords)
                    tseries_list.append([[]] * n_roi)
                    for i in xrange(n_roi):
                        tseries_list[-1][i] = _tseries_from_nifti_helper(
                            np.array(coords[i]).astype(int), data, TR, filter,
                            normalize, average)

                else:
                    tseries_list.append(
                        _tseries_from_nifti_helper(
                            np.array(coords).astype(int), data, TR, filter,
                            normalize, average))

            # The default behavior reads in all the coordinates in the volume:
            else:
                tseries_list.append(
                    _tseries_from_nifti_helper(coords, data, TR, filter,
                                               normalize, average))

        #Concatenate the time-series from the different scans:
        if isinstance(coords, tuple) or isinstance(coords, list):
            tseries = [[]] * n_roi
            #Do this per ROI
            for i in xrange(n_roi):
                tseries[i] = ts.concatenate_time_series(
                    [tseries_list[k][i] for k in xrange(len(tseries_list))])

        else:
            tseries = ts.concatenate_time_series(tseries_list)

    return tseries
Example #2
0
def time_series_from_file(nifti_files,coords,TR,normalize=None,average=False,
                          filter=None,verbose=False):
    """ Make a time series from a Analyze file, provided coordinates into the
            file 

    Parameters
    ----------

    nifti_files: a string or a list/tuple of strings.
        The full path(s) to the file(s) from which the time-series is (are)
        extracted
     
    coords: ndarray or list/tuple of ndarray
        x,y,z (inplane,inplane,slice) coordinates of the ROI(s) from which the
        time-series is (are) derived.
        
    TR: float, optional
        The TR of the fmri measurement
        
    normalize: bool, optional 
        Whether to normalize the activity in each voxel, defaults to
        None, in which case the original fMRI signal is used. Other options
        are: 'percent': the activity in each voxel is converted to percent
        change, relative to this scan. 'zscore': the activity is converted to a
        zscore relative to the mean and std in this voxel in this scan.

    average: bool, optional whether to average the time-series across the
        voxels in the ROI (assumed to be the first dimension). In which
        case, TS.data will be 1-d

    filter: dict, optional
       If provided with a dict of the form:

       {'lb':float or 0, 'ub':float or None, 'method':'fourier','boxcar' 'fir'
       or 'iir' }
       
       each voxel's data will be filtered into the frequency range [lb,ub] with
       nitime.analysis.FilterAnalyzer, using the method chosen here (defaults
       to 'fir')
       
    verbose: Whether to report on ROI and file being read.
    
    Returns
    -------

    time-series object

    Note
    ----

    Normalization occurs before averaging on a voxel-by-voxel basis, followed
    by the averaging. 

    """
    
    if normalize is not None:
        if normalize not in ('percent','zscore'):
            raise ValueError("Normalization of fMRI time-series can only be done using 'percent' or 'zscore' as input")
    #If just one string was provided:
    if isinstance(nifti_files,str):
        if verbose:
            print "Reading %s"%nifti_files
        im = load(nifti_files)
        data = im.get_data()
        #If the input is the coords of several ROIs
        if isinstance(coords,tuple) or isinstance(coords,list):
            n_roi = len(coords)
            out_data = [[]] * n_roi
            tseries = [[]] * n_roi
            for i in xrange(n_roi):
                tseries[i] = _tseries_from_nifti_helper(coords[i].astype(int),
                                                        data,TR,
                                                        filter,
                                                        normalize,
                                                        average)
        else:
            tseries = _tseries_from_nifti_helper(coords.astype(int),data,TR,
                                                 filter,normalize,average)
                
    #Otherwise loop over the files and concatenate:
    elif isinstance(nifti_files,tuple) or isinstance(nifti_files,list):
        tseries_list = []
        for f in nifti_files:
            if verbose:
                print "Reading %s"%f
            im = load(f)
            data = im.get_data()
            
            #If the input is the coords of several ROIs
            if isinstance(coords,tuple) or isinstance(coords,list):
                n_roi = len(coords)
                out_data = [[]] * n_roi
                tseries_list.append([[]] * n_roi)
                for i in xrange(n_roi):
                    tseries_list[-1][i] = _tseries_from_nifti_helper(
                                                coords[i].astype(int),
                                                data,TR,filter,normalize,average)

                
                
            else:
                tseries_list.append(_tseries_from_nifti_helper(
                                                       coords.astype(int),
                                                       data,TR,
                                                       filter,normalize,average))

        #Concatenate the time-series from the different scans:
                                    
        if isinstance(coords,tuple) or isinstance(coords,list):
            tseries = [[]] *n_roi
            #Do this per ROI
            for i in xrange(n_roi):
                tseries[i] = ts.concatenate_time_series(
                    [tseries_list[k][i] for k in xrange(len(tseries_list))])
            
        else:
            tseries = ts.concatenate_time_series(tseries_list)

    return tseries
Example #3
0
File: io.py Project: fperez/nitime
def time_series_from_file(nifti_files,coords,TR,normalize=None,average=False):
    """ Make a time series from a Analyze file, provided coordinates into the
            file 

    Parameters
    ----------

    nifti_files: a string or a list of strings.

           The full path(s) to the file(s) from which the time-series is (are)
           extracted
     
    coords: ndarray
        x,y,z (inplane,inplane,slice) coordinates of the ROI from which the
        time-series is to be derived.
        
    TR: float, optional
        TR, if different from the one which can be extracted from the nifti
        file header

    normalize: Whether to normalize the activity in each voxel, defaults to
        None, in which case the original fMRI signal is used. Other options
        are: 'percent': the activity in each voxel is converted to percent
        change, relative to this scan. 'zscore': the activity is converted to a
        zscore relative to the mean and std in this voxel in this scan.

    average: bool, optional whether to average the time-series across the
           voxels in the ROI (assumed to be the first dimension). In which
           case, TS.data will be 1-d

    
    Returns
    -------

    time-series object

    Note
    ----

    Normalization occurs before averaging on a voxel-by-voxel basis, followed
    by the averaging. 

    """
    if normalize is not None:
        if normalize not in ('percent','zscore'):
            raise ValueError("Normalization of fMRI time-series can only be done using 'percent' or 'zscore' as input")
    #If just one string was provided:
    if isinstance(nifti_files,str):
        im = load(nifti_files)
        data = im.get_data()

        out_data = np.asarray(data[coords[0],coords[1],coords[2]])

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

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

        if average:
            tseries.data = np.mean(tseries.data,0)
            
    #Otherwise loop over the files and concatenate:
    else:
        tseries_list = []
        for f in nifti_files:
            im = load(f)
            data = im.get_data()

            out_data = np.asarray(data[coords[0],coords[1],coords[2]])

            tseries_list.append(ts.TimeSeries(out_data,sampling_interval=TR))

            if normalize=='percent':
                tseries_list[-1] = tsa.NormalizationAnalyzer(tseries_list[-1]).percent_change
            elif normalize=='zscore':
                tseries_list[-1] = tsa.NormalizationAnalyzer(tseries_list[-1]).z_score

            if average:
                tseries_list[-1].data = np.mean(tseries_list[-1].data,0)

        tseries = ts.concatenate_time_series(tseries_list)
    return tseries