Пример #1
0
def test_TrialTypeImport():
    fromCSV = data.importConditions(os.path.join(fixturesPath, 'trialTypes.csv'))
    fromXLSX = data.importConditions(os.path.join(fixturesPath, 'trialTypes.xlsx'))

    for trialN, trialCSV in enumerate(fromCSV):
        trialXLSX = fromXLSX[trialN]
        assert trialXLSX.keys()==trialCSV.keys()
        for header in trialCSV.keys():
            if trialXLSX[header] != trialCSV[header]:
                print(header, trialCSV[header], trialXLSX[header])
            assert trialXLSX[header] == trialCSV[header]
Пример #2
0
def test_TrialTypeImport():
    fromCSV = data.importConditions(os.path.join(thisDir, 'trialTypes.csv'))
    fromXLSX = data.importConditions(os.path.join(thisDir, 'trialTypes.xlsx'))

    for trialN, trialCSV in enumerate(fromCSV):
        trialXLSX = fromXLSX[trialN]
        assert trialXLSX.keys()==trialCSV.keys()
        for header in trialCSV.keys():
            if trialXLSX[header]==None and numpy.isnan(trialCSV[header]):
                trialCSV[header]=None#this is ok
            if trialXLSX[header] != trialCSV[header]:
                print header, trialCSV[header], trialXLSX[header]
            assert trialXLSX[header] == trialCSV[header]
Пример #3
0
        def findPathsInFile(filePath):
            """Recursively search a conditions file (xlsx or csv)
             extracting valid file paths in any param/cond

            :param filePath: str to a potential file path (rel or abs)
            :return: list of dicts{'rel','abs'} of valid file paths
            """
            paths = []
            # does it look at all like an excel file?
            if (not isinstance(filePath, basestring)
                    or filePath[-4:] not in ['.csv', 'xlsx']):
                return paths
            thisFile = getPaths(filePath)
            # does it exist?
            if not thisFile:
                return paths
            # this file itself is valid so add to resources if not already
            if thisFile not in paths:
                paths.append(thisFile)
            conds = data.importConditions(thisFile['abs'])  # load the abs path
            for thisCond in conds:  # thisCond is a dict
                for param, val in list(thisCond.items()):
                    if isinstance(val, basestring) and len(val):
                        subFile = getPaths(val)
                    else:
                        subFile = None
                    if subFile:
                        paths.append(subFile)
                        # if it's a possible conditions file then recursive
                        if thisFile['abs'][-4:] in ["xlsx", ".csv"]:
                            contained = findPathsInFile(subFile['abs'])
                            paths.extend(contained)
            return paths
Пример #4
0
    def test_TrialHandlerAndXLSX(self):
        """Currently tests the contents of xslx file against known good example
        """
        conds = data.importConditions(os.path.join(fixturesPath,
                                                   'trialTypes.xlsx'))
        trials = data.TrialHandler(trialList=conds,
                                   seed=self.random_seed,
                                   nReps=2, autoLog=False)

        responses = [1,1,None,3,2,3, 1,3,2,2,1,1]
        rts = [0.1,0.1,None,0.3,0.2,0.3, 0.1,0.3,0.2,0.2,0.1,0.1]

        for trialN, trial in enumerate(trials):
            if responses[trialN] is None:
                continue
            trials.addData('resp', responses[trialN])
            trials.addData('rt',rts[trialN])

        trials.saveAsExcel(self.name)# '.xlsx' should be added automatically
        trials.saveAsText(self.name, delim=',')# '.xlsx' added automatically
        trials.saveAsWideText(os.path.join(self.temp_dir,'actualXlsx'))
        # Make sure the file is there
        assert os.path.isfile(self.fullName)
        #compare with known good file
        utils.compareXlsxFiles(self.fullName,
                               os.path.join(fixturesPath,'corrXlsx.xlsx'))
Пример #5
0
 def test_loopBlocks(self):
     """An experiment file with made-up params and routines to see whether
     future versions of experiments will get loaded.
     """
     #load the test experiment (with a stims loop, trials loop and blocks loop)
     expfile = path.join(self.exp.prefsPaths['tests'], 'data', 'testLoopsBlocks.psyexp')
     self.exp.loadFromXML(expfile) # reload the edited file
     #alter the settings so the data goes to our tmp dir
     datafileBase = os.path.join(self.tmp_dir, 'testLoopsBlocks')
     self.exp.settings.params['Data filename'].val = repr(datafileBase)
     #write the script from the experiment
     script = self.exp.writeScript(expPath=expfile)
     py_file = os.path.join(self.tmp_dir, 'testLoopBlocks.py')
     # save it
     f = codecs.open(py_file, 'w', 'utf-8')
     f.write(script.getvalue().replace("core.quit()", "pass"))
     f.write("del thisExp\n") #garbage collect the experiment so files are auto-saved
     f.close()
     #run the file (and make sure we return to this location afterwards)
     wd = os.getcwd()
     execfile(py_file)
     os.chdir(wd)
     #load the data
     dat = data.importConditions(datafileBase+".csv")
     assert len(dat)==8 # because 4 'blocks' with 2 trials each (3 stims per trial)
Пример #6
0
    def test_quest(self):
        conditions = data.importConditions(
            os.path.join(fixturesPath, 'multiStairConds.xlsx'))
        stairs = data.MultiStairHandler(
            stairType='quest', conditions=conditions, method='random',
            nTrials=20, name='QuestStairs', autoLog=False)
        exp = data.ExperimentHandler(
            name='testExp', savePickle=True, saveWideText=True,
            dataFileName=os.path.join(self.temp_dir, 'multiQuestExperiment'),
            autoLog=False)
        rng = np.random.RandomState(seed=self.random_seed)

        exp.addLoop(stairs)
        for intensity, condition in stairs:
            # make data that will cause different stairs to finish different
            # times
            if rng.rand() > condition['startVal']:
                corr = 1
            else:
                corr = 0
            stairs.addData(corr)

        stairs.saveAsExcel(os.path.join(self.temp_dir, 'multiQuestOut'))

        # contains more info
        stairs.saveAsPickle(os.path.join(self.temp_dir, 'multiQuestOut'))
        exp.close()
Пример #7
0
 def testTrialHandlerAndXLSX(self):
     conds = data.importConditions(os.path.join(thisDir, 'trialTypes.xlsx'))
     trials = data.TrialHandler(trialList=conds, seed=100, nReps=2)
     responses=[1,1,2,3,2,3, 1,3,2,2,1,1]
     rts=numpy.array(responses)/10.0
     for trialN, trial in enumerate(trials):
         trials.addData('resp', responses[trialN])
         trials.addData('rt',rts[trialN])
     trials.saveAsExcel(self.name)
     
     # Make sure the file is there
     assert os.path.isfile(self.fullName)
     expBook = load_workbook(os.path.join(thisDir,'corrXlsx.xlsx'))
     actBook = load_workbook(self.fullName)
     
     for wsN, expWS in enumerate(expBook.worksheets):
         actWS = actBook.worksheets[wsN]
         for key, expVal in expWS._cells.items():
             actVal = actWS._cells[key]
             try:
                 # convert to float if possible and compare with a reasonable
                 # (default) precision
                 expVal.value = float(expVal.value)
                 nose.tools.assert_almost_equals(expVal.value,
                                                 float(actVal.value))
             except:
                 # otherwise do precise comparison
                 nose.tools.assert_equal(expVal.value, actVal.value)
