Exemple #1
0
    def __init__(self, exp, parentName, name='code',
                 beginExp="", beginRoutine="", eachFrame="", endRoutine="",
                 endExperiment=""):
        super(CodeComponent, self).__init__(exp, parentName, name)

        self.type = 'Code'
        self.url = "http://www.psychopy.org/builder/components/code.html"
        # params
        # want a copy, else codeParamNames list gets mutated
        self.order = ['name', 'Begin Experiment', 'Begin Routine',
                      'Each Frame', 'End Routine', 'End Experiment']

        msg = _translate("Code at the start of the experiment (initialization"
                         "); right-click checks syntax")
        self.params['Begin Experiment'] = Param(
            beginExp, valType='extendedCode', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['Begin Experiment'])

        msg = _translate("Code to be run at the start of each repeat of the "
                         "Routine (e.g. each trial); "
                         "right-click checks syntax")
        self.params['Begin Routine'] = Param(
            beginRoutine, valType='extendedCode', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['Begin Routine'])

        msg = _translate("Code to be run on every video frame during for the"
                         " duration of this Routine; "
                         "right-click checks syntax")
        self.params['Each Frame'] = Param(
            eachFrame, valType='extendedCode', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['Each Frame'])

        msg = _translate("Code at the end of this repeat of the Routine (e.g."
                         " getting/storing responses); "
                         "right-click checks syntax")
        self.params['End Routine'] = Param(
            endRoutine, valType='extendedCode', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['End Routine'])

        msg = _translate("Code at the end of the entire experiment (e.g. "
                         "saving files, resetting computer); "
                         "right-click checks syntax")
        self.params['End Experiment'] = Param(
            endExperiment, valType='extendedCode', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['End Experiment'])

        # these inherited params are harmless but might as well trim:
        for p in ('startType', 'startVal', 'startEstim', 'stopVal',
                  'stopType', 'durationEstim'):
            del self.params[p]
Exemple #2
0
    def __init__(self, exp, parentName, name='sound_1', sound='A', volume=1,
                 startType='time (s)', startVal='0.0',
                 stopType='duration (s)', stopVal='1.0',
                 startEstim='', durationEstim=''):
        super(SoundComponent, self).__init__(
            exp, parentName, name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)
        self.type = 'Sound'
        self.url = "http://www.psychopy.org/builder/components/sound.html"
        self.exp.requirePsychopyLibs(['sound'])
        # params
        self.params['stopType'].allowedVals = ['duration (s)']
        self.params['stopType'].hint = _translate('The maximum duration of a'
                                                  ' sound in seconds')
        hnt = _translate("When does the component end? (blank to use the "
                         "duration of the media)")
        self.params['stopVal'].hint = hnt

        hnt = _translate("A sound can be a note name (e.g. A or Bf), a number"
                         " to specify Hz (e.g. 440) or a filename")
        self.params['sound'] = Param(
            sound, valType='str', allowedTypes=[], updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=hnt,
            label=_localized['sound'])
        _allowed = ['constant', 'set every repeat', 'set every frame']
        self.params['volume'] = Param(
            volume, valType='code', allowedTypes=[], updates='constant',
            allowedUpdates=_allowed[:],  # use a copy
            hint=_translate("The volume (in range 0 to 1)"),
            label=_localized["volume"])
Exemple #3
0
    def __init__(self, exp, parentName, name='mic_1',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0, startEstim='',
                 durationEstim='', stereo=False, channel=0):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Microphone'
        self.url = "http://www.psychopy.org/builder/components/microphone.html"
        self.exp.requirePsychopyLibs(['microphone'])

        # params
        msg = _translate(
            "Record two channels (stereo) or one (mono, smaller file)")
        self.params['stereo'] = Param(
            stereo, valType='bool',
            hint=msg,
            label=_localized['stereo'])

        self.params['stopType'].allowedVals = ['duration (s)']

        msg = _translate(
            'The duration of the recording in seconds; blank = 0 sec')
        self.params['stopType'].hint = msg

        msg = _translate("Enter a channel number. Default value is 0. If unsure, run 'sound.backend.get_input_devices()' to locate the system's selected device/channel.")

        self.params['channel'] = Param(channel, valType='int', hint=msg, label=_localized['channel'])
