Example #1
0
 def writeRoutineStartCode(self,buff):
     if self.params['discard previous'].val:
         buff.writeIndented('%(name)s.clearEvents()\n' % self.params)
     active = self.params['active'].val.strip(')], ').lstrip('([, ')
     if not _valid_var_re.match(active):
         if not ',' in active:
             active += ','  # to turn an int into tuple
         active = '(' + active + ')'
     lines = ('%(name)s.active = ' + '%s  # tuple or list of int 0..7\n' % active +
              '%(name)s.setEnabled(%(name)s.active)\n')
     if self.params['lights'].val:
         lines += '%(name)s.setLights(%(name)s.active)\n'
     if self.params['store'].val != 'nothing' or self.params['storeCorrect'].val:
         lines += ("%(name)s.btns = []  # responses stored in .btns and .rt\n" +
               "%(name)s.rt = []\n")
     buff.writeIndentedLines(lines % self.params)
Example #2
0
 def writeRoutineStartCode(self, buff):
     if self.params['discard previous'].val:
         buff.writeIndented('%(name)s.clearEvents()\n' % self.params)
     active = self.params['active'].val.strip(')], ').lstrip('([, ')
     if not _valid_var_re.match(active):
         if not ',' in active:
             active += ','  # to turn an int into tuple
         active = '(' + active + ')'
     lines = ('%(name)s.active = ' +
              '%s  # tuple or list of int 0..7\n' % active +
              '%(name)s.setEnabled(%(name)s.active)\n')
     if self.params['lights'].val:
         lines += '%(name)s.setLights(%(name)s.active)\n'
     if self.params['store'].val != 'nothing' or self.params[
             'storeCorrect'].val:
         lines += (
             "%(name)s.btns = []  # responses stored in .btns and .rt\n" +
             "%(name)s.rt = []\n")
     buff.writeIndentedLines(lines % self.params)