Пример #8
0
def test_ImportCondsUnicode():
    if not data.haveXlrd:
        # open pyxl thinks the right-to-left file has blanks in header
        pytest.skip("We know this fails with openpyxl")

    fromXLSX = data.importConditions(os.path.join(fixturesPath,
                                     'right_to_left_unidcode.xlsx'))
    assert u'\u05d2\u05d9\u05dc' in fromXLSX[0]['question']
Пример #9
0
def openTrialHandler(xlsx_source):
    exp_conditions = importConditions(xlsx_source)
    trials = TrialHandler(exp_conditions, 1)

    # Inform the ioDataStore that the experiment is using a
    # TrialHandler. The ioDataStore will create a table
    # which can be used to record the actual trial variable values (DV or IV)
    # in the order run / collected.
    #
    io.createTrialHandlerRecordTable(trials)
    return trials
Пример #10
0
    def exposurePhase(self, condFile = None, reps = 1):
		# test has rating, exposure has break
        self.generateDisplay()
        self.conditionsFile = data.importConditions('conditions/'+condFile)
        self.trials = data.TrialHandler(self.conditionsFile, method = 'sequential', nReps = reps, extraInfo = EXP_INFO)
        for trial in self.trials :
            thisSequence = [trial.A]
            for item in thisSequence:
                self.playSound(whichSound='sounds/'+str(item)+'.wav', ISI = 0.50)
			# core.wait(0) # uncomment to add silence between trials (in addition to ISI after each sound) replace 0 with amount of time
            if event.getKeys(['escape']): core.quit()
        self.trials.saveAsWideText(thisPhase+'datafile.csv', delim=",")
Пример #11
0
        def findPathsInFile(filePath):
            """Recursively search a conditions file (xlsx or csv)
             extracting valid file paths in any param/cond

            :param filePath: str to a potential file path (rel or abs)
            :return: list of dicts{'rel','abs'} of valid file paths
            """

            # Clean up filePath that cannot be eval'd
            if '$' in filePath:
                try:
                    filePath = filePath.strip('$')
                    filePath = eval(filePath)
                except NameError:
                    # List files in director and get condition files
                    if 'xlsx' in filePath or 'xls' in filePath or 'csv' in filePath:
                        # Get all xlsx and csv files
                        expPath = self.expPath
                        if 'html' in self.expPath:  # Get resources from parent directory i.e, original exp path
                            expPath = self.expPath.split('html')[0]
                        fileList = (
                        [getPaths(condFile) for condFile in os.listdir(expPath)
                         if len(condFile.split('.')) > 1
                         and condFile.split('.')[1] in ['xlsx', 'xls', 'csv']])
                        return fileList
            paths = []
            # does it look at all like an excel file?
            if (not isinstance(filePath, basestring)
                    or not os.path.splitext(filePath)[1] in ['.csv', '.xlsx',
                                                             '.xls']):
                return paths
            thisFile = getPaths(filePath)
            # does it exist?
            if not thisFile:
                return paths
            # this file itself is valid so add to resources if not already
            if thisFile not in paths:
                paths.append(thisFile)
            conds = data.importConditions(thisFile['abs'])  # load the abs path
            for thisCond in conds:  # thisCond is a dict
                for param, val in list(thisCond.items()):
                    if isinstance(val, basestring) and len(val):
                        subFile = getPaths(val)
                    else:
                        subFile = None
                    if subFile:
                        paths.append(subFile)
                        # if it's a possible conditions file then recursive
                        if thisFile['abs'][-4:] in ["xlsx", ".xls", ".csv"]:
                            contained = findPathsInFile(subFile['abs'])
                            paths.extend(contained)
            return paths
Пример #12
0
 def test_quest(self):
     conditions = data.importConditions(
         pjoin(TESTSDATA_PATH, 'multiStairConds.xlsx'))
     stairs = data.MultiStairHandler(stairType='quest', conditions=conditions,
                 method='random', nTrials=5)
     for intensity,condition in stairs:
         #make data that will cause different stairs to finish different times
         if random()>condition['startVal']:
             corr=1
         else:corr=0
         stairs.addData(corr)
     stairs.saveAsExcel(pjoin(self.temp_dir, 'multiQuestOut'))
     stairs.saveAsPickle(pjoin(self.temp_dir, 'multiQuestOut'))#contains more info
Пример #13
0
def test_TrialTypeImport():
    def checkEachtrial(fromCSV, fromXLSX):
        for trialN, trialCSV in enumerate(fromCSV):
            trialXLSX = fromXLSX[trialN]
            assert list(trialXLSX.keys()) == list(trialCSV.keys())
            for header in trialCSV:
                if trialXLSX[header] != trialCSV[header]:
                    print(header, trialCSV[header], trialXLSX[header])
                assert trialXLSX[header] == trialCSV[header]
    fromCSV = data.importConditions(os.path.join(fixturesPath,
                                                 'trialTypes.csv'))
    # use pandas/xlrd once
    fromXLSX = data.importConditions(os.path.join(fixturesPath,
                                                  'trialTypes.xlsx'))
    checkEachtrial(fromCSV, fromXLSX)

    # then pretend it doesn't exist to force use of openpyxl
    haveXlrd = data.haveXlrd
    data.haveXlrd = False
    fromXLSX = data.importConditions(os.path.join(fixturesPath,
                                                  'trialTypes.xlsx'))
    checkEachtrial(fromCSV, fromXLSX)
    data.haveXlrd = haveXlrd  # return to what it was
Пример #14
0
	def __init__(self,win,info):
		self.boards = [] #Empty board array
		self.reverseImage = 'images/card-back.png'
		self.win = win
		self.boardData = data.importConditions('expdata.xlsx') #Read in data file
		self.trials = data.TrialHandler(trialList=self.boardData, nReps=1, method="sequential")

		#Now create the experimentHandler
		self.thisExp = data.ExperimentHandler(
							name= "Card pair game", 
							version =1,
							extraInfo = info, #the info we created earlier
							dataFileName = "data/" + info['participant'] + "_" + info['session'] + "_part2_"+ info['dateStr']
						)		
Пример #15
0
 def removeComponent(self, component, compID):
     """Remove either a Routine or a Loop from the Flow
     """
     flow = self.frame.exp.flow
     if component.getType() == 'Routine':
         # check whether this will cause a collapsed loop
         # prev and next elements on flow are a loop init/end
         prevIsLoop = nextIsLoop = False
         if compID > 0:  # there is at least one preceding
             prevIsLoop = (flow[compID - 1]).getType() == 'LoopInitiator'
         if len(flow) > (compID + 1):  # there is at least one more compon
             nextIsLoop = (flow[compID + 1]).getType() == 'LoopTerminator'
         if prevIsLoop and nextIsLoop:
             # because flow[compID+1] is a terminator
             loop = flow[compID + 1].loop
             msg = _translate('The "%s" Loop is about to be deleted as '
                              'well (by collapsing). OK to proceed?')
             title = _translate('Impending Loop collapse')
             warnDlg = dialogs.MessageDialog(
                 parent=self.frame, message=msg % loop.params['name'],
                 type='Warning', title=title)
             resp = warnDlg.ShowModal()
             if resp in [wx.ID_CANCEL, wx.ID_NO]:
                 return  # abort
             elif resp == wx.ID_YES:
                 # make recursive calls to this same method until success
                 # remove the loop first
                 self.removeComponent(loop, compID)
                 # because the loop has been removed ID is now one less
                 self.removeComponent(component, compID - 1)
                 return  # have done the removal in final successful call
     # remove name from namespace only if it's a loop;
     # loops exist only in the flow
     elif 'conditionsFile' in component.params:
         conditionsFile = component.params['conditionsFile'].val
         if conditionsFile and conditionsFile not in ['None', '']:
             try:
                 trialList, fieldNames = data.importConditions(
                     conditionsFile, returnFieldNames=True)
                 for fname in fieldNames:
                     self.frame.exp.namespace.remove(fname)
             except Exception:
                 msg = ("Conditions file %s couldn't be found so names not"
                        " removed from namespace")
                 logging.debug(msg % conditionsFile)
         self.frame.exp.namespace.remove(component.params['name'].val)
     # perform the actual removal
     flow.removeComponent(component, id=compID)
     self.draw()
