def reachTeapotTask(): tryNum = 0 while(True) : global reachedTeapot reachedTeapot = False global avoidCat avoidCat = True # Action for hiding/showing text DelayHide = vizact.sequence( vizact.waittime(8), vizact.method.visible(False) ) Show = vizact.method.visible(True) instructions.setText("Welcome!") instructions.runAction(DelayHide) yield viztask.waitTime(5) instructions.runAction(Show) instructions.setText("Now, try to get the teapot without touching the cat in 15 seconds!") instructions.runAction(DelayHide) yield viztask.waitTime(15) instructions.runAction(Show) instructions.setText("Reached Teapot: "+str(reachedTeapot)+" Avoided Cat: "+str(avoidCat)) yield viztask.waitTime(5) yield ClapTask() tryNum = tryNum + 1 data = 'Try '+str(tryNum)+' Reached Teapot: '+str(reachedTeapot)+' Avoided Cat: '+str(avoidCat)+'\n' teapot_game_data.write(data) instructions.setText("Now, try again or exit to leave!") yield viztask.waitTime(5)
def testPhase(): info.setText("Experiment running") info.visible(viz.ON) vizact.ontimer(1, getData) yield viztask.waitTime(10) info.setText("Experiment over") yield viztask.waitTime(2)
def walk(): while (True) : yield viztask.addAction(cat,vizact.walkTo([2.8, 0, -3], walkSpeed = 1.5, turnSpeed = 1, walkAnim = 4)) yield viztask.waitTime(1.5) yield look1() yield viztask.addAction(cat,vizact.walkTo([-2.8, 0, -3], walkSpeed = 1.5, turnSpeed = 1, walkAnim = 4)) yield viztask.waitTime(1.5) yield look2()
def endingPhase(): childLookAtYou() windAudio.stop() endingAudio.play() yield viztask.waitTime(CHILD_RECOVERY_TIME) childModel.state(6) yield viztask.waitTime(endingAudioBasic.getDuration() - CHILD_RECOVERY_TIME) yield viztask.waitTime(END_TIME) finish()
def policeApproach(scene=viz.MainScene): yield viztask.waitTime(TIME_BEFORE_POLICE) addSirens(scene) yield viztask.waitTime(sirenAudio.getDuration()) moveFlashlightToCar(scene, POLICE_WALK_TIME) yield viztask.waitTime(POLICE_WALK_TIME) footstepsAudio.stop() global flashlight policeOfficerAudio = flashlight.playsound("resources/audio/PoliceOfficer.wav")
def prepareForObjectSelling( obj ): global SCENE, APARTMENT, OBJECTS, RIFT audio = obj.narrationFile[0] sound = viz.addAudio(audio) duration = sound.getDuration() yield viztask.waitTime(1) sound.play() print "now playing audio for prepare for selling object" yield viztask.waitTime(duration) ObjectSelling.init(APARTMENT, OBJECTS, SCENE, RIFT) ObjectSelling.enable()
def testPhase(): info.setText("Testing") info.visible(viz.ON) position = viz.MainView.getPosition() data = 'position:' + '\n'+str(position) data_file.write(data) yield viztask.waitTime(5) info.visible(viz.OFF) info.setText("Experiment finished testing phase") info.visible(viz.ON) yield viztask.waitTime(2)
def walking(): yield viztask.waitKeyDown(' ') male.addAction(vizact.walkTo([1, 0, 0])) yield vizproximity.waitEnter(femaleSensor) female.state(3) yield viztask.waitTime(2) male.state(33) yield viztask.waitTime(3) male.addAction(vizact.walkTo([-4, 0, 0], walkAnim = 70, walkSpeed = 2)) yield vizproximity.waitExit(femaleSensor) female.state(8)
def findCup(bottle): disableSelector() yield moveToDash(bottle) yield viztask.waitTime(TIME_BETWEEN_TASKS) # wait a bit before next task #Play instructions. cupInstructions = car.playsound('resources/audio/find_cup_audio.wav') #Wait for instructions to end yield viztask.waitTime(cupInstructions.getDuration()) enableSelector([cup1, cup2])
def findBottle(): disableSelector() yield moveToDash(toothPaste) yield viztask.waitTime(TIME_BETWEEN_TASKS) # wait a bit before next task #Play instructions. bottleInstructions = car.playsound('resources/audio/find_bottle_audio.wav') #Wait for instructions to end yield viztask.waitTime(bottleInstructions.getDuration()) enableSelector([bottle1, bottle2, bottleCap1, bottleCap2])
def findToothBrush(): #Wait for start of experiment yield viztask.waitTime(3) #Play instructions. toothBrushInstructions = car.playsound('resources/audio/find_toothbrush_audio.wav') #Wait for instructions to end. yield viztask.waitTime(toothBrushInstructions.getDuration()) #enable selector selector.enable()
def learnPhase(): # provide instructions for the participant info.setText("You'll have 30 seconds to explore") info.visible(viz.ON) # hide instructions after 5 seconds yield viztask.waitTime(5) info.visible(viz.OFF) # let participant know learning phase has ended yield viztask.waitTime(30) Reset()
def playPhoneAndRadio(): global main_screen, radio, selector, phoneEvent yield screen.playsound('resources/audio/vibrate.wav', viz.STOP) yield selector.disable() yield selector.disable() yield screen.endAction( pool = 0) yield vizact.removeEvent(phoneEvent) voicemail = screen.playsound('resources/audio/voicemail_mono.wav', viz.PLAY) yield viztask.waitTime(voicemail.getDuration()) newsReport = radio.playsound('resources/audio/RadioShowScene_louder.wav') yield viztask.waitTime(newsReport.getDuration()) viz.sendEvent(INTRO_OVER_EVENT)
def setupTarget(): viztask.waitTime(5) target = viz.add('arm/all_target.wrl') target.setScale(.01, .01, .01) target.setEuler(0, 90, 0) target.setPosition([-1.35, 1.5, -1.5]) reportTargetTime() #Adds invisible cube that launches fire global targetcube targetcube = [] targetcube.append(TouchCube()) targetcube[0].setPosition([-1.35, 1.5, -1.5])
def findToothPaste(): disableSelector() yield moveToDash(toothBrush) lowerBlanket() yield viztask.waitTime(TIME_BETWEEN_TASKS) # wait a bit longer before new instructions #Play instructions. toothPasteInstructions = car.playsound('resources/audio/find_toothpaste_audio.wav') #Wait for instructions to end yield viztask.waitTime(toothPasteInstructions.getDuration()) enableSelector([toothPaste,cap,cup1])
def getCoords(source, destination): """ source should be a 3D connection device, and the destination should be a 3d node type """ #set source scale scale1 = [.001,.001,.001] scale2 =[.01,.01,.01] #device.setTranslateScale(scale2) #device.setRotateScale(scale) while True: yield viztask.waitTime( .01 ) position = source.getRawTranslation() orientation = source.getRawRotation() #rescale position position = scalarMult(position,scale1) orientation = scalarMult(orientation,scale2) #invert signs of x and z x,y,z = position position = [-x,y,-z] #invert signs of x and z rotations, and exchange b and a a,b,g = orientation orientation = [b,-a,-g] #print(orientation) destination.setPosition(position, viz.REL_PARENT) destination.setEuler(orientation, viz.REL_PARENT)
def strippedTrialTask(avatar, turningAngle, vLinear, tLegs, idxTrial, output = {}): """ master task that invokes all other tasks as subtasks to ensure right order """ # add text for instructions screenText = viz.addText('trial no. '+str(idxTrial),viz.SCREEN) screenText.setBackdrop(viz.BACKDROP_RIGHT_BOTTOM) screenText.setBackdropColor(viz.GRAY) screenText.setPosition(0.05, 0.5) # wait for key press and execute trial yield viztask.waitKeyDown(' ') screenText.message('') passage = passageAction(turningAngle, vLinear, tLegs) avatar.addAction(passage) yield viztask.waitActionEnd(avatar, passage) # get homing vectors yield helperFunctions.saveHomingVectors(avatar, output) print output # post trial instructions & position reset yield viztask.waitTime(0.2) screenText.message('please select your\nanswer for trial '+str(idxTrial)) yield viztask.waitKeyDown(' ') screenText.remove() yield helperFunctions.resetTask(avatar)
def CycleAlertsTask (self): self._cycler = None #the next item in the list to display (starts with last) fade_out = vizact.fadeTo(0, 1, time=0.5, interpolate=vizact.easeOutStrong) fade_in = vizact.fadeTo(1, 0, time=0.5, interpolate=vizact.easeOutStrong) #set all alerts on map to 100% opaque so that they don't stay semi-transparent for i in [a for m, a in self._alerts.iteritems() if m != 'info']: a.alpha(1) while True: data = yield viztask.waitDirector(self.GetNextMessage) nextKey = data.returnValue if nextKey == 'info': #not verified anymore because info not in _messages self._infoPanel.setText(self._messages[nextKey]) else: self.DisplayAlert(self._messages[nextKey]) if nextKey != 'info': alertObj = self._alerts[nextKey] yield viztask.addAction(alertObj, fade_out) yield viztask.addAction(alertObj, fade_in) yield viztask.addAction(alertObj, fade_out) yield viztask.addAction(alertObj, fade_in) yield viztask.addAction(alertObj, fade_out) yield viztask.addAction(alertObj, fade_in) yield viztask.addAction(alertObj, fade_out) yield viztask.addAction(alertObj, fade_in) else: yield viztask.waitTime(5)
def playStory(): global selectedAvatar, playing, avs if selectedAvatar.name == 'exit': viztask.schedule(playBusCloseAudio) else: selectedAvatar.story.play() playing = True toOutput = 'Started listening to ' + selectedAvatar.name dc.collect(toOutput) yield viztask.waitMediaEnd(selectedAvatar.story) playing = False selectedAvatar.done = True if selectedAvatar.name == 'son/father': for avatar in avs: if avatar.name == 'father/son': avatar.done = True break if selectedAvatar.name == 'father/son': for avatar in avs: if avatar.name == 'son/father': avatar.done = True break toOutput = 'Finished listening to ' + selectedAvatar.name dc.collect(toOutput) yield viztask.waitTime(0.1) selectedAvatar = None
def trialCountDownTask(): """Task that count downs to time limit for trial""" # Action for text fading out text_fade = vizact.parallel( vizact.fadeTo(0,time=0.8,interpolate=vizact.easeOut) ,vizact.sizeTo([.1,.1,.1],time=0.8,interpolate=vizact.easeOut) ) # Reset time text time_text.clearActions() time_text.alpha(1.0) time_text.color(viz.BLACK) time_text.setScale([.05,.05,.05]) time_text.message('REMAINING: ' + str(int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT)/60)+ ':' + str(int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT)%60).zfill(2)) # Countdown from time limit start_time = viz.getFrameTime() last_remain = int(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT) while (viz.getFrameTime() - start_time) < globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT: # Compute remaining whole seconds remain = int(math.ceil(globals_oa.TIME_TO_FIND_IN_SCAVENGER_HUNT - (viz.getFrameTime() - start_time))) # Update text if time remaining changed if remain != last_remain: if remain <= 5: time_text.alpha(1.0) time_text.color(viz.RED) time_text.setScale([.05]*3) time_text.runAction(text_fade) time_text.message(str(remain/60)+ ':'+str(remain%60).zfill(2)) last_remain = remain # Wait tenth of second yield viztask.waitTime(0.1) print 'OUT OF TIME'
def getCoords(source, destination, log = False): """ source should be a 3D connection device, and the destination should be a 3d node type """ while True: yield viztask.waitTime( .01 ) position = source.getRawTranslation() orientation = source.getRawRotation() #sets the velocity of the glove (destination) to zero destination.setVelocity([0,0,0], viz.ABS_GLOBAL) destination.setAngularVelocity([0,0,0] ,viz.ABS_GLOBAL) #if selected do log scale on orientation if log: config.SMEulerScale= [0.5, 0.5 , 0.5] orientation = logScale(orientation) #rescale position position = list(numpy.multiply(position,config.SMPositionScale)) orientation = list(numpy.multiply(orientation,config.SMEulerScale)) #invert signs of x and z x,y,z = position #invert signs of x and z rotations, and exchange b and a a,b,g = orientation orientation = [b,a,g] destination.setPosition(position, viz.REL_PARENT) destination.setEuler(orientation, viz.REL_PARENT)
def startZone3Hunt(): global SWIM_ZONE_TO_ZONE_COMPLETE_EVENT # yield viztask.waitEvent(scavengerhunt.ZONE1_OVER_EVENT) # print "waiting for swimming to end" # yield viztask.waitEvent(SWIM_ZONE_TO_ZONE_COMPLETE_EVENT) # scavengerhunt.disableGrabber() # globals_oa.basket.disable(viz.RENDERING) yield fader.fadeOutTask() globals_oa.AUDIO_ZONE_CUT_AMBIENT.play() # globals_oa.ZONE3_TRANSITION.play() #Untested fish hiding # for school in schooling.all_fish_schools: # chromis_chromis.hidePercentage(20) # diplodus_annularis.hidePercentage(100) # labrus_viridis.hidePercentage(100) # sarpa_salpa.hidePercentage(20) for school in schooling.all_fish_schools: school.hidePercentage(50) globals_oa.currentZoneNumber = 2 transport_vhil.cycleZones() #viz.res.addPublishFile('data/speciesToFindZone3.txt') #scavengerhunt.initialize(globals_oa.terrainZone3, globals_oa.filePathToSpeciesForScavengerHuntInZone3) #Enable swimming yield fader.fadeInTask() globals_oa.AUDIO_ZONE3_AMBIENT.play() yield viztask.waitTime(3) globals_oa.ZONE3_AUDIO_1.play() # playAudioAndSaveGlobalPointer(globals_oa.ZONE3_AUDIO_1) viztask.schedule(startBoatOutro())
def destinationsTask(): # Action for hiding/showing text DelayHide = vizact.sequence( vizact.waittime(8), vizact.method.visible(False) ) Show = vizact.method.visible(True) yield viztask.waitTime(6) instructions.setText("Walk around!") instructions.runAction(DelayHide) yield viztask.waitTime(30) instructions.runAction(Show) instructions.setText("Thank you for your participation :)") #Show results of experiment print 'Avoided avatar:',avoidAvatar print 'Avoided cat:',avoidCat
def H2CO3formation(): global bigCO2, bigH2O, h2co3molecule, co2Path, lowPolyMole, highPolyMole, h2co3FormationTriggered h2co3FormationTriggered = True viz.sendEvent(globals_oa.H2CO3_COMPLETION_EVENT) #none of the following calls work to get the correct 3d position, phew! # x,y,z = bigH2O.getPosition(viz.ABS_GLOBAL) # x,y,z = bigH2O.getBoundingBox().center #hardcoded value below, until the sunny day when Worldviz gets us a call for the correct position of a 3d node! co2Path.remove() x,y,z = globals_oa.h2OLocationUntilWeChangeAgain[0], globals_oa.h2OLocationUntilWeChangeAgain[1], globals_oa.h2OLocationUntilWeChangeAgain[2] print x,y,z moveToH2O = vizact.moveTo([x,y,z] , speed = .75) yield viztask.addAction(bigCO2, moveToH2O) #yield viztask.waitTime(.05) #Fade molecules from bigCO2 and bigH2O to H2CO3 animation h2co3molecule.setPosition(globals_oa.h2CO3LocationUntilWeChangeAgain) lowPolyMole.enable(viz.RENDERING) highPolyMole.disable(viz.RENDERING) h2co3molecule.visible(viz.ON) h2co3molecule.setAnimationTime(8.9) #starts animation at 17.8 seconds # h2co3molecule.setAnimationSpeed(0.1) h2co3molecule.setAnimationLoopMode(0) # viztask.waitTime(.5) fadeOut = vizact.fadeTo(0, time=1) lowPolyMole.addAction(fadeOut) bigH2O.addAction(fadeOut) yield viztask.waitTime(5) bigCO2.visible(viz.OFF) bigH2O.visible(viz.OFF)
def showHiddenMolecules(): yield viztask.waitTime(0.5) for mole in LIST_OF_FALLING_MOLES: node = globals_oa.boat.getChild(mole) node.enable(viz.RENDERING) mole1 = globals_oa.boat.getChild('mole1') mole1.setAnimationSpeed(2) mole2 = globals_oa.boat.getChild('mole2') mole2.setAnimationSpeed(.7) mole3 = globals_oa.boat.getChild('mole3') mole3.setAnimationSpeed(2.3) mole4 = globals_oa.boat.getChild('mole4') mole4.setAnimationSpeed(1.2) mole9 = globals_oa.boat.getChild('mole9') mole9.setAnimationSpeed(1.5) mole12 = globals_oa.boat.getChild('mole12') mole12.setAnimationSpeed(0.8) mole15 = globals_oa.boat.getChild('mole15') mole15.setAnimationSpeed(1.9) mole20 = globals_oa.boat.getChild('mole20') mole20.setAnimationSpeed(0.7) mole21 = globals_oa.boat.getChild('mole21') mole21.setAnimationSpeed(1.4) mole25 = globals_oa.boat.getChild('mole25') mole25.setAnimationSpeed(1.1)
def learnPhase(): #provide instructions for the participant info.setText("You'll have 30 seconds to walk around and find the sphere") info.visible(viz.ON) #hide instructions after 5 seconds yield viztask.waitTime(5) info.visible(viz.OFF) #let participant know learning phase has ended yield viztask.waitTime(30) info.setText("Please return to the center of the room to begin the testing phase") info.visible(viz.ON) #Start testing phase after 5 seconds yield viztask.waitTime(5)
def creepilyMoveCloser(node): global introAudio1, introAudio2 global comeForward, firstSeatPosition, seatQueue global PID dout = DataOutputHelper(PID) comeForward = seatQueue[-2] firstSeatPosition = seatQueue[0] node.setPosition(firstSeatPosition) yield viztask.waitMediaEnd(introAudio1) introAudio2.play() # We want the participant to have a minute after the audio ends viz.callback(viz.MEDIA_EVENT,onAudioEnd) dout.timestamp(dout.busFile, 'Initial audio ended') yield viztask.waitMediaEnd(introAudio2) yield viztask.waitTime(.1) # Pause necessary for NodeViewDetection to get necessary info about node nvd = DetectWhetherInView.NodeViewDetection(node) FadeObject.beginFading() moveAsUsual = False getCloserBeforeBackAway = True while getCloserBeforeBackAway: node.setPosition(firstSeatPosition) yield waitTilNodeAndDestOutsideView(nvd, firstSeatPosition) yield waitTilNodeInsideView(nvd) node.setPosition(comeForward) yield creepilyMakeEyeContact(node, comeForward, dout) yield moveBackToFirstSeat(node, seatQueue) if abs(node.getPosition()[0] - firstSeatPosition[0]) < 0.1: getCloserBeforeBackAway = False moveAsUsual = True print 'waiting til node inside view...' yield waitTilNodeInsideView(nvd) while moveAsUsual: print 'waiting until node and dest outside view...' nextPosition = seatQueue[1] # Peek at nextPosition yield waitTilNodeAndDestOutsideView(nvd, nextPosition) # Pauses til node and that position are outside of view # Move to nextPosition print 'node and dest are outside view! Moving to next position...' node.setPosition(nextPosition) seatQueue.rotate(-1) # update seatQueue print 'waiting til node inside view...' yield waitTilNodeInsideView(nvd) print 'creepily dodging eye contact...' yield creepilyMakeEyeContact(node, seatQueue[0], dout) #if seatQueue[0] is not finalSeatPosition: print 'waiting 5 seconds then moving him back if hes in view at the end of the 5 seconds.' # TODO: This is not exactly what we want. yield moveBackwardsIfStaredAt(node, nvd) # If the node is not in the last seat position,
def ClapTask(): global reachedTeapot global avoidCat print 'Running ClapTask with value ',reachedTeapot if reachedTeapot and avoidCat: girl.state(152) yield viztask.waitTime(15) girl.state(34)
def InitFire(): global fireActivated reportFireTime() viztask.waitTime(1) fire = viz.add('fire_small2.osg') fire.setPosition([-1.35, 1.5, -2.75]) fire.hasparticles() fire.setScale(1, .5, .5) fire.addAction(vizact.spin(0,1,0,360)) ignition = fire.playsound('ignite.wav') ignition.volume(.25) explosion = fire.playsound('explosion.wav') explosion.volume(.25) firecracking = fire.playsound ('longfire.wav') firecracking.volume(.25) vizact.ontimer2(5, 1, KillFire, fire, ignition, explosion, firecracking) fireActivated = True
def learnPhase(): #provide instructions for the participant info.setText("You'll have 10 seconds to walk around and explore the room") info.visible(viz.ON) #hide instructions after 5 seconds yield viztask.waitTime(5) info.visible(viz.OFF) #let participant know learning phase has ended yield viztask.waitTime(5) info.setText("The testing phase will start in 5 seconds") info.visible(viz.ON) #Start testing phase after 5 seconds yield viztask.waitTime(5) info.visible(viz.OFF)
def runtrials(): global trialtype, trialtype_signed, groundplane, radiiPool, out yield viztask.waitTime(5.0) #allow me to get into the seat. setStage() # texture setting. #likely to have to be expanded. driver.reset() # initialization of driver [leftbends, rightbends] = BendMaker(radiiPool) 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) out = "" def updatePositionLabel(): global driver, trialtype_signed, trialtype ##WHAT DO I NEED TO SAVE? # get head position(x, y, z) pos = viz.get(viz.HEAD_POS) pos[1] = 0.0 # (x, 0, z) # get body orientation ori = viz.get(viz.BODY_ORI) steeringWheel = driver.getPos() #what data do we want? RoadVisibility Flag. SWA. Time, TrialType. x,z of that trial These can be reset in processing by subtracting the initial position and reorienting. SaveData(pos[0], pos[2], ori, steeringWheel) ##. vizact.ontimer((1.0 / 60.0), updatePositionLabel) for j in range(0, TotalN): #import vizjoy trialtype = abs(TRIALSEQ_signed[j]) trialtype_signed = TRIALSEQ_signed[j] txtDir = "" #pick correct object if trialtype_signed > 0: #right bend trialbend = rightbends[trialtype - 1] txtDir = "R" else: trialbend = leftbends[trialtype - 1] txtDir = "L" # Define a function that saves data def SaveData(pos_x, pos_z, ori, steer): global out #what data do we want? RoadVisibility Flag. SWA. Time, TrialType. x,z of that trial These can be reset in processing by subtracting the initial position and reorienting. if out != '-1': # Create the output string currTime = viz.tick() out = out + str(float((currTime))) + '\t' + str( trialtype_signed) + '\t' + str(pos_x) + '\t' + str( pos_z) + '\t' + str(ori) + '\t' + str( steer) + '\t' + str(radius) + '\t' + str( trialbend.getVisible()) + '\n' radius = radiiPool[trialtype - 1] if radius > 0: msg = "Radius: " + str(radius) + txtDir else: msg = "Radius: Straight" + txtDir txtCondt.message(msg) trialbend.visible(1) #translate bend to driver position. driverpos = viz.MainView.getPosition() print driverpos trialbend.setPosition(driverpos[0], 0, driverpos[2]) #now need to set orientation driverEuler = viz.MainView.getEuler() trialbend.setEuler(driverEuler, viz.ABS_GLOBAL) #will need to save initial vertex for line origin, and Euler. Is there a nifty way to save the relative position to the road? driver.setSWA_invisible() yield viztask.waitTime(2) #wait for input . trialbend.visible(0) driver.setSWA_visible() def checkCentred(): centred = False while not centred: x = driver.getPos() if abs(x) < .5: centred = True break # centred = False # while not centred: # x = driver.getPos() # print x ##wait a while print "waiting" yield viztask.waitDirector(checkCentred) print "waited" yield viztask.waitTime(2) #wait for input . else: #print file after looped through all trials. fileproper = ('Pilot_CDM.dat') # Opens nominated file in write mode path = viz.getOption('viz.publish.path/') file = open(path + fileproper, 'w') file.write(out) # Makes sure the file data is really written to the harddrive file.flush() #print out file.close() #exit vizard viz.quit() ##otherwise keeps writting data onto last file untill ESC
def run_condition_two(): # declare globals global collide_coords global movement_time global coordinate_array global trial_number global maze global phase global trial_object # setup collision destination collide_coords = end_coords ################ #Learning Phase# ################ #phase = 'Learning' # setup viewpoint and positioning yield setup_view() # setup maze for loading maze_name = maze_root + 'noarrows.IVE' maze = viz.add(maze_name) maze.visible(viz.OFF) if phase_selection is 'Learning': phase = 'Learning' # loop through each of the five learning phase trials for trial in range(1, 5): trial_number = trial # Show instructions and wait for user signal until they are removed instructions = viz.addText('Please explore the maze.', viz.SCREEN) instructions.fontSize(42) instructions.setPosition(.5, .5) instructions.alignment(viz.TEXT_CENTER_CENTER) yield viztask.waitKeyDown('m') instructions.remove() # show user fixation cross yield display_fix() # turn maze on yield maze.visible(viz.ON) # load coordinate_array in clear it so that previous trial data is gone coordinate_array = array([]) # enable events joy_timer.setEnabled(viz.ON) coor_timer.setEnabled(viz.ON) write_onkey.setEnabled(viz.ON) quit_onkey.setEnabled(viz.ON) pos_timer.setEnabled(viz.ON) # reset and start the clock movement_time = TickTockTimer() movement_time.StartTimer() # Wait for trial to expire yield viztask.waitTime(300) # yield viztask.waitTime(420) # disable all timers disable() write_trial_data() # turn maze off and then move maze.visible(viz.OFF) # if trial != 3: if trial != 5: yield move() # Display between phase instructions instructions = viz.addText( 'Please wait for the experimenter to give you more instructions.', viz.SCREEN) instructions.fontSize(42) instructions.setPosition(.5, .5) instructions.alignment(viz.TEXT_CENTER_CENTER) yield viztask.waitKeyDown('m') yield instructions.remove() phase = 'Testing' ############### #Testing Phase# ############### # setup maze start and end locations for each maze if maze_root == 'C:\Experiments\Bike_Extend_Pilot\SNAP\SNAPMazeA': # setup start location dictionary {Start Location:((Start Coordinates),(Start Orientation)),...} start_dic = { 'A': ((-1049, 40, 1530), (0, 0, 0)), 'B': ((675, 40, 1814), (-90, 0, 0)), 'C': ((110, 40, 678), (0, 0, 0)), 'D': ((-725, 40, 2155), (-90, 0, 0)), 'E': ((0, 40, 0), (0, 0, 0)), 'F': ((-1040, 0, 670), (-180, 0, 0)) } # setup object list (Object,Start Location,End Coordinates) objects = (('Table', 'C', (-710, -664, 669, 769)), ('Chair', 'A', (397, 464, 1784, 1849)), ('Round Stool', 'F', (148, 174, 1445, 1480)), ('Rug', 'E', (-312, -259, 1060, 1130)), ('Mirror', 'B', (-330, 259, 730, 755)), ('Wooden Basket', 'A', (-1070, -994, 361, 433)), ('Bench with cushions', 'B', (-316, -194, 1784, 1827)), ('Coat Rack', 'D', (-675, -645, 890, 945)), ('Wooden Chest', 'E', (-1071, -1032, 1170, 1850)), ('Potted Plant', 'F', (-6, 40, 206, 260)), ('TV', 'D', (113, 149, 1013, 1111)), ('Curtains', 'C', (-1070, -1022, 1518, 1538))) elif maze_root == 'C:\Experiments\Bike_Extend_Pilot\SNAP\SNAPMazeB': # setup start location dictionary {Start Location:((Start Coordinates),(Start Orientation)),...} start_dic = { 'A': ((-1835, 40, 1100), (0, 0, 0)), 'B': ((12, 40, -10), (0, 0, 0)), 'C': ((-1114, 40, 2151), (-180, 0, 0)), 'D': ((-1835, 40, 545), (-180, 0, 0)), 'E': ((-1255, 40, 323), (-90, 0, 0)), 'F': ((410, 40, 737), (-90, 0, 0)) } # setup object list (Object,Start Location,End Coordinates) objects = (('Purple Chair', 'C', (-223, -165, 1030, 1080)), ('Round Table', 'E', (-381, -277, 282, 358)), ('Fireplace', 'B', (-1873, -1854, 289, 371)), ('Long Table', 'A', (-1058, -951, 634, 669)), ('Dining Chair', 'F', (-854, -826, 1003, 1048)), ('Wall Lamp', 'E', (-1856, -1802, 1057, 1080)), ('Window', 'F', (-1519, -1440, 1410, 1433)), ('Umbrella Stand', 'D', (-678, -628, 681, 715)), ('Vase', 'A', (-19, 46, -57, -10)), ('Cabinet with Dishes', 'B', (-1290, -1251, 1019, 1201)), ('Floor Lamp', 'D', (-817, -772, 1435, 1491)), ('Rug', 'C', (-1600, -1510, 667, 715))) elif maze_root == 'C:\Experiments\Bike_Extend_Pilot\SNAP\SNAPMazeC': # setup start location dictionary {Start Location:((Start Coordinates),(Start Orientation)),...} start_dic = { 'A': ((788, 0, 110), (0, 0, 0)), 'B': ((2064, 0, 995), (180, 0, 0)), 'C': ((110, 0, 1050), (90, 0, 0)), 'D': ((100, 0, -47), (90, 0, 0)), 'E': ((700, 0, 2100), (180, 0, 0)), 'F': ((950, 0, 1714), (90, 0, 0)) } # setup object list (Object,Start Location,End Coordinates) objects = (('Aquarium', 'A', (370, 450, 1795, 1850)), ('Basket', 'B', (790, 830, 455, 500)), ('Playset', 'C', (90, 185, 2035, 2120)), ('Dartboard', 'D', (2020, 2120, 365, 430)), ('Ladder', 'E', (1650, 1700, 850, 900)), ('Bench', 'F', (1220, 1320, 1060, 1100)), ('Speaker', 'B', (730, 765, 1160, 1235)), ('Lawnmower', 'E', (1225, 1300, 1670, 1750)), ('Doghouse', 'F', (340, 450, 1050, 1100)), ('Freezer', 'A', (350, 470, -100, -35)), ('Crib', 'D', (1280, 1325, 675, 750)), ('washer', 'C', (690, 740, 1750, 1800))) elif maze_root == 'C:\Experiments\Bike_Extend_Pilot\SNAP\SNAPMazeD': # setup start location dictionary {Start Location:((Start Coordinates),(Start Orientation)),...} start_dic = { 'A': ((1395, 0, 1795), (90, 0, 0)), 'B': ((2060, 0, 316), (0, 0, 0)), 'C': ((1145, 0, 211), (0, 0, 0)), 'D': ((414, 0, 285), (0, 0, 0)), 'E': ((560, 0, 1150), (90, 0, 0)), 'F': ((1130, 0, 1070), (90, 0, 0)) } # setup object list (Object,Start Location,End Coordinates) objects = (('Drums', 'A', (740, 830, 1710, 1750)), ('Fountain', 'B', (1890, 1940, 1430, 1490)), ('Pooltable', 'C', (1660, 1750, 1200, 1250)), ('Bed', 'D', (1390, 1500, 1000, 1060)), ('Sandpit', 'E', (1680, 1750, 1800, 1850)), ('Stove', 'F', (790, 830, 610, 650)), ('Shower', 'D', (2345, 2400, 275, 365)), ('Barrel', 'E', (1770, 1820, 640, 675)), ('Tiger', 'F', (740, 830, 178, 200)), ('Bike', 'A', (370, 395, 560, 640)), ('Grill', 'D', (770, 830, 1100, 1140)), ('Ironingboard', 'C', (2080, 2120, 645, 735))) else: print 'Maze ' + maze_root + ' not supported for condition 2 testing phase.' # loop through object/finish location trial_number = 1 for object in objects: trial_object = object[1] # show user instructions instructions = viz.addText( 'Please navigate to the object displayed on the stand.', viz.SCREEN) instructions.fontSize(42) instructions.setPosition(.5, .5) instructions.alignment(viz.TEXT_CENTER_CENTER) yield viztask.waitKeyDown('m') instructions.remove() # show user fixation cross yield display_fix() # load coordinate_array, then clear it so that previous trial data is gone coordinate_array = array([]) # set object specific finish location collide_coords = object[2] # set position and orientation viz.MainView.setPosition(start_dic[object[1]][0], viz.ABS_GLOBAL) viz.MainView.setEuler((0, 0, 0), viz.ABS_GLOBAL) viz.MainView.setEuler(start_dic[object[1]][1], viz.BODY_ORI, viz.ABS_GLOBAL) # load the maze yield maze.visible(viz.ON) # enable events joy_timer.setEnabled(viz.ON) coor_timer.setEnabled(viz.ON) write_onkey.setEnabled(viz.ON) quit_onkey.setEnabled(viz.ON) pos_timer.setEnabled(viz.ON) # reset and start the clock movement_time = TickTockTimer() movement_time.StartTimer() # wait for "collision" signal yield signal.wait() # disable all timers disable() write_trial_data() # turn maze off and then move maze.visible(viz.OFF) if (object != objects[len(objects) - 1]): yield move() trial_number = trial_number + 1 maze.remove()
def trial(name, conditions, nTrials=23, feedback=False, withSimple=True): stairs = ST.MultiStairs(conditions=conditions, nTrials=nTrials, withSimple=withSimple) TrialNo = 0 data = 'Scene, Condition, Stimuli, TrialNo, TimeStamp, Head_x, Head_y, Head_z, Head_yaw, Head_pitch, Head_roll\n' headfile = open( 'HeadData_' + str(sub_id) + '_' + str(name) + '_' + time.strftime("%d-%b-%y_%H-%M") + '.csv', 'a') headfile.write(data) for thisStimuli, thisCondition in stairs: TrialNo += 1 # set the orientation currStim = thisStimuli if currStim < 0: oriDirection = 'Left' correctKey = viz.KEY_LEFT else: oriDirection = 'Right' correctKey = viz.KEY_RIGHT print thisStimuli if thisCondition['label'] == 'Very Close': distance = 7 elif thisCondition['label'] == 'Close': distance = 6 elif thisCondition['label'] == 'Middle': distance = 5 elif thisCondition['label'] == 'Far': distance = 3 else: # this is the duration for the catch trials, don't make it too short! distance = 3.5 runningTime = 0.75 # Show the cross eyepatch.visible(viz.ON) Cross.visible(viz.ON) yield viztask.waitTime(1.5) Cross.visible(viz.OFF) eyepatch.visible(viz.OFF) waittime = random.uniform(0.5, 0.75) yield viztask.waitTime(waittime) # Show the environment Target.setPosition([0, 0, distance], viz.ABS_GLOBAL) Target.visible(viz.ON) # Show "Start" waittime = random.uniform(0.25, 0.75) yield viztask.waitTime(waittime) record = viztask.schedule( recording(headfile, name, thisCondition['label'], thisStimuli, TrialNo)) AnimateView(currStim) yield viztask.waitTime(runningTime) Target.visible(viz.OFF) iniTime = viz.tick() view.endAction() view.reset(viz.HEAD_POS) # get the response thisResp = None respTime = None d = yield viztask.waitKeyDown( (viz.KEY_RIGHT, 'q', 'escape', viz.KEY_LEFT)) record.kill() if thisResp is None: thisKey = d.key if thisKey == correctKey: thisResp = 1 if feedback: info.setText('Correct. Well done!') info.visible(viz.ON) yield viztask.waitTime(1) info.visible(viz.OFF) else: thisResp = 0 if feedback: info.setText('Not correct. Try it again.') info.visible(viz.ON) yield viztask.waitTime(1) info.visible(viz.OFF) # get the response time respTime = d.time - iniTime if currStim == 0: thisResp = 0 stairs.addResponse(thisResp) stairs.addOtherData('Response Time', respTime) stairs.addOtherData('Actual Trial No', TrialNo) waittime = random.uniform(0.5, 0.75) yield viztask.waitTime(waittime) stairs.saveAsExcel( str(sub_id) + '_' + str(name) + '_' + time.strftime("%d-%b-%y_%H-%M"))
def getCoords(source, destination): """ source should be a 3D connection device, and the destination should be a 3d node type """ def logScale(orientation): """ list or len() = 3 -> list of len 3 takes the orintation list and returns the log of the magnitude of each element , and then keeps the original sign ex) [ 10 , -10 ,1000] -> [1 , -1, 3] """ import math base = 2 mag_orientation = [] sign = [] #list of signs #make all elements positive, store original signs for element in orientation: if math.fabs(element) == element: #element is positive mag_orientation.append(element) sign.append(1) else: #element is negative mag_orientation.append(-1 * element) sign.append(-1) #handle case where number is zero, and set to 1 n = 0 for element in mag_orientation: if element == 0: mag_orientation[n] = 1 n += 1 #take log of each element log_orientation = [] for element in mag_orientation: log = math.log(element, base) log_orientation.append(log) #restablish original signs orientation = scalarMult(sign, log_orientation) return orientation #set source scale # scale1 = [.0001,.0001,.0001] # scale2 =[.01,.01,.01] #log log = False while True: yield viztask.waitTime(.01) position = source.getRawTranslation() orientation = source.getRawRotation() #sets the velocity of the glove (destination) to zero destination.setVelocity([0, 0, 0], viz.ABS_GLOBAL) destination.setAngularVelocity([0, 0, 0], viz.ABS_GLOBAL) #if selected do log scale on orientation if log == True: config.orientationVector = [.5, .5, .5] orientation = logScale(orientation) #rescale position position = scalarMult(position, config.positionVector) orientation = scalarMult(orientation, config.orientationVector) #invert signs of x and z x, y, z = position #invert signs of x and z rotations, and exchange b and a a, b, g = orientation orientation = [b, a, g] #print(orientation) destination.setPosition(position, viz.REL_PARENT) destination.setEuler(orientation, viz.REL_PARENT)
def trial(bl, tr, exp, log): print(str(tr + 1) + ' of ' + str(exp.nr_trials)) tr_vars = trial_vars_init(exp) ## prealocate space for hand_samples recording during task; not for hand_samples_check i.e. during check if at start position hand_samples_check = [] hand_times_check = [] hand_samples = [np.NaN] * 200 hand_times = [np.NaN] * 200 hand_samples_count = 0 tr_vars.t_trial_start = viz.tick() feedback = create_text2d(' ') feedback.visible(viz.OFF) tr_vars.interval_beforesearch = (random.randint(8, 10) / 10.0) ## retrieve shape settings ########################## #colors tr_vars.tar_col_name = exp.target_colors[log.tar_col[tr]] tr_vars.dis_condition = exp.distractor_colors[log.dis_col[tr]] if tr_vars.tar_col_name == 'red': tr_vars.tar_col = exp.red if exp.distractor_colors[log.dis_col[tr]] == 'same': tr_vars.dis_col = exp.red else: tr_vars.dis_col = exp.blue elif tr_vars.tar_col_name == 'blue': tr_vars.tar_col = exp.blue if exp.distractor_colors[log.dis_col[tr]] == 'same': tr_vars.dis_col = exp.blue else: tr_vars.dis_col = exp.red #shapes tr_vars.tar_shape = exp.target_shapes[log.tar_shape[tr]] tr_vars.tar_pos = log.tar_pos[tr] tr_vars.dis_pos = (tr_vars.tar_pos + log.dis_pos[tr]) % 4 # dis_pos_cont as continuous counting from tar_pos tr_vars.dis_pos_cont = log.dis_pos[tr] # dis_pos_rel as relative to tar_pos: negative is left from, positive is right from tr_vars.dis_pos_rel = tr_vars.dis_pos - tr_vars.tar_pos if tr_vars.tar_shape == 'diamond': shape1 = makeDiamond(tr_vars.tar_pos, tr_vars.tar_col) tr_vars.shapes_irrel.remove(tr_vars.tar_pos) shape2 = makeSphere(tr_vars.dis_pos, tr_vars.dis_col) tr_vars.shapes_irrel.remove(tr_vars.dis_pos) if len(tr_vars.shapes_irrel) != 2: raise Exception( 'length of shapes_irrel should be 2. length shapes_irrel: {}'. format(len(tr_vars.shapes_irrel))) shape3 = makeSphere(tr_vars.shapes_irrel[0], tr_vars.tar_col) shape4 = makeSphere(tr_vars.shapes_irrel[1], tr_vars.tar_col) elif tr_vars.tar_shape == 'sphere': shape1 = makeSphere(tr_vars.tar_pos, tr_vars.tar_col) tr_vars.shapes_irrel.remove(tr_vars.tar_pos) shape2 = makeDiamond(tr_vars.dis_pos, tr_vars.dis_col) tr_vars.shapes_irrel.remove(tr_vars.dis_pos) if len(tr_vars.shapes_irrel) != 2: raise Exception( 'length of shapes_irrel should be 2. length shapes_irrel: {}'. format(len(tr_vars.shapes_irrel))) shape3 = makeDiamond(tr_vars.shapes_irrel[0], tr_vars.tar_col) shape4 = makeDiamond(tr_vars.shapes_irrel[1], tr_vars.tar_col) shape1.visible(viz.OFF) shape2.visible(viz.OFF) shape3.visible(viz.OFF) shape4.visible(viz.OFF) #implement sound shape1_sound = shape1.playsound('./sounds/0737.wav') shape1_sound.pause() shape2_sound = shape2.playsound('./sounds/0739.wav') shape2_sound.pause() shape3_sound = shape3.playsound('./sounds/0739.wav') shape3_sound.pause() shape4_sound = shape4.playsound('./sounds/0739.wav') shape4_sound.pause() hand_samples_check.append('check_start') hand_times_check.append(viz.tick()) old_sample = m_hand.getPosition() hand_samples_check.append(old_sample) hand_times_check.append(viz.tick()) tr_vars.t_on_start = 0 pls_break = 0 while True: new_sample = m_hand.getPosition() if not (new_sample == old_sample): hand_samples_check.append(new_sample) hand_times_check.append(viz.tick()) old_sample = new_sample tr_vars.finger_on_start = checkTouch(exp.start_pos, new_sample, exp.min_dist_start) # option to recalibrate in trial if viz.key.isDown('a'): yield calibrateHand() feedback.message("Press -0- to continue") feedback.visible(viz.ON) yield viztask.waitKeyDown(viz.KEY_KP_0) feedback.visible(viz.OFF) # wait for time after pp touch start before presenting shapes # make sure they stay on start until shapes are presented # if they move time after start counter resets if tr_vars.finger_on_start and tr_vars.t_on_start == 0: tr_vars.t_on_start = viz.tick() elif not tr_vars.finger_on_start and not tr_vars.t_on_start == 0: tr_vars.t_on_start = 0 elif tr_vars.finger_on_start and ( viz.tick() - tr_vars.t_on_start) > tr_vars.interval_beforesearch: pls_break = 1 if pls_break: break if ((viz.tick() - tr_vars.t_trial_start) > 2.5) and (tr_vars.long_start == 0): feedback.message("Move finger to start position") feedback.visible(viz.ON) tr_vars.long_start = 1 elif ( (viz.tick() - tr_vars.t_trial_start) > 4) and (tr_vars.long_start): feedback.visible(viz.OFF) yield viz.waitTime(0.001) feedback.visible(viz.OFF) shape1.visible(viz.ON) shape2.visible(viz.ON) shape3.visible(viz.ON) shape4.visible(viz.ON) # t in seconds tr_vars.t_search_on = viz.tick() hand_samples[hand_samples_count] = 'start_task' hand_times[hand_samples_count] = tr_vars.t_search_on hand_samples_count += 1 pls_break = 0 while True: new_sample = m_hand.getPosition() if not (new_sample == old_sample): hand_samples[hand_samples_count] = new_sample hand_times[hand_samples_count] = viz.tick() hand_samples_count += 1 old_sample = new_sample if checkTouch(exp.shape_positions[tr_vars.tar_pos], new_sample, exp.min_dist_shape): tr_vars.finger_on_target = 1 tr_vars.finger_on_shape = tr_vars.tar_pos shape1_sound.play() shape1.visible(viz.OFF) pls_break = 1 elif checkTouch(exp.shape_positions[tr_vars.dis_pos], new_sample, exp.min_dist_shape): tr_vars.finger_on_distractor = 1 tr_vars.finger_on_shape = tr_vars.dis_pos shape2_sound.play() shape2.visible(viz.OFF) pls_break = 1 else: for idx, position_irrel in enumerate(tr_vars.shapes_irrel): if checkTouch(exp.shape_positions[position_irrel], new_sample, exp.min_dist_shape): if idx == 0: shape3_sound.play() shape3.visible(viz.OFF) elif idx == 1: shape4_sound.play() shape4.visible(viz.OFF) tr_vars.finger_on_filler = 1 tr_vars.finger_on_shape = position_irrel pls_break = 1 if pls_break: break # break after display has been presented for 1 second if (viz.tick() - tr_vars.t_search_on) >= exp.max_search_time: break yield viz.waitTime(0.001) t_search_off = viz.tick() tr_vars.search_time = t_search_off - tr_vars.t_search_on if not tr_vars.finger_on_shape == -1: hand_samples[hand_samples_count] = 'on_shape' hand_times[hand_samples_count] = viz.tick() hand_samples_count += 1 while (viz.tick() - t_search_off) < 0.25: new_sample = m_hand.getPosition() if not (new_sample == old_sample): hand_samples[hand_samples_count] = new_sample hand_times[hand_samples_count] = viz.tick() hand_samples_count += 1 old_sample = new_sample yield viz.waitTime(0.001) shape1.remove() shape2.remove() shape3.remove() shape4.remove() shape1_sound.remove() shape2_sound.remove() shape3_sound.remove() shape4_sound.remove() hand_samples[hand_samples_count] = 'end_task' hand_times[hand_samples_count] = viz.tick() # add time threshold if tr_vars.finger_on_target and (tr_vars.search_time <= exp.reach_end_cutoff_t): feedback_correct_sound.play() feedback.message("Correct") elif tr_vars.finger_on_distractor or tr_vars.finger_on_filler: feedback_wrongshape_sound.play() feedback.message("Wrong shape") else: feedback_tooslow_sound.play() feedback.message("Too slow") feedback.visible(viz.ON) feedback_on = viz.tick() ## LOG SHIZZLE ## ################# #don't log: del tr_vars.dis_col del tr_vars.tar_col # split filler pos tr_vars.filler1_pos, tr_vars.filler2_pos = tr_vars.shapes_irrel del tr_vars.shapes_irrel ## TRIAL & BEHAV DATA LOG ## # trial_attr = 'pp_nr,pp_id,session,block,trial' trial_string = str(exp.pp_nr) + ',' + str( exp.pp_id) + ',' + exp.name + ',' + str(bl) + ',' + str(tr) # add all attr from tr_vars for attr, value in tr_vars.__dict__.iteritems(): if not attr.startswith('__'): # trial_attr += ',' + str(attr) trial_string += ',' + str(value) # add relevant attr from exp for attr in exp.tolog_exp_vars: # trial_attr += ',' + str(attr) trial_string += ',' + str(getattr(exp, attr)) trial_string += '\n' with open(exp.data_log_file, 'a') as f: f.write(trial_string) # print(trial_attr) ## HAND DATA LOG ## if not len(hand_samples) == len(hand_times): raise ValueError('nr of hand_samples not same as nr of hand times') with open(exp.data_hand_file, 'a') as f: f.write('{0} start_trial {1}\n'.format(tr_vars.t_trial_start, tr)) f.write('COORD start {0}\n'.format(' '.join(map(str, exp.start_pos)))) f.write('COORD target {0}\n'.format(' '.join( map(str, exp.shape_positions[tr_vars.tar_pos])))) f.write('COORD distractor {0}\n'.format(' '.join( map(str, exp.shape_positions[tr_vars.dis_pos])))) f.write('COORD filler1 {0}\n'.format(' '.join( map(str, exp.shape_positions[tr_vars.filler1_pos])))) f.write('COORD filler2 {0}\n'.format(' '.join( map(str, exp.shape_positions[tr_vars.filler2_pos])))) f.write('VAR pp_nr {0}\n'.format(exp.pp_nr)) f.write('VAR pp_id {0}\n'.format(exp.pp_id)) f.write('VAR block_nr {0}\n'.format(bl)) f.write('VAR tar_pos {0}\n'.format(tr_vars.tar_pos)) f.write('VAR dis_pos {0}\n'.format(tr_vars.dis_pos)) f.write('VAR dis_pos_rel {0}\n'.format(tr_vars.dis_pos_rel)) f.write('VAR dis_pos_cont {0}\n'.format(tr_vars.dis_pos_cont)) f.write('VAR tar_col {0}\n'.format(tr_vars.tar_col_name)) f.write('VAR dis_condition {0}\n'.format(tr_vars.dis_condition)) f.write('VAR tar_shape {0}\n'.format(tr_vars.tar_shape)) f.write('VAR exp_type {0}\n'.format(exp.name)) for xd, sample in enumerate(hand_samples_check): if isinstance(sample, str): f.write('MSG {0} {1}\n'.format(hand_times_check[xd], sample)) else: f.write('{0} {1}\n'.format(hand_times_check[xd], ' '.join(map(str, sample)))) for xd, sample in enumerate(hand_samples): if isinstance(sample, float) and isnan(sample): # print('break on hand_sample nr {}'.format(xd)) break elif isinstance(sample, str): f.write('MSG {0} {1}\n'.format(hand_times[xd], sample)) else: f.write('{0} {1}\n'.format(hand_times[xd], ' '.join(map(str, sample)))) # update variable time cutoff exp.reach_end_cutoff_list = exp.reach_end_cutoff_list[1:] + [ tr_vars.search_time ] exp.reach_end_cutoff_t = np.percentile(exp.reach_end_cutoff_list, 80) yield viztask.waitTime(1 - (viz.tick() - feedback_on)) feedback.remove() feedback_correct_sound.stop() feedback_wrongshape_sound.stop() feedback_tooslow_sound.stop()
def trial_down (): global k k = 0 global x x = 0 for i in range (100): yield viztask.waitTime(.5) ready_text = viz.addText3D('Get ready!',pos = [-2,1.7,20]) ready_text.color(0,0,0) yield viztask.waitTime(1) ready_text.remove () yield viztask.waitTime(2) yield room () doors = [] D1 = random.choice([-4.25,-3.25,-2.25,-1.25]) D2 = random.choice([4.75,5.75,6.75,7.75]) D3 = random.choice([13.75,14.75,15.75,16.75]) D4 = random.choice([22.75,23.75,24.75,25.75]) D5 = random.choice([31.75,32.75,33.75,34.75]) L_doors = [] L_doors.append(D1) L_doors.append(D2) L_doors.append(D3) L_doors.append(D4) L_doors.append(D5) D7 = random.choice([-4.25,-3.25,-2.25,-1.25]) D8 = random.choice([4.75,5.75,6.75,7.75]) D9 = random.choice([13.75,14.75,15.75,16.75]) D10 = random.choice([22.75,23.75,24.75,25.75]) D11 = random.choice([31.75,32.75,33.75,34.75]) R_doors = [] R_doors.append(D7) R_doors.append(D8) R_doors.append(D9) R_doors.append(D10) R_doors.append(D11) people = [] P1 = random.choice([9.25,10.25,11.25,12.25,18.25,19.25,20.25,21.25]) P2 = random.choice([27.25,28.25,29.25,30.25,36.25,37.25,38.25,39.25]) L_people = [] L_people.append(P1) L_people.append(P2) P3 = random.choice([9.25,10.25,11.25,12.25,18.25,19.25,20.25,21.25]) P4 = random.choice([27.25,28.25,29.25,30.25,36.25,37.25,38.25,39.25]) R_people = [] R_people.append(P3) R_people.append(P4) targ = random.choice(targets) if targ == 2.5: size = .051006 if targ == 3.5: size = .071409 if targ == 4.8: size = .097932 if targ == 6.2: size = .126495 if targ == 7.6: size = .155059 if targ == 9: size = .183622 if targ == 10.4: size = .212186 if targ == 11.8: size = .240749 if targ == 13.2: size = .269313 if targ == 14.6: size = .297876 if targ == 17.4: size = .355003 if targ == 20.2: size = .41213 if targ == 23: size = .469257 if targ == 25.8: size = .526384 if targ == 30: size = .612075 if targ == 38: size = .775295 print targ sphere = vizshape.addSphere((size),20,20) sphere.color(1.02,.444,0) sphere.setPosition([0,(size),(targ)]) shadow = vizshape.addCircle((size),20) shadow.color([.05,.05,.05]) #proportion of 1 for amount of each color (red, green, blue). 0,0,0 = black, 1,1,1 = white. shadow.setEuler([0,90,0]) shadow.setPosition([0,.001,(targ)]) for z in np.asarray(L_doors): door = vizshape.addBox(size=[.04445,2.13,.91]) door.texture(wood) door.setPosition([-4.9733,1.065,float(z)]) doors.append(door) doorknob = vizshape.addSphere(radius=.045,axis=vizshape.AXIS_X) doorknob.color(viz.YELLOW) doorknob.setPosition(-4.9396,1,(float(z)-.3364)) doors.append(doorknob) for z in np.asarray(R_doors): door = vizshape.addBox(size=[.04445,2.13,.91]) door.texture(wood) door.setPosition([4.9683,1.065,float(z)]) doors.append(door) doorknob = vizshape.addSphere(radius=.045,axis=vizshape.AXIS_X) doorknob.color(viz.YELLOW) doorknob.setPosition(4.9396,1,(float(z)-.3364)) doors.append(doorknob) for z in np.asarray(L_people): o = random.choice([0,90,180]) person = viz.addAvatar('vcc_female.cfg',euler=(float(o),0,0)) person.setPosition([-4.25,0,float(z)]) person.state(1) people.append(person) for z in np.asarray(R_people): o = random.choice([0,180,270]) person = viz.addAvatar('vcc_female.cfg',euler=(float(o),0,0)) person.setPosition([4.5,0,float(z)]) person.state(1) people.append(person) en_env() tic = time.time() yield viztask.waitTime(.01) time.sleep(.09+x) toc = time.time () mask.enable(viz.RENDERING) dis_env() sphere.remove () shadow.remove () for door in np.asarray(doors): door.remove() for person in np.asarray(people): person.remove() yield viztask.waitTime(1) mask.disable(viz.RENDERING) print toc - tic viz.callback(viz.KEYDOWN_EVENT,KeyEvents) yield viztask.waitKeyDown(viz.KEY_KP_ENTER) if k == 1: break times.append((toc - tic)+.01) print times
def mechanics(self): """tutorial mechanics: moves the dog outline around the environment and waits for the dog to be snapped to it before preforming the next action.""" if self.iterations == 0: #setting conditions for position transformations along single axis # model.pointer.setParent(viz.WORLD) config.orientationVector = [0, 0, 0] proxList.append(self.dogCenter) # elif self.iterations ==3: # #setting conditions for position transformations along all axes # proxList.remove(self.dogCenter) # elif self.iterations==4: # #setting conditinos for angular transformations # proxList.append(self.dogCenter) # config.orientationVector = self.origOrienVec # config.positionVector = [0,0,0] ## model.pointer.setPosition(0,1,-1) ## model.pointer.color(0,0,5) elif self.iterations == 3: #setting conditions for positional and angular transformations # model.pointer.color(self.startColor) # model.pointer.setParent(model.display.camcenter) proxList.remove(self.dogCenter) config.orientationVector = self.origOrienVec config.positionVector = self.origPosVec if self.iterations <= 0: # X AXIS POS TRANSFORMATION config.positionVector = [.0001, 0, 0] recordData.event(event='ROUND ' + str(self.iterations), result='move along x-axis') randomPos = [4 * (random.random() - 0.5), 0, 0] self.movePos = vizact.move(randomPos[0], randomPos[1], randomPos[2], time=animateOutline) yield viztask.waitTime(1) yield viztask.addAction(self.outlineCenter, self.movePos) elif self.iterations > 0 and self.iterations <= 1: #Y AXIS POS TRANS config.positionVector = [0, .0001, 0] recordData.event(event='ROUND ' + str(self.iterations), result='move along y-axis') randomPos = [0, 2 * (random.random() - 0.5), 0] self.movePos = vizact.move(randomPos[0], randomPos[1], randomPos[2], time=animateOutline) yield viztask.waitTime(1) yield viztask.addAction(self.outlineCenter, self.movePos) elif self.iterations > 1 and self.iterations <= 2: #Z AXIS POS TRANS config.positionVector = [0, 0, .0001] recordData.event(event='ROUND ' + str(self.iterations), result='move along z-axis') randomPos = [0, 0, 4 * (random.random() - 0.5)] self.movePos = vizact.move(randomPos[0], randomPos[1], randomPos[2], time=animateOutline) yield viztask.waitTime(1) yield viztask.addAction(self.outlineCenter, self.movePos) elif self.iterations > 2 and self.iterations <= 3: #ALL AXES POS TRANS config.positionVector = self.origPosVec recordData.event(event='ROUND ' + str(self.iterations), result='move along all axis') randomPos = [0, 1, -1] self.movePos = vizact.moveTo(randomPos, time=animateOutline) yield viztask.waitTime(1) yield viztask.addAction(self.outlineCenter, self.movePos) # # elif self.iterations>3 and self.iterations<=4: # #X AXIS ANG TRANS # config.orientationVector = [.01,0,0] # model.pointer.setEuler(0,0,0) # recordData.event(event = 'ROUND ' + str(self.iterations), result = 'euler about x-axis') # thisEuler = [0,0,0] # thisEuler[1] = random.randint(-100,100) # self.moveAng = vizact.spinTo(euler = thisEuler, time = animateOutline, mode = viz.REL_GLOBAL) # yield viztask.waitTime(1) # yield viztask.addAction(self.outlineCenter, self.moveAng) # # elif self.iterations>4 and self.iterations<=5: # #Y AXIS ANG TRANS # config.orientationVector = [0,.01,0] # model.pointer.setEuler(0,0,0) # recordData.event(event = 'ROUND ' + str(self.iterations), result = 'euler about y-axis') # thisEuler = [0,0,0] # thisEuler[0] = random.randint(-100,100) # self.moveAng = vizact.spinTo(euler = thisEuler, time = animateOutline, mode = viz.REL_GLOBAL) # yield viztask.waitTime(1) # yield viztask.addAction(self.outlineCenter, self.moveAng) # # elif self.iterations>5 and self.iterations<=6: # #Z AXIS ANG TRANS # config.orientationVector = [0,0,.01] # model.pointer.setEuler(0,0,0) # recordData.event(event = 'ROUND ' + str(self.iterations), result = 'euler about z-axis') # thisEuler = [0,0,0] # thisEuler[2] = random.randint(-100,100) # self.moveAng = vizact.spinTo(euler = thisEuler, time = animateOutline, mode = viz.REL_GLOBAL) # yield viztask.waitTime(1) # yield viztask.addAction(self.outlineCenter, self.moveAng) # # elif self.iterations>6 and self.iterations<=7: # #ALL AXES ANG TRANS # config.orientationVector = self.origOrienVec # model.pointer.setEuler(0,0,0) # recordData.event(event = 'ROUND ' + str(self.iterations), result = 'euler about all axis') # randomEuler = [random.randint(-100,100),random.randint(-100,100),random.randint(-100,100)] # self.moveAng = vizact.spinTo(euler = randomEuler, time = animateOutline) # yield viztask.waitTime(1) # yield viztask.addAction(self.outlineCenter, self.moveAng) elif self.iterations > 3 and self.iterations <= 9: #ALL AXES POS AND ANG TRANS recordData.event(event='ROUND ' + str(self.iterations), result='move along all axis') randomPos = [ 4 * (random.random() - 0.5), 2 * (random.random() - 0.5), 4 * (random.random() - 0.5) ] # randomEuler = [random.randint(-90,90),random.randint(-90,90),random.randint(-90,90)] self.movePos = vizact.moveTo(randomPos, time=animateOutline) # self.moveAng = vizact.spinTo(euler = randomEuler, time = animateOutline) transition = vizact.parallel(self.movePos) yield viztask.waitTime(1) yield viztask.addAction(self.outlineCenter, transition) else: #END menu.ingame.toggle() config.orientationVector = self.origOrienVec config.positionVector = self.origPosVec recordData.event(event='FINISHED', result='FINISHED') self.iterations = self.iterations + 1
def rvd_task(self): # make 3D surface to put object on / like a table in front of participant self.rvd_table.setPosition( [self.maze.start_pos[0], .5, self.maze.start_pos[2] + .5]) # move a bit away self.rvd_table.visible(viz.ON) sc = .03 # manually set scale factor of 3D objects self.maze.global_landmark.setScale(.03 * sc, .03 * sc, .03 * sc) self.maze.maze_end_ground.setScale(sc, sc, sc) # make a bit bigger self.maze.maze_start_ground.setScale(sc, sc, sc) # make a bit bigger self.maze.maze_start_ground.color(viz.YELLOW) # set start position as anchor y_offset = 1.0 z_offset = .4 scale_factor = 20 s_scaled = [ x / scale_factor for x in self.maze.maze_start_ground.getPosition() ] l_scaled = [ x / scale_factor for x in self.maze.maze_end_ground.getPosition() ] g_scaled = [ x / scale_factor for x in self.maze.global_landmark.getPosition() ] # get difference to correct the offset of to the start position ground abs_x_diff = abs(self.maze.maze_start_ground.getPosition()[0]) - abs( s_scaled[0]) # add/subtract offset in x direction if self.maze.maze_start_ground.getPosition()[0] < 0: s_scaled[0] = s_scaled[0] - abs_x_diff l_scaled[0] = l_scaled[0] - abs_x_diff g_scaled[0] = g_scaled[0] - abs_x_diff else: s_scaled[0] = s_scaled[0] + abs_x_diff l_scaled[0] = l_scaled[0] + abs_x_diff g_scaled[0] = g_scaled[0] + abs_x_diff # subtract z to table location and add offset on z direction combined_offset = self.maze.maze_start_ground.getPosition( )[2] + z_offset s_scaled[2] = s_scaled[2] + combined_offset l_scaled[2] = l_scaled[2] + combined_offset g_scaled[2] = g_scaled[2] + combined_offset # add height of table in y direction s_scaled[1] = s_scaled[1] + y_offset l_scaled[1] = l_scaled[1] + y_offset g_scaled[1] = g_scaled[1] + y_offset # set position of objects self.maze.maze_start_ground.setPosition(s_scaled) self.maze.maze_end_ground.setPosition(l_scaled) self.maze.global_landmark.setPosition(g_scaled) # # compute scaled, z_offseted (moved a bit forward) triangle of objects once and then make objects visible or not # scale_factor = 30 # # # set start position as anchor # z_offset = .2 # # self.maze.maze_start_ground.setPosition(self.maze.start_pos[0], 1.0, self.maze.start_pos[2] + z_offset) # # # set position of global landmark: only differs in z dimension from start position # z_dist_landmark_start = abs(self.maze.global_landmark.getPosition()[2] - self.maze.maze_start_ground.getPosition()[2]) / scale_factor # self.maze.global_landmark.setPosition([self.maze.maze_start_ground.getPosition()[0], # self.maze.maze_start_ground.getPosition()[1], # self.maze.maze_start_ground.getPosition()[2] + z_dist_landmark_start]) # # # set position of local landmark: differs in x and z dimensions from start position # x_dist_local_start = abs(self.maze.maze_end_ground.getPosition()[0] - self.maze.maze_start_ground.getPosition()[0]) / scale_factor # z_dist_local_start = (self.maze.maze_end_ground.getPosition()[2] - self.maze.maze_start_ground.getPosition()[2]) / scale_factor # # if self.maze.maze_end_ground.getPosition()[0] < 0: # self.maze.maze_end_ground.setPosition([self.maze.maze_start_ground.getPosition()[0] - x_dist_local_start, # self.maze.maze_start_ground.getPosition()[1], # self.maze.maze_start_ground.getPosition()[2] + z_dist_local_start]) # else: # self.maze.maze_end_ground.setPosition([self.maze.maze_start_ground.getPosition()[0] + x_dist_local_start, # self.maze.maze_start_ground.getPosition()[1], # self.maze.maze_start_ground.getPosition()[2] + z_dist_local_start]) # send positions of all target objects if self.current_trial_run is 1: event = 'type:rvd_triangle;S:' + str(self.maze.maze_start_ground.getPosition()) + \ ';L:' + str(self.maze.maze_end_ground.getPosition()) + \ ';G:' + str(self.maze.global_landmark.getPosition()) + ';' self.log_exp_progress(event) # make different objects visible and guess third object object_to_guess = self.rvd_list_all[int(self.subject_id) - 1] object_to_guess = object_to_guess[int(self.current_trial_run) - 1] marker_object_to_guess = object_to_guess if object_to_guess is 'G': object_to_guess = self.maze.global_landmark elif object_to_guess is 'L': object_to_guess = self.maze.maze_end_ground elif object_to_guess is 'S': object_to_guess = self.maze.maze_start_ground # move somewhere out of sight before making visible so not to indicate correct solution for 1 frame object_to_guess.setPosition([0, 0, -10]) self.maze.maze_end_ground.visible(viz.ON) self.maze.maze_start_ground.visible(viz.ON) self.maze.global_landmark.visible(viz.ON) # start tracking with mouseclick self.scene.change_instruction("Platzieren Sie das fehlende Objekt.") print '!!! EXPERIMENTER CLICK MOUSE TO START RVD TASK THEN PARTICIPANTS HAS TO CONFIRM PLACEMENT WITH TRIGGER!!!' yield self.hide_inst_continue_left_mouse() self.log_exp_progress("event:rvd_start;") # track object self.rvd_feedback = vizact.onupdate(0, self.track_rvd, object_to_guess) # place target with button yield self.hide_inst_continue_trigger() print '!!! OBJECT PLACED !!!' self.log_exp_progress("event:rvd_target_placed;object_location:"+\ str(object_to_guess.getPosition())+';'+\ 'object:'+marker_object_to_guess +';') self.rvd_feedback.remove() self.scene.change_instruction("Danke! Einen Moment...") # keep in view for 2 seconds yield viztask.waitTime(3) self.log_exp_progress("event:rvd_end;") self.rvd_task_on = False # hide objects self.rvd_table.visible(viz.OFF) self.maze.maze_start_ground.color(viz.WHITE) self.maze.maze_start_ground.visible(viz.OFF) self.maze.global_landmark.visible(viz.OFF) self.maze.maze_end_ground.visible(viz.OFF)
def experiment(side): yield viztask.waitNetwork(serverName) yield Practice(1, Target) for i in range(len(Sequence)): block = (i + 1) * 2 if side == 'LR': if i == 0 or i == 2: viewLink.preEuler([-10, 0, 0], target=viz.LINK_ORI_OP) else: viewLink.preEuler([10, 0, 0], target=viz.LINK_ORI_OP) else: if i == 0 or i == 2: viewLink.preEuler([10, 0, 0], target=viz.LINK_ORI_OP) else: viewLink.preEuler([-10, 0, 0], target=viz.LINK_ORI_OP) if Sequence[i] == 'C' or Sequence[i] == 'c': clouds = flashingCloud(3, 12, 12, 1, 5250, Target, freq) refresh = viztask.schedule(refreshing(clouds)) yield viztask.waitNetwork(serverName) info.setText('Block ' + str(block)) info.visible(viz.ON) yield viztask.waitTime(2) info.visible(viz.OFF) yield trialSetting_Exp(block, Target) for c in clouds: c.remove() refresh.kill() elif Sequence[i] == 'L' or Sequence[i] == 'l': yield viztask.waitNetwork(serverName) info.setText('Block ' + str(block)) info.visible(viz.ON) yield viztask.waitTime(2) info.visible(viz.OFF) yield trialSetting_Exp(block, Target) elif Sequence[i] == 'O' or Sequence[i] == 'o': Target.alpha(0) door = door_line(2.5, 0.5, 2) door.setParent(Target) door.setPosition([0, -1.5, 0], viz.REL_PARENT) door.zoffset(-1) outlineRoom = room_line(3, 12, 12, 2) outlineRoom.setParent(Target) outlineRoom.setPosition([0, -1.5, 0], viz.REL_PARENT) yield viztask.waitNetwork(serverName) info.setText('Block ' + str(block)) info.visible(viz.ON) yield viztask.waitTime(2) info.visible(viz.OFF) yield trialSetting_Exp(block, door) door.remove() outlineRoom.remove() Target.alpha(1) elif Sequence[i] == 'F' or Sequence[i] == 'f': Target.alpha(0) door = doorway(2.5, 0.5, 0.025) door.setParent(Target) door.setPosition([0, -1.5, 0], viz.REL_PARENT) door.zoffset(-1) room_env = RoomCreator(12, 12, 3, 1) room_env.setParent(Target) room_env.setPosition([0, -1.5, -11], viz.REL_PARENT) yield viztask.waitNetwork(serverName) info.setText('Block ' + str(block)) info.visible(viz.ON) yield viztask.waitTime(2) info.visible(viz.OFF) yield trialSetting_Exp(block, door) room_env.remove() door.remove() Target.alpha(1) viewLink.reset(viz.RESET_OPERATORS) yield Practice(block + 1, Target) info.setText('End of the Experiment.') info.visible(viz.ON) yield viztask.waitTime(90) viz.quit()
def InitalSetup(train): # t1 = viz.add('Assets/Textures/black.png') # wall1 = vizshape.addCube() # Setup black room for start and fade transition # wall1.setScale([10,5,0.2]) # wall1.setPosition(0,1,10) # wall1.texture(t1) # # wall2 = vizshape.addCube() # wall2.setScale([10,5,0.2]) # wall2.setPosition(0,1,20) # wall2.texture(t1) # # wall3 = vizshape.addCube() # wall3.setScale([0.2,5,10]) # wall3.setPosition(5,1,15) # wall3.texture(t1) # # wall4 = vizshape.addCube() # wall4.setScale([0.2,5,10]) # wall4.setPosition(-5,1,15) # wall4.texture(t1) # # wall5 = vizshape.addCube() # wall5.setScale([10,0.2,10]) # wall5.setPosition(0,2.5,15) # wall5.texture(t1) # # wall6 = vizshape.addCube() # wall6.setScale([10,1.0,10]) # wall6.setPosition(0,1.0,15) # wall6.texture(t1) text3D = viz.addText3D('Press Space to begin', pos=[ 0, 0.5, 20 ]) # Create text & position infront of player at a readable distance text3D.alignment(viz.ALIGN_CENTER_BOTTOM) text3D.setScale(1, 1, 1) text3D.setEuler(0, 0, 0) text3D.setReferenceFrame(viz.RF_EYE) text3D.disable( [viz.LIGHTING, viz.INTERSECTION, viz.DEPTH_TEST, viz.SHADOW_CASTING]) text3D.drawOrder(101) global spacePressed global playerOnTrain if (SetupHMD.hmdconnected): SetupHMD.SetRotation(0) SetupHMD.SetPos([0, 0, 15]) else: viz.MainView.setPosition([0, 1, 11]) while (spacePressed is not True): yield viztask.waitFrame(1) if (SetupHMD.hmdconnected): SetupHMD.SetRotation(180) trainPos = train.getPosition() trainPos[1] += 1.5 trainPos[2] += 1.6 SetupHMD.SetPos(trainPos) else: pos = train.getPosition(viz.ABS_GLOBAL) pos[0] += 0.3 # Along Seat pos[1] = 1.7 # Eye Height pos[2] += 1.3 # Depth viz.MainView.setPosition(pos) viz.MainView.setEuler(180, 0, 0) yield viztask.waitTime(0.1) text3D.remove() spacePressed = False playerOnTrain = True viztask.schedule(StationReached())
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) self.SAVEDATA = True # switch saving data on. 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) trial_radii = self.ConditionList_radii[ trialtype] #set radii for that trial trial_occl = self.ConditionList_occl[ trialtype] #set target number for the trial. print(str([trial_radii, trial_occl])) txtDir = "" ######choose correct road object.###### #print ("Length of bend array:", len(self.rightbends) radius_index = self.FACTOR_radiiPool.index(trial_radii) if trialtype_signed > 0: #right bend trialbend = self.rightbends[radius_index] txtDir = "R" else: trialbend = self.leftbends[radius_index] txtDir = "L" 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_occl) else: msg = "Radius: Straight" + txtDir + '_' + str(trial_occl) txtCondt.message(msg) #update class trial parameters# self.Trial_N = i self.Trial_radius = trial_radii self.Trial_occlusion = trial_occl self.Trial_BendObject = trialbend #translate bend to driver position. driverpos = viz.MainView.getPosition() print driverpos trialbend.setPosition(driverpos[0], 0, driverpos[2]) #now need to set orientation driverEuler = viz.MainView.getEuler() trialbend.setEuler(driverEuler, viz.ABS_GLOBAL) #will need to save initial vertex for line origin, and Euler. Is there a nifty way to save the relative position to the road? self.driver.setSWA_invisible() yield viztask.waitTime( trial_occl ) #wait an occlusion period. Will viztask waitime work within a class? trialbend.visible(1) yield viztask.waitTime( self.VisibleRoadTime - trial_occl ) #after the occlusion add the road again. 2.5s to avoid ceiling effects. trialbend.visible(0) #driver.setSWA_visible() def checkCentred(): centred = False x = self.driver.getPos() if abs(x) < .5: centred = True return (centred) ##wait a while print "waiting" #TODO: Recentre the wheel on automation. yield viztask.waitTrue(checkCentred) print "waited" self.driver.setSWA_visible() yield viztask.waitTime(2) #wait for input . #loop has finished. CloseConnections(self.EYETRACKING)
def MyTask(): yield viztask.waitTime(.5) viz.window.displayHTML('F:\Lab 2\index.html', size=[1200, 600], pos=[30, 30, -30]) head_tracker.setEuler([0, 0, 0])
def scenesTask(): while True: # Scene 1 events vp1[0].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp1[0].remove(display) vp1[1].add(display) vizconnect.resetViewpoints() scene1.waterSound.volume(0.05) scene1.choir_sound.minmax(0, 3) yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) scene1.waterSound.volume(0.2) scene1.choir_sound.minmax(5, 15) jumpFlash() vp1[1].remove(display) vp1[2].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp1[2].remove(display) vp1[3].add(display) vizconnect.resetViewpoints() scene1.timer.setEnabled(viz.ON) yield viztask.waitEvent(scene1.WATER_RISE_EVENT) yield scene1.BlurTask() scene1.enableUnderWater() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) manager.removeSensor(scene1.stoneSensor) jumpFlash() vp1[3].remove(display) # Scene 2 events scene1.setActive(False) scene2.setActive(True) grabTool.setItems(scene2.getGrabObjects()) vp2[0].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp2[0].remove(display) vp2[1].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp2[1].remove(display) vp2[2].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp2[2].remove(display) vp2[3].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) vp2[3].remove(display) # Scene 3 events scene2.setActive(False) scene3.setActive(True) vp3[0].add(display) vizconnect.resetViewpoints() yield viztask.waitAny([waitKey1, wait10]) scene3.lowerBox() yield viztask.waitAny([waitKey2, wait10]) scene3.raiseWalls() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp3[0].remove(display) vp3[1].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp3[1].remove(display) vp3[2].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash() vp3[2].remove(display) vp3[3].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) vp3[3].remove(display) scene3.setActive(False) scene3.raiseBox() scene1.setActive(True)
def runtrials(self): """Loops through the trial sequence""" viz.MainScene.visible(viz.ON, viz.WORLD) viz.mouse.setVisible(viz.OFF) #switch mouse off viz.clearcolor( viz.SKYBLUE) #HACK, since eyetracker background is white. if self.EYETRACKING: #pass it the filename, and also the timestamp. et_file = str(self.EXP_ID) + '_' + str( self.PP_id) #one file for the whole task. self.comms.start_trial(fname=et_file, timestamp=viz.tick()) if self.EYETRACKING: #viz.MainScene.visible(viz.OFF,viz.WORLD) #remove straight self.Straight.ToggleVisibility(0) filename = str(self.EXP_ID) + "_Calibration_" + str( self.PP_id ) #+ str(demographics[0]) + "_" + str(demographics[2]) #add experimental block to filename print(filename) # Start logging the pupil data pupilfile = gzip.open( os.path.join("Data", filename + ".pupil.jsons.gz"), 'a') closer = pupil_logger.start_logging(pupilfile, timestamper=viz.tick) def stop_pupil_logging(): closer() pupilfile.close() EXIT_CALLBACKS.insert(0, stop_pupil_logging) yield run_calibration(self.comms, filename) yield run_accuracy(self.comms, filename) #put straight visible self.Straight.ToggleVisibility(1) #add message after calibration to give the experimenter and participant time to prepare for the simulation. self.markers = Markers() #set up distractor task if self.DISTRACTOR_TYPE is not None: distractorfilename = str(self.EXP_ID) + '_' + str( self.PP_id) + '_distractor_' Distractor = Count_Adjustable.Distractor( distractorfilename, self.targetnumber, ppid=1, startscreentime=self.StartScreenTime, triallength=np.inf, ntrials=len(self.TRIALSEQ_df.index)) else: Distractor = None #set up scene before eyetracking self.driver = vizdriver.Driver(self.caveview, Distractor) viz.message( '\t\tYou will now begin the experiment \n\n The automated vehicle will attempt to navigate a series of bends. \nYour task as the supervisory driver is to make sure the vehicle stays within the road edges. \nDuring automation please keep your hands loosely on the wheel. \nYou may take control by pressing the gear pads. \nOnce pressed, you will immediately be in control of the vehicle \n\n Please fixate the centre of the calibration point in between trials' ) self.ToggleTextVisibility(viz.ON) for i, trial in self.TRIALSEQ_df.iterrows(): #if half-way through do accuracy test. #Trial loop has finished. if i == int(np.round(self.total_trials / 2, 0)): if self.EYETRACKING: self.markers.markers_visibility( 0) #remove markers for calibration self.Straight.ToggleVisibility(0) accuracy_filename = filename + '_middle' yield run_accuracy(self.comms, accuracy_filename) yield viztask.waitTime( 1) #a second pause before going into self.markers.markers_visibility( 1) #remove markersthe next trial self.Straight.ToggleVisibility(1) #import vizjoy print("Trialn: ", str(i)) print("current trial:", trial) #trial is now a row from a dataframe print("current trial radius:", trial["radius"]) trial_radii = trial['radius'] trial_yawrate_offset = trial['sab'] trial_dir = trial['bend'] print(str([trial_radii, trial_yawrate_offset])) txtDir = "" #print ("Length of bend array:", len(self.rightbends)) self.driver.setAutomation(True) self.AUTOMATION = True self.txtMode.message('A') if self.AUTOWHEEL: self.Wheel.control_on() if self.DISTRACTOR_TYPE is not None: if i == 0: #the first trial. #annotate eyetracking if self.EYETRACKING: self.comms.annotate("DistractorScreen") #switch texts off for the first trial. self.ToggleTextVisibility(viz.OFF) Distractor.StartTrial(self.targetoccurence_prob, self.targetnumber, trialn=i, displayscreen=True) #starts trial yield viztask.waitTrue(Distractor.getPlaySoundFlag) self.ToggleTextVisibility(viz.ON) else: Distractor.StartTrial(self.targetoccurence_prob, self.targetnumber, trialn=i, displayscreen=False) #starts trial radius_index = self.FACTOR_radiiPool.index(trial_radii) #choose correct road object. if trial_dir > 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) #pick radius self.Trial_radius = trial_radii #pick file. Put this in dedicated function. TODO: Should open all of these at the start of the file to save on processing. self.Trial_autofile_i = int(trial['autofile_i']) self.Trial_YR_readout = self.YR_readouts_80[self.Trial_autofile_i] self.Trial_SWA_readout = self.SWA_readouts_80[ self.Trial_autofile_i] self.Trial_playbackfilename = self.PlaybackPool80[ self.Trial_autofile_i] """ if self.Trial_radius == 40: i = random.choice(range(len(self.YR_readouts_40))) self.Trial_YR_readout = self.YR_readouts_40[i] self.Trial_SWA_readout = self.SWA_readouts_40[i] self.Trial_playbackfilename = self.PlaybackPool40[i] elif self.Trial_radius == 80: i = random.choice(range(len(self.YR_readouts_80))) self.Trial_YR_readout = self.YR_readouts_80[i] self.Trial_SWA_readout = self.SWA_readouts_80[i] self.Trial_playbackfilename = self.PlaybackPool80[i] else: raise Exception("Something bad happened") """ #update class# self.Trial_simulatedttlc = trial['simulated_ttlc'] self.Trial_design = trial['design'] self.Trial_dir = trial_dir self.Trial_N = i self.Trial_YawRate_Offset = trial_yawrate_offset self.Trial_BendObject = trialbend self.Trial_trialtype_signed = trial_dir self.Trial_playbacklength = len(self.Trial_YR_readout) self.Trial_midline = np.vstack( (self.Straight.midline, self.Trial_BendObject.midline)) self.Trial_OnsetTime = trial['onsettime'] #self.Trial_OnsetTime = np.random.choice(self.OnsetTimePool, size=1)[0] self.Trial_SaveName = str(self.EXP_ID) + '_' + str( self.PP_id) + '_' + str(self.Trial_N) #renew data frame. #self.OutputWriter = pd.DataFrame(index = range(self.TrialLength*60), columns=self.datacolumns) #make new empty EndofTrial data #renew csv writer self.OutputFile = io.BytesIO() self.OutputWriter = csv.writer(self.OutputFile) self.OutputWriter.writerow(self.datacolumns) #write headers. #annotate eyetracking if self.EYETRACKING: self.comms.annotate('Start_' + self.Trial_SaveName) yield viztask.waitTime(.5) #pause at beginning of trial #annotate eyetracking if self.EYETRACKING: #remove calib_pt and wait a further .5 s #TODO: add 1 s calibration dot. self.calib_pt.visible(1) yield viztask.waitTime(1.5) #pause at beginning of trial self.calib_pt.visible(0) yield viztask.waitTime(.5) #pause at beginning of trial if self.DEBUG: conditionmessage = 'SAB: ' + str(self.Trial_YawRate_Offset) + \ '\nRadius: ' +str(self.Trial_radius) + \ '\nOnsetTime: ' + str(self.Trial_OnsetTime) + \ '\nAutoFile: ' + str(self.Trial_autofile_i) + \ '\nsim TTLC: ' + str(self.Trial_simulatedttlc) + \ '\nDesign: ' + str(self.Trial_design) + \ '\nTask: ' + str(self.DISTRACTOR_TYPE) self.txtTrial.message(conditionmessage) if self.DEBUG_PLOT: #realtime plot. self.line_midline.set_data(self.Trial_midline[:, 0], self.Trial_midline[:, 1]) self.dot_origin.set_data( self.Trial_BendObject.CurveOrigin[0], self.Trial_BendObject.CurveOrigin[1]) self.plot_ax.axis([ min(self.Trial_midline[:, 0]) - 10, max(self.Trial_midline[:, 0]) + 10, min(self.Trial_midline[:, 1]) - 10, max(self.Trial_midline[:, 1]) + 10 ]) #set axis limits self.plot_positionarray_x, self.plot_positionarray_z, self.plot_closestpt_x, self.plot_closestpt_z = [], [], [], [] #arrays to store plot data in self.UPDATELOOP = True # def PlaybackReached(): """checks for playback limit or whether automation has been disengaged""" end = False #check whether automation has been switched off. if self.Current_playbackindex >= self.Trial_playbacklength: end = True return (end) def CheckDisengage(): """checks automation status of driver class """ end = False auto = self.driver.getAutomation() if auto == False: self.AUTOMATION = auto self.txtMode.message('M') #switch wheel control off, because user has disengaged #begin = timer() if self.AUTOWHEEL: self.Wheel.control_off() if self.EYETRACKING: self.comms.annotate('Disengage_' + self.Trial_SaveName) #pass #print ("WheelControlOff", timer() - begin) end = True return (end) #create viztask functions. waitPlayback = viztask.waitTrue(PlaybackReached) waitDisengage = viztask.waitTrue(CheckDisengage) d = yield viztask.waitAny([waitPlayback, waitDisengage]) if d.condition is waitPlayback: print('Playback Limit Reached') elif d.condition is waitDisengage: print('Automation Disengaged') self.SingleBeep() def RoadRunout(): """temporary HACK function to check whether the participant has ran out of road""" end = False if self.Trial_Timer > self.TrialLength: end = True return (end) #waitRoad = viztask.waitTrue (RoadRunout) #waitManual = viztask.waitTime(5) #d = yield viztask.waitAny( [ waitRoad, waitManual ] ) yield viztask.waitTrue(RoadRunout) print("Run out of Road") #if d.condition is waitRoad: # print ('Run out of Road') #elif d.condition is waitManual: # print ('Manual Time Elapsed') ##### END STEERING TASK ###### self.UPDATELOOP = False self.Trial_BendObject.ToggleVisibility(viz.OFF) ##reset trial. Also need to annotate each eyetracking trial. viz.director(self.SaveData, self.OutputFile, self.Trial_SaveName) self.ResetTrialAndDriver( ) #reset parameters for beginning of trial ##### INITIALISE END OF TRIAL SCREEN FOR DISTRACTOR TASK ####### if self.DISTRACTOR_TYPE is not None: #annotate eyetracking if self.EYETRACKING: self.comms.annotate('Distractor_' + self.Trial_SaveName) if self.AUTOWHEEL: self.Wheel.control_off() #switch text off self.ToggleTextVisibility(viz.OFF) Distractor.EndofTrial() #throw up the screen to record counts. # Pause before the query screen to avoid # spurious presses carrying over from the # task. # Hack the screen to be blank Distractor.EoTScreen.visible(viz.ON) Distractor.Question.visible(viz.OFF) Distractor.lblscore.visible(viz.OFF) yield viztask.waitTime(1.0) Distractor.EoTScreen_Visibility(viz.ON) ###interface with End of Trial Screen pressed = 0 while pressed < self.targetnumber: #keep looking for gearpad presses until pressed reaches trial_targetnumber print("waiting for gear press") yield viztask.waitTrue(self.driver.getGearPressed) pressed += 1 print('pressed ' + str(pressed)) Distractor.gearpaddown() self.driver.setGearPressed(False) yield viztask.waitTime(.5) #Distractor.EoTScreen_Visibility(viz.OFF) Distractor.RecordCounts() self.ToggleTextVisibility(viz.ON) #annotate eyetracking if self.EYETRACKING: self.comms.annotate('End_' + self.Trial_SaveName) #Trial loop has finished. if self.EYETRACKING: self.markers.remove_markers() #remove markers self.Straight.ToggleVisibility(0) accuracy_filename = filename + '_end' yield run_accuracy(self.comms, accuracy_filename) self.CloseConnections()
def experiment(): text_line1 = create_text2d('Please Wait') # text_line2 = create_text2d('',[0,1.8,4]) text_line1.visible(viz.OFF) #GET PP INFO yield participantInfo() yield viz.waitTime(0.5) # recalibrate hand to physical start position yield calibrateHand() #INITIALIZE LOG FILES # file name incl pp nr and id + number based on time so to avoid accidental overwriting rd_vers = str(int(time.time())) # initialize and head data log file exp.data_log_file = '{0}/data_log_{1}{2}_{3}.csv'.format( exp.data_path, exp.pp_nr, exp.pp_id, rd_vers) pr.data_log_file = exp.data_log_file with open(exp.data_log_file, 'w') as f: f.write(exp.log_heading) # initialize data hand log file exp.data_hand_file = '{0}/data_hand_{1}{2}_{3}.csv'.format( exp.data_path, exp.pp_nr, exp.pp_id, rd_vers) pr.data_hand_file = exp.data_hand_file with open(exp.data_hand_file, 'w') as f: f.write('hand data file {0} {1} {2}\n'.format(exp.pp_nr, exp.pp_id, rd_vers)) # write exp settings. Seperator = ':' exp_settings_write = '' for attr, value in exp.__dict__.iteritems(): if not attr.startswith('__'): exp_settings_write += str(attr) + ':' + str(value) + '\n' with open( '{0}/exp_settings_{1}{2}_{3}.csv'.format(exp.data_path, exp.pp_nr, exp.pp_id, rd_vers), 'w') as f: f.write(exp_settings_write) del exp_settings_write # PRACTICE BLOCKs for bl in range(pr.nr_blocks): text_line1.message("To start training block " + str(bl + 1) + "\npress -0-") text_line1.visible(viz.ON) yield viztask.waitKeyDown(viz.KEY_KP_0) text_line1.message("3") yield viztask.waitTime(1) text_line1.message("2") yield viztask.waitTime(1) text_line1.message("1") yield viztask.waitTime(1) text_line1.visible(viz.OFF) for tr in range(pr.nr_trials / pr.nr_blocks): tr += bl * pr.nr_trials / pr.nr_blocks yield trial(bl, tr, pr, log_pr) text_line1.message("Training block " + str(bl + 1) + ' of ' + str(pr.nr_blocks) + ' finished\nCall the experimenter...') text_line1.visible(viz.ON) yield viztask.waitKeyDown('a') # EXPERIMENTAL BLOCKs exp.reach_end_cutoff_list = pr.reach_end_cutoff_list exp.reach_end_cutoff_t = pr.reach_end_cutoff_t for bl in range(exp.nr_blocks): text_line1.message("To start experiment block " + str(bl + 1) + "\npress -0-") text_line1.visible(viz.ON) yield viztask.waitTime(0.25) yield viztask.waitKeyDown(viz.KEY_KP_0) text_line1.message("3") yield viztask.waitTime(1) text_line1.message("2") yield viztask.waitTime(1) text_line1.message("1") yield viztask.waitTime(1) text_line1.visible(viz.OFF) for tr in range(exp.nr_trials / exp.nr_blocks): tr += bl * exp.nr_trials / exp.nr_blocks yield trial(bl, tr, exp, log) if bl == ((exp.nr_blocks / 2) - 1): text_line1.message("Experiment block " + str(bl + 1) + ' of ' + str(exp.nr_blocks) + ' finished\nPlease call the experimenter...') text_line1.visible(viz.ON) yield viztask.waitKeyDown('a') elif bl == (exp.nr_blocks - 1): text_line1.message( 'The end\nThank you!\nPlease call the experimenter...') text_line1.visible(viz.ON) yield viztask.waitKeyDown('a') else: text_line1.message( "Experiment block " + str(bl + 1) + ' of ' + str(exp.nr_blocks) + ' finished\nYou can take a break now\npress -0- to continue') text_line1.visible(viz.ON) yield viztask.waitKeyDown(viz.KEY_KP_0) viz.quit()
def run_accuracy(comms, fname): fname = fname + '_accuracy_test' print(fname) ##MAKE WHITE BACKGROUND COLOUR FOR BETTER CALIBRATION #viz.MainWindow.clearcolor(viz.WHITE) #draw roadedges #fName = 'textures\strong_edge.bmp' # fName = imagepath + '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 = 300 # planesize = tilesize/5 # groundplane.setScale(tilesize, tilesize, tilesize) # groundplane.setEuler((0, 90, 0),viz.REL_LOCAL) # matrix = vizmat.Transform() # matrix.setScale( planesize, planesize, planesize ) # groundplane.texmat( matrix ) # groundplane.texture(groundtexture) # groundplane.visible(1) #markers = Markers() #add markers. #run through calibration programme #throw two 9 point fleixble grid. Can simple keep going until satisfied. #Needs a separate save function than the original to be completely self-sufficient. #boxsize = [.9,.8] #xy box size #lowerleft = [.05,.1] #starting corner boxsize = [.6, .4] #xy box size lowerleft = [.2, .2] #starting corner #start from top right nrow = 4 ncol = 3 Grid = MakeGrid(nrow, ncol, boxsize, lowerleft) nmarkers = nrow * ncol imagepath = 'C:/VENLAB data/shared_modules/textures/' #fn = imagepath + 'calibmarker.png' #fn = imagepath + 'calibmarker_black.png' #pupil-labs has issues. Stops due to not collecting enough data. Might be to tell it to stop? fn = imagepath + 'calibmarker_white.png' #seems to work best with this one. #fn = imagepath + 'calibmarker_white_old.png' def loadimage(fn): """Loads a and scales a texture from a given image path""" defaultscale = 800.0 / 600.0 aspect = 1920.0 / 1080.0 scale = aspect / defaultscale ttsize = 1 pt = viz.add(viz.TEXQUAD, viz.SCREEN) pt.scale(ttsize, ttsize * scale, ttsize) pt.texture(viz.add(fn)) pt.translate( Grid[0][0], Grid[0][1] ) # Now you can specify screen coordinates, so the visual angle is OK (i.e. no depth) pt.visible(0) return (pt) pt = loadimage(fn) pt_buffer = loadimage(imagepath + 'calibmarker_buffer.png') pt_buffer.visible(0) #### CALIB GRID ##### #need to make sure they are the same visual angle (account for the depth of the virtual world). #test the calibration by plotting the calibration sequence taken from the eyetracker (onto the dots) #(0.37, 0.6) #Point1 # (0.485, 0.6) #Point 2 # (0.6, 0.6) #Point 3 # (0.37, 0.495) #Point 4 # (0.485, 0.495) #Point 5 # (0.6, 0.495) #Point 6 # (0.37, 0.39) #Point 7 # (0.485, 0.39) #Point 8 # (0.6, 0.39) #Point 9 viz.message( '\t\t\tACCURACY TEST \n\nPlease look at the white dot in the very centre of the accuracy target. Try and move your head as little as possible' ) calib_flag = 0 record_flag = 0 satisfied = False i = 0 #index for point. #normalise markers on surface print(Grid) #calibpositions_normed = normaliseToSurface(Grid, markers.boxsize, markers.lowerleft) #print (calibpositions_normed) #comms.send_marker_positions(calibpositions_normed) comms.send_msg('P') #start accuracy test #add buffer point pt_buffer.visible(1) pt.visible(0) yield viztask.waitTime(.75) #wait for half a second pt_buffer.visible(0) #remove buffer point pt.visible(1) while not satisfied: msg_rcv = comms.poll_msg() if 'calibration.marker_sample_completed' in msg_rcv: pt_buffer.visible(1) #add buffer point pt.visible(0) yield viztask.waitTime(.5) #wait for half a second i = i + 1 if i > nmarkers - 1: #clamp i comms.send_msg('p') while True: msg_rcv = comms.poll_msg() if True in ['calibration' in j for j in msg_rcv]: out = [j for j in msg_rcv if 'calibration' in j][0] calib_accuracy = out.split('//')[0] calib_precision = out.split('//')[1] # calib_accuracy = out.split('calibration.Accuracy')[1].split('.Precision')[0] # calib_precision = out.split('calibration.Accuracy')[1].split('.Precision')[0] satisfied = True save_calibration([ calib_accuracy, calib_precision, time.time(), True ], fname) pt.visible(0) pt_buffer.visible(0) break # happy = vizinput.ask("Calibration Accuracy: " + calib_accuracy + "\nAre you satisfied?") # if happy: # print ("happy") # satisfied = True # pt.visible(0) # break # else: # print ("not happy") # satisfied = False # i = 0 # pt.translate(Grid[i][0], Grid[i][1]) # comms.send_msg('P') # break #yield viztask.returnValue(happy) #Now check if the calibration accuracy is good enough. Else run through again else: pt.translate(Grid[i][0], Grid[i][1]) pt_buffer.translate(Grid[i][0], Grid[i][1]) #pt.translate(0,0) yield viztask.waitTime(.75) #wait for half a second pt_buffer.visible(0) #remove buffer point pt.visible(1) yield viztask.waitTime(.5)
def run_calibration(comms, fname): fname = fname + '_calibration_accuracy' print(fname) ##MAKE WHITE BACKGROUND COLOUR FOR BETTER CALIBRATION viz.MainWindow.clearcolor(viz.WHITE) #addGroundPlane() markers = Markers() #add markers. #run through calibration programme #throw two 9 point fleixble grid. Can simple keep going until satisfied. #Needs a separate save function than the original to be completely self-sufficient. boxsize = [.6, .3] #xy box size lowerleft = [.2, .2] #starting corner #start from top right Grid = MakeGrid(3, 4, boxsize, lowerleft) imagepath = 'C:/VENLAB data/shared_modules/textures/' #fn = imagepath + 'calibmarker.png' #fn = imagepath + 'calibmarker_black.png' #pupil-labs has issues. Stops due to not collecting enough data. Might be to tell it to stop? fn = imagepath + 'calibmarker_white.png' #seems to work best with this one. #fn = imagepath + 'calibmarker_white_old.png' def loadimage(fn): """Loads a and scales a texture from a given image path""" defaultscale = 800.0 / 600.0 aspect = 1920.0 / 1080.0 scale = aspect / defaultscale ttsize = 1 pt = viz.add(viz.TEXQUAD, viz.SCREEN) pt.scale(ttsize, ttsize * scale, ttsize) pt.texture(viz.add(fn)) pt.translate( Grid[0][0], Grid[0][1] ) # Now you can specify screen coordinates, so the visual angle is OK (i.e. no depth) pt.visible(0) return (pt) pt = loadimage(fn) pt_buffer = loadimage(imagepath + 'calibmarker_buffer.png') pt_buffer.visible(0) #### CALIB GRID ##### #need to make sure they are the same visual angle (account for the depth of the virtual world). #test the calibration by plotting the calibration sequence taken from the eyetracker (onto the dots) #(0.37, 0.6) #Point1 # (0.485, 0.6) #Point 2 # (0.6, 0.6) #Point 3 # (0.37, 0.495) #Point 4 # (0.485, 0.495) #Point 5 # (0.6, 0.495) #Point 6 # (0.37, 0.39) #Point 7 # (0.485, 0.39) #Point 8 # (0.6, 0.39) #Point 9 viz.message( '\t\t\t CALIBRATION \n\nPlease look at the centre of the calibration target. Try and move your head as little as possible' ) calib_flag = 0 record_flag = 0 satisfied = False i = 0 #index for point. comms.send_msg('C') #start calibration #Add buffer point pt_buffer.visible(1) pt.visible(0) yield viztask.waitTime(.75) #wait for half a second pt_buffer.visible(0) #remove buffer point pt.visible(1) while not satisfied: msg_rcv = comms.poll_msg() if 'calibration.marker_sample_completed' in msg_rcv: pt_buffer.visible(1) pt.visible(0) yield viztask.waitTime(.5) #wait for half a second i = i + 1 if i > 11: #clamp i comms.send_msg('c') while True: msg_rcv = comms.poll_msg() if True in ['calibration' in j for j in msg_rcv]: out = [j for j in msg_rcv if 'calibration' in j][0] out = out[12:] print(out) calib_accuracy = out.split('//')[0] calib_precision = out.split('//')[1] # calib_accuracy = out.split('calibration.Accuracy')[1].split('.Precision')[0] # calib_precision = out.split('calibration.Accuracy')[1].split('.Precision')[0] happy = vizinput.ask("Calibration Accuracy: " + calib_accuracy + "\nAre you satisfied?") if happy: print("happy") satisfied = True pt.visible(0) pt_buffer.visible(0) save_calibration([ calib_accuracy, calib_precision, time.time(), True ], fname) break else: print("not happy") satisfied = False save_calibration([ calib_accuracy, calib_precision, time.time(), False ], fname) i = 0 pt.translate(Grid[i][0], Grid[i][1]) pt_buffer.translate(Grid[i][0], Grid[i][1]) #do the first one. comms.send_msg('C') pt_buffer.visible(1) pt.visible(0) yield viztask.waitTime( .75) #wait for half a second pt_buffer.visible(0) #remove buffer point pt.visible(1) break #yield viztask.returnValue(happy) #Now check if the calibration accuracy is good enough. Else run through again else: pt.translate(Grid[i][0], Grid[i][1]) pt_buffer.translate(Grid[i][0], Grid[i][1]) #Add buffer point #pt_buffer.visible(1) #pt.visible(0) yield viztask.waitTime(.75) #wait for half a second pt_buffer.visible(0) #remove buffer point pt.visible(1) yield viztask.waitTime(.5)
def main(): # Set up the instruction info.setText('Let the experimenter know if you are ready.') info.visible(viz.ON) yield viztask.waitKeyDown(' ') info.visible(viz.OFF) yield viztask.waitTime(1) yield practice() info.setText(beforeExp) info.visible(viz.ON) yield viztask.waitKeyDown(' ') info.visible(viz.OFF) for i in range(len(Sequence)): if i > 0: info.setText('End of Block ' + str(i) + '. \nWould you like to continue?') info.visible(viz.ON) yield viztask.waitKeyDown(' ') info.setText('Block ' + str(i + 1)) info.visible(viz.ON) yield viztask.waitTime(2) info.visible(viz.OFF) yield viztask.waitTime(1) if Sequence[i] == 'C' or Sequence[i] == 'c': condName = 'DotCloud' clouds = flashingCloud(3, 12, 12, 1, cloudFreq, Target, freq) refresh = viztask.schedule(refreshing(clouds)) yield trial(condName, exp_conditions) for c in clouds: c.remove() refresh.kill() elif Sequence[i] == 'L' or Sequence[i] == 'l': condName = 'Line' yield trial(condName, exp_conditions) elif Sequence[i] == 'O' or Sequence[i] == 'o': condName = 'OutlinedRoom' Target.alpha(0) door = door_line(2.5, 0.5, 2) door.setParent(Target) door.zoffset(-1) door.color(viz.ORANGE) outlineRoom = room_line(3, 12, 12, 2) outlineRoom.setParent(Target) yield trial(condName, exp_conditions) door.remove() outlineRoom.remove() Target.alpha(1) elif Sequence[i] == 'F' or Sequence[i] == 'f': condName = 'EmptyRoom' Target.alpha(0) door = doorway(2.5, 0.5, 0.025) door.setParent(Target) door.zoffset(-1) door.color(viz.ORANGE) room_env = RoomCreator(12, 12, 3, 1) room_env.setParent(Target) room_env.setPosition([0, 0, -11], viz.REL_PARENT) yield trial(condName, exp_conditions) room_env.remove() door.remove() Target.alpha(1) info.setText('Thank you!') info.visible(viz.ON) yield viztask.waitTime(2) viz.quit()
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) self.SAVEDATA = True # switch saving data on. viz.MainScene.visible(viz.ON,viz.WORLD) #add text to denote conditons - COMMENT OUT FOR EXPERIMENT txtCondt = viz.addText("Condition",parent = viz.SCREEN) txtCondt.setPosition(.7,.2) txtCondt.fontSize(36) for i, trialtype_signed in enumerate(self.TRIALSEQ_signed): ### iterates each trial ### #import vizjoy print("Trial: ", str(i)) print("TrialType: ", str(trialtype_signed)) trialtype = abs(trialtype_signed) trial_heading = self.ConditionList_heading[trialtype] #set heading for that trial trial_width = self.ConditionList_width[trialtype] #set target number for the trial. print(str([trial_heading, trial_width])) self.Straight = StraightMaker(x = 0, start_z = 0, end_z = 200, width = trial_width) self.Straight.visible(0) # changes message on screen msg = msg = "Heading: " + str(trial_heading) + '_' + str(trial_width) # COMMENT OUT FOR EXPERIMENT #update class trial parameters# self.Trial_N = i self.Trial_heading = trial_heading self.Trial_width = trial_width self.Trial_trialtype_signed = trialtype_signed #translate bend to driver position. driverpos = viz.MainView.getPosition() print(driverpos) self.Straight.setPosition(driverpos[0],0, driverpos[2]) # self.Straight.setPosition([0,0, 5], viz.REL_LOCAL) #now need to set orientation driverEuler = viz.MainView.getEuler() # gets current driver euler (orientation) print ("driverEuler", driverEuler) # prints the euler self.Straight.setEuler(driverEuler, viz.ABS_GLOBAL) # then sets the straight euler as the driver euler in global coordinates. #Euler needs to be in yaw,pitch,roll #bendEuler = driverEuler #offsetEuler = [driverEuler[0]+trial_heading, driverEuler[1], driverEuler[2]] offsetEuler = [trial_heading, 0, 0] # this creates the straight offset # print ("offsetEuler", offsetEuler) self.Straight.setEuler(offsetEuler, viz.REL_LOCAL) # this sets the next straight at the yaw offset of the condition list yield viztask.waitTime(1) #wait for one second before change of camera heading #change OFFSET OF VIEW #FOR EQUAL AND OPPOSITE USE THE LINE BELOW: self.Trial_Camera_Offset = trial_heading #set the view offset. #put a mask on so that the jump isn't so visible self.blackscreen.visible(viz.ON) yield viztask.waitFrame(6) #wait for six frames (.1 s) offset = viz.Matrix.euler( self.Trial_Camera_Offset, 0, 0 ) viz.MainWindow.setViewOffset( offset ) # counter rotates camera self.blackscreen.visible(viz.OFF) #turn the mask yield viztask.waitTime(1) #wait for one second after change of camera heading msg = msg + '\n' + 'Offset: ' + str(self.Trial_Camera_Offset) #Save your variables - COMMENT OUT FOR EXPERIMENT txtCondt.message(msg) # COMMENT OUT FOR EXPERIMENT #translate bend to driver position. driverpos = viz.MainView.getPosition() print(driverpos) self.Straight.setPosition(driverpos[0],0, driverpos[2]) # self.Straight.setPosition([0,0, 5], viz.REL_LOCAL) #now need to set orientation driverEuler = viz.MainView.getEuler() # gets current driver euler (orientation) print ("driverEuler", driverEuler) # prints the euler self.Straight.setEuler(driverEuler, viz.ABS_GLOBAL) # then sets the straight euler as the driver euler in global coordinates. #Euler needs to be in yaw,pitch,roll #bendEuler = driverEuler #offsetEuler = [driverEuler[0]+trial_heading, driverEuler[1], driverEuler[2]] offsetEuler = [trial_heading, 0, 0] # this creates the straight offset # print ("offsetEuler", offsetEuler) self.Straight.setEuler(offsetEuler, viz.REL_LOCAL) #will need to save initial vertex for line origin, and Euler. Is there a nifty way to save the relative position to the road? self.driver.setSWA_invisible() # sets SWA invisible on screen occl = 0 yield viztask.waitTime(occl) # This command will create a Condition object that will wait for the specified number of seconds to elapse. Will viztask waitime work within a class? #reset steering wheel set point. self.Trial_setpoint = self.driver.reset_setpoint() self.Straight.visible(1) yield viztask.waitTime(self.VisibleRoadTime-occl) #after the occlusion add the road again. 2.5s to avoid ceiling effects. self.Straight.visible(0) # driver.setSWA_visible() def checkCentred(): centred = False x = self.driver.getPos() if abs(x) < .1: centred = True return (centred) ##wait a while #print "waiting" #TODO: Recentre the wheel on automation. #yield viztask.waitTrue(checkCentred) #print "waited" #loop has finished. CloseConnections(self.EYETRACKING)
def runtrials(): global trialtype, trialtype_signed, groundplane, fixation_counter, inside_edge, outside_edge setStage() # texture setting addfix() # fixation setting driver.reset() # initialization of driver def updatePositionLabel(): global driver, trialtype_signed, fixation, fixation_counter, rdsize, outside_edge, inside_edge, trialtype, groundplane # get head position(x, y, z) pos = viz.get(viz.HEAD_POS) pos[1] = 0.0 # (x, 0, z) # get body orientation ori = viz.get(viz.BODY_ORI) steeringWheel = driver.getPos() ######Fixation. This section makes sure the fixation is moved with the observer. fpheight = .12 fixation.setEuler((ori, 0.0, 0.0),viz.ABS_GLOBAL) ##fixation point always faces observer if trialtype_signed > 0: ##fixations for right bends while fixation_counter < 3142: fix_dist = mt.sqrt( ( ( pos[0] - x_right_mid[fixation_counter] )**2 ) + ( ( pos[2] - z_right_mid[fixation_counter] )**2 ) ) if ( (fix_dist < 16.0) | (fix_dist > 16.3) ): fixation_counter += 1 continue elif ( (fix_dist > 16.0) and (fix_dist < 16.3) ): fpx = x_right_mid[fixation_counter] fpz = z_right_mid[fixation_counter] centre_x = x_right_mid[fixation_counter] centre_z = z_right_mid[fixation_counter] break else: ##if you move more than 16m away from any possible fixation, fixation goes back to 0,0,0 fixation_counter = 0 ##if you end up finding your path again, there is a brand new fixation for you! fpx = 0 fpz = 0 centre_x = 0 centre_z = 0 else: ##fixations for left bends while fixation_counter < 3142: fix_dist = mt.sqrt( ( ( pos[0] - x_left_mid[fixation_counter] )**2 ) + ( ( pos[2] - z_left_mid[fixation_counter] )**2 ) ) if ( (fix_dist < 16.0) | (fix_dist > 16.3) ): fixation_counter += 1 #compCount += 1 continue elif ( (fix_dist > 16.0) and (fix_dist < 16.3) ): fpx = x_left_mid[fixation_counter] fpz = z_left_mid[fixation_counter] centre_x = x_left_mid[fixation_counter] centre_z = z_left_mid[fixation_counter] #print fix_dist break else: fixation_counter = 0 fpx = 0 fpz = 0 centre_x = 0 centre_z = 0 ############################ ## added by Yuki # insert variables in driver class driver.function_insert(centre_x, centre_z, pos[0], pos[2], fix_dist) ############################ # fixation coordinate(X, eye height, Z) fixation.translate(fpx, fpheight, fpz) eyedata = 9999 #SaveData(pos[0], pos[1], pos[2], ori, steeringWheel, eyedata) ##. # start action ontimer(rate, function) vizact.ontimer((1.0/60.0),updatePositionLabel) for j in range(0,TotalN): #import vizjoy global outside_edge, inside_edge, trialtype, trialtype_signed trialtype=abs(TRIALSEQ_signed[j]) trialtype_signed = TRIALSEQ_signed[j] viz.MainScene.visible(viz.OFF,viz.WORLD) ## # Define a function that saves data ## def SaveData(pos_x, pos_y, pos_z, ori, steer, eye): ## # Create the output string ## currTime = viz.tick() ## #out = str(float((currTime))) + '\t' + str(pos_x) + '\t' + str(pos_z)+ '\t' + str(ori)+ '\t' + str(trialtype_signed) + '\n' ## ## out = str(float((currTime))) + '\t' + str(pos_x) + '\t' + str(pos_z)+ '\t' + str(ori)+ '\t' + str(steer) + '\t' + str(trialtype_signed) + '\n' ## #out = str(float((currTime))) + '\t' + str(pos_x) + '\t' + str(pos_z)+ '\t' + str(ori)+ '\t' + str(steer) + '\t' + str(eye[0]) + '\t' + str(eye[1]) + '\t' + str(eye[2]) + '\t' + str(eye[3]) + '\t' + str(eye[4]) + '\t' + str(trialtype_signed) + '\n' ## # Write the string to the output file ## file.write(out) ## # Makes sure the file data is really written to the harddrive ## file.flush() ## #print out roadEdges() driver.reset() viz.MainScene.visible(viz.ON,viz.WORLD) yield viztask.waitTime(10) #Trial Time if edge == 1: inside_edge.remove() outside_edge.remove() else: viz.quit() ##otherwise keeps writting data onto last file untill ESC
def trials(block_no, isPoles='None', trialNo=10, trialtype='Offset', continued=False): info.setText("Hurrah!! Please wait for the experimenter.") if isPoles in ['flipped', 'staying']: poles, polelist = poleCreator(ground, pole_wd, pole_dep, pole_ht, pole_no) writePolePos(isPoles, polelist) for m in range(trialNo): # Set up the response recording file global sub_rt if continued: sub_rt = open( 'VRrt_' + str(id) + '_Block_' + str(block_no) + '_Trial_' + str(m + 9) + '_' + time.strftime("%d-%b-%y_%H-%M") + '.csv', 'a') else: sub_rt = open( 'VRrt_' + str(id) + '_Block_' + str(block_no) + '_Trial_' + str(m + 1) + '_' + time.strftime("%d-%b-%y_%H-%M") + '.csv', 'a') data = 'frameNo,Color,TimeStamp,Response' sub_rt.write('\n' + data) # Set up the real target sensor area sensor_Target = vizproximity.Sensor( vizproximity.RectangleArea([6, 0.1], center=[0, real_tg_dist[(-1)**(m + 1)]]), None) manager.addSensor(sensor_Target) # Set up poles if they change between trials if isPoles == 'changing': poles, polelist = poleCreator(ground, pole_wd, pole_dep, pole_ht, pole_no) writePolePos(isPoles, polelist) elif isPoles == 'flipped': poles.setEuler([(90 * (1 - (-1)**m)), 0, 0], mode=viz.ABS_PARENT) poles.setPosition([0, 0, polePos[(-1)**(m)]], mode=viz.ABS_PARENT) # Stand by yield viztask.waitNetwork(serverName) # choose target depending on walking direction if isPoles == 'flipped': if flippedTarget == 'BO': if m % 2 == 0: Target2.alpha(0) Target1.color(tg2Color) else: Target1.alpha(0) Target2.color(tg2Color) else: if m % 2 == 0: Target2.alpha(0) Target1.color(tg1Color) else: Target1.alpha(0) Target2.color(tg1Color) viz.window.screenCapture('flipped_Image_' + str(m) + '.jpg') else: if m % 2 == 0: Target2.alpha(0) Target1.color(tg1Color) else: Target1.alpha(0) Target2.color(tg2Color) viz.window.screenCapture(isPoles + '_Image_' + str(m) + '.jpg') ground.visible(viz.ON) labNetwork.send('Ready') # Start walking yield viztask.waitNetwork(serverName) metronome.play() if isPoles == 'flipped': if flippedTarget == 'BO': if m % 2 == 0: colorChange = viztask.schedule(changeColor2(Target1)) else: colorChange = viztask.schedule(changeColor2()) else: if m % 2 == 0: colorChange = viztask.schedule(changeColor1()) else: colorChange = viztask.schedule(changeColor1(Target2)) else: if m % 2 == 0: colorChange = viztask.schedule(changeColor1()) else: colorChange = viztask.schedule(changeColor2()) labNetwork.send('Block' + str(block_no) + ' Trial ' + str(m)) yield viztask.waitTime(0.25) # reach the target yield vizproximity.waitEnter(sensor_Target) alert.play() metronome.stop() viz.clearcolor(viz.BLACK) ground.visible(viz.OFF) colorChange.kill() labNetwork.send('Reach Target!') manager.clearSensors() print Target1.getPosition(viz.ABS_GLOBAL) print Target2.getPosition(viz.ABS_GLOBAL) # Set up the information for participants at the end of trial if m < trialNo - 1: info.visible(viz.ON) yield viztask.waitTime(3) info.visible(viz.OFF) if isPoles == 'changing': poles.remove() else: # finish writing the response info.setText('End of Block ' + str(block_no)) info.visible(viz.ON) yield viztask.waitTime(3) info.visible(viz.OFF) if isPoles != 'None': poles.remove() # reset the targets if m % 2 == 0: Target2.alpha(1) else: Target1.alpha(1)
def performKeyMovements(self, camcenter, camlink): """ the loop that is submitted to the scheduler to act and move the camera, or change the camera center camcenter object is a 3d node object that is supplied to the camera keyboard control object, that is the parent of the camera to be manipulated """ n = 0 def yIsNegative(mainView): """ mainview object -> Boolean this function tests if the z coordinate of the main view is negative and returns True if negative, false if positive """ import math coordinates = mainView.getPosition(viz.ABS_GLOBAL) z = coordinates[1] # z coordinate if math.fabs(z) == z: # z is positive return False elif math.fabs(z) != z: # z is negative return True while True: #refresh rate should be 120Hz due to the fact that the Oculus refreshs at 120Hz yield viztask.waitTime(.0066666666666667) #check direction arrows (numpad keys 123 and 5) if (self.right == True and self.left == True): #decrease viewing radius if self.up == True: camlink.preTrans([0, 0, .05]) #increase viewing radius elif self.down == True: camlink.preTrans([0, 0, -.05]) #move right (only right pressed) elif self.right == True: camcenter.setEuler([-1.5, 0, 0], viz.REL_GLOBAL) #move left (only left pressed) elif self.left == True: camcenter.setEuler([1.5, 0, 0], viz.REL_GLOBAL) #move up elif self.up == True: euler = camcenter.getEuler() if euler[1] > 48: #needed to subtract 30 deg pass else: camcenter.setEuler([0, 1.5, 0], viz.REL_LOCAL) #move down elif self.down == True: #check if this move made us go through the floor if yIsNegative(viz.MainView) == True: pass else: # mainview above floor camcenter.setEuler([0, -1.5, 0], viz.REL_LOCAL)
def jumpFlash(): # Display jump flash jump_flash.visible(True) jump_flash.runAction( vizact.fadeTo(viz.BLACK, begin=viz.WHITE, time=2.0, interpolate=vizact.easeOutStrong)) jump_flash.addAction(vizact.method.visible(False)) waitKey1 = viztask.waitKeyDown('1') waitKey2 = viztask.waitKeyDown('2') wait10 = viztask.waitTime(5) waitJumpTime = 5 def scenesTask(): while True: # Scene 1 events vp1[0].add(display) vizconnect.resetViewpoints() yield viztask.waitTime(waitJumpTime) jumpSignal() yield viztask.waitEvent(CHANGE_SCENES_EVENT) jump_signal.visible(0) jumpFlash()
def runSetOfTrials(): global data global collided global positionList global hitPosition collided = False viz.callback(viz.COLLIDE_BEGIN_EVENT, onCollide) positions = createPositions() move = vizact.ontimer(0, UpdateMovement) variances = [] accuracys = [] for i in positions: data = "" positionList = [] logger.newTrial() environment.point.setPosition(0, parameters.point_height, 0) if i == 0: [x, z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate1) elif i == 1: [x, z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate2) elif i == 2: [x, z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate3) elif i == 3: [x, z] = polar2cartesian(parameters.radialCoordinate, parameters.angularCoordinate4) print[x, z] environment.goal.setPosition(x, parameters.goal_height, z) data += ("\nGoal Position: " + str(environment.goal.getPosition())) #enable joystick movement environment.point.visible(viz.ON) environment.goal.visible(viz.ON) if parameters.dreiDEnvironment: environment.shadow.visible(viz.ON) if (parameters.training or parameters.intro): environment.arrow.visible(viz.ON) environment.thrust.disable() move.setEnabled(viz.ON) #wait till key is pressed let object fall down yield s.wait() if parameters.dreiDEnvironment: environment.shadow.visible(viz.OFF) dropPosition = environment.point.getPosition() data += ('\nDrop Position: ' + str(dropPosition)) move.setEnabled(viz.OFF) #set force on the point + no gravity [x, z] = windSpeed.computeWindForce(environment.point.getPosition()) if parameters.dreiDEnvironment: environment.thrust.setForce([x, parameters.gravity, z]) else: environment.thrust.setForce([x, 0, z]) environment.thrust.enable() #print(environment.point.getPosition()) yield viztask.waitTime(1) #show fallen object environment.thrust.disable() environment.point.setVelocity([0, 0, 0]) yield viztask.waitTime(1) #save hit position use global hit position if 3D based on collision or get last position of point in 2d if not parameters.dreiDEnvironment: hitPosition = environment.point.getPosition() data += '\nHit Position: ' + str(hitPosition) #compute statistics accuracy = statistics.computeAccuracy(hitPosition, environment.goal.getPosition()) variance = statistics.computeVariance(dropPosition, positionList) data += '\nAccuracy: ' + str(accuracy) data += '\nVariance: ' + str(variance) #make point invisible wait and start next trial environment.point.visible(viz.OFF) environment.goal.visible(viz.OFF) if (parameters.training or parameters.intro): environment.arrow.visible(viz.OFF) yield viztask.waitTime(1) parameters.trialNumber += 1 data += "\n" + str(positionList) logger.write_logger(data) accuracys.append(accuracy) variances.append(variance) viztask.returnValue([variances, accuracys, positions.__len__()])
def runtrials(self): """Loops through the trial sequence""" global gtexture self.driver = vizdriver.Driver(self.caveview) self.SAVEDATA = True # switch saving data on. viz.MainScene.visible(viz.ON, viz.WORLD) #add text to denote conditons - COMMENT OUT FOR EXPERIMENT # 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): ### iterates each trial ### #import vizjoy print("Trial: ", str(i)) print("TrialType: ", str(trialtype_signed)) trialtype = abs(trialtype_signed) trial_heading = self.ConditionList_heading[ trialtype] #set heading for that trial trial_flow = self.ConditionList_flow[ trialtype] #set flow for trial print(str([trial_heading, trial_flow])) txtDir = "" ######choose correct road object.###### # changes message on screen # msg = msg = "Heading: " + str(trial_heading) # COMMENT OUT FOR EXPERIMENT #update class trial parameters# self.Trial_N = i self.Trial_heading = trial_heading self.trial_flow = trial_flow self.Trial_trialtype_signed = trialtype_signed yield viztask.waitTime( 1) #wait for one second before change of camera heading #1) Offset camera #FOR EQUAL AND OPPOSITE USE THE LINE BELOW: self.Trial_Camera_Offset = trial_heading #put a mask on so that the jump/flow change isn't so visible self.blackscreen.visible(viz.ON) yield viztask.waitFrame(6) #wait for six frames (.1 s) offset = viz.Matrix.euler(self.Trial_Camera_Offset, 0, 0) viz.MainWindow.setViewOffset(offset) # counter rotates camera gtexture.anisotropy(trial_flow) # sets new flow condition self.blackscreen.visible(viz.OFF) #turn the mask #2) give participant time with new flow field yield viztask.waitTime( 1) #wait for one second after change of camera heading # msg = msg + '\n' + 'Offset: ' + str(self.Trial_Camera_Offset) #Save your variables - COMMENT OUT FOR EXPERIMENT # txtCondt.message(msg) # COMMENT OUT FOR EXPERIMENT #3) Move straight to desired position # Translate straight to driver position. driverpos = viz.MainView.getPosition() print(driverpos) self.Straight.setPosition(driverpos[0], 0, driverpos[2]) # Match straight orientation to the driver driverEuler = viz.MainView.getEuler( ) # gets current driver euler (orientation) print("driverEuler", driverEuler) # prints the euler self.Straight.setEuler( driverEuler, viz.ABS_GLOBAL ) # then sets the straight euler as the driver euler in global coordinates. # Offset the angle offsetEuler = [trial_heading, 0, 0] # this creates the straight offset self.Straight.setEuler(offsetEuler, viz.REL_LOCAL) #will need to save initial vertex for line origin, and Euler. Is there a nifty way to save the relative position to the road? #4) Reset set point and make the straight visible self.Trial_setpoint = self.driver.reset_setpoint() self.driver.setSWA_invisible() # sets SWA invisible on screen self.Straight.visible(1) #5) Wait for the trial time yield viztask.waitTime( self.VisibleRoadTime ) # add the road again. 2.5s to avoid ceiling effects. #6) Remove straight self.Straight.visible(0) def checkCentred(): centred = False x = self.driver.getPos() if abs(x) < .1: centred = True return (centred) ##wait a while #print "waiting" #TODO: Recentre the wheel on automation. #yield viztask.waitTrue(checkCentred) #print "waited" #loop has finished. CloseConnections(self.EYETRACKING)
def scheduleTimer(sensor): yield viztask.waitTime(3) #~ wait 3 seconds before it go's ##~ Taken from Tutorial: "Measuring reaction time" """~ Can't quite get it to work correctly but wanted to keep for referance.