def hrfplot2(in_file, maxT): import numpy as np import matplotlib.pyplot as plt from pylab import figure, axes, pie, title, show from nipy.modalities.fmri import hrf from nipy.modalities.fmri.utils import T, lambdify_t import csv with open(in_file) as f: reader = csv.reader(f, delimiter=str("\t")) d = list(reader) mat = np.array(d) onsets = mat[:, 0] int_lst_onsets = [int(float(x)) for x in onsets] int_lst_onsets.sort() glover = hrf.glover(T) tb = int_lst_onsets bb = 1 nb = bb * sum([glover.subs(T, T - t) for t in tb]) nbv = lambdify_t(nb) t = np.linspace(0, float(maxT), 10000) plt.plot(t, nbv(t), c='b', label=in_file) for t in tb: plt.plot([t, t], [0, bb * 0.1], c='r') plt.legend() plt.show()
def test_define(): expr = sympy.exp(3*t) yield assert_equal(str(expr), 'exp(3*t)') newf = define('f', expr) yield assert_equal(str(newf), 'f(t)') f = lambdify_t(newf) tval = np.random.standard_normal((3,)) yield assert_almost_equal(np.exp(3*tval), f(tval))
def test_spectral_decomposition(): # mainly to test that the second sign follows the first spectral, approx = spectral_decomposition(hrf.glover) val_makers = [lambdify_t(def_func(T)) for def_func in spectral] t = np.linspace(-15,50,3251) vals = [val_maker(t) for val_maker in val_makers] ind = np.argmax(vals[1]) yield assert_true(vals[0][ind] > 0) # test that we can get several components spectral, approx = spectral_decomposition(hrf.glover, ncomp=5) yield assert_equal(len(spectral), 5)
from nipy.modalities.fmri.utils import events, Symbol, lambdify_t from nipy.modalities.fmri.hrf import glover # Symbol for amplitude a = Symbol('a') # Some event onsets regularly spaced onsets = np.linspace(0,50,6) # Make amplitudes from onset times (greater as function of time) amplitudes = onsets[:] # Flip even numbered amplitudes amplitudes = amplitudes * ([-1, 1] * 3) # Make event functions evs = events(onsets, amplitudes=amplitudes, g=a + 0.5 * a**2, f=glover) # Real valued function for symbolic events real_evs = lambdify_t(evs) # Time points at which to sample t_samples = np.linspace(0,60,601) pylab.plot(t_samples, real_evs(t_samples), c='r') for onset, amplitude in zip(onsets, amplitudes): pylab.plot([onset, onset],[0, 25 * amplitude], c='b') pylab.show()
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Plot of the canonical Glover HRF """ import numpy as np from nipy.modalities.fmri import hrf, utils import matplotlib.pyplot as plt # hrf.glover is a symbolic function; get a function of time to work on arrays hrf_func = utils.lambdify_t(hrf.glover(utils.T)) t = np.linspace(0,25,200) plt.plot(t, hrf_func(t)) a=plt.gca() a.set_xlabel(r'$t$') a.set_ylabel(r'$h_{can}(t)$')
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: """ Plot of the canonical Glover HRF """ import numpy as np from nipy.modalities.fmri import hrf, utils import matplotlib.pyplot as plt # hrf.glover is a symbolic function; get a function of time to work on arrays hrf_func = utils.lambdify_t(hrf.glover(utils.T)) t = np.linspace(0, 25, 200) plt.plot(t, hrf_func(t)) a = plt.gca() a.set_xlabel(r'$t$') a.set_ylabel(r'$h_{can}(t)$')
from nipy.modalities.fmri.utils import events, Symbol, lambdify_t from nipy.modalities.fmri.hrf import glover # Symbol for amplitude a = Symbol('a') # Some event onsets regularly spaced onsets = np.linspace(0, 50, 6) # Make amplitudes from onset times (greater as function of time) amplitudes = onsets[:] # Flip even numbered amplitudes amplitudes = amplitudes * ([-1, 1] * 3) # Make event functions evs = events(onsets, amplitudes=amplitudes, g=a + 0.5 * a**2, f=glover) # Real valued function for symbolic events real_evs = lambdify_t(evs) # Time points at which to sample t_samples = np.linspace(0, 60, 601) pylab.plot(t_samples, real_evs(t_samples), c='r') for onset, amplitude in zip(onsets, amplitudes): pylab.plot([onset, onset], [0, 25 * amplitude], c='b') pylab.show()
import matplotlib.pyplot as plt from nipy.modalities.fmri import hrf from nipy.modalities.fmri.utils import T, lambdify_t # HRFs as functions of (symbolic) time glover = hrf.glover(T) afni = hrf.afni(T) ta = [0,4,8,12,16]; tb = [2,6,10,14,18] ba = 1; bb = -2 na = ba * sum([glover.subs(T, T - t) for t in ta]) nb = bb * sum([afni.subs(T, T - t) for t in tb]) nav = lambdify_t(na) nbv = lambdify_t(nb) t = np.linspace(0,30,200) plt.plot(t, nav(t), c='r', label='Face') plt.plot(t, nbv(t), c='b', label='Object') plt.plot(t, nbv(t)+nav(t), c='g', label='Combined') for t in ta: plt.plot([t,t],[0,ba*0.5],c='r') for t in tb: plt.plot([t,t],[0,bb*0.5],c='b') plt.plot([0,30], [0,0],c='#000000') plt.legend() plt.show()
def make_bold(fname, stim_onset=None): """ Convert raw model output to BOLD signal Parameters ---------- fname : str File-name (including path if not in working directory) of HDF5 container that was generated by `run_model`. stim_onset : float Time (in seconds) of stimulus onset. By default, onset/offset timings of stimuli are stored in the HDF5 container generated by `run_model`. Only override this setting, if you know what you are doing. Returns ------- Nothing : None The computed BOLD signal is stored as dataset `BOLD` at the top level of the HDF5 container specified by `fname`. Notes ----- Regional neural voltages are converted to BOLD time-series using the linear hemodynamic response function proposed by Glover [1]_. For details consult the supporting information of our paper [2]_. References ---------- .. [1] Glover G. Deconvolution of Impulse Response in Event-Related BOLD FMRI. NeuroImage 9: 416-429, 1999. .. [2] S. Fuertinger, J. C. Zinn, and K. Simonyan. A Neural Population Model Incorporating Dopaminergic Neurotransmission during Complex Voluntary Behaviors. PLoS Computational Biology, 10(11), 2014. """ # Make sure container exists and is valid f = checkhdf(fname, peek=True) try: V = f['V'].value except: f.close() raise ValueError("HDF5 file " + fname + " does not have the required fields!") # Compute cycle length based on the sampling rate used to generate the file N = f['params']['names'].size s_rate = f['params']['s_rate'].value n_cycles = f['params']['n_cycles'].value len_cycle = f['params']['len_cycle'].value cycle_idx = int(np.round(s_rate * len_cycle)) # Make sure `stim_onset` makes sense if stim_onset != None: scalarcheck(stim_onset, 'stim_onset', bounds=[0, len_cycle]) # Get task from file to start sub-sampling procedure task = f['params']['task'].value # Compute cycle length based on the sampling rate used to generate the file N = f['params']['names'].size n_cycles = f['params']['n_cycles'].value len_cycle = f['params']['len_cycle'].value cycle_idx = int(np.round(s_rate * len_cycle)) # Compute step size and (if not provided by the user) compute stimulus onset time dt = 1 / s_rate if stim_onset == None: stim_onset = f['params']['stimulus'].value # Use Glover's Hemodynamic response function as convolution kernel (with default length 32) hrft = utils.lambdify_t(hrf.glover(utils.T)) hrf_kernel = np.hstack((np.zeros( (int(s_rate * stim_onset), )), hrft(np.arange(0, 32, dt)))) # Convolve the de-meaned model time-series with the kernel convV = ndimage.filters.convolve1d((V.T - V.mean(axis=1)).T, hrf_kernel, mode='constant') # Allocate space for BOLD signal BOLD = np.zeros((N, n_cycles)) # Sub-sample convoluted data depending on task to get BOLD signal if task == 'speech': # Get interval to be considered for boldification start = int(np.round(f['params']['speechoff'].value * s_rate)) stop = start + int(np.round(f['params']['acquisition'].value * s_rate)) elif task == 'rest': # Get interval to be considered for boldification start = 0 stop = int(np.round(f['params']['stimulus'].value * s_rate)) else: raise ValueError("Don't know what to do for task " + task) # Compute BOLD signal for all time points for j in xrange(n_cycles): BOLD[:, j] = convV[:, start:stop].mean(axis=1) start += cycle_idx stop += cycle_idx # Re-scale the the signal BOLD = BOLD * 0.02 # Save it to the file try: f.create_dataset('BOLD', data=BOLD) except: f['BOLD'].write_direct(BOLD) f.close()