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')
def pupilDiffPlotSubject(dm):

	"""
	desc:
		Creates the overall pupil-size plot for switch-to-bright and
		switch-to-dark rounds, separately for each subject.

	arguments:
		dm:
			desc:	A DataMatrix.
			type:	DataMatrix
	"""

	i = 0
	Plot.new(size=Plot.s)
	for subject_nr, _dm in dm.walk('subject_nr'):
		t = 'pp %s (N=%d)' % (subject_nr, len(_dm))
		print(t)
		pupilDiffPlot(_dm, label=str(subject_nr))
		i += 1
	plt.axvline(dm['endInvertTime'].mean(), color='black', linestyle='--')
	plt.axvline(dm['endAdaptationTime'].mean(), color='black', linestyle='--')
	plt.axhline(0, color='black', linestyle='-')
	plt.xlabel('Time since round start (ms)')
	plt.ylabel('Mean pupil area')
	plt.xlim(0, traceLen)
	plt.legend(frameon=False)
	Plot.save('pupilDiffPlotSubject', show=show)
def crossExpContour(dm):

	"""
	desc:
		Plots a multipanel contour plot depicting the correlation between
		pupil size and fixation saliency for each experiment.

	arguments:
		dm:
			type:	DataMatrix
	"""

	assert(constants.exp == 'exp1')
	Plot.new(constants.bigPlot)
	plt.subplot(221)
	simpleContour(dm, title='Exp. 1')
	constants.exp = 'exp2'
	dm = helpers.getDataMatrix(cacheId='data.%s' % constants.exp)
	dm = helpers.filter(dm, cacheId='filter.%s' % constants.exp)
	plt.subplot(222)
	simpleContour(dm, title='Exp. 2')
	constants.exp = 'exp3'
	dm = helpers.getDataMatrix(cacheId='data.%s' % constants.exp)
	dm = helpers.filter(dm, cacheId='filter.%s' % constants.exp)
	plt.subplot(223)
	simpleContour(dm.select('cond == "single"'), title='Exp. 3 single')
	plt.subplot(224)
	simpleContour(dm.select('cond == "dual"'), title='Exp. 3 dual')
	Plot.save('correlationPlot', folder='crossExp', show=constants.show)
def exp1RegressionPlot(dm):
	
	"""
	desc:
		Creates a demo plot in which fixation saliency is shown as a function
		of pupil size.
		
	arguments:
		dm:
			type:	DataMatrix.		
	"""

	Plot.new(size=smallPlot)
	lX = []
	lY = []
	for _dm in dm.group('b__pupilSize'):	
		lX.append(_dm['_pupilSize'].mean())
		lY.append(_dm['salFrom'].mean())
		
	aX = np.array(lX)
	aY = np.array(lY)
	plt.plot(aX, aY, 'o-', color=exp1Col)
	plt.xlabel('Pupil diameter (Z score)')
	plt.ylabel('Fixation saliency (arbitrary units)')
	plt.xlim(-2, 2)
	plt.xticks([-2, -1, 0, 1, 2])
	plt.ylim(14, 20)
	Plot.save('exp1RegressionPlot', folder='exp1')
