Exemple #1
0
def _blankdrift():
    """
    Create the blank drift formula
    
    Returns
    -------
    df  a formula that contains a constant regressor
    """
    t = formula.Term('t')
    pt = [formula.define('constant',1.0+0*t)]
    df =  formula.Formula(pt)
    return df
Exemple #2
0
def test_define():
    t = F.Term('t')
    expr = sympy.exp(3*t)
    yield assert_equal, str(expr), 'exp(3*t)'

    newf = F.define('f', expr)
    yield assert_equal, str(newf), 'f(t)'

    f = aliased.lambdify(t, newf)

    tval = np.random.standard_normal((3,))
    yield assert_almost_equal, np.exp(3*tval), f(tval)
Exemple #3
0
def _polydrift(order, tmax):
    """
    Create a polynomial drift formula
    
    Parameters
    ----------
    order, int, number of polynomials in the drift model
    tmax, float maximal time value used in the sequence
          this is used to normalize porperly the columns
    
    Returns
    -------
    pol a formula that contains all the polynomial drift 
    plus a constant regressor
    """
    t = formula.Term('t')
    pt = []
    # fixme : ideally  this should be orthonormalized  
    for k in range(order):
        pt.append(formula.define('poly_drift_%d'%(k+1),t**(k+1)/tmax**(k+1))) 
    pt.append(formula.define('constant',1.0+0*t))
    pol =  formula.Formula(pt)
    return pol
Exemple #4
0
def _cosinedrift(hfcut, tmax, tsteps):
    """
    Create a cosine drift formula

    Parameters
    ----------
    hfcut, float , cut frequency of the low-pass filter
    tmax, float  maximal time value used in the sequence
    tsteps, int,  number of TRs in the sequence
    
    Returns
    -------
    cos  a formula that contains all the polynomial drift 
    plus a constant regressor
    """
    t = formula.Term('t')
    pt = []
    order = int(np.floor(2 * float(tmax) / float(hfcut)) + 1)
    for k in range(1,order):
        u = np.sqrt(2.0/tmax) * utils.sympy_cos(np.pi*(t/tmax+ 0.5/tsteps)*k )
        pt.append(formula.define('cosine_drift_%d'%(k+1),u)) 
    pt.append(formula.define('constant',1.0+0*t))
    cos =  formula.Formula(pt)
    return cos
the amount of time since the last stimulus
T[i-1]
"""

import numpy as np
import nipy.testing as niptest
import sympy

from nipy.modalities.fmri import utils, formula, hrf

dt = np.random.uniform(low=0, high=2.5, size=(50,))
t = np.cumsum(dt)


a = sympy.Symbol('a')
linear = formula.define('linear', utils.events(t, dt, f=hrf.glover))
quadratic = formula.define('quad', utils.events(t, dt, f=hrf.glover, g=a**2))
cubic = formula.define('cubic', utils.events(t, dt, f=hrf.glover, g=a**3))

f1 = formula.Formula([linear, quadratic, cubic])

# Evaluate them

tval = formula.make_recarray(np.linspace(0,100, 1001), 't')
X1 = f1.design(tval, return_float=True)

# Let's make it exponential with a time constant tau

l = sympy.Symbol('l')
exponential = utils.events(t, dt, f=hrf.glover, g=sympy.exp(-l*a))
f3 = formula.Formula([exponential])
Exemple #6
0
the amount of time since the last stimulus
T[i-1]
"""

import numpy as np
import nipy.testing as niptest
import sympy

from nipy.modalities.fmri import utils, formula, hrf

dt = np.random.uniform(low=0, high=2.5, size=(50,))
t = np.cumsum(dt)


a = sympy.Symbol("a")
linear = formula.define("linear", utils.events(t, dt, f=hrf.glover))
quadratic = formula.define("quad", utils.events(t, dt, f=hrf.glover, g=a ** 2))
cubic = formula.define("cubic", utils.events(t, dt, f=hrf.glover, g=a ** 3))

