def calibrateHand():
    if exp.optotrak:
        optoLink = viz.link(hand, m_hand)

    text_line1 = create_text2d(
        'Please put finger on physical start position\n press -space- to start calibration'
    )
    yield viztask.waitKeyDown(' ')
    text_line1.message("Calibration in progress")
    #collect samples
    samples = []
    old_sample = m_hand.getPosition()
    samples.append(old_sample)
    while len(samples) < 100:
        new_sample = m_hand.getPosition()
        if not (new_sample == old_sample):
            samples.append(new_sample)
            old_sample = new_sample
        yield viz.waitTime(0.001)
    check_position = np.mean(samples, axis=0)

    position_offset = np.array(exp.start_pos) - np.array(check_position)
    print position_offset
    hand0 = optofilter.position(hand,
                                offset=(position_offset[0],
                                        position_offset[1] + 0.006,
                                        position_offset[2]))
    if exp.optotrak:
        optoLink = viz.link(hand0, m_hand)
    text_line1.message("Calibration done")
    yield viz.waitTime(0.75)
    text_line1.visible(viz.OFF)
Esempio n. 2
0
 def run(self):
     while True:
         with self.lock:
             if self.shouldIRun:
                 #for d in self.data:
                    # print d
                 #viz.waitTime(1)
                 print "Hallo"
             else:
                 print "Stopped"
                 return
         viz.waitTime(1)
    def run(self):
        """Loops through the trial sequence"""
        viz.MainScene.visible(viz.ON, viz.WORLD)

        #start with all turned off
        for scene in self.scenes:
            scene.turn_off()
        ### why is the ground plane not changing????!!!! ###
        for lab, trial in self.CONDITIONLIST.iterrows():
            if trial['Day/Night'] > 0:
                trial_scene = self.scenes[0]
                #print(trial_scene)
                self.Straight.setAlpha(0.25)
            else:
                trial_scene = self.scenes[1]
                #print(trial_scene)
                self.Straight.setAlpha(0.025)

            #switch the particular scene on
            print(trial_scene.name)
            trial_scene.turn_on()
            yield viz.waitTime(1)

            #switch that particular scene off
            trial_scene.turn_off()
Esempio n. 4
0
def perturbation():
    global speed_S, speed_P, accel_max, belt, ptb, stp_counter, stp

    if (belt == 'L'):  # increase left speed
        #		labjack_impulse()
        out = serializepacket(speed_P[0], speed_S[1], accel_max, accel_max, 0)
        s.sendall(out)
        belt = '0'  # next call: decelerate
        stp_counter = 0
        stp = random.randint(step_range[0], step_range[1])
        print "PTB", ptb, "- LEFT"
        #send impulse
        labjack_impulse()
        viz.waitTime(
            0.6
        )  #use this waitime function with viz.director to create another thread
        out = serializepacket(speed_S[0], speed_S[1], accel_max, accel_max, 0)
        s.sendall(out)
        labjack_impulse()

    elif (belt == 'R'):  # increase right speed
        out = serializepacket(speed_S[0], speed_P[1], accel_max, accel_max, 0)
        s.sendall(out)
        belt = '0'  # next call: decelerate
        stp_counter = 0
        stp = random.randint(step_range[0], step_range[1])
        print "PTB", ptb, "- RIGHT"
        #send impulse
        labjack_impulse()
        viz.waitTime(
            0.6
        )  #use this waitime function with viz.director to create another thread
        out = serializepacket(speed_S[0], speed_S[1], accel_max, accel_max, 0)
        s.sendall(out)
        labjack_impulse()

    else:  # decrease speed
        out = serializepacket(speed_S[0], speed_S[1], accel_max, accel_max, 0)
        s.sendall(out)
        ptb += 1  # one more perturbation completed
        print ptb
Esempio n. 5
0
def saveUpdateLoop(avatar, file):
	global isRecording, waittask
	while True:		
		if isRecording:
			saveAvatar(avatar, file)
			waittask = viz.waitTime(RECORDING_FREQUENCY) #how often we should save data
