def showcolorcircle(self, numStim=8):  # show the color circle
        """
        Draw and paint a color circle
        :param numStim: the number of colors in the color circle
        """
        _, Mrgb = self.circolors(numStim)

        winM = visual.Window(size=[800, 800], allowGUI=True, bpc=(self.depthBits, self.depthBits, self.depthBits),
                             depthBits=self.depthBits, colorSpace=self.colorSpace, color=self.Crgb)

        rectsize = 0.5 * winM.size[0] * 2 / numStim
        radius = 0.3 * winM.size[0]
        alphas = np.linspace(0, 360, numStim, endpoint=False)

        rect = visual.Rect(win=winM,
                           units="pix",
                           width=int(rectsize), height=int(rectsize))
        for i_rect in range(numStim):
            rect.fillColorSpace=self.colorSpace
            rect.lineColorSpace=self.colorSpace
            rect.fillColor = Mrgb[i_rect]
            rect.lineColor = Mrgb[i_rect]
            rect.pos = misc.pol2cart(alphas[i_rect], radius)
            rect.draw()

        winM.flip()

        event.waitKeys()
        winM.close()
Пример #2
0
    def make_ring(self, text_size=45):
        """ create the ring
        20210518 - use images instead to match eprime experiment
        makes self.ringimg['rew'] and self.ringimg['neu']
        see
        https://discourse.psychopy.org/t/the-best-way-to-draw-many-text-objects-rsvp/2758
        """

        # color and symbol for ring reward
        cues = {
            'neu': {
                'color': 'gray',
                'sym': '#'
            },
            'rew': {
                'color': 'green',
                'sym': '$'
            }
        }
        n_in_ring = 12
        el_rs = 250  # TODO: make relative to screen size?
        el_thetas = np.linspace(0, 360, n_in_ring, endpoint=False)
        el_xys = np.array(misc.pol2cart(el_thetas, el_rs)).T
        ringtext = visual.TextStim(win=self.win,
                                   units='pix',
                                   bold=True,
                                   height=text_size,
                                   text='$')  # '$' will be changed
        cap_rect_norm = [
            -(text_size / 2.0) / (self.win.size[0] / 2.0),  # left
            +(text_size / 2.0) / (self.win.size[1] / 2.0),  # top
            +(text_size / 2.0) / (self.win.size[0] / 2.0),  # right
            -(text_size / 2.0) / (self.win.size[1] / 2.0)  # bottom
        ]
        for k in ['rew', 'neu']:
            ringtext.text = cues[k]['sym']
            ringtext.color = cues[k]['color']
            buff = visual.BufferImageStim(win=self.win,
                                          stim=[ringtext],
                                          rect=cap_rect_norm)
            # img = (np.flipud(np.array(buff.image)[..., 0]) / 255.0 * 2.0 - 1.0)
            self.ringimg[k] = visual.ElementArrayStim(
                win=self.win,
                units="pix",
                nElements=n_in_ring,
                sizes=buff.image.size,
                xys=el_xys,
                # colors=cues[k]['color'],
                elementMask=None,
                elementTex=buff.image)
Пример #3
0
 def testElementArray(self):
     win = self.win
     contextName = self.contextName
     if not win._haveShaders:
         raise nose.plugins.skip.SkipTest("ElementArray requires shaders, which aren't available")
     win.flip()
     # using init
     thetas = numpy.arange(0, 360, 10)
     N = len(thetas)
     radii = numpy.linspace(0, 1.0, N) * self.scaleFactor
     x, y = misc.pol2cart(theta=thetas, radius=radii)
     xys = numpy.array([x, y]).transpose()
     spiral = visual.ElementArrayStim(win, nElements=N, sizes=0.5 * self.scaleFactor, sfs=3.0, xys=xys, oris=thetas)
     spiral.draw()
     utils.compareScreenshot("elarray1_%s.png" % (contextName), win)
Пример #4
0
 def test_element_array(self):
     win = self.win
     if not win._haveShaders:
         pytest.skip("ElementArray requires shaders, which aren't available")
     #using init
     thetas = numpy.arange(0,360,10)
     N=len(thetas)
     radii = numpy.linspace(0,1.0,N)*self.scaleFactor
     x, y = misc.pol2cart(theta=thetas, radius=radii)
     xys = numpy.array([x,y]).transpose()
     spiral = visual.ElementArrayStim(win, nElements=N,sizes=0.5*self.scaleFactor,
         sfs=3.0, xys=xys, oris=thetas)
     spiral.draw()
     win.flip()
     spiral.draw()
     utils.compareScreenshot('elarray1_%s.png' %(self.contextName), win)
     win.flip()