def windowPlot(dm, standalone=True, color=blue[1], label=None):

    """
	desc:
		Creates a graph in which the effect of pupil size on saliency is shown
		separately for each temporal displacement. I.e. the effect of pupil size
		on trial N on saliency on trial N+1, etc.

	arguments:
		dm:
			type:	DataMatrix

	keywords:
		standalone:
			desc:	Indicates whether this is a standalone plot, in which case
					it will create and save the plot, or not.
			type:	bool
		color:
			desc:	Plot color.
			type:	[str, unicode]
		label:
			desc:	Line label.
			type:	[str, unicode]
	"""

    if standalone:
        Plot.new(widePlot)
    dm = dm.intertrialer(["file", "trialId", "saccNr"], "salFrom", _range=windowRange)
    xData = []
    yData = []
    eData = []
    for r in windowRange:
        if r == 0:
            _dv = "salFrom"
        elif r < 0:
            _dv = "salFrom_m%d" % (-1 * r)
        else:
            _dv = "salFrom_p%d" % r
        print "dv = %s" % _dv
        s, t, lo, up = stats.effectSlope(dm, dv=_dv)
        print s
        xData.append(r)
        yData.append(s)
        eData.append([lo, up])
    xData = np.array(xData)
    yData = np.array(yData)
    eData = np.array(eData)
    plt.fill_between(xData, eData[:, 0], eData[:, 1], color=color, alpha=0.1)
    plt.plot(windowRange, yData, "o-", color=color, label=label)
    plt.axhline(linestyle="--", color="black")
    plt.xlabel("Pupil-size timepoint relative to saliency timepoint")
    plt.xticks(windowRange)
    plt.xlim(windowRange[0], windowRange[-1])
    plt.ylabel("Partial slope")
    plt.yticks(slopeTicks[exp])
    plt.ylim(slopeLim[exp])
    if standalone:
        Plot.save("windowPlot", folder=exp, show=show)
def trialPlot(dm, soa, _show=show, err=True, minSmp=200, suffix='', padding=0,
	diff=True):

	"""
	A pupil-trace plot for the full trial epoch.

	Arguments:
	dm				--	A DataMatrix.
	soa				--	The SOA to select.

	Keyword arguments:
	_show			--	Indicates whether the plot should be shown.
						(default=True)
	err				--	Indicates whether error bars should be drawn.
						(default=True)
	suffix			--	A suffix to identify the trace. (default='')
	padding			--	A padding time to be added to the traceLen. (default=0)
	diff			--	Indicates whether the difference trace should be plotted
						as well. (default=True)
	"""

	assert(soa in dm.unique('soa'))
	if _show:
		Plot.new(size=Plot.ws)
		plt.title('SOA: %d ms' % (soa+55))
	plt.axhline(1, linestyle='--', color='black')
	dm = dm.select('soa == %d' % soa)
	# Determine the trace length and create the trace plot
	traceLen = soa + 105 + padding
	traceParams = trialParams.copy()
	traceParams['traceLen'] = traceLen
	tracePlot(dm, traceParams=traceParams, err=err, suffix='.%d%s' % (soa, \
		suffix), minSmp=minSmp)
	# Cue
	plt.axvspan(0, cueDur, color=blue[1], alpha=.2)
	# Target. Take into account to cue duration in determining the target onset.
	targetOnset = soa+55
	plt.axvspan(targetOnset, targetOnset+targetDur, color=blue[1], alpha=.2)
	plt.xlim(0, 2550)
	plt.legend(frameon=False)
	plt.xlabel('Time since cue onset (ms)')
	plt.ylabel('Pupil size (norm.)')
	plt.yticks([1,1.025, 1.05])
	plt.xticks(range(0, 2501, 500))
	if diff:
		plt.ylim(.92, 1.07)
		plt.axhline(diffY, linestyle='--', color='black')
		plt.twinx()
		plt.tick_params(axis="y")
		plt.ylim(.92, 1.07)
		plt.yticks([.925,.95, .975], [-.025, 0, .025])
	else:
		plt.ylim(.98, 1.07)
	if _show:
		Plot.save('trialPlot.%d' % soa, 'trialPlot', show=show)
