def show_rvt_peak(r, fg): """ :param r: :param fg: :return: """ rvt_peak_plot = figure(fg) rvt_peak_plot.clf() # set(fg, 'KeyPressFcn', @afni_fig_interface) # Appears to be unnecessary to retain from MATLAB code subplot(211) plot(r['t'], real(r['x']),'g') if r['rvt'].any(): subplot(211) plot(r['t_mid_prd'], z_scale(r['rvt'], min(r['p_trace']), max(r['p_trace'])), 'k') plot(r['tp_trace'], r['p_trace'], 'ro', r['tp_trace'], r['p_trace'],'r') plot(r['tn_trace'], r['n_trace'], 'bo', r['tn_trace'], r['n_trace'],'b') plot(r['t_mid_prd'], r['p_trace_mid_prd'], 'kx') for i in range(len(r['prd'])): text(r['t_mid_prd'][i], r['p_trace_mid_prd'][i], '%.2f' % r['prd'][i]) if r['tR']: if r['p_trace_r'].any(): plot(r['tR'], r['p_trace_r'], 'm') plot(r['tR'], r['n_trace_r'], 'y') if r['rvtrs'].any(): plot(r['tR'], z_scale(r['rvtrs'], min(r['p_trace']), max(r['p_trace'])), 'k.') xlabel('time (sec)') title(r['v_name']) # , 'Interpreter', 'None') subplot(413) vn = real(r['x']) / (abs(r['x']) + spacing(1)) plot(r['t'], vn, 'g') plot(r['t'], r['phase'] / 2 / pi, 'm') if 'phase_r' in r: plot(r['tR'], r['phase_r'] / 2 / pi, 'm-.') xlabel('time (sec)') title('Scaled by magnitude of analytical signal') # , 'Interpreter', 'None') legend(['Scaled signal', 'phase']) subplot(414) plot(r['time_series_time'], r['phase_slice'][:, 0], 'ro') # This one isn't any different than the next plot line, check out why values are funky plot(r['time_series_time'], r['phase_slice'][:, 1], 'bo') plot(r['time_series_time'], r['phase_slice'][:, 1], 'b-') plot(r['t'], r['phase'], 'k') grid('on') xlabel('time (sec)') title('Phase sampled at slice acquisition time') legend(['slice 0', 'slice 1', 'slice 1', 'original phase']) # plotsign2(fg) # Another AFNI function, not crucial at the moment to making one figure show()
def rvt_from_peakfinder(r): if r['demo']: quiet = 0 print "quiet = %s" % quiet # Calculate RVT if len(r['p_trace']) != len(r['n_trace']): dd = abs(len(r['p_trace']) - len(r['n_trace'])) if dd > 1: # have not seen this yet, trap for it. print 'Error RVT_from_PeakFinder:\n' \ ' Peak trace lengths differ by %d\n' \ ' This is unusual, please upload data\n' \ ' sample to afni.nimh.nih.gov' % dd # keyboard return else: # just a difference of 1, happens sometimes, seems ok to discard one sample print 'Notice RVT_from_PeakFinder:\n' \ ' Peak trace lengths differ by %d\n'\ ' Clipping longer trace.' % dd dm = min(len(r['p_trace']), len(r['n_trace'])) if len(r['p_trace']) != dm: r['p_trace'] = r['p_trace'][0:dm] r['tp_trace'] = r['tp_trace'][0:dm] else: r['n_trace'] = r['n_trace'][0:dm] r['tn_trace'] = r['tn_trace'][0:dm] r['rv'] = subtract(r['p_trace'], r['n_trace']) # NEED TO consider which starts first and # whether to initialize first two values by means # and also, what to do when we are left with one # incomplete pair at the end nptrc = len(r['tp_trace']) r['rvt'] = r['rv'][0:nptrc - 1] / r['prd'] if r['p_trace_r'].any: r['rvr'] = subtract(r['p_trace_r'], r['n_trace_r']) # Debugging lines below # with open('rvr.csv', 'w') as f: # for i in r['rvr']: # f.write("%s\n" % i) # with open('prdR.csv', 'w') as f: # for i in r['prdR']: # f.write("%s\n" % i) r['rvtr'] = numpy.ndarray(numpy.shape(r['rvr'])) divide(r['rvr'], r['prdR'], r['rvtr']) # Smooth RVT so that we can resample it at volume_tr later fnyq = r['phys_fs'] / 2 # nyquist of physio signal fcut = 2 / r['volume_tr'] # cut below nyquist for volume_tr w = float(r['frequency_cutoff']) / float( fnyq) # cut off frequency normalized b = firwin(numtaps=(r['fir_order'] + 1), cutoff=w, window='hamming') v = r['rvtr'] around(v, 6, v) # Debugging lines below # with open('a.csv', 'w') as f: # for i in v: # f.write("%s\n" % i) mv = mean(v) # remove the mean v = (v - mv) # filter both ways to cancel phase shift v = lfilter(b, 1, v) if r['legacy_transform'] == 0: v = numpy.flipud( v ) # Turns out these don't do anything in the MATLAB version(Might be a major problem) v = lfilter(b, 1, v) if r['legacy_transform'] == 0: v = numpy.flipud( v ) # Turns out these don't do anything in the MATLAB version(Might be a major problem) r['rvtrs'] = v + mv # create RVT regressors r['rvtrs_slc'] = zeros((len(r['rvt_shifts']), len(r['time_series_time']))) for i in range(0, len(r['rvt_shifts'])): shf = r['rvt_shifts'][i] nsamp = int(round(shf * r['phys_fs'])) sind = add(range(0, len(r['t'])), nsamp) print sind sind[nonzero(sind < 0)] = 0 sind[nonzero(sind > (len(r['t']) - 1))] = len(r['t']) - 1 rvt_shf = interp1d(r['t'], r['rvtrs'][sind], r['interpolation_style'], bounds_error=True) rvt_shf_y = rvt_shf(r['time_series_time']) subplot(111) plot(r['time_series_time'], rvt_shf_y) r['rvtrs_slc'][:][i] = rvt_shf_y if r['quiet'] == 0 and r['show_graphs'] == 1: print '--> Calculated RVT \n--> Created RVT regressors' subplot(211) plot(r['t_mid_prd'], z_scale(r['rvt'], min(r['p_trace']), max(r['p_trace'])), 'k') if any(r['p_trace_r']): plot(r['tR'], z_scale(r['rvtrs'], min(r['p_trace']), max(r['p_trace'])), 'm') show() if r['demo']: # uiwait(msgbox('Press button to resume', 'Pausing', 'modal')) pass return r
def phase_base(amp_type, phasee): """ :type phasee: object :param amp_type: if 0, it is a time-based phase estimation if 1, it is an amplitude-based phase estimation :param phasee: phasee information :return: """ if amp_type == 0: # Calculate the phase of the trace, with the peak to be the start of the phase nptrc = len(phasee['tp_trace']) phasee['phase'] = -2 * ones(size(phasee['t'])) i = 0 j = 0 while i <= (nptrc - 2): while phasee['t'][j] < phasee['tp_trace'][i + 1]: if phasee['t'][j] >= phasee['tp_trace'][i]: # Note: Using a constant 244 period for each interval # causes slope discontinuity within a period. # One should resample period[i] so that it is # estimated at each time in phasee['t'][j], # dunno if that makes much of a difference in the end however. if j == 10975: pass phasee['phase'][j] = (phasee['t'][j] - phasee['tp_trace'][i]) / phasee['prd'][i]\ + phasee['zero_phase_offset'] if phasee['phase'][j] < 0: phasee['phase'][j] = -phasee['phase'][j] if phasee['phase'][j] > 1: phasee['phase'][j] -= 1 j += 1 if i == 124: pass i += 1 # Remove the points flagged as unset temp = nonzero(phasee['phase'] < -1) phasee['phase'][temp] = 0.0 # Change phase to radians phasee['phase'] = phasee['phase'] * 2 * pi else: # phase based on amplitude # at first scale to the max mxamp = max(phasee['p_trace']) phasee['phase_pol'] = [] gR = z_scale(phasee['v'], 0, mxamp) # Scale, per Glover 2000's paper bins = arange(.01, 1.01, .01) * mxamp hb_value = my_hist(gR,bins) #hb_value = histogram(gR, bins) if phasee['show_graphs'] == 1: center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hb_value[:len(hb_value)-1])#, align='center') plt.show() #find the polarity of each time point in v i = 0 itp = 0 inp = 0 tp = phasee['tp_trace'][0] tn = phasee['tn_trace'][0] while (i <= len(phasee['v'])) and (phasee['t'][i] < tp) and (phasee['t'][i] < tn): phasee['phase_pol'].append(0) i += 1 if tp < tn: # Expiring phase (peak behind us) cpol = -1 itp = 1 else: # Inspiring phase (bottom behind us) cpol = 1 inp = 1 phasee['phase_pol'] = zeros(size(phasee['v'])) # Not sure why you would replace the # list that you created 10 lines prior to this # Add a fake point to tptrace and tntrace to avoid ugly if statements phasee['tp_trace'] = append(phasee['tp_trace'], phasee['t'][-1]) phasee['tn_trace'] = append(phasee['tn_trace'], phasee['t'][-1]) while i < len(phasee['v']): phasee['phase_pol'][i] = cpol if phasee['t'][i] == phasee['tp_trace'][itp]: cpol = -1 itp = min((itp + 1), (len(phasee['tp_trace']) - 1)) elif phasee['t'][i] == phasee['tn_trace'][inp]: cpol = 1 inp = min((inp + 1), (len(phasee['tn_trace']) - 1)) # cpol, inp, itp, i, R i += 1 phasee['tp_trace'] = delete(phasee['tp_trace'], -1) phasee['tn_trace'] = delete(phasee['tn_trace'], -1) if phasee['show_graphs'] == 1: #clf plt.plot(phasee['t'], gR,'b') ipositive = nonzero(phasee['phase_pol'] > 0) ipositive = ipositive[0] ipositive_x = [] for i in ipositive: ipositive_x.append(phasee['t'][i]) ipositive_y = zeros(size(ipositive_x)) ipositive_y.fill(0.55 * mxamp) plt.plot(ipositive_x, ipositive_y, 'r.') inegative = nonzero(phasee['phase_pol'] < 0) inegative = inegative[0] inegative_x = [] for i in inegative: inegative_x.append(phasee['t'][i]) inegative_y = zeros(size(inegative_x)) inegative_y.fill(0.45 * mxamp) plt.plot(inegative_x, inegative_y, 'g.') plt.show() # Now that we have the polarity, without computing sign(dR/dt) # as in Glover et al 2000, calculate the phase per eq. 3 of that paper # First the sum in the numerator for i, val in enumerate(gR): gR[i] = (round(val / mxamp * 100) + 1) gR = clip(gR, 0, 99) shb = sum(hb_value) hbsum = [] hbsum.append(float(hb_value[0]) / shb) for i in range(1, 100): hbsum.append(hbsum[i - 1] + (float(hb_value[i]) / shb)) for i in range(len(phasee['t'])): phasee['phase'].append(pi * hbsum[int(gR[i]) - 1] * phasee['phase_pol'][i]) phasee['phase'] = array(phasee['phase']) # Time series time vector phasee['time_series_time'] = arange(0, (max(phasee['t']) - 0.5 * phasee['volume_tr']), phasee['volume_tr']) phasee['phase_slice'] = zeros((len(phasee['time_series_time']), phasee['number_of_slices'])) phasee['phase_slice_reg'] = zeros((len(phasee['time_series_time']), 4, phasee['number_of_slices'])) for i_slice in range(phasee['number_of_slices']): tslc = phasee['time_series_time'] + phasee['slice_offset'][i_slice] for i in range(len(phasee['time_series_time'])): imin = argmin(abs(tslc[i] - phasee['t'])) #mi = abs(tslc[i] - phasee['t']) # probably not needed phasee['phase_slice'][i, i_slice] = phasee['phase'][imin] # Make regressors for each slice phasee['phase_slice_reg'][:, 0, i_slice] = sin(phasee['phase_slice'][:,i_slice]) phasee['phase_slice_reg'][:, 1, i_slice] = cos(phasee['phase_slice'][:,i_slice]) phasee['phase_slice_reg'][:, 2, i_slice] = sin(2 * phasee['phase_slice'][:,i_slice]) phasee['phase_slice_reg'][:, 3, i_slice] = cos(2 * phasee['phase_slice'][:,i_slice]) if phasee['quiet'] == 0 and phasee['show_graphs'] == 1: print '--> Calculated phase' plt.subplot(413) a = divide(divide(phasee['phase'], 2), pi) plt.plot(phasee['t'], divide(divide(phasee['phase'], 2), pi), 'm') if 'phase_r' in phasee: plt.plot(phasee['tR'], divide(divide(phasee['phase_r'], 2), pi), 'm-.') plt.subplot(414) plt.plot(phasee['time_series_time'], phasee['phase_slice'][:,1], 'ro', phasee['time_series_time'], phasee['phase_slice'][:,2], 'bo', phasee['time_series_time'], phasee['phase_slice'][:,2], 'b-') plt.plot(phasee['t'], phasee['phase'], 'k') #grid on # title it plt.title(phasee['v_name']) plt.show() # Need to implement this yet #if phasee['Demo']: #uiwait(msgbox('Press button to resume', 'Pausing', 'modal')) return phasee
def rvt_from_peakfinder(r): if r['demo']: quiet = 0 print "quiet = %s" % quiet # Calculate RVT if len(r['p_trace']) != len(r['n_trace']): dd = abs(len(r['p_trace']) - len(r['n_trace'])) if dd > 1: # have not seen this yet, trap for it. print 'Error RVT_from_PeakFinder:\nPeak trace lengths differ by %d\nThis is unusual, please upload data' \ '\nsample to afni.nimh.nih.gov' % dd # keyboard return else: # just a difference of 1, happens sometimes, seems ok to discard one sample print 'Notice RVT_from_PeakFinder:\nPeak trace lengths differ by %d\nClipping longer trace.' % dd dm = min(len(r['p_trace']), len(r['p_trace'])) if len(r['p_trace']) != dm: r['p_trace'] = r['p_trace'][0:dm] r['tp_trace'] = r['tp_trace'][0:dm] else: r['n_trace'] = r['n_trace'][0:dm] r['tn_trace'] = r['tn_trace'][0:dm] r['rv'] = subtract(r['p_trace'], r['n_trace']) # NEED TO consider which starts first and # whether to initialize first two values by means # and also, what to do when we are left with one # incomplete pair at the end nptrc = len(r['tp_trace']) r['rvt'] = r['rv'][0:nptrc - 1] / r['prd'] if r['p_trace_r'].any: r['rvr'] = subtract(r['p_trace_r'], r['n_trace_r']) # Debugging lines below # with open('rvr.csv', 'w') as f: # for i in r['rvr']: # f.write("%s\n" % i) # with open('prdR.csv', 'w') as f: # for i in r['prdR']: # f.write("%s\n" % i) r['rvtr'] = numpy.ndarray(numpy.shape(r['rvr'])) divide(r['rvr'], r['prdR'], r['rvtr']) # Smooth RVT so that we can resample it at volume_tr later fnyq = r['phys_fs'] / 2 # nyquist of physio signal fcut = 2 / r['volume_tr'] # cut below nyquist for volume_tr w = float(r['frequency_cutoff']) / float(fnyq) # cut off frequency normalized b = firwin(numtaps=(r['fir_order'] + 1), cutoff=w, window='hamming') v = r['rvtr'] around(v, 6, v) # Debugging lines below # with open('a.csv', 'w') as f: # for i in v: # f.write("%s\n" % i) mv = mean(v) # remove the mean v = (v - mv) # filter both ways to cancel phase shift v = lfilter(b, 1, v) # v = numpy.flipud(v) # Turns out these don't do anything in the MATLAB version(Might be a major problem) v = lfilter(b, 1, v) # v = numpy.flipud(v) # Turns out these don't do anything in the MATLAB version(Might be a major problem) r['rvtrs'] = v + mv # create RVT regressors r['rvtrs_slc'] = zeros((len(r['rvt_shifts']), len(r['time_series_time']))) for i in range(0, len(r['rvt_shifts'])): shf = r['rvt_shifts'][i] nsamp = int(round(shf * r['phys_fs'])) sind = add(range(0, len(r['t'])), nsamp) print sind sind[nonzero(sind < 0)] = 0 sind[nonzero(sind > (len(r['t']) - 1))] = len(r['t']) - 1 rvt_shf = interp1d(r['t'], r['rvtrs'][sind], r['interpolation_style'], bounds_error=True) rvt_shf_y = rvt_shf(r['time_series_time']) subplot(111) plot(r['time_series_time'], rvt_shf_y) r['rvtrs_slc'][:][i] = rvt_shf_y if r['quiet'] == 0 and r['show_graphs'] == 1: print '--> Calculated RVT \n--> Created RVT regressors' subplot(211) plot(r['t_mid_prd'], z_scale(r['rvt'], min(r['p_trace']), max(r['p_trace'])), 'k') if any(r['p_trace_r']): plot(r['tR'], z_scale(r['rvtrs'], min(r['p_trace']), max(r['p_trace'])), 'm') show() if r['demo']: # uiwait(msgbox('Press button to resume', 'Pausing', 'modal')) pass return r
def phase_base(amp_type, phasee): """ :type phasee: object :param amp_type: if 0, it is a time-based phase estimation if 1, it is an amplitude-based phase estimation :param phasee: phasee information :return: """ if amp_type == 0: # Calculate the phase of the trace, with the peak to be the start of the phase nptrc = len(phasee['tp_trace']) phasee['phase'] = -2 * ones(size(phasee['t'])) i = 0 j = 0 while i <= (nptrc - 2): while phasee['t'][j] < phasee['tp_trace'][i + 1]: if phasee['t'][j] >= phasee['tp_trace'][i]: # Note: Using a constant 244 period for each interval # causes slope discontinuity within a period. # One should resample period[i] so that it is # estimated at each time in phasee['t'][j], # dunno if that makes much of a difference in the end however. if j == 10975: pass phasee['phase'][j] = (phasee['t'][j] - phasee['tp_trace'][i]) / phasee['prd'][i]\ + phasee['zero_phase_offset'] if phasee['phase'][j] < 0: phasee['phase'][j] = -phasee['phase'][j] if phasee['phase'][j] > 1: phasee['phase'][j] -= 1 j += 1 if i == 124: pass i += 1 # Remove the points flagged as unset temp = nonzero(phasee['phase'] < -1) phasee['phase'][temp] = 0.0 # Change phase to radians phasee['phase'] = phasee['phase'] * 2 * pi else: # phase based on amplitude # at first scale to the max mxamp = max(phasee['p_trace']) phasee['phase_pol'] = [] gR = z_scale(phasee['v'], 0, mxamp) # Scale, per Glover 2000's paper bins = arange(.01, 1.01, .01) * mxamp hb_value = my_hist(gR, bins) #hb_value = histogram(gR, bins) if phasee['show_graphs'] == 1: center = (bins[:-1] + bins[1:]) / 2 plt.bar(center, hb_value[:len(hb_value) - 1]) #, align='center') plt.show() #find the polarity of each time point in v i = 0 itp = 0 inp = 0 tp = phasee['tp_trace'][0] tn = phasee['tn_trace'][0] while (i <= len(phasee['v'])) and (phasee['t'][i] < tp) and (phasee['t'][i] < tn): phasee['phase_pol'].append(0) i += 1 if tp < tn: # Expiring phase (peak behind us) cpol = -1 itp = 1 else: # Inspiring phase (bottom behind us) cpol = 1 inp = 1 phasee['phase_pol'] = zeros(size( phasee['v'])) # Not sure why you would replace the # list that you created 10 lines prior to this # Add a fake point to tptrace and tntrace to avoid ugly if statements phasee['tp_trace'] = append(phasee['tp_trace'], phasee['t'][-1]) phasee['tn_trace'] = append(phasee['tn_trace'], phasee['t'][-1]) while i < len(phasee['v']): phasee['phase_pol'][i] = cpol if phasee['t'][i] == phasee['tp_trace'][itp]: cpol = -1 itp = min((itp + 1), (len(phasee['tp_trace']) - 1)) elif phasee['t'][i] == phasee['tn_trace'][inp]: cpol = 1 inp = min((inp + 1), (len(phasee['tn_trace']) - 1)) # cpol, inp, itp, i, R i += 1 phasee['tp_trace'] = delete(phasee['tp_trace'], -1) phasee['tn_trace'] = delete(phasee['tn_trace'], -1) if phasee['show_graphs'] == 1: #clf plt.plot(phasee['t'], gR, 'b') ipositive = nonzero(phasee['phase_pol'] > 0) ipositive = ipositive[0] ipositive_x = [] for i in ipositive: ipositive_x.append(phasee['t'][i]) ipositive_y = zeros(size(ipositive_x)) ipositive_y.fill(0.55 * mxamp) plt.plot(ipositive_x, ipositive_y, 'r.') inegative = nonzero(phasee['phase_pol'] < 0) inegative = inegative[0] inegative_x = [] for i in inegative: inegative_x.append(phasee['t'][i]) inegative_y = zeros(size(inegative_x)) inegative_y.fill(0.45 * mxamp) plt.plot(inegative_x, inegative_y, 'g.') plt.show() # Now that we have the polarity, without computing sign(dR/dt) # as in Glover et al 2000, calculate the phase per eq. 3 of that paper # First the sum in the numerator for i, val in enumerate(gR): gR[i] = (round(val / mxamp * 100) + 1) gR = clip(gR, 0, 99) shb = sum(hb_value) hbsum = [] hbsum.append(float(hb_value[0]) / shb) for i in range(1, 100): hbsum.append(hbsum[i - 1] + (float(hb_value[i]) / shb)) for i in range(len(phasee['t'])): phasee['phase'].append(pi * hbsum[int(gR[i]) - 1] * phasee['phase_pol'][i]) phasee['phase'] = array(phasee['phase']) # Time series time vector phasee['time_series_time'] = arange( 0, (max(phasee['t']) - 0.5 * phasee['volume_tr']), phasee['volume_tr']) phasee['phase_slice'] = zeros( (len(phasee['time_series_time']), phasee['number_of_slices'])) phasee['phase_slice_reg'] = zeros( (len(phasee['time_series_time']), 4, phasee['number_of_slices'])) for i_slice in range(phasee['number_of_slices']): tslc = phasee['time_series_time'] + phasee['slice_offset'][i_slice] for i in range(len(phasee['time_series_time'])): imin = argmin(abs(tslc[i] - phasee['t'])) #mi = abs(tslc[i] - phasee['t']) # probably not needed phasee['phase_slice'][i, i_slice] = phasee['phase'][imin] # Make regressors for each slice phasee['phase_slice_reg'][:, 0, i_slice] = sin( phasee['phase_slice'][:, i_slice]) phasee['phase_slice_reg'][:, 1, i_slice] = cos( phasee['phase_slice'][:, i_slice]) phasee['phase_slice_reg'][:, 2, i_slice] = sin( 2 * phasee['phase_slice'][:, i_slice]) phasee['phase_slice_reg'][:, 3, i_slice] = cos( 2 * phasee['phase_slice'][:, i_slice]) if phasee['quiet'] == 0 and phasee['show_graphs'] == 1: print '--> Calculated phase' plt.subplot(413) a = divide(divide(phasee['phase'], 2), pi) plt.plot(phasee['t'], divide(divide(phasee['phase'], 2), pi), 'm') if 'phase_r' in phasee: plt.plot(phasee['tR'], divide(divide(phasee['phase_r'], 2), pi), 'm-.') plt.subplot(414) plt.plot(phasee['time_series_time'], phasee['phase_slice'][:, 1], 'ro', phasee['time_series_time'], phasee['phase_slice'][:, 2], 'bo', phasee['time_series_time'], phasee['phase_slice'][:, 2], 'b-') plt.plot(phasee['t'], phasee['phase'], 'k') #grid on # title it plt.title(phasee['v_name']) plt.show() # Need to implement this yet #if phasee['Demo']: #uiwait(msgbox('Press button to resume', 'Pausing', 'modal')) return phasee