예제 #1
0
def natural_spline(tvals, knots=None, order=3, intercept=True):
    """
    Create a design matrix with columns given by a natural spline of a given
    order and a specified set of knots.

    Parameters
    ----------
    tvals : np.array
        Time values
    knots : None or sequence, optional
       Sequence of float.  Default None (same as empty list)
    order : int, optional
       Order of the spline. Defaults to a cubic (==3)
    intercept : bool, optional
       If True, include a constant function in the natural
       spline. Default is False

    Returns
    -------
    X : np.ndarray

    Examples
    --------
    >>> tvals = np.linspace(0,50,101)
    >>> drift = natural_spline(tvals, knots=[10,20,30,40])
    >>> drift.shape
    (101, 8)
    """
    tvals = make_recarray(tvals, ['t'])
    t = Term('t')
    f = formulae.natural_spline(t,
                                knots=knots,
                                order=order,
                                intercept=intercept)
    return f.design(tvals, return_float=True)
예제 #2
0
파일: design.py 프로젝트: alexis-roche/nipy
def natural_spline(tvals, knots=None, order=3, intercept=True):
    """
    Create a design matrix with columns given by a natural spline of a given
    order and a specified set of knots.

    Parameters
    ----------
    tvals : np.array
        Time values
    knots : None or sequence, optional
       Sequence of float.  Default None (same as empty list)
    order : int, optional
       Order of the spline. Defaults to a cubic (==3)
    intercept : bool, optional
       If True, include a constant function in the natural
       spline. Default is False

    Returns
    -------
    X : np.ndarray

    Examples
    --------
    >>> tvals = np.linspace(0,50,101)
    >>> drift = natural_spline(tvals, knots=[10,20,30,40])
    >>> drift.shape
    (101, 8)
    """
    tvals = make_recarray(tvals, ['t'])
    t = Term('t')
    f = formulae.natural_spline(t, knots=knots, order=order, intercept=intercept)
    return f.design(tvals, return_float=True)
예제 #3
0
파일: test_FIAC.py 프로젝트: Naereen/nipy
def protocol(recarr, design_type, *hrfs):
    """ Create an object that can evaluate the FIAC

    Subclass of formulae.Formula, but not necessary.

    Parameters
    ----------
    recarr : (N,) structured array
       with fields 'time' and 'event'
    design_type : str
       one of ['event', 'block'].  Handles how the 'begin' term is
       handled.  For 'block', the first event of each block is put in
       this group. For the 'event', only the first event is put in this
       group. The 'begin' events are convolved with hrf.glover.
    hrfs: symoblic HRFs
       Each event type ('SSt_SSp','SSt_DSp','DSt_SSp','DSt_DSp') is
       convolved with each of these HRFs in order.

    Returns
    -------
    f: Formula
       Formula for constructing design matrices.
    contrasts : dict
       Dictionary of the contrasts of the experiment.
    """
    event_types = np.unique(recarr['event'])
    N = recarr.size
    if design_type == 'block':
        keep = np.not_equal((np.arange(N)) % 6, 0)
    else:
        keep = np.greater(np.arange(N), 0)
    # This first frame was used to model out a potentially
    # 'bad' first frame....
    _begin = recarr['time'][~keep]

    termdict = {}
    termdict['begin'] = utils.define('begin', utils.events(_begin, f=hrf.glover))
    drift = formulae.natural_spline(utils.T,
                                   knots=[N_ROWS/2.+1.25],
                                   intercept=True)
    for i, t in enumerate(drift.terms):
        termdict['drift%d' % i] = t
    # After removing the first frame, keep the remaining
    # events and times
    times = recarr['time'][keep]
    events = recarr['event'][keep]

    # Now, specify the experimental conditions.  This creates expressions named
    # SSt_SSp0, SSt_SSp1, etc.  with one expression for each (eventtype, hrf)
    # pair
    for v in event_types:
        k = np.array([events[i] == v for i in range(times.shape[0])])
        for l, h in enumerate(hrfs):
            # Make sure event type is a string (not byte string)
            term_name = '%s%d' % (to_str(v), l)
            termdict[term_name] = utils.define(term_name,
                                               utils.events(times[k], f=h))
    f = formulae.Formula(list(termdict.values()))
    Tcontrasts = {}
    Tcontrasts['average'] = (termdict['SSt_SSp0'] + termdict['SSt_DSp0'] +
                             termdict['DSt_SSp0'] + termdict['DSt_DSp0']) / 4.
    Tcontrasts['speaker'] = (termdict['SSt_DSp0'] - termdict['SSt_SSp0'] +
                             termdict['DSt_DSp0'] - termdict['DSt_SSp0']) * 0.5
    Tcontrasts['sentence'] = (termdict['DSt_DSp0'] + termdict['DSt_SSp0'] -
                              termdict['SSt_DSp0'] - termdict['SSt_SSp0']) * 0.5
    Tcontrasts['interaction'] = (termdict['SSt_SSp0'] - termdict['SSt_DSp0'] -
                                 termdict['DSt_SSp0'] + termdict['DSt_DSp0'])
    # Ftest
    Fcontrasts = {}
    Fcontrasts['overall1'] = formulae.Formula(list(Tcontrasts.values()))

    return f, Tcontrasts, Fcontrasts