def splitHalfReliabilityBehav(dm, soa=2445, dv='response_time', n=10000):

	"""
	Tests the split-half reliability of the behavioral cuing effect at the peak
	sample.

	Arguments:
	dm		--	A DataMatrix.

	Keyword arguments:
	soa		--	The SOA. (default=2445)
	dv		--	The dependent variable to use. (default='correct')
	n		--	The number of runs. (default=1000)
	"""

	@cachedArray
	def corrArray(dm, soa, dv, n):
		import time
		lR = []
		t0 = time.time()
		for i in range(n):
			l1 = []
			l2 = []
			for _dm in dm.group('subject_nr'):
				_dm.shuffle()
				dm1 = _dm[:len(_dm)/2]
				dm2 = _dm[len(_dm)/2:]
				ce1 = cuingEffectBehav(dm1, dv=dv)
				ce2 = cuingEffectBehav(dm2, dv=dv)
				l1.append(ce1)
				l2.append(ce2)
			s, j, r, p, se = linregress(l1, l2)
			print '%d (%d s): r = %.4f, p = %.4f' % (i, time.time()-t0, r, p)
			lR.append(r)
		return np.array(lR)

	assert(soa in dm.unique('soa'))
	dm = dm.select('soa == %d' % soa)
	Plot.new(size=(3,3))
	a = corrArray(dm, soa, dv, n, cacheId='corrArrayBehav.%s' % dv)
	a.sort()
	ci95up = a[np.ceil(.975 * len(a))]
	ci95lo = a[np.floor(.025 * len(a))]
	s = 'M = %.2f, P(r > 0) = %.2f, 95%%: %.2f - %.2f' % (a.mean(),
		np.mean(a > 0), ci95lo, ci95up)
	print s
	plt.hist(a, bins=n/10, color=blue[1])
	plt.title(s)
	plt.axvline(0, color='black')
	plt.xlim(-1, 1)
	plt.xlabel('Split-half correlation (r)')
	plt.ylabel('Frequency (N)')
	Plot.save('splitHalfReliability.behav.%s' % dv, folder='corrAnalysis',
		show=show)
def respLockPlot(dm, soa, _show=True, err=True, suffix=''):

	"""
	Generates a response-locked pupil-trace plot.

	Arguments:
	dm		--	A DataMatrix.
	soa		--	The SOA to analyze.

	Keyword arguments:
	_show			--	Indicates whether the plot should be shown.
						(default=True)
	err				--	Indicates whether error bars should be drawn.
						(default=True)
	suffix			--	A suffix to identify the trace. (default='')
	"""

	assert(soa in dm.unique('soa'))
	if _show:
		Plot.new(size=Plot.ws)
		plt.title('SOA: %d ms%s' % (soa+55, suffix))
	dm = dm.select('soa == %d' % soa)
	# Recoding target luminance
	print 'Recoding target luminance ...'
	dm = dm.addField('targetLum', dtype=str)
	for i in dm.range():
		if (dm['cueLum'][i] == 'bright' and dm['cueValidity'][i] == 'valid') \
			or (dm['cueLum'][i] == 'dark' and dm['cueValidity'][i] == \
			'invalid'):
			dm['targetLum'][i] = 'bright'
		else:
			dm['targetLum'][i] = 'dark'
	print 'Done'
	# Draw lines
	plt.axhline(1, linestyle='--', color='black')
	plt.axvline(dm['response_time'].mean(), linestyle='--', color='black')
	# Determine the trace length and create the trace plot
	traceParams = respLockParams.copy()
	traceParams['offset'] = soa+55
	tracePlot(dm, traceParams=traceParams, err=False, suffix='.respLock.%d%s' \
		% (soa, suffix), lumVar='targetLum')
	# Target
	plt.axvspan(0, targetDur, color=blue[1], alpha=.2)
	plt.xlim(0, traceParams['traceLen'])
	plt.legend(frameon=False)
	plt.xlabel('Time since target onset (ms)')
	plt.ylabel('Pupil size (norm.)')
	plt.ylim(.95, 1.4)
	plt.yticks([1, 1.1, 1.2, 1.3])
	plt.xticks(range(0, 1501, 250))
	if _show:
		Plot.save('respLockPlot.%d%s' % (soa, suffix), 'respLock', show=show)
