if ok1.keys in ['', [], None]:  # No response was made
    ok1.keys = None
# store data for thisExp (ExperimentHandler)
thisExp.addData('ok1.keys', ok1.keys)
if ok1.keys != None:  # we had a response
    thisExp.addData('ok1.rt', ok1.rt)
thisExp.nextEntry()
# the Routine "instrPractice" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
practiceTrials = data.TrialHandler(
    nReps=2.0,
    method='random',
    extraInfo=expInfo,
    originPath=
    u'/Users/patrickbissett/OneDrive/Poldrack/TrainedInhibition/PsychoPy/IntegratingDifferentCodeFlexibleStim12.psyexp',
    trialList=data.importConditions('Trialtypes5.xlsx'),
    seed=None,
    name='practiceTrials')
thisExp.addLoop(practiceTrials)  # add the loop to the experiment
thisPracticeTrial = practiceTrials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisPracticeTrial.rgb)
if thisPracticeTrial != None:
    for paramName in thisPracticeTrial.keys():
        exec(paramName + '= thisPracticeTrial.' + paramName)

for thisPracticeTrial in practiceTrials:
    currentLoop = practiceTrials
    # abbreviate parameter names if possible (e.g. rgb = thisPracticeTrial.rgb)
Exemplo n.º 2
0
                           ori=0,
                           color='white',
                           colorSpace='rgb',
                           opacity=1,
                           depth=0.0)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer(
)  # to track time remaining of each (non-slip) routine

# set up handler to look after randomisation of conditions etc
instructions = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('other/instructions.csv'),
    seed=None,
    name='instructions')
thisExp.addLoop(instructions)  # add the loop to the experiment
thisInstruction = instructions.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisInstruction.rgb)
if thisInstruction != None:
    for paramName in thisInstruction.keys():
        exec(paramName + '= thisInstruction.' + paramName)

for thisInstruction in instructions:
    currentLoop = instructions
    # abbreviate parameter names if possible (e.g. rgb = thisInstruction.rgb)
    if thisInstruction != None:
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "Instruction"-------
for thisComponent in InstructionComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "Instruction" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
practice_trials = data.TrialHandler(
    nReps=1,
    method='random',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('conditions_practice.csv'),
    seed=None,
    name='practice_trials')
thisExp.addLoop(practice_trials)  # add the loop to the experiment
thisPractice_trial = practice_trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisPractice_trial.rgb)
if thisPractice_trial != None:
    for paramName in thisPractice_trial.keys():
        exec(paramName + '= thisPractice_trial.' + paramName)

for thisPractice_trial in practice_trials:
    currentLoop = practice_trials
    # abbreviate parameter names if possible (e.g. rgb = thisPractice_trial.rgb)
    if thisPractice_trial != None:
Exemplo n.º 4
0
            win.flip()

        ready_screen.draw()
        win.flip()
        event.waitKeys(keyList=['space'])

    # write logs

    # send END log event
    logging.log(level=logging.DATA,
                msg='******* END run %i *******' % run_number)

    # save the trial infomation from trial handler
    log_filename2 = "%s_%i.csv" % (log_filename[:-4], run_number)
    trials.saveAsText(log_filename2, delim=',', dataOut=('n', 'all_raw'))


# =====================
# MAIN
#
# - set up stimuli and runs

for ridx, run in enumerate(runs):
    #print run
    trials = data.TrialHandler(run,
                               nReps=1,
                               extraInfo=run_data,
                               dataTypes=['stim_onset', 'rt', 'rating'],
                               method='sequential')
    do_run(ridx + 1, trials)
Exemplo n.º 5
0
    depth=0.0)
key_resp = keyboard.Keyboard()

# Initialize components for Routine "Last_Q"
Last_QClock = core.Clock()

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer(
)  # to track time remaining of each (non-slip) routine

# set up handler to look after randomisation of conditions etc
trials_3 = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('cond_batch_def.csv'),
    seed=None,
    name='trials_3')
thisExp.addLoop(trials_3)  # add the loop to the experiment
thisTrial_3 = trials_3.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
if thisTrial_3 != None:
    for paramName in thisTrial_3:
        exec('{} = thisTrial_3[paramName]'.format(paramName))

for thisTrial_3 in trials_3:
    currentLoop = trials_3
    # abbreviate parameter names if possible (e.g. rgb = thisTrial_3.rgb)
    if thisTrial_3 != None:
