def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # replaces variable params with defaults inits = getInitVals(self.params) code = ("%s = visual.PatchStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr)) code += (" tex=%(image)s, mask=%(mask)s,\n" " ori=%(ori)s, pos=%(pos)s, size=%(size)s, sf=%(sf)s, phase=%(phase)s,\n" " color=%(color)s, colorSpace=%(colorSpace)s, opacity=%(opacity)s,\n" # no newline - start optional parameters " texRes=%(texture resolution)s" % inits) buff.writeIndentedLines(code) if self.params['interpolate'].val == 'linear': buff.write(", interpolate=True") else: buff.write(", interpolate=False") depth = -self.getPosInRoutine() buff.write(", depth=%.1f)\n" % depth) # finish with newline
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoPy') if self.params['wrapWidth'].val in ['', 'None', 'none']: inits['wrapWidth'] = 'None' code = ("%(name)s = visual.TextStim(win=win, " "name='%(name)s',\n" " text=%(text)s,\n" " font=%(font)s,\n" " " + unitsStr + "pos=%(pos)s, height=%(letterHeight)s, " "wrapWidth=%(wrapWidth)s, ori=%(ori)s, \n" " color=%(color)s, colorSpace=%(colorSpace)s, " "opacity=%(opacity)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz=True, ' elif flip == 'vert': flipStr = 'flipVert=True, ' elif flip: msg = ("flip value should be 'horiz' or 'vert' (no quotes)" " in component '%s'") raise ValueError(msg % self.params['name'].val) else: flipStr = '' depth = -self.getPosInRoutine() buff.writeIndented(' ' + flipStr + 'depth=%.1f);\n' % depth)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params, 'PsychoPy') code = ("{inits[name]} = visual.ImageStim(\n" " win=win,\n" " name='{inits[name]}', {units}\n" " image={inits[image]}, mask={inits[mask]},\n" " ori={inits[ori]}, pos={inits[pos]}, size={inits[size]},\n" " color={inits[color]}, colorSpace={inits[colorSpace]}, opacity={inits[opacity]},\n" " flipHoriz={inits[flipHoriz]}, flipVert={inits[flipVert]},\n" # no newline - start optional parameters " texRes={inits[texture resolution]}" .format(inits=inits, units=unitsStr)) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code)
def writeInitCode(self, buff): self._noiseNewSample="" # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.noise import NoiseStim\n") # replaces variable params with defaults and sets sample updateing flag inits = getInitVals(self.params) #for myparam in inits: # if ('noise' in myparam): # if (inits[myparam].updates in ['set every frame']): # self._forceRebuild=True #if not (inits[myparam].updates in ['constant', None, 'None']): # inits[myparam]='1' #if not (self.params['A_noiseType'].updates in ['constant', None, 'None']): # inits['A_noiseType']='Binary' #if ('rebuild_frame' in self._noiseNewSample): # print 'Warning: Rebuilding the noise sample every frame may be slow and could corrupt frame timing' # noise sample updating set to every repeat or frame will override result of parameter settings self._forceUpdateRepeat = False self._forceUpdateFrames = False self._forceUpdateSeconds = False if inits['noiseNewSample'].val in ['Repeat']: self._forceUpdateRepeat = True elif inits['noiseNewSample'].val in ['N-frames']: self._forceUpdateFrames = True elif inits['noiseNewSample'].val in ['Seconds']: self._forceUpdateSeconds = True #self._when=float(inits['Z_when'].val) #print self._when #else whenIsVariale=false #if (inits['carrier'].val in ['noise','Noise']): # inits['carrier']="%(name)s.noiseTex" %inits code = ("%s = visual.NoiseStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " noiseImage=%(noiseImage)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, " % inits + "sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + "opacity=%(opacity)s, blendmode=%(blendmode)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s,\n" % inits + " noiseType=%(noiseType)s, noiseElementSize=%(noiseElementSize)s, noiseBaseSf=%(noiseBaseSf)s,\n" %inits+ " noiseBW=%(noiseBW)s, noiseBWO=%(noiseBWO)s, noiseFractalPower=%(noiseFractalPower)s,noiseFilterLower=%(noiseFilterLower)s, noiseFilterUpper=%(noiseFilterUpper)s, noiseFilterOrder=%(noiseFilterOrder)s, noiseClip=%(noiseClip)s" %inits) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code) if not(self.params['noiseType'] in ['none', 'None']): buff.writeIndented("%(name)s.buildNoise()\n" %self.params)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params, 'PsychoPy') code = ("%s = visual.ImageStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " image=%(image)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + "opacity=%(opacity)s,\n" % inits + " flipHoriz=%(flipHoriz)s, flipVert=%(flipVert)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s" % inits) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): inits = getInitVals(self.params) noAudio = '{}'.format(inits['No audio'].val).lower() for param in inits: if inits[param] in ['', None, 'None', 'none']: inits[param] = 'undefined' code = "{name}Clock = new util.Clock();\n".format(**inits) buff.writeIndented(code) code = ("{name} = new visual.MovieStim({{\n" " win: psychoJS.window,\n" " name: '{name}',\n" " movie: {movie},\n" " units: {units},\n" " pos: {pos},\n" " size: {size},\n" " ori: {ori},\n" " opacity: {opacity},\n" " loop: false,\n" " noAudio: {noAudio},\n" " }});\n").format(name = inits['name'], movie = inits['movie'], units = inits['units'], pos = inits['pos'], size = inits['size'], ori = inits['ori'], opacity = inits['opacity'], noAudio=noAudio) buff.writeIndentedLines(code)
def writeInitCode(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = sound.Sound(%s, secs=%s)\n" % (inits['name'], inits['sound'], inits['stopVal'])) buff.writeIndented("%(name)s.setVolume(%(volume)s)\n" % (inits))
def writeRoutineStartCode(self, buff): inits = getInitVals(self.params) if inits['stopVal'] in [None, 'None', '']: buff.writeIndented("%s.setSound(%s)\n" % (inits['name'], inits['sound'])) else: buff.writeIndented("%s.setSound(%s, secs=%s)\n" % (inits['name'], inits['sound'], inits['stopVal']))
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params) if inits['size'].val in ['1.0', '1']: inits['size'].val = '[1.0, 1.0]' if self.params['shape'] == 'regular polygon...': vertices = self.params['nVertices'] else: vertices = self.params['shape'] if vertices in ['line', '2']: code = ("%s = visual.Line(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " start=(-%(size)s[0]/2.0, 0), end=(+%(size)s[0]/2.0, 0),\n" % inits) elif vertices in ['triangle', '3']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " vertices=[[-%(size)s[0]/2.0,-%(size)s[1]/2.0], [+%(size)s[0]/2.0,-%(size)s[1]/2.0], [0,%(size)s[1]/2.0]],\n" % inits) elif vertices in ['rectangle', '4']: code = ("%s = visual.Rect(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " width=%(size)s[0], height=%(size)s[1],\n" % inits) elif vertices in ['star']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s', vertices='star7',%s\n" % (inits['name'], unitsStr) + " size=%(size)s,\n" % inits) elif vertices in ['cross']: code = ("%s = visual.ShapeStim(\n" % inits['name'] + " win=win, name='%s', vertices='cross',%s\n" % (inits['name'], unitsStr) + " size=%(size)s,\n" % inits) else: code = ("%s = visual.Polygon(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " edges=%s," % str(inits['nVertices'].val) + " size=%(size)s,\n" % inits) code += (" ori=%(ori)s, pos=%(pos)s,\n" " lineWidth=%(lineWidth)s, lineColor=%(lineColor)s, lineColorSpace=%(lineColorSpace)s,\n" " fillColor=%(fillColor)s, fillColorSpace=%(fillColorSpace)s,\n" " opacity=%(opacity)s, " % inits) depth = -self.getPosInRoutine() code += "depth=%.1f, " % depth if self.params['interpolate'].val == 'linear': code += "interpolate=True)\n" else: code += "interpolate=False)\n" buff.writeIndentedLines(code)
def writeInitCode(self, buff): inits = getInitVals(self.params) # build up an initialization string for Slider(): initStr = ("{name} = visual.Slider(win=win, name='{name}',\n" " size={size}, pos={pos},\n" " labels={labels}, ticks={ticks},\n" " granularity={granularity}, style={styles},\n" " color={color}, font={font},\n" " flip={flip})\n" .format(**inits)) buff.writeIndented(initStr)
def writeInitCode(self, buff): self._noiseNewSample="" # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.noise import NoiseStim\n") # replaces variable params with defaults and sets sample updating flag inits = getInitVals(self.params) self._forceUpdateRepeat = False self._forceUpdateFrames = False self._forceUpdateSeconds = False if inits['noiseNewSample'].val in ['Repeat']: self._forceUpdateRepeat = True elif inits['noiseNewSample'].val in ['N-frames']: self._forceUpdateFrames = True elif inits['noiseNewSample'].val in ['Seconds']: self._forceUpdateSeconds = True code = ("%s = visual.NoiseStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " noiseImage=%(noiseImage)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, sf=%(sf)s,\n" % inits + " phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + " opacity=%(opacity)s, blendmode=%(blendmode)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s, filter=%(filter)s,\n" % inits + " noiseType=%(noiseType)s, noiseElementSize=%(noiseElementSize)s, \n" %inits + " noiseBaseSf=%(noiseBaseSf)s, noiseBW=%(noiseBW)s,\n" %inits + " noiseBWO=%(noiseBWO)s, noiseOri=%(noiseOri)s,\n" %inits + " noiseFractalPower=%(noiseFractalPower)s,noiseFilterLower=%(noiseFilterLower)s,\n" %inits + " noiseFilterUpper=%(noiseFilterUpper)s, noiseFilterOrder=%(noiseFilterOrder)s,\n" %inits + " noiseClip=%(noiseClip)s, imageComponent=%(imageComponent)s" %inits) #if self.params['filter'].val == 'True': # code += ", filter=True" #else: # code += ", filter=False" if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code) if not(self.params['noiseType'] in ['none', 'None']): buff.writeIndented("%(name)s.buildNoise()\n" %self.params)
def writeInitCode(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if '$' in inits['stopVal'].val: inits['stopVal'].val = -1 else: if inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = sound.Sound(%s, secs=%s, stereo=%s)\n" % (inits['name'], inits['sound'], inits['stopVal'], self.exp.settings.params['Force stereo'])) buff.writeIndented("%(name)s.setVolume(%(volume)s)\n" % (inits))
def writeInitCode(self, buff): inits = getInitVals(self.params) # build up an initialization string for Form(): initStr = ("win.allowStencil = True\n" "{name} = visual.Form(win=win, name='{name}',\n" " items={Items},\n" " textHeight={Text Height},\n" " randomize={Randomize},\n" " size={Size},\n" " pos={Pos},\n" " itemPadding={Item Padding})\n".format(**inits)) buff.writeIndented(initStr)
def _writeCreationCodeJS(self, buff, useInits): # If we're in writeInitCode then we need to convert params to initVals # because some (variable) params haven't been created yet. if useInits: inits = getInitVals(self.params) else: inits = self.params if self.params['units'].val == 'from exp settings': unitsStr = "'height'" logging.warning("{units} not a valid screen unit for online studies. Switching {name} units to 'height'." .format(units=self.params['units'], name=self.params['name'])) else: unitsStr = "%(units)s" % self.params noAudio = '{}'.format(inits['No audio'].val).lower() loop = '{}'.format(inits['loop'].val).lower() if useInits: for param in inits: if inits[param] in ['', None, 'None', 'none']: inits[param] = 'undefined' code = "{name}Clock = new util.Clock();\n".format(**inits) buff.writeIndented(code) code = ("{name} = new visual.MovieStim({{\n" " win: psychoJS.window,\n" " name: '{name}',\n" " movie: {movie},\n" " units: {units},\n" " pos: {pos},\n" " size: {size},\n" " ori: {ori},\n" " opacity: {opacity},\n" " loop: {loop},\n" " noAudio: {noAudio},\n" " }});\n").format(name=inits['name'], movie=inits['movie'], units=unitsStr, pos=inits['pos'], size=inits['size'], ori=inits['ori'], loop=loop, opacity=inits['opacity'], noAudio=noAudio) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if '$' in inits['stopVal'].val: inits['stopVal'].val = -1 elif inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = new Sound({\n" " win: psychoJS.window,\n" " value: %s,\n" " secs: %s,\n" " });\n" % (inits['name'], inits['sound'], inits['stopVal'])) buff.writeIndented("%(name)s.setVolume(%(volume)s);\n" % (inits))
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init inits = getInitVals(self.params) code = ("%(name)s = visual.Aperture(\n" " win=win, name='%(name)s',\n" " " + unitsStr + "size=%(size)s, pos=%(pos)s)\n" "%(name)s.disable() # disable until its actually used\n") buff.writeIndentedLines(code % inits)
def writeInitCode(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if '$' in inits['stopVal'].val: inits['stopVal'].val = -1 else: if inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = sound.Sound(%s, secs=%s, stereo=%s, hamming=%s,\n" " name='%s')\n" % (inits['name'], inits['sound'], inits['stopVal'], self.exp.settings.params['Force stereo'], inits['hamming'], inits['name'])) buff.writeIndented("%(name)s.setVolume(%(volume)s)\n" % (inits))
def writeInitCodeJS(self, buff): inits = getInitVals(self.params, target="PsychoJS") # Write code code = ( "%(name)s = new hardware.Camera({\n" " name:'%(name)s',\n" " win: psychoJS.window," "});\n" "// Get permission from participant to access their camera\n" "await %(name)s.authorize()\n" "// Switch on %(name)s\n" "await %(name)s.open()\n" "\n" ) buff.writeIndentedLines(code % inits)
def writeInitCodeJS(self, buff): # replaces variable params with sensible defaults inits = getInitVals(self.params) if '$' in inits['stopVal'].val: inits['stopVal'].val = -1 elif inits['stopVal'].val in ['', None, 'None']: inits['stopVal'].val = -1 elif float(inits['stopVal'].val) > 2: inits['stopVal'].val = -1 buff.writeIndented("%s = new sound.Sound({\n" " win: psychoJS.window,\n" " value: %s,\n" " secs: %s,\n" " });\n" % (inits['name'], inits['sound'], inits['stopVal'])) buff.writeIndented("%(name)s.setVolume(%(volume)s);\n" % (inits))
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 writeInitCode(self, buff): self._noiseNewSample="" # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.noise import NoiseStim\n") # replaces variable params with defaults and sets sample updating flag inits = getInitVals(self.params) self._forceUpdateRepeat = False self._forceUpdateFrames = False self._forceUpdateSeconds = False if inits['noiseNewSample'].val in ['Repeat']: self._forceUpdateRepeat = True elif inits['noiseNewSample'].val in ['N-frames']: self._forceUpdateFrames = True elif inits['noiseNewSample'].val in ['Seconds']: self._forceUpdateSeconds = True code = ("%s = visual.NoiseStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " noiseImage=%(noiseImage)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, sf=%(sf)s,\n" % inits + " phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + " opacity=%(opacity)s, blendmode=%(blendmode)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s, filter=%(filter)s,\n" % inits + " noiseType=%(noiseType)s, noiseElementSize=%(noiseElementSize)s, \n" %inits + " noiseBaseSf=%(noiseBaseSf)s, noiseBW=%(noiseBW)s,\n" %inits + " noiseBWO=%(noiseBWO)s, noiseOri=%(noiseOri)s,\n" %inits + " noiseFractalPower=%(noiseFractalPower)s,noiseFilterLower=%(noiseFilterLower)s,\n" %inits + " noiseFilterUpper=%(noiseFilterUpper)s, noiseFilterOrder=%(noiseFilterOrder)s,\n" %inits + " noiseClip=%(noiseClip)s, imageComponent=%(imageComponent)s" %inits) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code) if not(self.params['noiseType'] in ['none', 'None']): buff.writeIndented("%(name)s.buildNoise()\n" %self.params)
def writeInitCodeJS(self, buff): inits = getInitVals(self.params) for param in inits: if inits[param].val in ['', None, 'None', 'none']: inits[param].val = 'undefined' # Check for unsupported units if inits['units'].val == 'from exp settings': inits['units'] = copy.copy(self.exp.settings.params['Units']) if inits['units'].val in ['cm', 'deg', 'degFlatPos', 'degFlat']: msg = ("'{units}' units for your '{name}' Slider are not currently supported for PsychoJS: " "switching units to 'height'. Note, this will affect the size and positioning of '{name}'.") logging.warning(msg.format(units=inits['units'].val, name=inits['name'].val)) inits['units'].val = "height" boolConverter = {False: 'false', True: 'true'} sliderStyles = {'slider': 'SLIDER', '()': 'RATING', 'rating': 'RATING', 'radio': 'RADIO', 'labels45': 'LABELS_45', 'whiteOnBlack': 'WHITE_ON_BLACK', 'triangleMarker': 'TRIANGLE_MARKER'} # If no style given, set default 'rating' as list if len(inits['styles'].val) == 0: inits['styles'].val = ['rating'] # reformat styles for JS inits['styles'].val = ', '.join(["visual.Slider.Style.{}". format(sliderStyles[style]) for style in inits['styles'].val]) # add comma so is treated as tuple in py2js and converted to list, as required inits['styles'].val += ',' inits['styles'].val = py2js.expression2js(inits['styles'].val) # build up an initialization string for Slider(): initStr = ("{name} = new visual.Slider({{\n" " win: psychoJS.window, name: '{name}',\n" " size: {size}, pos: {pos}, units: {units},\n" " labels: {labels}, ticks: {ticks},\n" " granularity: {granularity}, style: {styles},\n" " color: new util.Color({color}), \n" " fontFamily: {font}, bold: true, italic: false, \n" ).format(**inits) initStr += (" flip: {flip},\n" "}});\n\n").format(flip=boolConverter[inits['flip'].val]) buff.writeIndentedLines(initStr)
def writeInitCode(self, buff): inits = getInitVals(self.params) # check units if inits['units'].val == 'from exp settings': inits['units'].val = None inits['depth'] = -self.getPosInRoutine() # build up an initialization string for Slider(): initStr = ("{name} = visual.Slider(win=win, name='{name}',\n" " size={size}, pos={pos}, units={units},\n" " labels={labels}, ticks={ticks},\n" " granularity={granularity}, style={styles},\n" " color={color}, font={font},\n" " flip={flip}, depth={depth})\n".format(**inits)) buff.writeIndented(initStr)
def _writeCreationCode(self, buff, useInits): # This will be called by either self.writeInitCode() or # self.writeRoutineStartCode() # # The reason for this is that moviestim is actually created fresh each # time the movie is loaded. # # leave units blank if not needed if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # If we're in writeInitCode then we need to convert params to initVals # because some (variable) params haven't been created yet. if useInits: params = getInitVals(self.params) else: params = self.params if self.params['backend'].val == 'moviepy': code = ("%s = visual.MovieStim3(\n" % params['name'] + " win=win, name='%s',%s\n" % (params['name'], unitsStr) + " noAudio = %(No audio)s,\n" % params) elif self.params['backend'].val == 'avbin': code = ("%s = visual.MovieStim(\n" % params['name'] + " win=win, name='%s',%s\n" % (params['name'], unitsStr)) else: code = ("%s = visual.MovieStim2(\n" % params['name'] + " win=win, name='%s',%s\n" % (params['name'], unitsStr) + " noAudio = %(No audio)s,\n" % params) code += (" filename=%(movie)s,\n" " ori=%(ori)s, pos=%(pos)s, opacity=%(opacity)s,\n" " loop=%(loop)s,\n" % params) buff.writeIndentedLines(code) if self.params['size'].val != '': buff.writeIndented(" size=%(size)s,\n" % params) depth = -self.getPosInRoutine() code = (" depth=%.1f,\n" " )\n") buff.writeIndentedLines(code % depth)
def _writeCreationCodeJS(self, buff, useInits): # If we're in writeInitCode then we need to convert params to initVals # because some (variable) params haven't been created yet. if useInits: inits = getInitVals(self.params) else: inits = self.params if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params noAudio = '{}'.format(inits['No audio'].val).lower() loop = '{}'.format(inits['loop'].val).lower() if useInits: for param in inits: if inits[param] in ['', None, 'None', 'none']: inits[param] = 'undefined' code = "{name}Clock = new util.Clock();\n".format(**inits) buff.writeIndented(code) code = ("{name} = new visual.MovieStim({{\n" " win: psychoJS.window,\n" " name: '{name}', {units}\n" " movie: {movie},\n" " pos: {pos},\n" " size: {size},\n" " ori: {ori},\n" " opacity: {opacity},\n" " loop: {loop},\n" " noAudio: {noAudio},\n" " }});\n").format(name=inits['name'], movie=inits['movie'], units=unitsStr, pos=inits['pos'], size=inits['size'], ori=inits['ori'], loop=loop, opacity=inits['opacity'], noAudio=noAudio) buff.writeIndentedLines(code)
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 writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.secondorder import EnvelopeGrating\n") # replaces variable params with defaults and sets sample updating flag inits = getInitVals(self.params) code = ( "%s = visual.EnvelopeGrating(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " carrier=%(carrier)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s,\n" % inits + " sf=%(sf)s, phase=%(phase)s, anchor=%(anchor)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s,\n " % inits + " opacity=%(opacity)s, contrast=%(contrast)s,\n" % inits + " texRes=%(texture resolution)s, envelope=%(envelope)s,\n" % inits + " envori=%(envori)s, envsf=%(envsf)s,\n" % inits + " envphase=%(envphase)s, power=%(power)s,\n" % inits + " moddepth=%(moddepth)s, blendmode=%(blendmode)s" % inits) if self.params['beat'].val in ['Y', 'y', 'Yes', 'yes', 'True', 'true']: code += ", beat=True" elif self.params['beat'].val in [ 'N', 'n', 'No', 'no', 'False', 'false' ]: code += ", beat=False" else: code += ", beat=%(beat)s" % inits if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth code += "if sys.version[0]=='3' and np.min(win.gamma) == None:\n" code += " logging.warning('Envelope grating in use with no gamma set. Unless you have hardware gamma correction the image will be distorted.')\n" code += "elif np.min(win.gamma) < 1.01:\n" code += " logging.warning('Envelope grating in use with window gamma <= 1.0 or no gamma set at all. Unless you have hardware gamma correction the image will be distorted.')\n" buff.writeIndentedLines(code)
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 = ( "clipFilename = 'recording_%(name)s_%%s.%(outputType)s' %% tag\n" ) buff.writeIndentedLines(code % inits) code = ( "# if there's more than 1 clip with this tag, append a counter for all beyond the first\n" "if i > 0:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "clipFilename += '_%%s' %% i" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ( "clip.save(os.path.join(%(name)sRecFolder, clipFilename))\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-2, relative=True)
def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = " units : undefined, \n" else: unitsStr = " units : %(units)s, \n" % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoJS') # check for NoneTypes for param in inits: if inits[param] in [None, 'None', '']: inits[param].val = 'undefined' if param == 'text': inits[param].val = "''" code = ("%(name)s = new visual.TextStim({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" " text: %(text)s,\n" " font: %(font)s,\n" + unitsStr + " pos: %(pos)s, height: %(letterHeight)s," " wrapWidth: %(wrapWidth)s, ori: %(ori)s,\n" " color: new util.Color(%(color)s)," " opacity: %(opacity)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz : true, ' elif flip == 'vert': flipStr = 'flipVert : true, ' elif flip: msg = ("flip value should be 'horiz' or 'vert' (no quotes)" " in component '%s'") raise ValueError(msg % self.params['name'].val) else: flipStr = '' depth = -self.getPosInRoutine() code = (" %sdepth: %.1f \n" "});\n\n" % (flipStr, depth)) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = " units: undefined, \n" else: unitsStr = " units: %(units)s, \n" % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoJS') # check for NoneTypes for param in inits: if inits[param] in [None, 'None', '']: inits[param].val = 'undefined' if param == 'text': inits[param].val = "" code = ("%(name)s = new visual.TextStim({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" " text: %(text)s,\n" " font: %(font)s,\n" + unitsStr + " pos: %(pos)s, height: %(letterHeight)s," " wrapWidth: %(wrapWidth)s, ori: %(ori)s,\n" " color: new util.Color(%(color)s)," " opacity: %(opacity)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz : true, ' elif flip == 'vert': flipStr = 'flipVert : true, ' elif flip and not flip == "None": msg = ("flip value should be 'horiz' or 'vert' (no quotes)" " in component '%s'") raise ValueError(msg % self.params['name'].val) else: flipStr = '' depth = -self.getPosInRoutine() code = (" %sdepth: %.1f \n" "});\n\n" % (flipStr, depth)) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "units : undefined, " else: unitsStr = "units : %(units)s, " % self.params # replace variable params with defaults inits = getInitVals(self.params, 'PsychoJS') for paramName in inits: val = inits[paramName].val if val is True: inits[paramName] = 'true' elif val is False: inits[paramName] = 'false' elif val in [None, 'None', 'none', '', 'sin']: inits[paramName].valType = 'code' inits[paramName].val = 'undefined' code = ("{inits[name]} = new visual.ImageStim({{\n" " win : psychoJS.window,\n" " name : '{inits[name]}', {units}\n" " image : {inits[image]}, mask : {inits[mask]},\n" " ori : {inits[ori]}, pos : {inits[pos]}, size : {inits[size]},\n" " color : new util.Color({inits[color]}), opacity : {inits[opacity]},\n" " flipHoriz : {inits[flipHoriz]}, flipVert : {inits[flipVert]},\n" # no newline - start optional parameters " texRes : {inits[texture resolution]}" .format(inits=inits, units=unitsStr)) if self.params['interpolate'].val == 'linear': code += ", interpolate : true" else: code += ", interpolate : false" depth = -self.getPosInRoutine() code += (", depth : %.1f \n" "});\n" % (depth) ) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): inits = getInitVals(self.params) for param in inits: if inits[param].val in ['', None, 'None', 'none']: inits[param].val = 'undefined' boolConverter = {False: 'false', True: 'true'} sliderStyles = { 'slider': 'SLIDER', '()': 'RATING', 'rating': 'RATING', 'radio': 'RADIO', 'labels45': 'LABELS_45', 'whiteOnBlack': 'WHITE_ON_BLACK', 'triangleMarker': 'TRIANGLE_MARKER' } # If no style given, set default 'rating' as list if len(inits['styles'].val) == 0: inits['styles'].val = ['rating'] # reformat styles for JS inits['styles'].val = ', '.join([ "visual.Slider.Style.{}".format(sliderStyles[style]) for style in inits['styles'].val ]) # add comma so is treated as tuple in py2js and converted to list, as required inits['styles'].val += ',' inits['styles'].val = py2js.expression2js(inits['styles'].val) # build up an initialization string for Slider(): initStr = ( "{name} = new visual.Slider({{\n" " win: psychoJS.window, name: '{name}',\n" " size: {size}, pos: {pos},\n" " labels: {labels}, ticks: {ticks},\n" " granularity: {granularity}, style: {styles},\n" " color: new util.Color({color}), \n" " fontFamily: {font}, bold: true, italic: false, \n").format( **inits) initStr += (" flip: {flip},\n" "}});\n\n").format(flip=boolConverter[inits['flip'].val]) buff.writeIndentedLines(initStr)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params) depth = -self.getPosInRoutine() code = ("%s = visual.DotStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " nDots=%(nDots)s, dotSize=%(dotSize)s,\n" % inits + " speed=%(speed)s, dir=%(dir)s, coherence=%(coherence)s,\n" % inits + " fieldPos=%(fieldPos)s, fieldSize=%(fieldSize)s, fieldAnchor=%(anchor)s, fieldShape=%(fieldShape)s,\n" % inits + " signalDots=%(signalDots)s, noiseDots=%(noiseDots)s,dotLife=%(dotLife)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, opacity=%(opacity)s,\n" % inits + " depth=%.1f)\n" % depth) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): inits = getInitVals(self.params, 'PsychoJS') code = ("%(name)s = new visual.ButtonStim({\n") buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ("win: psychoJS.window,\n" "name: '%(name)s',\n" "text: %(text)s,\n" "fillColor: %(fillColor)s,\n" "borderColor: %(borderColor)s,\n" "color: %(color)s,\n" "colorSpace: %(colorSpace)s,\n" "pos: %(pos)s,\n" "letterHeight: %(letterHeight)s,\n" "size: %(size)s\n") buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = ("});\n" "%(name)s.clock = new util.Clock();\n\n") buff.writeIndentedLines(code % inits)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params) depth = -self.getPosInRoutine() code = ("%s = visual.DotStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " nDots=%(nDots)s, dotSize=%(dotSize)s,\n" % inits + " speed=%(speed)s, dir=%(dir)s, coherence=%(coherence)s,\n" % inits + " fieldPos=%(fieldPos)s, fieldSize=%(fieldSize)s,fieldShape=%(fieldShape)s,\n" % inits + " signalDots=%(signalDots)s, noiseDots=%(noiseDots)s,dotLife=%(dotLife)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, opacity=%(opacity)s,\n" % inits + " depth=%.1f)\n" % depth) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # JS code does not use Brush class params = getInitVals(self.params) code = ("{name} = {{}};\n" "get{name} = function() {{\n" " return ( new visual.ShapeStim({{\n" " win: psychoJS.window,\n" " vertices: [[0, 0]],\n" " lineWidth: {lineWidth},\n" " lineColor: new util.Color({lineColor}),\n" " opacity: {opacity},\n" " closeShape: false,\n" " autoLog: false\n" " }}))\n" "}}\n\n").format(name=params['name'], lineWidth=params['lineWidth'], lineColor=params['lineColor'], opacity=params['opacity']) buff.writeIndentedLines(code) # add reset function code = ("{name}Reset = function() {{\n" " if ({name}Shapes.length > 0) {{\n" " for (let shape of {name}Shapes) {{\n" " shape.setAutoDraw(false);\n" " }}\n" " }}\n" " {name}AtStartPoint = false;\n" " {name}Shapes = [];\n" " {name}CurrentShape = -1;\n" "}}\n\n").format(name=params['name']) buff.writeIndentedLines(code) # Define vars for drawing code = ("{name}CurrentShape = -1;\n" "{name}BrushPos = [];\n" "{name}Pointer = new core.Mouse({{win: psychoJS.window}});\n" "{name}AtStartPoint = false;\n" "{name}Shapes = [];\n").format(name=params['name']) buff.writeIndentedLines(code)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.secondorder import EnvelopeGrating\n") # replaces variable params with defaults and sets sample updating flag inits = getInitVals(self.params) code = ("%s = visual.EnvelopeGrating(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " carrier=%(carrier)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s,\n" % inits + " sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s,\n " % inits + " opacity=%(opacity)s, contrast=%(contrast)s,\n" % inits + " texRes=%(texture resolution)s, envelope=%(envelope)s,\n" % inits + " envori=%(envori)s, envsf=%(envsf)s,\n" % inits + " envphase=%(envphase)s, power=%(power)s,\n" % inits + " moddepth=%(moddepth)s, blendmode=%(blendmode)s" %inits ) if self.params['beat'].val in ['Y','y','Yes', 'yes','True','true']: code += ", beat=True" elif self.params['beat'].val in ['N','n','No', 'no','False','false']: code += ", beat=False" else: code += ", beat=%(beat)s" %inits if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth code += "if sys.version[0]=='3' and np.min(win.gamma) == None:\n" code += " logging.warning('Envelope grating in use with no gamma set. Unless you have hardware gamma correction the image will be distorted.')\n" code += "elif np.min(win.gamma) < 1.01:\n" code += " logging.warning('Envelope grating in use with window gamma <= 1.0 or no gamma set at all. Unless you have hardware gamma correction the image will be distorted.')\n" buff.writeIndentedLines(code)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.secondorder import EnvelopeGrating\n") # replaces variable params with defaults and sets sample updateing flag inits = getInitVals(self.params) code = ( "%s = visual.EnvelopeGrating(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " carrier=%(carrier)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, " % inits + "sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + "opacity=%(opacity)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s,\n" % inits + " envelope=%(envelope)s, envori=%(envori)s,\n" % inits + " envsf=%(envsf)s, envphase=%(envphase)s, moddepth=%(moddepth)s, blendmode=%(blendmode)s" % inits) if self.params['beat'].val in ['Y', 'y', 'Yes', 'yes', 'True', 'true']: code += ", beat=True" elif self.params['beat'].val in [ 'N', 'n', 'No', 'no', 'False', 'false' ]: code += ", beat=False" else: code += ", beat=%(beat)s" % inits if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code)
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 writeInitCodeJS(self, buff): if self.params['units'].val == 'from exp settings': unitsStr = "'height'" logging.warning( "{units} not a valid screen unit for online studies. Switching {name} units to 'height'." .format(units=self.params['units'], name=self.params['name'])) else: unitsStr = "%(units)s" % self.params inits = getInitVals(self.params) noAudio = '{}'.format(inits['No audio'].val).lower() for param in inits: if inits[param] in ['', None, 'None', 'none']: inits[param] = 'undefined' code = "{name}Clock = new util.Clock();\n".format(**inits) buff.writeIndented(code) code = ("{name} = new visual.MovieStim({{\n" " win: psychoJS.window,\n" " name: '{name}',\n" " movie: {movie},\n" " units: {units},\n" " pos: {pos},\n" " size: {size},\n" " ori: {ori},\n" " opacity: {opacity},\n" " loop: {loop},\n" " noAudio: {noAudio},\n" " }});\n").format(name=inits['name'], movie=inits['movie'], units=unitsStr, pos=inits['pos'], size=inits['size'], ori=inits['ori'], loop=inits['loop'], opacity=inits['opacity'], noAudio=noAudio) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = " units: undefined, \n" else: unitsStr = " units: %(units)s, \n" % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoJS') # check for NoneTypes for param in inits: if inits[param] in [None, 'None', '']: inits[param].val = 'undefined' if param == 'text': inits[param].val = "" code = ("%(name)s = new visual.TextBox({\n" " win: psychoJS.window,\n" " name: '%(name)s',\n" " text: %(text)s,\n" " font: %(font)s,\n" " pos: %(pos)s, letterHeight: %(letterHeight)s,\n" " size: %(size)s," + unitsStr + " color: %(color)s, colorSpace: %(colorSpace)s,\n" " fillColor: %(fillColor)s, borderColor: %(borderColor)s,\n" " languageStyle: %(languageStyle)s,\n" " bold: %(bold)s, italic: %(italic)s,\n" " opacity: %(opacity)s,\n" " padding: %(padding)s,\n" " alignment: %(alignment)s,\n" " editable: %(editable)s,\n" " multiline: true,\n" " anchor: %(anchor)s,\n") buff.writeIndentedLines(code % inits) depth = -self.getPosInRoutine() code = (" depth: %.1f \n" "});\n\n" % (depth)) buff.writeIndentedLines(code) depth = -self.getPosInRoutine()
def writeInitCode(self, buff): inits = getInitVals(self.params) # build up an initialization string for Form(): code = ("win.allowStencil = True\n" "%(name)s = visual.Form(win=win, name='%(name)s',\n") buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "items=%(Items)s,\n" "textHeight=%(Text Height)s,\n" "font=%(Font)s,\n" "randomize=%(Randomize)s,\n" "style=%(Style)s,\n" "fillColor=%(fillColor)s, borderColor=%(borderColor)s, itemColor=%(itemColor)s, \n" "responseColor=%(responseColor)s, markerColor=%(markerColor)s, colorSpace=%(colorSpace)s, \n" "size=%(size)s,\n" "pos=%(pos)s,\n" "itemPadding=%(Item Padding)s") buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True) code = (")\n") buff.writeIndentedLines(code % inits)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s," % self.params # do writing of init inits = getInitVals(self.params, 'PsychoPy') code = ("%(name)s = visual.ButtonStim(win, \n" " text=%(text)s, font=%(font)s,\n" " pos=%(pos)s," + unitsStr + "\n" " letterHeight=%(letterHeight)s,\n" " size=%(size)s, borderWidth=%(borderWidth)s,\n" " fillColor=%(fillColor)s, borderColor=%(borderColor)s,\n" " color=%(color)s, colorSpace=%(colorSpace)s,\n" " opacity=%(opacity)s,\n" " bold=%(bold)s, italic=%(italic)s,\n" " padding=%(padding)s,\n" " anchor=%(anchor)s,\n" " name='%(name)s')\n" "%(name)s.buttonClock = core.Clock()") buff.writeIndentedLines(code % inits)
def writeInitCode(self, buff): inits = getInitVals(self.params) # check units if inits['units'].val == 'from exp settings': inits['units'].val = None inits['depth'] = -self.getPosInRoutine() # Use None as a start value if none set inits['initVal'] = inits['initVal'] or None # build up an initialization string for Slider(): initStr = ("{name} = visual.Slider(win=win, name='{name}',\n" " startValue={initVal}, size={size}, pos={pos}, units={units},\n" " labels={labels}, ticks={ticks}, granularity={granularity},\n" " style={styles}, styleTweaks={styleTweaks}, opacity={opacity},\n" " labelColor={color}, markerColor={fillColor}, lineColor={borderColor}, colorSpace={colorSpace},\n" " font={font}, labelHeight={letterHeight},\n" " flip={flip}, ori={ori}, depth={depth}, readOnly={readOnly})\n" .format(**inits)) buff.writeIndented(initStr)
def writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params # do writing of init inits = getInitVals(self.params, 'PsychoPy') if self.params['shape'] == 'regular polygon...': inits['shape'] = self.params['nVertices'] elif self.params['shape'] == 'custom polygon...': inits['shape'] = self.params['vertices'] code = ( "%(name)s = visual.ROI(win, name='%(name)s', device=eyetracker,\n") buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ("debug=%(debug)s,\n" "shape=%(shape)s,\n" + unitsStr + "pos=%(pos)s, size=%(size)s, anchor=%(anchor)s, ori=0.0)\n") buff.writeIndentedLines(code % inits) buff.setIndentLevel(-1, relative=True)
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 writeInitCode(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.secondorder import EnvelopeGrating\n") # replaces variable params with defaults and sets sample updateing flag inits = getInitVals(self.params) code = ("%s = visual.EnvelopeGrating(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " carrier=%(carrier)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, " % inits + "sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + "opacity=%(opacity)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s,\n" % inits + " envelope=%(envelope)s, envori=%(envori)s,\n" % inits + " envsf=%(envsf)s, envphase=%(envphase)s, moddepth=%(moddepth)s, blendmode=%(blendmode)s" %inits ) if self.params['beat'].val in ['Y','y','Yes', 'yes','True','true']: code += ", beat=True" elif self.params['beat'].val in ['N','n','No', 'no','False','false']: code += ", beat=False" else: code += ", beat=%(beat)s" %inits if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units : %(units)s, " % self.params # do writing of init # replaces variable params with sensible defaults inits = getInitVals(self.params, 'PsychoJS') if self.params['wrapWidth'].val in ['', 'None', 'none']: inits['wrapWidth'] = 'undefined' code = ("%(name)s = new psychoJS.visual.TextStim({win : win, " "name : '%(name)s',\n" " text : %(text)s,\n" " font : %(font)s,\n" " " + unitsStr + "pos : %(pos)s, height : %(letterHeight)s, " "wrapWidth : %(wrapWidth)s, ori:%(ori)s, \n" " color : %(color)s, colorSpace:%(colorSpace)s, " "opacity : %(opacity)s,") buff.writeIndentedLines(code % inits) flip = self.params['flip'].val.strip() if flip == 'horiz': flipStr = 'flipHoriz : true, ' elif flip == 'vert': flipStr = 'flipVert : true, ' elif flip: msg = ("flip value should be 'horiz' or 'vert' (no quotes)" " in component '%s'") raise ValueError(msg % self.params['name'].val) else: flipStr = '' depth = -self.getPosInRoutine() code = (" %sdepth : %.1f \n" "});\n" % (flipStr, depth)) buff.writeIndentedLines(code)
def writeInitCodeJS(self, buff): inits = getInitVals(self.params) for param in inits: if inits[param].val in ['', None, 'None', 'none']: inits[param].val = 'undefined' boolConverter = {False: 'false', True: 'true'} sliderStyles = {'slider': 'SLIDER', '()': 'RATING', 'rating': 'RATING', 'radio': 'RADIO', 'labels45': 'LABELS_45', 'whiteOnBlack': 'WHITE_ON_BLACK', 'triangleMarker': 'TRIANGLE_MARKER'} # If no style given, set default 'rating' as list if len(inits['styles'].val) == 0: inits['styles'].val = ['rating'] # reformat styles for JS inits['styles'].val = ', '.join(["visual.Slider.Style.{}". format(sliderStyles[style]) for style in inits['styles'].val]) # add comma so is treated as tuple in py2js and converted to list, as required inits['styles'].val += ',' inits['styles'].val = py2js.expression2js(inits['styles'].val) # build up an initialization string for Slider(): initStr = ("{name} = new visual.Slider({{\n" " win: psychoJS.window, name: '{name}',\n" " size: {size}, pos: {pos},\n" " labels: {labels}, ticks: {ticks},\n" " granularity: {granularity}, style: {styles},\n" " color: new util.Color({color}), \n" " fontFamily: {font}, bold: true, italic: false, \n" ).format(**inits) initStr += (" flip: {flip},\n" "}});\n\n").format(flip=boolConverter[inits['flip'].val]) buff.writeIndentedLines(initStr)
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) # Save recording code = ( "# Save %(name)s recordings\n" "%(name)sClips = %(name)s.flush()\n" "for rt in %(name)sClips:\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "for i, clip in enumerate(%(name)sClips[rt]):\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(1, relative=True) code = ( "clipName = os.path.join(%(name)sRecFolder, f'recording_{rt}_{i}.%(outputType)s')\n" "clip.save(clipName)\n" ) buff.writeIndentedLines(code % inits) buff.setIndentLevel(-2, relative=True)
def writeRoutineStartCode(self, buff): inits = getInitVals(self.params) code = ("%(name)s = microphone.AdvAudioCapture(name='%(name)s', " "saveDir=wavDirName, stereo=%(stereo)s)\n") buff.writeIndented(code % inits)
def writeRoutineStartCode(self, buff): inits = getInitVals(self.params) if '$' in inits['stopVal'].val: buff.writeIndented("%s.setSound(%s, secs=%s)\n" % (inits['name'], inits['sound'], inits['stopVal'])) buff.writeIndented("%(name)s.setVolume(%(volume)s)\n" % (inits))
def writeInitCode(self, buff): self._noiseNewSample = "" # do we need units code? if self.params['units'].val == 'from exp settings': unitsStr = "" else: unitsStr = "units=%(units)s, " % self.params #buff.writeIndented("from psychopy.visual.noise import NoiseStim\n") # replaces variable params with defaults and sets sample updateing flag inits = getInitVals(self.params) #for myparam in inits: # if ('noise' in myparam): # if (inits[myparam].updates in ['set every frame']): # self._forceRebuild=True #if not (inits[myparam].updates in ['constant', None, 'None']): # inits[myparam]='1' #if not (self.params['A_noiseType'].updates in ['constant', None, 'None']): # inits['A_noiseType']='Binary' #if ('rebuild_frame' in self._noiseNewSample): # print 'Warning: Rebuilding the noise sample every frame may be slow and could corrupt frame timing' # noise sample updating set to every repeat or frame will override result of parameter settings self._forceUpdateRepeat = False self._forceUpdateFrames = False self._forceUpdateSeconds = False if inits['noiseNewSample'].val in ['Repeat']: self._forceUpdateRepeat = True elif inits['noiseNewSample'].val in ['N-frames']: self._forceUpdateFrames = True elif inits['noiseNewSample'].val in ['Seconds']: self._forceUpdateSeconds = True #self._when=float(inits['Z_when'].val) #print self._when #else whenIsVariale=false #if (inits['carrier'].val in ['noise','Noise']): # inits['carrier']="%(name)s.noiseTex" %inits code = ( "%s = visual.NoiseStim(\n" % inits['name'] + " win=win, name='%s',%s\n" % (inits['name'], unitsStr) + " noiseImage=%(noiseImage)s, mask=%(mask)s,\n" % inits + " ori=%(ori)s, pos=%(pos)s, size=%(size)s, " % inits + "sf=%(sf)s, phase=%(phase)s,\n" % inits + " color=%(color)s, colorSpace=%(colorSpace)s, " % inits + "opacity=%(opacity)s, blendmode=%(blendmode)s, contrast=%(contrast)s,\n" % inits + # no newline - start optional parameters " texRes=%(texture resolution)s,\n" % inits + " noiseType=%(noiseType)s, noiseElementSize=%(noiseElementSize)s, noiseBaseSf=%(noiseBaseSf)s,\n" % inits + " noiseBW=%(noiseBW)s, noiseBWO=%(noiseBWO)s, noiseFractalPower=%(noiseFractalPower)s,noiseFilterLower=%(noiseFilterLower)s, noiseFilterUpper=%(noiseFilterUpper)s, noiseFilterOrder=%(noiseFilterOrder)s, noiseClip=%(noiseClip)s" % inits) if self.params['interpolate'].val == 'linear': code += ", interpolate=True" else: code += ", interpolate=False" depth = -self.getPosInRoutine() code += ", depth=%.1f)\n" % depth buff.writeIndentedLines(code) if not (self.params['noiseType'] in ['none', 'None']): buff.writeIndented("%(name)s.buildNoise()\n" % self.params)
def writeInitCodeJS(self, buff): # Check for unsupported units if self.params['units'].val in ['from exp settings', 'cm', 'deg', 'degFlatPos', 'degFlat']: msg = "'{units}' units for your '{name}' shape is not currently supported for PsychoJS: " \ "switching units to 'height'." logging.warning(msg.format(units=self.params['units'].val, name=self.params['name'].val,)) unitsStr = "'height'" else: unitsStr = self.params['units'] # replace variable params with defaults inits = getInitVals(self.params) # check for NoneTypes for param in inits: if inits[param] in [None, 'None', 'none', '']: inits[param].val = 'undefined' if inits['size'].val in ['1.0', '1']: inits['size'].val = '[1.0, 1.0]' if self.params['shape'] == 'regular polygon...': vertices = self.params['nVertices'] else: vertices = self.params['shape'] # Temporary checks to catch use of unsupported shapes/polygons if vertices in ['cross', 'star']: msg = "{} shape is in development. Not currently supported in PsychoJS.".format(vertices) raise NotImplementedError(msg) elif self.params['shape'] == 'regular polygon...' and self.params['nVertices'].val not in ['2', '3', '4']: msg = ("Regular polygon is currently in development " "and not yet supported in PsychoJS.". format(vertices)) raise NotImplementedError(msg) if vertices in ['line', '2']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}',\n" " units: {unitsStr},\n" " vertices: [[-{size}[0]/2.0, 0], [+{size}[0]/2.0, 0]],\n") elif vertices in ['triangle', '3']: code = ("{name} = new visual.ShapeStim ({{\n" " win: psychoJS.window, name: '{name}',\n" " units: {unitsStr},\n" " vertices: [[-{size}[0]/2.0, -{size}[1]/2.0], [+{size}[0]/2.0, -{size}[1]/2.0], [0, {size}[1]/2.0]],\n") elif vertices in ['rectangle', '4']: code = ("{name} = new visual.Rect ({{\n" " win: psychoJS.window, name: '{name}',\n" " units: {unitsStr},\n" " width: {size}[0], height: {size}[1],\n") depth = -self.getPosInRoutine() interpolate = 'true' if self.params['interpolate'].val != 'linear': interpolate = 'false' code += (" ori: {ori}, pos: {pos},\n" " lineWidth: {lineWidth}, lineColor: new util.Color({lineColor}),\n" " fillColor: new util.Color({fillColor}),\n" " opacity: {opacity}, depth: {depth}, interpolate: {interpolate},\n" "}});\n\n") buff.writeIndentedLines(code.format(name=inits['name'], unitsStr=unitsStr, lineWidth=inits['lineWidth'], size=inits['size'], ori=inits['ori'], pos=inits['pos'], lineColor=inits['lineColor'], fillColor=inits['fillColor'], opacity=inits['opacity'], depth=depth, interpolate=interpolate, ))