Example #3
0
    def writeFrameCode(self, buff):
        """Write the code that will be called every frame
        """
        #some shortcuts
        store = self.params['store'].val
        storeCorr = self.params['storeCorrect'].val
        forceEnd = self.params['forceEndRoutine'].val
        allowedKeys = self.params['allowedKeys'].val.strip()

        buff.writeIndented("\n")
        buff.writeIndented("# *%s* updates\n" % (self.params['name']))
        self.writeStartTestCode(
            buff)  #writes an if statement to determine whether to draw etc
        buff.writeIndented("%(name)s.status = STARTED\n" % (self.params))
        allowedKeysIsVar = _valid_var_re.match(
            str(allowedKeys)) and not allowedKeys == 'None'
        if allowedKeysIsVar:
            # if it looks like a variable, check that the variable is suitable to eval at run-time
            buff.writeIndented(
                "# AllowedKeys looks like a variable named `%s`\n" %
                allowedKeys)
            buff.writeIndented("if not '%s' in locals():\n" % allowedKeys)
            buff.writeIndented(
                "    logging.error('AllowedKeys variable `%s` is not defined.')\n"
                % allowedKeys)
            buff.writeIndented("    core.quit()\n")
            buff.writeIndented(
                "if not type(%s) in [list, tuple, np.ndarray]:\n" %
                allowedKeys)
            buff.writeIndented("    if not isinstance(%s, basestring):\n" %
                               allowedKeys)
            buff.writeIndented(
                "        logging.error('AllowedKeys variable `%s` is not string- or list-like.')\n"
                % allowedKeys)
            buff.writeIndented("        core.quit()\n")
            buff.writeIndented("    elif not ',' in %s: %s = (%s,)\n" %
                               (allowedKeys, allowedKeys, allowedKeys))
            buff.writeIndented("    else:  %s = eval(%s)\n" %
                               (allowedKeys, allowedKeys))
            keyListStr = "keyList=list(%s)" % allowedKeys  # eval() at run time
        buff.writeIndented("# keyboard checking is just starting\n")
        if store != 'nothing':
            buff.writeIndented("%(name)s.clock.reset()  # now t=0\n" %
                               self.params)
        if self.params['discard previous'].val:
            buff.writeIndented("event.clearEvents(eventType='keyboard')\n")
        buff.setIndentLevel(-1, relative=True)  #to get out of the if statement
        #test for stop (only if there was some setting for duration or stop)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            self.writeStopTestCode(
                buff)  #writes an if statement to determine whether to draw etc
            buff.writeIndented("%(name)s.status = STOPPED\n" % (self.params))
            buff.setIndentLevel(-1,
                                relative=True)  #to get out of the if statement

        buff.writeIndented("if %(name)s.status == STARTED:\n" % (self.params))
        buff.setIndentLevel(1, relative=True)  #to get out of the if statement
        dedentAtEnd = 1  #keep track of how far to dedent later
        #do we need a list of keys? (variable case is already handled)
        if allowedKeys in [None, "none", "None", "", "[]", "()"]:
            keyListStr = ""
        elif not allowedKeysIsVar:
            try:
                keyList = eval(allowedKeys)
            except:
                raise CodeGenerationException(self.params["name"],
                                              "Allowed keys list is invalid.")
            if type(
                    keyList
            ) == tuple:  #this means the user typed "left","right" not ["left","right"]
                keyList = list(keyList)
            elif isinstance(keyList, basestring):  #a single string/key
                keyList = [keyList]
            keyListStr = "keyList=%s" % (repr(keyList))
        #check for keypresses
        buff.writeIndented("theseKeys = event.getKeys(%s)\n" % (keyListStr))
        if self.exp.settings.params['Enable Escape'].val:
            buff.writeIndentedLines('\n# check for quit:')
            buff.writeIndented('if "escape" in theseKeys:\n')
            buff.writeIndented('    endExpNow = True\n')

        #how do we store it?
        if store != 'nothing' or forceEnd:
            #we are going to store something
            buff.writeIndented(
                "if len(theseKeys) > 0:  # at least one key was pressed\n")
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1  #indent by 1

        if store == 'first key':  #then see if a key has already been pressed
            buff.writeIndented(
                "if %(name)s.keys == []:  # then this was the first keypress\n"
                % (self.params))
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1  #indent by 1
            buff.writeIndented(
                "%(name)s.keys = theseKeys[0]  # just the first key pressed\n"
                % (self.params))
            buff.writeIndented("%(name)s.rt = %(name)s.clock.getTime()\n" %
                               (self.params))
        elif store == 'last key':
            buff.writeIndented(
                "%(name)s.keys = theseKeys[-1]  # just the last key pressed\n"
                % (self.params))
            buff.writeIndented("%(name)s.rt = %(name)s.clock.getTime()\n" %
                               (self.params))
        elif store == 'all keys':
            buff.writeIndented(
                "%(name)s.keys.extend(theseKeys)  # storing all keys\n" %
                (self.params))
            buff.writeIndented(
                "%(name)s.rt.append(%(name)s.clock.getTime())\n" %
                (self.params))

        if storeCorr:
            buff.writeIndented("# was this 'correct'?\n" % self.params)
            buff.writeIndented(
                "if (%(name)s.keys == str(%(correctAns)s)) or (%(name)s.keys == %(correctAns)s):\n"
                % (self.params))
            buff.writeIndented("    %(name)s.corr = 1\n" % (self.params))
            buff.writeIndented("else:\n")
            buff.writeIndented("    %(name)s.corr = 0\n" % (self.params))

        if forceEnd == True:
            buff.writeIndented("# a response ends the routine\n" % self.params)
            buff.writeIndented("continueRoutine = False\n")

        buff.setIndentLevel(-(dedentAtEnd), relative=True)
