示例#1
0
 def __init__(
         self,
         exp,
         parentName,
         name='etRecord',
         startType='time (s)',
         startVal=0.0,
         stopType='duration (s)',
         stopVal=1.0,
         startEstim='',
         durationEstim='',
         #legacy
         save='final',
         configFile='myTracker.yaml'):
     BaseComponent.__init__(self,
                            exp,
                            parentName,
                            name=name,
                            startType=startType,
                            startVal=startVal,
                            stopType=stopType,
                            stopVal=stopVal,
                            startEstim=startEstim,
                            durationEstim=durationEstim)
     self.type = 'EyetrackerRecord'
     self.url = "https://www.psychopy.org/builder/components/eyetracker.html"
     self.exp.requirePsychopyLibs(['iohub', 'hardware'])
示例#2
0
    def __init__(
            self,
            exp,
            parentName,
            name='etRecord',
            startType='time (s)',
            startVal=0.0,
            stopType='duration (s)',
            stopVal=1.0,
            startEstim='',
            durationEstim='',
            actionType="Start and Stop",
            #legacy
            save='final',
            configFile='myTracker.yaml'):
        BaseComponent.__init__(self,
                               exp,
                               parentName,
                               name=name,
                               startType=startType,
                               startVal=startVal,
                               stopType=stopType,
                               stopVal=stopVal,
                               startEstim=startEstim,
                               durationEstim=durationEstim)
        self.type = 'EyetrackerRecord'
        self.url = "https://www.psychopy.org/builder/components/eyetracker.html"
        self.exp.requirePsychopyLibs(['iohub', 'hardware'])

        self.params['actionType'] = Param(
            actionType,
            valType='str',
            inputType='choice',
            categ='Basic',
            allowedVals=["Start and Stop", "Start Only", "Stop Only"],
            hint=_translate(
                "Should this component start and / or stop eye tracker recording?"
            ),
            label=_translate("Record Actions"))

        self.depends.append({
            "dependsOn": "actionType",  # must be param name
            "condition": "=='Start Only'",  # val to check for
            "param": "stop",  # param property to alter
            "true": "hide",  # what to do with param if condition is True
            "false": "show",  # permitted: hide, show, enable, disable
        })

        self.depends.append({
            "dependsOn": "actionType",  # must be param name
            "condition": "=='Stop Only'",  # val to check for
            "param": "start",  # param property to alter
            "true": "hide",  # what to do with param if condition is True
            "false": "show",  # permitted: hide, show, enable, disable
        })

        # TODO: Display actionType control after component name.
        #       Currently, adding params before start / stop time
        #       in .order has no effect
        self.order = self.order[:1] + ['actionType'] + self.order[1:]
示例#3
0
    def __init__(self,
                 exp,
                 parentName,
                 name='ISI',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=0.5,
                 startEstim='',
                 durationEstim=''):
        BaseComponent.__init__(self, exp, parentName, name=name)
        self.updatesList = []  # a list of dicts {compParams, fieldName}
        self.type = 'Static'
        self.url = "http://www.psychopy.org/builder/components/static.html"
        hnt = _translate(
            "Custom code to be run during the static period (after updates)")
        self.params['code'] = Param("",
                                    valType='code',
                                    hint=hnt,
                                    label=_localized['Custom code'])
        self.order = ['name']  # make name come first (others don't matter)

        hnt = _translate("How do you want to define your start point?")
        self.params['startType'] = Param(startType,
                                         valType='str',
                                         allowedVals=['time (s)', 'frame N'],
                                         hint=hnt)
        hnt = _translate("How do you want to define your end point?")
        _allow = ['duration (s)', 'duration (frames)', 'time (s)', 'frame N']
        self.params['stopType'] = Param(
            stopType,
            valType='str',
            allowedVals=_allow,  # copy not needed
            hint=hnt)
        hnt = _translate("When does the component start?")
        self.params['startVal'] = Param(startVal,
                                        valType='code',
                                        allowedTypes=[],
                                        hint=hnt)
        hnt = _translate("When does the component end? (blank is endless)")
        self.params['stopVal'] = Param(stopVal,
                                       valType='code',
                                       allowedTypes=[],
                                       updates='constant',
                                       allowedUpdates=[],
                                       hint=hnt)
        hnt = _translate("(Optional) expected start (s), purely for "
                         "representing in the timeline")
        self.params['startEstim'] = Param(startEstim,
                                          valType='code',
                                          allowedTypes=[],
                                          hint=hnt)
        hnt = _translate("(Optional) expected duration (s), purely for "
                         "representing in the timeline")
        self.params['durationEstim'] = Param(durationEstim,
                                             valType='code',
                                             allowedTypes=[],
                                             hint=hnt)