f1 = formula.Formula([linear, quadratic, cubic])

# Evaluate them

tval = formula.make_recarray(np.linspace(0, 100, 1001), "t")
X1 = f1.design(tval, return_float=True)

# Let's make it exponential with a time constant tau

l = sympy.Symbol("l")
exponential = utils.events(t, dt, f=hrf.glover, g=sympy.exp(-l * a))
f3 = formula.Formula([exponential])
Exemple #7
0
def convolve_regressors(paradigm, hrf_model, names=None, fir_delays=[0], 
    fir_duration = 1.):
    """
    Creation of  a formula that represents 
    the convolution of the conditions onset witha  certain hrf model
    
    Parameters
    ----------
    paradigm array of shape (nevents,2) if the type is event-related design 
             or (nenvets,3) for a block design
             that contains (condition id, onset) or 
             (condition id, onset, duration)
    hrf_model, string that can be 'Canonical', 
               'Canonical With Derivative' or 'FIR'
               that specifies the hemodynamic reponse function
    names=None, list of strings corresponding to the condition names
                if names==None, these are create as 'c1',..,'cn'
                meaning 'condition 1'.. 'condition n'
    fir_delays=[0], optional, array of shape(nb_onsets) or list
                    in case of FIR design, yields the array of delays 
                    used in the FIR model
    fir_duration=1., float, duration of the FIR block; 
                     in general it should eb equal to the tr    
 
    Returns
    -------
    f a formula object that contains the convolved regressors 
      as functions of time    
    names list of strings corresponding to the condition names
          the output names depend on teh hrf model used
          if 'Canonical' then this is identical to the input names
          if 'Canonical With Derivative', then two names are produced for
             input name 'name': 'name' and 'name_derivative'

    fixme: 
    normalization of the columns of the design matrix ?
    """
    paradigm = np.asarray(paradigm)
    if paradigm.ndim !=2:
        raise ValueError('Paradigm should have 2 dimensions')
    ncond = int(paradigm[:,0].max()+1)
    if names==None:
        names=["c%d" % k for k in range(ncond)]
    else:
        if len(names)<ncond:
            raise ValueError, 'the number of names is less than the \
                  number of conditions'   
        else:
            ncond = len(names)        
    listc = []
    hnames = []
    if paradigm.shape[1]>2:
        typep = 'block'  
    else:
        typep='event'
 
    for nc in range(ncond):
        onsets =  paradigm[paradigm[:,0]==nc,1]
        nos = np.size(onsets) 
        if nos>0:
            if typep=='event':
                if hrf_model=="Canonical":
                    c = formula.define(names[nc], utils.events(onsets, f=hrf.glover))
                    listc.append(c)
                    hnames.append(names[nc])
                elif hrf_model=="Canonical With Derivative":
                    c1 = formula.define(names[nc],
                                        utils.events(onsets, f=hrf.glover))
                    c2 = formula.define(names[nc]+"_derivative",
                                        utils.events(onsets, f=hrf.dglover))
                    listc.append(c1)
                    listc.append(c2)
                    hnames.append(names[nc])
                    hnames.append(names[nc]+"_derivative")
                elif hrf_model=="FIR":
                    for i,ft in enumerate(fir_delays):
                        lnames = names[nc]+"_delay_%d"%i
                        changes = np.hstack((onsets+ft,onsets+ft+fir_duration))
                        ochanges = np.argsort(changes)
                        values = np.hstack((np.ones(nos), np.zeros(nos)))
                        changes = changes[ochanges]
                        values = values[ochanges]
                        c = formula.define(lnames, utils.step_function(changes,values))
                        listc.append(c)
                        hnames.append(lnames)
                else:
                    raise NotImplementedError,'unknown hrf model'
            elif typep=='block':
                offsets =  onsets+paradigm[paradigm[:,0]==nc,2]
                changes = np.hstack((onsets,offsets))
                values = np.hstack((np.ones(nos), -np.ones(nos)))

                if hrf_model=="Canonical":
                    c = utils.events(changes,values, f=hrf.iglover)
                    listc.append(c)
                    hnames.append(names[nc])
                elif hrf_model=="Canonical With Derivative":
                    c1 = utils.events(changes,values, f=hrf.iglover)
                    c2 = utils.events(changes,values, f=hrf.glover)
                    listc.append(c1)
                    listc.append(c2)
                    hnames.append(names[nc])
                    hnames.append(names[nc]+"_derivative")
                elif hrf_model=="FIR":
                    raise NotImplementedError,\
                          'block design are not compatible with FIR at the moment'
                else:
                    raise NotImplementedError,'unknown hrf model'  
            else:
                raise NotImplementedError,'unknown type of paradigm'
    
    # create the formula
    p = formula.Formula(listc)
     
    return p, hnames