Example #4
0
    def writeFrameCode(self,buff):
        """Write the code that will be called every frame.
        """
        #some shortcuts
        store = self.params['store'].val
        storeCorr = self.params['storeCorrect'].val
        forceEnd = self.params['forceEndRoutine'].val
        useBoxTimer = self.params['useBoxTimer'].val

        #check whether we need to test for allowed keys (or just take all)
        allowedKeys = self.params['allowedKeys'].val.strip()
        allowedKeysIsVar = _valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None'
        if allowedKeysIsVar: #only insert this code if we think allowed keys is a variable
            # if it looks like a variable, check that the variable is suitable to eval at run-time
            buff.writeIndented("# AllowedKeys looks like a variable named `%s`\n" % allowedKeys)
            buff.writeIndented("if not '%s' in locals():\n" % allowedKeys)
            buff.writeIndented("    logging.error('AllowedKeys variable `%s` is not defined.')\n" % allowedKeys)
            buff.writeIndented("    core.quit()\n")
            buff.writeIndented("if not type(%s) in [list, tuple, np.ndarray]:\n" % allowedKeys)
            buff.writeIndented("    if not isinstance(%s, basestring):\n" % allowedKeys)
            buff.writeIndented("        logging.error('AllowedKeys variable `%s` is not string- or list-like.')\n" % allowedKeys)
            buff.writeIndented("        core.quit()\n")
            buff.writeIndented("    elif not ',' in %s: %s = (%s,)\n" % (allowedKeys, allowedKeys, allowedKeys))
            buff.writeIndented("    else:  %s = eval(%s)\n" % (allowedKeys, allowedKeys))
            keyListStr = "keyList=list(%s)" % allowedKeys  # eval() at run time
        #now create the string that will loop-continue if
        if allowedKeys in [None, "none", "None", "", "[]", "()"]:
            keyCheckStr=""
        elif not allowedKeysIsVar:
            try:
                keyList = eval(allowedKeys)
            except:
                raise CodeGenerationException(self.params["name"], "Allowed keys list is invalid.")
            if type(keyList)==tuple: #this means the user typed "left","right" not ["left","right"]
                keyList=list(keyList)
            elif isinstance(keyList, basestring): #a single string/key
                keyList=[keyList]
            keyCheckStr= "%s" %(repr(keyList))

        # if just now starting on this frame:
        buff.writeIndented("# *%(name)s* updates\n" % self.params)
        #write start code
        self.writeStartTestCode(buff)  #writes an if statement to determine whether to start
        buff.writeIndented("%(name)s.status = STARTED\n" % self.params)
        buff.writeIndented("%(name)s.clock.reset()  # now t=0\n" % self.params)
        if self.params['discard previous'].val:
            buff.writeIndented("# clear %(name)s responses (in a loop - the Cedrus own function doesn't work well)\n" % self.params)
            buff.writeIndented("%(name)s.poll_for_response()\n" % self.params)
            buff.writeIndented("while len(%(name)s.response_queue):\n" % self.params)
            buff.writeIndented("    %(name)s.clear_response_queue()\n" % self.params)
            buff.writeIndented("    %(name)s.poll_for_response() #often there are more resps waiting!\n" % self.params)
        if useBoxTimer:
            buff.writeIndented("%(name)s.reset_rt_timer() #set the response time clock to 0\n" % self.params)

        buff.setIndentLevel(-1, relative=True)  # to get out of the if statement
        #test for stop (only if there was some setting for duration or stop)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            self.writeStopTestCode(buff)  # writes an if statement to determine whether to draw etc
            buff.writeIndented("%(name)s.status = STOPPED\n" % self.params)
            buff.setIndentLevel(-1, True)

        buff.writeIndented("if %(name)s.status == STARTED:\n" % self.params)
        buff.setIndentLevel(1, relative=True)  #to get out of the if statement
        dedentAtEnd = 1  # keep track of how far to dedent later

        buff.writeIndented("theseKeys=[]\n" % self.params)
        buff.writeIndented("theseRTs=[]\n" % self.params)
        buff.writeIndented("# check for key presses\n" % self.params)
        buff.writeIndented("%(name)s.poll_for_response()\n" %self.params)
        buff.writeIndented("while len(%(name)s.response_queue):\n" %self.params)
        buff.writeIndented("    evt = %(name)s.get_next_response()\n" %self.params)
        if len(keyCheckStr):
            buff.writeIndented("    if evt['key'] not in %s:\n" %keyList)
            buff.writeIndented("        continue #we don't care about this key\n")
        buff.writeIndented("    if evt['pressed']: #could be extended to examine releases too?\n")
        buff.writeIndented("      theseKeys.append(evt['key'])\n")
        if useBoxTimer:
            buff.writeIndented("      theseRTs.append(evt['time']/1000.0) #NB psychopy times are in s not ms\n")
        else:
            buff.writeIndented("      theseRTs.append(%(name)s.clock.getTime())\n" %self.params)
        buff.writeIndented("    %(name)s.poll_for_response()\n" %self.params)
        buff.writeIndented("%(name)s.clear_response_queue() # make sure we don't process these evts again\n" % self.params)


        #how do we store it?
        if store!='nothing' or forceEnd:
            #we are going to store something
            buff.writeIndented("if len(theseKeys) > 0:  # at least one key was pressed\n")
            buff.setIndentLevel(1,True); dedentAtEnd+=1 #indent by 1

        if store=='first key':#then see if a key has already been pressed
            buff.writeIndented("if %(name)s.keys == []:  # then this was the first keypress\n" %(self.params))
            buff.setIndentLevel(1,True); dedentAtEnd+=1 #indent by 1
            buff.writeIndented("%(name)s.keys = theseKeys[0]  # just the first key pressed\n" %(self.params))
            buff.writeIndented("%(name)s.rt = theseRTs[0]\n" %(self.params))
        elif store=='last key':
            buff.writeIndented("%(name)s.keys = theseKeys[-1]  # just the last key pressed\n" %(self.params))
            buff.writeIndented("%(name)s.rt = theseRTs[-1]\n" %(self.params))
        elif store=='all keys':
            buff.writeIndented("%(name)s.keys.extend(theseKeys)  # storing all keys\n" %(self.params))
            buff.writeIndented("%(name)s.rt.extend(theseRTs)\n" %(self.params))
        else:
            print store, type(store), str(store)
        if storeCorr:
            buff.writeIndented("# was this 'correct'?\n" %self.params)
            buff.writeIndented("if (%(name)s.keys == str(%(correctAns)s)) or (%(name)s.keys == %(correctAns)s):\n" %(self.params))
            buff.writeIndented("    %(name)s.corr = 1\n" %(self.params))
            buff.writeIndented("else:\n")
            buff.writeIndented("    %(name)s.corr = 0\n" %(self.params))

        if forceEnd==True:
            buff.writeIndented("# a response ends the routine\n" %self.params)
            buff.writeIndented("continueRoutine = False\n")

        buff.setIndentLevel(-(dedentAtEnd), relative=True)