Exemplo n.º 6
0
 def test_comparison_equals(self):
     t1 = data.TrialHandler([dict(foo=1)], 2)
     t2 = data.TrialHandler([dict(foo=1)], 2)
     assert t1 == t2
Exemplo n.º 7
0
 def test_comparison_not_equal_after_iteration(self):
     t1 = data.TrialHandler([dict(foo=1)], 2)
     t2 = data.TrialHandler([dict(foo=1)], 3)
     t1.__next__()
     t2.__next__()
     assert t1 != t2
Exemplo n.º 8
0
for thisComponent in Instruct2Components:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# check responses
if key_resp_4.keys in ['', [], None]:  # No response was made
    key_resp_4.keys=None
thisExp.addData('key_resp_4.keys',key_resp_4.keys)
if key_resp_4.keys != None:  # we had a response
    thisExp.addData('key_resp_4.rt', key_resp_4.rt)
thisExp.nextEntry()
# the Routine "Instruct2" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
practice = data.TrialHandler(nReps=1, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('trialListPrac.xlsx'),
    seed=None, name='practice')
thisExp.addLoop(practice)  # add the loop to the experiment
thisPractice = practice.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisPractice.rgb)
if thisPractice != None:
    for paramName in thisPractice:
        exec('{} = thisPractice[paramName]'.format(paramName))

for thisPractice in practice:
    currentLoop = practice
    # abbreviate parameter names if possible (e.g. rgb = thisPractice.rgb)
    if thisPractice != None:
        for paramName in thisPractice:
            exec('{} = thisPractice[paramName]'.format(paramName))
    
Exemplo n.º 9
0
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "instructions"-------
for thisComponent in instructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "instructions" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
block = data.TrialHandler(nReps=2,
                          method='random',
                          extraInfo=expInfo,
                          originPath=-1,
                          trialList=[None],
                          seed=None,
                          name='block')
thisExp.addLoop(block)  # add the loop to the experiment
thisBlock = block.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisBlock.rgb)
if thisBlock != None:
    for paramName in thisBlock:
        exec('{} = thisBlock[paramName]'.format(paramName))

for thisBlock in block:
    currentLoop = block
    # abbreviate parameter names if possible (e.g. rgb = thisBlock.rgb)
    if thisBlock != None:
        for paramName in thisBlock:
Exemplo n.º 10
0
trialLists = [
    genTrials(ii,
              shape_trials,
              shape_lures,
              col_trials,
              col_lures,
              num_stims,
              min_dist,
              grid_size,
              participantNum=participantNum) for ii in range(Blocks)
]
#practice trials
pracList = genTrials('Practice',
                     4,
                     2,
                     0,
                     0, [4, 8],
                     min_dist,
                     grid_size,
                     participantNum=participantNum)

taskTrials = [
    data.TrialHandler(trialLists[ii], 1) for ii in range(len(trialLists))
]
for handlerNum in range(len(trialLists)):
    taskTrials[handlerNum].data.addDataType('resp')
    taskTrials[handlerNum].data.addDataType('RT')
pracTrials = data.TrialHandler(pracList, 1)
pracTrials.data.addDataType('resp')
pracTrials.data.addDataType('RT')
print('cueMS from frames =', cueFrames*(1000./refreshRate))
print('num of SOAs in the trial:', trialFrames/SOAFrames)

##Factorial design
numResponsesPerTrial = 1 #default. Used to create headers for dataFile
stimList = []
#cuePositions = [dot for dot in range(nDots) if dot not in [0,nDots-1]]
cuePositions = [10]
print('cuePositions: ',cuePositions)
#cuePositions = cuePositions[2:(nDots-3)] #drop the first and final two dots
#Set up the factorial design (list of all conditions)

for cuePos in cuePositions:
    stimList.append({'cuePos':cuePos})

trials = data.TrialHandler(stimList, nReps = trialsPerCondition)
#print(trials)


####Create output file###
#########################################################################
dataFile = open(fileNameWithPath + '.txt', 'w')
numResponsesPerTrial = 1

#headers for initial datafile rows, they don't get repeated. These appear in the file in the order they appear here.
oneOffHeaders = [
    'subject',
    'task',
    'staircase',
    'trialNum'
]
        core.quit()

    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "scannerwarmup"-------