def pilotgraph(data, name, xlabel):

	Plot.new(size=(3,3))
	x = -.4
	xticks = []
	for key, rt, se in data:
		xticks.append(key)
		plt.bar(x, rt-rt_adjust, color=blue[1])
		plt.errorbar(x+.4, rt-rt_adjust, se, color='black', capsize=0)
		x += 1
	plt.xlim(-.7, x+.2)
	plt.xticks(range(len(data)), xticks)
	plt.xlabel(xlabel)
	plt.ylabel('Response time (s)')
	plt.ylim(0, 25)
	Plot.save(name, folder='pilot')
def subjectDiffPlot(dm):

	"""
	Creates a line plot of the pupil effect separately for each subject.

	Arguments:
	dm		--	A DataMatrix.
	"""

	Plot.new(size=Plot.w)
	colors = brightColors * 10
	for _dm in dm.group('subject_nr'):
		print 'Subject %d' % _dm['subject_nr'][0]
		traceDiffPlot(_dm, color=colors.pop())
	plt.axhline(0, linestyle='--', color='black')
	Plot.save('subjectDiffPlot', 'subject', show=show)
def pupilPlotExample(dm):

	"""
	desc:
		Creates the overall pupil-size plot for switch-to-bright and
		switch-to-dark rounds for participant 10.

	arguments:
		dm:
			desc:	A DataMatrix.
			type:	DataMatrix
	"""

	dm = dm.select('subject_nr == 10')
	Plot.new(size=Plot.s)
	pupilPlot(dm)
	Plot.save('pupilPlotExample', show=show)
def corrPlot(dm, soaBehav, soaPupil, suffix=''):

	"""
	Plots and analyzes the correlation between the cuing effect in behavior and
	pupil size.

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

	Keyword arguments:
	suffix		--	A suffix for the plot filename. (default='')
	"""

	if stripCorr:
		suffix += '.stripCorr'
	Plot.new(size=Plot.ws)
	plt.title('SOA: %d ms (behavior), %d ms (pupil)' % (soaBehav+55, \
		soaPupil+55))
	plt.ylim(-.2, 1)
	plt.xlabel('Time since cue onset (ms)')
	plt.ylabel('Behavior - pupil correlation (r)')
	plt.axhline(0, linestyle='--', color='black')
	# Cue shading
	plt.axvspan(0, cueDur, color=blue[1], alpha=.2)
	# Target shading
	targetOnset = soaPupil+55
	plt.axvspan(targetOnset, targetOnset+targetDur, color=blue[1], alpha=.2)
	plt.xlim(0, 2550)
	# Accuracy
	a = corrTrace(dm, soaBehav, soaPupil, dv='correct', suffix='acc', \
		cacheId='corrTrace.correct.%d.%d%s' % (soaBehav, soaPupil, suffix))
	tk.markStats(plt.gca(), a[:,1])
	plt.plot(a[:,0], label='Accuracy', color=blue[1])
	# RTs
	a = corrTrace(dm, soaBehav, soaPupil, dv='response_time', suffix='rt', \
		cacheId='corrTrace.rt.%d.%d%s' % (soaBehav, soaPupil, suffix))
	tk.markStats(plt.gca(), a[:,1])
	tk.markStats(plt.gca(), a[:,1], color='red')
	plt.plot(a[:,0], label='Response times', color=orange[1])
	plt.legend(frameon=False, loc='upper left')
	Plot.save('corrAnalysis.%d.%d%s' % (soaBehav, soaPupil, suffix),
		'corrAnalysis', show=show)
def subjectPlot(dm):

	"""
	Generates a separate trial plot for each subject.

	Arguments:
	dm		--	A DataMatrix.
	"""

	Plot.new(size=Plot.xl)
	i = 1
	for _dm in dm.group('subject_nr'):
		subject_nr = _dm['subject_nr'][0]
		N = len(_dm)
		plt.subplot(np.ceil(dm.count('subject_nr')/4.), 5, i)
		plt.title('%s (%d)' % (subject_nr, N))
		trialPlot(_dm, 2445, _show=False, err=False, suffix='.subject%.2d' % \
			subject_nr)
		i += 1
	Plot.save('subjectPlot', 'subject', show=show)
