# -*- coding: utf-8 -*- """ Created on Tue Oct 14 18:11:07 2014 @author: Geoffrey """ # -*- coding: utf-8 -*- """ Created on Wed Oct 08 15:35:11 2014 @author: c1248317 """ import sys pack_path = "D:/Google Drive/Work/Experiences/EyeTracking" sys.path.insert(0, pack_path) output_path = "D:/Google Drive/Work/Experiences/experiment-deviation-initial/img" seq_path = "D:/Experience-EyeTrackerData/experiment-deviation-initial/output-seq.h5" traj_path = "D:/Experience-EyeTrackerData/experiment-deviation-initial/output.h5" import os os.chdir(pack_path) from eyetools import util_old as util os.chdir(output_path) import numpy as np import pandas as pd import matplotlib from matplotlib import cm from scipy.interpolate import interp1d import matplotlib.patches as patches import matplotlib.pyplot as plt matplotlib.rcParams.update({'font.size': 18}) plt.ioff() import pickle #m = pickle.load( open( "save_traj.p", "rb" ) ) m = pickle.load( open(output_path+"/traj_and_RT_second_only.p", "rb" ) ) offset_control_second = m["offset_control"] back_color = "#3C3C3C" xmin, xmax = -800, 800 ymin, ymax = -800, 800 directions_toplot = np.array([15.0, 30.0]) cv = matplotlib.colors.ColorConverter() rc = np.array(m["rectangle_tol"]) def distLinePoint(p1, p2, p3): ## p3 is the point, p1 to p2 is the line """Give the distance between a point p3 and a line defined by p1 and p2. The distance is negative if the point above or on the left of the line""" v_ortho = np.array((-(p1[1]-p2[1]),p1[0]-p2[0]))[np.newaxis,:] ## v = (x0 - x1, y1 - y0) v_hypotenus = np.array(p3) - np.array(p1)[np.newaxis,:] ## we could have done p3 - p2 or p1 - p3, does not matter distance = np.dot(v_ortho, v_hypotenus.T) / np.sqrt(v_ortho.dot(v_ortho.T)) #print distance return -distance cmap1 = cm.get_cmap('autumn') cmap2 = cm.get_cmap('cool') def plotDeviation(data, xlabel, ylabel, ax, lcolor, aligned=(False, False), time_normed=False): nb = data["trial ID"].iloc[0] lcolor = cmap1(float(nb)/(800)) if lcolor=="r" else cmap2(float(nb)/(800)) if data["trial ID"].iloc[0] % 5 != 0: return pd.DataFrame(columns = ["time", "deviation"]) else: print data["trial ID"].iloc[0] if time_normed==True: f = interp1d(data[xlabel].values, data[ylabel].values, kind= "linear") norm_time = np.linspace(data[xlabel].min(),data[xlabel].max(), 100) #print f(norm_time).shape, np.arange(100)[:,np.newaxis].shape new_data = np.hstack((np.arange(100)[:,np.newaxis],f(norm_time)[:,np.newaxis])) ax.plot(new_data[:,0], new_data[:,1], color = lcolor, lw=3.0, alpha=0.9) return pd.DataFrame(new_data, columns = ["time", "deviation"]) else: x = data[xlabel] - aligned[0]*data[xlabel].iloc[0] y = data[ylabel] - aligned[1]*data[ylabel].iloc[0] #ax.scatter(x, y, color = lcolor, lw=1.0, alpha=0.9) ax.plot(x, y, color = lcolor, lw=2.5, alpha=0.7) return pd.DataFrame([x,y], columns = ["time", "deviation"]) def plotAllTraj(ax, traj, direction, xlabel, ylabel, aligned=(False, False)): select = util.selectByHalfDistance(traj, direction, "right") new = traj.ix[select,:] new.groupby("trial ID").apply(plotDeviation, xlabel, ylabel, ax, "r", aligned=aligned) select = util.selectByHalfDistance(traj, direction, "left") new = traj.ix[select,:] new.groupby("trial ID").apply(plotDeviation, xlabel, ylabel, ax, "l", aligned=aligned) def compDeviation(traj): """ Calculate the deviation of a saccade from the straight line formed by its start and end points Params: -- traj: should be numpy array of shape (n, 2) """ if isinstance(traj, pd.DataFrame): #print "got a dataframe, try to put it in an array..." traj = traj.values #print traj p0 = traj[0,:]; p1 = traj[-1,:] ## pray for no NaN! #print p0[0], p0[1], p1[0], p1[1] distances = distLinePoint(p0, p1, traj) return pd.DataFrame(distances.T, columns = ["deviation"]) ALIGNED = True # aligned on the start position BOOTSTRAP = False for i in xrange(len(m["subjects"] )): participant = m["subjects"][i] onetraj = m["test2"][i] controltraj = m["control2"][i] for d1 in directions_toplot: print "Working on file:", participant, str(d1) fig = plt.figure(figsize = (7, 11)) ax = fig.add_subplot(211, axisbg="#666666", aspect='equal')#, projection = "3d") ax.set_title(participant+" dir:"+str(d1)+"\n\nSaccade Trajectories") ax.set_ylabel("Y-axis(degrees)") ax.set_xlabel("X-axis(degrees)") onetraj["xp_degree"] = onetraj["xp"] * 0.035935614921 onetraj["yp_degree"] = onetraj["yp"] * 0.035935614921 plotAllTraj(ax, onetraj, d1, "xp_degree", "yp_degree", aligned=(False, False)) ax.set_xlim((-14.5,14.5)) ax.set_ylim((14.5, -14.5)) ax.vlines(0, -14.5, 14.5, color="black", lw=1.5, linestyles="dashed", zorder=10) ax.hlines(0, -14.5, 14.5, color="black", lw=1.5, linestyles="dashed", zorder=10) ## only true for the condition 30 degrees: ax.scatter([-11.69, 11.69], [0, 0], marker="x", color="red", s=45.0, zorder=11) #ax.scatter([0, 0], [-6.75, 6.75], marker="o", color="red", s=45.0, zorder=11) ax = fig.add_subplot(212, axisbg="#666666") ax.set_title("Saccade Deviation over Time") ax.set_ylim((-2.9,2.9)) onetraj["deviation"] = onetraj[["xp_degree", "yp_degree"]].groupby(onetraj["trial ID"]).apply(compDeviation).values onetraj.reset_index(inplace=True, drop = True) plotAllTraj(ax, onetraj, d1, "time", "deviation", aligned=(True, False)) ax.set_ylabel("deviation from \nstraight line (degrees)") ax.set_xlabel("time from saccade start (ms)") ax.vlines(20.0, -3, 3, color="black", lw=1.5, linestyles="dashed", zorder=10) ax.hlines(0, 0, 150, color="gray", lw=1.0, linestyles="dashed") ax.set_xlim((0,150)) plt.tight_layout() plt.savefig("curves/condition-both-aligned"+m["subjects"][i]+"-"+str(d1)+".png", dpi = 300) plt.close()