for thisComponent in scannerwarmupComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions(u'event_rt.csv'),
                           seed=1,
                           name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
Exemplo n.º 13
0
                         font='Arial',
                         units='deg')
fixation = visual.PatchStim(win,
                            color=-1,
                            tex=None,
                            mask='circle',
                            size=0.2,
                            units='deg')

# create the list of stimulus conditions: 3 T1 positions, and 8 T2 positions (or 8 lags), i.e., 24 stimulus conditions
stimList = []
for T1pos in [5, 6, 7]:
    for T2pres in [1]:
        for T2pos in [1, 3, 5, 7, 9]:
            stimList.append({'T1pos': T1pos, 'T2pres': T2pres, 'T2pos': T2pos})
trials = data.TrialHandler(stimList, 15)

for thisTrial in trials:

    T1position = trials.thisTrial['T1pos']
    T1 = numbers[numpy.random.random_integers(0, 7)]

    T2position = trials.thisTrial['T1pos'] + trials.thisTrial['T2pos']
    if trials.thisTrial['T2pres'] == 1:
        T2 = numbers[numpy.random.random_integers(0, 7)]
    else:
        T2 = letters[numpy.random.random_integers(0, 25)]

    #fixation screen
    for frameN in range(int(round(params['fp'] * params['frameRate']))):
        fixation.draw()
Exemplo n.º 14
0
print('graphical_elements_ok')

#randomize stimulus presentations (equal amounts per part)
stim = np.zeros(Ntrials)

s = np.repeat(np.arange(Ngratings), (Ntrials / Ngratings))
s = np.random.permutation(s)
stim = s

print('stim_ok')

# Within-subjects design
TrialList = []
TrialList.append({"gratings": stim.astype(int)})
print(TrialList)
trials = data.TrialHandler(trialList=TrialList, nReps=1, method="sequential")
thisExp.addLoop(trials)

# welcome screen
welcome.draw()
window.flip()
event.waitKeys(keyList="space")

instruct.draw()
example_1.draw()
example_2.draw()
window.flip()
event.waitKeys(keyList="space")

start.draw()
window.flip()
Exemplo n.º 15
0
if instr1Resp.keys in ['', [], None]:  # No response was made
    instr1Resp.keys = None
thisExp.addData('instr1Resp.keys', instr1Resp.keys)
if instr1Resp.keys != None:  # we had a response
    thisExp.addData('instr1Resp.rt', instr1Resp.rt)
thisExp.addData('instr1Resp.started', instr1Resp.tStartRefresh)
thisExp.addData('instr1Resp.stopped', instr1Resp.tStopRefresh)
thisExp.nextEntry()
# the Routine "instructions" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('goNogoCond1.xlsx'),
                           seed=None,
                           name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial:
        exec('{} = thisTrial[paramName]'.format(paramName))

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
Exemplo n.º 16
0
#last screen
exit_screen = visual.TextStim(win,
                              text='Thank you for participating!',
                              pos=(0, 0),
                              units='norm',
                              height=0.1)

#logging
expdir = os.getcwd()
subjdir = '%s/logs/%s' % (expdir, subj_id)
if not os.path.exists(subjdir):
    os.makedirs(subjdir)
log_file = os.path.join(subjdir, 'sub{}_Investment-Ratings-{}.csv')
trial_data = [r for r in csv.DictReader(open('TrustRatings.csv', 'rU'))]
trials = data.TrialHandler(trial_data[:], 1, method="sequential")

question_map = {'2': 'trustworthy', '1': 'likeable', '0': 'approachable'}

stim_map = {
    '3': 'pos',
    '2': 'neg',
    '1': 'neu',
}

#clock
globalClock = core.Clock()
logging.setDefaultClock(globalClock)
timer = core.Clock()

#main task
Exemplo n.º 17
0
if __continue.keys in ['', [], None]:  # No response was made
    __continue.keys = None
thisExp.addData('__continue.keys', __continue.keys)
if __continue.keys != None:  # we had a response
    thisExp.addData('__continue.rt', __continue.rt)
thisExp.addData('__continue.started', __continue.tStartRefresh)
thisExp.addData('__continue.stopped', __continue.tStopRefresh)
thisExp.nextEntry()
# the Routine "_instructions" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
_loop_noises = data.TrialHandler(
    nReps=1,
    method='random',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('csvs/noise_conditions.csv'),
    seed=None,
    name='_loop_noises')
