示例#1
0
def cuingEffectPupil(dm, traceParams=trialParams, epoch=(500,1000)):

	"""
	Determines the pupil cuing effect for a given dataset. This is the mean
	difference between bright and dark trials within a specific epoch.

	Arguments:
	dm				--	A DataMatrix.

	Keyword arguments:
	traceParams		--	The trace parameters. (default=trialParams)
	epoch			--	The time interval for which to estimate the pupil
						effect. (default=(500,1000))

	Returns:
	A value reflecting the pupil cuing effect.
	"""

	x1, y1, err1 = tk.getTraceAvg(dm.select('cueLum == "bright"', verbose= \
		False), **traceParams)
	x2, y2, err2 = tk.getTraceAvg(dm.select('cueLum == "dark"', verbose= \
		False), **traceParams)
	d = y2-y1
	d = d[epoch[0]:epoch[1]]
	return d.mean()
示例#2
0
def traceDiffPeaks(dm):

	"""
	desc: |
		Determines the peaks where the effect is largest, and smallest, in real
		units. This analysis is based on non-baselined pupil size.

	arguments:
		dm:		A DataMatrix.
	"""

	traceParams = trialParams.copy()
	del traceParams['baseline']
	x1, y1, err1 = tk.getTraceAvg(dm.select('cueLum == "bright"'), \
		**traceParams)
	x2, y2, err2 = tk.getTraceAvg(dm.select('cueLum == "dark"'), \
		**traceParams)
	xGrand, yGrand, errGrand = tk.getTraceAvg(dm, **traceParams)
	d = 100. * (y2-y1) / yGrand
	iMax = np.where(d == d.max())[0][0]
	iMin = np.where(d == d.min())[0][0]
	print 'Max effect: %.2f (sample %d)' % (d[iMax], iMax)
	print 'Min effect: %.2f (sample %d)' % (d[iMin], iMin)
	plt.subplot(211)
	plt.plot(y1, color=green[1])
	plt.plot(y2, color=blue[1])
	plt.plot(yGrand, color=gray[1])
	plt.subplot(212)
	plt.plot(d, color='black')
	plt.axvline(iMax, color='black')
	plt.axvline(iMin, color='black')
	Plot.save('traceDiffPeaks')
示例#3
0
def tracePlot(dm, traceParams=trialParams, suffix='', err=True,
	lumVar='cueLum', minSmp=200, diff=True):

	"""
	A pupil-trace plot for a single epoch.

	Arguments:
	dm				--	A DataMatrix.

	Keyword arguments:
	traceParams		--	The trace parameters. (default=trialParams)
	suffix			--	A suffix to identify the trace. (default='')
	err				--	Indicates whether error bars should be drawn.
						(default=True)
	lumVar			--	The variable that contains the luminance information.
						(default='cueLum')
	diff			--	Indicates whether the difference trace should be plotted
						as well. (default=True)
	"""

	# At the moment we can only determine error bars for cueLum
	assert(not err or lumVar == 'cueLum')
	assert(lumVar in ['cueLum', 'targetLum'])
	dmBright = dm.select('%s == "bright"' % lumVar)
	dmDark = dm.select('%s == "dark"' % lumVar)
	x1, y1, err1 = tk.getTraceAvg(dmBright, **traceParams)
	x2, y2, err2 = tk.getTraceAvg(dmDark, **traceParams)
	if err:
		d = y2-y1
		aErr = lmeTrace(dm, traceParams=traceParams, suffix=suffix, \
			cacheId='lmeTrace%s' % suffix)
		aT = aErr[:,0]
		aLo = aErr[:,1]
		aHi = aErr[:,2]
		minErr = (d-aLo)/2
		maxErr = (aHi-d)/2
		y1min = y1 - minErr
		y1max = y1 + maxErr
		y2min = y2 - minErr
		y2max = y2 + maxErr
		plt.fill_between(x1, y1min, y1max, color=green[1], alpha=.25)
		plt.fill_between(x2, y2min, y2max, color=blue[1], alpha=.25)
		tk.markStats(plt.gca(), np.abs(aT), below=False, thr=2, minSmp=minSmp)
	if diff:
		plt.plot(x1, diffY+y2-y1, color=orange[1], label='Pupillary cuing effect')
	if lumVar == 'cueLum':
		plt.plot(x1, y1, color=green[1], label='Cue on bright (N=%d)' \
			% len(dmBright))
		plt.plot(x2, y2, color=blue[1], label='Cue on dark (N=%d)' \
			% len(dmDark))
	elif lumVar == 'targetLum':
		plt.plot(x1, y1, color=green[1], label='Target on bright')
		plt.plot(x2, y2, color=blue[1], label='Target on dark')