Exemple #4
0
    def __init__(self, exp, parentName, name='aperture', units='norm',
                 size=1, pos=(0, 0),
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim=''):
        # initialise main parameters
        super(ApertureComponent, self).__init__(
            exp, parentName, name=name, units=units,
            pos=pos, size=size,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Aperture'
        self.url = "http://www.psychopy.org/builder/components/aperture.html"
        # params:
        # NB make some adjustments on the params defined by _visual component
        self.order = ['name', 'size', 'pos']  # make sure this is at top

        msg = _translate(
            "How big is the aperture? (a single number for diameter)")
        self.params['size'].hint = msg
        # only localize hints and labels
        self.params['size'].label = _translate("Size")
        self.params['pos'].hint = _translate("Where is the aperture centred?")

        # inherited from _visual component but not needed
        del self.params['ori']
        del self.params['color']
        del self.params['colorSpace']
        del self.params['opacity']
Exemple #5
0
    def __init__(self, exp, parentName, name='mic_1',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0, startEstim='',
                 durationEstim='', stereo=False):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Microphone'
        self.url = "http://www.psychopy.org/builder/components/microphone.html"
        self.exp.requirePsychopyLibs(['microphone'])

        # params
        msg = _translate(
            "Record two channels (stereo) or one (mono, smaller file)")
        self.params['stereo'] = Param(
            stereo, valType='bool',
            hint=msg,
            label=_localized['stereo'])

        self.params['stopType'].allowedVals = ['duration (s)']

        msg = _translate(
            'The duration of the recording in seconds; blank = 0 sec')
        self.params['stopType'].hint = msg
Exemple #6
0
    def __init__(self, exp, parentName, name='movie', movie='',
                 units='from exp settings',
                 pos=(0, 0), size='', ori=0,
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim='',
                 forceEndRoutine=False, backend='moviepy',
                 noAudio=False):
        super(MovieComponent, self).__init__(
            exp, parentName, name=name, units=units,
            pos=pos, size=size, ori=ori,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Movie'
        self.url = "http://www.psychopy.org/builder/components/movie.html"
        # comes immediately after name and timing params
        self.order = ['forceEndRoutine']
        self.targets = ['PsychoPy', 'PsychoJS']

        # params
        self.params['stopVal'].hint = _translate(
            "When does the component end? (blank to use the duration of "
            "the media)")

        msg = _translate("A filename for the movie (including path)")
        self.params['movie'] = Param(
            movie, valType='str', allowedTypes=[],
            updates='constant', allowedUpdates=['constant', 'set every repeat'],
            hint=msg,
            label=_localized['movie'])

        msg = _translate("What underlying lib to use for loading movies")
        self.params['backend'] = Param(
            backend, valType='str',
            allowedVals=['moviepy', 'avbin', 'opencv'],
            hint=msg,
            label=_localized['backend'])

        # todo: msg = _translate(...)
        msg = _translate("Prevent the audio stream from being loaded/processed "
               "(moviepy and opencv only)")
        self.params["No audio"] = Param(
            noAudio, valType='bool',
            hint=msg,
            label=_localized['No audio'])

        msg = _translate("Should the end of the movie cause the end of "
                         "the routine (e.g. trial)?")
        self.params['forceEndRoutine'] = Param(
            forceEndRoutine, valType='bool', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['forceEndRoutine'])

        # these are normally added but we don't want them for a movie
        del self.params['color']
        del self.params['colorSpace']
Exemple #7
0
    def __init__(self, exp, parentName, name='buttonBox',
                 store='first key',
                 useTimer=True, deviceNumber=0, allowedKeys="",
                 getReleaseTime=False,  # not yet supported
                 forceEndRoutine=True, storeCorrect=False, correctAns="",
                 discardPrev=True,
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim='',):
        super(cedrusButtonBoxComponent, self).__init__(
            exp, parentName, name=name,
            allowedKeys=allowedKeys, store=store, discardPrev=discardPrev,
            forceEndRoutine=forceEndRoutine, storeCorrect=storeCorrect,
            correctAns=correctAns, startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'cedrusButtonBox'
        self.url = "http://www.psychopy.org/builder/components/cedrusButtonBox.html"

        self.exp.requirePsychopyLibs(['hardware'])

        self.params['correctAns'].hint = _translate(
            "What is the 'correct' response? NB, buttons are labelled 0 to "
            "6 on a 7-button box. Enter 'None' (no quotes) if withholding "
            "a response is correct. Might be helpful to add a correctAns "
            "column and use $correctAns to compare to the key press.")

        self.params['correctAns'].valType = 'code'

        self.params['allowedKeys'].hint = _translate(
            'Keys to be read (blank for any) or key numbers separated by '
            'commas')

        msg = _translate('Device number, if you have multiple devices which'
                         ' one do you want (0, 1, 2...)')
        self.params['deviceNumber'] = Param(
            deviceNumber, valType='code', allowedTypes=[],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['deviceNumber'], categ='Advanced')

        # self.params['getReleaseTime'] = Param(getReleaseTime,
        #    valType='bool', allowedVals=[True, False],
        #    updates='constant', allowedUpdates=[],
        #    hint="Wait for the key to be released and store the time
        #       that it was held down",
        #    label="Get release time")

        msg = _translate('According to Cedrus the response box timer has '
                         'a drift - use with caution!')
        self.params['useBoxTimer'] = Param(
            getReleaseTime, valType='bool', allowedVals=[True, False],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['useBoxTimer'], categ='Advanced')
Exemple #8
0
    def __init__(self, exp, parentName, name='p_port',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim='',
                 address=None, startData="1", stopData="0",
                 syncScreen=True):
        super(ParallelOutComponent, self).__init__(
            exp, parentName, name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'ParallelOut'
        self.url = "http://www.psychopy.org/builder/components/parallelout.html"
        self.categories = ['I/O']
        self.exp.requirePsychopyLibs(['parallel'])

        # params
        self.order = ['address', 'startData', 'stopData']

        # main parameters
        addressOptions = prefs.hardware['parallelPorts'] + [u'LabJack U3']
        if not address:
            address = addressOptions[0]

        msg = _translate("Parallel port to be used (you can change these "
                         "options in preferences>general)")
        self.params['address'] = Param(
            address, valType='str', allowedVals=addressOptions,
            hint=msg,
            label=_localized['address'])

        self.params['startData'] = Param(
            startData, valType='code', allowedTypes=[],
            hint=_translate("Data to be sent at 'start'"),
            label=_localized['startData'])

        self.params['stopData'] = Param(
            stopData, valType='code', allowedTypes=[],
            hint=_translate("Data to be sent at 'end'"),
            label=_localized['stopData'])

        msg = _translate("If the parallel port data relates to visual "
                         "stimuli then sync its pulse to the screen refresh")
        self.params['syncScreen'] = Param(
            syncScreen, valType='bool',
            allowedVals=[True, False],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['syncScreen'])
Exemple #9
0
 def __init__(self, exp, parentName, name=''):
     self.type = 'Unknown'
     self.exp = exp  # so we can access the experiment if necess
     self.parentName = parentName  # to access the routine too if needed
     self.params = {}
     self.depends = []
     _hint = _translate("Name of this component (alpha-numeric or _, "
                        "no spaces)")
     self.params['name'] = Param(name, valType='code',
                                 hint=_hint,
                                 label=_localized['name'])
     self.order = ['name']  # name first, then timing, then others
Exemple #10
0
    def __init__(self, exp, parentName, name='text',
                 # effectively just a display-value
                 text=_translate('Any text\n\nincluding line breaks'),
                 font='Arial', units='from exp settings',
                 color='white', colorSpace='rgb',
                 pos=(0, 0), letterHeight=0.1, ori=0,
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 flip='', startEstim='', durationEstim='', wrapWidth=''):
        super(TextComponent, self).__init__(exp, parentName, name=name,
                                            units=units,
                                            color=color,
                                            colorSpace=colorSpace,
                                            pos=pos,
                                            ori=ori,
                                            startType=startType,
                                            startVal=startVal,
                                            stopType=stopType,
                                            stopVal=stopVal,
                                            startEstim=startEstim,
                                            durationEstim=durationEstim)
        self.type = 'Text'
        self.url = "http://www.psychopy.org/builder/components/text.html"

        # params
        _allow3 = ['constant', 'set every repeat', 'set every frame']  # list
        self.params['text'] = Param(
            text, valType='str', allowedTypes=[],
            updates='constant', allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The text to be displayed"),
            label=_localized['text'])
        self.params['font'] = Param(
            font, valType='str', allowedTypes=[],
            updates='constant', allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The font name (e.g. Comic Sans)"),
            label=_localized['font'])
        del self.params['size']  # because you can't specify width for text
        self.params['letterHeight'] = Param(
            letterHeight, valType='code', allowedTypes=[],
            updates='constant', allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("Specifies the height of the letter (the width"
                            " is then determined by the font)"),
            label=_localized['letterHeight'])

        self.params['wrapWidth'] = Param(
            wrapWidth, valType='code', allowedTypes=[],
            updates='constant', allowedUpdates=['constant'],
            hint=_translate("How wide should the text get when it wraps? (in"
                            " the specified units)"),
            label=_localized['wrapWidth'])
        self.params['flip'] = Param(
            flip, valType='str', allowedTypes=[],
            updates='constant', allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("horiz = left-right reversed; vert = up-down"
                            " reversed; $var = variable"),
            label=_localized['flip'])
        for prm in ('ori', 'opacity', 'colorSpace', 'units', 'wrapWidth',
                    'flip'):
            self.params[prm].categ = 'Advanced'
Exemple #11
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)
Exemple #12
0
    def __init__(self, exp, parentName,
                 name='var1', startExpValue = '',
                 startRoutineValue='',
                 startFrameValue=''):

        super(VariableComponent, self).__init__(
            exp, parentName, name)

        categories = ['Custom']
        self.type = 'Variable'
        self.url = "http://www.psychopy.org/builder/components/variable.html"
        self.order += ['startExpValue', 'saveStartExp', 'startRoutineValue', 'saveStartRoutine', 'startFrameValue',
                       'saveFrameValue', 'saveEndRoutine', 'saveEndExp']

        # set parameters
        hnt = _translate("The start value. A variable can be set to any value.")
        self.params['startExpValue'] = Param(
            startExpValue, valType='code', allowedTypes=[], updates='constant',
            hint=hnt,
            label=_localized['startExpValue'])
        hnt = _translate("Set the value for the beginning of each routine.")
        self.params['startRoutineValue'] = Param(
            startRoutineValue, valType='code', allowedTypes=[], updates='constant',
            hint=hnt,
            label=_localized['startRoutineValue'])
        hnt = _translate("Set the value for the beginning of every screen refresh.")
        self.params['startFrameValue'] = Param(
            startFrameValue, valType='code', allowedTypes=[],
            hint=hnt,
            label=_localized['startFrameValue'])
        # Save options
        hnt = _translate('Save the experiment start value in data file.')
        self.params['saveStartExp'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveStartExp'],
            categ='Save')
        hnt = _translate('Save the experiment end value in data file.')
        self.params['saveEndExp'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveEndExp'],
            categ='Save')
        hnt = _translate('Save the routine start value in data file.')
        self.params['saveStartRoutine'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveStartRoutine'],
            categ='Save')
        hnt = _translate('Save the routine end value in data file.')
        self.params['saveEndRoutine'] = Param(
            True, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveEndRoutine'],
            categ='Save')
        hnt = _translate('Save choice of frame value in data file.')
        self.params['saveFrameValue'] = Param(
            'never', valType='str',
            allowedVals=['first', 'last', 'all', 'never'],
            updates='constant',
            hint=hnt,
            label=_localized['saveFrameValue'],
            categ='Save')
Exemple #13
0
    def __init__(self, exp, parentName, name='mouse',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim='',
                 save='final', forceEndRoutineOnPress="any click",
                 timeRelativeTo='routine'):
        super(MouseComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Mouse'
        self.url = "http://www.psychopy.org/builder/components/mouse.html"
        self.exp.requirePsychopyLibs(['event'])
        self.categories = ['Inputs']

        self.order += [
            'forceEndRoutineOnPress',
            'saveMouseState', 'timeRelativeTo',
            'newClicksOnly', 'clickable', 'saveParamsClickable']

        # params
        msg = _translate(
            "How often should the mouse state (x,y,buttons) be stored? "
            "On every video frame, every click or just at the end of the "
            "Routine?")
        self.params['saveMouseState'] = Param(
            save, valType='str',
            allowedVals=['final', 'on click', 'every frame', 'never'],
            hint=msg,
            label=_localized['saveMouseState'])

        msg = _translate("Should a button press force the end of the routine"
                         " (e.g end the trial)?")
        if forceEndRoutineOnPress is True:
            forceEndRoutineOnPress = 'any click'
        elif forceEndRoutineOnPress is False:
            forceEndRoutineOnPress = 'never'
        self.params['forceEndRoutineOnPress'] = Param(
            forceEndRoutineOnPress, valType='str',
            allowedVals=['never', 'any click', 'valid click'],
            updates='constant',
            hint=msg,
            label=_localized['forceEndRoutineOnPress'])

        msg = _translate("What should the values of mouse.time should be "
                         "relative to?")
        self.params['timeRelativeTo'] = Param(
            timeRelativeTo, valType='str',
            allowedVals=['experiment', 'routine'],
            updates='constant',
            hint=msg,
            label=_localized['timeRelativeTo'])


        msg = _translate('If the mouse button is already down when we start'
                         'checking then wait for it to be released before'
                         'recording as a new click.'
                         )
        self.params['newClicksOnly'] = Param(
            True, valType='bool',
            updates='constant',
            hint=msg,
            label=_localized['New clicks only'])
        msg = _translate('A comma-separated list of your stimulus names that '
                         'can be "clicked" by the participant. '
                         'e.g. target, foil'
                         )
        self.params['clickable'] = Param(
            '', valType='code',
            updates='constant',
            hint=msg,
            label=_localized['Clickable stimuli'])

        msg = _translate('The params (e.g. name, text), for which you want '
                         'to store the current value, for the stimulus that was'
                         '"clicked" by the mouse. Make sure that all the '
                         'clickable objects have all these params.'
                         )
        self.params['saveParamsClickable'] = Param(
            'name,', valType='code',
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['Store params for clicked'])
Exemple #14
0
    def __init__(self,
                 exp,
                 parentName,
                 name='key_resp',
                 allowedKeys="'y','n','left','right','space'",
                 store='last key',
                 forceEndRoutine=True,
                 storeCorrect=False,
                 correctAns="",
                 discardPrev=True,
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal='',
                 startEstim='',
                 durationEstim='',
                 syncScreenRefresh=True):
        super(KeyboardComponent, self).__init__(exp,
                                                parentName,
                                                name,
                                                startType=startType,
                                                startVal=startVal,
                                                stopType=stopType,
                                                stopVal=stopVal,
                                                startEstim=startEstim,
                                                durationEstim=durationEstim)

        self.type = 'Keyboard'
        self.url = "https://www.psychopy.org/builder/components/keyboard.html"
        self.exp.requirePsychopyLibs(['gui'])

        # params

        # NB name and timing params always come 1st
        self.order += [
            'forceEndRoutine',  # Basic tab
            'allowedKeys',
            'store',
            'storeCorrect',
            'correctAns'  # Data tab
        ]

        msg = _translate(
            "A comma-separated list of keys (with quotes), such as "
            "'q','right','space','left'")
        self.params['allowedKeys'] = Param(
            allowedKeys,
            valType='list',
            inputType="single",
            allowedTypes=[],
            categ='Basic',
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=(msg),
            label=_localized['allowedKeys'])

        # hints say 'responses' not 'key presses' because the same hint is
        # also used with button boxes
        msg = _translate("Do you want to discard all responses occuring "
                         "before the onset of this component?")
        self.params['discard previous'] = Param(
            discardPrev,
            valType='bool',
            inputType="bool",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            hint=msg,
            label=_localized['discard previous'])

        msg = _translate("Choose which (if any) responses to store at the "
                         "end of a trial")
        self.params['store'] = Param(
            store,
            valType='str',
            inputType="choice",
            allowedTypes=[],
            categ='Data',
            allowedVals=['last key', 'first key', 'all keys', 'nothing'],
            updates='constant',
            hint=msg,
            label=_localized['store'])

        msg = _translate("Should a response force the end of the Routine "
                         "(e.g end the trial)?")
        self.params['forceEndRoutine'] = Param(
            forceEndRoutine,
            valType='bool',
            inputType="bool",
            allowedTypes=[],
            categ='Basic',
            updates='constant',
            hint=msg,
            label=_localized['forceEndRoutine'])

        msg = _translate("Do you want to save the response as "
                         "correct/incorrect?")
        self.params['storeCorrect'] = Param(storeCorrect,
                                            valType='bool',
                                            inputType="bool",
                                            allowedTypes=[],
                                            categ='Data',
                                            updates='constant',
                                            hint=msg,
                                            label=_localized['storeCorrect'])

        msg = _translate(
            "What is the 'correct' key? Might be helpful to add a "
            "correctAns column and use $correctAns to compare to the key "
            "press.")
        self.params['correctAns'] = Param(correctAns,
                                          valType='str',
                                          inputType="single",
                                          allowedTypes=[],
                                          categ='Data',
                                          updates='constant',
                                          hint=msg,
                                          label=_localized['correctAns'])

        msg = _translate(
            "A reaction time to a visual stimulus should be based on when "
            "the screen flipped")
        self.params['syncScreenRefresh'] = Param(
            syncScreenRefresh,
            valType='bool',
            inputType="bool",
            categ='Data',
            updates='constant',
            hint=msg,
            label=_localized['syncScreenRefresh'])
Exemple #15
0
Part of the PsychoPy library
Copyright (C) 2015 Jonathan Peirce
Distributed under the terms of the GNU General Public License (GPL).
"""

from __future__ import absolute_import, print_function
from builtins import super  # provides Py3-style super() using python-future

from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
import numpy as np

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'variable.png')
tooltip = _translate('Variable: create a new variable')

# only use _localized values for label values, nothing functional:
_localized = {'name': _translate('Name'),
              'startExpValue': _translate('Experiment start value'),
              'startRoutineValue': _translate('Routine start value'),
              'startFrameValue': _translate('Frame start value'),
              'saveStartExp': _translate('Save exp start value'),
              'saveStartRoutine': _translate('Save routine start value'),
              'saveFrameValue': _translate('Save frame value'),
              'saveEndRoutine': _translate('Save routine end value'),
              'saveEndExp': _translate('Save exp end value')}


class VariableComponent(BaseComponent):
    """An class for creating variables in builder."""
Exemple #16
0
    def __init__(self, parentName, exp, expName='', fullScr=True,
                 winSize=(1024, 768), screen=1, monitor='testMonitor',
                 showMouse=False, saveLogFile=True, showExpInfo=True,
                 expInfo="{'participant':'', 'session':'001'}",
                 units='use prefs', logging='exp',
                 color='$[0,0,0]', colorSpace='rgb', enableEscape=True,
                 blendMode='avg',
                 saveXLSXFile=False, saveCSVFile=False,
                 saveWideCSVFile=True, savePsydatFile=True,
                 savedDataFolder='',
                 useVersion='',
                 filename=None, exportHTML='on Sync'):
        self.type = 'Settings'
        self.exp = exp  # so we can access the experiment if necess
        self.exp.requirePsychopyLibs(['visual', 'gui'])
        self.parentName = parentName
        self.url = "http://www.psychopy.org/builder/settings.html"

        # if filename is the default value fetch the builder pref for the
        # folder instead
        if filename is None:
            filename = ("u'xxxx/%s_%s_%s' % (expInfo['participant'], expName,"
                        " expInfo['date'])")
        if filename.startswith("u'xxxx"):
            folder = self.exp.prefsBuilder['savedDataFolder'].strip()
            filename = filename.replace("xxxx", folder)

        # params
        self.params = {}
        self.order = ['expName', 'Show info dlg', 'Experiment info',
                      'Data filename',
                      'Save excel file', 'Save csv file',
                      'Save wide csv file', 'Save psydat file',
                      'Save log file', 'logging level',
                      'Monitor', 'Screen', 'Full-screen window',
                      'Window size (pixels)',
                      'color', 'colorSpace', 'Units', 'HTML path']
        # basic params
        self.params['expName'] = Param(
            expName, valType='str', allowedTypes=[],
            hint=_translate("Name of the entire experiment (taken by default"
                            " from the filename on save)"),
            label=_localized["expName"])
        self.params['Show info dlg'] = Param(
            showExpInfo, valType='bool', allowedTypes=[],
            hint=_translate("Start the experiment with a dialog to set info"
                            " (e.g.participant or condition)"),
            label=_localized["Show info dlg"], categ='Basic')
        self.params['Enable Escape'] = Param(
            enableEscape, valType='bool', allowedTypes=[],
            hint=_translate("Enable the <esc> key, to allow subjects to quit"
                            " / break out of the experiment"),
            label=_localized["Enable Escape"])
        self.params['Experiment info'] = Param(
            expInfo, valType='code', allowedTypes=[],
            hint=_translate("The info to present in a dialog box. Right-click"
                            " to check syntax and preview the dialog box."),
            label=_localized["Experiment info"], categ='Basic')
        self.params['Use version'] = Param(
            useVersion, valType='str',
            # search for options locally only by default, otherwise sluggish
            allowedVals=_versionFilter(versionOptions(), wx.__version__)
                        + ['']
                        + _versionFilter(availableVersions(), wx.__version__),
            hint=_translate("The version of PsychoPy to use when running "
                            "the experiment."),
            label=_localized["Use version"], categ='Basic')
        self.params['Force stereo'] = Param(
            enableEscape, valType='bool', allowedTypes=[],
            hint=_translate("Force audio to stereo (2-channel) output"),
            label=_localized["Force stereo"])

        # screen params
        self.params['Full-screen window'] = Param(
            fullScr, valType='bool', allowedTypes=[],
            hint=_translate("Run the experiment full-screen (recommended)"),
            label=_localized["Full-screen window"], categ='Screen')
        self.params['Window size (pixels)'] = Param(
            winSize, valType='code', allowedTypes=[],
            hint=_translate("Size of window (if not fullscreen)"),
            label=_localized["Window size (pixels)"], categ='Screen')
        self.params['Screen'] = Param(
            screen, valType='num', allowedTypes=[],
            hint=_translate("Which physical screen to run on (1 or 2)"),
            label=_localized["Screen"], categ='Screen')
        self.params['Monitor'] = Param(
            monitor, valType='str', allowedTypes=[],
            hint=_translate("Name of the monitor (from Monitor Center). Right"
                            "-click to go there, then copy & paste a monitor "
                            "name here."),
            label=_localized["Monitor"], categ="Screen")
        self.params['color'] = Param(
            color, valType='str', allowedTypes=[],
            hint=_translate("Color of the screen (e.g. black, $[1.0,1.0,1.0],"
                            " $variable. Right-click to bring up a "
                            "color-picker.)"),
            label=_localized["color"], categ='Screen')
        self.params['colorSpace'] = Param(
            colorSpace, valType='str',
            hint=_translate("Needed if color is defined numerically (see "
                            "PsychoPy documentation on color spaces)"),
            allowedVals=['rgb', 'dkl', 'lms', 'hsv', 'hex'],
            label=_localized["colorSpace"], categ="Screen")
        self.params['Units'] = Param(
            units, valType='str', allowedTypes=[],
            allowedVals=['use prefs', 'deg', 'pix', 'cm', 'norm', 'height',
                         'degFlatPos', 'degFlat'],
            hint=_translate("Units to use for window/stimulus coordinates "
                            "(e.g. cm, pix, deg)"),
            label=_localized["Units"], categ='Screen')
        self.params['blendMode'] = Param(
            blendMode, valType='str',
            allowedTypes=[], allowedVals=['add', 'avg'],
            hint=_translate("Should new stimuli be added or averaged with "
                            "the stimuli that have been drawn already"),
            label=_localized["blendMode"], categ='Screen')
        self.params['Show mouse'] = Param(
            showMouse, valType='bool', allowedTypes=[],
            hint=_translate("Should the mouse be visible on screen?"),
            label=_localized["Show mouse"], categ='Screen')

        # data params
        self.params['Data filename'] = Param(
            filename, valType='code', allowedTypes=[],
            hint=_translate("Code to create your custom file name base. Don"
                            "'t give a file extension - this will be added."),
            label=_localized["Data filename"], categ='Data')
        self.params['Save log file'] = Param(
            saveLogFile, valType='bool', allowedTypes=[],
            hint=_translate("Save a detailed log (more detailed than the "
                            "excel/csv files) of the entire experiment"),
            label=_localized["Save log file"], categ='Data')
        self.params['Save wide csv file'] = Param(
            saveWideCSVFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in comma-separated-value "
                            "(.csv) format for maximum portability"),
            label=_localized["Save wide csv file"], categ='Data')
        self.params['Save csv file'] = Param(
            saveCSVFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in comma-separated-value "
                            "(.csv) format for maximum portability"),
            label=_localized["Save csv file"], categ='Data')
        self.params['Save excel file'] = Param(
            saveXLSXFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in Excel (.xlsx) format"),
            label=_localized["Save excel file"], categ='Data')
        self.params['Save psydat file'] = Param(
            savePsydatFile, valType='bool', allowedVals=[True],
            hint=_translate("Save data from loops in psydat format. This is "
                            "useful for python programmers to generate "
                            "analysis scripts."),
            label=_localized["Save psydat file"], categ='Data')
        self.params['logging level'] = Param(
            logging, valType='code',
            allowedVals=['error', 'warning', 'data', 'exp', 'info', 'debug'],
            hint=_translate("How much output do you want in the log files? "
                            "('error' is fewest messages, 'debug' is most)"),
            label=_localized["logging level"], categ='Data')

        # HTML output params
        # self.params['OSF Project ID'] = ProjIDParam(
        #     '', valType='str', # automatically updates to allow choices
        #     hint=_translate("The ID of this project (e.g. 5bqpc)"),
        #     label="OSF Project ID", categ='Online')
        self.params['HTML path'] = Param(
            'html', valType='str', allowedTypes=[],
            hint=_translate("Place the HTML files will be saved locally "),
            label="Output path", categ='Online')
        self.params['JS libs'] = Param(
            'packaged', valType='str', allowedVals=['packaged'],
            hint=_translate("Should we package a copy of the JS libs or use"
                            "remote copies (http:/www.psychopy.org/js)?"),
            label="JS libs", categ='Online')
        self.params['Completed URL'] = Param(
            '', valType='str',
            hint=_translate("Where should participants be redirected after the experiment on completion\n"
                            " INSERT COMPLETION URL E.G.?"),
            label="Completed URL", categ='Online')
        self.params['Incomplete URL'] = Param(
            '', valType='str',
            hint=_translate("Where participants are redirected if they do not complete the task\n"
                            " INSERT INCOMPLETION URL E.G.?"),
            label="Incomplete URL", categ='Online')


        self.params['exportHTML'] = Param(
            exportHTML, valType='str',
            allowedVals=['on Save', 'on Sync', 'manually'],
            hint=_translate("When to export experiment to the HTML folder."),
            label=_localized["Export HTML"], categ='Online')
Exemple #17
0
# Part of the PsychoPy library
# Copyright (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy.experiment import valid_var_re
import re

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'joystick.png')
tooltip = _translate('Joystick: query joystick position and buttons')

# only use _localized values for label values, nothing functional:
_localized = {
    'saveJoystickState': _translate('Save joystick state'),
    'forceEndRoutineOnPress': _translate('End Routine on press'),
    'timeRelativeTo': _translate('Time relative to'),
    'Clickable stimuli': _translate('Clickable stimuli'),
    'Store params for clicked': _translate('Store params for clicked'),
    'deviceNumber': _translate('Device number'),
    'allowedButtons': _translate('Allowed Buttons')
}


class JoystickComponent(BaseComponent):
    """An event class for checking the joystick location and buttons
Exemple #18
0
    def __init__(self,
                 exp,
                 parentName,
                 name='env_grating',
                 carrier='sin',
                 mask='None',
                 sf=1.0,
                 interpolate='linear',
                 units='from exp settings',
                 color='$[1,1,1]',
                 colorSpace='rgb',
                 pos=(0, 0),
                 size=(0.5, 0.5),
                 ori=0,
                 phase=0.0,
                 texRes='128',
                 envelope='sin',
                 envsf=1.0,
                 envori=0.0,
                 envphase=0.0,
                 beat=False,
                 power=1.0,
                 contrast=0.5,
                 moddepth=1.0,
                 blendmode='avg',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim=''):
        super().__init__(exp,
                         parentName,
                         name=name,
                         units=units,
                         color=color,
                         colorSpace=colorSpace,
                         pos=pos,
                         size=size,
                         ori=ori,
                         startType=startType,
                         startVal=startVal,
                         stopType=stopType,
                         stopVal=stopVal,
                         startEstim=startEstim,
                         durationEstim=durationEstim)

        self.type = 'EnvGrating'
        self.url = "http://www.psychopy.org/builder/components/EnvelopeGrating.html"
        self.order = ['carrier', 'mask']

        # params

        self.params['ori'].categ = "Carrier"

        msg = _translate(
            "The (2D) texture of the background - can be sin, sqr,"
            " sinXsin... or a filename (including path)")
        self.params['carrier'] = Param(
            carrier,
            valType='file',
            inputType="file",
            allowedTypes=[],
            allowedVals=["sin", "sqr", "sinXsin"],
            categ="Carrier",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['carrier'])

        msg = _translate("An image to define the alpha mask (ie shape)- "
                         "gauss, circle... or a filename (including path)")
        self.params['mask'] = Param(
            mask,
            valType='file',
            inputType="file",
            allowedVals=["gauss", "circle"],
            allowedTypes=[],
            categ="Carrier",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['mask'])

        msg = _translate("Contrast of background carrier")
        self.params['contrast'] = Param(
            contrast,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Carrier",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['contrast'])

        msg = _translate(
            "Spatial frequency of background carrier repeats across the "
            "grating in 1 or 2 dimensions, e.g. 4 or [2,3]")
        self.params['sf'] = Param(
            sf,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Carrier",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['sf'])

        msg = _translate("Spatial positioning of the background carrier "
                         "(wraps in range 0-1.0)")
        self.params['phase'] = Param(
            phase,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Carrier",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['phase'])

        msg = _translate(
            "Resolution of the texture for standard ones such as sin, sqr "
            "etc. For most cases a value of 256 pixels will suffice")
        self.params['texture resolution'] = Param(
            texRes,
            valType='num',
            inputType="choice",
            allowedVals=['32', '64', '128', '256', '512'],
            categ="Carrier",
            updates='constant',
            allowedUpdates=[],
            hint=msg,
            label=_localized['texture resolution'])

        msg = _translate("How should the image be interpolated if/when "
                         "rescaled")
        self.params['interpolate'] = Param(interpolate,
                                           valType='str',
                                           inputType="choice",
                                           allowedVals=['linear', 'nearest'],
                                           categ="Carrier",
                                           updates='constant',
                                           allowedUpdates=[],
                                           hint=msg,
                                           label=_localized['interpolate'])

        msg = _translate("The (2D) texture of the envelope - can be sin, sqr,"
                         " sinXsin... or a filename (including path)")
        self.params['envelope'] = Param(
            envelope,
            valType='file',
            inputType="file",
            allowedVals=["sin", "sqr", "sinXsin"],
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envelope'])

        msg = _translate(
            "Spatial frequency of the modulation envelope repeats across the "
            "grating in 1 or 2 dimensions, e.g. 4 or [2,3]")
        self.params['envsf'] = Param(
            envsf,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envsf'])

        msg = _translate("Spatial positioning of the modulation envelope"
                         "(wraps in range 0-1.0)")
        self.params['envphase'] = Param(
            envphase,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envphase'])

        msg = _translate("Orientation of the modulation envelope"
                         "(wraps in range 0-360)")
        self.params['envori'] = Param(
            envori,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envori'])

        msg = _translate("Modulation depth of modulation envelope")
        self.params['moddepth'] = Param(
            moddepth,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['moddepth'])

        msg = _translate(
            "Power of modulation envelope. "
            "The modulator will be raised to this power "
            "according to the equation S=cC*(1+mM)^power, "
            "where C is the carrier and M is the modulator. "
            "and c and m are there respective contrast and modulation depth. "
            "Only works with AM envelopes (hence +1) in "
            "equation. Power is ignored if a beat is requested. "
            "This is used to obtain the square root of the modulator (power = 0.5) "
            "which is useful if combining two envelope gratings "
            "with different carriers and a 180 degree phase shift "
            "as the resulting combined signal will not "
            "have any reduction in local contrast at any point in the image. "
            "This is similar - but not identical to - the method used by "
            "Landy and Oruc, Vis Res 2002. "
            "Note overall contrast (apparent carrier contrast) will be altered."
        )
        self.params['power'] = Param(
            moddepth,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['power'])

        msg = _translate("Do you want a 'beat'? [beat = carrier*envelope, "
                         "no beat = carrier*(1+envelope), True/False, Y/N]")
        self.params['beat'] = Param(
            beat,
            valType='str',
            inputType="single",
            allowedTypes=[],
            categ="Envelope",
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['beat'])

        msg = _translate(
            "OpenGL Blendmode. Avg is most common mode"
            " in PsychoPy, add is useful if combining a beat with"
            " the carrier image or numpy array at point of display")
        self.params['blendmode'] = Param(
            blendmode,
            valType='str',
            inputType="choice",
            allowedVals=['avg', 'add'],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['blendmode'],
            categ="Appearance")

        del self.params['fillColor']
        del self.params['fillColorSpace']
        del self.params['borderColor']
        del self.params['borderColorSpace']
Exemple #19
0
"""
Part of the PsychoPy library
Copyright (C) 2018 Jonathan Peirce
Distributed under the terms of the GNU General Public License (GPL).
"""

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'sound.png')
tooltip = _translate('Sound: play recorded files or generated sounds',)

# only use _localized values for label values, nothing functional:
_localized = {'sound': _translate('Sound'),
              'volume': _translate('Volume'),
              'syncScreenRefresh': _translate('sync RT with screen')}


class SoundComponent(BaseComponent):
    """An event class for presenting sound stimuli"""
    categories = ['Stimuli']

    def __init__(self, exp, parentName, name='sound_1', sound='A', volume=1,
                 startType='time (s)', startVal='0.0',
                 stopType='duration (s)', stopVal='1.0',
                 startEstim='', durationEstim='',
Exemple #20
0
    def __init__(self, exp, parentName, name='mic',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0,
                 startEstim='', durationEstim='',
                 channels='auto', device="default",
                 sampleRate='Voice (16kHz)', maxSize=24000,
                 outputType='default', speakTimes=True, trimSilent=False,
                 transcribe=True, transcribeBackend="Google", transcribeLang="en-US", transcribeWords="",
                 #legacy
                 stereo=None, channel=None):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Microphone'
        self.url = "https://www.psychopy.org/builder/components/microphone.html"
        self.exp.requirePsychopyLibs(['sound'])

        self.order += []

        self.params['stopType'].allowedVals = ['duration (s)']
        msg = _translate(
            'The duration of the recording in seconds; blank = 0 sec')
        self.params['stopType'].hint = msg

        # params
        msg = _translate("What microphone device would you like the use to record? This will only affect local "
                         "experiments - online experiments ask the participant which mic to use.")
        self.params['device'] = Param(
            device, valType='str', inputType="choice", categ="Basic",
            allowedVals=list(devices),
            hint=msg,
            label=_translate("Device")
        )

        msg = _translate(
            "Record two channels (stereo) or one (mono, smaller file). Select 'auto' to use as many channels "
            "as the selected device allows.")
        if stereo is not None:
            # If using a legacy mic component, work out channels from old bool value of stereo
            channels = ['mono', 'stereo'][stereo]
        self.params['channels'] = Param(
            channels, valType='str', inputType="choice", categ='Hardware',
            allowedVals=['auto', 'mono', 'stereo'],
            hint=msg,
            label=_translate('Channels'))

        msg = _translate(
            "How many samples per second (Hz) to record at")
        self.params['sampleRate'] = Param(
            sampleRate, valType='num', inputType="choice", categ='Hardware',
            allowedVals=list(sampleRates),
            hint=msg,
            label=_translate('Sample Rate (Hz)'))

        msg = _translate(
            "To avoid excessively large output files, what is the biggest file size you are likely to expect?")
        self.params['maxSize'] = Param(
            maxSize, valType='num', inputType="single", categ='Hardware',
            hint=msg,
            label=_translate('Max Recording Size (kb)'))

        msg = _translate(
            "What file type should output audio files be saved as?")
        self.params['outputType'] = Param(
            outputType, valType='code', inputType='choice', categ='Data',
            allowedVals=["default"] + AUDIO_SUPPORTED_CODECS,
            hint=msg,
            label=_translate("Output File Type")
        )

        msg = _translate(
            "Tick this to save times when the participant starts and stops speaking")
        self.params['speakTimes'] = Param(
            speakTimes, valType='bool', inputType='bool', categ='Data',
            hint=msg,
            label=_translate("Speaking Start / Stop Times")
        )

        msg = _translate(
            "Trim periods of silence from the output file")
        self.params['trimSilent'] = Param(
            trimSilent, valType='bool', inputType='bool', categ='Data',
            hint=msg,
            label=_translate("Trim Silent")
        )

        # Transcription params
        self.order += [
            'transcribe',
            'transcribeBackend',
            'transcribeLang',
            'transcribeWords',
        ]
        self.params['transcribe'] = Param(
            transcribe, valType='bool', inputType='bool', categ='Transcription',
            hint=_translate("Whether to transcribe the audio recording and store the transcription"),
            label=_translate("Transcribe Audio")
        )

        for depParam in ['transcribeBackend', 'transcribeLang', 'transcribeWords']:
            self.depends.append({
                "dependsOn": "transcribe",
                "condition": "==True",
                "param": depParam,
                "true": "enable",  # what to do with param if condition is True
                "false": "disable",  # permitted: hide, show, enable, disable
            })

        self.params['transcribeBackend'] = Param(
            transcribeBackend, valType='code', inputType='choice', categ='Transcription',
            allowedVals=list(allTranscribers),
            hint=_translate("What transcription service to use to transcribe audio?"),
            label=_translate("Transcription Backend")
        )

        self.params['transcribeLang'] = Param(
            transcribeLang, valType='str', inputType='single', categ='Transcription',
            hint=_translate("What language you expect the recording to be spoken in, e.g. en-US for English"),
            label=_translate("Transcription Language")
        )

        self.params['transcribeWords'] = Param(
            transcribeWords, valType='list', inputType='single', categ='Transcription',
            hint=_translate("Set list of words to listen for - if blank will listen for all words in chosen language. \n\n"
                            "If using the built-in transcriber, you can set a minimum % confidence level using a colon "
                            "after the word, e.g. 'red:100', 'green:80'. Otherwise, default confidence level is 80%."),
            label=_translate("Expected Words")
        )
Exemple #21
0
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2021 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function
from builtins import super  # provides Py3-style super() using python-future

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate
from psychopy.localization import _localized as __localized
_localized = __localized.copy()

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'envelopegrating.png')
tooltip = _translate(
    'Envelope Grating: present cyclic textures including 2nd order envelope stimuli, prebuilt or from a '
    'file')

# only use _localized values for label values, nothing functional:
_localized.update({
    'carrier': _translate('Carrier texture'),
    'ori': _translate('Carrier Orientation'),
    'mask': _translate('Mask'),
    'sf': _translate('Carrier spatial frequency'),
    'phase': _translate('Carrier phase (in cycles)'),
    'contrast': _translate('Carrier contrast'),
    'texture resolution': _translate('Texture resolution'),
    'interpolate': _translate('Interpolate'),
    'envelope': _translate('Envelope texture'),
    'envsf': _translate('Envelope spatial frequency'),
    'envori': _translate('Envelope orientation'),
Exemple #22
0
class MicrophoneComponent(BaseComponent):
    """An event class for capturing short sound stimuli"""
    categories = ['Responses']
    targets = ['PsychoPy', 'PsychoJS']
    iconFile = Path(__file__).parent / 'microphone.png'
    tooltip = _translate('Microphone: basic sound capture (fixed onset & '
                         'duration), okay for spoken words')

    def __init__(self, exp, parentName, name='mic',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0,
                 startEstim='', durationEstim='',
                 channels='auto', device="default",
                 sampleRate='Voice (16kHz)', maxSize=24000,
                 outputType='default', speakTimes=True, trimSilent=False,
                 transcribe=True, transcribeBackend="Google", transcribeLang="en-US", transcribeWords="",
                 #legacy
                 stereo=None, channel=None):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Microphone'
        self.url = "https://www.psychopy.org/builder/components/microphone.html"
        self.exp.requirePsychopyLibs(['sound'])

        self.order += []

        self.params['stopType'].allowedVals = ['duration (s)']
        msg = _translate(
            'The duration of the recording in seconds; blank = 0 sec')
        self.params['stopType'].hint = msg

        # params
        msg = _translate("What microphone device would you like the use to record? This will only affect local "
                         "experiments - online experiments ask the participant which mic to use.")
        self.params['device'] = Param(
            device, valType='str', inputType="choice", categ="Basic",
            allowedVals=list(devices),
            hint=msg,
            label=_translate("Device")
        )

        msg = _translate(
            "Record two channels (stereo) or one (mono, smaller file). Select 'auto' to use as many channels "
            "as the selected device allows.")
        if stereo is not None:
            # If using a legacy mic component, work out channels from old bool value of stereo
            channels = ['mono', 'stereo'][stereo]
        self.params['channels'] = Param(
            channels, valType='str', inputType="choice", categ='Hardware',
            allowedVals=['auto', 'mono', 'stereo'],
            hint=msg,
            label=_translate('Channels'))

        msg = _translate(
            "How many samples per second (Hz) to record at")
        self.params['sampleRate'] = Param(
            sampleRate, valType='num', inputType="choice", categ='Hardware',
            allowedVals=list(sampleRates),
            hint=msg,
            label=_translate('Sample Rate (Hz)'))

        msg = _translate(
            "To avoid excessively large output files, what is the biggest file size you are likely to expect?")
        self.params['maxSize'] = Param(
            maxSize, valType='num', inputType="single", categ='Hardware',
            hint=msg,
            label=_translate('Max Recording Size (kb)'))

        msg = _translate(
            "What file type should output audio files be saved as?")
        self.params['outputType'] = Param(
            outputType, valType='code', inputType='choice', categ='Data',
            allowedVals=["default"] + AUDIO_SUPPORTED_CODECS,
            hint=msg,
            label=_translate("Output File Type")
        )

        msg = _translate(
            "Tick this to save times when the participant starts and stops speaking")
        self.params['speakTimes'] = Param(
            speakTimes, valType='bool', inputType='bool', categ='Data',
            hint=msg,
            label=_translate("Speaking Start / Stop Times")
        )

        msg = _translate(
            "Trim periods of silence from the output file")
        self.params['trimSilent'] = Param(
            trimSilent, valType='bool', inputType='bool', categ='Data',
            hint=msg,
            label=_translate("Trim Silent")
        )

        # Transcription params
        self.order += [
            'transcribe',
            'transcribeBackend',
            'transcribeLang',
            'transcribeWords',
        ]
        self.params['transcribe'] = Param(
            transcribe, valType='bool', inputType='bool', categ='Transcription',
            hint=_translate("Whether to transcribe the audio recording and store the transcription"),
            label=_translate("Transcribe Audio")
        )

        for depParam in ['transcribeBackend', 'transcribeLang', 'transcribeWords']:
            self.depends.append({
                "dependsOn": "transcribe",
                "condition": "==True",
                "param": depParam,
                "true": "enable",  # what to do with param if condition is True
                "false": "disable",  # permitted: hide, show, enable, disable
            })

        self.params['transcribeBackend'] = Param(
            transcribeBackend, valType='code', inputType='choice', categ='Transcription',
            allowedVals=list(allTranscribers),
            hint=_translate("What transcription service to use to transcribe audio?"),
            label=_translate("Transcription Backend")
        )

        self.params['transcribeLang'] = Param(
            transcribeLang, valType='str', inputType='single', categ='Transcription',
            hint=_translate("What language you expect the recording to be spoken in, e.g. en-US for English"),
            label=_translate("Transcription Language")
        )

        self.params['transcribeWords'] = Param(
            transcribeWords, valType='list', inputType='single', categ='Transcription',
            hint=_translate("Set list of words to listen for - if blank will listen for all words in chosen language. \n\n"
                            "If using the built-in transcriber, you can set a minimum % confidence level using a colon "
                            "after the word, e.g. 'red:100', 'green:80'. Otherwise, default confidence level is 80%."),
            label=_translate("Expected Words")
        )

    def writeStartCode(self, buff):
        inits = getInitVals(self.params)
        # Use filename with a suffix to store recordings
        code = (
            "# Make folder to store recordings from %(name)s\n"
            "%(name)sRecFolder = filename + '_%(name)s_recorded'\n"
            "if not os.path.isdir(%(name)sRecFolder):\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "os.mkdir(%(name)sRecFolder)\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)

    def writeStartCodeJS(self, buff):
        inits = getInitVals(self.params)
        code = (
            "// Define folder to store recordings from %(name)s"
            "%(name)sRecFolder = filename + '_%(name)s_recorded"
        )
        buff.writeIndentedLines(code % inits)

    def writeInitCode(self, buff):
        inits = getInitVals(self.params)
        # Substitute sample rate value for numeric equivalent
        inits['sampleRate'] = sampleRates[inits['sampleRate'].val]
        # Substitute channel value for numeric equivalent
        inits['channels'] = {'mono': 1, 'stereo': 2, 'auto': None}[self.params['channels'].val]
        # Substitute device name for device index
        device = devices[self.params['device'].val]
        if hasattr(device, "deviceIndex"):
            inits['device'] = device.deviceIndex
        else:
            inits['device'] = None
        # Create Microphone object and clips dict
        code = (
            "%(name)s = sound.microphone.Microphone(\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "device=%(device)s, channels=%(channels)s, \n"
                "sampleRateHz=%(sampleRate)s, maxRecordingSize=%(maxSize)s\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        code = (
            ")\n"
        )
        buff.writeIndentedLines(code % inits)

    def writeInitCodeJS(self, buff):
        inits = getInitVals(self.params)
        inits['sampleRate'] = sampleRates[inits['sampleRate'].val]
        # Alert user if non-default value is selected for device
        if inits['device'].val != 'default':
            alert(5055, strFields={'name': inits['name'].val})
        # Write code
        code = (
            "%(name)s = new sound.Microphone({\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "win : psychoJS.window, \n"
                "name:'%(name)s',\n"
                "sampleRateHz : %(sampleRate)s,\n"
                "channels : %(channels)s,\n"
                "maxRecordingSize : %(maxSize)s,\n"
                "loopback : true,\n"
                "policyWhenFull : 'ignore',\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        code = (
            "});\n"
        )
        buff.writeIndentedLines(code % inits)

    def writeFrameCode(self, buff):
        """Write the code that will be called every frame"""
        inits = getInitVals(self.params)
        inits['routine'] = self.parentName
        # Start the recording
        code = (
            "\n"
            "# %(name)s updates"
        )
        buff.writeIndentedLines(code % inits)
        self.writeStartTestCode(buff)
        code = (
                "# start recording with %(name)s\n"
                "%(name)s.start()\n"
                "%(name)s.status = STARTED\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        # Get clip each frame
        code = (
            "if %(name)s.status == STARTED:\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "# update recorded clip for %(name)s\n"
                "%(name)s.poll()\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        # Stop recording
        self.writeStopTestCode(buff)
        code = (
            "# stop recording with %(name)s\n"
            "%(name)s.stop()\n"
            "%(name)s.status = FINISHED\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-2, relative=True)

    def writeFrameCodeJS(self, buff):
        inits = getInitVals(self.params)
        inits['routine'] = self.parentName
        # Start the recording
        self.writeStartTestCodeJS(buff)
        code = (
                "await %(name)s.start();\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        code = (
            "}"
        )
        buff.writeIndentedLines(code % inits)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            # Stop the recording
            self.writeStopTestCodeJS(buff)
            code = (
                    "%(name)s.pause();\n"
            )
            buff.writeIndentedLines(code % inits)
            buff.setIndentLevel(-1, relative=True)
            code = (
                "}"
            )
            buff.writeIndentedLines(code % inits)

    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)

    def writeRoutineEndCodeJS(self, buff):
        inits = getInitVals(self.params)
        inits['routine'] = self.parentName
        if len(self.exp.flow._loopList):
            inits['loop'] = self.exp.flow._loopList[-1].params['name']
            inits['filename'] = f"'recording_{inits['name']}_{inits['loop']}_' + {inits['loop']}.thisN"
        else:
            inits['loop'] = ""
            inits['filename'] = f"'recording_{inits['name']}'"
        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"
            "// get the recording\n"
            "%(name)s.lastClip = await %(name)s.getRecording({\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "tag: %(filename)s,\n"
                "flush: false\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-1, relative=True)
        code = (
            "});\n"
            "psychoJS.experiment.addData('%(name)s.clip', %(filename)s);\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)

    def writeExperimentEndCode(self, buff):
        """Write the code that will be called at the end of
        an experiment (e.g. save log files or reset hardware)
        """
        inits = getInitVals(self.params)
        if len(self.exp.flow._loopList):
            currLoop = self.exp.flow._loopList[-1]  # last (outer-most) loop
        else:
            currLoop = self.exp._expHandler
        inits['loop'] = currLoop.params['name']
        if inits['outputType'].val == 'default':
            inits['outputType'].val = 'wav'
        # Save recording
        code = (
            "# save %(name)s recordings\n"
            "for tag in %(name)s.clips:"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                "for i, clip in enumerate(%(name)s.clips[tag]):\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(1, relative=True)
        code = (
                    "clip.save(os.path.join(%(name)sRecFolder, 'recording_%(name)s_%%s_%%s.%(outputType)s' %% (tag, i)))\n"
        )
        buff.writeIndentedLines(code % inits)
        buff.setIndentLevel(-2, relative=True)
Exemple #23
0
from __future__ import absolute_import, print_function
from builtins import super  # provides Py3-style super() using python-future

from os import path
from pathlib import Path

from psychopy.alerts import alert
from psychopy.experiment.components import BaseComponent, Param, getInitVals, _translate
from psychopy.sound.microphone import Microphone, _hasPTB
from psychopy.sound.audiodevice import sampleRateQualityLevels
from psychopy.sound.audioclip import AUDIO_SUPPORTED_CODECS
from psychopy.localization import _localized as __localized

_localized = __localized.copy()
_localized.update({'stereo': _translate('Stereo'),
                   'channel': _translate('Channel')})
from psychopy.tests import _vmTesting

if _hasPTB and not _vmTesting:
    devices = {d.deviceName: d for d in Microphone.getDevices()}
else:
    devices = {}
sampleRates = {r[1]: r[0] for r in sampleRateQualityLevels.values()}
devices['default'] = None

onlineTranscribers = {
    "Google": "GOOGLE"
}
localTranscribers = {
    "Google": "google",
Exemple #24
0
Distributed under the terms of the GNU General Public License (GPL).
"""

from __future__ import absolute_import, print_function
from builtins import super  # provides Py3-style super() using python-future

from os import path
from psychopy.experiment.components import BaseComponent, Param, getInitVals, _translate
from psychopy.sound._base import knownNoteNames
from psychopy.localization import _localized as __localized
_localized = __localized.copy()

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'sound.png')
tooltip = _translate('Sound: play recorded files or generated sounds',)

# only use _localized values for label values, nothing functional:
_localized.update({'sound': _translate('Sound'),
                   'volume': _translate('Volume'),
                   'syncScreenRefresh': _translate('Sync Start With Screen')})


class SoundComponent(BaseComponent):
    """An event class for presenting sound stimuli"""
    categories = ['Stimuli']

    def __init__(self, exp, parentName, name='sound_1', sound='A', volume=1,
                 startType='time (s)', startVal='0.0',
                 stopType='duration (s)', stopVal='1.0',
                 startEstim='', durationEstim='',
Exemple #25
0
# Copyright (C) 2015 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, \
    getInitVals, _translate
from psychopy.visual import slider

__author__ = 'Jon Peirce'

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'slider.png')
tooltip = _translate('Slider: A simple, flexible object for getting ratings')

# only use _localized values for label values, nothing functional:
_localized = {
    'categoryChoices': _translate('Category choices'),
    'labels': _translate('Labels'),
    'ticks': _translate('Ticks'),
    'size': _translate('Size'),
    'pos': _translate('Position [x,y]'),
    'forceEndRoutine': _translate('Force end of Routine'),
    'storeHistory': _translate('Store history'),
    'storeRating': _translate('Store rating'),
    'storeRatingTime': _translate('Store rating time')}

knownStyles = slider.Slider.knownStyles
Exemple #26
0
    fullPath = os.path.join(thisFolder, relPath)
    with open(fullPath, "r") as f:
        txt = f.read()
    return txt


# used when writing scripts and in namespace:
_numpyImports = ['sin', 'cos', 'tan', 'log', 'log10', 'pi', 'average',
                 'sqrt', 'std', 'deg2rad', 'rad2deg', 'linspace', 'asarray']
_numpyRandomImports = ['random', 'randint', 'normal', 'shuffle']

# this is not a standard component - it will appear on toolbar not in
# components panel

# only use _localized values for label values, nothing functional:
_localized = {'expName': _translate("Experiment name"),
              'Show info dlg':  _translate("Show info dialog"),
              'Enable Escape':  _translate("Enable Escape key"),
              'Experiment info':  _translate("Experiment info"),
              'Data filename':  _translate("Data filename"),
              'Full-screen window':  _translate("Full-screen window"),
              'Window size (pixels)':  _translate("Window size (pixels)"),
              'Screen': _translate('Screen'),
              'Monitor':  _translate("Monitor"),
              'color': _translate("Color"),
              'colorSpace':  _translate("Color space"),
              'Units':  _translate("Units"),
              'blendMode':   _translate("Blend mode"),
              'Show mouse':  _translate("Show mouse"),
              'Save log file':  _translate("Save log file"),
              'Save wide csv file':
Exemple #27
0
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from builtins import str
from builtins import range
from past.builtins import basestring
from os import path

from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy.experiment import CodeGenerationException, valid_var_re

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'keyboard.png')
tooltip = _translate('Keyboard: check and record keypresses')

# only use _localized values for label values, nothing functional:
_localized = {'allowedKeys': _translate('Allowed keys'),
              'discard previous': _translate('Discard previous'),
              'store': _translate('Store'),
              'forceEndRoutine': _translate('Force end of Routine'),
              'storeCorrect': _translate('Store correct'),
              'correctAns': _translate('Correct answer'),
              'syncScreenRefresh': _translate('sync RT with screen')}


class KeyboardComponent(BaseComponent):
    """An event class for checking the keyboard at given timepoints"""
    # an attribute of the class, determines the section in components panel
    categories = ['Responses']
Exemple #28
0
    def __init__(self, parentName, exp, expName='', fullScr=True,
                 winSize=(1024, 768), screen=1, monitor='testMonitor',
                 showMouse=False, saveLogFile=True, showExpInfo=True,
                 expInfo="{'participant':'', 'session':'001'}",
                 units='height', logging='exp',
                 color='$[0,0,0]', colorSpace='rgb', enableEscape=True,
                 blendMode='avg',
                 saveXLSXFile=False, saveCSVFile=False,
                 saveWideCSVFile=True, savePsydatFile=True,
                 savedDataFolder='',
                 useVersion='',
                 filename=None, exportHTML='on Sync'):
        self.type = 'Settings'
        self.exp = exp  # so we can access the experiment if necess
        self.exp.requirePsychopyLibs(['visual', 'gui'])
        self.parentName = parentName
        self.url = "http://www.psychopy.org/builder/settings.html"

        # if filename is the default value fetch the builder pref for the
        # folder instead
        if filename is None:
            filename = ("u'xxxx/%s_%s_%s' % (expInfo['participant'], expName,"
                        " expInfo['date'])")
        if filename.startswith("u'xxxx"):
            folder = self.exp.prefsBuilder['savedDataFolder'].strip()
            filename = filename.replace("xxxx", folder)

        # params
        self.params = {}
        self.order = ['expName', 'Show info dlg', 'Experiment info',
                      'Data filename',
                      'Save excel file', 'Save csv file',
                      'Save wide csv file', 'Save psydat file',
                      'Save log file', 'logging level',
                      'Monitor', 'Screen', 'Full-screen window',
                      'Window size (pixels)',
                      'color', 'colorSpace', 'Units', 'HTML path']
        # basic params
        self.params['expName'] = Param(
            expName, valType='str', allowedTypes=[],
            hint=_translate("Name of the entire experiment (taken by default"
                            " from the filename on save)"),
            label=_localized["expName"])
        self.params['Show info dlg'] = Param(
            showExpInfo, valType='bool', allowedTypes=[],
            hint=_translate("Start the experiment with a dialog to set info"
                            " (e.g.participant or condition)"),
            label=_localized["Show info dlg"], categ='Basic')
        self.params['Enable Escape'] = Param(
            enableEscape, valType='bool', allowedTypes=[],
            hint=_translate("Enable the <esc> key, to allow subjects to quit"
                            " / break out of the experiment"),
            label=_localized["Enable Escape"])
        self.params['Experiment info'] = Param(
            expInfo, valType='code', allowedTypes=[],
            hint=_translate("The info to present in a dialog box. Right-click"
                            " to check syntax and preview the dialog box."),
            label=_localized["Experiment info"], categ='Basic')
        self.params['Use version'] = Param(
            useVersion, valType='str',
            # search for options locally only by default, otherwise sluggish
            allowedVals=_versionFilter(versionOptions(), wx.__version__)
                        + ['']
                        + _versionFilter(availableVersions(), wx.__version__),
            hint=_translate("The version of PsychoPy to use when running "
                            "the experiment."),
            label=_localized["Use version"], categ='Basic')
        self.params['Force stereo'] = Param(
            enableEscape, valType='bool', allowedTypes=[],
            hint=_translate("Force audio to stereo (2-channel) output"),
            label=_localized["Force stereo"])

        # screen params
        self.params['Full-screen window'] = Param(
            fullScr, valType='bool', allowedTypes=[],
            hint=_translate("Run the experiment full-screen (recommended)"),
            label=_localized["Full-screen window"], categ='Screen')
        self.params['Window size (pixels)'] = Param(
            winSize, valType='code', allowedTypes=[],
            hint=_translate("Size of window (if not fullscreen)"),
            label=_localized["Window size (pixels)"], categ='Screen')
        self.params['Screen'] = Param(
            screen, valType='num', allowedTypes=[],
            hint=_translate("Which physical screen to run on (1 or 2)"),
            label=_localized["Screen"], categ='Screen')
        self.params['Monitor'] = Param(
            monitor, valType='str', allowedTypes=[],
            hint=_translate("Name of the monitor (from Monitor Center). Right"
                            "-click to go there, then copy & paste a monitor "
                            "name here."),
            label=_localized["Monitor"], categ="Screen")
        self.params['color'] = Param(
            color, valType='str', allowedTypes=[],
            hint=_translate("Color of the screen (e.g. black, $[1.0,1.0,1.0],"
                            " $variable. Right-click to bring up a "
                            "color-picker.)"),
            label=_localized["color"], categ='Screen')
        self.params['colorSpace'] = Param(
            colorSpace, valType='str',
            hint=_translate("Needed if color is defined numerically (see "
                            "PsychoPy documentation on color spaces)"),
            allowedVals=['rgb', 'dkl', 'lms', 'hsv', 'hex'],
            label=_localized["colorSpace"], categ="Screen")
        self.params['Units'] = Param(
            units, valType='str', allowedTypes=[],
            allowedVals=['use prefs', 'deg', 'pix', 'cm', 'norm', 'height',
                         'degFlatPos', 'degFlat'],
            hint=_translate("Units to use for window/stimulus coordinates "
                            "(e.g. cm, pix, deg)"),
            label=_localized["Units"], categ='Screen')
        self.params['blendMode'] = Param(
            blendMode, valType='str',
            allowedTypes=[], allowedVals=['add', 'avg'],
            hint=_translate("Should new stimuli be added or averaged with "
                            "the stimuli that have been drawn already"),
            label=_localized["blendMode"], categ='Screen')
        self.params['Show mouse'] = Param(
            showMouse, valType='bool', allowedTypes=[],
            hint=_translate("Should the mouse be visible on screen?"),
            label=_localized["Show mouse"], categ='Screen')

        # sound params
        self.params['Audio lib'] = Param(
            'Use prefs', valType='str', allowedVals=['Use prefs', 'ptb', 'pyo', 'sounddevice', 'pygame'],
            hint=_translate("Which Python sound engine do you want to play your sounds?"),
            label=_translate("Audio library"), categ='Audio')
        self.params['Audio latency priority'] = Param(
            'Use prefs', valType='str', allowedVals=['Use prefs', '0:prioritise compatibility', '1:balance latency/compatibility', '2:prioritise low latency', '3:aggressive low-latency', '4:critical low-latency'],
            hint=_translate("How important is audio latency for you? If essential then you may need to get all your sounds in correct formats."),
            label=_translate("Audio latency priority"), categ='Audio')

        # data params
        self.params['Data filename'] = Param(
            filename, valType='code', allowedTypes=[],
            hint=_translate("Code to create your custom file name base. Don"
                            "'t give a file extension - this will be added."),
            label=_localized["Data filename"], categ='Data')
        self.params['Save log file'] = Param(
            saveLogFile, valType='bool', allowedTypes=[],
            hint=_translate("Save a detailed log (more detailed than the "
                            "excel/csv files) of the entire experiment"),
            label=_localized["Save log file"], categ='Data')
        self.params['Save wide csv file'] = Param(
            saveWideCSVFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in comma-separated-value "
                            "(.csv) format for maximum portability"),
            label=_localized["Save wide csv file"], categ='Data')
        self.params['Save csv file'] = Param(
            saveCSVFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in comma-separated-value "
                            "(.csv) format for maximum portability"),
            label=_localized["Save csv file"], categ='Data')
        self.params['Save excel file'] = Param(
            saveXLSXFile, valType='bool', allowedTypes=[],
            hint=_translate("Save data from loops in Excel (.xlsx) format"),
            label=_localized["Save excel file"], categ='Data')
        self.params['Save psydat file'] = Param(
            savePsydatFile, valType='bool', allowedVals=[True],
            hint=_translate("Save data from loops in psydat format. This is "
                            "useful for python programmers to generate "
                            "analysis scripts."),
            label=_localized["Save psydat file"], categ='Data')
        self.params['logging level'] = Param(
            logging, valType='code',
            allowedVals=['error', 'warning', 'data', 'exp', 'info', 'debug'],
            hint=_translate("How much output do you want in the log files? "
                            "('error' is fewest messages, 'debug' is most)"),
            label=_localized["logging level"], categ='Data')

        # HTML output params
        # self.params['OSF Project ID'] = ProjIDParam(
        #     '', valType='str', # automatically updates to allow choices
        #     hint=_translate("The ID of this project (e.g. 5bqpc)"),
        #     label="OSF Project ID", categ='Online')
        self.params['HTML path'] = Param(
            'html', valType='str', allowedTypes=[],
            hint=_translate("Place the HTML files will be saved locally "),
            label="Output path", categ='Online')
        self.params['JS libs'] = Param(
            'packaged', valType='str', allowedVals=['packaged'],
            hint=_translate("Should we package a copy of the JS libs or use"
                            "remote copies (http:/www.psychopy.org/js)?"),
            label="JS libs", categ='Online')
        self.params['Completed URL'] = Param(
            '', valType='str',
            hint=_translate("Where should participants be redirected after the experiment on completion\n"
                            " INSERT COMPLETION URL E.G.?"),
            label="Completed URL", categ='Online')
        self.params['Incomplete URL'] = Param(
            '', valType='str',
            hint=_translate("Where participants are redirected if they do not complete the task\n"
                            " INSERT INCOMPLETION URL E.G.?"),
            label="Incomplete URL", categ='Online')


        self.params['exportHTML'] = Param(
            exportHTML, valType='str',
            allowedVals=['on Save', 'on Sync', 'manually'],
            hint=_translate("When to export experiment to the HTML folder."),
            label=_localized["Export HTML"], categ='Online')
Exemple #29
0
    def __init__(self, exp, parentName, name='polygon', interpolate='linear',
                 units='from exp settings',
                 lineColor='$[1,1,1]', lineColorSpace='rgb', lineWidth=1,
                 fillColor='$[1,1,1]', fillColorSpace='rgb',
                 shape='triangle', nVertices=4,
                 pos=(0, 0), size=(0.5, 0.5), ori=0,
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim=''):
        super(PolygonComponent, self).__init__(
            exp, parentName, name=name, units=units,
            pos=pos, size=size, ori=ori,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Polygon'
        self.url = "http://www.psychopy.org/builder/components/polygon.html"
        self.exp.requirePsychopyLibs(['visual'])
        self.targets = ['PsychoPy', 'PsychoJS']
        self.order = ['shape', 'nVertices']
        self.depends = [  # allows params to turn each other off/on
            {"dependsOn": "shape",  # must be param name
             "condition": "=='regular polygon...'",  # val to check for
             "param": "nVertices",  # param property to alter
             "true": "enable",  # what to do with param if condition is True
             "false": "disable",  # permitted: hide, show, enable, disable
             }
        ]

        # params
        msg = _translate("How many vertices in your regular polygon?")
        self.params['nVertices'] = Param(
            nVertices, valType='int',
            updates='constant',
            allowedUpdates=['constant'],
            hint=msg,
            label=_localized['nVertices'])

        msg = _translate("What shape is this? With 'regular polygon...' you "
                         "can set number of vertices")
        self.params['shape'] = Param(
            shape, valType='str',
            allowedVals=["line", "triangle", "rectangle", "cross",
                         "regular polygon..."],
            updates='constant',
            allowedUpdates=['constant'],
            hint=msg,
            label=_localized['shape'])

        msg = _translate("Choice of color space for the fill color "
                         "(rgb, dkl, lms, hsv)")
        self.params['fillColorSpace'] = Param(
            fillColorSpace,
            valType='str', allowedVals=['rgb', 'dkl', 'lms', 'hsv', 'rgb255'],
            updates='constant',
            hint=msg,
            label=_localized['fillColorSpace'], categ='Advanced')

        msg = _translate("Fill color of this shape; Right-click to bring up a"
                         " color-picker (rgb only)")
        self.params['fillColor'] = Param(
            fillColor, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['fillColor'], categ='Advanced')

        msg = _translate("Choice of color space for the fill color "
                         "(rgb, dkl, lms, hsv)")
        self.params['lineColorSpace'] = Param(
            lineColorSpace, valType='str',
            allowedVals=['rgb', 'dkl', 'lms', 'hsv'],
            updates='constant',
            hint=msg,
            label=_localized['lineColorSpace'], categ='Advanced')

        msg = _translate("Line color of this shape; Right-click to bring"
                         " up a color-picker (rgb only)")
        self.params['lineColor'] = Param(
            lineColor, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['lineColor'], categ='Advanced')

        msg = _translate("Width of the shape's line (always in pixels - this"
                         " does NOT use 'units')")
        self.params['lineWidth'] = Param(
            lineWidth, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['lineWidth'])

        msg = _translate(
            "How should the image be interpolated if/when rescaled")
        self.params['interpolate'] = Param(
            interpolate, valType='str', allowedVals=['linear', 'nearest'],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['interpolate'], categ='Advanced')

        msg = _translate(
            "Size of this stimulus [w,h]. Note that for a line only the "
            "first value is used, for triangle and rect the [w,h] is as "
            "expected,\n but for higher-order polygons it represents the "
            "[w,h] of the ellipse that the polygon sits on!! ")
        self.params['size'] = Param(
            size, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['size'])

        del self.params['color']
        del self.params['colorSpace']
Exemple #30
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'text.png')
tooltip = _translate('Text: present text stimuli')

# only use _localized values for label values, nothing functional:
_localized = {
    'text': _translate('Text'),
    'font': _translate('Font'),
    'letterHeight': _translate('Letter height'),
    'wrapWidth': _translate('Wrap width'),
    'flip': _translate('Flip (mirror)'),
    'languageStyle': _translate('Language style')
}


class TextComponent(BaseVisualComponent):
    """An event class for presenting text-based stimuli
    """
Exemple #31
0
    def __init__(self, exp, parentName, name='env_grating', carrier='sin',
                 mask='None', sf=1.0, interpolate='linear',
                 units='from exp settings', color='$[1,1,1]', colorSpace='rgb',
                 pos=(0, 0), size=(0.5, 0.5), ori=0, phase=0.0, texRes='128',
                 envelope='sin',envsf=1.0,envori=0.0,envphase=0.0, beat=False, contrast=0.5, moddepth=1.0, blendmode='avg',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0,
                 startEstim='', durationEstim=''):
        super(EnvGratingComponent, self).__init__(
            exp, parentName, name=name, units=units,
            color=color, colorSpace=colorSpace,
            pos=pos, size=size, ori=ori,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'EnvGrating'
        self.url = "http://www.psychopy.org/builder/components/EnvelopeGrating.html"
        self.order = ['carrier', 'mask']

        # params

        self.params['ori'] = Param(
            ori, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=_translate("Orientation of this stimulus (in deg)"),
            label=_localized['ori'],categ="Carrier")

        msg = _translate("The (2D) texture of the background - can be sin, sqr,"
                         " sinXsin... or a filename (including path)")
        self.params['carrier'] = Param(
            carrier, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['carrier'], categ="Carrier")

        msg = _translate("An image to define the alpha mask (ie shape)- "
                         "gauss, circle... or a filename (including path)")
        self.params['mask'] = Param(
            mask, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['mask'], categ="Carrier")

        msg = _translate("Contrast of background carrier")
        self.params['contrast'] = Param(
            contrast, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['contrast'], categ="Carrier")

        msg = _translate("Spatial frequency of background carrier repeats across the "
                         "grating in 1 or 2 dimensions, e.g. 4 or [2,3]")
        self.params['sf'] = Param(
            sf, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['sf'], categ="Carrier")

        msg = _translate("Spatial positioning of the background carrier "
                         "(wraps in range 0-1.0)")
        self.params['phase'] = Param(
            phase, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['phase'], categ="Carrier")

        msg = _translate(
            "Resolution of the texture for standard ones such as sin, sqr "
            "etc. For most cases a value of 256 pixels will suffice")
        self.params['texture resolution'] = Param(
            texRes,
            valType='code', allowedVals=['32', '64', '128', '256', '512'],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['texture resolution'], categ="Carrier")

        msg = _translate("How should the image be interpolated if/when "
                         "rescaled")
        self.params['interpolate'] = Param(
            interpolate, valType='str', allowedVals=['linear', 'nearest'],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['interpolate'], categ="Carrier")


        msg = _translate("The (2D) texture of the envelope - can be sin, sqr,"
                         " sinXsin... or a filename (including path)")
        self.params['envelope'] = Param(
            envelope, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envelope'], categ="Envelope")

        msg = _translate("Spatial frequency of the modulation envelope repeats across the "
                         "grating in 1 or 2 dimensions, e.g. 4 or [2,3]")
        self.params['envsf'] = Param(
            envsf, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envsf'], categ="Envelope")

        msg = _translate("Spatial positioning of the modulation envelope"
                         "(wraps in range 0-1.0)")
        self.params['envphase'] = Param(
            envphase, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envphase'], categ="Envelope")

        msg = _translate("Orientation of the modulation envelope"
                         "(wraps in range 0-360)")
        self.params['envori'] = Param(
            envori, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['envori'], categ="Envelope")

        msg = _translate("Modulation depth of modulation envelope")
        self.params['moddepth'] = Param(
            moddepth, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['moddepth'], categ="Envelope")

        msg = _translate("Do you want a 'beat'? [beat = carrier*envelope, "
                         "no beat = carrier*(1+envelope), True/False, Y/N]")
        self.params['beat'] = Param(
            beat, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['beat'], categ="Envelope")

        msg = _translate("OpenGL Blendmode. Avg is most common mode"
                         " in PsychoPy, add is useful if combining a beat with"
                         " the carrier image or numpy array at point of display")
        self.params['blendmode'] = Param(
            blendmode, valType='str', allowedVals=['avg', 'add'],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['blendmode'], categ="Basic")
Exemple #32
0
    def __init__(
            self,
            exp,
            parentName,
            name='text',
            # effectively just a display-value
            text=_translate('Any text\n\nincluding line breaks'),
            font='Arial',
            units='from exp settings',
            color='white',
            colorSpace='rgb',
            pos=(0, 0),
            letterHeight=0.1,
            ori=0,
            startType='time (s)',
            startVal=0.0,
            stopType='duration (s)',
            stopVal=1.0,
            flip='',
            startEstim='',
            durationEstim='',
            wrapWidth='',
            languageStyle='LTR'):
        super(TextComponent, self).__init__(exp,
                                            parentName,
                                            name=name,
                                            units=units,
                                            color=color,
                                            colorSpace=colorSpace,
                                            pos=pos,
                                            ori=ori,
                                            startType=startType,
                                            startVal=startVal,
                                            stopType=stopType,
                                            stopVal=stopVal,
                                            startEstim=startEstim,
                                            durationEstim=durationEstim)
        self.type = 'Text'
        self.url = "http://www.psychopy.org/builder/components/text.html"

        # params
        _allow3 = ['constant', 'set every repeat', 'set every frame']  # list
        self.params['text'] = Param(
            text,
            valType='extendedStr',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The text to be displayed"),
            label=_localized['text'])
        self.params['font'] = Param(
            font,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The font name (e.g. Comic Sans)"),
            label=_localized['font'])
        del self.params['size']  # because you can't specify width for text
        self.params['letterHeight'] = Param(
            letterHeight,
            valType='code',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("Specifies the height of the letter (the width"
                            " is then determined by the font)"),
            label=_localized['letterHeight'])

        self.params['wrapWidth'] = Param(
            wrapWidth,
            valType='code',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant'],
            hint=_translate("How wide should the text get when it wraps? (in"
                            " the specified units)"),
            label=_localized['wrapWidth'])
        self.params['flip'] = Param(
            flip,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("horiz = left-right reversed; vert = up-down"
                            " reversed; $var = variable"),
            label=_localized['flip'])
        self.params['languageStyle'] = Param(
            languageStyle,
            valType='str',
            allowedVals=['LTR', 'RTL', 'Arabic'],
            hint=_translate(
                "Handle right-to-left (RTL) languages and Arabic reshaping"),
            label=_localized['languageStyle'])
        for prm in ('ori', 'opacity', 'colorSpace', 'units', 'wrapWidth',
                    'flip', 'languageStyle'):
            self.params[prm].categ = 'Advanced'
Exemple #33
0
    def __init__(
        self,
        exp,
        parentName,
        name='buttonBox',
        store='first key',
        useTimer=True,
        deviceNumber=0,
        allowedKeys="",
        getReleaseTime=False,  # not yet supported
        forceEndRoutine=True,
        storeCorrect=False,
        correctAns="",
        discardPrev=True,
        startType='time (s)',
        startVal=0.0,
        stopType='duration (s)',
        stopVal=1.0,
        startEstim='',
        durationEstim='',
    ):
        super(cedrusButtonBoxComponent,
              self).__init__(exp,
                             parentName,
                             name=name,
                             allowedKeys=allowedKeys,
                             store=store,
                             discardPrev=discardPrev,
                             forceEndRoutine=forceEndRoutine,
                             storeCorrect=storeCorrect,
                             correctAns=correctAns,
                             startType=startType,
                             startVal=startVal,
                             stopType=stopType,
                             stopVal=stopVal,
                             startEstim=startEstim,
                             durationEstim=durationEstim)

        self.type = 'cedrusButtonBox'
        self.url = "http://www.psychopy.org/builder/components/cedrusButtonBox.html"

        self.exp.requirePsychopyLibs(['hardware'])

        self.params['correctAns'].hint = _translate(
            "What is the 'correct' response? NB, buttons are labelled 0 to "
            "6 on a 7-button box. Enter 'None' (no quotes) if withholding "
            "a response is correct. Might be helpful to add a correctAns "
            "column and use $correctAns to compare to the key press.")

        self.params['correctAns'].valType = 'code'

        self.params['allowedKeys'].hint = _translate(
            'Keys to be read (blank for any) or key numbers separated by '
            'commas')

        msg = _translate('Device number, if you have multiple devices which'
                         ' one do you want (0, 1, 2...)')
        self.params['deviceNumber'] = Param(deviceNumber,
                                            valType='code',
                                            allowedTypes=[],
                                            updates='constant',
                                            allowedUpdates=[],
                                            hint=msg,
                                            label=_localized['deviceNumber'],
                                            categ='Advanced')

        # self.params['getReleaseTime'] = Param(getReleaseTime,
        #    valType='bool', allowedVals=[True, False],
        #    updates='constant', allowedUpdates=[],
        #    hint="Wait for the key to be released and store the time
        #       that it was held down",
        #    label="Get release time")

        msg = _translate('According to Cedrus the response box timer has '
                         'a drift - use with caution!')
        self.params['useBoxTimer'] = Param(getReleaseTime,
                                           valType='bool',
                                           allowedVals=[True, False],
                                           updates='constant',
                                           allowedUpdates=[],
                                           hint=msg,
                                           label=_localized['useBoxTimer'],
                                           categ='Advanced')
Exemple #34
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2022 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).

from pathlib import Path
from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy.hardware import qmix
from psychopy.localization import _localized as __localized
_localized = __localized.copy()

_localized.update({
    'pumpIndex':
    _translate('Pump index'),
    'syringeType':
    _translate('Syringe type'),
    'pumpAction':
    _translate('Pump action'),
    'flowRate':
    _translate('Flow rate'),
    'flowRateUnit':
    _translate('Flow rate unit'),
    'switchValveWhenDone':
    _translate('Switch valve after dosing'),
    'syncToScreen':
    _translate('Sync to screen')
})

Exemple #35
0
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, \
    getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'grating.png')
tooltip = _translate('Grating: present cyclic textures, prebuilt or from a '
                     'file')

# only use _localized values for label values, nothing functional:
_localized = {'tex': _translate('Texture'),
              'mask': _translate('Mask'),
              'sf': _translate('Spatial frequency'),
              'phase': _translate('Phase (in cycles)'),
              'texture resolution': _translate('Texture resolution'),
              'blendmode':_translate('OpenGL blend mode'),
              'interpolate': _translate('Interpolate')}


class GratingComponent(BaseVisualComponent):
    """A class for presenting grating stimuli"""

    def __init__(self, exp, parentName, name='grating', image='sin',
Exemple #36
0
class QmixPumpComponent(BaseComponent):
    """Operate a Cetoni neMESYS syringe pump"""
    targets = ['PsychoPy']
    categories = ['I/O']
    iconFile = Path(__file__).parent / 'pump.png'
    tooltip = _translate(
        'Pump: deliver liquid stimuli via a Cetoni neMESYS syringe pump')

    def __init__(self,
                 exp,
                 parentName,
                 name='pump',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim='',
                 pumpIndex=0,
                 syringeType='50 mL glass',
                 pumpAction='dispense',
                 flowRate=1.0,
                 flowRateUnit='mL/s',
                 switchValveWhenDone=True,
                 syncToScreen=True):

        super(QmixPumpComponent, self).__init__(exp,
                                                parentName,
                                                name,
                                                startType=startType,
                                                startVal=startVal,
                                                stopType=stopType,
                                                stopVal=stopVal,
                                                startEstim=startEstim,
                                                durationEstim=durationEstim)

        self.type = 'QmixPump'
        self.url = 'https://www.psychopy.org/builder/components/pump.html'

        self.exp.requireImport(importName='qmix',
                               importFrom='psychopy.hardware')

        # Order in which the user-settable parameters will be displayed
        # in the component's properties window.
        self.order += [
            'syncToScreen',  # Basic tab
            'pumpIndex',
            'syringeType',
            'pumpAction',
            'flowRate',
            'flowRateUnit',
            'switchValveWhenDone',  # Hardware tab
        ]

        self.params['pumpIndex'] = Param(
            pumpIndex,
            categ='Hardware',
            valType='code',
            inputType="single",
            hint=_translate('The index of the pump(s) (first pump is 0).'),
            label=_localized['pumpIndex'])

        self.params['syringeType'] = Param(
            syringeType,
            categ='Hardware',
            valType='str',
            inputType="choice",
            allowedVals=qmix.syringeTypes,
            hint=_translate('Syringe type and dimensions'),
            label=_localized['syringeType'])

        self.params['pumpAction'] = Param(
            pumpAction,
            categ='Hardware',
            valType='str',
            inputType="choice",
            allowedVals=['aspirate', 'dispense'],
            direct=False,
            hint=_translate('Whether the syringe should be filled (aspirate) '
                            'or emptied (dispense'),
            label=_localized['pumpAction'])

        self.params['flowRate'] = Param(flowRate,
                                        categ='Hardware',
                                        valType='num',
                                        inputType="single",
                                        hint='The flow rate',
                                        label=_localized['flowRate'])

        self.params['flowRateUnit'] = Param(flowRateUnit,
                                            categ='Hardware',
                                            valType='str',
                                            inputType="choice",
                                            allowedVals=qmix.flowRateUnits,
                                            hint='The unit of the flow rate',
                                            label=_localized['flowRateUnit'])

        self.params['switchValveWhenDone'] = Param(
            switchValveWhenDone,
            valType='bool',
            inputType="bool",
            categ='Hardware',
            allowedVals=[True, False],
            hint=_translate('Switch the valve after pump operation'),
            label=_localized['switchValveWhenDone'])

        self.params['syncToScreen'] = Param(
            syncToScreen,
            valType='bool',
            inputType="bool",
            categ='Basic',
            allowedVals=[True, False],
            hint=_translate('Sync pump onset to the screen refresh'),
            label=_localized['syncToScreen'])

    def writeRunOnceInitCode(self, buff):
        code = ('# Initialize all pumps so they are ready to be used when we\n'
                '# need them later. This enables us to dynamically select\n'
                '# pumps during the experiment without worrying about their\n'
                '# initialization.\n'
                'qmix._init_all_pumps()\n')
        buff.writeOnceIndentedLines(code)

    def writeRoutineStartCode(self, buff):
        """Write the code that will be called at the start of the routine.
        """
        code = (
            '\n'
            '# Select the correct pre-initialized pump, and set the \n'
            '# syringe type according to the Pumo Component properties.\n'
            '_pumpInstance = qmix.pumps[%(pumpIndex)s]\n'
            '%(name)s = qmix._PumpWrapperForBuilderComponent(_pumpInstance)\n'
            '%(name)s.syringeType = %(syringeType)s\n'
            '%(name)s.flowRateUnit = %(flowRateUnit)s\n'
            '%(name)s.status = None\n' % self.params)
        buff.writeIndentedLines(code)

    def writeFrameCode(self, buff):
        """Write the code that will be called every frame.
        """
        buff.writeIndented("# *%s* updates\n" % (self.params['name']))
        self.writeStartTestCode(buff)
        buff.writeIndented("%(name)s.status = STARTED\n" % self.params)

        if self.params['syncToScreen'].val:
            if self.params['pumpAction'] == 'aspirate':
                code = ('win.callOnFlip(%(name)s.fill, '
                        'flowRate=%(flowRate)s)\n') % self.params
            else:
                code = 'win.callOnFlip(%(name)s.empty, flowRate=%(flowRate)s)\n' % self.params
        else:
            if self.params['pumpAction'] == 'aspirate':
                code = '%(name)s.fill(flowRate=%(flowRate)s)\n' % self.params
            else:
                code = '%(name)s.empty(flowRate=%(flowRate)s)\n' % self.params

        buff.writeIndentedLines(code)
        buff.setIndentLevel(-1, relative=True)

        # 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)
            buff.writeIndented("%(name)s.status = FINISHED\n" % self.params)

            if self.params['syncToScreen'].val:
                if self.params['switchValveWhenDone'].val:
                    code = ('win.callOnFlip(%(name)s.stop)\n'
                            'win.callOnFlip(%(name)s.switchValvePosition)\n' %
                            self.params)
                else:
                    code = 'win.callOnFlip(%(name)s.stop)\n' % self.params
            else:
                if self.params['switchValveWhenDone'].val:
                    code = ('%(name)s.stop()\n'
                            '%(name)s.switchValvePosition()\n' % self.params)
                else:
                    code = '%(name)s.stop()\n' % self.params

            buff.writeIndentedLines(code)
            buff.setIndentLevel(-2, relative=True)

    def writeRoutineEndCode(self, buff):
        # Make sure that we stop the pumps even if the routine has been
        # ended prematurely.
        if self.params['switchValveWhenDone'].val:
            code = ('\nif %(name)s.status == STARTED:\n'
                    '    %(name)s.stop()\n'
                    '    %(name)s.switchValvePosition()\n\n' % self.params)
        else:
            code = ('\nif %(name)s.status == STARTED:\n'
                    '    %(name)s.stop()\n\n' % self.params)

        buff.writeIndentedLines(code)

        # get parent to write code too (e.g. store onset/offset times)
        super().writeRoutineEndCode(buff)
Exemple #37
0
"""
Part of the PsychoPy library
Copyright (C) 2015 Jonathan Peirce
Distributed under the terms of the GNU General Public License (GPL).
"""

from __future__ import absolute_import, print_function
from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
import numpy as np

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'var.png')
tooltip = _translate('Variable: create a new variable')

# only use _localized values for label values, nothing functional:
_localized = {'name': _translate('Name'),
              'startExpValue': _translate('Experiment start value'),
              'startRoutineValue': _translate('Routine start value'),
              'startFrameValue': _translate('Frame start value'),
              'saveStartExp': _translate('Save exp start value'),
              'saveStartRoutine': _translate('Save routine start value'),
              'saveFrameValue': _translate('Save frame value'),
              'saveEndRoutine': _translate('Save routine end value'),
              'saveEndExp': _translate('Save exp end value')}


class VariableComponent(BaseComponent):
    """An class for creating variables in builder."""
Exemple #38
0
    def __init__(self,
                 exp,
                 parentName,
                 name='pump',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim='',
                 pumpIndex=0,
                 syringeType='50 mL glass',
                 pumpAction='dispense',
                 flowRate=1.0,
                 flowRateUnit='mL/s',
                 switchValveWhenDone=True,
                 syncToScreen=True):

        super(QmixPumpComponent, self).__init__(exp,
                                                parentName,
                                                name,
                                                startType=startType,
                                                startVal=startVal,
                                                stopType=stopType,
                                                stopVal=stopVal,
                                                startEstim=startEstim,
                                                durationEstim=durationEstim)

        self.type = 'QmixPump'
        self.url = 'https://www.psychopy.org/builder/components/pump.html'

        self.exp.requireImport(importName='qmix',
                               importFrom='psychopy.hardware')

        # Order in which the user-settable parameters will be displayed
        # in the component's properties window.
        self.order += [
            'syncToScreen',  # Basic tab
            'pumpIndex',
            'syringeType',
            'pumpAction',
            'flowRate',
            'flowRateUnit',
            'switchValveWhenDone',  # Hardware tab
        ]

        self.params['pumpIndex'] = Param(
            pumpIndex,
            categ='Hardware',
            valType='code',
            inputType="single",
            hint=_translate('The index of the pump(s) (first pump is 0).'),
            label=_localized['pumpIndex'])

        self.params['syringeType'] = Param(
            syringeType,
            categ='Hardware',
            valType='str',
            inputType="choice",
            allowedVals=qmix.syringeTypes,
            hint=_translate('Syringe type and dimensions'),
            label=_localized['syringeType'])

        self.params['pumpAction'] = Param(
            pumpAction,
            categ='Hardware',
            valType='str',
            inputType="choice",
            allowedVals=['aspirate', 'dispense'],
            direct=False,
            hint=_translate('Whether the syringe should be filled (aspirate) '
                            'or emptied (dispense'),
            label=_localized['pumpAction'])

        self.params['flowRate'] = Param(flowRate,
                                        categ='Hardware',
                                        valType='num',
                                        inputType="single",
                                        hint='The flow rate',
                                        label=_localized['flowRate'])

        self.params['flowRateUnit'] = Param(flowRateUnit,
                                            categ='Hardware',
                                            valType='str',
                                            inputType="choice",
                                            allowedVals=qmix.flowRateUnits,
                                            hint='The unit of the flow rate',
                                            label=_localized['flowRateUnit'])

        self.params['switchValveWhenDone'] = Param(
            switchValveWhenDone,
            valType='bool',
            inputType="bool",
            categ='Hardware',
            allowedVals=[True, False],
            hint=_translate('Switch the valve after pump operation'),
            label=_localized['switchValveWhenDone'])

        self.params['syncToScreen'] = Param(
            syncToScreen,
            valType='bool',
            inputType="bool",
            categ='Basic',
            allowedVals=[True, False],
            hint=_translate('Sync pump onset to the screen refresh'),
            label=_localized['syncToScreen'])
Exemple #39
0
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2015 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
import re

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'mouse.png')
tooltip = _translate('Mouse: query mouse position and buttons')

# only use _localized values for label values, nothing functional:
_localized = {'saveMouseState': _translate('Save mouse state'),
              'forceEndRoutineOnPress': _translate('End Routine on press'),
              'timeRelativeTo': _translate('Time relative to'),
              'Clickable stimuli': 'Clickable stimuli',
              'Store params for clicked': 'Store params for clicked',
              'New clicks only': 'New clicks only'}


class MouseComponent(BaseComponent):
    """An event class for checking the mouse location and buttons
    at given timepoints
    """
    categories = ['Responses']
Exemple #40
0
class ApertureComponent(BaseVisualComponent):
    """An event class for using GL stencil to restrict the viewing area to a
    circle or square of a given size and position"""

    categories = ['Stimuli']
    targets = ['PsychoPy']
    iconFile = Path(__file__).parent / 'aperture.png'
    tooltip = _translate(
        'Aperture: restrict the drawing of stimuli to a given '
        'region')

    def __init__(self,
                 exp,
                 parentName,
                 name='aperture',
                 units='norm',
                 size=1,
                 pos=(0, 0),
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal=1.0,
                 startEstim='',
                 durationEstim=''):
        # initialise main parameters
        super(ApertureComponent, self).__init__(exp,
                                                parentName,
                                                name=name,
                                                units=units,
                                                pos=pos,
                                                size=size,
                                                startType=startType,
                                                startVal=startVal,
                                                stopType=stopType,
                                                stopVal=stopVal,
                                                startEstim=startEstim,
                                                durationEstim=durationEstim)

        self.type = 'Aperture'
        self.url = "https://www.psychopy.org/builder/components/aperture.html"
        self.order += []

        msg = _translate(
            "How big is the aperture? (a single number for diameter)")
        self.params['size'].hint = msg
        # only localize hints and labels
        self.params['size'].label = _translate("Size")
        self.params['pos'].hint = _translate("Where is the aperture centred?")

        # Remove BaseVisual params which are not needed
        del self.params['ori']
        del self.params['color']
        del self.params['colorSpace']
        del self.params['fillColor']
        del self.params['borderColor']
        del self.params['opacity']

    def writeInitCode(self, buff):
        # do writing of init
        inits = getInitVals(self.params)

        # do we need units code?
        if self.params['units'].val == 'from exp settings':
            unitsStr = ""
        else:
            unitsStr = f"units={inits['units']},"

        code = (
            f"{inits['name']} = visual.Aperture(\n"
            f"    win=win, name='{inits['name']}',\n"
            f"    {unitsStr} size={inits['size']}, pos={inits['pos']})\n"
            f"{inits['name']}.disable()  # disable until its actually used\n")
        buff.writeIndentedLines(code)

    def writeFrameCode(self, buff):
        """Only activate the aperture for the required frames
        """
        params = self.params
        code = (f"\n" f"# *{params['name']}* updates\n")
        buff.writeIndented(code)
        # writes an if statement to determine whether to draw etc
        self.writeStartTestCode(buff)
        buff.writeIndented("%(name)s.enabled = True\n" % self.params)
        # to get out of the if statement
        buff.setIndentLevel(-1, relative=True)
        if self.params['stopVal'].val not in ['', None, -1, 'None']:
            # writes an if statement to determine whether to draw etc
            self.writeStopTestCode(buff)
            buff.writeIndented("%(name)s.enabled = False\n" % self.params)
            # to get out of the if statement
            buff.setIndentLevel(-2, relative=True)
        # set parameters that need updating every frame
        # do any params need updating? (this method inherited from _base)
        if self.checkNeedToUpdate('set every frame'):
            code = (
                "if %(name)s.status == STARTED:  # only update if being  drawn\n"
            )
            buff.writeIndented(code % self.params)

            buff.setIndentLevel(+1, relative=True)  # to enter the if block
            self.writeParamUpdates(buff, 'set every frame')
            buff.setIndentLevel(-1, relative=True)  # to exit the if block

    def writeRoutineEndCode(self, buff):
        msg = "%(name)s.enabled = False  # just in case it was left enabled\n"
        buff.writeIndented(msg % self.params)

        # get parent to write code too (e.g. store onset/offset times)
        super().writeRoutineEndCode(buff)
Exemple #41
0
from __future__ import absolute_import, print_function

from builtins import str
from past.builtins import basestring
from os import path

from psychopy.experiment.components import Param, _translate
from psychopy.experiment.components.keyboard import KeyboardComponent
from psychopy.experiment import CodeGenerationException, valid_var_re

__author__ = 'Jon Peirce'

# abs path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'cedrusBox.png')
tooltip = _translate('Cedrus Button Box: Cedrus response boxes, using the '
                     'pyxid library provided by Cedrus')

# only use _localized values for label values, nothing functional:
_localized = {'deviceNumber': _translate('Device number'),
              'useBoxTimer': _translate("Use box timer")}


class cedrusButtonBoxComponent(KeyboardComponent):
    """An event class for checking an Cedrus RBxxx button boxes
    using XID library

    This is based on keyboard component, several important differences:
    - no special response class analogous to event.BuilderKeyResponse()
    - enabled responses (active keys) are handled by the hardware device

    More than one component in a routine will produce conflicts between
Exemple #42
0
from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, \
    getInitVals, _translate
from psychopy.visual import slider
from psychopy.experiment import py2js
from psychopy import logging
from psychopy.localization import _localized as __localized
_localized = __localized.copy()
import copy

__author__ = 'Jon Peirce'

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'slider.png')
tooltip = _translate('Slider: A simple, flexible object for getting ratings')

# only use _localized values for label values, nothing functional:
_localized.update({
    'categoryChoices': _translate('Category choices'),
    'labels': _translate('Labels'),
    'ticks': _translate('Ticks'),
    'forceEndRoutine': _translate('Force end of Routine'),
    'storeHistory': _translate('Store history'),
    'storeRating': _translate('Store rating'),
    'storeRatingTime': _translate('Store rating time'),
    'readOnly': _translate('readOnly')
})

knownStyles = slider.Slider.knownStyles
Exemple #43
0
    def __init__(self, exp, parentName,
                 name='slider',
                 labels='',
                 ticks="(1, 2, 3, 4, 5)",
                 size='(1.0, 0.1)',
                 pos='(0, -0.4)',
                 flip=False,
                 style=['rating'],
                 granularity=0,
                 color="LightGray",
                 font="HelveticaBold",
                 startType='time (s)', startVal='0.0',
                 stopType='condition', stopVal='',
                 startEstim='', durationEstim='',
                 forceEndRoutine=True,
                 storeRating=True, storeRatingTime=True, storeHistory=False):
        super(SliderComponent, self).__init__(
                exp, parentName, name,
                startType=startType, startVal=startVal,
                stopType=stopType, stopVal=stopVal,
                startEstim=startEstim, durationEstim=durationEstim)
        self.type = 'SliderComponent'
        self.url = "http://www.psychopy.org/builder/components/slidercomponent.html"
        self.exp.requirePsychopyLibs(['visual', 'event'])

        # params
        self.order = ['name',
                      'size', 'pos',
                      'ticks', 'labels', 'granularity',
                      'font','flip','color','styles',
                      ]

        # normal params:
        # = the usual as inherited from BaseVisual plus:
        self.params['ticks'] = Param(
                ticks, valType='list', allowedTypes=[],
                updates='constant',
                allowedUpdates=['constant', 'set every repeat'],
                hint=_translate("Tick positions (numerical) on the scale, "
                                "separated by commas"),
                label=_localized['ticks'])
        self.params['labels'] = Param(
                labels, valType='list', allowedTypes=[],
                updates='constant',
                allowedUpdates=['constant', 'set every repeat'],
                hint=_translate("Labels for the tick marks on the scale, "
                                "separated by commas"),
                label=_localized['labels'])
        self.params['granularity'] = Param(
                granularity, valType='code', allowedTypes=[],
                updates='constant',
                allowedUpdates=['constant', 'set every repeat'],
                hint=_translate("Specifies the minimum step size "
                                "(0 for a continuous scale, 1 for integer "
                                "rating scale)"),
                label=_translate('Granularity'))
        self.params['forceEndRoutine'] = Param(
                forceEndRoutine, valType='bool', allowedTypes=[],
                updates='constant', allowedUpdates=[],
                hint=_translate("Should setting a rating (releasing the mouse) "
                                "cause the end of the routine (e.g. trial)?"),
                label=_localized['forceEndRoutine'])
        self.params['pos'] = Param(
                pos, valType='code', allowedTypes=[],
                updates='constant',
                allowedUpdates=['constant', 'set every repeat',
                                'set every frame'],
                hint=_translate("x,y position on the screen"),
                label=_localized['pos'])
        self.params['size'] = Param(
                size, valType='code', allowedTypes=[],
                updates='constant',
                allowedUpdates=['constant', 'set every repeat',
                                'set every frame'],
                hint=_translate(
                        "Size on screen. e.g. (500,10) pix for horizontal,"
                        "(10,500) pix for vertical"),
                label=_localized['size'])

        # advanced params:
        self.params['flip'] = Param(
                flip, valType='bool',
                updates='constant', allowedUpdates=[],
                hint=_translate(
                        "By default the labels will be on the bottom or "
                        "left of the scale, but this can be flipped to the "
                        "other side."),
                label=_translate('Flip'),
                categ='Appearance')
        self.params['color'] = Param(
                color, valType='str',
                updates='constant',
                allowedUpdates=['constant', 'set every repeat',
                                'set every frame'],
                hint=_translate(
                        "Color of the lines and labels (might be"
                        "overridden by the style setting)"),
                label=_translate('Color'),
                categ='Appearance')
        self.params['font'] = Param(
                font, valType='str',
                updates='constant',
                allowedUpdates=['constant', 'set every repeat'],
                hint=_translate(
                        "Font for the labels"),
                label=_translate('Font'),
                categ='Appearance')
        self.params['styles'] = Param(
                style, valType='fixedList',
                updates='constant', allowedVals=knownStyles,
                hint=_translate(
                        "Styles determine the appearance of the slider"),
                label=_translate('Styles'),
                categ='Appearance')

        # data params
        self.params['storeRating'] = Param(
                storeRating, valType='bool', allowedTypes=[],
                updates='constant', allowedUpdates=[],
                hint=_translate("store the rating"),
                label=_localized['storeRating'],
                categ='Data')
        self.params['storeRatingTime'] = Param(
                storeRatingTime, valType='bool', allowedTypes=[],
                updates='constant', allowedUpdates=[],
                hint=_translate("Store the time taken to make the choice (in "
                                "seconds)"),
                label=_localized['storeRatingTime'],
                categ='Data')
        self.params['storeHistory'] = Param(
                storeHistory, valType='bool', allowedTypes=[],
                updates='constant', allowedUpdates=[],
                hint=_translate("store the history of (selection, time)"),
                label=_localized['storeHistory'],
                categ='Data')
Exemple #44
0
    def __init__(self,
                 exp,
                 parentName,
                 name='slider',
                 labels='',
                 ticks="(1, 2, 3, 4, 5)",
                 size='(1.0, 0.1)',
                 pos='(0, -0.4)',
                 flip=False,
                 style=['rating'],
                 granularity=0,
                 color="LightGray",
                 font="Open Sans",
                 startType='time (s)',
                 startVal='0.0',
                 stopType='condition',
                 stopVal='',
                 startEstim='',
                 durationEstim='',
                 forceEndRoutine=True,
                 storeRating=True,
                 storeRatingTime=True,
                 storeHistory=False,
                 readOnly=False):
        super(SliderComponent, self).__init__(exp,
                                              parentName,
                                              name,
                                              startType=startType,
                                              startVal=startVal,
                                              stopType=stopType,
                                              stopVal=stopVal,
                                              startEstim=startEstim,
                                              durationEstim=durationEstim)
        self.type = 'Slider'
        self.url = "http://www.psychopy.org/builder/components/slider.html"
        self.exp.requirePsychopyLibs(['visual', 'event'])
        self.targets = ['PsychoPy', 'PsychoJS']

        # params
        self.order += [
            'forceEndRoutine',  # Basic tab
            'font',  # Appearance tab
            'flip',  # Layout tab
            'ticks',
            'labels',
            'granularity',
            'readOnly',  # Data tab
        ]
        self.order.insert(self.order.index("colorSpace"), "style")
        self.order.insert(self.order.index("units"), "Item Padding")

        # normal params:
        # = the usual as inherited from BaseVisual plus:
        self.params['ticks'] = Param(
            ticks,
            valType='list',
            inputType="single",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=_translate("Tick positions (numerical) on the scale, "
                            "separated by commas"),
            label=_localized['ticks'])
        self.params['labels'] = Param(
            labels,
            valType='list',
            inputType="single",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=_translate("Labels for the tick marks on the scale, "
                            "separated by commas"),
            label=_localized['labels'])
        self.params['granularity'] = Param(
            granularity,
            valType='num',
            inputType="single",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=_translate("Specifies the minimum step size "
                            "(0 for a continuous scale, 1 for integer "
                            "rating scale)"),
            label=_translate('Granularity'))
        self.params['forceEndRoutine'] = Param(
            forceEndRoutine,
            valType='bool',
            inputType="bool",
            allowedTypes=[],
            categ='Basic',
            updates='constant',
            allowedUpdates=[],
            hint=_translate("Should setting a rating (releasing the mouse) "
                            "cause the end of the routine (e.g. trial)?"),
            label=_localized['forceEndRoutine'])
        self.params['readOnly'] = Param(
            readOnly,
            valType='bool',
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=[],
            hint=_translate(
                "Should participant be able to change the rating on the Slider?"
            ),
            label=_localized['readOnly'])

        # advanced params:
        self.params['flip'] = Param(
            flip,
            valType='bool',
            inputType="bool",
            categ='Layout',
            updates='constant',
            allowedUpdates=[],
            hint=_translate(
                "By default the labels will be on the bottom or "
                "left of the scale, but this can be flipped to the "
                "other side."),
            label=_translate('Flip'))

        self.params['color'].hint = "Color of the lines and labels (might be"
        "overridden by the style setting)"

        self.params['font'] = Param(
            font,
            valType='str',
            inputType="single",
            categ='Appearance',
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=_translate("Font for the labels"),
            label=_translate('Font'))

        self.params['styles'] = Param(
            style,
            valType='str',
            inputType="choice",
            categ='Appearance',
            updates='constant',
            allowedVals=knownStyles,
            hint=_translate("Styles determine the appearance of the slider"),
            label=_translate('Styles'))

        # data params
        self.params['storeRating'] = Param(storeRating,
                                           valType='bool',
                                           inputType="bool",
                                           allowedTypes=[],
                                           categ='Data',
                                           updates='constant',
                                           allowedUpdates=[],
                                           hint=_translate("store the rating"),
                                           label=_localized['storeRating'])
        self.params['storeRatingTime'] = Param(
            storeRatingTime,
            valType='bool',
            inputType="bool",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=[],
            hint=_translate("Store the time taken to make the choice (in "
                            "seconds)"),
            label=_localized['storeRatingTime'])
        self.params['storeHistory'] = Param(
            storeHistory,
            valType='bool',
            inputType="bool",
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=[],
            hint=_translate("store the history of (selection, time)"),
            label=_localized['storeHistory'])

        del self.params['fillColor']
        del self.params['borderColor']
Exemple #45
0
    def __init__(self, exp, parentName, name='key_resp',
                 allowedKeys="'y','n','left','right','space'",
                 store='last key', forceEndRoutine=True, storeCorrect=False,
                 correctAns="", discardPrev=True,
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal='',
                 startEstim='', durationEstim='',
                 syncScreenRefresh=True):
        super(KeyboardComponent, self).__init__(
            exp, parentName, name,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Keyboard'
        self.url = "http://www.psychopy.org/builder/components/keyboard.html"
        self.exp.requirePsychopyLibs(['gui'])

        # params

        # NB name and timing params always come 1st
        self.order = ['forceEndRoutine', 'allowedKeys', 'store',
                      'storeCorrect', 'correctAns']

        msg = _translate(
            "A comma-separated list of keys (with quotes), such as "
            "'q','right','space','left'")
        self.params['allowedKeys'] = Param(
            allowedKeys, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat'],
            hint=(msg),
            label=_localized['allowedKeys'])

        # hints say 'responses' not 'key presses' because the same hint is
        # also used with button boxes
        msg = _translate("Do you want to discard all responses occuring "
                         "before the onset of this component?")
        self.params['discard previous'] = Param(
            discardPrev, valType='bool', allowedTypes=[],
            updates='constant',
            hint=msg,
            label=_localized['discard previous'])

        msg = _translate("Choose which (if any) responses to store at the "
                         "end of a trial")
        self.params['store'] = Param(
            store, valType='str', allowedTypes=[],
            allowedVals=['last key', 'first key', 'all keys', 'nothing'],
            updates='constant',
            hint=msg,
            label=_localized['store'])

        msg = _translate("Should a response force the end of the Routine "
                         "(e.g end the trial)?")
        self.params['forceEndRoutine'] = Param(
            forceEndRoutine, valType='bool', allowedTypes=[],
            updates='constant',
            hint=msg,
            label=_localized['forceEndRoutine'])

        msg = _translate("Do you want to save the response as "
                         "correct/incorrect?")
        self.params['storeCorrect'] = Param(
            storeCorrect, valType='bool', allowedTypes=[],
            updates='constant',
            hint=msg,
            label=_localized['storeCorrect'])

        msg = _translate(
            "What is the 'correct' key? Might be helpful to add a "
            "correctAns column and use $correctAns to compare to the key "
            "press.")
        self.params['correctAns'] = Param(
            correctAns, valType='str', allowedTypes=[],
            updates='constant',
            hint=msg,
            label=_localized['correctAns'])

        msg = _translate(
            "A reaction time to a visual stimulus should be based on when "
            "the screen flipped")
        self.params['syncScreenRefresh'] = Param(
            syncScreenRefresh, valType='bool',
            updates='constant',
            hint=msg,
            label=_localized['syncScreenRefresh'])
Exemple #46
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy import prefs

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))

iconFile = path.join(prefs.paths['resources'], 'base.png')
tooltip = _translate('Unknown: A component that is not known by the current '
                     'installed version of PsychoPy\n(most likely from the '
                     'future)')

# only use _localized values for label values, nothing functional:
_localized = {'name': _translate('Name')}


class UnknownComponent(BaseComponent):
    """This is used by Builder to represent a component that was not known
    by the current installed version of PsychoPy (most likely from the future).
    We want this to be loaded, represented and saved but not used in any
    script-outputs. It should have nothing but a name - other params will be
    added by the loader
    """
    def __init__(self, exp, parentName, name=''):
        self.type = 'Unknown'
        self.exp = exp  # so we can access the experiment if necess
Exemple #47
0
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from builtins import str
from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'polygon.png')
tooltip = _translate('Polygon: any regular polygon (line, triangle, square'
                     '...circle)')

# only use _localized values for label values, nothing functional:
_localized = {'nVertices': _translate('Num. vertices'),
              'fillColorSpace': _translate('Fill color-space'),
              'fillColor': _translate('Fill color'),
              'lineColorSpace': _translate('Line color-space'),
              'lineColor': _translate('Line color'),
              'lineWidth': _translate('Line width'),
              'interpolate': _translate('Interpolate'),
              'size': _translate("Size [w,h]"),
              'shape': _translate("Shape")}


class PolygonComponent(BaseVisualComponent):
    """A class for presenting grating stimuli"""
Exemple #48
0
    def __init__(
            self,
            exp,
            parentName,
            name='text',
            # effectively just a display-value
            text=_translate('Any text\n\nincluding line breaks'),
            font='Arial',
            units='from exp settings',
            bold=False,
            italic=False,
            color='white',
            colorSpace='rgb',
            opacity=1.0,
            pos=(0, 0),
            size=None,
            letterHeight=0.05,
            ori=0,
            lineSpacing=1.0,
            padding=None,  # gap between box and text
            startType='time (s)',
            startVal=0.0,
            anchor='center',
            stopType='duration (s)',
            stopVal=1.0,
            startEstim='',
            durationEstim='',
            languageStyle='LTR',
            fillColor=None,
            borderColor=None,
            flipHoriz=False,
            flipVert=False,
            editable=False,
            autoLog=True):
        super(TextboxComponent, self).__init__(exp,
                                               parentName,
                                               name=name,
                                               units=units,
                                               color=color,
                                               colorSpace=colorSpace,
                                               pos=pos,
                                               ori=ori,
                                               startType=startType,
                                               startVal=startVal,
                                               stopType=stopType,
                                               stopVal=stopVal,
                                               startEstim=startEstim,
                                               durationEstim=durationEstim)
        self.type = 'Textbox'
        self.url = "http://www.psychopy.org/builder/components/text.html"
        self.order = [  # controls both tab order and params within tabs
            "font",  # Format tab
            "color",
            "fillColor",  # Color tab next
            "anchor",  # Layout tab
        ]
        # params
        _allow3 = ['constant', 'set every repeat', 'set every frame']  # list
        self.params['color'].label = _translate("Letter color")
        self.params['color'].categ = "Color"
        self.params['opacity'].categ = "Color"

        self.params['text'] = Param(
            text,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The text to be displayed"),
            label=_localized['text'])
        self.params['font'] = Param(
            font,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("The font name (e.g. Comic Sans)"),
            label=_localized['font'],
            categ='Format')
        self.params['letterHeight'] = Param(
            letterHeight,
            valType='code',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],  # copy the list
            hint=_translate("Specifies the height of the letter (the width"
                            " is then determined by the font)"),
            label=_localized['letterHeight'])
        self.params['flipHoriz'] = Param(
            flipHoriz,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            hint=_translate("horiz = left-right reversed; vert = up-down"
                            " reversed; $var = variable"),
            label=_localized['flipHorizontal'])
        self.params['flipVert'] = Param(
            flipVert,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            hint=_translate("horiz = left-right reversed; vert = up-down"
                            " reversed; $var = variable"),
            label=_localized['flipVertical'])
        self.params['languageStyle'] = Param(
            languageStyle,
            valType='str',
            allowedVals=['LTR', 'RTL', 'Arabic'],
            hint=_translate(
                "Handle right-to-left (RTL) languages and Arabic reshaping"),
            label=_localized['languageStyle'],
            categ='Layout')
        self.params['italic'] = Param(
            italic,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            hint=_translate("Should text be italic?"),
            label=_localized['italic'],
            categ='Format')
        self.params['bold'] = Param(bold,
                                    valType='bool',
                                    allowedTypes=[],
                                    updates='constant',
                                    hint=_translate("Should text be bold?"),
                                    label=_localized['bold'],
                                    categ='Format')
        self.params['lineSpacing'] = Param(
            lineSpacing,
            valType='num',
            allowedTypes=[],
            updates='constant',
            hint=_translate("Defines the space between lines"),
            label=_localized['lineSpacing'],
            categ='Format')
        self.params['padding'] = Param(
            padding,
            valType='code',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],
            hint=_translate(
                "Defines the space between text and the textbox border"),
            label=_localized['padding'],
            categ='Layout')
        self.params['anchor'] = Param(
            anchor,
            valType='str',
            allowedVals=[
                'center',
                'top-center',
                'bottom-center',
                'center-left',
                'center-right',
                'top-left',
                'top-right',
                'bottom-left',
                'bottom-right',
            ],
            updates='constant',
            hint=_translate(
                "Should text anchor to the top, center or bottom of the box?"),
            label=_localized['anchor'],
            categ='Layout')
        self.params['fillColor'] = Param(
            fillColor,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],
            hint=_translate("Textbox background colour"),
            label=_localized['fillColor'],
            categ='Color')
        self.params['borderColor'] = Param(
            borderColor,
            valType='str',
            allowedTypes=[],
            updates='constant',
            allowedUpdates=_allow3[:],
            hint=_translate("Textbox border colour"),
            label=_localized['borderColor'],
            categ='Color')
        self.params['editable'] = Param(
            editable,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            hint=_translate("Should textbox be editable?"),
            label=_localized['editable'])
        self.params['autoLog'] = Param(
            autoLog,
            valType='bool',
            allowedTypes=[],
            updates='constant',
            hint=_translate(
                'Automatically record all changes to this in the log file'),
            label=_localized['autoLog'],
            categ='Data')

        for param in ('ori', 'units', 'flipHoriz', 'flipVert'):
            self.params[param].categ = 'Layout'
        for param in ('colorSpace', ):
            self.params[param].categ = 'Color'
Exemple #49
0
    fullPath = os.path.join(thisFolder, relPath)
    with open(fullPath, "r") as f:
        txt = f.read()
    return txt


# used when writing scripts and in namespace:
_numpyImports = ['sin', 'cos', 'tan', 'log', 'log10', 'pi', 'average',
                 'sqrt', 'std', 'deg2rad', 'rad2deg', 'linspace', 'asarray']
_numpyRandomImports = ['random', 'randint', 'normal', 'shuffle']

# this is not a standard component - it will appear on toolbar not in
# components panel

# only use _localized values for label values, nothing functional:
_localized = {'expName': _translate("Experiment name"),
              'Show info dlg':  _translate("Show info dialog"),
              'Enable Escape':  _translate("Enable Escape key"),
              'Experiment info':  _translate("Experiment info"),
              'Data filename':  _translate("Data filename"),
              'Full-screen window':  _translate("Full-screen window"),
              'Window size (pixels)':  _translate("Window size (pixels)"),
              'Screen': _translate('Screen'),
              'Monitor':  _translate("Monitor"),
              'color': _translate("Color"),
              'colorSpace':  _translate("Color space"),
              'Units':  _translate("Units"),
              'blendMode':   _translate("Blend mode"),
              'Show mouse':  _translate("Show mouse"),
              'Save log file':  _translate("Save log file"),
              'Save wide csv file':
Exemple #50
0
    def __init__(self, exp, parentName,
                 name='var1', startExpValue = '',
                 startRoutineValue='',
                 startFrameValue=''):

        super().__init__(exp, parentName, name)

        categories = ['Custom']
        self.type = 'Variable'
        self.url = "http://www.psychopy.org/builder/components/variable.html"
        self.order += ['startExpValue', 'saveStartExp', 'startRoutineValue', 'saveStartRoutine', 'startFrameValue',
                       'saveFrameValue', 'saveEndRoutine', 'saveEndExp']

        # set parameters
        hnt = _translate("The start value. A variable can be set to any value.")
        self.params['startExpValue'] = Param(
            startExpValue, valType='code', allowedTypes=[], updates='constant',
            hint=hnt,
            label=_localized['startExpValue'])
        hnt = _translate("Set the value for the beginning of each routine.")
        self.params['startRoutineValue'] = Param(
            startRoutineValue, valType='code', allowedTypes=[], updates='constant',
            hint=hnt,
            label=_localized['startRoutineValue'])
        hnt = _translate("Set the value for the beginning of every screen refresh.")
        self.params['startFrameValue'] = Param(
            startFrameValue, valType='code', allowedTypes=[],
            hint=hnt,
            label=_localized['startFrameValue'])
        # Save options
        hnt = _translate('Save the experiment start value in data file.')
        self.params['saveStartExp'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveStartExp'],
            categ='Save')
        hnt = _translate('Save the experiment end value in data file.')
        self.params['saveEndExp'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveEndExp'],
            categ='Save')
        hnt = _translate('Save the routine start value in data file.')
        self.params['saveStartRoutine'] = Param(
            False, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveStartRoutine'],
            categ='Save')
        hnt = _translate('Save the routine end value in data file.')
        self.params['saveEndRoutine'] = Param(
            True, valType='bool',
            updates='constant',
            hint=hnt,
            label=_localized['saveEndRoutine'],
            categ='Save')
        hnt = _translate('Save choice of frame value in data file.')
        self.params['saveFrameValue'] = Param(
            'never', valType='str',
            allowedVals=['first', 'last', 'all', 'never'],
            updates='constant',
            hint=hnt,
            label=_localized['saveFrameValue'],
            categ='Save')
Exemple #51
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'envgrating.png')
tooltip = _translate('Envelope Grating: present cyclic textures including 2nd order envelope stimuli, prebuilt or from a '
                     'file')

# only use _localized values for label values, nothing functional:
_localized = {'carrier': _translate('Carrier texture'),
              'ori': _translate('Carrier Orientation'),
              'mask': _translate('Mask'),
              'sf': _translate('Carrier spatial frequency'),
              'phase': _translate('Carrier phase (in cycles)'),
              'contrast': _translate('Carrier contrast'),
              'texture resolution': _translate('Texture resolution'),
              'interpolate': _translate('Interpolate'),
              'envelope': _translate('Envelope texture'),
              'envsf':_translate('Envelope spatial frequency'),
              'envori':_translate('Envelope orientation'),
              'envphase':_translate('Envelope phase'),
              'moddepth':_translate('Envelope modulation depth'),
Exemple #52
0
# Part of the PsychoPy library
# Copyright (C) 2015 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

# Author: Jeremy R. Gray, 2012

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'microphone.png')
tooltip = _translate('Microphone: basic sound capture (fixed onset & '
                     'duration), okay for spoken words')

_localized = {'stereo': _translate('Stereo')}


class MicrophoneComponent(BaseComponent):
    """An event class for capturing short sound stimuli"""
    categories = ['Responses']

    def __init__(self, exp, parentName, name='mic_1',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=2.0, startEstim='',
                 durationEstim='', stereo=False):
        super(MicrophoneComponent, self).__init__(
            exp, parentName, name=name,
            startType=startType, startVal=startVal,
Exemple #53
0
"""
Part of the PsychoPy library
Copyright (C) 2018 Jonathan Peirce
Distributed under the terms of the GNU General Public License (GPL).
"""

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseComponent, Param, getInitVals, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'sound.png')
tooltip = _translate('Sound: play recorded files or generated sounds')

# only use _localized values for label values, nothing functional:
_localized = {'sound': _translate('Sound'), 'volume': _translate('Volume')}


class SoundComponent(BaseComponent):
    """An event class for presenting sound stimuli"""
    categories = ['Stimuli']

    def __init__(self, exp, parentName, name='sound_1', sound='A', volume=1,
                 startType='time (s)', startVal='0.0',
                 stopType='duration (s)', stopVal='1.0',
                 startEstim='', durationEstim=''):
        super(SoundComponent, self).__init__(
            exp, parentName, name,
Exemple #54
0
    def __init__(self,
                 exp,
                 parentName,
                 name='joystick',
                 startType='time (s)',
                 startVal=0.0,
                 stopType='duration (s)',
                 stopVal='',
                 startEstim='',
                 durationEstim='',
                 save='final',
                 forceEndRoutineOnPress="any click",
                 timeRelativeTo='joystick onset',
                 deviceNumber='0',
                 allowedButtons=''):
        super(JoystickComponent, self).__init__(exp,
                                                parentName,
                                                name=name,
                                                startType=startType,
                                                startVal=startVal,
                                                stopType=stopType,
                                                stopVal=stopVal,
                                                startEstim=startEstim,
                                                durationEstim=durationEstim)

        self.type = 'Joystick'
        self.url = "http://www.psychopy.org/builder/components/joystick.html"
        self.exp.requirePsychopyLibs(['event'])
        self.categories = ['Inputs']

        self.order = [
            'forceEndRoutineOnPress', 'saveJoystickState', 'timeRelativeTo',
            'clickable', 'saveParamsClickable', 'deviceNumber',
            'allowedButtons'
        ]

        # params
        msg = _translate(
            "How often should the joystick state (x,y,buttons) be stored? "
            "On every video frame, every click or just at the end of the "
            "Routine?")
        self.params['saveJoystickState'] = Param(
            save,
            valType='str',
            categ='Data',
            allowedVals=['final', 'on click', 'every frame', 'never'],
            hint=msg,
            label=_localized['saveJoystickState'])

        msg = _translate("Should a button press force the end of the routine"
                         " (e.g end the trial)?")
        if forceEndRoutineOnPress is True:
            forceEndRoutineOnPress = 'any click'
        elif forceEndRoutineOnPress is False:
            forceEndRoutineOnPress = 'never'
        self.params['forceEndRoutineOnPress'] = Param(
            forceEndRoutineOnPress,
            valType='str',
            categ='Basic',
            allowedVals=['never', 'any click', 'valid click'],
            updates='constant',
            hint=msg,
            label=_localized['forceEndRoutineOnPress'])

        msg = _translate("What should the values of joystick.time should be "
                         "relative to?")
        self.params['timeRelativeTo'] = Param(
            timeRelativeTo,
            valType='str',
            categ='Data',
            allowedVals=['joystick onset', 'experiment', 'routine'],
            updates='constant',
            hint=msg,
            label=_localized['timeRelativeTo'])

        msg = _translate('A comma-separated list of your stimulus names that '
                         'can be "clicked" by the participant. '
                         'e.g. target, foil')
        self.params['clickable'] = Param('',
                                         valType='code',
                                         categ='Data',
                                         updates='constant',
                                         hint=msg,
                                         label=_localized['Clickable stimuli'])

        msg = _translate(
            'The params (e.g. name, text), for which you want '
            'to store the current value, for the stimulus that was'
            '"clicked" by the joystick. Make sure that all the '
            'clickable objects have all these params.')
        self.params['saveParamsClickable'] = Param(
            'name,',
            valType='code',
            categ='Data',
            updates='constant',
            allowedUpdates=[],
            hint=msg,
            label=_localized['Store params for clicked'])

        msg = _translate('Device number, if you have multiple devices which'
                         ' one do you want (0, 1, 2...)')

        self.params['deviceNumber'] = Param(deviceNumber,
                                            valType='code',
                                            allowedTypes=[],
                                            categ='Hardware',
                                            updates='constant',
                                            allowedUpdates=[],
                                            hint=msg,
                                            label=_localized['deviceNumber'])

        msg = _translate(
            'Buttons to be read (blank for any) numbers separated by '
            'commas')

        self.params['allowedButtons'] = Param(
            allowedButtons,
            valType='code',
            allowedTypes=[],
            categ='Data',
            updates='constant',
            allowedUpdates=[],
            hint=msg,
            label=_localized['allowedButtons'])
Exemple #55
0
#!/usr/bin/env python
# -*- coding: utf-8 -*-

# Part of the PsychoPy library
# Copyright (C) 2018 Jonathan Peirce
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, getInitVals, Param, _translate

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'movie.png')
tooltip = _translate('Movie: play movie files')

# only use _localized values for label values, nothing functional:
_localized = {'movie': _translate('Movie file'),
              'forceEndRoutine': _translate('Force end of Routine'),
              'backend': _translate('backend'),
              'No audio': _translate('No audio')}


class MovieComponent(BaseVisualComponent):
    """An event class for presenting movie-based stimuli"""

    def __init__(self, exp, parentName, name='movie', movie='',
                 units='from exp settings',
                 pos=(0, 0), size='', ori=0,
                 startType='time (s)', startVal=0.0,
Exemple #56
0
    def __init__(self, exp, parentName, name='grating', image='sin',
                 mask='None', sf='None', interpolate='linear',
                 units='from exp settings', color='$[1,1,1]', colorSpace='rgb',
                 pos=(0, 0), size=(0.5, 0.5), ori=0, phase=0.0, texRes='128',
                 startType='time (s)', startVal=0.0,
                 stopType='duration (s)', stopVal=1.0, blendmode='avg',
                 startEstim='', durationEstim=''):
        super(GratingComponent, self).__init__(
            exp, parentName, name=name, units=units,
            color=color, colorSpace=colorSpace,
            pos=pos, size=size, ori=ori,
            startType=startType, startVal=startVal,
            stopType=stopType, stopVal=stopVal,
            startEstim=startEstim, durationEstim=durationEstim)

        self.type = 'Grating'
        self.url = "http://www.psychopy.org/builder/components/grating.html"
        self.order = ['tex', 'mask']

        # params
        msg = _translate("The (2D) texture of the grating - can be sin, sqr,"
                         " sinXsin... or a filename (including path)")
        self.params['tex'] = Param(
            image, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['tex'], categ="Advanced")

        msg = _translate("An image to define the alpha mask (ie shape)- "
                         "gauss, circle... or a filename (including path)")
        self.params['mask'] = Param(
            mask, valType='str', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['mask'], categ="Advanced")

        msg = _translate("Spatial frequency of image repeats across the "
                         "grating in 1 or 2 dimensions, e.g. 4 or [2,3]")
        self.params['sf'] = Param(
            sf, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['sf'], categ="Advanced")

        msg = _translate("Spatial positioning of the image on the grating "
                         "(wraps in range 0-1.0)")
        self.params['phase'] = Param(
            phase, valType='code', allowedTypes=[],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['phase'], categ="Advanced")

        msg = _translate(
            "Resolution of the texture for standard ones such as sin, sqr "
            "etc. For most cases a value of 256 pixels will suffice")
        self.params['texture resolution'] = Param(
            texRes,
            valType='code', allowedVals=['32', '64', '128', '256', '512'],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['texture resolution'], categ="Advanced")

        msg = _translate("How should the image be interpolated if/when "
                         "rescaled")
        self.params['interpolate'] = Param(
            interpolate, valType='str', allowedVals=['linear', 'nearest'],
            updates='constant', allowedUpdates=[],
            hint=msg,
            label=_localized['interpolate'], categ="Advanced")

        msg = _translate("OpenGL Blendmode: avg gives traditional transparency,"
                         " add is important to combine gratings)]")
        self.params['blendmode'] = Param(
            blendmode, valType='str', allowedVals=['avg', 'add'],
            updates='constant',
            allowedUpdates=['constant', 'set every repeat', 'set every frame'],
            hint=msg,
            label=_localized['blendmode'], categ="Basic")
Exemple #57
0
from builtins import str
from past.builtins import basestring
from os import path

from psychopy.constants import PY3
from psychopy.experiment.components import Param, _translate
from psychopy.experiment.components.keyboard import KeyboardComponent
from psychopy.experiment import CodeGenerationException, valid_var_re

__author__ = 'Jon Peirce'

# abs path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'cedrusBox.png')
tooltip = _translate('Cedrus Button Box: Cedrus response boxes, using the '
                     'pyxid library provided by Cedrus')

# only use _localized values for label values, nothing functional:
_localized = {
    'deviceNumber': _translate('Device number'),
    'useBoxTimer': _translate("Use box timer")
}


class cedrusButtonBoxComponent(KeyboardComponent):
    """An event class for checking an Cedrus RBxxx button boxes
    using XID library

    This is based on keyboard component, several important differences:
    - no special response class analogous to event.BuilderKeyResponse()
    - enabled responses (active keys) are handled by the hardware device
Exemple #58
0
from os import path

from psychopy.constants import PY3
from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy.experiment import CodeGenerationException, valid_var_re
from psychopy.localization import _localized as __localized
_localized = __localized.copy()
from pkgutil import find_loader

# Check for psychtoolbox
havePTB = find_loader('psychtoolbox') is not None

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'keyboard.png')
tooltip = _translate('Keyboard: check and record keypresses')

# only use _localized values for label values, nothing functional:
_localized.update({
    'allowedKeys': _translate('Allowed keys'),
    'discard previous': _translate('Discard previous'),
    'store': _translate('Store'),
    'forceEndRoutine': _translate('Force end of Routine'),
    'storeCorrect': _translate('Store correct'),
    'correctAns': _translate('Correct answer'),
    'syncScreenRefresh': _translate('Sync timing with screen')
})


class KeyboardComponent(BaseComponent):
    """An event class for checking the keyboard at given timepoints"""
Exemple #59
0
# Part of the PsychoPy library
# Copyright (C) 2002-2018 Jonathan Peirce (C) 2019-2020 Open Science Tools Ltd.
# Distributed under the terms of the GNU General Public License (GPL).

from __future__ import absolute_import, print_function

from os import path
from psychopy.experiment.components import BaseVisualComponent, Param, getInitVals, _translate
from psychopy.localization import _localized as __localized
_localized = __localized.copy()

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'textbox.png')
tooltip = _translate('Textbox: present text stimuli but cooler')

# only use _localized values for label values, nothing functional:
_localized.update({
    'text': _translate('Text'),
    'font': _translate('Font'),
    'letterHeight': _translate('Letter height'),
    'flipHorizontal': _translate('Flip horizontal'),
    'flipVertical': _translate('Flip vertical'),
    'languageStyle': _translate('Language style'),
    'bold': _translate('Bold'),
    'italic': _translate('Italic'),
    'lineSpacing': _translate('Line Spacing'),
    'padding': _translate('Padding'),
    'anchor': _translate('Anchor'),
    'fillColor': _translate('Fill Colour'),
Exemple #60
0
from __future__ import absolute_import, print_function
from builtins import super  # provides Py3-style super() using python-future

from os import path
from psychopy.experiment.components import BaseComponent, Param, _translate
from psychopy.experiment import valid_var_re
from psychopy.experiment import CodeGenerationException, valid_var_re
from psychopy.localization import _localized as __localized
_localized = __localized.copy()
import re

# the absolute path to the folder containing this path
thisFolder = path.abspath(path.dirname(__file__))
iconFile = path.join(thisFolder, 'joystick.png')
tooltip = _translate('Joystick: query joystick position and buttons')

# only use _localized values for label values, nothing functional:
_localized.update({
    'saveJoystickState':
    _translate('Save joystick state'),
    'forceEndRoutineOnPress':
    _translate('End Routine on press'),
    'timeRelativeTo':
    _translate('Time relative to'),
    'Clickable stimuli':
    _translate('Clickable stimuli'),
    'Store params for clicked':
    _translate('Store params for clicked'),
    'deviceNumber':
    _translate('Device number'),