thisExp.addLoop(_loop_noises)  # add the loop to the experiment
this_loop_noise = _loop_noises.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = this_loop_noise.rgb)
if this_loop_noise != None:
    for paramName in this_loop_noise:  # assign each variable to their corresponding value
        exec('{} = this_loop_noise[paramName]'.format(paramName))

for this_loop_noise in _loop_noises:
    currentLoop = _loop_noises
    # abbreviate parameter names if possible (e.g. rgb = this_loop_noise.rgb)
    if this_loop_noise != None:
Exemplo n.º 18
0
        thisComponent.setAutoDraw(False)
# check responses
if key_resp_3.keys in ['', [], None]:  # No response was made
    key_resp_3.keys = None
# store data for thisExp (ExperimentHandler)
thisExp.addData('key_resp_3.keys', key_resp_3.keys)
if key_resp_3.keys != None:  # we had a response
    thisExp.addData('key_resp_3.rt', key_resp_3.rt)
thisExp.nextEntry()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(
    nReps=1,
    method='random',
    extraInfo=expInfo,
    originPath=
    u'/Users/aaron/Documents/GitHub/NCIL-SOC-2015/PsychoPy/stroop.psyexp',
    trialList=data.importConditions(u'psychopy_playing_conditions.xlsx'),
    seed=666,
    name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
Exemplo n.º 19
0
 def test_comparison_not_equal(self):
     t1 = data.TrialHandler([dict(foo=1)], 2)
     t2 = data.TrialHandler([dict(foo=1)], 3)
     assert t1 != t2
Exemplo n.º 20
0
if expInfo['session'] == '1':
    run = [1, 2, 1, 2, 2, 1, 2, 1, 1]
elif expInfo['session'] == '2':
    run = [2, 2, 1, 1, 1, 2, 2, 1, 2]
myarray = []
for i in range(len(run)):
    myarray.append(
        {
            'run': run[i],
            'runNum': (i)
        }
    )  #puts data into an array of dictionaries that the TrialHandler function will accept
block = data.TrialHandler(nReps=1,
                          method=u'sequential',
                          extraInfo=expInfo,
                          originPath=None,
                          trialList=myarray,
                          seed=None,
                          name='block')
thisExp.addLoop(block)  #add the loop to the experiment
thisBlock = block.trialList[0]  #so we can initialise stimuli with some values
#abbreviate parameter names if possible (e.g. rgb=thisBlock.rgb)
if thisBlock != None:
    for paramName in thisBlock.keys():
        exec(paramName + '=thisBlock.' + paramName)
begExpClock.reset()
for thisBlock in block:
    currentLoop = block
    #abbrieviate parameter names if possible (e.g. rgb=thisBlock.rgb)
    if thisBlock != None:
        for paramName in thisBlock.keys():
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "setup"-------
for thisComponent in setupComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "setup" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
tasks = data.TrialHandler(nReps=3,
                          method='sequential',
                          extraInfo=expInfo,
                          originPath=-1,
                          trialList=[None],
                          seed=None,
                          name='tasks')
thisExp.addLoop(tasks)  # add the loop to the experiment
thisTask = tasks.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTask.rgb)
if thisTask != None:
    for paramName in thisTask:
        exec('{} = thisTask[paramName]'.format(paramName))

for thisTask in tasks:
    currentLoop = tasks
    # abbreviate parameter names if possible (e.g. rgb = thisTask.rgb)
    if thisTask != None:
        for paramName in thisTask:
Exemplo n.º 22
0
    # refresh the screen
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()
    else:  # this Routine was not non-slip safe so reset non-slip timer
        routineTimer.reset()

#-------Ending Routine "instructions"-------
for thisComponent in instructionsComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method=u'sequential',
                           extraInfo=expInfo,
                           originPath=None,
                           trialList=data.importConditions(csv_file),
                           seed=None,
                           name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