def exp2InstructionPlot(dm):

	"""
	desc:
		Plots the effect of pupil size on saliency for different task
		instructions.

	arguments:
		dm:
			type:	DataMatrix
	"""

	assert(exp == 'exp2')
	Plot.new(size=smallPlot)
	for color, fmt, sceneType in [(fractalCol, 'o-', 'fractal'),
		(sceneCol, 's:', 'scene')]:
		lSlope = []
		if sceneType == 'fractal':
			x = -.1
		else:
			x = .1
		lX = []
		for inst in ['free', 'search', 'memory']:
			lX.append(x)
			_dm = dm.select('inst == "%s"' % inst).select(
				'sceneType == "%s"' % sceneType)
			s, t, lo, up = stats.effectSlope(_dm)
			lSlope.append(s)
			plt.plot([x, x], [lo, up], '-', color=color)
			x += 1
		plt.plot(lX, lSlope, fmt, color=color, label=sceneType.capitalize()+'s')
	plt.xticks(range(0,3), ['Free', 'Search', 'Memory'])
	plt.yticks([0, 2, 4, 6])
	plt.ylabel('Partial slope')
	plt.xlabel('Task')
	plt.xlim(-.5, 2.5)
	plt.ylim(slopeLim)
	plt.axhline(0, color='black', linestyle='--')
	plt.legend(frameon=False, loc='upper left')
	Plot.save('instructionPlot', folder=exp, show=show)
def exp3SaccadePlot(dm):

	"""
	desc:
		Creates a saccade plot with the different task conditions as individual
		lines.

	arguments:
		dm:
			type:	DataMatrix
	"""

	from analysis import helpers
	dmSingle = dm.select('cond == "single"')
	dmDual = dm.select('cond == "dual"')
	Plot.new(widePlot)
	helpers.saccadePlot(dmSingle, standalone=False, color=exp3SingleCol,
		label='Single task')
	helpers.saccadePlot(dmDual, standalone=False, color=exp3DualCol,
		label='Dual task')
	plt.legend(frameon=False)
	Plot.save('saccadePlot.task', folder=exp, show=show)
def crossExpWindowPlot(dm):

	"""
	desc:
		Creates a window plot with the Exp. 1 and 2 as individual lines.

	arguments:
		dm:
			type:	DataMatrix
	"""

	assert(constants.exp == 'exp1')
	Plot.new(constants.widePlot)
	helpers.windowPlot(dm, standalone=False, color=constants.exp1Col,
		label='Exp. 1')
	constants.exp = 'exp2'
	dm = helpers.getDataMatrix(cacheId='data.%s' % constants.exp)
	dm = helpers.filter(dm, cacheId='filter.%s' % constants.exp)
	helpers.windowPlot(dm, standalone=False, color=constants.exp2Col,
		label='Exp. 2')
	plt.legend(frameon=False)
	Plot.save('windowPlot', folder='crossExp', show=constants.show)
def pupilPlotSubject(dm):

	"""
	desc:
		Creates the overall pupil-size plot for switch-to-bright and
		switch-to-dark rounds, separately for each subject.

	arguments:
		dm:
			desc:	A DataMatrix.
			type:	DataMatrix
	"""

	i = 0
	Plot.new(Plot.xl)
	for subject_nr, _dm in dm.walk('subject_nr'):
		t = 'pp %s (N=%d)' % (subject_nr, len(_dm))
		print(t)
		plt.subplot(2, dm.count('subject_nr')/2, i)
		plt.title(t)
		pupilPlot(_dm)
		i += 1
	Plot.save('pupilPlotSubject', show=show)
