# 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()
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()
from nipy.algorithms.statistics.api import Formula, make_recarray from nipy.modalities.fmri import utils, hrf # 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)
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
from nipy.algorithms.statistics.api import Formula, make_recarray from nipy.modalities.fmri import utils, hrf from nipy.modalities.fmri.fmristat import hrf as delay # We take event onsets, and a specified HRF model, and make symbolic functions # of time c1 = utils.events([3,7,10], f=hrf.glover) # Symbolic function of time c2 = utils.events([1,3,9], f=hrf.glover) # Symbolic function of time c3 = utils.events([3,4,6], f=delay.spectral[0]) # Symbolic function of time # 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)
# hrf h1 = sympy.Function('hrf1') h2 = sympy.Function('hrf2') t = Term('t') # Session 1 t1 = Term('t1') c11 = utils.events([3,7,10], f=h1); c11 = c11.subs(t, t1) c21 = utils.events([1,3,9], f=h1); c21 = c21.subs(t, t1) c31 = utils.events([2,4,8], f=h1); c31 = c31.subs(t, t1) d1 = utils.fourier_basis([0.3,0.5,0.7]); d1 = d1.subs(t, t1) tval1 = np.linspace(0,20,101) f1 = Formula([c11,c21,c31]) + d1 f1 = f1.subs('hrf1', hrf.glover) # Session 2 t2 = Term('t2') c12 = utils.events([3.3,7,10], f=h2); c12 = c12.subs(t, t2) c22 = utils.events([1,3.2,9], f=h2); c22 = c22.subs(t, t2) c32 = utils.events([2,4.2,8], f=h2); c32 = c32.subs(t, t2) d2 = utils.fourier_basis([0.3,0.5,0.7]); d2 = d2.subs(t, t2) tval2 = np.linspace(0,10,51) f2 = Formula([c12,c22,c32]) + d2 f2 = f2.subs('hrf2', hrf.dglover) sess_factor = Factor('sess', [1,2])
# run 1 t1 = Term('t1') # Time within run 1 c11 = utils.events([3, 7, 10], f=h1) # Condition 1, run 1 # The events utility returns a formula in terms of 't' - general time c11 = c11.subs(t, t1) # Now make it in terms of time in run 1 # Same for conditions 2 and 3 c21 = utils.events([1, 3, 9], f=h1) c21 = c21.subs(t, t1) c31 = utils.events([2, 4, 8], f=h1) c31 = c31.subs(t, t1) # Add also a Fourier basis set for drift with frequencies 0.3, 0.5, 0.7 d1 = utils.fourier_basis([0.3, 0.5, 0.7]) d1 = d1.subs(t, t1) # Here's our formula for run 1 signal terms of time in run 1 (t1) f1 = Formula([c11, c21, c31]) + d1 # run 2 t2 = Term('t2') # Time within run 2 # Conditions 1 through 3 in run 2 c12 = utils.events([3.3, 7, 10], f=h2) c12 = c12.subs(t, t2) c22 = utils.events([1, 3.2, 9], f=h2) c22 = c22.subs(t, t2) c32 = utils.events([2, 4.2, 8], f=h2) c32 = c32.subs(t, t2) d2 = utils.fourier_basis([0.3, 0.5, 0.7]) d2 = d2.subs(t, t2) # Formula for run 2 signal in terms of time in run 2 (t2) f2 = Formula([c12, c22, c32]) + d2
# Formula for run 2 signal in terms of time in run 2 (t2) f2 = Formula([c12, c22, c32]) + d2 # Factor giving constant for run. The [1, 2] means that there are two levels to # this factor, and that when we get to pass in values for this factor, # instantiating an actual design matrix (see below), a value of 1 means level # 1 and a value of 2 means level 2. run_factor = Factor('run', [1, 2]) run_1_coder = run_factor.get_term(1) # Term coding for level 1 run_2_coder = run_factor.get_term(2) # Term coding for level 2 # The multi run formula will combine the indicator (dummy value) terms from the # run factor with the formulae for the runs (which are functions of (run1, run2) # time. The run_factor terms are step functions that are zero when not in the # run, 1 when in the run. f = Formula([run_1_coder]) * f1 + Formula([run_2_coder]) * f2 + run_factor # Now, we evaluate the formula. So far we've been entirely symbolic. Now we # start to think about the values at which we want to evaluate our symbolic # formula. # We'll use these values for time within run 1. The times are in seconds from # the beginning of run 1. In our case run 1 was 20 seconds long. 101 below # gives 101 values from 0 to 20 including the endpoints, giving a dt of 0.2. tval1 = np.linspace(0, 20, 101) # run 2 lasts 10 seconds. These are the times in terms of the start of run 2. tval2 = np.linspace(0, 10, 51) # We pad out the tval1 / tval2 time vectors with zeros corresponding to the # TRs in run 2 / run 1. ttval1 = np.hstack([tval1, np.zeros(tval2.shape)])
from nipy.algorithms.statistics.api import Formula, make_recarray from nipy.modalities.fmri import utils, hrf from nipy.modalities.fmri.fmristat import hrf as delay # We take event onsets, and a specified HRF model, and make symbolic functions # of time c1 = utils.events([3, 7, 10], f=hrf.glover) # Symbolic function of time c2 = utils.events([1, 3, 9], f=hrf.glover) # Symbolic function of time c3 = utils.events([3, 4, 6], f=delay.spectral[0]) # Symbolic function of time # 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)
# Session 2 t2 = Term('t2') c12 = utils.events([3.3,7,10], f=h2); c12 = c12.subs(t, t2) c22 = utils.events([1,3.2,9], f=h2); c22 = c22.subs(t, t2) c32 = utils.events([2,4.2,8], f=h2); c32 = c32.subs(t, t2) d2 = utils.fourier_basis([0.3,0.5,0.7]); d2 = d2.subs(t, t2) tval2 = np.linspace(0,10,51) f2 = Formula([c12,c22,c32]) + d2 sess_factor = Factor('sess', [1,2]) # The multi session formula f = Formula([sess_factor.terms[0]]) * f1 + Formula([sess_factor.terms[1]]) * f2 # Now, we evaluate the formula # the arrays now have 152=101+51 rows... ttval1 = np.hstack([tval1, np.zeros(tval2.shape)]) ttval2 = np.hstack([np.zeros(tval1.shape), tval2]) session = np.array([1]*tval1.shape[0] + [2]*tval2.shape[0]) f = f.subs(h1, hrf.glover) f = f.subs(h2, hrf.glover) # Create the recarray that will be used to create the design matrix rec = np.array([(t1,t2, s) for t1, t2, s in zip(ttval1, ttval2, session)], np.dtype([('t1', np.float),