예제 #4
0
파일: test_FIAC.py 프로젝트: Naereen/nipy
def altprotocol(d, design_type, *hrfs):
    """ Create an object that can evaluate the FIAC.

    Subclass of formulae.Formula, but not necessary.

    Parameters
    ----------
    d : np.recarray
       recarray defining design in terms of time, sentence speaker

    design_type : str in ['event', 'block']
        Handles how the 'begin' term is handled.
        For 'block', the first event of each block
        is put in this group. For the 'event', 
        only the first event is put in this group.

        The 'begin' events are convolved with hrf.glover.

    hrfs: symoblic HRFs
        Each event type ('SSt_SSp','SSt_DSp','DSt_SSp','DSt_DSp')
        is convolved with each of these HRFs in order.

    """
    if design_type == 'block':
        keep = np.not_equal((np.arange(d.time.shape[0])) % 6, 0)
    else:
        keep = np.greater(np.arange(d.time.shape[0]), 0)

    # This first frame was used to model out a potentially
    # 'bad' first frame....

    _begin = d.time[~keep]
    d = d[keep]

    termdict = {}
    termdict['begin'] = utils.define('begin', utils.events(_begin, f=hrf.glover))
    drift = formulae.natural_spline(utils.T,
                                   knots=[N_ROWS/2.+1.25],
                                   intercept=True)
    for i, t in enumerate(drift.terms):
        termdict['drift%d' % i] = t

    # Now, specify the experimental conditions
    # The elements of termdict are DiracDeltas, rather than HRFs

    st = formulae.Factor('sentence', ['DSt', 'SSt'])
    sp = formulae.Factor('speaker', ['DSp', 'SSp'])

    indic = {}
    indic['sentence'] =  st.main_effect
    indic['speaker'] =  sp.main_effect
    indic['interaction'] = st.main_effect * sp.main_effect
    indic['average'] = formulae.I

    for key in indic.keys():
        # The matrix signs will be populated with +- 1's
        # d is the recarray having fields ('time', 'sentence', 'speaker')
        signs = indic[key].design(d, return_float=True)

        for l, h in enumerate(hrfs):

            # symb is a sympy expression representing a sum
            # of [h(t-_t) for _t in d.time]
            symb = utils.events(d.time, amplitudes=signs, f=h)

            # the values of termdict will have keys like
            # 'average0', 'speaker1'
            # and values  that are sympy expressions like average0(t), 
            # speaker1(t)
            termdict['%s%d' % (key, l)] = utils.define("%s%d" % (key, l), symb)

    f = formulae.Formula(list(termdict.values()))

    Tcontrasts = {}
    Tcontrasts['average'] = termdict['average0']
    Tcontrasts['speaker'] = termdict['speaker0']
    Tcontrasts['sentence'] = termdict['sentence0']
    Tcontrasts['interaction'] = termdict['interaction0']

    # F tests

    Fcontrasts = {}
    Fcontrasts['overall1'] = formulae.Formula(list(Tcontrasts.values()))

    nhrf = len(hrfs)
    Fcontrasts['averageF'] = formulae.Formula([termdict['average%d' % j] for j in range(nhrf)])
    Fcontrasts['speakerF'] = formulae.Formula([termdict['speaker%d' % j] for j in range(nhrf)])
    Fcontrasts['sentenceF'] = formulae.Formula([termdict['sentence%d' % j] for j in range(nhrf)])
    Fcontrasts['interactionF'] = formulae.Formula([termdict['interaction%d' % j] for j in range(nhrf)])

    Fcontrasts['overall2'] = Fcontrasts['averageF'] + Fcontrasts['speakerF'] + Fcontrasts['sentenceF'] + Fcontrasts['interactionF']

    return f, Tcontrasts, Fcontrasts