def corrExample(dm, soaBehav, soaPupil, dv='correct', suffix=''):

	"""
	Plots an example of the correlation between behavior and pupil size at the
	most strongly correlating point.

	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 effect.
					(default='correct')
	suffix		--	A filename suffix.
	"""

	assert(soaPupil in dm.unique('soa'))
	assert(soaBehav in dm.unique('soa'))
	if stripCorr:
		suffix += '.stripCorr'
	a = corrTrace(dm, soaBehav, soaPupil, dv='correct', suffix='acc', \
		cacheId='corrTrace.correct.%d.%d%s' % (soaBehav, soaPupil, suffix))
	bestSample = np.argmax(a[:,0])
	dmBehav = dm.select('soa == %d' % soaBehav)
	dmPupil = dm.select('soa == %d' % soaPupil)
	xData = []
	yData = []
	print 'pp\tbehav\tpupil'
	for subject_nr in dm.unique('subject_nr'):
		ceb = cuingEffectBehav(dmBehav.select('subject_nr == %d' \
			% subject_nr, verbose=False), dv=dv)
		cep = cuingEffectPupil(dmPupil.select('subject_nr == %d' \
			% subject_nr, verbose=False), epoch=(bestSample, \
			bestSample+winSize))
		print '%.2d\t %.4f\t%.4f' % (subject_nr, ceb, cep)
		yData.append(100.*ceb)
		xData.append(cep)
	if stripCorr:
		index, xData, yData = stripStd(np.array(xData), np.array(yData))
	Plot.new(size=(3,3))
	plt.title('SOA: %d ms (behavior), %d ms (pupil)' % (soaBehav+55, \
		soaPupil+55))
	Plot.regress(xData, yData)
	plt.text(0.05, 0.90, 'Sample = %d' % bestSample, ha='left', \
			va='top', transform=plt.gca().transAxes)
	plt.axhline(0, linestyle='--', color='black')
	plt.axvline(0, linestyle='--', color='black')
	plt.plot(xData, yData, 'o', color='black')
	plt.ylabel('Behav. cuing effect (%)')
	plt.xlabel('Pupil cuing effect (norm.)')
	Plot.save('corrExample.%d.%d%s' % (soaBehav, soaPupil, suffix),
		'corrAnalysis', show=show)
def saccadePlot(dm, standalone=True, color=blue[1], label=None):

    """
	desc:
		Creates a graph in which the effect of pupil size on saliency is shown
		separately for each saccade in a trial.

	arguments:
		dm:
			desc:	Data
			type:

	keywords:
		standalone:
			desc:	Indicates whether this is a standalone plot, in which case
					it will create and save the plot, or not.
			type:	bool
		color:
			desc:	Plot color.
			type:	[str, unicode]
		label:
			desc:	Line label.
			type:	[str, unicode]
	"""

    if standalone:
        Plot.new(size=widePlot)
    xData = []
    yData = []
    eData = []
    for saccNr in [None] + range(1, maxSacc + 1):
        if saccNr == None:
            _dm = dm
        else:
            _dm = dm.select("saccNr == %d" % saccNr)
        s, p, lo, up = stats.effectSlope(_dm)
        if saccNr == None:
            if standalone:
                x = -1
            elif exp == "exp1":
                x = -1.2
            else:
                x = -0.8
            plt.errorbar(x, s, yerr=[[s - lo], [up - s]], capsize=0, fmt="o-", color=color)
        else:
            xData.append(saccNr)
            yData.append(s)
            eData.append([lo, up])
    xData = np.array(xData)
    yData = np.array(yData)
    eData = np.array(eData)
    plt.fill_between(xData, eData[:, 0], eData[:, 1], color=color, alpha=0.1)
    plt.plot(xData, yData, "o-", color=color, label=label)
    plt.axhline(0, linestyle="--", color="black")
    plt.xlabel("Saccade number")
    plt.xlim(-2, maxSacc + 1)
    plt.xticks([-1] + range(1, 21), ["Full"] + range(1, 21))
    plt.ylabel("Partial slope")
    plt.yticks(slopeTicks[exp])
    plt.ylim(slopeLim[exp])
    if standalone:
        Plot.save("saccadePlot", folder=exp, show=show)