示例#4
0
    def writeRoutineEndCodeJS(self, buff):
        inits = getInitVals(self.params)
        inits['routine'] = self.parentName
        if inits['transcribeBackend'].val in allTranscribers:
            inits['transcribeBackend'].val = allTranscribers[self.params['transcribeBackend'].val]
        # Warn user if their transcriber won't work online
        if inits['transcribe'].val and inits['transcribeBackend'].val not in onlineTranscribers.values():
            default = list(onlineTranscribers.values())[0]
            alert(4605, strFields={"transcriber": inits['transcribeBackend'].val, "default": default})

        # Write base end routine code
        BaseComponent.writeRoutineEndCodeJS(self, buff)
        # Store recordings from this routine
        code = (
            "// stop the microphone (make the audio data ready for upload)\n"
            "await %(name)s.stop();\n"
            "// construct a filename for this recording\n"
            "thisFilename = 'recording_%(name)s_' + currentLoop.name + '_' + currentLoop.thisN\n"
            "// get the recording\n"
            "%(name)s.lastClip = await %(name)s.getRecording({\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "tag: thisFilename + '_' + util.MonotonicClock.getDateStr(),\n"
                "flush: false\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        code = (
            "});\n"
            "psychoJS.experiment.addData('%(name)s.clip', thisFilename);\n"
            "// start the asynchronous upload to the server\n"
            "%(name)s.lastClip.upload();\n"
        )
        buff.writeIndentedLines(code % inits)
        if self.params['transcribe'].val:
            code = (
                "// transcribe the recording\n"
                "const transcription = await %(name)s.lastClip.transcribe({\n"
            )
            buff.writeIndentedLines(code % inits)
            buff.setIndentLevel(1, relative=True)
            code = (
                    "languageCode: %(transcribeLang)s,\n"
                    "engine: sound.AudioClip.Engine.%(transcribeBackend)s,\n"
                    "wordList: %(transcribeWords)s\n"
            )
            buff.writeIndentedLines(code % inits)
            buff.setIndentLevel(-1, relative=True)
            code = (
                "});\n"
                "%(name)s.lastScript = transcription.transcript;\n"
                "%(name)s.lastConf = transcription.confidence;\n"
                "psychoJS.experiment.addData('%(name)s.transcript', %(name)s.lastScript);\n"
                "psychoJS.experiment.addData('%(name)s.confidence', %(name)s.lastConf);\n"
            )
            buff.writeIndentedLines(code % inits)
