Ejemplo n.º 1
0
# Inter-stimulus intervals (time between events)
dt = np.random.uniform(low=0, high=2.5, size=(50,))
# Onset times from the ISIs
t = np.cumsum(dt)

# We're going to model the amplitudes ('a') by dt (the time between events)
a = sympy.Symbol('a')
linear = utils.define('linear', utils.events(t, dt, f=hrf.glover))
quadratic = utils.define('quad', utils.events(t, dt, f=hrf.glover, g=a**2))
cubic = utils.define('cubic', utils.events(t, dt, f=hrf.glover, g=a**3))

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

# Evaluate this time-based formula at specific times to make the design matrix
tval = make_recarray(np.linspace(0,100, 1001), 't')
X1 = f1.design(tval, return_float=True)

# Now we make a model where the relationship of time between events and signal
# is an 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([exponential])

# Make a design matrix by passing in time and required parameters
params = make_recarray([(4.5, 3.5)], ('l', '_b0'))
X3 = f3.design(tval, params, return_float=True)

# the columns or d/d_b0 and d/dl
tt = tval.view(np.float)
v1 = np.sum([hrf.glovert(tt - s)*np.exp(-4.5*a) for s,a  in zip(t, dt)], 0)
v2 = np.sum([-3.5*a*hrf.glovert(tt - s)*np.exp(-4.5*a) for s,a  in zip(t, dt)], 0)
Ejemplo n.º 2
0
Archivo: fir.py Proyecto: ofenlab/nipy
# The splines are functions of t (time)
bsp_fns = linBspline(np.arange(0, 10, 2))

# We're going to evaluate at these specific values of time
tt = np.linspace(0, 50, 101)
tvals = tt.view(np.dtype([('t', np.float)]))

# Some inter-stimulus intervals
isis = np.random.uniform(low=0, high=3, size=(4, )) + 10.

# Made into event onset times
e = np.cumsum(isis)

# Make event onsets into functions of time convolved with the spline functions.
event_funcs = [utils.events(e, f=fn) for fn in bsp_fns]

# Put into a formula.
f = Formula(event_funcs)

# The design matrix
X = f.design(tvals, return_float=True)

# Show the design matrix as line plots
plt.plot(X[:, 0])
plt.plot(X[:, 1])
plt.plot(X[:, 2])
plt.xlabel('time (s)')
plt.title('B spline used as bases for an FIR response model')
plt.show()
Ejemplo n.º 3
0
# We can also use a Fourier basis for some other onsets - again making symbolic
# functions of time
d = utils.fourier_basis([3,5,7]) # Formula

# Make a formula for all four sets of onsets
f = Formula([c1,c2,c3]) + d

# A contrast is a formula expressed on the elements of the design formula
contrast = Formula([c1-c2, c1-c3])

# Instantiate actual values of time at which to create the design matrix rows
t = make_recarray(np.linspace(0,20,50), 't')

# Make the design matrix, and get contrast matrices for the design
X, c = f.design(t, return_float=True, contrasts={'C':contrast})

# c is a dictionary, containing a 2 by 9 matrix - the F contrast matrix for our
# contrast of interest
assert X.shape == (50, 9)
assert c['C'].shape == (2, 9)

# In this case the contrast matrix is rather obvious.
np.testing.assert_almost_equal(c['C'],
                               [[1,-1, 0, 0, 0, 0, 0, 0, 0],
                                [1, 0, -1, 0, 0, 0, 0, 0, 0]])

# We can get the design implied by our contrast at our chosen times
preC = contrast.design(t, return_float=True)
np.testing.assert_almost_equal(preC[:, 0], X[:, 0] - X[:, 1])
np.testing.assert_almost_equal(preC[:, 1], X[:, 0] - X[:, 2])
Ejemplo n.º 4
0
Archivo: fir.py Proyecto: FNNDSC/nipy
        k1, k2, k3 = knots[i:i+3]
        d1 = k2-k1
        def anon(x,k1=k1,k2=k2,k3=k3):
            return ((x-k1) / d1 * np.greater(x, k1) * np.less_equal(x, k2) +
                    (k3-x) / d1 * np.greater(x, k2) * np.less(x, k3))
        fns.append(implemented_function(name, anon))
    return fns