예제 #5
0
def protocol(recarr, design_type, *hrfs):
    """ Create an object that can evaluate the FIAC

    Subclass of formulae.Formula, but not necessary.

    Parameters
    ----------
    recarr : (N,) structured array
       with fields 'time' and 'event'
    design_type : str
       one of ['event', 'block'].  Handles how the 'begin' term is
       handled.  For 'block', the first event of each block is put in
       this group. For the 'event', only the first event is put in this
       group. The 'begin' events are convolved with hrf.glover.
    hrfs: symoblic HRFs
       Each event type ('SSt_SSp','SSt_DSp','DSt_SSp','DSt_DSp') is
       convolved with each of these HRFs in order.

    Returns
    -------
    f: Formula
       Formula for constructing design matrices.
    contrasts : dict
       Dictionary of the contrasts of the experiment.
    """
    event_types = np.unique(recarr['event'])
    N = recarr.size
    if design_type == 'block':
        keep = np.not_equal((np.arange(N)) % 6, 0)
    else:
        keep = np.greater(np.arange(N), 0)
    # This first frame was used to model out a potentially
    # 'bad' first frame....
    _begin = recarr['time'][~keep]

    termdict = {}
    termdict['begin'] = utils.define('begin', utils.events(_begin,
                                                           f=hrf.glover))
    drift = formulae.natural_spline(utils.T,
                                    knots=[N_ROWS / 2. + 1.25],
                                    intercept=True)
    for i, t in enumerate(drift.terms):
        termdict['drift%d' % i] = t
    # After removing the first frame, keep the remaining
    # events and times
    times = recarr['time'][keep]
    events = recarr['event'][keep]

    # Now, specify the experimental conditions.  This creates expressions named
    # SSt_SSp0, SSt_SSp1, etc.  with one expression for each (eventtype, hrf)
    # pair
    for v in event_types:
        k = np.array([events[i] == v for i in range(times.shape[0])])
        for l, h in enumerate(hrfs):
            # Make sure event type is a string (not byte string)
            term_name = '%s%d' % (to_str(v), l)
            termdict[term_name] = utils.define(term_name,
                                               utils.events(times[k], f=h))
    f = formulae.Formula(list(termdict.values()))
    Tcontrasts = {}
    Tcontrasts['average'] = (termdict['SSt_SSp0'] + termdict['SSt_DSp0'] +
                             termdict['DSt_SSp0'] + termdict['DSt_DSp0']) / 4.
    Tcontrasts['speaker'] = (termdict['SSt_DSp0'] - termdict['SSt_SSp0'] +
                             termdict['DSt_DSp0'] - termdict['DSt_SSp0']) * 0.5
    Tcontrasts['sentence'] = (termdict['DSt_DSp0'] + termdict['DSt_SSp0'] -
                              termdict['SSt_DSp0'] -
                              termdict['SSt_SSp0']) * 0.5
    Tcontrasts['interaction'] = (termdict['SSt_SSp0'] - termdict['SSt_DSp0'] -
                                 termdict['DSt_SSp0'] + termdict['DSt_DSp0'])
    # Ftest
    Fcontrasts = {}
    Fcontrasts['overall1'] = formulae.Formula(list(Tcontrasts.values()))

    return f, Tcontrasts, Fcontrasts
