-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathOrca18_midlineOnly.py
More file actions
429 lines (299 loc) · 13 KB
/
Orca18_midlineOnly.py
File metadata and controls
429 lines (299 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
"""
Script to run silent failure paradigm, with cognitive load. Every trial begins with a period of automation.
The Class myExperiment handles execution of the experiment.
This script relies on the following modules:
For eyetracking - eyetrike_calibration_standard.py; eyetrike_accuracy_standard.py; also the drivinglab_pupil plugin.
For perspective correct rendering - myCave.py
For motion through the virtual world - vizdriver.py
"""
import sys
rootpath = 'C:\\VENLAB data\\shared_modules\\Logitech_force_feedback'
sys.path.append(rootpath)
rootpath = 'C:\\VENLAB data\\shared_modules'
sys.path.append(rootpath)
rootpath = 'C:\\VENLAB data\\shared_modules\\pupil\\capture_settings\\plugins\\drivinglab_pupil\\'
sys.path.append(rootpath)
import viz # vizard library
import numpy as np # numpy library - such as matrix calculation
import random # python library
import vizdriver_Orca18 as vizdriver # vizard library
import viztask # vizard library
import math as mt # python library
import vizshape
import vizact
import vizmat
import myCave
import pandas as pd
rootpath = 'C:\\VENLAB data\\TrackMaker\\'
sys.path.append(rootpath)
from vizTrackMaker import vizStraight, vizBend
#import PPinput
def LoadEyetrackingModules():
"""load eyetracking modules and check connection"""
from eyetrike_calibration_standard import Markers, run_calibration
from eyetrike_accuracy_standard import run_accuracy
from UDP_comms import pupil_comms
###Connect over network to eyetrike and check the connection
comms = pupil_comms() #Initiate a communication with eyetrike
#Check the connection is live
connected = comms.check_connection()
if not connected:
print("Cannot connect to Eyetrike. Check network")
raise Exception("Could not connect to Eyetrike")
else:
pass
#markers = Markers() #this now gets added during run_calibration
def LoadCave():
"""loads myCave and returns Caveview"""
#set EH in myCave
cave = myCave.initCave()
caveview = cave.getCaveView()
return (caveview)
def GenerateConditionLists(FACTOR_radiiPool, FACTOR_YawRate_offsets, TrialsPerCondition):
"""Based on two factor lists and TrialsPerCondition, create a factorial design and return trialarray and condition lists"""
NCndts = len(FACTOR_radiiPool) * len(FACTOR_YawRate_offsets)
print ("number of conditiosn", NCndts)
# ConditionList = range(NCndts)
#automatically generate factor lists so you can adjust levels using the FACTOR variables
ConditionList_radii = np.repeat(FACTOR_radiiPool, len(FACTOR_YawRate_offsets) )
ConditionList_YawRate_offsets = np.tile(FACTOR_YawRate_offsets, len(FACTOR_radiiPool) )
print (ConditionList_radii)
print (ConditionList_YawRate_offsets)
TotalN = NCndts * TrialsPerCondition
TRIALSEQ = range(1,NCndts+1)*TrialsPerCondition
np.random.shuffle(TRIALSEQ)
direc = [1,-1]*(TotalN/2) #makes half left and half right.
np.random.shuffle(direc)
TRIALSEQ_signed = np.array(direc)*np.array(TRIALSEQ)
print("TrialSeq_signed", TRIALSEQ_signed)
return (TRIALSEQ_signed, ConditionList_radii, ConditionList_YawRate_offsets)
# ground texture setting
def setStage():
"""Creates grass textured groundplane"""
###should set this hope so it builds new tiles if you are reaching the boundary.
fName = 'C:/VENLAB data/shared_modules/textures/strong_edge.bmp'
# add groundplane (wrap mode)
groundtexture = viz.addTexture(fName)
groundtexture.wrap(viz.WRAP_T, viz.REPEAT)
groundtexture.wrap(viz.WRAP_S, viz.REPEAT)
groundplane = viz.addTexQuad() ##ground for right bends (tight)
tilesize = 500
planesize = tilesize/5
groundplane.setScale(tilesize, tilesize, tilesize)
groundplane.setEuler((0, 90, 0),viz.REL_LOCAL)
#groundplane.setPosition((0,0,1000),viz.REL_LOCAL) #move forward 1km so don't need to render as much.
matrix = vizmat.Transform()
matrix.setScale( planesize, planesize, planesize )
groundplane.texmat( matrix )
groundplane.texture(groundtexture)
groundplane.visible(1)
viz.clearcolor(viz.SKYBLUE)
return groundplane
def BendMaker(radlist, start):
"""makes left and right roads for for a given radii and return them in a list"""
leftbendlist = []
rightbendlist = []
grey = [.8,.8,.8]
for r in radlist:
rightbend = vizBend(startpos = start, rads = r, x_dir = 1, colour = grey, road_width=0)
rightbendlist.append(rightbend)
leftbend = vizBend(startpos = start, rads = r, x_dir = -1, colour = grey, road_width=0)
leftbendlist.append(leftbend)
return leftbendlist,rightbendlist
class myExperiment(viz.EventClass):
def __init__(self, eyetracking, practice, exp_id, ppid = 1):
viz.EventClass.__init__(self)
self.EYETRACKING = eyetracking
self.PRACTICE = practice
self.EXP_ID = exp_id
if EYETRACKING == True:
LoadEyetrackingModules()
self.PP_id = ppid
self.TrialLength = 15 #length of time that road is visible. Constant throughout experiment
#### PERSPECTIVE CORRECT ######
self.caveview = LoadCave() #this module includes viz.go()
# #BirdsEye
# self.caveview.setPosition([0,100,0])
# self.caveview.setEuler([0,90,0])
##### SET CONDITION VALUES #####
self.FACTOR_radiiPool = [40] # A sharp and gradual bend
self.FACTOR_YawRate_offsets = [0] #6 yawrate offsets, specified in degrees per second.
self.TrialsPerCondition = 6
[trialsequence_signed, cl_radii, cl_yawrates] = GenerateConditionLists(self.FACTOR_radiiPool, self.FACTOR_YawRate_offsets, self.TrialsPerCondition)
self.TRIALSEQ_signed = trialsequence_signed #list of trialtypes in a randomised order. -ve = leftwards, +ve = rightwards.
self.ConditionList_radii = cl_radii
self.ConditionList_YawRate_offsets = cl_yawrates
##### ADD GRASS TEXTURE #####
gplane1 = setStage()
self.gplane1 = gplane1
#### MAKE STRAIGHT OBJECT ####
L = 16 #2sec.
self.Straight = vizStraight(startpos = [0,0], road_width = 0, length = 16, colour = [.8, .8, .8])
self.Straight.ToggleVisibility(viz.ON)
##### MAKE BEND OBJECTS #####
[leftbends,rightbends] = BendMaker(self.FACTOR_radiiPool, self.Straight.RoadEnd)
self.leftbends = leftbends
self.rightbends = rightbends
self.callback(viz.TIMER_EVENT,self.updatePositionLabel)
self.starttimer(0,0,viz.FOREVER) #self.update position label is called every frame.
self.Continue_Timer = False
####### DATA SAVING ######
datacolumns = ['ppid', 'radius','yawrate_offset','trialn','timestamp','trialtype_signed','World_x','World_z','WorldYaw','SWA','YawRate_seconds','TurnAngle_frames','Distance_frames','dt']
self.datacolumns = datacolumns
self.Output = None #dataframe that gets renewed each trial.
#self.Output = pd.DataFrame(columns=datacolumns) #make new empty EndofTrial data
### parameters that are set at the start of each trial ####
self.Trial_radius = 0
self.Trial_YawRate_Offset = 0
self.Trial_N = 0
self.Trial_trialtype_signed = 0
self.Trial_Timer = 0 #keeps track of trial length.
self.Trial_BendObject = None
#### parameters that are updated each timestamp ####
self.Current_pos_x = 0
self.Current_pos_z = 0
self.Current_yaw = 0
self.Current_SWA = 0
self.Current_Time = 0
self.Current_RowIndex = 0
self.Current_YawRate_seconds = 0
self.Current_TurnAngle_frames = 0
self.Current_distance = 0
self.Current_dt = 0
#self.callback(viz.EXIT_EVENT,self.SaveData) #if exited, save the data.
def runtrials(self):
"""Loops through the trial sequence"""
if self.EYETRACKING:
filename = str(self.EXP_ID) + "_Calibration" #+ str(demographics[0]) + "_" + str(demographics[2]) #add experimental block to filename
print (filename)
yield run_calibration(comms, filename)
yield run_accuracy(comms, filename)
self.driver = vizdriver.Driver(self.caveview)
viz.MainScene.visible(viz.ON,viz.WORLD)
#add text to denote conditons.
txtCondt = viz.addText("Condition",parent = viz.SCREEN)
txtCondt.setPosition(.7,.2)
txtCondt.fontSize(36)
if self.EYETRACKING:
comms.start_trial()
for i, trialtype_signed in enumerate(self.TRIALSEQ_signed):
#import vizjoy
print("Trial: ", str(i))
print("TrialType: ", str(trialtype_signed))
trialtype = abs(trialtype_signed)
#trialtype is indexed from one. so need to minus one from it.
trial_radii = self.ConditionList_radii[trialtype-1] #set radii for that trial
trial_yawrate_offset = self.ConditionList_YawRate_offsets[trialtype-1] #set target number for the trial.
print(str([trial_radii, trial_yawrate_offset]))
txtDir = ""
#print ("Length of bend array:", len(self.rightbends))
radius_index = self.FACTOR_radiiPool.index(trial_radii)
#choose correct road object.
if trialtype_signed > 0: #right bend
trialbend = self.rightbends[radius_index]
txtDir = "R"
else:
#trialbend = self.leftbends[radius_index]
#txtDir = "L"
trialbend = self.rightbends[radius_index]
txtDir = "R"
trialbend.ToggleVisibility(viz.ON)
if trial_radii > 0: #if trial_radii is above zero it is a bend, not a straight
msg = "Radius: " + str(trial_radii) + txtDir + '_' + str(trial_yawrate_offset)
else:
msg = "Radius: Straight" + txtDir + '_' + str(trial_yawrate_offset)
txtCondt.message(msg)
#update class#
self.Trial_N = i
self.Trial_radius = trial_radii
self.Trial_YawRate_Offset = trial_yawrate_offset
self.Trial_BendObject = trialbend
#renew data frame.
self.Output = pd.DataFrame(index = range(self.TrialLength*60), columns=self.datacolumns) #make new empty EndofTrial data
yield viztask.waitTime(3) #pause at beginning of trial
#here we need to annotate eyetracking recording.
self.Continue_Timer = True #
yield viztask.waitTime(self.TrialLength) #wait for input .
self.Continue_Timer = False
self.Trial_BendObject.ToggleVisibility(viz.OFF)
##reset trial. Also need to annotate each eyetracking trial.
trialdata = self.Output.copy()
fname = 'Data//Midline_' + str(self.Trial_radius) + '_' + str(self.Trial_N) + '.csv'
#print (trialdata)
#print (fname)
viz.director(self.SaveData, trialdata, fname)
#reset row index.
self.Current_RowIndex = 0
self.ResetDriverPosition()
#self.SaveData(trialdata)
#loop has finished.
CloseConnections(self.EYETRACKING)
#viz.quit()
def getNormalisedEuler(self):
"""returns three dimensional euler on 0-360 scale"""
euler = self.caveview.getEuler()
euler[0] = vizmat.NormAngle(euler[0])
euler[1] = vizmat.NormAngle(euler[1])
euler[2] = vizmat.NormAngle(euler[2])
return euler
def ResetDriverPosition(self):
"""Sets Driver Position and Euler to original start point"""
self.driver.reset()
def RecordData(self):
"""Records Data into Dataframe"""
#datacolumns = ['ppid', 'radius','occlusion','trialn','timestamp','trialtype_signed','World_x','World_z','WorldYaw','SWA']
output = [self.PP_id, self.Trial_radius, self.Trial_YawRate_Offset, self.Trial_N, self.Current_Time, self.Trial_trialtype_signed,
self.Current_pos_x, self.Current_pos_z, self.Current_yaw, self.Current_SWA, self.Current_YawRate_seconds, self.Current_TurnAngle_frames,
self.Current_distance, self.Current_dt] #output array.
#print ("length of output: ", len(output))
#print ("size of self.Output: ", self.Output.shape)
#print(output)
self.Output.loc[self.Current_RowIndex,:] = output #this dataframe is actually just one line.
# def SaveData(self, data, filename):
# """Saves Current Dataframe to csv file"""
# data = data.dropna() #drop any trailing space.
# data.to_csv(filename)
def SaveData(self, data, filename):
"""Saves Current Dataframe to csv file"""
data = data.dropna() #drop any trailing space.
data.to_csv(filename)
def updatePositionLabel(self, num):
"""Timer function that gets called every frame. Updates parameters for saving"""
"""Here need to bring in steering bias updating from Trout as well"""
if self.Continue_Timer:
#print("UpdatingPosition...")
#update driver view.
UpdateValues = self.driver.UpdateView() #update view and return values used for update
# get head position(x, y, z)
pos = self.caveview.getPosition()
ori = self.getNormalisedEuler()
### #update Current parameters ####
self.Current_pos_x = pos[0]
self.Current_pos_z = pos[2]
self.Current_SWA = UpdateValues[4]
self.Current_yaw = ori[0]
self.Current_RowIndex += 1
self.Current_Time = viz.tick()
self.Current_YawRate_seconds = UpdateValues[0]
self.Current_TurnAngle_frames = UpdateValues[1]
self.Current_distance = UpdateValues[2]
self.Current_dt = UpdateValues[3]
self.RecordData() #write a line in the dataframe.
def CloseConnections(EYETRACKING):
"""Shuts down EYETRACKING and wheel threads then quits viz"""
print ("Closing connections")
if EYETRACKING:
comms.stop_trial() #closes recording
#kill automation
viz.quit()
if __name__ == '__main__':
###### SET EXPERIMENT OPTIONS ######
EYETRACKING = False
PRACTICE = True
TILING = False
EXP_ID = "Orca18"
if PRACTICE == True: # HACK
EYETRACKING = False
myExp = myExperiment(EYETRACKING, PRACTICE, EXP_ID)
viz.callback(viz.EXIT_EVENT,CloseConnections, myExp.EYETRACKING)
viztask.schedule(myExp.runtrials())