示例#4
0
def getDiffTrace(dm):

	"""desc: |
	The difference pupil trace, i.e. the difference between Land-on-Dark and
	Land-on-Bright trials.

	arguments:
		dm:		A DataMatrix.

	returns: |
		A difference trace.
	"""

	dmWhite = dm.select('saccCol == "white"', verbose=False)
	xAvg, yAvg, errAvg= TraceKit.getTraceAvg(dm, signal='pupil',
		phase='postSacc', traceLen=postTraceLen, baseline=baseline,
		baselineLock=baselineLock)
	xWhite, yWhite, errWhite = TraceKit.getTraceAvg(dmWhite,
		signal='pupil', phase='postSacc', traceLen=postTraceLen,
		baseline=baseline, baselineLock=baselineLock)
	yWhite -= yAvg
	return yWhite
示例#5
0
def traceDiffPlot(dm, traceParams=trialParams, suffix='', err=True, \
	color=blue[1], label=None):

	"""
	A pupil-trace plot for a single epoch.

	Arguments:
	dm				--	A DataMatrix.

	Keyword arguments:
	traceParams		--	The trace parameters. (default=trialParams)
	suffix			--	A suffix to identify the trace. (default='')
	err				--	Indicates whether error bars should be drawn.
						(default=True) Note: UNUSED
	color			--	The line color. (default=blue[1])
	label			--	The line label. (default=None)
	"""

	x1, y1, err1 = tk.getTraceAvg(dm.select('cueLum == "bright"'), \
		**traceParams)
	x2, y2, err2 = tk.getTraceAvg(dm.select('cueLum == "dark"'), **traceParams)
	d = y2-y1
	plt.plot(d, color=color, label=label)
示例#6
0
def tracePlot(dm, traceParams, suffix="", err=True):

    """
	desc: |
		A pupil-trace plot for a single epoch.

	arguments:
		dm:				A DataMatrix.
		traceParams:	The trace parameters.

	keywords:
		suffix:			A suffix to identify the trace.
		err:			Indicates whether error bars should be drawn.
	"""

    x1, y1, err1 = TraceKit.getTraceAvg(dm.select('saccCol == "white"'), **traceParams)
    x2, y2, err2 = TraceKit.getTraceAvg(dm.select('saccCol == "black"'), **traceParams)
    if err:
        d = y1 - y2
        aErr = lmeTrace(dm, traceParams=traceParams, suffix=suffix, cacheId="lmeTrace.%s%s" % (exp, suffix))
        aT = aErr[:, 0]
        aLo = aErr[:, 2]
        aHi = aErr[:, 1]
        minErr = (d - aLo) / 2
        maxErr = (aHi - d) / 2
        y1min = y1 - minErr
        y1max = y1 + maxErr
        y2min = y2 - minErr
        y2max = y2 + maxErr
        plt.fill_between(x1, y1min, y1max, color=brightColor, label="Bright")
        plt.fill_between(x2, y2min, y2max, color=darkColor, label="Dark")
        TraceKit.markStats(plt.gca(), np.abs(aT), below=False, thr=2, minSmp=200, loExt=True, hiExt=True)
        plt.plot(x1, d, color="green")
    else:
        plt.plot(x1, y1, color=brightColor, label="Bright")
        plt.plot(x2, y2, color=darkColor, label="Dark")