Пример #16
0
    def testPhase(self, condFile = None, reps = 1):
		# test has rating, exposure has break
        self.generateDisplay()
        self.conditionsFile = data.importConditions('conditions/'+condFile)
        self.trials = data.TrialHandler(self.conditionsFile, method = 'sequential', nReps = reps, extraInfo = EXP_INFO)
        for trial in self.trials :
            # fix filter NA for future
            thisSequence = [trial.A]
            for item in thisSequence:
                self.playSound(whichSound='sounds/'+str(item)+'.wav', ISI = 0.50)
            if thisPhase == 'test':
                rating = self.collectRating()
                self.trials.addData('rating', rating)
            if event.getKeys(['escape']): core.quit()
        self.trials.saveAsWideText(thisPhase+'datafile.csv', delim=",")
Пример #17
0
 def test_simple(self):
     conditions = data.importConditions(
         pjoin(fixturesPath, 'multiStairConds.xlsx'))
     stairs = data.MultiStairHandler(stairType='simple', conditions=conditions,
             method='random', nTrials=20, name='simpleStairs', autoLog=False)
     exp = data.ExperimentHandler(name='testExp',
                 savePickle=True,
                 saveWideText=True,
                 dataFileName=pjoin(self.temp_dir, 'multiStairExperiment'), autoLog=False)
     exp.addLoop(stairs)
     for intensity,condition in stairs:
         #make data that will cause different stairs to finish different times
         if random()>condition['startVal']:
             corr=1
         else:corr=0
         stairs.addData(corr)
     stairs.saveAsExcel(pjoin(self.temp_dir, 'multiStairOut'))
     stairs.saveAsPickle(pjoin(self.temp_dir, 'multiStairOut'))#contains more info
if thisCycleLoop != None:
    for paramName in thisCycleLoop.keys():
        exec(paramName + '= thisCycleLoop.' + paramName)

for thisCycleLoop in CycleLoop:
    currentLoop = CycleLoop
    # print "LOOP COUNT (Cycle No): ", currentLoop
    # abbreviate parameter names if possible (e.g. rgb = thisCycleLoop.rgb)
    if thisCycleLoop != None:
        for paramName in thisCycleLoop.keys():
            exec(paramName + '= thisCycleLoop.' + paramName)
    
    # LOOP for IRREGULAR TARGETS
    irregularTargets = data.TrialHandler(nReps=4, method=u'random', 
        extraInfo=expInfo, originPath=None,
        trialList=data.importConditions('Oddballs_irregular_WavFilesCalib.csv'),
        seed=None, name='irregularTargets')
        # NOTE now how there are only 4 repetitions (nReps) of the irregularTargets,
        # whereas you might assume 8 to be the correct number, but now as we define
        # the deviant-deviant interval differently so that the deviant can be preceded by
        # 2-6 or 8-12 standard tones and during 8 consecutive tones there might be two deviants
        # for example the each block now consists of 16 tones in contrast to 8 tones per block
        # of the regular condition (see below), see the Fig. 1 of Jongsma et al. (2013) for graphical
        # representation

    thisExp.addLoop(irregularTargets)  # add the loop to the experiment
    thisIrregularTarget = irregularTargets.trialList[0]  # so we can initialise stimuli with some values
    # abbreviate parameter names if possible (e.g. rgb=thisIrregularTarget.rgb)
    if thisIrregularTarget != None:
        for paramName in thisIrregularTarget.keys():
            exec(paramName + '= thisIrregularTarget.' + paramName)