# The splines are functions of t (time)
bsp_fns = linBspline(np.arange(0,10,2))

# We're going to evaluate at these specific values of time
tt = np.linspace(0,50,101)
tvals= tt.view(np.dtype([('t', np.float)]))

# Some interstimulus intervals
isis = np.random.uniform(low=0, high=3, size=(4,)) + 10.
# Made into event onset times
e = np.cumsum(isis)

f = Formula([utils.events(e, f=fn) for fn in bsp_fns])

# The design matrix
X = f.design(tvals, return_float=True)

plt.plot(X[:,0])
plt.plot(X[:,1])
plt.plot(X[:,2])
plt.show()
Ejemplo n.º 5
0
 from nipy.algorithms.statistics.api import Term, Formula
 data = np.rec.fromarrays(([1,3,4,5,8,10,9], range(1,8)),
   ...                          names=('Y', 'X'))
 f = Formula([Term("X"), 1])
 dmtx = f.design(data, return_float=True)
 model = ARModel(dmtx, 2)
   We go through the ``model.iterative_fit`` procedure long-hand:
   for i in range(6):
   ...     results = model.fit(data['Y'])
   ...     print("AR coefficients:", model.rho)
   ...     rho, sigma = yule_walker(data["Y"] - results.predicted,
   ...                              order=2,
   ...                              df=model.df_resid)
   ...     model = ARModel(model.design, rho) #doctest: +FP_6DP
   ...
   AR coefficients: [ 0.  0.]
   AR coefficients: [-0.61530877 -1.01542645]
   AR coefficients: [-0.72660832 -1.06201457]
   AR coefficients: [-0.7220361  -1.05365352]
   AR coefficients: [-0.72229201 -1.05408193]
   AR coefficients: [-0.722278   -1.05405838]
 results.theta #doctest: +FP_6DP
   array([ 1.59564228, -0.58562172])
 results.t() #doctest: +FP_6DP
   array([ 38.0890515 ,  -3.45429252])
 print(results.Tcontrast([0,1]))  #doctest: +FP_6DP
   <T contrast: effect=-0.58562172384377043, sd=0.16953449108110835,
   t=-3.4542925165805847, df_den=5>
 print(results.Fcontrast(np.identity(2)))  #doctest: +FP_6DP
   <F contrast: F=4216.810299725842, df_den=5, df_num=2>
   Reinitialize the model, and do the automated iterative fit
Ejemplo n.º 6
0
# Vector of run numbers for each time point (with values 1 or 2)
run_no = np.array([1] * tval1.shape[0] + [2] * tval2.shape[0])

# Create the recarray that will be used to create the design matrix. The
# recarray gives the actual values for the symbolic terms in the formulae.  In
# our case the terms are t1, t2, and the (indicator coding) terms from the run
# factor.
rec = np.array([(tv1, tv2, s) for tv1, tv2, s in zip(ttval1, ttval2, run_no)],
               np.dtype([('t1', np.float), ('t2', np.float), ('run', np.int)]))

# The contrast we care about
contrast = Formula([run_1_coder * c11 - run_2_coder * c12])

# # Create the design matrix
X = f.design(rec, return_float=True)

# Show ourselves the design space covered by the contrast, and the corresponding
# contrast matrix
preC = contrast.design(rec, return_float=True)
# C is the matrix such that preC = X.dot(C.T)
C = np.dot(np.linalg.pinv(X), preC)
print(C)

# We can also get this by passing the contrast into the design creation.
X, c = f.design(rec, return_float=True, contrasts=dict(C=contrast))
assert np.allclose(C, c['C'])