示例#7
0
def prepFit(dm, suffix=''):

	"""
	Perform a linear-regression fit on only the first 220 ms.

	Arguments:
	dm		--	DataMatrix

	Keyword arguments:
	suffix	--	A suffix for the output files. (default='')
	"""

	fig = newFig(size=bigWide)
	plt.subplots_adjust(wspace=0, hspace=0)
	i = 0

	l = [['subjectNr', 'sConst', 'iConst', 'sOnset', 'iOnset', 'sSwap',
		'iSwap']]

	for dm in [dm] + dm.group('subject_nr'):

		print 'Subject %s' % i
		row = [i]

		# We use a 6 x 2 plot grid
		# XX X X X X
		# XX X X X X
		if i == 0:
			# Overall plot
			ax = plt.subplot2grid((2,6),(0,0), colspan=2, rowspan=2)
			linewidth = 1
			title = 'Full data (N=%d)' % len(dm.select('cond != "swap"'))
		else:
			# Individual plots
			ax = plt.subplot2grid((2,6),((i-1)/4, 2+(i-1)%4))
			linewidth = 1
			title = '%d (N=%d)' % (i, len(dm.select('cond != "swap"')))

		plt.text(0.9, 0.1, title, horizontalalignment='right', \
			verticalalignment='bottom', transform=ax.transAxes)

		if i == 0:
			plt.xticks([0, 50, 100, 150, 200])
		elif i > 0 and i < 5:
			plt.xticks([])
		else:
			plt.xticks([0, 100])
		if i > 0:
			plt.yticks([])
		else:
			plt.yticks([0, -.01, -.02])
		plt.ylim(-.025, .01)
		plt.axhline(0, color='black', linestyle=':')
		for cond in ('constant', 'onset', 'swap'):
			_dm = dm.select("cond == '%s'" % cond, verbose=False)
			dmWhite = _dm.select('saccCol == "white"', verbose=False)
			xAvg, yAvg, errAvg= TraceKit.getTraceAvg(_dm, signal='pupil', \
				phase='postSacc', traceLen=postTraceLen, baseline=baseline, \
				baselineLock=baselineLock)
			xWhite, yWhite, errWhite = TraceKit.getTraceAvg(dmWhite, \
				signal='pupil', phase='postSacc', traceLen=postTraceLen, \
				baseline=baseline, baselineLock=baselineLock)
			yWhite -= yAvg
			xWhite = xWhite[:prepWin]
			yWhite = yWhite[:prepWin]
			if cond == 'constant':
				col = constColor
				lineStyle = '-'
			elif cond == 'onset':
				col = onsetColor
				lineStyle = '--'
			else:
				col = swapColor
				lineStyle = '-.'
				yWhite *= -1
			opts = Plot.regress(xWhite, yWhite, lineColor=col, symbolColor=col,
				label=cond, annotate=False, symbol=lineStyle, linestyle=':')
			s = 1000.*opts[0]
			_i = 1000.*opts[1]
			print 's = %.4f, i = %.4f' % (s, _i)
			if i > 0:
				row += [s, _i]
			else:
				plt.legend(frameon=False, loc='upper right')
		if i > 0:
			l.append(row)
		i += 1
	saveFig('linFitPrepWin%s' % suffix, show=False)
	dm = DataMatrix(l)
	dm.save('output/%s/linFitPrepWin%s.csv' % (exp, suffix))

	# Summarize the data and perform ttests on the model parameters
	for dv in ['s', 'i']:
		print'\nAnalyzing %s' % dv
		aConst = dm['%sConst' % dv]
		aOnset = dm['%sOnset' % dv]
		aSwap = dm['%sSwap' % dv]
		print 'Constant: M = %f, SE = %f' % (aConst.mean(), \
			aConst.std() / np.sqrt(N))
		print 'Onset: M = %f, SE = %f' % (aOnset.mean(), \
			aOnset.std() / np.sqrt(N))
		print 'Swap: M = %f, SE = %f' % (aSwap.mean(), \
			aSwap.std() / np.sqrt(N))
		# Standard t-tests
		t, p = ttest_rel(aConst, aOnset)
		print 'Const vs onset, t = %.4f, p = %.4f' % (t, p)
		t, p = ttest_rel(aSwap, aOnset)
		print 'Swap vs onset, t = %.4f, p = %.4f' % (t, p)
		t, p = ttest_rel(aConst, aSwap)
		print 'Const vs swap, t = %.4f, p = %.4f' % (t, p)