Exemplo n.º 23
0
    def run_experiment(self,
                       window_dim=[800, 600],
                       screen_index=0,
                       monitor_name="testMonitor"):
        """ The main function that performs the stimulus presentation with synchronized timing

		Args:
		----
		window_dim, screen_index, monitor_name: size, index, and name of stim presentation monitor. (see PsychoPy Window documentation for specifics)


		Note:
		----
		- make sure to set SYN_CONNECTED = True when actually connected to Synapse

		- to make sure the code runs smoothly, best to comment out all print statements before running an experiment 

		"""

        if (self.SYN_CONNECTED):
            # Connect to Synapse & switch to preview mode
            syn = synex.syn_connect('192.168.1.37')

        #defining the window
        window = visual.Window(size=window_dim,
                               screen=screen_index,
                               monitor=monitor_name,
                               color=[-1, -1, -1],
                               units='pix')

        #instantiate a generic flash stimulus; will set the specifics of the parameters (pres_dur, luminance) later in the loop.
        flash = fs2.Flash_Stim(cur_screen=screen_index,
                               cur_monitor=monitor_name,
                               win_dim=window_dim,
                               pres_dur=0,
                               luminance=0)
        marker = pdm.PhotodiodeMarker()

        #making experimentHandler, and trials from rand_trials_sample
        trials_subset = self.rand_trials_sample()
        """
		data_info={"ISI": 's',
				"flash_dur": 'ms',
				"luminance": 'RGB ranging from -1 (black) to 1 (white)',
				"wave_freq": 'hz', #waveFreq = freq of the tone
				"pulse_dur": 'ms', #pulseDur = length of time the tone is played
				"wave_amp": 'dB', #waveAmp = sound levels
				"stimulus": '0 (A only), 1 (V only) , or 2 (A+V)',
				"delay": 'ms' # delay between presenting A and V
				}
		"""

        exp = data.ExperimentHandler(name='testExp',
                                     savePickle=True,
                                     saveWideText=True,
                                     dataFileName='experiment')

        trials = data.TrialHandler(
            trialList=trials_subset, nReps=1, method='sequential'
        )  # since already randomized we can go ahead and use "sequential" here...

        exp.addLoop(trials)

        #load values into the buffer before the trial starts...
        params_list = synex.get_params(trials)

        if (self.SYN_CONNECTED):
            syn.setMode(3)  # switch to record mode

    #	event.waitKeys(keyList='space') #could put this in to have the actual experiment (1st pdm flash, etc.) start on keypress

        expClock = core.Clock()
        expClock.reset()

        #the experiment loop! 0: Auditory only; 1: Visual only; 2: A+V
        for trial in trials:

            inter = trial['ISI_s']

            #initial marker flash for each trial
            for n in range(0, 10):  #draw for 10 frames
                marker.draw_marker(window)

            window.flip()
            """
			#print("Waiting system delay time...", self.SYSTEM_DELAY, " ms \n")
			time.sleep(self.SYSTEM_DELAY/1000.0)
			 
			#maximum delay if presenting auditory before visual plus maybe 30-50% ~250ms + 125 = 375ms
			sleep_time = (self.JITTER*1.5)/1000.0
			time.sleep(sleep_time) 

			"""

            stim_code = trial['stimulus']

            if (self.SYN_CONNECTED):
                #set the auditory value decided by Psychopy in Synapse: WaveAmp, WaveFreq, Delay (?)
                synex.set_stim_params(params_list, syn, trials.thisTrialN)
                synex.set_schmitt(syn, lockout_time=self.SYSTEM_DELAY
                                  )  # set the system delay lockout time
                synex.set_stimcode(syn, stim_code)

            if (stim_code == 0 or stim_code == 2):  #auditory stim only || A+V
                core.wait((self.JITTER + self.SYSTEM_DELAY) / 1000.0)

            elif (stim_code == 1):  #visual stim only
                core.wait(self.JITTER / 1000.0)

            if (stim_code == 0):  #auditory stim only
                #print("=============================\n")
                #print("===Auditory component only===\n *Play tone at %d dB*\n" %trial['wave_amp_dB'])
                trial['delay_ms'] = None  #set all visual parameters to None
                trial["flash_dur_ms"] = None
                trial["luminance"] = None
                trial['delay_ms'] = None
                #wait while the audio is playing
                exp.addData('Aud_onset', expClock.getTime())
                core.wait(trial['pulse_dur_ms'] / 1000.0)

            elif (stim_code == 1):  #visual stim only

                trial['wave_freq_Hz'] = None
                trial['pulse_dur_ms'] = None
                trial['wave_amp_dB'] = None
                trial[
                    'delay_ms'] = None  # set all audio-related parameters to none

                if (self.SYN_CONNECTED):
                    #set the auditory value decided by Psychopy in Synapse: WaveAmp, WaveFreq, Delay (?)
                    syn.setParameterValue(
                        'aStim2', 'WaveAmp',
                        0)  # set all values to 0  bc no auditory
                    syn.setParameterValue('aStim2', 'WaveFreq', 0)
                    syn.setParameterValue('aStim2', 'PulseDur', 0)

                #print("===========================\n")
                #print("===Visual component only===\n")
                dur = (
                    trial['flash_dur_ms']
                ) / 1000.0  #pres. dur. in ms -> div by 1000 since flash takes in seconds
                lum = trial['luminance']  # luminance

                flash.pres_dur = dur
                flash.luminance = lum

                #print("Luminance: ", lum)
                #present the stimulus
                exp.addData('Vis_onset',
                            expClock.getTime())  #record visual onset time

                marker.draw_marker(window)
                flash.flash(window)
                window.flip()

            elif (stim_code == 2):  #A+V stim
                #option 1: Audio first: delay -
                if (trial['delay_ms'] < 0
                    ):  #delay = time (ms) between A and V within the trial
                    #print("=================================================\n")
                    #print("===Auditory and visual components on: A first ===\n *Play tone at %d dB*\n" %trial['wave_amp_dB'])

                    # add auditory onset data
                    exp.addData('Aud_onset', expClock.getTime())

                    # wait while the audio is going + the delay btw stimuli
                    total_wait = (abs(trial['delay_ms']) +
                                  trial['pulse_dur_ms']) / 1000.0
                    #print("Waiting for tone to play: " ,trial['pulse_dur_ms'] , "ms")
                    #print("Waiting (stimulus delay): " ,(trial['delay_ms']), " ms")

                    core.wait(total_wait)

                    dur = (trial['flash_dur_ms']) / 1000.0  #pres. dur. in ms
                    lum = trial['luminance']  # luminance

                    flash.pres_dur = dur
                    flash.luminance = lum

                    #print("Luminance: \n", lum)
                    # Record visual onset
                    exp.addData('Vis_onset', expClock.getTime())

                    #present the stimulus
                    marker.draw_marker(window)
                    flash.flash(window)
                    window.flip(
                    )  #TODO: change to be timed by frame instead of seconds

                #option 2: Visual first: delay +
                if (trial['delay_ms'] > 0):
                    #print("=================================================\n")
                    #print("===Auditory and visual components on: V first ===\n *Play tone at %d dB*\n" %trial['wave_amp_dB'])
                    dur = (trial['flash_dur_ms']) / 1000.0  #pres. dur. in ms
                    lum = trial['luminance']  # luminance

                    flash.pres_dur = dur
                    flash.luminance = lum

                    #print("Luminance: \n", lum)
                    exp.addData('Vis_onset',
                                expClock.getTime())  # visual onset data

                    #present the stimulus
                    marker.draw_marker(window)
                    flash.flash(window)
                    window.flip(
                    )  #TODO: change to be timed by frame instead of seconds

                    #convert delay to seconds
                    #	total_wait = (trial['delay_ms']+trial['pulse_dur_ms'])/1000.0 # after visual presented, need to wait the delay btw stimuli + the duration of the audio pulse
                    #print("Waiting (stimulus delay): " ,trial['delay_ms'], " ms")
                    core.wait(trial['delay_ms'] / 1000.0)

                    exp.addData('Aud_onset', expClock.getTime())

                    #print("Waiting for tone to play: " ,trial['pulse_dur_ms'], "ms")
                    core.wait(trial['pulse_dur_ms'] / 1000.0)

                #option 3: Simultaneous: delay 0
                if (trial['delay_ms'] == 0):
                    #print("======================================================\n")
                    #print("===Auditory and visual components on: Simultaneous ===\n *Play tone at %d dB*\n" %trial['wave_amp_dB'])
                    dur = (trial['flash_dur_ms']) / 1000.0  #pres. dur. in ms
                    lum = trial['luminance']  # luminance

                    flash.pres_dur = dur
                    flash.luminance = lum

                    #print("Luminance: \n", lum)

                    exp.addData('Aud_onset', expClock.getTime())
                    exp.addData('Vis_onset', expClock.getTime())

                    #present the stimulus
                    marker.draw_marker(window)
                    flash.flash(window)
                    window.flip(
                    )  #TODO: change to be timed by frame instead of seconds

            #print("Waiting ISI Time: ", inter, 's \n')
            core.wait(
                inter - (self.JITTER / 1000.0)
            )  #inter stimulus interval = time between successive presentations
            window.flip()

            exp.nextEntry()