# Show the names of the non-trivial elements of the contrast
nonzero = np.nonzero(np.fabs(C) >= 1e-5)[0]
print((f.dtype.names[nonzero[0]], f.dtype.names[nonzero[1]]))
Ejemplo n.º 7
0
run_no = np.array([1]*tval1.shape[0] + [2]*tval2.shape[0])

# Create the recarray that will be used to create the design matrix. The
# recarray gives the actual values for the symbolic terms in the formulae.  In
# our case the terms are t1, t2, and the (indicator coding) terms from the run
# factor.
rec = np.array([(tv1, tv2, s) for tv1, tv2, s in zip(ttval1, ttval2, run_no)],
               np.dtype([('t1', np.float),
                         ('t2', np.float),
                         ('run', np.int)]))

# The contrast we care about
contrast = Formula([run_1_coder * c11 - run_2_coder * c12])

# # Create the design matrix
X = f.design(rec, return_float=True)

# Show ourselves the design space covered by the contrast, and the corresponding
# contrast matrix
preC = contrast.design(rec, return_float=True)
# C is the matrix such that preC = X.dot(C.T)
C = np.dot(np.linalg.pinv(X), preC)
print(C)

# We can also get this by passing the contrast into the design creation.
X, c = f.design(rec, return_float=True, contrasts=dict(C=contrast))
assert np.allclose(C, c['C'])

# Show the names of the non-trivial elements of the contrast
nonzero = np.nonzero(np.fabs(C) >= 1e-5)[0]
print((f.dtype.names[nonzero[0]], f.dtype.names[nonzero[1]]))
Ejemplo n.º 8
0
# We can also use a Fourier basis for some other onsets - again making symbolic
# functions of time
d = utils.fourier_basis([3, 5, 7])  # Formula

# Make a formula for all four sets of onsets
f = Formula([c1, c2, c3]) + d

# A contrast is a formula expressed on the elements of the design formula
contrast = Formula([c1 - c2, c1 - c3])

# Instantiate actual values of time at which to create the design matrix rows
t = make_recarray(np.linspace(0, 20, 50), 't')

# Make the design matrix, and get contrast matrices for the design
X, c = f.design(t, return_float=True, contrasts={'C': contrast})

# c is a dictionary, containing a 2 by 9 matrix - the F contrast matrix for our
# contrast of interest
assert X.shape == (50, 9)
assert c['C'].shape == (2, 9)

# In this case the contrast matrix is rather obvious.
np.testing.assert_almost_equal(
    c['C'], [[1, -1, 0, 0, 0, 0, 0, 0, 0], [1, 0, -1, 0, 0, 0, 0, 0, 0]])

# We can get the design implied by our contrast at our chosen times
preC = contrast.design(t, return_float=True)
np.testing.assert_almost_equal(preC[:, 0], X[:, 0] - X[:, 1])
np.testing.assert_almost_equal(preC[:, 1], X[:, 0] - X[:, 2])
Ejemplo n.º 9
0
rec = np.array([(t1,t2, s) for t1, t2, s in zip(ttval1, ttval2, session)],
               np.dtype([('t1', np.float),
                         ('t2', np.float),
                         ('sess', np.int)]))

# The contrast we care about

# It would be a good idea to be able to create
# the contrast from the Formula, "f" above,
# applying all of f's aliases to it....

sess_1 = sess_factor.get_term(1)
sess_2 = sess_factor.get_term(2)
contrast = Formula([sess_1*c11-sess_2*c12])
contrast = contrast.subs(h1, hrf.glover)
contrast = contrast.subs(h2, hrf.glover)

# # Create the design matrix

X = f.design(rec, return_float=True)

preC = contrast.design(rec, return_float=True)

C = np.dot(np.linalg.pinv(X), preC)
print C

nonzero = np.nonzero(np.fabs(C) >= 0.1)[0]
print (f.dtype.names[nonzero[0]], f.dtype.names[nonzero[1]])
print ((sess_2*c12).subs(h2, hrf.glover), (sess_1*c11).subs(h1, hrf.glover))