示例#8
0
def fit(dm, suffix='', maxSmp=None):

	"""
	Fits the data based on an exponential pupil model.

	Arguments:
	dm		--	DataMatrixpass

	Keyword arguments:
	suffix	--	A suffix for the output files. (default='')
	maxSmp	--	The maximum number of samples to base the fit on, or None for
				no limit. (default=None)
	"""

	fig = newFig(size=bigWide)
	plt.subplots_adjust(wspace=0, hspace=0)
	i = 0

	l = [['subjectNr', 't0Const', 'speedConst', 'lim1Const', 'lim2Const', \
		't0Onset', 'speedOnset', 'lim1Onset', 'lim2Onset']]

	for dm in [dm] + dm.group('subject_nr'):

		print 'Subject %s' % i
		row = [i]

		# We use a 6 x 2 plot grid
		# XX X X X X
		# XX X X X X
		if i == 0:
			# Overall plot
			ax = plt.subplot2grid((2,6),(0,0), colspan=2, rowspan=2)
			# Draw 'window of preparation'
			plt.axvspan(0, prepWin, color=green[1], alpha=.2)
			linewidth = 1
			title = 'Full data (N=%d)' % len(dm.select('cond != "swap"'))
		else:
			# Individual plots
			ax = plt.subplot2grid((2,6),((i-1)/4, 2+(i-1)%4))
			linewidth = 1
			title = '%d (N=%d)' % (i, len(dm.select('cond != "swap"')))

		plt.text(0.9, 0.1, title, horizontalalignment='right', \
			verticalalignment='bottom', transform=ax.transAxes)

		if i == 0:
			plt.xticks([0, 500, 1000, 1500])
		elif i > 0 and i < 5:
			plt.xticks([])
		else:
			plt.xticks([0, 1000])
		if i > 0:
			plt.yticks([])
		else:
			plt.yticks([0, -.1, -.2, -.3])
		for cond in ('constant', 'onset'):
			_dm = dm.select("cond == '%s'" % cond, verbose=False)
			dmWhite = _dm.select('saccCol == "white"', verbose=False)
			xAvg, yAvg, errAvg= TraceKit.getTraceAvg(_dm, signal='pupil', \
				phase='postSacc', traceLen=postTraceLen, baseline=baseline, \
				baselineLock=baselineLock)
			xWhite, yWhite, errWhite = TraceKit.getTraceAvg(dmWhite, \
				signal='pupil', phase='postSacc', traceLen=postTraceLen, \
				baseline=baseline, baselineLock=baselineLock)
			yWhite -= yAvg
			if cond == 'constant':
				col = constColor
				lineStyle = '-'
			elif cond == 'onset':
				col = onsetColor
				lineStyle = '--'
			else:
				col = swapColor
				lineStyle = '-'
			if maxSmp != None:
				xWhite = xWhite[:maxSmp]
				yWhite = yWhite[:maxSmp]
			opts = fitCurve(xWhite, yWhite, col=col, label=cond, \
				linewidth=linewidth, lineStyle=lineStyle)
			print 't0 = %.4f, s = %.4f, l1 = %.4f, l2 = %.4f' % tuple(opts)
			t0 = opts[0]
			if i > 0:
				row += list(opts)
			else:
				plt.legend(frameon=False, loc='upper right')
			print '%s : %f' % (cond, t0)
		if i > 0:
			l.append(row)
		i += 1
	saveFig('fit%s' % suffix, show=False)
	dm = DataMatrix(l)
	dm.save('output/%s/fit%s.csv' % (exp, suffix))

	# Summarize the data and perform ttests on the model parameters
	for dv in ['t0', 'speed', 'lim1', 'lim2']:
		print'\nAnalyzing %s' % dv
		aConst = dm['%sConst' % dv]
		aOnset = dm['%sOnset' % dv]
		print 'Constant: M = %f, SE = %f' % (aConst.mean(), \
			aConst.std() / np.sqrt(N))
		print 'Onset: M = %f, SE = %f' % (aOnset.mean(), \
			aOnset.std() / np.sqrt(N))
		t, p = ttest_rel(aConst, aOnset)
		print 'Const vs onset, t = %.4f, p = %.4f' % (t, p)