Exemplo n.º 24
0
                                ori=0,
                                color='white',
                                colorSpace='rgb',
                                opacity=1,
                                depth=-5.0)

# Create some handy timers
globalClock = core.Clock()  # to track the time since experiment started
routineTimer = core.CountdownTimer(
)  # to track time remaining of each (non-slip) routine

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('Trust.csv'),
                           seed=None,
                           name='trials')
thisExp.addLoop(trials)  # add the loop to the experiment
thisTrial = trials.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
if thisTrial != None:
    for paramName in thisTrial.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
Exemplo n.º 25
0
bubble = visual.Circle(win, fillColor='black', lineColor='black')

#==========================
# Define the trial sequence
#==========================

# Define a list of trials with their properties:
#   - Which image (without the suffix)
#   - Which orientation
stim_order = []
for im, ori in zip(imlist, orilist):
    stim_order.append({'im': im, 'ori': ori})

trials = data.TrialHandler(stim_order,
                           nReps=1,
                           extraInfo=exp_info,
                           method='sequential',
                           originPath=datapath)

#=====================
# Start the experiment
#=====================

# Initialize two clocks:
#   - for image change time
#   - for response time
change_clock = core.Clock()
rt_clock = core.Clock()

# Run through the trials
for trial in trials:
Exemplo n.º 26
0
#-------------------------------------------------------------------------------------------#