Beispiel #20
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)
Beispiel #21
0
	def finishTrial(self, trialDict):

		"""
		desc:
			Performs post-trial initialization.

		arguments:
			trialDict:
				desc:	Trial information.
				type:	dict
			l:
				desc:	A whitespace-splitted line of data.
				type:	list
		"""

		print 'nFixLost: %(nFixLost)d, maxFixErr = %(maxFixErr).2f' % trialDict
		trialDict['rt'] = self.endTime - self.startTime
		trialDict['correct'] = self.correct # Get the correct correct
		trialDict['endInvertTime'] = np.mean(self.endInvertTime)
		trialDict['endAdaptationTime'] = np.mean(self.endAdaptationTime)
		trialDict['endCollectionTime'] = np.mean(self.endCollectionTime)
		trialDict['endRoundTime'] = np.mean(self.endRoundTime)
		path = 'likelihood/%s-%.4d.pickle' % (trialDict['file'],
			trialDict['trialId'])
		trialDict['__likelihood__'] = path
		pickle.dump(self.likelihoodTraces, open(path, 'w'))

		# Determine the mean vector of the fixations
		fax = np.mean([xy[0] for xy in self.fixList])
		fay = np.mean([xy[1] for xy in self.fixList])
		fdx = fax - xc
		fdy = fay - yc
		fa = np.degrees(np.arctan2(fdy, fdx))
		fr = np.sqrt(fdx**2 + fdy**2)
		# Determine the vector of the target
		tx = trialDict['targetX']
		ty = trialDict['targetY']
		tdx = tx - xc
		tdy = ty - yc
		ta = np.degrees(np.arctan2(tdy, tdx))
		tr = np.sqrt(tdx**2 + tdy**2)
		# Determine the vector error
		errA = ta-fa
		if errA < 0:
			errA += 360
		trialDict['errA'] = errA
		trialDict['errR'] = fr
		s = 'Vector: r = %.2f, d(a) = %.2f' % (fr, errA)
		print s
		if '--plot' in sys.argv:
			Plot.new()
			plt.title(s)
			plt.xlim(0, 1280)
			plt.ylim(0, 1024)
			plt.axvline(xc, linestyle='--', color='black')
			plt.axhline(yc, linestyle='--', color='black')
			for x, y in self.fixList:
				plt.plot(x, y, '.', color=blue[1])
			plt.plot(tx, ty, 'o', color=orange[1])
			plt.plot([xc, xc+fdx], [yc, yc+fdy], color=blue[1])
			plt.plot([xc, xc+tdx], [yc, yc+tdy], color=orange[1])
			plotName = '%s-%d' % (trialDict['file'], trialDict['trialId'])
			Plot.save(plotName)