Exemple #8
0
def protocol(fh, design_type, *hrfs):
    """
    Create an object that can evaluate the FIAC.
    Subclass of formula.Formula, but not necessary.
    
    Parameters:
    -----------
    
    fh : file handler
    File-like object that reads in the FIAC design,
    i.e. like file('subj1_evt_fonc3.txt')
    
    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.
    
    Outputs:
    --------
    f: Formula
    Formula for constructing design matrices.
    
    contrasts : dict
    Dictionary of the contrasts of the experiment.
    """
    eventdict = {1: "SSt_SSp", 2: "SSt_DSp", 3: "DSt_SSp", 4: "DSt_DSp"}

    fh = fh.read().strip().splitlines()

    times = []
    events = []

    for row in fh:
        time, eventtype = map(float, row.split())
        times.append(time)
        events.append(eventdict[eventtype])
    if design_type == "block":
        keep = np.not_equal((np.arange(len(times))) % 6, 0)
    else:
        keep = np.greater(np.arange(len(times)), 0)
    # This first frame was used to model out a potentially
    # 'bad' first frame....

    _begin = np.array(times)[~keep]

    termdict = {}
    termdict["begin"] = formula.define("begin", utils.events(_begin, f=hrf.glover))
    drift = formula.natural_spline(hrf.t, knots=[191 / 2.0 + 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 = np.array(times)[keep]
    events = np.array(events)[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 eventdict.values():
        for l, h in enumerate(hrfs):
            k = np.array([events[i] == v for i in range(times.shape[0])])
            termdict["%s%d" % (v, l)] = formula.define("%s%d" % (v, l), utils.events(times[k], f=h))
    f = formula.Formula(termdict.values())
    Tcontrasts = {}
    Tcontrasts["average"] = (
        termdict["SSt_SSp0"] + termdict["SSt_DSp0"] + termdict["DSt_SSp0"] + termdict["DSt_DSp0"]
    ) / 4.0
    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"] = formula.Formula(Tcontrasts.values())

    return f, Tcontrasts, Fcontrasts
Exemple #9
0
def altprotocol(fh, design_type, *hrfs):
    """
    Create an object that can evaluate the FIAC.
    Subclass of formula.Formula, but not necessary.

    Parameters:
    -----------

    fh : file handler
        File-like object that reads in the FIAC design,
        but has a different format (test_FIACdata.altdescr)

    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.

    """
    d = csv2rec(fh)

    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"] = formula.define("begin", utils.events(_begin, f=hrf.glover))
    drift = formula.natural_spline(hrf.t, knots=[191 / 2.0 + 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 = formula.Factor("sentence", ["DSt", "SSt"])
    sp = formula.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"] = formula.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)] = formula.define("%s%d" % (key, l), symb)

    f = formula.Formula(termdict.values())

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

    # F tests

    Fcontrasts = {}
    Fcontrasts["overall1"] = formula.Formula(Tcontrasts.values())

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

    Fcontrasts["overall2"] = (
        Fcontrasts["averageF"] + Fcontrasts["speakerF"] + Fcontrasts["sentenceF"] + Fcontrasts["interactionF"]
    )

    return f, Tcontrasts, Fcontrasts