# ---------- usefule lists ----------


TrialComponents = [image] + sliderComponents + buttonComponents + ballComponents

# repeaet the trial for 5 times, range(0,5) = [0,1,2,3,4]
for k in range(0,5):

    # ----- trial preparation -----
    
    # set up handler to look after randomisation of conditions etc
    trials = data.TrialHandler(nReps=1, method='sequential', 
        extraInfo=expInfo, originPath=-1,
        trialList=data.importConditions(conditionFile[0], selection=selectionGenerator(ramDistractor)),
        seed=None, name='trials')
        
    thisExp.addLoop(trials)                 # add the loop to the experiment
    thisTrial = trials.trialList[0]         # so we can initialise stimuli with some values
    
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName)) 

    # ----- enter one trial -----
    
    for thisTrial in trials:
        currentLoop = trials
        
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()
        win.clearBuffer()

# -------Ending Routine "instructPractice"-------
for thisComponent in instructPracticeComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "instructPractice" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
practice = data.TrialHandler(nReps=1.0,
                             method='sequential',
                             extraInfo=expInfo,
                             originPath=-1,
                             trialList=data.importConditions('practice.xlsx'),
                             seed=None,
                             name='practice')
thisExp.addLoop(practice)  # add the loop to the experiment
thisPractice = practice.trialList[
    0]  # so we can initialise stimuli with some values

# abbreviate parameter names if possible (e.g. rgb = thisPractice.rgb)
if thisPractice != None:
    for paramName in thisPractice.keys():
        exec(paramName + '= thisPractice.' + paramName)

for thisPractice in practice:
    currentLoop = practice
    # abbreviate parameter names if possible (e.g. rgb = thisPractice.rgb)
stimuli = exptInfo['05. Stimuli'].split(',')

stimList = []
for stimulus in stimuli:
    for speed in speeds:
        stimList.append({
            'stimulus':
            stimulus,
            'speed':
            speed,
            'stimCueSound':
            './sounds/stim {}cms {}.wav'.format(speed, stimulus),
            'timingCueSound':
            './sounds/timing {}cm-sec.wav'.format(speed)
        })
trials = data.TrialHandler(stimList, exptInfo['03. Number of repeats'])

# ----

# -- MAKE FOLDER/FILES TO SAVE DATA --

saveFiles = DataFileCollection(
    foldername=exptInfo['09. Folder for saving data'],
    filename=exptInfo['02. Experiment name'] + '_' +
    exptInfo['10. Date and time'] + '_P' + exptInfo['01. Participant Code'],
    headers=['trial', 'stimulus', 'speed', 'rating'],
    dlgInput=exptInfo)

# ----