def lmeBehavior(dm, suffix=''):

	"""
	Analyzes the behavioral data with mixed effects.

	Arguments:
	dm		--	A DataMatrix.
	
	keywords:
	suffix	--	A filename suffix.
	"""

	global R
	try:
		R
	except:
		R = RBridge()

	i = 1
	Plot.new(size=Plot.ws)
	for dv in ['correct', 'irt']:
		# Also analyze the grouped 945 and 2445 SOAs, which gives more power
		# than analyzing them separately.
		R.load(dm.select('soa != 45'))
		lm = R.lmer('%s ~ cueValidity * soa + (1|subject_nr)' % dv)
		lm.save('output/lmeBehavior.longInteract.%s.csv' % dv)
		lm._print(title='Long: %s' % dv, sign=10)
		lm = R.lmer('%s ~ cueValidity + (1|subject_nr)' % dv)
		lm.save('output/lmeBehavior.longNoInteract.%s.csv' % dv)
		lm._print(title='Long: %s' % dv, sign=10)
		# Loop over SOAs
		lSoa = []
		lVal = []
		lInv = []
		for soa in [45, 945, 2445]:
			_dm = dm.select('soa == %d' % soa, verbose=False)
			R.load(_dm)
			lm = R.lmer('%s ~ cueValidity + (1|subject_nr)' % dv)
			lm.save('output/lmeBehavior.%s.%s.csv' % (dv, soa))
			lm._print(title='%s (%s)' % (dv, soa), sign=10)
			mInv = lm['est'][0] # Invalid is reference
			mVal = mInv + lm['est'][1] #4Add slope for validity effect
			d = lm['est'][1]
			m = mInv + .5*d
			minD = d - lm['se'][1]
			maxD = d + lm['se'][1]
			# Determine error bars based on the slope CIs
			cInv = [m-minD/2, m-maxD/2]
			cVal = [m+minD/2, m+maxD/2]
			if dv == 'irt':
				mVal = 1./mVal
				mInv = 1./mInv
				cInv = [1./cInv[0], 1./cInv[1]]
				cVal = [1./cVal[0], 1./cVal[1]]
			else:
				mVal = 100.*mVal
				mInv = 100.*mInv
				cInv = [100.*cInv[0], 100.*cInv[1]]
				cVal = [100.*cVal[0], 100.*cVal[1]]
			# We plot the errorbars separately, because it's a bit easier than
			# passing them onto `plt.errorbar()`.
			plt.plot([soa+55, soa+55], cVal, '-', color=valColor)
			plt.plot([soa+55, soa+55], cInv, '-', color=invColor)
			lSoa.append(soa+55)
			lVal.append(mVal)
			lInv.append(mInv)
		plt.xlim(-100, 2750)
		plt.xticks([100, 1000, 2500])
		plt.xlabel('Cue-target interval (ms)')
		if dv == 'irt':
			plt.ylabel('Respone time (ms)')
			plt.ylim(420, 630)
			plt.yticks([450, 500, 550, 600])
		else:
			plt.ylabel('Accuracy (%)')
			plt.ylim(80, 95)
			plt.yticks([82.5, 85, 87.5, 90, 92.5])
		i += 1
		nVal = len(dm.select('cueValidity == "valid"', verbose=False))
		nInv = len(dm.select('cueValidity == "invalid"', verbose=False))
		plt.plot(lSoa, lVal, 'o-', color=valColor, label='Valid (N=%d)' % nVal)
		plt.plot(lSoa, lInv, 'o-', color=invColor, label='Invalid (N=%d)' % \
			nInv)
		plt.legend(frameon=False)
	Plot.save('behavior%s' % suffix, 'behavior', show=show)
print('Phase 3:', itr(28.0483, 8., 0.8761))
print('Phase 4 (raw):', itr(51.0775291309, 30., None))
print('Phase 4 (use):', itr(75.2328265173, 30., None))

def itrPhase(phase, N):
	a = np.loadtxt('phase%d.csv' % phase, delimiter=',')
	abr = np.zeros(a.shape[0])
	for i in range(a.shape[0]):
		rt = a[i,0]
		P = a[i,1]
		abr[i] = itr(rt, N, P)
	print('Phase 1: Mean ITR: %.2f' % abr.mean())
	print(abr)
	return abr, abr.mean(), abr.std()

Plot.new(size=Plot.xs)

a, m, sd = itrPhase(1, 2)
print(m)
plt.bar(0, m, width=.5, color=blue[1])
plt.plot([.25] * 10, a, 'o', color=green[2])

a, m, sd = itrPhase(2, 4)
print(m)
plt.bar(1, m, width=.5, color=blue[1])
plt.plot([1.25] * 9, a, 'o', color=green[2])

a, m, sd = itrPhase(3, 8)
print(m)
plt.bar(2, m, width=.5, color=blue[1])
plt.plot([2.25] * 9, a, 'o', color=green[2])