Esempio n. 6
0
def cross_trial(start_time, wait_time, rt_deadline, remove, 
					message="",training=False):
	""" Implements a single trial
	Parameters
	==========
	start_time:float
	  IF start_time == 0, wait for the next trigger pulse. Else,
	  wait until start_time to begin the trial.
	wait_time:float
	  time to wait until the cross should remove one of its lines
	rt_deadline:float
	  if the subject did not respond more quickly than the deadline,
	  tell them they blew it
	remove:str
	  The portion of the cross to remove. Either "hbar" or "vbar".
	"""
	descr = {"onset":start_time,
			 "duration":wait_time,
			 "crossbar":remove}
	new_texture = hbar if remove == "vbar" else vbar
	if start_time == 0:
		yield vizact.waitsignal(TRIGGER_EVENT)
	else:
		while viz.tick() < start_time:
			yield viz.waitTime(0.01)
			
	# ---- If there's a message, display it for MESSAGE_TIME
	#block_text.message(message)
	#vizact.ontimer2(rate=MESSAGE_TIME, repeats=0,func=clear_text)
	
	# ---- Flash the cue
	quad.texture(cue)
	yield viztask.waitTime(0.5)
	quad.texture(cross)
	
	# ---- Wait the required time
	yield viztask.waitTime(wait_time)
	
	# ---- Set the new texture
	quad.texture(new_texture)
	#Wait for next frame to be drawn to screen
	d = yield viztask.waitDraw()

	#Save display time
	displayTime = d.time

	#Wait for a reaction
	reaction = yield viztask.waitAny( 
		[HBAR_RESPONSE,
		 VBAR_RESPONSE] )
	time_at_response, = reaction.data.data[0]

	# How did they do??
	# -> Hbar remains
	if reaction.condition is HBAR_RESPONSE:
		descr["acc_success"] = remove == "vbar"
		response = "hbar"
	# -> vbar remains
	if reaction.condition is VBAR_RESPONSE:
		descr["acc_success"] = remove == "hbar"
		response = "vbar"
		
	# print "removed:", remove,"responded:",response
	# Calculate reaction time
	reactionTime = time_at_response - displayTime
	descr["speed_success"] = reactionTime < rt_deadline
	success = descr["speed_success"] and descr["acc_success"]
	# What sort of feedback to give?
	#if training:
		# In training blocks, show the rt
		#yield training_display(reactionTime,descr["acc_success"])
	#else:
	if success:
		yield success_display(reactionTime)
	else:
		failtype = "WRONG" if descr["speed_success"] else "TIMEOUT"
		yield fail_display(failtype, reactionTime)
	
	quad.texture(cross)
	descr["response"]   = response
	descr["success"]    = success
	descr["rt"]         = reactionTime
	descr["rt_deadline"]= rt_deadline
	descr["changetime"] = d.time
	viztask.returnValue(descr)
	def die(self):
		if(True is self.flag):
			viz.waitTime(2)
			print "People of ZION: WE ARE DYIIIIIIIIIIING. :( "
			viz.waitTime(2)
			print "People of ZION: WE ALL FALL DOWN. :( :("
	def tester2(self,name):
		
		print "*****Looking around*****"
		viz.waitTime(3)
		if None is self.first:
			self.first = "smith"
		print "\nAgent SMITH: I WILL KILL YOU ALLLLLL!!!\n"
		viz.waitTime(2)
		if(False == self.yo):
			self.flag = True
			viz.waitTime(2)
			viz.quit()
		else:
			viz.waitTime(2)
			print "Agent SMITH: Wait waaa!!"
			viz.waitTime(2)
			print "*****NEO beats up Agent SMITH and destroys him*****"
			viz.waitTime(2)
			print "Agent SMITH: Damn you NEOOOOO!!\nAgent SMITH: NOW Fall Agent SMITH"