Example #5
0
    def writeFrameCode(self, buff):
        """Write the code that will be called every frame.
        """
        #some shortcuts
        store = self.params['store'].val
        storeCorr = self.params['storeCorrect'].val
        forceEnd = self.params['forceEndRoutine'].val
        useBoxTimer = self.params['useBoxTimer'].val

        #check whether we need to test for allowed keys (or just take all)
        allowedKeys = self.params['allowedKeys'].val.strip()
        allowedKeysIsVar = _valid_var_re.match(
            str(allowedKeys)) and not allowedKeys == 'None'
        if allowedKeysIsVar:  #only insert this code if we think allowed keys is a variable
            # if it looks like a variable, check that the variable is suitable to eval at run-time
            buff.writeIndented(
                "# AllowedKeys looks like a variable named `%s`\n" %
                allowedKeys)
            buff.writeIndented("if not '%s' in locals():\n" % allowedKeys)
            buff.writeIndented(
                "    logging.error('AllowedKeys variable `%s` is not defined.')\n"
                % allowedKeys)
            buff.writeIndented("    core.quit()\n")
            buff.writeIndented(
                "if not type(%s) in [list, tuple, np.ndarray]:\n" %
                allowedKeys)
            buff.writeIndented("    if not isinstance(%s, basestring):\n" %
                               allowedKeys)
            buff.writeIndented(
                "        logging.error('AllowedKeys variable `%s` is not string- or list-like.')\n"
                % allowedKeys)
            buff.writeIndented("        core.quit()\n")
            buff.writeIndented("    elif not ',' in %s: %s = (%s,)\n" %
                               (allowedKeys, allowedKeys, allowedKeys))
            buff.writeIndented("    else:  %s = eval(%s)\n" %
                               (allowedKeys, allowedKeys))
            keyListStr = "keyList=list(%s)" % allowedKeys  # eval() at run time
        #now create the string that will loop-continue if
        if allowedKeys in [None, "none", "None", "", "[]", "()"]:
            keyCheckStr = ""
        elif not allowedKeysIsVar:
            try:
                keyList = eval(allowedKeys)
            except:
                raise CodeGenerationException(self.params["name"],
                                              "Allowed keys list is invalid.")
            if type(
                    keyList
            ) == tuple:  #this means the user typed "left","right" not ["left","right"]
                keyList = list(keyList)
            elif isinstance(keyList, basestring):  #a single string/key
                keyList = [keyList]
            keyCheckStr = "%s" % (repr(keyList))

        # if just now starting on this frame:
        buff.writeIndented("# *%(name)s* updates\n" % self.params)
        #write start code
        self.writeStartTestCode(
            buff)  #writes an if statement to determine whether to start
        buff.writeIndented("%(name)s.status = STARTED\n" % self.params)
        buff.writeIndented("%(name)s.clock.reset()  # now t=0\n" % self.params)
        if self.params['discard previous'].val:
            buff.writeIndented(
                "# clear %(name)s responses (in a loop - the Cedrus own function doesn't work well)\n"
                % self.params)
            buff.writeIndented("%(name)s.poll_for_response()\n" % self.params)
            buff.writeIndented("while len(%(name)s.response_queue):\n" %
                               self.params)
            buff.writeIndented("    %(name)s.clear_response_queue()\n" %
                               self.params)
            buff.writeIndented(
                "    %(name)s.poll_for_response() #often there are more resps waiting!\n"
                % self.params)
        if useBoxTimer:
            buff.writeIndented(
                "%(name)s.reset_rt_timer() #set the response time clock to 0\n"
                % self.params)

        buff.setIndentLevel(-1,
                            relative=True)  # to get out of the if statement
        #test for stop (only if there was some setting for duration or stop)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            self.writeStopTestCode(
                buff
            )  # writes an if statement to determine whether to draw etc
            buff.writeIndented("%(name)s.status = STOPPED\n" % self.params)
            buff.setIndentLevel(-1, True)

        buff.writeIndented("if %(name)s.status == STARTED:\n" % self.params)
        buff.setIndentLevel(1, relative=True)  #to get out of the if statement
        dedentAtEnd = 1  # keep track of how far to dedent later

        buff.writeIndented("theseKeys=[]\n" % self.params)
        buff.writeIndented("theseRTs=[]\n" % self.params)
        buff.writeIndented("# check for key presses\n" % self.params)
        buff.writeIndented("%(name)s.poll_for_response()\n" % self.params)
        buff.writeIndented("while len(%(name)s.response_queue):\n" %
                           self.params)
        buff.writeIndented("    evt = %(name)s.get_next_response()\n" %
                           self.params)
        if len(keyCheckStr):
            buff.writeIndented("    if evt['key'] not in %s:\n" % keyList)
            buff.writeIndented(
                "        continue #we don't care about this key\n")
        buff.writeIndented(
            "    if evt['pressed']: #could be extended to examine releases too?\n"
        )
        buff.writeIndented("      theseKeys.append(evt['key'])\n")
        if useBoxTimer:
            buff.writeIndented(
                "      theseRTs.append(evt['time']/1000.0) #NB psychopy times are in s not ms\n"
            )
        else:
            buff.writeIndented(
                "      theseRTs.append(%(name)s.clock.getTime())\n" %
                self.params)
        buff.writeIndented("    %(name)s.poll_for_response()\n" % self.params)
        buff.writeIndented(
            "%(name)s.clear_response_queue() # make sure we don't process these evts again\n"
            % self.params)

        #how do we store it?
        if store != 'nothing' or forceEnd:
            #we are going to store something
            buff.writeIndented(
                "if len(theseKeys) > 0:  # at least one key was pressed\n")
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1  #indent by 1

        if store == 'first key':  #then see if a key has already been pressed
            buff.writeIndented(
                "if %(name)s.keys == []:  # then this was the first keypress\n"
                % (self.params))
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1  #indent by 1
            buff.writeIndented(
                "%(name)s.keys = theseKeys[0]  # just the first key pressed\n"
                % (self.params))
            buff.writeIndented("%(name)s.rt = theseRTs[0]\n" % (self.params))
        elif store == 'last key':
            buff.writeIndented(
                "%(name)s.keys = theseKeys[-1]  # just the last key pressed\n"
                % (self.params))
            buff.writeIndented("%(name)s.rt = theseRTs[-1]\n" % (self.params))
        elif store == 'all keys':
            buff.writeIndented(
                "%(name)s.keys.extend(theseKeys)  # storing all keys\n" %
                (self.params))
            buff.writeIndented("%(name)s.rt.extend(theseRTs)\n" %
                               (self.params))
        else:
            print store, type(store), str(store)
        if storeCorr:
            buff.writeIndented("# was this 'correct'?\n" % self.params)
            buff.writeIndented(
                "if (%(name)s.keys == str(%(correctAns)s)) or (%(name)s.keys == %(correctAns)s):\n"
                % (self.params))
            buff.writeIndented("    %(name)s.corr = 1\n" % (self.params))
            buff.writeIndented("else:\n")
            buff.writeIndented("    %(name)s.corr = 0\n" % (self.params))

        if forceEnd == True:
            buff.writeIndented("# a response ends the routine\n" % self.params)
            buff.writeIndented("continueRoutine = False\n")

        buff.setIndentLevel(-(dedentAtEnd), relative=True)