示例#9
0
def mainPlots(dm, perSubject=False, suffix="", zoom=False):

    """
	desc: |
		Generates the main plots, consisting of four panes (difference,
		Constant, Swap, Onset)

	arguments:
		dm:				DataMatrix

	keywords:
		perSubject:
			desc: |
					Indicates whether a single grand mean plot should be
					generated (False) or individual plots per subject
					(True).
			type:	bool
		suffix:
			desc:	A suffix for the plot filename.
			type:	[str, unicode]
		zoom:
			desc:	Indicates whether we should generate a zoom plot.
			type:	bool
	"""

    if perSubject:
        subjectList = dm.unique("subject_nr")
    else:
        subjectList = ["all"]
    for subjectNr in subjectList:
        print ("Generating main plots for subject: %s" % subjectNr)
        if subjectNr == "all":
            _dm = dm
        else:
            _dm = dm.select("subject_nr == %d" % subjectNr, verbose=False)
        if zoom:
            fig = newFig(size=(2, 5))
        else:
            fig = newFig(size=big)
        plt.subplots_adjust(wspace=0, hspace=0)
        # Pre difference plot
        if zoom:
            ax = plt.subplot2grid((4, 2), (0, 0), colspan=1)
        else:
            ax = plt.subplot2grid((4, 7), (0, 0), colspan=1)
        plt.ylabel("Pupil-size diff (norm.)")
        if zoom:
            plt.ylim(-0.03, 0.01)
            plt.yticks([-0.02, -0.01, 0])
            plt.xticks([preTraceLen - 25], [-25])
            plt.xlim(preTraceLen - 50, preTraceLen)
        else:
            plt.ylim(-0.5, 0.2)
            plt.yticks([0.0, -0.2, -0.4])
            plt.xticks([25], [-150])
            plt.xlim(0, preTraceLen)
        ax.spines["right"].set_visible(False)
        ax.get_yaxis().tick_left()
        ax.axhline(0, linestyle="--", color="black")
        # Draw saccade onsets
        sMin = _dm["flipSDelay"].min()
        sMax = _dm["flipSDelay"].max()
        sMean = _dm["flipSDelay"].mean()
        plt.axvspan(preTraceLen - sMin, preTraceLen - sMax, color=flipSColor, alpha=0.1)
        plt.axvline(preTraceLen - sMean, color=flipSColor, linestyle=flipEStyle)
        for cond in ("constant", "swap", "onset"):
            print "\t%s" % cond
            __dm = _dm.select('cond == "%s"' % cond, verbose=False)
            _dmWhite = __dm.select('saccCol == "white"', verbose=False)
            _dmBlack = __dm.select('saccCol == "black"', verbose=False)
            xPre, blackPre, err = TraceKit.getTraceAvg(
                _dmBlack, signal="pupil", phase="cue", lock="end", traceLen=preTraceLen, baseline=baseline
            )
            xPre, whitePre, err = TraceKit.getTraceAvg(
                _dmWhite, signal="pupil", phase="cue", lock="end", traceLen=preTraceLen, baseline=baseline
            )
            if cond == "constant":
                col = constColor
                style = constStyle
            elif cond == "swap":
                col = swapColor
                style = swapStyle
            else:
                col = onsetColor
                style = onsetStyle
            plt.plot(xPre, whitePre - blackPre, color=col, label=cond, linestyle=style)
            if cond == "swap":
                plt.plot(xPre, blackPre - whitePre, ":", color=col, label="inverse swap")
                # Post difference plot
        if zoom:
            ax = plt.subplot2grid((4, 2), (0, 1), colspan=6)
        else:
            ax = plt.subplot2grid((4, 7), (0, 1), colspan=6)
        ax.spines["left"].set_visible(False)
        plt.axvline(0, linestyle="--", color="black")
        if zoom:
            plt.ylim(-0.03, 0.01)
            plt.yticks([-0.02, -0.01, 0])
            plt.xticks([0, 25])
            plt.xlim(0, 50)
        else:
            plt.ylim(-0.5, 0.2)
            plt.yticks([0.0, -0.2, -0.4])
            plt.xlim(0, postTraceLen)
            plt.xticks(range(0, postTraceLen, 150))
        ax.axhline(0, linestyle="--", color="black")
        ax.get_yaxis().set_ticklabels([])
        # Title
        plt.text(
            0.1, 0.9, "Difference", horizontalalignment="center", verticalalignment="center", transform=ax.transAxes
        )
        # Draw saccade offsets
        eMin = -_dm["flipEDelay"].min()
        eMax = -_dm["flipEDelay"].max()
        eMean = -_dm["flipEDelay"].mean()
        plt.axvspan(eMin, eMax, color=flipEColor, alpha=0.1)
        plt.axvline(eMean, color=flipEColor, linestyle=flipEStyle)
        # Draw 'window of preparation'
        plt.axvspan(0, prepWin, color=green[1], alpha=0.2)
        for cond in ("constant", "swap", "onset"):
            print "\t%s" % cond
            __dm = _dm.select('cond == "%s"' % cond, verbose=False)
            _dmWhite = __dm.select('saccCol == "white"', verbose=False)
            _dmBlack = __dm.select('saccCol == "black"', verbose=False)
            xPost, blackPost, err = TraceKit.getTraceAvg(
                _dmBlack, signal="pupil", phase="postSacc", lock="start", traceLen=postTraceLen, baseline=baseline
            )
            xPost, whitePost, err = TraceKit.getTraceAvg(
                _dmWhite, signal="pupil", phase="postSacc", lock="start", traceLen=postTraceLen, baseline=baseline
            )
            if cond == "constant":
                col = constColor
                style = constStyle
            elif cond == "swap":
                col = swapColor
                style = swapStyle
            else:
                col = onsetColor
                style = onsetStyle
            plt.plot(xPost, whitePost - blackPost, color=col, label=cond, linestyle=style)
            if cond == "swap":
                plt.plot(xPost, blackPost - whitePost, ":", color=col, label="inverse swap")
        plt.legend(frameon=False)

        # Main plots
        i = 1
        for cond in ("constant", "swap", "onset"):
            print "\t%s" % cond
            __dm = _dm.select('cond == "%s"' % cond, verbose=False)
            _dmWhite = __dm.select('saccCol == "white"', verbose=False)
            _dmBlack = __dm.select('saccCol == "black"', verbose=False)
            if zoom:
                ax = plt.subplot2grid((4, 2), (i, 0), colspan=1)
            else:
                ax = plt.subplot2grid((4, 7), (i, 0), colspan=1)
            ax.spines["right"].set_visible(False)
            ax.get_yaxis().tick_left()
            ax.axhline(1.0, linestyle="--", color="black")
            # Draw saccade onsets
            sMin = __dm["flipSDelay"].min()
            sMax = __dm["flipSDelay"].max()
            sMean = __dm["flipSDelay"].mean()
            plt.axvspan(preTraceLen - sMin, preTraceLen - sMax, color=flipSColor, alpha=0.1)
            plt.axvline(preTraceLen - sMean, color=flipSColor, linestyle=flipSStyle)
            tracePlot(__dm, traceParamsPre, suffix=".%s.%s.pre" % (cond, subjectNr), err=True)
            plt.xticks([25], [-150])
            if i < 3:
                ax.get_xaxis().set_ticklabels([])
            if cond == "swap":
                plt.ylabel("Pupil size (norm.)")
            if zoom:
                plt.xlim(preTraceLen - 50, preTraceLen)
                plt.ylim(0.99, 1.05)
                plt.xticks([preTraceLen - 25], [-25])
            else:
                plt.xlim(0, preTraceLen)
                plt.ylim(yMin, yMax)
                plt.xticks([25], [-150])
                # Post-saccade
            if zoom:
                ax = plt.subplot2grid((4, 2), (i, 1), colspan=6)
            else:
                ax = plt.subplot2grid((4, 7), (i, 1), colspan=6)
            ax.spines["left"].set_visible(False)
            plt.axvline(0, linestyle="--", color="black")
            ax.axhline(1.0, linestyle="--", color="black")
            # Title
            plt.text(0.1, 0.9, cond, horizontalalignment="center", verticalalignment="center", transform=ax.transAxes)
            # Draw saccade offsets
            eMin = -__dm["flipEDelay"].min()
            eMax = -__dm["flipEDelay"].max()
            eMean = -__dm["flipEDelay"].mean()
            plt.axvspan(eMin, eMax, color=flipEColor, alpha=0.1)
            plt.axvline(eMean, color=flipEColor, linestyle=flipEStyle)
            tracePlot(__dm, traceParamsPost, suffix=".%s.%s.post" % (cond, subjectNr), err=True)
            if zoom:
                plt.xlim(0, 50)
                plt.ylim(0.99, 1.05)
                plt.xticks([0, 25])
            else:
                plt.xlim(0, postTraceLen)
                plt.ylim(yMin, yMax)
                plt.xticks(range(0, postTraceLen, 150))
            if i == 3:
                plt.xlabel("Time after saccade (ms)")
            if i < 3:
                ax.get_xaxis().set_ticklabels([])
            ax.get_yaxis().tick_right()
            ax.get_yaxis().set_ticklabels([])
            if cond == "constant":
                plt.legend(frameon=False, loc="lower left")
            i += 1
        saveFig("main.subject.%s%s" % (subjectNr, suffix), show=True)
