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 convolve_regressors(paradigm, hrf_model, end_time, fir_delays=[0], fir_duration=1.): """ Creation of a formula that represents the convolution of the conditions onset with a certain hrf model Parameters ---------- paradigm: paradigm instance hrf_model: string that can be 'Canonical', 'Canonical With Derivative' or 'FIR' that specifies the hemodynamic reponse function end_time: float, end time of the paradigm (needed only for block designs) 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: formula instance, contains the convolved regressors as functions of time names: list of strings, the condition names, that depend on the 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 ? """ listc = [] hnames = [] typep = paradigm.type for nc in np.unique(paradigm.con_id): onsets = paradigm.onset[paradigm.con_id == nc] nos = np.size(onsets) if paradigm.amplitude is not None: values = paradigm.amplitude[paradigm.con_id == nc] else: values = np.ones(nos) if nos < 1: continue if typep == 'event': if hrf_model == "Canonical": c = utils.define( nc, utils.events(onsets, values, f=hrf.glover)) listc.append(c) hnames.append(nc) elif hrf_model == "Canonical With Derivative": c1 = utils.define( nc, utils.events(onsets, values, f=hrf.glover)) c2 = utils.define(nc + "_derivative", utils.events(onsets, values, f=hrf.dglover)) listc.append(c1) listc.append(c2) hnames.append(nc) hnames.append(nc + "_derivative") elif hrf_model == "FIR": for i, ft in enumerate(fir_delays): lnames = nc + "_delay_%d" % i changes = np.hstack((onsets + ft, onsets + ft + fir_duration)) ochanges = np.argsort(changes) lvalues = np.hstack((values, np.zeros(nos))) changes = changes[ochanges] lvalues = lvalues[ochanges] c = utils.define(lnames, utils.step_function(changes, lvalues)) listc.append(c) hnames.append(lnames) else: raise NotImplementedError('unknown hrf model') elif typep == 'block': offsets = onsets + paradigm.duration[paradigm.con_id == nc] intervals = [[on, off] for (on, off) in zip(onsets, offsets)] blks = utils.blocks(intervals, values) changes = np.hstack((onsets, offsets)) cvalues = np.hstack((values, - values)) if hrf_model == "Canonical": c = utils.convolve_functions(blks, hrf.glover(hrf.T), [0, end_time], 0.001) listc.append(c) hnames.append(nc) elif hrf_model == "Canonical With Derivative": c1 = utils.convolve_functions(blks, hrf.glover(hrf.T), [0, end_time], 0.001) c2 = utils.events(changes, cvalues, f=hrf.glover) listc.append(c1) listc.append(c2) hnames.append(nc) hnames.append(nc + "_derivative") elif hrf_model == "FIR": raise NotImplementedError( 'block design are not compatible with FIR') else: raise NotImplementedError('unknown hrf model') # create the formula p = formula.Formula(listc) return p, hnames
# 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)$')
""" Plot of the canonical Glover HRF """ import numpy as np from nipy.modalities.fmri import hrf import pylab from matplotlib import rc rc('text', usetex=True) t = np.linspace(0,25,200) pylab.plot(t, hrf.glover(t)) a=pylab.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: """ This example uses a different HRF for different event types """ import numpy as np 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')
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()