Esempio n. 9
0
def runanimation():
    global posx, posy, posz, tail, alpha, yaw, pitch, roll
    global GAIN, SPHERESIZE
    print len(accx)
    [lpx, lpy, lpz] = [[],[],[]]
    # Assume the first time is equal to 1/Fs
    dt = t
    dt2 = dt*dt
    starttime = time.time()
    for i in range(0,len(accx)):
        curtime = float(ts[i])
        timenow = time.time()
        if i > 0:
            dt = curtime-float(ts[i-1])
        [ax, ay, az] = [(accx[i]), (accy[i]), (accz[i])]
        
        # Check for gaps in data, do not move if the threshold is reached
        if dt < 0.5:
            # Calculate the new positions. y-axis is the elevation!
            posx += g*ax*dt*dt
            posz += g*ay*dt*dt
            posy += g*az*dt*dt
            lpx.append(posx)
            lpy.append(posy)
            lpz.append(posz)
            while len(lpx)>Z_LOWPASS:
                lpx.pop(0); lpy.pop(0); lpz.pop(0)
            
            partic = sphere.copy()
            partic.setScale(SPHERESIZE,SPHERESIZE,SPHERESIZE)
            partic.setPosition(avg(lpx),avg(lpy)+1,avg(lpz))
            # Direction cone
            '''
            X = viz.Transform()
            X.makeIdent()
            X.preTrans(posx,posy+1,posz)
            X.setEuler([yaw[i], pitch[i], roll[i]])
            X.preTrans(0,0.4,0)
            cone.setMatrix(X)
            '''
            # Moving average for camera position
            cpx.append(posx); cpy.append(posy); cpz.append(posz)
            while len(cpx) > 15:
                cpx.pop(0); cpy.pop(0); cpz.pop(0)
            cx = 0; cy = 0; cz = 0
            for j in range(0,len(cpx)):
                cx += cpx[j]; cy += cpy[j]; cz += cpz[j]
            cx/=len(cpx); cy/=len(cpy); cz/=len(cpz)
            
            # Calculate resulting camera position and theatrical movement
            camx = cx + dist * math.sin(curtime*animspeed)
            camz = cz + dist * math.cos(curtime*animspeed)
            camy = cy + 2 + 0.5* math.sin(curtime*animspeed*2)
            
            # Fixate view at the moving average
            viz.MainView.lookAt([cx,cy+1,cz])
            vizcam.PivotNavigate([camx,camy,camz],dist,[1.0,1.0],viz.MainView)
            
            # Change color according to the magnitude
            #amplitude = math.sqrt(ax*ax+ay*ay+az*az)
            red = acc_M[i]/MAX_AMP
            green = 1-acc_M[i]/MAX_AMP
            partic.color(red,green,0)
            tail.append(partic.id)
            alpha.append(1)
            
        decaytail(dt)
        yield viz.waitTime(dt)
    while len(tail) >5:
        decaytail(dt)
        yield viz.waitTime(dt)
    print 'All done in: %f seconds.'%(time.time()-starttime)
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 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()
Esempio n. 12
0
def runanimation():
    global posx, posy, posz, tail, alpha, yaw, pitch, roll
    global GAIN, SPHERESIZE
    print len(accx)
    [lpx, lpy, lpz] = [[], [], []]
    # Assume the first time is equal to 1/Fs
    dt = t
    dt2 = dt * dt
    starttime = time.time()
    for i in range(0, len(accx)):
        curtime = float(ts[i])
        timenow = time.time()
        if i > 0:
            dt = curtime - float(ts[i - 1])
        [ax, ay, az] = [(accx[i]), (accy[i]), (accz[i])]

        # Check for gaps in data, do not move if the threshold is reached
        if dt < 0.5:
            # Calculate the new positions. y-axis is the elevation!
            posx += g * ax * dt * dt
            posz += g * ay * dt * dt
            posy += g * az * dt * dt
            lpx.append(posx)
            lpy.append(posy)
            lpz.append(posz)
            while len(lpx) > Z_LOWPASS:
                lpx.pop(0)
                lpy.pop(0)
                lpz.pop(0)

            partic = sphere.copy()
            partic.setScale(SPHERESIZE, SPHERESIZE, SPHERESIZE)
            partic.setPosition(avg(lpx), avg(lpy) + 1, avg(lpz))
            # Direction cone
            '''
            X = viz.Transform()
            X.makeIdent()
            X.preTrans(posx,posy+1,posz)
            X.setEuler([yaw[i], pitch[i], roll[i]])
            X.preTrans(0,0.4,0)
            cone.setMatrix(X)
            '''
            # Moving average for camera position
            cpx.append(posx)
            cpy.append(posy)
            cpz.append(posz)
            while len(cpx) > 15:
                cpx.pop(0)
                cpy.pop(0)
                cpz.pop(0)
            cx = 0
            cy = 0
            cz = 0
            for j in range(0, len(cpx)):
                cx += cpx[j]
                cy += cpy[j]
                cz += cpz[j]
            cx /= len(cpx)
            cy /= len(cpy)
            cz /= len(cpz)

            # Calculate resulting camera position and theatrical movement
            camx = cx + dist * math.sin(curtime * animspeed)
            camz = cz + dist * math.cos(curtime * animspeed)
            camy = cy + 2 + 0.5 * math.sin(curtime * animspeed * 2)

            # Fixate view at the moving average
            viz.MainView.lookAt([cx, cy + 1, cz])
            vizcam.PivotNavigate([camx, camy, camz], dist, [1.0, 1.0],
                                 viz.MainView)

            # Change color according to the magnitude
            #amplitude = math.sqrt(ax*ax+ay*ay+az*az)
            red = acc_M[i] / MAX_AMP
            green = 1 - acc_M[i] / MAX_AMP
            partic.color(red, green, 0)
            tail.append(partic.id)
            alpha.append(1)

        decaytail(dt)
        yield viz.waitTime(dt)
    while len(tail) > 5:
        decaytail(dt)
        yield viz.waitTime(dt)
    print 'All done in: %f seconds.' % (time.time() - starttime)
Esempio n. 13
0
 def manageThread(self,thread):
     lsAll =[["a","b","c"],[1,2,3],[4,5,6],[]]
     for ls in lsAll:
         thread.changeData(ls)
         viz.waitTime(5)
     thread.stop()
Esempio n. 14
0
 def stopThread(self,thread):
     viz.waitTime(10)
     thread.stop()
     return