예제 #6
0
def altprotocol(d, design_type, *hrfs):
    """ Create an object that can evaluate the FIAC.

    Subclass of formulae.Formula, but not necessary.

    Parameters
    ----------
    d : np.recarray
       recarray defining design in terms of time, sentence speaker

    design_type : str in ['event', 'block']
        Handles how the 'begin' term is handled.
        For 'block', the first event of each block
        is put in this group. For the 'event', 
        only the first event is put in this group.

        The 'begin' events are convolved with hrf.glover.

    hrfs: symoblic HRFs
        Each event type ('SSt_SSp','SSt_DSp','DSt_SSp','DSt_DSp')
        is convolved with each of these HRFs in order.

    """
    if design_type == 'block':
        keep = np.not_equal((np.arange(d.time.shape[0])) % 6, 0)
    else:
        keep = np.greater(np.arange(d.time.shape[0]), 0)

    # This first frame was used to model out a potentially
    # 'bad' first frame....

    _begin = d.time[~keep]
    d = d[keep]

    termdict = {}
    termdict['begin'] = utils.define('begin', utils.events(_begin,
                                                           f=hrf.glover))
    drift = formulae.natural_spline(utils.T,
                                    knots=[N_ROWS / 2. + 1.25],
                                    intercept=True)
    for i, t in enumerate(drift.terms):
        termdict['drift%d' % i] = t

    # Now, specify the experimental conditions
    # The elements of termdict are DiracDeltas, rather than HRFs

    st = formulae.Factor('sentence', ['DSt', 'SSt'])
    sp = formulae.Factor('speaker', ['DSp', 'SSp'])

    indic = {}
    indic['sentence'] = st.main_effect
    indic['speaker'] = sp.main_effect
    indic['interaction'] = st.main_effect * sp.main_effect
    indic['average'] = formulae.I

    for key in indic.keys():
        # The matrix signs will be populated with +- 1's
        # d is the recarray having fields ('time', 'sentence', 'speaker')
        signs = indic[key].design(d, return_float=True)

        for l, h in enumerate(hrfs):

            # symb is a sympy expression representing a sum
            # of [h(t-_t) for _t in d.time]
            symb = utils.events(d.time, amplitudes=signs, f=h)

            # the values of termdict will have keys like
            # 'average0', 'speaker1'
            # and values  that are sympy expressions like average0(t),
            # speaker1(t)
            termdict['%s%d' % (key, l)] = utils.define("%s%d" % (key, l), symb)

    f = formulae.Formula(list(termdict.values()))

    Tcontrasts = {}
    Tcontrasts['average'] = termdict['average0']
    Tcontrasts['speaker'] = termdict['speaker0']
    Tcontrasts['sentence'] = termdict['sentence0']
    Tcontrasts['interaction'] = termdict['interaction0']

    # F tests

    Fcontrasts = {}
    Fcontrasts['overall1'] = formulae.Formula(list(Tcontrasts.values()))

    nhrf = len(hrfs)
    Fcontrasts['averageF'] = formulae.Formula(
        [termdict['average%d' % j] for j in range(nhrf)])
    Fcontrasts['speakerF'] = formulae.Formula(
        [termdict['speaker%d' % j] for j in range(nhrf)])
    Fcontrasts['sentenceF'] = formulae.Formula(
        [termdict['sentence%d' % j] for j in range(nhrf)])
    Fcontrasts['interactionF'] = formulae.Formula(
        [termdict['interaction%d' % j] for j in range(nhrf)])

    Fcontrasts['overall2'] = Fcontrasts['averageF'] + Fcontrasts[
        'speakerF'] + Fcontrasts['sentenceF'] + Fcontrasts['interactionF']

    return f, Tcontrasts, Fcontrasts