示例#10
0
def latencyCorr(dm):

    """
	Determines the correlation between saccade latency and the latency of the
	PLR.

	Arguments:
	dm		--	DataMatrix
	"""

    dm = dm.addField("saccLat2Bin", dtype=float)
    dm = dm.calcPerc("saccLat2", "saccLat2Bin", keys=["subject_nr"], nBin=10)
    # dm = dm.select('cond == "onset"')
    l = [["subject_nr", "cond", "bin", "saccLat", "t0"]]
    colors = TangoPalette.brightColors[:] * 10
    for _dm in dm.group(["subject_nr", "saccLat2Bin"]):
        for cond in ("constant", "onset"):
            __dm = _dm.select("cond == '%s'" % cond, verbose=False)
            dmWhite = __dm.select('saccCol == "white"', verbose=False)
            xAvg, yAvg, errAvg = TraceKit.getTraceAvg(
                __dm,
                signal="pupil",
                phase="postSacc",
                traceLen=postTraceLen,
                baseline=baseline,
                baselineLock=baselineLock,
            )
            xWhite, yWhite, errWhite = TraceKit.getTraceAvg(
                dmWhite,
                signal="pupil",
                phase="postSacc",
                traceLen=postTraceLen,
                baseline=baseline,
                baselineLock=baselineLock,
            )
            yWhite -= yAvg
            opts = fitCurve(xWhite, yWhite, plot=False)
            t0 = opts[0]
            subject = __dm["subject_nr"][0]
            col = colors[int(subject)]
            saccLat = __dm["saccLat2"].mean()
            _bin = __dm["saccLat2Bin"][0]
            plt.plot(saccLat, t0, "o", color=col)
            l.append([subject, cond, _bin, saccLat, t0])
            print subject, t0, saccLat
    dm = DataMatrix(l)
    dm.save("output/%s/latencyCorr.csv" % exp)
    print dm
    # plt.plot(dm['saccLat'], dm['t0'], '.')
    s, i, r, p, se = linregress(dm["saccLat"], dm["t0"])
    print "r = %.4f, p = %.4f" % (r, p)
    plt.plot(dm["saccLat"], i + s * dm["saccLat"])
    plt.show()

    newFig(size=(4.8, 2.4))
    plt.subplots_adjust(bottom=0.2)
    pmX = PivotMatrix(dm, ["cond", "bin"], ["subject_nr"], "saccLat", colsWithin=True, err="se")
    print pmX

    pmY = PivotMatrix(dm, ["cond", "bin"], ["subject_nr"], "t0", colsWithin=True, err="se")
    print pmY

    xM = np.array(pmX.m[-2, 2:-2], dtype=float)
    xErr = np.array(pmX.m[-1, 2:-2], dtype=float)
    xMConst = xM[: len(xM) / 2]
    xMOnset = xM[len(xM) / 2 :]
    xErrConst = xErr[: len(xErr) / 2]
    xErrOnset = xErr[len(xErr) / 2 :]

    yM = np.array(pmY.m[-2, 2:-2], dtype=float)
    yErr = np.array(pmY.m[-1, 2:-2], dtype=float)
    yMConst = yM[: len(yM) / 2]
    yMOnset = yM[len(yM) / 2 :]
    yErrConst = yErr[: len(yErr) / 2]
    yErrOnset = yErr[len(yErr) / 2 :]

    plt.errorbar(
        xMConst, yMConst, xerr=xErrConst, yerr=yErrConst, label="Constant", capsize=0, color=constColor, fmt="o-"
    )
    plt.errorbar(xMOnset, yMOnset, xerr=xErrOnset, yerr=yErrOnset, label="Onset", capsize=0, color=onsetColor, fmt="o-")
    plt.legend(frameon=False)
    plt.xlabel("Saccade latency (ms)")
    plt.ylabel("PLR latency (ms)")
    saveFig("latencyCorr")

    aov = AnovaMatrix(dm, ["cond", "bin"], "t0", "subject_nr")
    print aov
    aov.save("output/%s/aov.latencyCorr.csv" % exp)