示例#5
0
 def writeRoutineEndCode(self, buff):
     inits = getInitVals(self.params)
     # Alter inits
     if len(self.exp.flow._loopList):
         inits['loop'] = self.exp.flow._loopList[-1].params['name']
         inits['filename'] = f"'recording_{inits['name']}_{inits['loop']}_%s.{inits['outputType']}' % {inits['loop']}.thisTrialN"
     else:
         inits['loop'] = "thisExp"
         inits['filename'] = f"'recording_{inits['name']}'"
     transcribe = inits['transcribe'].val
     if inits['transcribe'].val == False:
         inits['transcribeBackend'].val = None
     if inits['outputType'].val == 'default':
         inits['outputType'].val = 'wav'
     # Warn user if their transcriber won't work locally
     if inits['transcribe'].val:
         if  inits['transcribeBackend'].val in localTranscribers:
             inits['transcribeBackend'].val = localTranscribers[self.params['transcribeBackend'].val]
         else:
             default = list(localTranscribers.values())[0]
             alert(4610, strFields={"transcriber": inits['transcribeBackend'].val, "default": default})
     # Store recordings from this routine
     code = (
         "# tell mic to keep hold of current recording in %(name)s.clips and transcript (if applicable) in %(name)s.scripts\n"
         "# this will also update %(name)s.lastClip and %(name)s.lastScript\n"
         "%(name)s.stop()\n"
         "%(name)sClip, %(name)sScript = %(name)s.bank(\n"
     )
     buff.writeIndentedLines(code % inits)
     buff.setIndentLevel(1, relative=True)
     code = (
         "tag='%(loop)s', transcribe='%(transcribeBackend)s',\n"
     )
     buff.writeIndentedLines(code % inits)
     if transcribe:
         code = (
             "language=%(transcribeLang)s, expectedWords=%(transcribeWords)s\n"
         )
     else:
         code = (
             "config=None\n"
         )
     buff.writeIndentedLines(code % inits)
     buff.setIndentLevel(-1, relative=True)
     code = (
         ")\n"
         "%(loop)s.addData('%(name)s.clip', os.path.join(%(name)sRecFolder, %(filename)s))\n"
     )
     buff.writeIndentedLines(code % inits)
     if transcribe:
         code = (
             "%(loop)s.addData('%(name)s.script', %(name)sScript)\n"
         )
         buff.writeIndentedLines(code % inits)
     # Write base end routine code
     BaseComponent.writeRoutineEndCode(self, buff)
示例#6
0
 def writeRoutineEndCode(self, buff):
     inits = getInitVals(self.params)
     inits['routine'] = self.parentName
     # Store recordings from this routine
     code = (
         "%(name)s.bank('%(routine)s')\n"
     )
     buff.writeIndentedLines(code % inits)
     # Write base end routine code
     BaseComponent.writeRoutineEndCode(self, buff)
示例#7
0
 def __init__(self, exp, parentName, name='ISI',
              startType='time (s)', startVal=0.0,
              stopType='duration (s)', stopVal=0.5,
              startEstim='', durationEstim=''):
     BaseComponent.__init__(self, exp, parentName, name=name)
     self.updatesList = []  # a list of dicts {compParams, fieldName}
     self.type = 'Static'
     self.url = "https://www.psychopy.org/builder/components/static.html"
     hnt = _translate(
         "Custom code to be run during the static period (after updates)")
     self.params['code'] = Param("", valType='code', inputType="multi", categ='Custom',
                                 hint=hnt,
                                 label=_localized['Custom code'])
示例#8
0
    def __init__(self, exp, parentName, name='ISI',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=0.5,
                 startEstim='', durationEstim=''):
        BaseComponent.__init__(self, exp, parentName, name=name)
        self.updatesList = []  # a list of dicts {compParams, fieldName}
        self.type = 'Static'
        self.url = "http://www.psychopy.org/builder/components/static.html"
        hnt = _translate(
            "Custom code to be run during the static period (after updates)")
        self.params['code'] = Param("", valType='code',
                                    hint=hnt,
                                    label=_localized['Custom code'])
        self.order = ['name']  # make name come first (others don't matter)

        hnt = _translate("How do you want to define your start point?")
        self.params['startType'] = Param(startType, valType='str',
                                         allowedVals=['time (s)', 'frame N'],
                                         hint=hnt)
        hnt = _translate("How do you want to define your end point?")
        _allow = ['duration (s)', 'duration (frames)', 'time (s)', 'frame N']
        self.params['stopType'] = Param(stopType, valType='str',
                                        allowedVals=_allow,  # copy not needed
                                        hint=hnt)
        hnt = _translate("When does the component start?")
        self.params['startVal'] = Param(startVal, valType='code',
                                        allowedTypes=[],
                                        hint=hnt)
        hnt = _translate("When does the component end? (blank is endless)")
        self.params['stopVal'] = Param(stopVal, valType='code',
                                       allowedTypes=[],
                                       updates='constant', allowedUpdates=[],
                                       hint=hnt)
        hnt = _translate("(Optional) expected start (s), purely for "
                         "representing in the timeline")
        self.params['startEstim'] = Param(startEstim, valType='code',
                                          allowedTypes=[],
                                          hint=hnt)
        hnt = _translate("(Optional) expected duration (s), purely for "
                         "representing in the timeline")
        self.params['durationEstim'] = Param(durationEstim, valType='code',
                                             allowedTypes=[],
                                             hint=hnt)