Example #6
0
    def writeFrameCode(self,buff):
        """Write the code that will be called every frame
        """
        #some shortcuts
        store=self.params['store'].val
        storeCorr=self.params['storeCorrect'].val
        forceEnd=self.params['forceEndRoutine'].val
        allowedKeys = self.params['allowedKeys'].val.strip()

        buff.writeIndented("\n")
        buff.writeIndented("# *%s* updates\n" %(self.params['name']))
        self.writeStartTestCode(buff)#writes an if statement to determine whether to draw etc
        buff.writeIndented("%(name)s.status = STARTED\n" %(self.params))
        allowedKeysIsVar = _valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None'
        if allowedKeysIsVar:
            # if it looks like a variable, check that the variable is suitable to eval at run-time
            buff.writeIndented("# AllowedKeys looks like a variable named `%s`\n" % allowedKeys)
            buff.writeIndented("if not '%s' in locals():\n" % allowedKeys)
            buff.writeIndented("    logging.error('AllowedKeys variable `%s` is not defined.')\n" % allowedKeys)
            buff.writeIndented("    core.quit()\n")
            buff.writeIndented("if not type(%s) in [list, tuple, np.ndarray]:\n" % allowedKeys)
            buff.writeIndented("    if not isinstance(%s, basestring):\n" % allowedKeys)
            buff.writeIndented("        logging.error('AllowedKeys variable `%s` is not string- or list-like.')\n" % allowedKeys)
            buff.writeIndented("        core.quit()\n")
            buff.writeIndented("    elif not ',' in %s: %s = (%s,)\n" % (allowedKeys, allowedKeys, allowedKeys))
            buff.writeIndented("    else:  %s = eval(%s)\n" % (allowedKeys, allowedKeys))
            keyListStr = "keyList=list(%s)" % allowedKeys  # eval() at run time
        buff.writeIndented("# keyboard checking is just starting\n")
        if store != 'nothing':
            buff.writeIndented("%(name)s.clock.reset()  # now t=0\n" % self.params)
        if self.params['discard previous'].val:
            buff.writeIndented("event.clearEvents()\n")
        buff.setIndentLevel(-1, relative=True)#to get out of the if statement
        #test for stop (only if there was some setting for duration or stop)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            self.writeStopTestCode(buff)#writes an if statement to determine whether to draw etc
            buff.writeIndented("%(name)s.status = STOPPED\n" %(self.params))
            buff.setIndentLevel(-1, relative=True)#to get out of the if statement

        buff.writeIndented("if %(name)s.status == STARTED:\n" %(self.params))
        buff.setIndentLevel(1, relative=True)#to get out of the if statement
        dedentAtEnd=1#keep track of how far to dedent later
        #do we need a list of keys? (variable case is already handled)
        if allowedKeys in [None, "none", "None", "", "[]", "()"]:
            keyListStr=""
        elif not allowedKeysIsVar:
            try:
                keyList = eval(allowedKeys)
            except:
                raise CodeGenerationException(self.params["name"], "Allowed keys list is invalid.")
            if type(keyList)==tuple: #this means the user typed "left","right" not ["left","right"]
                keyList=list(keyList)
            elif isinstance(keyList, basestring): #a single string/key
                keyList=[keyList]
            keyListStr= "keyList=%s" %(repr(keyList))
        #check for keypresses
        buff.writeIndented("theseKeys = event.getKeys(%s)\n" %(keyListStr))

        #how do we store it?
        if store!='nothing' or forceEnd:
            #we are going to store something
            buff.writeIndented("if len(theseKeys) > 0:  # at least one key was pressed\n")
            buff.setIndentLevel(1,True); dedentAtEnd+=1 #indent by 1

        if store=='first key':#then see if a key has already been pressed
            buff.writeIndented("if %(name)s.keys == []:  # then this was the first keypress\n" %(self.params))
            buff.setIndentLevel(1,True); dedentAtEnd+=1 #indent by 1
            buff.writeIndented("%(name)s.keys = theseKeys[0]  # just the first key pressed\n" %(self.params))
            buff.writeIndented("%(name)s.rt = %(name)s.clock.getTime()\n" %(self.params))
        elif store=='last key':
            buff.writeIndented("%(name)s.keys = theseKeys[-1]  # just the last key pressed\n" %(self.params))
            buff.writeIndented("%(name)s.rt = %(name)s.clock.getTime()\n" %(self.params))
        elif store=='all keys':
            buff.writeIndented("%(name)s.keys.extend(theseKeys)  # storing all keys\n" %(self.params))
            buff.writeIndented("%(name)s.rt.append(%(name)s.clock.getTime())\n" %(self.params))

        if storeCorr:
            buff.writeIndented("# was this 'correct'?\n" %self.params)
            buff.writeIndented("if (%(name)s.keys == str(%(correctAns)s)) or (%(name)s.keys == %(correctAns)): %(name)s.corr = 1\n" %(self.params))
            buff.writeIndented("else: %(name)s.corr=0\n" %self.params)

        if forceEnd==True:
            buff.writeIndented("# a response ends the routine\n" %self.params)
            buff.writeIndented("continueRoutine = False\n")

        buff.setIndentLevel(-(dedentAtEnd), relative=True)