# -- SETUP VISUAL INTERFACE INCLUDING VAS --
Exemplo n.º 29
0
    def start(self, data_folder, mode=u'Демо', test_screen=None):
        logging.console.setLevel(logging.WARNING)
        log = logging.LogFile('data/' + data_folder + '/' + self.name + '.log',
                              level=logging.INFO,
                              filemode='w')

        self.init_attr()

        # Make output folder
        DATA_FILE = 'data/' + data_folder + '/' + self.name + '.csv'
        self.data_file = open(DATA_FILE, mode='w')
        self.data_file.write(';'.join(self.varnames) + '\n')

        self.test_screen = test_screen
        self.init_devices()
        self.init_instr_stimuli()
        self.init_trial_stimuli()

        # --------------------------------------------------------------------
        # Start the test
        # 1. Instruction
        self.vars['series'] = 'training'
        # We will need this for demonstration
        self.training_trials = self.trial_dict.pop('training')

        try:
            self.start_demonstration()
        except FinishTest:
            self.exit()
            return

        self.keys = [x['cor_resp'] for x in self.training_trials]
        trials = data.TrialHandler(self.training_trials,
                                   self.nreps,
                                   method='random')
        core.wait(1)

        maxtrials = self.maxtrain
        for trial in trials:
            if self.totalN + 1 > maxtrials:
                self.status = 'interrupted'
                self.exit()
            # Run trial
            self.trial_seq += 1
            self.totalN += 1
            self.vars['n'] = self.totalN
            self.vars['trial'] = trials.thisN + 1
            for i, v in trial.iteritems():
                self.vars[i] = v

            self.wait(trial)
            self.write_data()

            # Check status
            if self.trial_seq >= self.mintrain:
                if float(self.ncorrect) / self.trial_seq >= self.mincorrect:
                    break
                else:
                    try:
                        self.check_status()
                    except FinishTest:
                        self.exit()
                        return
            logging.flush()

        # --------------------------------------------------------------------
        # 2. Main series
        if mode == u'Демо':
            maxtrials = self.ndemo
        else:
            maxtrials = self.maxtrials

        try:
            self.instr_stimuli['start_main'].draw()
            self.test_screen.flip()
            self.suspend(wait=None)
        except FinishTest:
            self.exit()
            return
        except GoOn:
            pass

        for series in self.trial_dict:
            self.nfailed = 0
            self.invalidstrike = 0
            self.ncorrect = 0
            self.trial_seq = 0

            self.vars['series'] = series

            self.keys = [x['cor_resp'] for x in self.trial_dict[series]]

            trials = data.TrialHandler(self.trial_dict[series],
                                       self.nreps,
                                       method='random')
            core.wait(1)
            for trial in trials:
                if self.totalN + 1 > maxtrials:
                    self.status = 'complete'
                    break
                if self.trial_seq >= self.mintrain:
                    try:
                        self.check_status()
                    except FinishTest:
                        self.exit()
                        return

                # break after breaktrials number of trials
                if self.totalN > 0 and (self.totalN % self.breaktrials) == 0:
                    self.make_a_break(self.breaktime)

                self.trial_seq += 1
                self.totalN += 1
                self.vars['n'] = self.totalN
                self.vars['trial'] = trials.thisN + 1
                for i, v in trial.iteritems():
                    self.vars[i] = v

                self.wait(trial)
                self.write_data()
                logging.flush()
        else:
            self.status = 'complete'

        self.exit()
        return
#######################
## Factorial design ###
#######################
numResponsesPerTrial = 1 #default. Used to create headers for dataFile
stimList = []
#cuePositions = [dot for dot in range(nDots) if dot not in [0,nDots-1]]
cuePositions = [pos for pos in range(8,17)]
print('cuePositions: ',cuePositions)
#cuePositions = cuePositions[2:(nDots-3)] #drop the first and final two dots
#Set up the factorial design (list of all conditions)

for cuePos in cuePositions:
    stimList.append({'cuePos':cuePos})

trials = data.TrialHandler(stimList, nReps = trialsPerCondition) #trialsPerCondition on line 80 so that it's in the setup dialogue box. Change it there to change dialogue box default. 


####Create output file###
#########################################################################
dataFile = open(fileNameWithPath + '.txt', 'w')
numResponsesPerTrial = 1

#headers for initial datafile rows, they don't get repeated. These appear in the file in the order they appear here.
oneOffHeaders = [
    'subject',
    'task',
    'staircase',
    'trialNum',
    'stimulus',
    'monitorWidth',