def display_tseries(tseries,vox_idx='all',fig=None,show_mean=True): """ Display the voxel time-series of all voxels selected with vox_idx, along with the mean and sem. Currently, voxels must be along the zeroth dimension of TimeSeries object tseries """ if fig is None: fig = plt.figure() TR = tseries.sampling_interval if vox_idx=='all': vox_tseries = tseries else: vox_tseries = ts.TimeSeries(tseries.data[vox_idx],sampling_interval=TR) fig = viz.plot_tseries(vox_tseries,fig) if show_mean: fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data,0), sampling_interval=TR), yerror=ts.TimeSeries(stats.sem(vox_tseries.data,0), sampling_interval=TR),fig=fig, error_alpha = 0.3, linewidth=4, color='r') return fig
def display_tseries(tseries, vox_idx='all', fig=None, show_mean=True): """ Display the voxel time-series of all voxels selected with vox_idx, along with the mean and sem. Currently, voxels must be along the zeroth dimension of TimeSeries object tseries """ if fig is None: fig = plt.figure() TR = tseries.sampling_interval if vox_idx == 'all': vox_tseries = tseries else: vox_tseries = ts.TimeSeries(tseries.data[vox_idx], sampling_interval=TR) fig = viz.plot_tseries(vox_tseries, fig) if show_mean: fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data, 0), sampling_interval=TR), yerror=ts.TimeSeries(stats.sem( vox_tseries.data, 0), sampling_interval=TR), fig=fig, error_alpha=0.3, linewidth=4, color='r') return fig
def coord_event_related_analysis(coord, raw_bold, clean_bold, onset_events, TR, len_et, results_path, mask_name): # Prepare the event related analyzer from nitime t0 = ts.TimeSeries(raw_bold, sampling_interval=TR, time_unit='s') t1 = ts.TimeSeries(clean_bold, sampling_interval=TR, time_unit='s') # t2 = ts.Events(onset_events, time_unit='s') t2 = ts.TimeSeries(onset_events, sampling_interval=TR, time_unit='s') E = nta.EventRelatedAnalyzer(t1, t2, len_et) # Create figures fig = viz.plot_tseries(t0, ylabel='BOLD (raw) '+str(coord)) fig.savefig(os.path.join(results_path, mask_name + '_rawbold.png')) plt.close() fig = viz.plot_tseries(t1, ylabel='BOLD (clean) '+str(coord)) fig.savefig(os.path.join(results_path, mask_name + '_cleanbold.png')) plt.close() fig = viz.plot_tseries(E.eta, ylabel='BOLD (% signal change) '+str(coord), yerror=E.ets) fig.savefig(os.path.join(results_path, mask_name + '_eta.png')) plt.close() fig = viz.plot_tseries(E.FIR, ylabel='BOLD (% signal change) '+str(coord)) fig.savefig(os.path.join(results_path, mask_name + '_fir.png')) plt.close()
def plot_event(signal_filt, trg_ts, std_ts, kernel, infile): """Plot peri-stimulus timecourse of each event type as well as the canonical pupil response function""" outfile = pupil_utils.get_outfile(infile, '_PSTCplot.png') plt.ioff() all_events = std_ts.data + (trg_ts.data * 2) all_events_ts = ts.TimeSeries(all_events, sampling_rate=30., time_unit='s') all_era = nta.EventRelatedAnalyzer(signal_filt, all_events_ts, len_et=75, correct_baseline=True) fig, ax = plt.subplots() viz.plot_tseries(all_era.eta, yerror=all_era.ets, fig=fig) ax.plot((all_era.eta.time * (10**-12)), kernel) ax.legend(['Standard', 'Target', 'Pupil IRF']) fig.savefig(outfile) plt.close(fig)
def display_vox(tseries,vox_idx,fig=None): """ Display the voxel time-series """ if fig is None: fig = plt.figure() vox_tseries = ts.TimeSeries(tseries.data[vox_idx],sampling_interval=TR) fig = viz.plot_tseries(vox_tseries,fig) fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data,0), sampling_interval=TR), yerror=ts.TimeSeries(stats.sem(vox_tseries.data,0), sampling_interval=TR),fig=fig, error_alpha = 0.3,ylabel='% signal change', linewidth=4, color='r') return fig
def display_vox(tseries, vox_idx, fig=None): """ Display the voxel time-series """ if fig is None: fig = plt.figure() vox_tseries = ts.TimeSeries(tseries.data[vox_idx], sampling_interval=TR) fig = viz.plot_tseries(vox_tseries, fig) fig = viz.plot_tseries(ts.TimeSeries(np.mean(vox_tseries.data, 0), sampling_interval=TR), yerror=ts.TimeSeries(stats.sem(vox_tseries.data, 0), sampling_interval=TR), fig=fig, error_alpha=0.3, ylabel='% signal change', linewidth=4, color='r') return fig
def display_tseries(tseries, vox_idx, fig=None): """ Display the voxel time-series Currently, voxels must be along the zeroth dimension """ if fig is None: fig = plt.figure() TR = tseries.sampling_interval vox_tseries = ts.TimeSeries(tseries.data[vox_idx], sampling_interval=TR) fig = viz.plot_tseries(vox_tseries, fig) fig = viz.plot_tseries( ts.TimeSeries(np.mean(vox_tseries.data, 0), sampling_interval=TR), yerror=ts.TimeSeries(stats.sem(vox_tseries.data, 0), sampling_interval=TR), fig=fig, error_alpha=0.3, ylabel="% signal change", linewidth=4, color="r", ) return fig
def plot_event(signal_filt, con_ts, incon_ts, neut_ts, kernel, infile, plot_kernel=True): """Plot peri-stimulus timecourse of each event type as well as the canonical pupil response function""" outfile = pupil_utils.get_proc_outfile(infile, '_PSTCplot.png') plt.ioff() all_events = con_ts.data + (incon_ts.data * 2) + (neut_ts.data * 3) all_events_ts = ts.TimeSeries(all_events, sampling_rate=30., time_unit='s') all_era = nta.EventRelatedAnalyzer(signal_filt, all_events_ts, len_et=90, correct_baseline=False) fig, ax = plt.subplots() viz.plot_tseries(all_era.eta, yerror=all_era.ets, fig=fig) if plot_kernel: ax.plot((all_era.eta.time * (10**-12)), kernel) ax.legend(['Congruent', 'Incongruent', 'Neutral']) fig.savefig(outfile) plt.close(fig)
means = [] for stim,spike in zip([stim1,stim2],[spike_times1,spike_times2]): stim_time_series = ts.TimeSeries(t0=0,data=stim,sampling_interval=50, time_unit='us') stim_time_series.time_unit = 'ms' spike_ev = ts.Events(spike,time_unit='us') #Initialize the event-related analyzer event_related = tsa.EventRelatedAnalyzer(stim_time_series,spike_ev, len_et=200, offset=-200) et.append(event_related.eta) means.append(np.mean(stim_time_series.data)) #Stack the data from both time-series, initialize a new time-series and fig =viz.plot_tseries(ts.TimeSeries(data=np.vstack([et[0].data,et[1].data]), sampling_rate=et[0].sampling_rate,time_unit='ms')) ax = fig.get_axes()[0] xlim = ax.get_xlim() #Now we plot the means for each of the stimulus time-series: ax.plot([xlim[0],xlim[1]],[means[0],means[0]],'b--') ax.plot([xlim[0],xlim[1]],[means[1],means[1]],'g--')
This generates the AR(2) time series: """ X, noise, _ = utils.ar_generator(npts, sigma, coefs, drop_transients) ts_x = TimeSeries(X, sampling_rate=Fs, time_unit='s') ts_noise = TimeSeries(noise, sampling_rate=1000, time_unit='s') """ We use the plot_tseries function in order to visualize the process: """ fig01 = plot_tseries(ts_x, label='AR signal') fig01 = plot_tseries(ts_noise, fig=fig01, label='Noise') fig01.axes[0].legend() """ .. image:: fig/ar_est_1var_01.png Now we estimate back the model parameters, using two different estimation algorithms. """ coefs_est, sigma_est = alg.AR_est_YW(X, 2) # no rigorous purpose behind 100 transients
""" event_related = tsa.EventRelatedAnalyzer(stim_time_series, spike_ev, len_et=200, offset=-200) """ The actual STA gets calculated in this line (the call to 'event_related.eta') and the result gets input directly into the plotting function: """ fig01 = viz.plot_tseries(event_related.eta, ylabel='Amplitude (dB SPL)') """ We prettify the plot a bit by adding a dashed line at the mean of the stimulus """ ax = fig01.get_axes()[0] xlim = ax.get_xlim() ylim = ax.get_ylim() mean_stim = np.mean(stim_time_series.data) ax.plot([xlim[0], xlim[1]], [mean_stim, mean_stim], 'k--') """
""" # Author: Denis Engemann <d.engemann@fz-juelichde> # Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print __doc__ from mne import fiff from mne.datasets import sample from nitime.viz import plot_tseries import pylab as pl data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis-ave.fif' # Reading evoked = fiff.Evoked(fname, setno=0, baseline=(None, 0), proj=True) # Pick channels to view picks = fiff.pick_types(evoked.info, meg='grad', eeg=False, exclude='bads') evoked_ts = evoked.to_nitime(picks=picks) plot_tseries(evoked_ts) pl.show()
condition = behavioral['name'] onset = behavioral['onset'] import pandas as pd events = pd.DataFrame({'onset': onset, 'trial_type': condition}) # from nilearn.image import index_img # func_img=index_img(func_img, onset) # data=func_img.get_data() #------------------------------------------------------------------------ # Create the mask image #------------------------------------------------------------------------ #------------------------------------------------------------------------ TR = 1. len_et = 494 n_jobs = -1 t1 = ts.TimeSeries(func_img, sampling_interval=TR) t2 = ts.TimeSeries(onset, sampling_interval=TR) E = nta.EventRelatedAnalyzer(t1, t2, len_et, n_jobs) # fig01=viz.plot_tseries(E.eta, ylabel='BOLD(% signal' # 'change)', yerror=E.ets) fig02 = viz.plot_tseries(E.FIR, ylabel='BOLD (% signal change)') fig03 = viz.plot_tseries(E.xcorr_eta, ylabel='BOLD (% signal change)') plt.show()
TR=TR, normalize='percent', average=True, filter=dict(lb=f_lb, ub=f_ub, method='boxcar'), verbose=True).data # seed_ts[i_seed] = ntio.time_series_from_file(data_file, # coords=seed_coords, # TR=TR, # average=True, # verbose=True).data seed_T = ntts.TimeSeries(seed_ts, sampling_interval=TR) fig = viz.plot_tseries(seed_T) seed_Cor = nta.CorrelationAnalyzer(seed_T) fig = viz.drawmatrix_channels(seed_Cor.corrcoef, seed_rois, color_anchor=0) # Get target data # initialize target time series list target_ts = np.zeros((len(target_rois), n_TRs)) for i_target, target_name in enumerate(target_rois): print '\n', target_name, target_roi_type if target_roi_type is 'mask': target_file = os.path.join(mask_roi_dir, '{}.nii'.format(target_name)) # load roi mask
import nitime.timeseries as ts import nitime.analysis as ta import nitime.viz as tv from matplotlib.mlab import csv2rec #Load the data from file: data =csv2rec('data/event_related_fmri.csv') #Initialize TimeSeries objects: t1 = ts.TimeSeries(data.bold,sampling_interval=2) t2 = ts.TimeSeries(data.events,sampling_interval=2) #Initialized the event-related analyzer with the two time-series: E = ta.EventRelatedAnalyzer(t1,t2,15,offset=-5) #Visualize the results: tv.plot_tseries(E.FIR,ylabel='BOLD (% signal change)') tv.plot_tseries(E.xcorr_eta,ylabel='BOLD (% signal change)') #Now do the same, this time: with the zscore flag set to True: E = ta.EventRelatedAnalyzer(t1,t2,15,offset=-5,zscore=True) fig = tv.plot_tseries(E.xcorr_eta,ylabel='BOLD (% signal change)')
TR=TR, normalize='percent', average=True, filter=dict(lb=f_lb, ub=f_ub, method='boxcar'), verbose=True).data # seed_ts[i_seed] = ntio.time_series_from_file(data_file, # coords=seed_coords, # TR=TR, # average=True, # verbose=True).data seed_T = ntts.TimeSeries(seed_ts, sampling_interval=TR) fig = viz.plot_tseries(seed_T) seed_Cor = nta.CorrelationAnalyzer(seed_T) fig = viz.drawmatrix_channels(seed_Cor.corrcoef, seed_rois, color_anchor=0) # Get target data # initialize target time series list target_ts = np.zeros((len(target_rois), n_TRs)) for i_target, target_name in enumerate(target_rois): print '\n', target_name, target_roi_type if target_roi_type is 'mask': target_file = os.path.join(mask_roi_dir, '{}.nii'.format(target_name)) # load roi mask target_mask = nib.load(target_file)
import nitime.timeseries as ts import nitime.analysis as ta import nitime.viz as tv from matplotlib.mlab import csv2rec #Load the data from file: data =csv2rec('data/event_related_fmri.csv') #Initialize TimeSeries objects: t1 = ts.TimeSeries(data.bold,sampling_interval=2) t2 = ts.TimeSeries(data.events,sampling_interval=2) #Initialized the event-related analyzer with the two time-series: E = ta.EventRelatedAnalyzer(t1,t2,15,offset=-5) #Visualize the results: fig = tv.plot_tseries(E.eta,ylabel='BOLD (% signal change)',yerror=E.ets)
import os from matplotlib.mlab import csv2rec """ Extracting the average time-series from one signal, time-locked to the occurence of some type of event in another signal is a very typical operation in the analysis of time-series from neuroscience experiments. Therefore, we have an additional example of this kind of analysis in Auditory processing in grasshoppers The following example is taken from an fMRI experiment in which a subject was viewing a motion stimulus, while fMRI BOLD was recorded. The time-series in this data set were extracted from motion-sensitive voxels near area MT (a region containing motion-sensitive cells) in this subject’s brain. 6 different kinds of trials could occur in this experiment (designating different directions and locations of motion). The following example shows the extraction of the time-dependent responses of the voxels in this region to the different stimuli. """ TR = 2. # interval len_et = 15 # number of samples # Load data. data_path = os.path.join(nitime.__path__[0], "data") data = csv2rec(os.path.join(data_path, "event_related_fmri.csv")) t1 = ts.TimeSeries(data.bold, sampling_interval=TR) t2 = ts.TimeSeries(data.events, sampling_interval=TR) E = nta.EventRelatedAnalyzer(t1, t2, len_et) # Plot. fig01 = viz.plot_tseries(E.eta, ylabel="BOLD (% signal change)", yerror=E.ets) fig02 = viz.plot_tseries(E.FIR, ylabel="BOLD (% signal change)") fig03 = viz.plot_tseries(E.xcorr_eta, ylabel="BOLD (% signal change)") plt.show()
""" This generates an AR(2) time series: """ X, v, _ = utils.ar_generator(npts, sigma, coefs, drop_transients) """We use the plot_tseries function in order to visualize the process: """ import nitime.timeseries as ts from nitime.viz import plot_tseries fig_noise = plot_tseries(ts.TimeSeries(v,sampling_rate=1000,time_unit='s')) fig_noise.suptitle('noise') """ .. image:: fig/simple_ar_01.* """ fig_ar = plot_tseries(ts.TimeSeries(X,sampling_rate=1000,time_unit='s')) fig_ar.suptitle('AR signal') """ .. image:: fig/simple_ar_02.*
This generates the AR(2) time series: """ X, noise, _ = utils.ar_generator(npts, sigma, coefs, drop_transients) ts_x = TimeSeries(X, sampling_rate=Fs, time_unit='s') ts_noise = TimeSeries(noise, sampling_rate=1000, time_unit='s') """ We use the plot_tseries function in order to visualize the process: """ fig01 = plot_tseries(ts_x,label='AR signal') fig01 = plot_tseries(ts_noise,fig=fig01,label='Noise') fig01.axes[0].legend() """ .. image:: fig/ar_est_1var_01.png Now we estimate back the model parameters, using two different estimation algorithms. """ coefs_est, sigma_est = alg.AR_est_YW(X, 2)
normalize=None, average=True, filter=dict(lb=f_lb, ub=f_ub, method='boxcar'), verbose=True).data # normalize='percent' # seed_ts[i_seed] = ntio.time_series_from_file(data_file, # coords=seed_coords, # TR=TR, # average=True, # verbose=True).data seed_T = ntts.TimeSeries(seed_ts, sampling_interval=TR) fig_seed_tseries = viz.plot_tseries(seed_T) plt.title('seed tseries, {}'.format(fmri_file)) seed_Cor = nta.CorrelationAnalyzer(seed_T) fig_seed_cor = viz.drawmatrix_channels(seed_Cor.corrcoef, seed_rois, color_anchor=0) plt.title('correlation, {}'.format(fmri_file)) # Get target data # initialize target time series target_ts = np.zeros((len(target_rois), n_TRs)) for i_target, target_name in enumerate(target_rois): print '\n', target_name target_file = os.path.join(roi_dir, '{}.mat'.format(target_name)) # find the coordinates of cortex voxels
============================ """ # Author: Denis Engemann <*****@*****.**> # Alexandre Gramfort <*****@*****.**> # # License: BSD (3-clause) print(__doc__) import mne from mne.datasets import sample from nitime.viz import plot_tseries import matplotlib.pyplot as plt data_path = sample.data_path() fname = data_path + '/MEG/sample/sample_audvis-ave.fif' # Reading evoked = mne.read_evokeds(fname, condition=0, baseline=(None, 0), proj=True) # Pick channels to view picks = mne.pick_types(evoked.info, meg='grad', eeg=False, exclude='bads') evoked_ts = evoked.to_nitime(picks=picks) plot_tseries(evoked_ts) plt.show()
""" Two different methods of the EventRelatedAnalyzer are used: :attr:`E.eta` refers to the event-triggered average of the activity and :attr:`E.ets` refers to the event-triggered standard error of the mean (where the degrees of freedom are set by the number of trials). Note that you can also extract the event-triggered data itself as a list, by referring instead to :attr:`E.et_data`. We pass the eta and ets calculations straight into the visualization function, which plots the result: """ fig01 = viz.plot_tseries(E.eta, ylabel='BOLD (% signal change)', yerror=E.ets) """ .. image:: fig/event_related_fmri_01.png In the following example an alternative approach is taken to calculating the event-related activity, based on the finite impulse-response model (see [Burock2000]_ for details) """ fig02 = viz.plot_tseries(E.FIR, ylabel='BOLD (% signal change)')
spike_times = (spike_times/50).astype(int) #Initialize the time-series holding the spike-times: spike_time_series = ts.UniformTimeSeries(t0=0,sampling_interval=0.05, time_unit='ms', data=np.zeros(stim.shape)) #The position of a spike is encoded as a '1': spike_time_series.data[spike_times] = 1 #Initialize the event-related analyzer event_related = tsa.EventRelatedAnalyzer(stim_time_series, spike_time_series,len_et=250, offset=-200) #The actual STA gets calculated in this line (the call to 'event_related.eta') #and the result gets input directly into the plotting function: fig = viz.plot_tseries(event_related.eta,ylabel='Amplitude (dB SPL)') #We also plot the average of the stimulus amplitude and the time of the spike, #using dashed lines: ax = fig.get_axes()[0] xlim = ax.get_xlim() ylim = ax.get_ylim() mean_stim = np.mean(stim_time_series.data) ax.plot([xlim[0],xlim[1]],[mean_stim,mean_stim],'k--') ax.plot([0,0],[ylim[0],ylim[1]],'k--')
import os from matplotlib.mlab import csv2rec import matplotlib.pyplot as plt import nitime import nitime.timeseries as ts import nitime.analysis as nta import nitime.viz as viz TR = 2. len_et = 15 data_path = os.path.join(nitime.__path__[0], 'data') data = csv2rec(os.path.join(data_path, 'event_related_fmri.csv')) t1 = ts.TimeSeries(data.bold, sampling_interval=TR) print(t1.shape) t2 = ts.TimeSeries(data.events, sampling_interval=TR) print(t2.shape) E = nta.EventRelatedAnalyzer(t1, t2, len_et) fig01 = viz.plot_tseries(E.eta, ylabel='Bold (change)') fig02 = viz.plot_tseries(E.FIR, ylabel='Bold (change)') fig03 = viz.plot_tseries(E.xcorr_eta, ylabel='Bold (change)') plt.show()