Example #7
0
    def writeFrameCode(self,buff):
        """Write the code that will be called every frame.
        """
        #some shortcuts
        store = self.params['store'].val
        storeCorr = self.params['storeCorrect'].val
        forceEnd = self.params['forceEndRoutine'].val
        useBoxTimer = self.params['useBoxTimer'].val

        #check whether we need to test for allowed keys (or just take all)
        allowedKeys = self.params['allowedKeys'].val.strip()
        allowedKeysIsVar = _valid_var_re.match(str(allowedKeys)) and not allowedKeys == 'None'
        if allowedKeysIsVar: #only insert this code if we think allowed keys is a variable
            # if it looks like a variable, check that the variable is suitable to eval at run-time
            buff.writeIndented("# AllowedKeys looks like a variable named `%s`\n" % allowedKeys)
            buff.writeIndented("if not '%s' in locals():\n" % allowedKeys)
            buff.writeIndented("    logging.error('AllowedKeys variable `%s` is not defined.')\n" % allowedKeys)
            buff.writeIndented("    core.quit()\n")
            buff.writeIndented("if not type(%s) in [list, tuple, np.ndarray]:\n" % allowedKeys)
            buff.writeIndented("    if not isinstance(%s, basestring):\n" % allowedKeys)
            buff.writeIndented("        logging.error('AllowedKeys variable `%s` is not string- or list-like.')\n" % allowedKeys)
            buff.writeIndented("        core.quit()\n")
            buff.writeIndented("    elif not ',' in %s: %s = (%s,)\n" % (allowedKeys, allowedKeys, allowedKeys))
            buff.writeIndented("    else:  %s = eval(%s)\n" % (allowedKeys, allowedKeys))
            keyListStr = "keyList=list(%s)" % allowedKeys  # eval() at run time
        #now create the string that will loop-continue if
        if allowedKeys in [None, "none", "None", "", "[]", "()"]:
            keyCheckStr=""
        elif not allowedKeysIsVar:
            try:
                keyList = eval(allowedKeys)
            except:
                raise CodeGenerationException(self.params["name"], "Allowed keys list is invalid.")
            if type(keyList)==tuple: #this means the user typed "left","right" not ["left","right"]
                keyList=list(keyList)
            elif isinstance(keyList, basestring): #a single string/key
                keyList=[keyList]
            keyCheckStr= "%s" %(repr(keyList))

        # if just now starting on this frame:
        buff.writeIndented("# *%(name)s* updates\n" % self.params)
        #write start code
        self.writeStartTestCode(buff)  #writes an if statement to determine whether to start
        lines = "%(name)s.status = STARTED\n"
        if self.params['discard previous'].val:
            buff.writeIndented("%(name)s.poll_for_response()\n" % self.params)
            buff.writeIndented("%(name)s.clear_response_queue()\n" % self.params)
        if useBoxTimer:
            buff.writeIndented("%(name)s.reset_rt_timer() #set the response time clock to 0\n" % self.params)

        buff.setIndentLevel(-1, relative=True)  # to get out of the if statement
        #test for stop (only if there was some setting for duration or stop)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            self.writeStopTestCode(buff)  # writes an if statement to determine whether to draw etc
            buff.writeIndented("%(name)s.status = STOPPED\n" % self.params)
            buff.setIndentLevel(-1, True)

        buff.writeIndented("if %(name)s.status == STARTED:\n" % self.params)
        buff.setIndentLevel(1, relative=True)  #to get out of the if statement
        dedentAtEnd = 1  # keep track of how far to dedent later

        lines="theseButtonsPressed=[]"
        lines="theseButtonsRTs=[]"
        lines += "# check for button presses\n"
        lines += "%(name)s.poll_for_response()\n" %self.params
        lines += "for evt in %(name)s.response_queue:\n" %self.params
        if len(keyCheckStr):
            lines += "    if evt['key'] not in %s:\n" %keyListStr
            lines += "        continue #we don't careabout this key\n" %keyListStr
        lines += "    if evt['pressed']: #could be extended to examine releases too?\n"
        lines += "      theseButtonsPressed.append(evt['key'])\n"
        if useBoxTimer:
            lines += "      theseButtonsRTs.append(evt['time'])\n"
        else:
            lines += "      theseButtonsRTs.append(%(name)sClock.getTime())\n" %self.params
        buff.writeIndented("%(name)s.clear_response_queue() #and clear those responses so we don't process them again\n" % self.params)
        buff.writeIndentedLines(lines % self.params)
        lines=""

        # store something?
        if store != 'nothing' or forceEnd:
            buff.writeIndented("if len(theseButtonsPressed):  # at least one button was pressed this frame\n" % self.params)
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1

        if store == 'first button':
            buff.writeIndented("if %(name)sBtns == []:  # True if the first\n" % self.params)
            buff.setIndentLevel(1, True)
            dedentAtEnd += 1
            buff.writeIndented("%(name)sBtns = theseButtonsPressed[0]  # just the first button\n" % self.params)
            buff.writeIndented("%(name)sRTs = theseButtonsRTs[0]\n" %(self.params))
        elif store == 'last button':
            buff.writeIndented("%(name)sBtns = theseButtonsPressed[-1]  # just the last button\n" % self.params)
            buff.writeIndented("%(name)sRTs = theseButtonsRTs[-1]\n" % self.params)
        elif store == 'all buttons':
            buff.writeIndented("%(name)sBtns.extend(theseButtonsPressed)  # all buttons\n" % self.params)
            buff.writeIndented("%(name)sRTs.extend(theseButtonsRTs)\n" % self.params)

        lines = ''
        if storeCorr:
            lines += ("# was this 'correct'?\n" +
                     "if %(name)sBtns == str(%(correctAns)s):\n" +
                     "    %(name)sCorr = 1\n" +
                     "else:\n    %(name)sCorr=0\n")
        if forceEnd:
            lines += ("# a response forces the end of the routine\n" +
                     "continueRoutine = False\n")
        buff.writeIndentedLines(lines % self.params)
        buff.setIndentLevel(-(dedentAtEnd), relative=True)