# Initialize components for Routine "trial2"
trial2Clock = core.Clock()
text_2 = visual.TextStim(win=win, ori=0, name='text_2',
    text='nonsense',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace=u'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
trials = data.TrialHandler(nReps=5, method=u'random', 
    extraInfo=expInfo, originPath=u'/Users/trueswelllab/Downloads/videomodule-master/text experiment.psyexp',
    trialList=data.importConditions(u'test.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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #20
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('UG.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:
        for paramName in thisTrial.keys():
Пример #21
0
def importTrials(fileName,method="sequential",seed=random.randint(1,100)):
	(stimList,fieldNames) = data.importConditions(fileName,returnFieldNames=True)
	trials = data.TrialHandler(stimList,1,method=method,seed=seed) #seed is ignored for sequential; used for 'random'
	return (trials,fieldNames)
Пример #22
0
text = visual.TextStim(win=win, name='text',
    text='default text',
    font='Arial',
    pos=(0, 0), height=0.1, wrapWidth=None, ori=0, 
    color=1.0, colorSpace='rgb', opacity=1,
    depth=-2.0);
ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI')

# 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=5, method='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('test.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.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #23
0
# -------Ending Routine "Instruction"-------
for thisComponent in InstructionComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('TODO.started', TODO.tStartRefresh)
thisExp.addData('TODO.stopped', TODO.tStopRefresh)
# 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
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions(trialImages),
                           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
    counter = 1
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
Пример #24
0
                                   colorSpace=u'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
trials = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=None,
    trialList=data.importConditions('PPAconditionsEEG2016-10-24.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:
        for paramName in thisTrial.keys():
Пример #25
0
    def loadFromXML(self, filename):
        """Loads an xml file and parses the builder Experiment from it
        """
        self._doc.parse(filename)
        root = self._doc.getroot()

        # some error checking on the version (and report that this isn't valid
        # .psyexp)?
        filenameBase = os.path.basename(filename)
        if root.tag != "PsychoPy2experiment":
            logging.error('%s is not a valid .psyexp file, "%s"' %
                          (filenameBase, root.tag))
            # the current exp is already vaporized at this point, oops
            return
        self.psychopyVersion = root.get('version')
        versionf = float(self.psychopyVersion.rsplit('.', 1)[0])
        if versionf < 1.63:
            msg = 'note: v%s was used to create %s ("%s")'
            vals = (self.psychopyVersion, filenameBase, root.tag)
            logging.warning(msg % vals)

        # Parse document nodes
        # first make sure we're empty
        self.flow = Flow(exp=self)  # every exp has exactly one flow
        self.routines = {}
        self.namespace = NameSpace(self)  # start fresh
        modifiedNames = []
        duplicateNames = []

        # fetch exp settings
        settingsNode = root.find('Settings')
        for child in settingsNode:
            self._getXMLparam(params=self.settings.params, paramNode=child,
                              componentNode=settingsNode)
        # name should be saved as a settings parameter (only from 1.74.00)
        if self.settings.params['expName'].val in ['', None, 'None']:
            shortName = os.path.splitext(filenameBase)[0]
            self.setExpName(shortName)
        # fetch routines
        routinesNode = root.find('Routines')
        allCompons = getAllComponents(
            self.prefsBuilder['componentsFolders'], fetchIcons=False)
        # get each routine node from the list of routines
        for routineNode in routinesNode:
            routineGoodName = self.namespace.makeValid(
                routineNode.get('name'))
            if routineGoodName != routineNode.get('name'):
                modifiedNames.append(routineNode.get('name'))
            self.namespace.user.append(routineGoodName)
            routine = Routine(name=routineGoodName, exp=self)
            # self._getXMLparam(params=routine.params, paramNode=routineNode)
            self.routines[routineNode.get('name')] = routine
            for componentNode in routineNode:

                componentType = componentNode.tag
                if componentType in allCompons:
                    # create an actual component of that type
                    component = allCompons[componentType](
                        name=componentNode.get('name'),
                        parentName=routineNode.get('name'), exp=self)
                else:
                    # create UnknownComponent instead
                    component = allCompons['UnknownComponent'](
                        name=componentNode.get('name'),
                        parentName=routineNode.get('name'), exp=self)
                # check for components that were absent in older versions of
                # the builder and change the default behavior
                # (currently only the new behavior of choices for RatingScale,
                # HS, November 2012)
                # HS's modification superceded Jan 2014, removing several
                # RatingScale options
                if componentType == 'RatingScaleComponent':
                    if (componentNode.get('choiceLabelsAboveLine') or
                            componentNode.get('lowAnchorText') or
                            componentNode.get('highAnchorText')):
                        pass
                    # if not componentNode.get('choiceLabelsAboveLine'):
                    #    # this rating scale was created using older version
                    #    component.params['choiceLabelsAboveLine'].val=True
                # populate the component with its various params
                for paramNode in componentNode:
                    self._getXMLparam(params=component.params,
                                      paramNode=paramNode,
                                      componentNode=componentNode)
                compGoodName = self.namespace.makeValid(
                    componentNode.get('name'))
                if compGoodName != componentNode.get('name'):
                    modifiedNames.append(componentNode.get('name'))
                self.namespace.add(compGoodName)
                component.params['name'].val = compGoodName
                routine.append(component)
        # for each component that uses a Static for updates, we need to set
        # that
        for thisRoutine in list(self.routines.values()):
            for thisComp in thisRoutine:
                for thisParamName in thisComp.params:
                    thisParam = thisComp.params[thisParamName]
                    if thisParamName == 'advancedParams':
                        continue  # advanced isn't a normal param
                    elif thisParam.updates and "during:" in thisParam.updates:
                        # remove the part that says 'during'
                        updates = thisParam.updates.split(': ')[1]
                        routine, static = updates.split('.')
                        if routine not in self.routines:
                            msg = ("%s was set to update during %s Static "
                                   "Component, but that component no longer "
                                   "exists")
                            logging.warning(msg % (thisParamName, static))
                        else:
                            self.routines[routine].getComponentFromName(
                                static).addComponentUpdate(
                                thisRoutine.params['name'],
                                thisComp.params['name'], thisParamName)
        # fetch flow settings
        flowNode = root.find('Flow')
        loops = {}
        for elementNode in flowNode:
            if elementNode.tag == "LoopInitiator":
                loopType = elementNode.get('loopType')
                loopName = self.namespace.makeValid(elementNode.get('name'))
                if loopName != elementNode.get('name'):
                    modifiedNames.append(elementNode.get('name'))
                self.namespace.add(loopName)
                loop = eval('%s(exp=self,name="%s")' % (loopType, loopName))
                loops[loopName] = loop
                for paramNode in elementNode:
                    self._getXMLparam(paramNode=paramNode, params=loop.params)
                    # for conditions convert string rep to list of dicts
                    if paramNode.get('name') == 'conditions':
                        param = loop.params['conditions']
                        # e.g. param.val=[{'ori':0},{'ori':3}]
                        try:
                            param.val = eval('%s' % (param.val))
                        except SyntaxError:
                            # This can occur if Python2.7 conditions string
                            # contained long ints (e.g. 8L) and these can't be
                            # parsed by Py3. But allow the file to carry on
                            # loading and the conditions will still be loaded
                            # from the xlsx file
                            pass
                # get condition names from within conditionsFile, if any:
                try:
                    # psychophysicsstaircase demo has no such param
                    conditionsFile = loop.params['conditionsFile'].val
                except Exception:
                    conditionsFile = None
                if conditionsFile in ['None', '']:
                    conditionsFile = None
                if conditionsFile:
                    try:
                        trialList, fieldNames = data.importConditions(
                            conditionsFile, returnFieldNames=True)
                        for fname in fieldNames:
                            if fname != self.namespace.makeValid(fname):
                                duplicateNames.append(fname)
                            else:
                                self.namespace.add(fname)
                    except Exception:
                        pass  # couldn't load the conditions file for now
                self.flow.append(LoopInitiator(loop=loops[loopName]))
            elif elementNode.tag == "LoopTerminator":
                self.flow.append(LoopTerminator(
                    loop=loops[elementNode.get('name')]))
            elif elementNode.tag == "Routine":
                if elementNode.get('name') in self.routines:
                    self.flow.append(self.routines[elementNode.get('name')])
                else:
                    logging.error("A Routine called '{}' was on the Flow but "
                                  "could not be found (failed rename?). You "
                                  "may need to re-insert it".format(
                        elementNode.get('name')))
                    logging.flush()

        if modifiedNames:
            msg = 'duplicate variable name(s) changed in loadFromXML: %s\n'
            logging.warning(msg % ', '.join(list(set(modifiedNames))))
        if duplicateNames:
            msg = 'duplicate variable names: %s'
            logging.warning(msg % ', '.join(list(set(duplicateNames))))
        # if we succeeded then save current filename to self
        self.filename = filename
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)

##############################################
io.clearEvents('all')

###############################################

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=None,
    trialList=data.importConditions(
        'list_pool/AS/' + expInfo['listname'] +
        '.xlsx'),  ##'meta_list_pool/'+ expInfo['listname'] + '.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.keys():
        exec(paramName + '= thisTrial.' + paramName)

import socket
host = "192.168.1.2"  # set to IP address of target computer
if channel == 1:
    port = 13021
Пример #27
0
if key_resp_2.keys in ['', [], None]:  # No response was made
    key_resp_2.keys = None
# store data for thisExp (ExperimentHandler)
thisExp.addData('key_resp_2.keys', key_resp_2.keys)
if key_resp_2.keys != None:  # we had a response
    thisExp.addData('key_resp_2.rt', key_resp_2.rt)
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_2 = data.TrialHandler(nReps=1,
                             method='random',
                             extraInfo=expInfo,
                             originPath=None,
                             trialList=data.importConditions(u'trial.xlsx'),
                             seed=None,
                             name='trials_2')
thisExp.addLoop(trials_2)  # add the loop to the experiment
thisTrial_2 = trials_2.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisTrial_2.rgb)
if thisTrial_2 != None:
    for paramName in thisTrial_2.keys():
        exec(paramName + '= thisTrial_2.' + paramName)

for thisTrial_2 in trials_2:
    currentLoop = trials_2
    # abbreviate parameter names if possible (e.g. rgb = thisTrial_2.rgb)
    if thisTrial_2 != None:
        for paramName in thisTrial_2.keys():
Пример #28
0
        win.flip()

# -------Ending Routine "wait_for_scanner"-------
for thisComponent in wait_for_scannerComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# set interal clock time for when scanner is triggered
scannerTriggerOnset = globalClock.getTime()
thisExp.addData('scannerTriggerOnset', scannerTriggerOnset)
# the Routine "wait_for_scanner" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

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

for thisStroop_block_condition_order in stroop_block_condition_order:
    currentLoop = stroop_block_condition_order
    # abbreviate parameter names if possible (e.g. rgb = thisStroop_block_condition_order.rgb)
    if thisStroop_block_condition_order != None:
        for paramName in thisStroop_block_condition_order:
            exec('{} = thisStroop_block_condition_order[paramName]'.format(paramName))
    
Пример #29
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)

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=None,
                           trialList=data.importConditions(u'MM_onsets.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)
RTclock = core.Clock()
max_rt = 1

##### Wait for scanner trigger key #####
event.clearEvents(eventType='keyboard')
Пример #30
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 "intoPrepare"-------
for thisComponent in intoPrepareComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "intoPrepare" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

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

for thisMain_loop in main_loop:
    currentLoop = main_loop
    # abbreviate parameter names if possible (e.g. rgb = thisMain_loop.rgb)
    if thisMain_loop != None:
        for paramName in thisMain_loop.keys():
            exec(paramName + '= thisMain_loop.' + paramName)
    
Пример #31
0
expInfo['expName'] = expName


# Experiment handler
thisExp = data.ExperimentHandler(name=expName, version='',
        extraInfo=expInfo, runtimeInfo=None,
	originPath=None,
	savePickle=False, 
	saveWideText=False) #prevent the experiment handler to write expe data upon termination (and overwriting our files)
	

#--------------------------------------
# Load trial files 
#---------------------------------------
# read from csv file
trialList = data.importConditions(TRIALS_FILE, returnFieldNames=False)
trials = data.TrialHandler(trialList, nReps=1, method='sequential', extraInfo=expInfo)
trials.data.addDataType('respKey')
trials.data.addDataType('respTime')
trials.data.addDataType('stimOnset')
trials.data.addDataType('maskOnset')
trials.data.addDataType('imOnset')
trials.data.addDataType('imStop')
trials.data.addDataType('scale1')
trials.data.addDataType('RTscale1')
trials.data.addDataType('scale2')
trials.data.addDataType('RTscale2')
trials.data.addDataType('scale3')
trials.data.addDataType('RTscale3')

#----------------
Пример #32
0
for thisComponent in instrComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        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)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #33
0
# Initialize components for Routine "end"
endClock = core.Clock()
ending = visual.TextStim(win=win, ori=0, name='ending',
    text='Thanks for participating! Turn around and tell the experimenter that you are finished!',    font='Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    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
instr1 = data.TrialHandler(nReps=1, method='sequential', 
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions('instructions-p1.xlsx'),
    seed=None, name='instr1')
thisExp.addLoop(instr1)  # add the loop to the experiment
thisInstr1 = instr1.trialList[0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisInstr1.rgb)
if thisInstr1 != None:
    for paramName in thisInstr1.keys():
        exec(paramName + '= thisInstr1.' + paramName)

for thisInstr1 in instr1:
    currentLoop = instr1
    # abbreviate parameter names if possible (e.g. rgb = thisInstr1.rgb)
    if thisInstr1 != None:
        for paramName in thisInstr1.keys():
            exec(paramName + '= thisInstr1.' + paramName)
    
Пример #34
0
trialClock = core.Clock()
ISI = core.StaticPeriod(win=win, screenHz=expInfo['frameRate'], name='ISI')
text = visual.TextStim(win=win, ori=0, name='text',
    text=NumberString,    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace=u'rgb', opacity=1,
    depth=-1.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=5, method=u'random', 
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions('datasource.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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #35
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()
# the Routine "directions2" 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='random', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('conditions/practice.xlsx'),
    seed=0, 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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #36
0
    win.flip()

win.flip()  # get a blank screen
#core.wait(timeBuffering)  # buffering for participant

#---------------------------------------------------------------------------------------------------#
#-------------------------------------------FORMAL-TRIALS-------------------------------------------#
#---------------------------------------------------------------------------------------------------#

# set up handler to look after randomisation of conditions etc

Repeat = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions(conditionFile[0]),
                           seed=None,
                           name='Repeat')
thisExp.addLoop(Repeat)  # add the loop to the experiment
thisRepeat = Repeat.trialList[
    0]  # so we can initialise stimuli with some values

# abbreviate parameter names if possible (e.g. rgb = thisRepeat.rgb)
if thisRepeat != None:
    for paramName in thisRepeat:
        exec('{} = thisRepeat[paramName]'.format(paramName))

#--------------------#
#-------Repeat-------#
#--------------------#
Пример #37
0
        win.flip()

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

# the Routine "start" 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='random',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions(trialFile),
                           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:
        for paramName in thisTrial.keys():
win.flip()
while countDown.getTime() > 0:
    pass    
text2.setAutoDraw(False)
text1.setAutoDraw(True)
countDown.add(1)
win.flip()
while countDown.getTime() > 0:
    pass    
win.flip()
text1.setAutoDraw(False)

# set up handler to look after randomisation of conditions etc
Blocks = data.TrialHandler(nReps=1, method='sequential', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('VSTMBlockListv1.csv'),
    seed=None, name='Blocks')
thisExp.addLoop(Blocks)  # add the loop to the experiment
thisBlock = Blocks.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)

for thisBlock in Blocks:
    currentLoop = Blocks
    # abbreviate parameter names if possible (e.g. rgb = thisBlock.rgb)
    if thisBlock != None:
        for paramName in thisBlock.keys():
            exec(paramName + '= thisBlock.' + paramName)
            
Пример #39
0
# -------Ending Routine "instruct"-------
for thisComponent in instructComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
thisExp.addData('instrText.started', instrText.tStartRefresh)
thisExp.addData('instrText.stopped', instrText.tStopRefresh)
# the Routine "instruct" 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=5.0,
                           method='random',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('trialTypes.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:
        for paramName in thisTrial:
#msg variable just needs some value at start
msg=''
FeedbackMsg = visual.TextStim(win=win, ori=0, name='FeedbackMsg',
    text='default text',    font='Arial',
    units='norm', pos=[0, 0], height=0.1, wrapWidth=None,
    color='white', colorSpace='rgb', opacity=1,
    depth=-1.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=u'sequential', 
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions(INPUTFILE),#TrialListShort1#TrialList5Loads6Repeats
    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)



# PRESENT THE SCREEN TO WAIT FOR THE MRI TRIGGER
#vol = launchScan(win, MR_settings,  mode='Scan')

# ########################################################
# There should be WAITING FOR SCANNER trial here
Пример #41
0
text_2 = visual.TextStim(win=win, name='text_2',
    text='Movement',
    font='Arial',
    pos=(0, 0.4), height=0.1, wrapWidth=None, ori=0, 
    color='white', colorSpace='rgb', opacity=1, 
    languageStyle='LTR',
    depth=-4.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('trials.csv', selection='0:8'),
    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:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName))
    
Пример #42
0
    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
taskLoop = data.TrialHandler(nReps=1,
                             method='sequential',
                             extraInfo=expInfo,
                             originPath=-1,
                             trialList=data.importConditions('taskCond.xlsx'),
                             seed=None,
                             name='taskLoop')
thisExp.addLoop(taskLoop)  # add the loop to the experiment
thisTaskLoop = taskLoop.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisTaskLoop.rgb)
if thisTaskLoop != None:
    for paramName in thisTaskLoop:
        exec('{} = thisTaskLoop[paramName]'.format(paramName))

for thisTaskLoop in taskLoop:
    currentLoop = taskLoop
    # abbreviate parameter names if possible (e.g. rgb = thisTaskLoop.rgb)
    if thisTaskLoop != None:
        for paramName in thisTaskLoop:
Пример #43
0
    color=1.0, colorSpace=u'rgb', opacity=1,
    depth=-3.0)
Probe = visual.TextStim(win=win, ori=0, name='Probe',
    text='default text',    font=u'Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color=u'white', colorSpace=u'rgb', opacity=1,
    depth=-4.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=u'sequential', 
    extraInfo=expInfo, originPath=u'/Users/jason/Dropbox/SteffenerColumbia/Scripts/ExperimentalStimuli/Johannes/test1.psyexp',
    trialList=data.importConditions(u'../LetterSternberg/PartialTrial1.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.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #44
0
#inicializace promenne
msqFeedback = ''
textFeedBack = visual.TextStim(win=win, ori=0, name='textFeedBack',
    text='nonsense',    font='Arial',
    pos=[0, 0], height=0.1, wrapWidth=None,
    color='white', colorSpace='rgb', opacity=1,
    depth=-1.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=None,
    trialList=data.importConditions('AEDistRG2015.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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #45
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 "FirstAcquisition"-------
for thisComponent in FirstAcquisitionComponents:
    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=None,
    trialList=data.importConditions('run-designs/syntax_run1.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.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
Пример #46
0
# check responses
if fix_end.keys in ['', [], None]:  # No response was made
    fix_end.keys = None
thisExp.addData('fix_end.keys', fix_end.keys)
if fix_end.keys != None:  # we had a response
    thisExp.addData('fix_end.rt', fix_end.rt)
thisExp.addData('fix_end.started', fix_end.tStartRefresh)
thisExp.addData('fix_end.stopped', fix_end.tStopRefresh)
thisExp.nextEntry()

# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1,
                           method='sequential',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('text_cond.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:
        for paramName in thisTrial:
Пример #47
0
        stim_writer = csv.writer(csvfile, delimiter=',',
                                quotechar='|', quoting=csv.QUOTE_MINIMAL)
        if this_cicle==0:
            stim_writer.writerow(['stim','response'])
            for i in range(0,nStim):
                stim_writer.writerow([stims[i], response[i]])
        else:
            for i in range(0,nStim):
                stim_writer.writerow([stims[i], response[i]])
        
    print "generated %d targets in cicle %d"%(t,this_cicle+1)
    
# 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('stims/stim_file_%s_%s_%s_%s.csv' %(expName,expInfo['participant'],expInfo['session'], expInfo['date'])),
    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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #48
0
        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 "ISI"-------
for thisComponent in ISIComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)


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

for thisFacetrial in facetrials:
    currentLoop = facetrials
    # abbreviate parameter names if possible (e.g. rgb = thisFacetrial.rgb)
    if thisFacetrial != None:
        for paramName in thisFacetrial.keys():
            exec(paramName + '= thisFacetrial.' + paramName)
    
for thisComponent in instrPracticeComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# check responses
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()

# set up handler to look after randomisation of conditions etc
practiceTrials = data.TrialHandler(nReps=1.0, method='random', 
    extraInfo=expInfo, originPath=u'/Users/patrickbissett/OneDrive/Poldrack/TrainedInhibition/PsychoPy/IntegratingDifferentCode3-5-15.psyexp',
    trialList=data.importConditions(u'Trialtypes4New.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)
    if thisPracticeTrial != None:
        for paramName in thisPracticeTrial.keys():
            exec(paramName + '= thisPracticeTrial.' + paramName)
    
Пример #50
0
        win.flip()

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

# the Routine "ins" 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='random',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('word.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:
        for paramName in thisTrial:
Пример #51
0
myMouse = event.Mouse(win = myWin)
finalPositions={}
markerPositions={}

def makeRevEdgeGauss(width, center, size=512):
        edge = np.ones(size*3, float)#3x to achieve edge-padding
        centerLocation = int(size+center*size)
        edge[centerLocation:]=0
        gauss = filters.makeGauss(x=np.linspace(-1.0,1.0,size), mean=0, sd=width)/np.sqrt(2*np.pi*width**2)
        smthEdge = np.convolve(edge, gauss,'same')
        smthEdge = (smthEdge[size:size*2]-smthEdge.min())/(smthEdge.max()-smthEdge.min())#just take the middle section
        smthEdge.shape=(1,size)
        return np.tile(smthEdge,(size,1))*2-1

#Setting for Trial Handler
stimList = data.importConditions('MOAConflictConds.xlsx')
trials = data.TrialHandler(trialList=stimList, nReps=repeats, extraInfo=info)
trials.data.addDataType('LumEdge')
trials.data.addDataType('Marker')
#trials.data.addDataType('Condition')

#Create stimuli
if info['Flip']=='n':
    lum = colorFunctions.makeEdgeGauss(width=info['Blur'],center=0.5, size=512)*info['Edge Contrast Lum']
    lmlms= colorFunctions.makeEdgeGauss(width=info['Blur'],center=0.5, size=512)*info['Edge Contrast LM']
    slms= colorFunctions.makeEdgeGauss(width=info['Blur'],center=(0.5+info['Gap']), size=512)*info['Edge Contrast S']
    lm= colorFunctions.makeEdgeGauss(width=info['Blur'],center=(0.5+info['Gap']), size=512)*info['Edge Contrast LM']
    s= colorFunctions.makeEdgeGauss(width=info['Blur'],center=(0.5+info['Gap']), size=512)*info['Edge Contrast S']

if info['Flip']=='y':
    lum = makeRevEdgeGauss(width=info['Blur'],center=0.5, size=512)*info['Edge Contrast Lum']
Пример #52
0
                             color=[0.5, 0.5, 0.5],
                             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=None,
                           trialList=data.importConditions('sublim.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:
        for paramName in thisTrial.keys():
if start.keys in ['', [], None]:  # No response was made
   start.keys=None
# store data for thisExp (ExperimentHandler)
thisExp.addData('start.keys',start.keys)
if start.keys != None:  # we had a response
    thisExp.addData('start.rt', start.rt)
thisExp.nextEntry()
# the Routine "instruct" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

#########start of task1########

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

for thisTask1 in task1:
    currentLoop = task1
    # abbreviate parameter names if possible (e.g. rgb = thisTask1.rgb)
    if thisTask1 != None:
        for paramName in thisTask1.keys():
            exec(paramName + '= thisTask1.' + paramName)
    
Пример #54
0
    def loadFromXML(self, filename):
        """Loads an xml file and parses the builder Experiment from it
        """
        self._doc.parse(filename)
        root = self._doc.getroot()

        # some error checking on the version (and report that this isn't valid
        # .psyexp)?
        filenameBase = os.path.basename(filename)
        if root.tag != "PsychoPy2experiment":
            logging.error('%s is not a valid .psyexp file, "%s"' %
                          (filenameBase, root.tag))
            # the current exp is already vaporized at this point, oops
            return
        self.psychopyVersion = root.get('version')
        versionf = float(self.psychopyVersion.rsplit('.', 1)[0])
        if versionf < 1.63:
            msg = 'note: v%s was used to create %s ("%s")'
            vals = (self.psychopyVersion, filenameBase, root.tag)
            logging.warning(msg % vals)

        # Parse document nodes
        # first make sure we're empty
        self.flow = Flow(exp=self)  # every exp has exactly one flow
        self.routines = {}
        self.namespace = NameSpace(self)  # start fresh
        modifiedNames = []
        duplicateNames = []

        # fetch exp settings
        settingsNode = root.find('Settings')
        for child in settingsNode:
            self._getXMLparam(params=self.settings.params,
                              paramNode=child,
                              componentNode=settingsNode)
        # name should be saved as a settings parameter (only from 1.74.00)
        if self.settings.params['expName'].val in ['', None, 'None']:
            shortName = os.path.splitext(filenameBase)[0]
            self.setExpName(shortName)
        # fetch routines
        routinesNode = root.find('Routines')
        allCompons = getAllComponents(self.prefsBuilder['componentsFolders'],
                                      fetchIcons=False)
        # get each routine node from the list of routines
        for routineNode in routinesNode:
            routineGoodName = self.namespace.makeValid(routineNode.get('name'))
            if routineGoodName != routineNode.get('name'):
                modifiedNames.append(routineNode.get('name'))
            self.namespace.user.append(routineGoodName)
            routine = Routine(name=routineGoodName, exp=self)
            # self._getXMLparam(params=routine.params, paramNode=routineNode)
            self.routines[routineNode.get('name')] = routine
            for componentNode in routineNode:

                componentType = componentNode.tag
                if componentType in allCompons:
                    # create an actual component of that type
                    component = allCompons[componentType](
                        name=componentNode.get('name'),
                        parentName=routineNode.get('name'),
                        exp=self)
                else:
                    # create UnknownComponent instead
                    component = allCompons['UnknownComponent'](
                        name=componentNode.get('name'),
                        parentName=routineNode.get('name'),
                        exp=self)
                # check for components that were absent in older versions of
                # the builder and change the default behavior
                # (currently only the new behavior of choices for RatingScale,
                # HS, November 2012)
                # HS's modification superceded Jan 2014, removing several
                # RatingScale options
                if componentType == 'RatingScaleComponent':
                    if (componentNode.get('choiceLabelsAboveLine')
                            or componentNode.get('lowAnchorText')
                            or componentNode.get('highAnchorText')):
                        pass
                    # if not componentNode.get('choiceLabelsAboveLine'):
                    #    # this rating scale was created using older version
                    #    component.params['choiceLabelsAboveLine'].val=True
                # populate the component with its various params
                for paramNode in componentNode:
                    self._getXMLparam(params=component.params,
                                      paramNode=paramNode,
                                      componentNode=componentNode)
                compGoodName = self.namespace.makeValid(
                    componentNode.get('name'))
                if compGoodName != componentNode.get('name'):
                    modifiedNames.append(componentNode.get('name'))
                self.namespace.add(compGoodName)
                component.params['name'].val = compGoodName
                routine.append(component)
        # for each component that uses a Static for updates, we need to set
        # that
        for thisRoutine in list(self.routines.values()):
            for thisComp in thisRoutine:
                for thisParamName in thisComp.params:
                    thisParam = thisComp.params[thisParamName]
                    if thisParamName == 'advancedParams':
                        continue  # advanced isn't a normal param
                    elif thisParam.updates and "during:" in thisParam.updates:
                        # remove the part that says 'during'
                        updates = thisParam.updates.split(': ')[1]
                        routine, static = updates.split('.')
                        if routine not in self.routines:
                            msg = ("%s was set to update during %s Static "
                                   "Component, but that component no longer "
                                   "exists")
                            logging.warning(msg % (thisParamName, static))
                        else:
                            self.routines[routine].getComponentFromName(
                                static).addComponentUpdate(
                                    thisRoutine.params['name'],
                                    thisComp.params['name'], thisParamName)
        # fetch flow settings
        flowNode = root.find('Flow')
        loops = {}
        for elementNode in flowNode:
            if elementNode.tag == "LoopInitiator":
                loopType = elementNode.get('loopType')
                loopName = self.namespace.makeValid(elementNode.get('name'))
                if loopName != elementNode.get('name'):
                    modifiedNames.append(elementNode.get('name'))
                self.namespace.add(loopName)
                loop = eval('%s(exp=self,name="%s")' % (loopType, loopName))
                loops[loopName] = loop
                for paramNode in elementNode:
                    self._getXMLparam(paramNode=paramNode, params=loop.params)
                    # for conditions convert string rep to list of dicts
                    if paramNode.get('name') == 'conditions':
                        param = loop.params['conditions']
                        # e.g. param.val=[{'ori':0},{'ori':3}]
                        try:
                            param.val = eval('%s' % (param.val))
                        except SyntaxError:
                            # This can occur if Python2.7 conditions string
                            # contained long ints (e.g. 8L) and these can't be
                            # parsed by Py3. But allow the file to carry on
                            # loading and the conditions will still be loaded
                            # from the xlsx file
                            pass
                # get condition names from within conditionsFile, if any:
                try:
                    # psychophysicsstaircase demo has no such param
                    conditionsFile = loop.params['conditionsFile'].val
                except Exception:
                    conditionsFile = None
                if conditionsFile in ['None', '']:
                    conditionsFile = None
                if conditionsFile:
                    try:
                        trialList, fieldNames = data.importConditions(
                            conditionsFile, returnFieldNames=True)
                        for fname in fieldNames:
                            if fname != self.namespace.makeValid(fname):
                                duplicateNames.append(fname)
                            else:
                                self.namespace.add(fname)
                    except Exception:
                        pass  # couldn't load the conditions file for now
                self.flow.append(LoopInitiator(loop=loops[loopName]))
            elif elementNode.tag == "LoopTerminator":
                self.flow.append(
                    LoopTerminator(loop=loops[elementNode.get('name')]))
            elif elementNode.tag == "Routine":
                if elementNode.get('name') in self.routines:
                    self.flow.append(self.routines[elementNode.get('name')])
                else:
                    logging.error("A Routine called '{}' was on the Flow but "
                                  "could not be found (failed rename?). You "
                                  "may need to re-insert it".format(
                                      elementNode.get('name')))
                    logging.flush()

        if modifiedNames:
            msg = 'duplicate variable name(s) changed in loadFromXML: %s\n'
            logging.warning(msg % ', '.join(list(set(modifiedNames))))
        if duplicateNames:
            msg = 'duplicate variable names: %s'
            logging.warning(msg % ', '.join(list(set(duplicateNames))))
        # if we succeeded then save current filename to self
        self.filename = filename
Пример #55
0
    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)
thisExp.addData('text.started', text.tStartRefresh)
thisExp.addData('text.stopped', text.tStopRefresh)
# 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=24, method='sequential', 
    extraInfo=expInfo, originPath=-1,
    trialList=data.importConditions('stimuli.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:
        for paramName in thisTrial:
            exec('{} = thisTrial[paramName]'.format(paramName))
    
Пример #56
0
                                  texRes=128,
                                  interpolate=True,
                                  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
Introduction_Loop = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=-1,
    trialList=data.importConditions('procedure\\Introduction_list.csv'),
    seed=None,
    name='Introduction_Loop')
thisExp.addLoop(Introduction_Loop)  # add the loop to the experiment
thisIntroduction_Loop = Introduction_Loop.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb = thisIntroduction_Loop.rgb)
if thisIntroduction_Loop != None:
    for paramName in thisIntroduction_Loop.keys():
        exec(paramName + '= thisIntroduction_Loop.' + paramName)

for thisIntroduction_Loop in Introduction_Loop:
    currentLoop = Introduction_Loop
    # abbreviate parameter names if possible (e.g. rgb = thisIntroduction_Loop.rgb)
    if thisIntroduction_Loop != None:
        for paramName in thisIntroduction_Loop.keys():
Пример #57
0
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)










# set up handler to look after randomisation of conditions etc
trials = data.TrialHandler(nReps=1, method='random', 
    extraInfo=expInfo, originPath=None,
    trialList=data.importConditions('mainTrials.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:
        for paramName in thisTrial.keys():
            exec(paramName + '= thisTrial.' + paramName)
    
Пример #58
0
def main():
    # Sets system time as the random seed
    np.random.seed(seed=None)

    # Prompt GUI for participant ID
    id = ask_for_id()

    # Set up window and how many frames image should be displayed depending on refresh rate of monitor
    window = visual.Window(color=bg_color,
                           monitor='monitor',
                           fullscr=full_screen)
    frame_rate = window.getActualFrameRate()

    # Display instructional messages for user
    instruction_msg = visual.TextStim(
        window,
        color=text_color,
        text=
        f"For each image, answer whether the building shown is damaged. Each image will be shown briefly.\n\nTo answer, please press {key_list[0]} for yes and {key_list[1]} for no.\n\nPress any key to continue."
    )
    instruction_msg.draw()
    window.flip()
    event.waitKeys()
    instruction_msg.text = f"For the first few images, you will hear a beep if you give the correct answer.\n\nPress any key to continue."
    instruction_msg.draw()
    window.flip()
    event.waitKeys()

    plus_horiz = visual.ShapeStim(window,
                                  units='pix',
                                  vertices=[[-20, 0], [20, 0]])
    plus_vert = visual.ShapeStim(window,
                                 units='pix',
                                 vertices=[[0, 20], [0, -20]])

    user_data = pd.DataFrame(columns=data_columns)
    img = visual.ImageStim(window, size=img_dims)

    # Setup staircase procedures using defined parameters
    conds = data.importConditions('demo_params.csv')
    staircases = []
    for cond in conds:
        staircases.append(
            data.QuestHandler(startVal=cond['startVal'],
                              startValSd=cond['startValSd'],
                              pThreshold=cond['pThreshold'],
                              nTrials=cond['nTrials'],
                              beta=cond['beta'],
                              delta=cond['delta'],
                              gamma=cond['gamma'],
                              minVal=cond['minVal'],
                              maxVal=cond['maxVal']))

    img_list = get_imgs(img_dir, damage_subdir, num_each, nodamage_subdir)
    print(f"{len(img_list)} images loaded.")

    key_list.append('escape')

    # Run through image list with participant
    rounds = 1
    while len(img_list) > 0:

        staircase = random.choice(staircases)
        curr_time = next(staircase)
        curr_time = float(format(curr_time, '.3f'))

        # Get and parse random image's information
        subdir, img_name = get_random_img(img_list)
        truth = 'y' if subdir == damage_subdir else 'n'
        img.setImage(img_dir + subdir + '/' + img_name)

        # Display the image for set number of frames
        frames_to_show = get_frames_to_show(curr_time, frame_rate)
        keypress = None
        start_time, end_time = time.time(), 0
        for _ in range(frames_to_show):
            img.draw()
            window.flip()

            keypress = event.getKeys(keyList=key_list)
            if 'escape' in keypress:
                instruction_msg.text = 'Experiment aborted. Quitting...'
                instruction_msg.draw()
                window.flip()
                core.wait(3.0)
                core.quit()
            if len(keypress) > 0:
                end_time = time.time()
                break

        plus_horiz.draw()
        plus_vert.draw()
        window.flip()

        # Track reaction time for user response
        if keypress is None or len(keypress) == 0:
            keypress = event.waitKeys(keyList=key_list)
            if 'escape' in keypress:
                instruction_msg.text = 'Experiment aborted. Quitting...'
                instruction_msg.draw()
                window.flip()
                core.wait(3.0)
                core.quit()
            end_time = time.time()
        reaction_time = float(format(end_time - start_time, '.3f'))

        # Log and process user's input as correct or incorrect
        answer = 'y' if keypress[0] == key_list[0] else 'n'
        event.clearEvents()
        if answer == truth:
            if rounds <= feedback_rounds:
                beep = sound.Sound('A', secs=0.25)
                beep.play()
            staircase.addResponse(1)
        else:
            staircase.addResponse(0)

        user_data.loc[len(user_data)] = ([
            img_name, answer, truth, curr_time, reaction_time
        ])
        rounds += 1

        if rounds == feedback_rounds + 1:
            instruction_msg.text = 'From now on, feedback will no longer be provided.'
            instruction_msg.draw()
            window.flip()
            core.wait(3.0)

    # Calculate the final presentation time from the average of the staircases
    avg = 0
    for staircase in staircases:
        avg += next(staircase)
    avg /= len(staircases)
    with open('demo_result.txt', 'w') as f:
        f.write(f"The final presentation time is {avg} seconds.\n")

    user_data['Correct'] = (
        user_data['Actual'] == user_data['Response']).astype(int)

    # Output individual participant data to .csv file
    if not os.path.exists(data_dir):
        os.makedirs(data_dir)
    user_data.to_csv(f"{data_dir}/data_{id}.csv")

    instruction_msg.text = "Test completed. Closing window..."
    instruction_msg.draw()
    window.flip()
    core.wait(3.0)

    core.quit()
Пример #59
0
    if continueRoutine:  # don't flip if this routine is over or we'll get a blank screen
        win.flip()

# -------Ending Routine "intro"-------
for thisComponent in introComponents:
    if hasattr(thisComponent, "setAutoDraw"):
        thisComponent.setAutoDraw(False)
# the Routine "intro" 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='random',
                           extraInfo=expInfo,
                           originPath=-1,
                           trialList=data.importConditions('questions.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.keys():
        exec(paramName + '= thisTrial.' + paramName)

for thisTrial in trials:
    currentLoop = trials
    # abbreviate parameter names if possible (e.g. rgb = thisTrial.rgb)
    if thisTrial != None:
        for paramName in thisTrial.keys():
Пример #60
0
# store data for thisExp (ExperimentHandler)
thisExp.addData('welcome_keypress.keys', welcome_keypress.keys)
if welcome_keypress.keys != None:  # we had a response
    thisExp.addData('welcome_keypress.rt', welcome_keypress.rt)
thisExp.nextEntry()
# the Routine "welcome" was not non-slip safe, so reset the non-slip timer
routineTimer.reset()

# set up handler to look after randomisation of conditions etc
practice_loop = data.TrialHandler(
    nReps=1,
    method='sequential',
    extraInfo=expInfo,
    originPath=
    u'/Users/Rivendell/Documents/UWA/Psychopy_workshop/Example experiment1/temp.psyexp',
    trialList=data.importConditions(u'practice_trials.xlsx'),
    seed=None,
    name='practice_loop')
thisExp.addLoop(practice_loop)  # add the loop to the experiment
thisPractice_loop = practice_loop.trialList[
    0]  # so we can initialise stimuli with some values
# abbreviate parameter names if possible (e.g. rgb=thisPractice_loop.rgb)
if thisPractice_loop != None:
    for paramName in thisPractice_loop.keys():
        exec(paramName + '= thisPractice_loop.' + paramName)

for thisPractice_loop in practice_loop:
    currentLoop = practice_loop
    # abbreviate parameter names if possible (e.g. rgb = thisPractice_loop.rgb)
    if thisPractice_loop != None:
        for paramName in thisPractice_loop.keys():