Пример #5
0
    def show_color_circle(self, num_col=16, gray_level=None):
        """
        Show color circle.
        :param num_col: Number of colors to be shown.
        :param gray_level: Gray level.
        """

        self.op_mode = True
        if gray_level is None:
            gray_level = self.gray_level

        phis = np.linspace(0, 2 * np.pi, num_col, endpoint=False)
        m_rgb = self.dklc2rgb(
            phi=phis,
            gray_level=gray_level,
        )

        win = visual.Window(size=[800, 600], monitor="eDc-1", fullscr=False)
        # set background gray level
        win.colorSpace = "rgb"
        win.color = self.color2pp(
            np.array([gray_level, gray_level, gray_level]))[0]
        win.flip()

        rect_size = 0.4 * win.size[0] * 2 / num_col
        radius = 0.2 * win.size[0]
        alphas = np.linspace(0, 360, num_col, endpoint=False)

        rect = visual.Rect(win=win,
                           units="pix",
                           width=int(rect_size),
                           height=int(rect_size))
        for i_rect in range(num_col):
            rect.fillColorSpace = "rgb"
            rect.lineColorSpace = "rgb"
            rect.fillColor = m_rgb[i_rect]
            rect.lineColor = m_rgb[i_rect]
            rect.pos = misc.pol2cart(alphas[i_rect], radius)
            rect.draw()

        win.flip()

        event.waitKeys()
        win.close()
        self.op_mode = False
Пример #6
0
 def testElementArray(self):        
     win = self.win
     contextName=self.contextName
     #using init
     thetas = numpy.arange(0,360,10)
     N=len(thetas)
     radii = numpy.linspace(0,1.0,N)
     x, y = misc.pol2cart(theta=thetas, radius=radii)
     xys = numpy.array([x,y]).transpose()
     if win._haveShaders:
         spiral = visual.ElementArrayStim(win, nElements=N,sizes=0.5,
             sfs=3, xys=xys, oris=thetas)
         spiral.draw()
         utils.compareScreenshot('data/elarray1_%s.png' %(contextName), win)
         win.flip()#AFTER compare screenshot
     else:
         nose.tools.assert_raises(Exception, visual.ElementArrayStim, win, nElements=N,sizes=0.5,
             sfs=3, xys=xys, oris=thetas)
Пример #7
0
def show_colorcircle(subject, contrast, depthBits, numStim):
    if contrast is None:
        contrast = 0.15
    if depthBits is None:
        depthBits = 10
    if numStim is None:
        numStim = 16

    theta = np.linspace(0, 2 * np.pi, numStim, endpoint=False)

    cp = ColorPicker(c=contrast,
                     sscale=2.6,
                     unit='rad',
                     depthBits=depthBits,
                     subject=None)
    Msml = []
    Mrgb = []
    for t in theta:
        sml, rgb = cp.newcolor(theta=t)
        Msml.append(sml)
        Mrgb.append(rgb)

    sub_cp = ColorPicker(c=contrast,
                         sscale=2.6,
                         unit='rad',
                         depthBits=depthBits,
                         subject=subject)
    sub_Msml = []
    sub_Mrgb = []
    for t in theta:
        sml, rgb = sub_cp.newcolor(theta=t)
        sub_Msml.append(sml)
        sub_Mrgb.append(rgb)

    winM = visual.Window(fullscr=True,
                         allowGUI=True,
                         bpc=(cp.depthBits, cp.depthBits, cp.depthBits),
                         depthBits=cp.depthBits,
                         colorSpace=cp.colorSpace,
                         color=cp.sml2rgb(cp.center()))

    rectsize = 0.2 * winM.size[0] * 2 / numStim
    radius = 0.1 * winM.size[0]
    alphas = np.linspace(0, 360, numStim, endpoint=False)

    rect = visual.Rect(win=winM,
                       units="pix",
                       width=int(rectsize),
                       height=int(rectsize))

    winM.flip()
    for t in range(50):
        for wait_keys in event.waitKeys():
            if wait_keys == 'left':
                for i_rect in range(numStim):
                    rect.fillColorSpace = cp.colorSpace
                    rect.lineColorSpace = cp.colorSpace
                    rect.fillColor = Mrgb[i_rect]
                    rect.lineColor = Mrgb[i_rect]
                    rect.pos = misc.pol2cart(alphas[i_rect], radius)
                    rect.draw()
                winM.flip()
            elif wait_keys == 'right':
                sub_rect = rect
                for i_rect in range(numStim):
                    sub_rect.fillColorSpace = sub_cp.colorSpace
                    sub_rect.lineColorSpace = sub_cp.colorSpace
                    sub_rect.fillColor = sub_Mrgb[i_rect]
                    sub_rect.lineColor = sub_Mrgb[i_rect]
                    sub_rect.pos = misc.pol2cart(alphas[i_rect], radius)
                    sub_rect.draw()
                    text = visual.TextStim(winM,
                                           text=subject,
                                           pos=[0.3, -0.5],
                                           height=0.05,
                                           color='black')
                    text.draw()
                winM.flip()
            elif wait_keys == 'escape':
                core.quit()
