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')
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")
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 fitSwap(dm, suffix='all'):

	"""
	desc: |
		Performs a mixture-model of the swap condition.

	arguments:
		dm:			A DataMatrix,

	keywords:
		suffix:
			desc:	A suffix.
			type:	[str, unicode]

	returns:
		desc: |
			- None if suffix is 'all'
			- Otherwise An (i1, i2) tuple indicating the end of the preparation
			  period and the start of the non-preparation period.
		type:
			[tuple, None]
	"""


	dmSwap = dm.select('cond == "swap"', verbose=False)
	ySwap = getDiffTrace(dmSwap, cacheId='swapDiff%s.%s' % (exp, suffix))
	dmOnset = dm.select('cond == "onset"', verbose=False)
	yOnset = getDiffTrace(dmOnset, cacheId='onsetDiff%s.%s' % (exp, suffix))
	dmConst= dm.select('cond == "constant"', verbose=False)
	yConst = getDiffTrace(dmConst, cacheId='constDiff%s.%s' % (exp, suffix))
	lP = []
	lErr = []
	for i in np.arange(1000):
		y1 = yConst[i]
		y2 = yOnset[i]
		y3 = ySwap[i]
		pBest = None
		errBest = None
		for p in np.linspace(0, 1, 1000):
			y3est = p*-y1 + (1-p)*y2
			err = abs(y3est-y3)
			if errBest == None or err < errBest:
				errBest = err
				pBest = p
		lP.append(pBest)
		lErr.append(errBest)
	aP = np.array(lP)
	fig = newFig(size=flat)
	plt.ylim(-.1, 1.1)
	plt.axhline(0, linestyle=':', color='black')
	plt.axhline(1, linestyle=':', color='black')
	plt.yticks(np.linspace(0,1,6))
	plt.ylabel('Preparation index')
	plt.xlabel('Time relative to display change (ms)')
	if suffix == 'all':
		# Values hard-coded based on fitSwapAll() output
		plt.axvspan(352.50-1.96*13.22, 352.50+1.96*13.22, color=brown[1],
			alpha=.1)
		plt.axvline(352.50, color=brown[1], linestyle='--')
	else:
		lRoi = TraceKit.markStats(plt.gca(), aP, thr=.5, below=False,
			color=green[0])
		if len(lRoi) != 1:
			i1 = np.nan
		else:
			i1 = lRoi[0][1]
		lRoi = TraceKit.markStats(plt.gca(), aP, thr=.5, below=True, color=red[0])
		if len(lRoi) != 1:
			i2 = np.nan
		else:
			i2 = lRoi[0][0]
	plt.plot(aP, color=blue[1])
	saveFig('fitSwap/%s' % suffix)
	if suffix != 'all':
		return i1, i2
def posTracePlots(dm, signal="x"):

    """
	Analyzes the position traces. Most useful to see whether the eyes gravitate
	towards the saccade side before the actual saccade.

	Arguments:
	dm		--	DataMatrix

	Keyword arguments:
	signal	--	Indicates the trace signal. (default='x')
	"""

    for subjectNr in ["all"] + dm.unique("subject_nr"):
        print baseline, subjectNr
        if subjectNr == "all":
            _dm = dm
        else:
            _dm = dm.select("subject_nr == %d" % subjectNr, verbose=False)

        fig = newFig(size=(12, 4))
        plt.subplots_adjust(wspace=0)
        # Select DataMatrices
        _dmLeft = _dm.select('saccSide == "left"', verbose=False)
        _dmRight = _dm.select('saccSide == "right"', verbose=False)
        # Get stats
        if subjectNr == "all":
            aStatsPre = np.load("stats/%s/x.pre.npy" % exp)
            print "First significant: %s" % np.where(aStatsPre[:, 0] < 0.05)[0]
            aErrLeft, aErrRight, aDiff = errorTrace(aStatsPre, _dmLeft, _dmRight, phase="cue", signal="x")
        else:
            aErrLeft, aErrRight, aDiff = None, None, None
            # Pre-saccade
        ax = plt.subplot2grid((1, 7), (0, 0), colspan=1)
        plt.axhline(384, linestyle="--", color="black")
        plt.ylim(0, 1024)
        plt.xlim(0, preTraceLen)
        plt.xticks(range(0, preTraceLen, 50), range(-preTraceLen, 1, 50))

        if subjectNr == "all":
            TraceKit.markStats(ax, aStatsPre[:, 0], minSmp=1)
        TraceKit.plotTraceAvg(
            ax,
            _dmLeft,
            signal=signal,
            aErr=aErrLeft,
            phase="cue",
            lock="end",
            traceLen=preTraceLen,
            lineColor=brightColor,
            errColor=brightColor,
        )
        TraceKit.plotTraceAvg(
            ax,
            _dmRight,
            signal=signal,
            aErr=aErrRight,
            phase="cue",
            lock="end",
            traceLen=preTraceLen,
            lineColor=darkColor,
            errColor=darkColor,
        )

        # Post-saccade
        ax = plt.subplot2grid((1, 7), (0, 1), colspan=6)
        plt.axhline(384, linestyle="--", color="black")
        plt.ylim(0, 1024)
        plt.xlim(0, postTraceLen)
        plt.xticks(range(0, postTraceLen, 50))
        plt.yticks([])

        TraceKit.plotTraceAvg(
            ax,
            _dmLeft,
            signal=signal,
            phase="postSacc",
            traceLen=postTraceLen,
            lineColor=brightColor,
            errColor=brightColor,
        )
        TraceKit.plotTraceAvg(
            ax,
            _dmRight,
            signal=signal,
            phase="postSacc",
            traceLen=postTraceLen,
            lineColor=darkColor,
            errColor=darkColor,
        )
        saveFig("%s.posTrace.%s" % (signal, subjectNr), show=True)