示例#9
0
    def writeStartTestCode(self, buff):
        """This will be executed as the final component in the routine
        """
        buff.writeIndented("# *%s* period\n" % (self.params['name']))
        BaseComponent.writeStartTestCode(self, buff)

        if self.params['stopType'].val == 'time (s)':
            durationSecsStr = "%(stopVal)s-t" % (self.params)
        elif self.params['stopType'].val == 'duration (s)':
            durationSecsStr = "%(stopVal)s" % (self.params)
        elif self.params['stopType'].val == 'duration (frames)':
            durationSecsStr = "%(stopVal)s*frameDur" % (self.params)
        elif self.params['stopType'].val == 'frame N':
            durationSecsStr = "(%(stopVal)s-frameN)*frameDur" % (self.params)
        else:
            msg = ("Couldn't deduce end point for startType=%(startType)s, "
                   "stopType=%(stopType)s")
            raise Exception(msg % self.params)
        vals = (self.params['name'], durationSecsStr)
        buff.writeIndented("%s.start(%s)\n" % vals)
示例#10
0
    def writeStartTestCode(self, buff):
        """This will be executed as the final component in the routine
        """
        buff.writeIndented("# *%s* period\n" % (self.params['name']))
        BaseComponent.writeStartTestCode(self, buff)

        if self.params['stopType'].val == 'time (s)':
            durationSecsStr = "%(stopVal)s-t" % (self.params)
        elif self.params['stopType'].val == 'duration (s)':
            durationSecsStr = "%(stopVal)s" % (self.params)
        elif self.params['stopType'].val == 'duration (frames)':
            durationSecsStr = "%(stopVal)s*frameDur" % (self.params)
        elif self.params['stopType'].val == 'frame N':
            durationSecsStr = "(%(stopVal)s-frameN)*frameDur" % (self.params)
        else:
            msg = ("Couldn't deduce end point for startType=%(startType)s, "
                   "stopType=%(stopType)s")
            raise Exception(msg % self.params)
        vals = (self.params['name'], durationSecsStr)
        buff.writeIndented("%s.start(%s)\n" % vals)
示例#11
0
 def test_dollar_sign_syntax(self):
     # Define several "tykes" - values which are likely to cause confusion - along with whether or not they are valid syntax
     tykes = {
         "$hello $there": False,
         "$hello \\$there": False,
         "hello $there": False,
         "\\$hello there": True,
         "#$hello there": False,
         "$#hello there": True,
         "$hello #there": True,
         "$hello #$there": True,
         "$hello \"\\$there\"": True,
         "$hello \'\\$there\'": True,
     }
     # Make a component with a str parameter for each tyke
     tykeComponent = BaseComponent(None, None)
     for (i, val) in enumerate(tykes):
         tykeComponent.params.update({str(i): Param(val, "str")})
     for (i, val) in enumerate(tykes):
         # Check the validity of each tyke param against the expected value
         assert tykeComponent.params[str(i)].dollarSyntax()[0] == tykes[val]