Пример #8
0
rewtype = shuf_for_ntrials(['rew', 'neu'], ntrials)

# ---------- GO --------------------------
# setup task (get send_ttl, crcl, iti_fix)
task = mgsTask(None,
               usePP=settings['usePP'],
               fullscreen=settings['fullscreen'])

# ----- DRAW A RING OF $ OR  --------

# create the ring, see
# https://discourse.psychopy.org/t/the-best-way-to-draw-many-text-objects-rsvp/2758
n_in_ring = 12
el_rs = 250  # TODO: make relative to screen size?
el_thetas = np.linspace(0, 360, n_in_ring, endpoint=False)
el_xys = np.array(misc.pol2cart(el_thetas, el_rs)).T
text_size = 45
ringtext = visual.TextStim(win=task.win,
                           units='pix',
                           bold=True,
                           height=text_size,
                           text='$')  # '$' will be changed
cap_rect_norm = [
    -(text_size / 2.0) / (task.win.size[0] / 2.0),  # left
    +(text_size / 2.0) / (task.win.size[1] / 2.0),  # top
    +(text_size / 2.0) / (task.win.size[0] / 2.0),  # right
    -(text_size / 2.0) / (task.win.size[1] / 2.0)  # bottom
]
ringimg = {}
for k in ['rew', 'neu']:
    ringtext.text = cues[k]['sym']
else:
    frameDur = 1.0 / 60.0  # couldn't get a reliable measure so guess
logFile.write('RefreshRate=' + unicode(refr_rate) + '\n')
logFile.write('FrameDuration=' + unicode(frameDur) + '\n')

TargetPos = np.where(Targets == 1)[0]
TargetOnsetInFrames = np.floor(TargetOnsetinSec / frameDur)
nrOfTargetFrames = int(TargetDur / frameDur)
logFile.write('TargetOnsetInFrames=' + unicode(TargetOnsetInFrames) + '\n')
logFile.write('nrOfTargetFrames=' + unicode(nrOfTargetFrames) + '\n')

speed = speedPixPerSec * frameDur  # speedPixPerFrame
# set directions
direction = [999]
for deg in [0, 45, 90, 135, 180, 225, 270, 315]:
    temp = pol2cart(deg, speed)
    direction.append(temp)

logFile.write('speed=' + unicode(speed) + '\n')
logFile.write('Directions=' + unicode(direction) + '\n')

# set durations
nrOfVols = 172
durations = np.arange(ExpectedTR, ExpectedTR * nrOfVols + ExpectedTR,
                      ExpectedTR)
totalTime = ExpectedTR * nrOfVols