示例#11
0
def corrTrace(dm, soaBehav, soaPupil, dv='correct', suffix='', \
	traceParams=trialParams):

	"""
	Calculates the correlation between the behavioral cuing effect and the
	pupil-size cuing effect.

	Arguments:
	dm			--	A DataMatrix.
	soaBehav	--	The SOA to analyze for the behavioral effect.
	soaPupil	--	The SOA to analyze for the pupil effect.

	Keyword arguments:
	dv			--	The dependent variable to use for the behavioral cuing
					effect. (default='correct')
	suffix		--	A suffix to identify the trace for caching. (default='')

	Returns:
	A 2D numpy array r- and p-values for each sample.
	"""

	assert(soaPupil in dm.unique('soa'))
	assert(soaBehav in dm.unique('soa'))
	dmBehav = dm.select('soa == %d' % soaBehav)
	dmPupil = dm.select('soa == %d' % soaPupil)
	nSubject = dmPupil.count('subject_nr')
	# Determine the trace length and create the trace plot
	traceLen = soaPupil + 105
	traceParams = trialParams.copy()
	traceParams['traceLen'] = traceLen
	# First determine the behavioral cuing effect for each participant
	print 'Determining behavioral cuing effect ...'
	aCuingEffect = np.empty(nSubject)
	for _dm in dmBehav.group('subject_nr'):
		i = _dm['subject_nr'][0]
		aCuingEffect[i] = cuingEffectBehav(_dm, dv=dv)
	print aCuingEffect
	print 'M = %.4f (%.4f)' % (aCuingEffect.mean(), aCuingEffect.std())
	print 'Done'
	# Next create 2 dimensional array with pupil-effect traces for each
	# participant over time
	print 'Creating pupil-effect traces ...'
	aPupilEffect = np.empty( (nSubject, traceLen) )
	for _dm in dmPupil.group('subject_nr'):
		i = _dm['subject_nr'][0]
		print 'Subject %d' % i
		x1, y1, err1 = tk.getTraceAvg(_dm.select('cueLum == "bright"', \
			verbose=False), **traceParams)
		x2, y2, err2 = tk.getTraceAvg(_dm.select('cueLum == "dark"', \
			verbose=False), **traceParams)
		d = y2-y1
		aPupilEffect[i] = d
	print 'Done'
	# Now walk through the pupil-effect array sample by sample and determine
	# the correlation with the behavioral cuing effect.
	print 'Determine correlations ...'
	aStats = np.empty( (traceLen, 2) )
	for i in range(traceLen):
		if stripCorr:
			index, a, b = stripStd(aCuingEffect, aPupilEffect[:,i])
		else:
			a, b = aCuingEffect, aPupilEffect[:,i]
		s, _i, r, p, se = linregress(a, b)
		print 'soaBehav: %d, soaPupil: %d' % (soaBehav, soaPupil)
		print '%d: r = %.4f, p = %.4f (N = %d)' % (i, r, p, len(a))
		aStats[i,0] = r
		aStats[i,1] = p
	print 'Done'
	return aStats