# create clock and Landolt clock
clock = core.Clock()
logging.setDefaultClock(clock)
"""

from psychopy import visual, event, misc
import numpy

nDots = 500
maxSpeed = 0.02
dotSize = .0075

dotsTheta=numpy.random.rand(nDots)*360
dotsRadius=(numpy.random.rand(nDots)**0.5)*2
speed=numpy.random.rand(nDots)*maxSpeed

win = visual.Window([800,600],rgb=[-1,-1,-1])
dots = visual.ElementArrayStim(win, elementTex=None, elementMask='circle', 
    nElements=nDots, sizes=dotSize)

for frameN in range(400):
    
    #update radius
    dotsRadius = (dotsRadius+speed)
    #random radius where radius too large
    outFieldDots = (dotsRadius>=2.0)
    dotsRadius[outFieldDots] = numpy.random.rand(sum(outFieldDots))*2.0
    
    dotsX, dotsY = misc.pol2cart(dotsTheta,dotsRadius)
    dotsX *= 0.75 #to account for wider aspect ratio
    dots.setXYs(numpy.array([dotsX, dotsY]).transpose())
    dots.draw()
    
    win.flip()
Пример #11
0
def motionScan(scanDict,
               screenSize=[1024, 768],
               dotSpeed=5.8,
               dotMotion='radial',
               direction=1.0):
    scanLength = float(scanDict['numCycles'] * scanDict['period'] +
                       scanDict['preScanRest'])
    #get actual size of window--useful in the functions
    #count number of screens
    if scanDict['operatorScreen'] == scanDict['subjectScreen']:
        screenCount = 1
    else:
        screenCount = 2
    screenSize = scanDict['screenSize']
    thisPlatform = scanDict['platform']
    #if there is only one window, need to display the winOp stuff and then clear it
    #second window is deeply damanged in 1.79. Thought it was the aperture, but it's also the element stim I think
    #pop up the Tr info and wait for "ok"
    winOp = visual.Window([500, 500],
                          monitor='testMonitor',
                          units='norm',
                          screen=scanDict['operatorScreen'],
                          color=[0.0, 0.0, 0.0],
                          colorSpace='rgb')
    msgScanLength = visual.TextStim(winOp,
                                    pos=[0, 0.5],
                                    units='norm',
                                    height=0.1,
                                    text='Scan length (s): %.1f' % scanLength)
    msgScanTr = visual.TextStim(winOp,
                                pos=[0, 0],
                                units='norm',
                                height=0.1,
                                text='No. of Volumes (at Tr=%.2f): %.1f' %
                                (scanDict['Tr'], scanLength / scanDict['Tr']))
    msgOK = visual.TextStim(winOp,
                            pos=[0, -0.5],
                            units='norm',
                            height=0.1,
                            text='Operator, press any key to proceed')
    msgScanLength.draw()
    msgScanTr.draw()
    msgOK.draw()
    winOp.flip()
    #wait for keypress
    thisKey = None
    while thisKey == None:
        thisKey = event.waitKeys()
    if thisKey in ['q', 'escape']:
        core.quit()  #abort
    else:
        event.clearEvents()
    #close the winOp
    winOp.close()

    #open subject window
    winSub = visual.Window(screenSize,
                           monitor=scanDict['monCalFile'],
                           units='deg',
                           screen=scanDict['subjectScreen'],
                           color=[0.0, 0.0, 0.0],
                           colorSpace='rgb',
                           fullscr=False,
                           allowGUI=False)
    subWinSize = winSub.size
    #parse out vars from scanDict
    IR = scanDict['innerRadius']
    OR = scanDict['outerRadius']
    screenSize = numpy.array([subWinSize[0], subWinSize[1]])
    fixPercentage = scanDict['fixFraction']
    fixDuration = 0.2
    respDuration = 1.0
    dummyLength = int(numpy.ceil(scanLength * 60 / 100))
    subjectResponse = numpy.zeros((dummyLength, 1))
    subjectResponse[:] = numpy.nan
    white = [1.0, 1.0, 1.0]
    gray = [0.0, 0.0, 0.0]
    black = [-1.0, -1.0, -1.0]
    numDots = 700
    dotSize = 0.1  #deg
    #dotAperture=OR
    frameRate = 60.0
    quitKeys = ['q', 'escape']
    #OR+=1

    dummyVar = 0
    #following startfield.py demo
    #dot locations
    dotsPolarAngle = numpy.random.rand(numDots) * 360
    dotsRadius = (numpy.random.rand(numDots)**0.5) * OR
    numpy.savetxt('rads.txt', dotsRadius, fmt='%.1f')
    numpy.savetxt('pols.txt', dotsPolarAngle, fmt='%.1f')
    dotsDirection = numpy.random.rand(numDots) * 2.0 * math.pi

    #make an aperture mask
    #    ap = visual.Aperture(winSub,size=(OR-1)*2.0 ,units='deg')
    #ap = visual.Aperture(winSub,size=(OR-1) ,units='deg')
    #ap.disable()
    #create the dots
    #color is based on contrast--not sure this is quite how I want it?
    # if contrast is 0, dot color is 0 which = background
    # if contrast is 1, dot color is 1, which is white, which is the "full" contrast...
    dotContrast = [
        scanDict['contrast'], scanDict['contrast'], scanDict['contrast']
    ]
    movingDots = visual.ElementArrayStim(winSub,
                                         units='deg',
                                         fieldShape='circle',
                                         nElements=numDots,
                                         sizes=dotSize,
                                         elementMask='circle',
                                         colors=dotContrast)
    #move them into initial position
    dotsX, dotsY = misc.pol2cart(dotsPolarAngle, dotsRadius)
    numpy.savetxt('dotx.txt', dotsX, fmt='%.1f')
    numpy.savetxt('doty.txt', dotsY, fmt='%.1f')
    #dotsX *= 0.75 #aspect ratio issue
    movingDots.setXYs(numpy.array([dotsX, dotsY]).transpose())

    #fixation
    fix0 = visual.Circle(winSub,
                         radius=IR,
                         edges=32,
                         lineColor=gray,
                         lineColorSpace='rgb',
                         fillColor=gray,
                         fillColorSpace='rgb',
                         autoLog=False)
    fix1 = visual.ShapeStim(winSub,
                            pos=[0.0, 0.0],
                            vertices=((0.0, -0.15), (0.0, 0.15)),
                            lineWidth=3.0,
                            lineColor=black,
                            lineColorSpace='rgb',
                            fillColor=black,
                            fillColorSpace='rgb',
                            autoLog=False)
    fix2 = visual.ShapeStim(winSub,
                            pos=[0.0, 0.0],
                            vertices=((-0.15, 0), (0.15, 0.0)),
                            lineWidth=3.0,
                            lineColor=black,
                            lineColorSpace='rgb',
                            autoLog=False)

    #wait for subject
    if direction == 1:
        scanNameText = 'motion localizer. On condition is %s dots' % ('moving')
    else:
        scanNameText = 'motion localizer. On condition is %s dots' % ('static')

    msg1 = visual.TextStim(winSub,
                           pos=[0, +2],
                           text='%s \n\nSubject: press a button when ready.' %
                           scanNameText)
    msg1.draw()
    winSub.flip()
    thisKey = None
    responseKeys = list(scanDict['subjectResponse'])
    responseKeys.extend('q')
    responseKeys.extend('escape')
    while thisKey == None:
        thisKey = event.waitKeys(keyList=responseKeys)
    if thisKey in quitKeys:
        core.quit()
    else:
        event.clearEvents()
    responseKeys = list(scanDict['subjectResponse'])

    #wait for trigger
    msg1.setText('Noise Coming....')
    msg1.draw()
    winSub.flip()
    trig = None
    triggerKeys = list(scanDict['trigger'])
    triggerKeys.extend('q')
    triggerKeys.extend('escape')
    while trig == None:
        trig = event.waitKeys(keyList=triggerKeys)
    if trig in quitKeys:
        core.quit()
    else:
        event.clearEvents()

    #start the timer
    scanTimer = core.Clock()
    startTime = scanTimer.getTime()
    #ap.enable()
    #draw the stimulus
    #winSub.setColor(black)
    movingDots.draw()
    fix0.draw()
    fix1.draw()
    fix2.draw()
    winSub.flip()

    #draw the time
    timeNow = scanTimer.getTime()
    #timeMsg=visual.TextStim(winSub,pos=[-screenSize[0]/2+100,-screenSize[1]/2+15],units='pix',text= 't = %.3f' %timeNow)
    #    timeMsg = visual.TextStim(winOp,pos=[0,-1],text = 't = %.3f' %timeNow)
    #    timeMsg.draw()

    #print(timeNow)
    loopCounter = 0
    fixTimer = core.Clock()
    respTimer = core.Clock()
    flipTimer = core.Clock()
    fixOri = 0
    numCoins = 0
    epochTimer = core.Clock()
    miniEpochTimer = core.Clock()
    event.clearEvents()

    #pre-scan stimulus

    #let's make a kind of phase variable that I can adjust for pre-scan rest
    phaseInit = 0
    #need a kind of phase variable to dial back (rather, advance it up through part of a period)
    phaseInit = scanDict[
        'period'] - scanDict['preScanRest'] % scanDict['period']

    #drift it
    while timeNow < startTime + scanLength:
        timeBefore = timeNow  #um, is this aliasing?
        timeNow = scanTimer.getTime()
        deltaT = timeNow - timeBefore
        runningT = timeNow - startTime
        phase = phaseInit + timeNow
        mode = phase % scanDict['period']

        #every 100 frames, decide if fixation should change or not
        if loopCounter % 100 == 0 and loopCounter > 10:
            #flip a coin to decide
            flipCoin = numpy.random.ranf()
            if flipCoin < fixPercentage:
                #reset timers/change ori
                fixOri = 45
                fixTimer.reset()
                respTimer.reset()
                numCoins += 1
                subjectResponse[numCoins] = 0
        fixTimeCheck = fixTimer.getTime()
        respTimeCheck = respTimer.getTime()
        if fixTimeCheck > fixDuration:  #timer expired--reset ori
            fixOri = 0
        epochTime = epochTimer.getTime()
        miniEpochTime = miniEpochTimer.getTime()

        #every 2 seconds, change the direction of some dots
        if loopCounter % 60 == 0 and loopCounter > 10:
            #change direction of 30% of the dots
            flipCoinDots = numpy.random.rand(numDots)
            flippedDots = flipCoinDots > 0.3
            numFlipped = numpy.sum(flippedDots)
            dotsDirection[flippedDots] = numpy.random.rand(
                numFlipped) * 2.0 * math.pi
            flipTimer.reset()

        #12s epoch
#        if epochTime<scanDict['preScanRest']+scanDict['period']/2.0:
        if mode < scanDict['period'] / 2.0:
            # on condition (first half of period)
            if direction == 1:
                #moving dots for ON CONDITION
                #update dot positions, but keep them inside the radius!
                dotsX = dotsX + dotSpeed * deltaT * numpy.cos(dotsDirection)
                dotsY = dotsY + dotSpeed * deltaT * numpy.sin(dotsDirection)
                lostDots = numpy.square(dotsX) + numpy.square(
                    dotsY) > numpy.square(OR)
                if len(lostDots) > 0:
                    #convert to polar coordintates using old position
                    dotsT, dotsR = misc.cart2pol(
                        dotsX[lostDots] -
                        dotSpeed * deltaT * numpy.cos(dotsDirection[lostDots]),
                        dotsY[lostDots] -
                        dotSpeed * deltaT * numpy.sin(dotsDirection[lostDots]))
                    #flip the direction of motion
                    dotsT += 180
                    #convert back to cartesian coordinates
                    newX, newY = misc.pol2cart(dotsT, dotsR)
                    dotsX[lostDots] = newX
                    dotsY[lostDots] = newY

                movingDots.setXYs(numpy.array([dotsX, dotsY]).transpose())
            else:
                #static dots for ON CONDITION
                if miniEpochTime > 1.0:
                    #new field of dots
                    dotsPolarAngle = numpy.random.rand(numDots) * 360
                    dotsRadius = (numpy.random.rand(numDots)**0.5) * OR
                    dotsX, dotsY = misc.pol2cart(dotsPolarAngle, dotsRadius)
                    movingDots.setXYs(numpy.array([dotsX, dotsY]).transpose())
                    miniEpochTimer.reset()
#        elif epochTime<scanDict['preScanRest']+scanDict['period']:
        elif mode < scanDict['period']:
            #OFF condition (second half of period)
            if direction == 1:
                if miniEpochTime > 1.0:
                    #new field of dots
                    dotsPolarAngle = numpy.random.rand(numDots) * 360
                    dotsRadius = (numpy.random.rand(numDots)**0.5) * OR
                    dotsX, dotsY = misc.pol2cart(dotsPolarAngle, dotsRadius)
                    movingDots.setXYs(numpy.array([dotsX, dotsY]).transpose())
                    miniEpochTimer.reset()
            else:
                #update dot positions, but keep them inside the radius!
                dotsX = dotsX + dotSpeed * deltaT * numpy.cos(dotsDirection)
                dotsY = dotsY + dotSpeed * deltaT * numpy.sin(dotsDirection)
                lostDots = numpy.square(dotsX) + numpy.square(
                    dotsY) > numpy.square(OR)
                if len(lostDots) > 0:
                    #convert to polar coordintates using old position
                    dotsT, dotsR = misc.cart2pol(
                        dotsX[lostDots] -
                        dotSpeed * deltaT * numpy.cos(dotsDirection[lostDots]),
                        dotsY[lostDots] -
                        dotSpeed * deltaT * numpy.sin(dotsDirection[lostDots]))
                    #flip the direction of motion
                    dotsT += 180
                    #convert back to cartesian coordinates
                    newX, newY = misc.pol2cart(dotsT, dotsR)
                    dotsX[lostDots] = newX
                    dotsY[lostDots] = newY

                movingDots.setXYs(numpy.array([dotsX, dotsY]).transpose())

        else:
            epochTimer.reset()

        fix1.setOri(fixOri)
        fix2.setOri(fixOri)
        #ap.enable()
        movingDots.draw()
        #ap.disable()
        fix0.draw()
        fix1.draw()
        fix2.draw()
        #        timeMsg.setText('t = %.3f' %timeNow)
        #        timeMsg.draw()
        #msgScanLength.draw()
        #msgScanTr.draw()
        winSub.flip()
        #        winOp.flip()

        #look for responses
        for key in event.getKeys():
            if key in quitKeys:
                core.quit()
            elif key in responseKeys and respTimeCheck < respDuration:
                subjectResponse[numCoins] = 1

        loopCounter += 1

    #check responses
    findResp = subjectResponse[~numpy.isnan(subjectResponse)]
    calcResp = findResp[findResp == 1]
    numCorrect = float(calcResp.shape[0])
    if numCoins > 0:
        percentCorrect = 100.0 * float(numCorrect) / (float(numCoins))
    else:
        percentCorrect = 100.0

    msgText = 'You got %.0f %% correct!' % (percentCorrect, )
    msgPC = visual.TextStim(winSub, pos=[0, +3], text=msgText)
    msgPC.draw()
    winSub.flip()

    #    numpy.savetxt('debug.txt',debugVar,fmt='%.3f')
    #create an output file in a subdirectory
    #check for the subdirectory
    if os.path.isdir('subjectResponseFiles') == False:
        #create directory
        os.makedirs('subjectResponseFiles')
    nowTime = datetime.datetime.now()
    outFile = 'motionResponse%04d%02d%02d_%02d%02d.txt' % (
        nowTime.year, nowTime.month, nowTime.day, nowTime.hour, nowTime.minute)
    outFilePath = os.path.join('subjectResponseFiles', outFile)
    numpy.savetxt(outFilePath, findResp, fmt='%.0f')
    core.wait(2)
    #    winOp.close()
    winSub.close()
Пример #12
0
win = visual.Window([800, 600])

redPill = visual.Circle(win, size=[0.1, 0.4], fillColor='red')
bluePill = visual.Circle(win, size=[0.1, 0.4], fillColor='blue')

mouse = event.Mouse()

for thisTrial in range(nTrials):
    lastChoice = None
    core.wait(0.5)
    for frameN in range(1000):
        redTheta = frameN * 0.2
        blueTheta = frameN * (-0.4)

        redPill.pos = misc.pol2cart(redTheta, radius=0.6)
        bluePill.pos = misc.pol2cart(blueTheta, radius=0.8)

        redPill.draw()
        bluePill.draw()
        win.flip()

        if sum(mouse.getPressed()):
            if redPill.contains(mouse) and lastChoice != 'red':
                print("You chose the red pill")
                lastChoice = 'red'
            elif bluePill.contains(mouse) and lastChoice != 'blue':
                print("You chose the blue pill")
                lastChoice = 'blue'
            else:
                print("you missed!!!")
Пример #13
0
    ExpectedTR = arrays["TR"]

NrOfSteps = arrays["NrOfSteps"]
NrOfVols = arrays["NrOfVols"]
print('TARGETS: ')
print TargetOnsetinSec

# calculate
Offset = pixCover / NrOfSteps / 2
aryOri = [0, 45, 90, 135, 180, 225, 270, 315]
distances = np.linspace(-pixCover / 2 + Offset, pixCover / 2 - Offset,
                        NrOfSteps)

aryPosPix = []
for ori in [90, 45, 180, 135, 270, 225, 0, 315]:
    temp = zip(*pol2cart(np.tile(ori, NrOfSteps), distances))
    aryPosPix.append(temp)

# create array to log key pressed events
TriggerPressedArray = np.array([])
TargetPressedArray = np.array([])

logFile.write('Conditions=' + unicode(Conditions) + '\n')
logFile.write('TargetOnsetinSec=' + unicode(TargetOnsetinSec) + '\n')
logFile.write('TargetDur=' + unicode(TargetDur) + '\n')

# %%
"""STIMULI"""

# INITIALISE SOME STIMULI
grating = visual.GratingStim(