Пример #1
0
    def __init__(self, params=None, reportobj=None, subroutines=[]):
        logging.LogFile(params['cwd'] + os.sep + params['logfile'],
                        level=logging.INFO,
                        filemode='w')
        logging.LogFile(level=logging.ERROR)

        logging.info('Using Python ' + sys.version)

        self.args = sys.argv
        self.params = self.update_params(self.args, params)
        self.win = None
        self.model = None
        self.routines = subroutines
        self.thisExp = None
        self.name = params['name']
        self.cwd = params['cwd']
        self.reportobj = reportobj

        if params['monitor'] not in monitors.getAllMonitors():
            logging.error('monitor not found: ' + params.monitor)
            logging.info('available monitors: ' +
                         ' '.join(monitors.getAllMonitors()))
            logging.info('Define monitor in monitor center.')
            logging.info('To launch monitor center, type:\n'
                         'python -m psychopy.monitors.MonitorCenter')
            core.quit()
        else:
            self.monitor = monitors.Monitor(
                '',
                width=None,
                distance=self.params['viewing_distance'],
                gamma=None,
                notes=None,
                useBits=None,
                verbose=True,
                currentCalib=None,
                autoLog=True)
            self.monitor.setSizePix((1920, 1280))
            self.monitor.setWidth(54.15)

            logging.exp('using monitor: ' + self.params['monitor'] +
                        ' with viewing_distance=' +
                        str(self.params['viewing_distance']) + ' cm\n' +
                        ' resolution (pixel/deg): ' +
                        str(deg2pix(1, self.monitor)))
            # TODO: change screen_pixel_size back to calculation from monitor
            # TODO: change the monitor definition width so that screen_pixel_size=0.282
            if 'screen_pixel_size' not in self.params['model']:
                self.params['model']['screen_pixel_size'] = pix2cm(
                    1, self.monitor) * 10.0

            #self.params['model']['screen_pixel_size'] = 0.282
            self.params['model'][
                'viewing_distance'] = self.params['viewing_distance'] / 2.54

        self.expInfo = params['exp_info']
        self.expInfo['date'] = data.getDateStr()

        # Ensure that relative paths start from the same directory as this script
        _thisDir = os.path.dirname(os.path.abspath(__file__))
        os.chdir(_thisDir)
        # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc
        runsubject = self.params['runsubject']
        if runsubject:
            self.filename = self.cwd + os.sep + u'data' + os.sep + '%s_%s_%s' % (
                self.expInfo['participant'], params['name'],
                self.expInfo['date'])
        else:
            self.filename = self.cwd + os.sep + u'data' + os.sep + 'model-' + params[
                'expName']
Пример #2
0
import nidaqTools as daqT

#%% Initialize 
# Reading stimulus information & generating epochs
# Ask user where the stim input file is located
stim_fname = gui.fileOpenDlg(os.getcwd())[0]
# Pre-organizing the routine and epochs
routine = PyStimRoutine(stim_fname)
print('Stimulus routine with {eN} epochs is generated...'.format(\
    eN = routine.total_epoch_n))

#%% We need a monitor and a window to present the stimulus
# Parameters of projection for stimulus creation
(proj_params, use_nidaq) = pt.setup_params(stim_fname)
# Overwrite the current monitor parameters
mon = monitors.Monitor(proj_params["monitorName"])

win = visual.Window(
    size=mon.getSizePix(), viewScale =proj_params['viewScale'],
    pos = [proj_params['posX'],proj_params['posY']],
    useFBO = True, screen = proj_params['onDLP'],
    allowGUI=False, color=[-1, -1, -1],
    viewOri = 0.0, fullscr=False, monitor=mon)

#Detecting dropped frames if any
win.setRecordFrameIntervals(True)
win._refreshTreshold = 1/proj_params["monitorRefreshRate"]+0.004 # warn if frame is late more than 4 ms
logging.console.setLevel(logging.WARNING)

# Perspective correction
if proj_params['warper']:
Пример #3
0
            break
    else:
        #ctypes.windll.user32.MessageBoxA(0,'Please specify a number','Invalid participant number',0)      
        break
outputFile = open(fileName, 'w')

subjectNumber = expInfo['subjNum']


#Column headers for output file
outStr = "Time\tValueDisplayed\tButtonPressed(z=yes,m=no)\tResponseTime\t"
outputFile.write(outStr + "eol\n")

# Setup the Psycho variables (screen, stimuli, sounds, ect)
win = visual.Window(fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='FenskeLabTestingComps', color=[0,0,0], colorSpace='rgb', units='deg')
mon = monitors.Monitor('FenskeLabTestingComps')
trialClock = core.Clock()
eventClock = core.Clock()
evalClock = core.Clock()
keyResp = event.BuilderKeyResponse()  # create an object of type KeyResponse

#Base trial value, will change when task starts
trialValue = 10.00

instructionsOne = visual.ImageStim(win=win,image = 'Slide16.jpg', pos=[0,0], size=(20,15))
instructionsOne.setAutoDraw(True)
win.flip()
event.waitKeys()
instructionsOne.setAutoDraw(False)

instructionsTwo = visual.ImageStim(win=win,image = 'Slide17.jpg', pos=[0,0], size=(20,15))
Пример #4
0
# make a sequence of fix-stim jitter
fix_seq = np.random.uniform(timing_info['fix_mean'] - timing_info['fix_range'],
                            timing_info['fix_mean'] + timing_info['fix_range'],
                            size=(param['n_blocks'], param['n_trials']))
fix_frames_seq = (fix_seq * win_info['framerate']).round().astype(int)
select_seq = np.random.uniform(
    timing_info['select_mean'] - timing_info['select_range'],
    timing_info['select_mean'] + timing_info['select_range'],
    size=(param['n_blocks'], param['n_trials']))
select_frames_seq = (select_seq * win_info['framerate']).round().astype(int)

##################################
###      MAKE STIMULI          ###
##################################
mon = monitors.Monitor('cocoLab',
                       width=win_info['screen_width'],
                       distance=win_info['screen_distance'])
mon.setSizePix(win_info['win_size'])
win = visual.Window(size=win_info['win_size'],
                    color=win_info['bg_color'],
                    fullscr=win_info['fullscr'],
                    units="deg",
                    autoLog=0,
                    monitor=mon)

# and text stuff
startExp = visual.TextStim(
    win,
    text='Willkommen zur Casinoaufgabe!\nGleich geht es los.',
    color=win_info['fg_color'],
    height=0.6,
Пример #5
0
    def renderThreadFcn(self):
        ''' Makes a PsychoPy window and begins listening for commands '''

        #setup must be done in same thread as rendering
        from psychopy import visual, logging, core, filters, event, monitors

        self.mon = monitors.Monitor('StimMonitor')
        self.mon.setDistance(25)
        self.mon.setSizePix([1920, 1080])
        self.mon.setWidth(51)
        res = [1920, 1080]
        if self.windowed:
            res = [800, 600]

        #make window
        self.win = visual.Window(size=res,
                                 monitor=self.mon,
                                 fullscr=(not self.windowed),
                                 screen=1)

        #stimulus
        self.grating = visual.GratingStim(self.win,
                                          tex="sqr",
                                          mask="gauss",
                                          units="deg",
                                          size=(30, 30),
                                          sf=0.05,
                                          ori=2,
                                          interpolate=True)
        self.drawGrating = True

        self.patch = visual.ImageStim(self.win,
                                      color=(0.0, 0.0, 0.0),
                                      units="deg",
                                      mask="circle",
                                      size=(50, 50),
                                      texRes=1024)
        self.drawPatch = False

        #photodiode stim
        photodiodeStimPos = (-self.mon.getSizePix()[0] / 2,
                             self.mon.getSizePix()[1] / 2)
        self.photodiodeStim = visual.ImageStim(self.win,
                                               color=(-1.0, -1.0, -1.0),
                                               units="pix",
                                               pos=photodiodeStimPos,
                                               size=(200, 200))
        self.drawPhotodiodeStim = True  #will be manually drawn on top of whatever stim is up

        #render loop
        timeBetweenFrames = 0.008
        while True:
            #update window
            self.win.flip()
            t0 = time.time()

            #read commands
            self.doCommands()

            #update stim phase based on jitter / temporal frequency
            self.updatePhase()

            #update photodiode stim
            self.updatePhotodiodeStim()

            #draw stims
            if self.drawPatch:
                self.patch.draw()
            if self.drawGrating:
                self.grating.draw()
            if self.drawPhotodiodeStim:
                #must draw this last so it's on top
                self.photodiodeStim.draw()

            elapsed = time.time() - t0
            #sleep for half the time remaining until the next frame
            sleepTime = max((timeBetweenFrames - elapsed) / 2, 0.005)
            time.sleep(sleepTime)
Пример #6
0
*modified based on visual_grating_drifting.py
*upload and run the arduino code first and then run the python code
'''

import serial
from psychopy import visual, monitors, logging
import time

if __name__ == "__main__":

    #set variables for serial communication
    port = '/dev/cu.usbmodem142301'
    baud_rate = 9600

    # visual stimulus session
    NEC = monitors.Monitor('NEC')
    NEC.setDistance(14)  # mice is cm from the screen
    NEC.setSizePix([1280, 1024])  # resolution(pixel) of the monitor
    NEC.setWidth(37.5)  # width of monitor, cm
    win0 = visual.Window(screen=1,
                         monitor=NEC,
                         fullscr=True,
                         color=[-1, -1, -1],
                         unit='deg')  # create window
    grat_stim_h = visual.GratingStim(
        win=win0,
        tex='sin',
        units='deg',
        pos=(0.0, 0.0),  # horizontal grating
        size=100000,
        sf=0.04,
            interpolate=True,
            autoLog=False)
        imagesRight.append(imageObjectRight)
        drawDebug = False
        if drawDebug:
            imageObjectLeft.draw()
            myWin.flip()

    imageObjects = [imagesLeft, imagesRight]
    return imageObjects


if __name__ == '__main__':  #Running this file directly, must want to test functions in this file
    from psychopy import monitors
    monitorname = 'testmonitor'
    mon = monitors.Monitor(monitorname, width=40.5, distance=57)
    windowUnits = 'deg'  #purely to make sure lineup array still works when windowUnits are something different from norm units
    bgColor = [-.7, -.7, -.7]
    myWin = visual.Window(monitor=mon,
                          colorSpace='rgb',
                          fullscr=True,
                          color=bgColor,
                          units=windowUnits)
    #myWin = visual.Window(monitor=mon,size=(widthPix,heightPix),allowGUI=allowGUI,units=units,color=bgColor,colorSpace='rgb',fullscr=fullscr,screen=scrn,waitBlanking=waitBlank) #Holcombe lab monitor

    logging.console.setLevel(logging.WARNING)
    autopilot = False
    clickSound, badClickSound = setupSoundsForResponse()

    imagesOrLetters = False
    if imagesOrLetters:
Пример #8
0
# Handles exp data as a whole. 
thisExp = data.ExperimentHandler(
        name=expName,
        extraInfo=fixedExpInfo,
        savePickle=True,
        saveWideText=True,
        dataFileName=fileName)

# --------------- MONITOR & STIMULI CREATION --------------- #

widthPix = 720
heightPix = 540
# widthPix = 2560
# heightPix = 1600
# mon = monitors.Monitor('test', width=53.1, distance=60.)
mon = monitors.Monitor('testMonitor')
# mon.setSizePix((widthPix, heightPix))
win = visual.Window(
    monitor=mon,
    # size=(widthPix, heightPix),
    colorSpace='rgb',
    color = '#000000',
    fullscr=False,
    allowGUI=False, #switch to true to add to exp window
    units='deg')

# if i want to keep track of frames for measuring RT
win.recordFrameIntervals = True

#Changing the font to Arial fixed the right arrow problem.
target_arrow = visual.TextStim(win, 
Пример #9
0
    expInfo['participant'], expInfo['expName'], expInfo['run'],
    expInfo['date'])

# save a log file and set level for msg to be received
logFile = logging.LogFile(logFileName + '.log', level=logging.INFO)
logging.console.setLevel(logging.WARNING)  # set console to receive warnings

# %% MONITOR AND WINDOW

# set monitor information:
distanceMon = 29.5  # [99 for Nova coil]
widthMon = 35  # [30 for Nova coil]
PixW = 1920.0  # [1920.0] in scanner
PixH = 1200.0  # [1200.0] in scanner

moni = monitors.Monitor('testMonitor', width=widthMon, distance=distanceMon)
moni.setSizePix([PixW, PixH])  # [1920.0, 1080.0] in psychoph lab

# log monitor info
logFile.write('MonitorDistance=' + unicode(distanceMon) + 'cm' + '\n')
logFile.write('MonitorWidth=' + unicode(widthMon) + 'cm' + '\n')
logFile.write('PixelWidth=' + unicode(PixW) + '\n')
logFile.write('PixelHeight=' + unicode(PixH) + '\n')

# set screen:
myWin = visual.Window(size=(PixW, PixH),
                      screen=0,
                      winType='pyglet',
                      allowGUI=False,
                      allowStencil=False,
                      fullscr=True,
fileName = expInfo['observer'] + expInfo['dateStr']
dataFile = open(fileName + '.csv',
                'w')  #a simple text file with 'comma-separated-values'
dataFile.write('targetSide,oriIncrement,correct\n')

#create the staircase handler
staircase = data.StairHandler(
    startVal=20.0,
    stepType='db',
    stepSizes=[8, 4, 4, 2, 2, 1, 1],
    nUp=1,
    nDown=3,  #will home in on the 80% threshold
    nTrials=50)

#create window and stimuli
myMon = monitors.Monitor('MyMon')
myMon.setDistance(70)
myMon.setWidth(30)
myMon.setSizePix([1280, 1024])

win = visual.Window([800, 600], allowGUI=False, units='deg',
                    monitor=myMon)  #, monitor='testMonitor', units='deg')
foil = visual.PatchStim(win,
                        sf=1,
                        size=4,
                        mask='gauss',
                        ori=expInfo['refOrientation'])
target = visual.PatchStim(win,
                          sf=1,
                          size=4,
                          mask='gauss',
Пример #11
0
    def __init__(self, CONF):
        self.CONF = CONF

        # fetch the most recent calib for this monitor
        mon = monitors.Monitor('tesfgft')
        mon.setWidth(CONF["screen"]["size"][0])
        mon.setSizePix(CONF["screen"]["resolution"])

        self.window = visual.Window(
            size=CONF["screen"]["resolution"],
            # display_resolution=CONF["screen"]["resolution"],
            monitor=mon,
            fullscr=CONF["screen"]["full"],
            # units="cm",
            allowGUI=True
        )

        # set up instructions and overview
        self.task = visual.TextStim(self.window,
                                    text=CONF["task"]["name"],
                                    alignHoriz='center',
                                    alignVert='center',
                                    height=CONF["instructionSizes"]["taskHeight"],
                                    pos=CONF["instructionSizes"]["taskPos"],
                                    units="cm"
                                    )
        self.session = visual.TextStim(self.window,
                                       text="P" + CONF["participant"] +
                                       " Session " +
                                       CONF["session"] + " " +
                                       CONF["version"],
                                       pos=CONF["instructionSizes"]["sessionPos"],
                                       height=CONF["instructionSizes"]["sessionHeight"],
                                       alignHoriz='center',
                                       alignVert='center',
                                       units="cm"
                                       )

        self.instructions = visual.TextStim(
            self.window, text=CONF["instructions"]["text"], height=CONF["instructionSizes"]["instructionsHeight"], units="cm")

        self.startPrompt = visual.TextStim(
            self.window, text=CONF["instructions"]["startPrompt"], height=CONF["instructionSizes"]["startPromptHeight"], units="cm", pos=(0, -CONF["screen"]["size"][1]/2+3))

        self.cue = visual.TextStim(self.window)

        # Setup fixation box
        self.fixation_box = visual.Rect(
            self.window, height=CONF["fixation"]["height"],
            width=CONF["fixation"]["width"],
            fillColor=CONF["fixation"]["boxColor"],
            lineColor=CONF["fixation"]["boxColor"],
            units=CONF["screen"]["units"])

        # setup stopwatch

        # self.counter = visual.TextStim(self.window)
        self.counter = visual.TextBox(window=self.window,
                                      # border_color=[-1, -1, 1],
                                      ## grid_color=[-1, -1, 1],
                                      ## textgrid_shape=(10, 1),
                                      # grid_stroke_width=1,
                                      # textgrid_shape=[20, 4],
                                      font_color=[1, 1, 1],
                                      size=(1, 1),
                                      font_size=41,
                                      pos=(0.05, 0),
                                      grid_horz_justification='center',
                                      grid_vert_justification='center',
                                      #   units='cm', #TODO: get this to work
                                      )
Пример #12
0
    expInfo = {'Participant': ''}

    #DIALOGUE WINDOW FOR PARTICIPANT NAME
    dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName)
    if dlg.OK == False:
        core.quit()

    #CREATE FILE NAME, PRINT HEADER IF FILE DOESN'T EXIST
    filename = OUTPATH + u'%s_%s_%s' % (expInfo['Participant'], date,
                                        expName) + '.csv'
    if not os.path.isfile(filename):
        csvOutput(
            ["Direction", "Letter Height (degrees)", "Eccentricity (degrees)"])

#WINDOW CREATION
mon = monitors.Monitor('TV')
mon.setWidth(200)
win = visual.Window(size=(3840, 2160),
                    fullscr=False,
                    screen=-1,
                    winType='pyglet',
                    allowGUI=True,
                    allowStencil=False,
                    monitor=mon,
                    color='grey',
                    colorSpace='rgb',
                    blendMode='avg',
                    useFBO=True,
                    units='cm')

#INITIALIZE KEYBOARD
expName = 'orientation_search' 
expInfo = {u'session': u'001', u'participant': u''}
dlg = gui.DlgFromDict(dictionary=expInfo, title=expName)
if dlg.OK == False: core.quit()  # user pressed cancel
expInfo['date'] = data.getDateStr()  # add a simple timestamp
expInfo['expName'] = expName

expInfo['graphic_card'] = info.get_renderer()
cpu_info = cpuinfo.get_cpu_info()
expInfo['cpu_info'] = cpu_info['brand']
expInfo['pc_name'] = platform.node() 
expInfo['monitorName'] = monitorName
expInfo['resolution'] = '_'.join(str(x) for x in resolution)

mon = monitors.Monitor(monitorName)
win = visual.Window(resolution, units='deg', monitor=mon, fullscr = True)

if (mon.getSizePix()!=resolution):
    print 'Resolution in monitor center is different from the one requested for this experiment. Please make them equal to make sure that the computations of visual angle will be correct for the resolution you want.'
    core.quit()

if (not np.array_equal(win.size,resolution)):
    print 'Actual display resolution differs from requested. PsychoPy cannot change resolution for you. Please do it yourself before running the script or correct requested resolution.'
    core.quit()


lineSize = 1 #deg - this is NOT the actual line size, but rather a size of the square in which the line is a diagonal (historical reasons)

# line texture
smoothMask = -np.ones([16,16], 'f')
Пример #14
0
from EyeLinkCoreGraphicsPsychoPy import EyeLinkCoreGraphicsPsychoPy
from psychopy.constants import STOPPED, PLAYING

# SETP 1: connect to the tracker
tk = pylink.EyeLink('100.1.1.1')

# STEP 2: Open an EDF data file on the Host
tk.openDataFile('video.edf')
# add personalized data file header (preamble text)
tk.sendCommand("add_file_preamble_text 'Psychopy video demo'")

# STEP 3: # open a window for graphics and calibration
scnWidth, scnHeight = (1280, 800)

#always create a monitor object before you run the script
customMon = monitors.Monitor('demoMon', width=35, distance=65)
customMon.setSizePix((scnWidth, scnHeight))

# open a window
win = visual.Window((scnWidth, scnHeight),
                    fullscr=True,
                    monitor=customMon,
                    units='pix',
                    allowStencil=True)

# require Pylink to use custom calibration graphics--"EyeLinkCoreGraphicsPsychopy.py"
graphics = EyeLinkCoreGraphicsPsychoPy(tk, win)
pylink.openGraphicsEx(graphics)

# STEP 4: Setup Host parameters
# put the tracker in idle mode before we change its parameters
import pandas as pd
import os
import numpy as np
import glob
#Not sure all of these are needed

############  SET MONITOR VARIABLES ###########################
# Monitor parameters
MON_distance = 60  # Distance between subject's eyes and monitor
MON_width = 34  # Width of your monitor in cm
MON_size = [1920, 1080]  # Pixel-dimensions of your monitor, width / height
MON_frame_rate = 60  # Hz: usually 60, but you can always check with the function getActualFrameRate

# Create monitor
my_monitor = monitors.Monitor(
    'testMonitor', width=MON_width, distance=MON_distance
)  # Create monitor object from the variables above. This is needed to control size of stimuli in degrees.
my_monitor.setSizePix(MON_size)

############# GET PARTICIPANT INFO USING GUI ###########################
popup = gui.Dlg(title='animate inanimate distinction')  # The titel of the box
popup.addField('ID: ')  # Imput for alias to distinguish between participants
popup.addField("age: ")
popup.addField("gender: ", choices=['female', 'male', "other"])
popup.addField("Scanner: ", choices=['Prisma', 'Skyra'])
popup.addField("Scan day: ", choices=['Tuesday', 'Wednesday'])
popup.show()  # Shows the popup
if popup.OK:  # If there is imput in the popup, then it is saved to ID
    EXP_info = popup.data
elif popup.Cancel:  # If not the program is closed
    core.quit()
Пример #16
0
from psychopy import visual, monitors
import psychopy.event

m = monitors.Monitor("default")

win = psychopy.visual.Window(monitor=m,
                             size=[400, 400],
                             units="pix",
                             fullscr=False)

grating = psychopy.visual.GratingStim(win=win, units="pix", size=[80, 80])

# basic:
grating.draw()
img = win.getMovieFrame()  # get the output image

#----------------------------------
# Phase:

#grating_hpos = [-150, -50, 50, 150]
#grating_phase = [0.0, 0.16, 0.33, 0.5]

#for i in range(4):
#    grating.phase = grating_phase[i]
#    grating.pos = [grating_hpos[i], 0]
#    grating.draw()

#----------------------------------
# Frequency:

#grating.sf = 5.0/80.0
Пример #17
0
def main():
    """ Summary of workflow:

    Preparation
    -----------
    1. Double-check of required materials & the validity of preference setting
    2. Setup experiment info
    3. Setup the window and begin the session
    4. Introduce task

    Conduct Experiment
    ------------------
    5. Schedule and run each block
    6. End the session and write experiment info (start info + preference + runtime info) to log
    7. clean up
    """

    # Double-check of required materials & the validity of preference setting
    double_check()

    # Setup experiment info
    start_info = obtain_start_info()  # Subject ID & session No
    dual_task_cond, shape_task_cond, filling_task_cond = import_conditions()
    runtime_info = {}
    runtime_info['session_start'] = time.time()

    # Setup the window and begin the session
    exp_mon = monitors.Monitor(name='testMonitor', width=mon_width)
    win = visual.Window(size=(mon_width, mon_height),
                        fullscr=True,
                        color='black',
                        monitor=exp_mon,
                        units='norm')
    drawer = Drawer(win)

    # Introduce task (task overview)
    instruction = visual.ImageStim(win, size=(1.5, 1.5))
    for i in range(3):
        present_instruction(win, instruction, i)

# Schedule and run each block
# Practice session
    if include_practice:
        present_instruction(win, instruction,
                            7)  # start message of practice session
        conduct_prac_block(win, instruction, 3, drawer, shape_task_cond)
        conduct_prac_block(win, instruction, 4, drawer, filling_task_cond)
        conduct_prac_block(win, instruction, 5, drawer, dual_task_cond)
        present_instruction(win, instruction,
                            8)  # end message of practice session
    # Formal session
    conduct_fml_block(win, instruction, 3, drawer, shape_task_cond, {
        **start_info,
        **{
            'block': 'shape_task'
        }
    })
    conduct_fml_block(win, instruction, 4, drawer, filling_task_cond, {
        **start_info,
        **{
            'block': 'filling_task'
        }
    })
    conduct_fml_block(win, instruction, 5, drawer, dual_task_cond, {
        **start_info,
        **{
            'block': 'dual_task'
        }
    })
    present_instruction(win, instruction,
                        6)  # end message of the whole session

    # End the session and write experiment info to log
    runtime_info['session_end'] = time.time()
    preferences = {
        'include_practice': include_practice,
        'display_time': display_time,
        'blank_time': blank_time,
        'feedback_time': feedback_time,
        'left_key': list(response_key.keys())[0],
        'right_key': list(response_key.keys())[1],
        'num_trial_prac': num_trial_prac,
        'num_trial_fml': num_trial_fml
    }
    exp_info = {**start_info, **preferences, **runtime_info}
    exp_record = pd.DataFrame([exp_info], columns=exp_info.keys())
    need_header = not os.path.exists(exp_info_log_path)
    with open(exp_info_log_path, 'a') as f:
        exp_record.to_csv(f, header=need_header, index=False)


# cleanup
    win.close()
    core.quit()
Пример #18
0
fast_trial = ("Too fast! \nSlow down. \nYou can continue in 5 seconds.")
break_inst = (
    "Feel free to take a break! \nPress the green button when you're ready to continue."
)

#initialize dependent variables
rt_list = []
choice_list = []
accuracy_list = []

#instantiate psychopy object instances
clock = core.Clock()
expTime_clock = core.Clock()
trialTime_clock = core.Clock()

testing_monitor = monitors.Monitor('testing_computer')
testing_monitor.setSizePix = [1920, 1080]
testing_monitor.saveMon()

screen_size = testing_monitor.setSizePix
center = [0, 0]

if screen_size != testing_monitor.setSizePix:
    center[0] = (testing_monitor.setSizePix[0] / 2) - (screen_size[0] / 2)
    center[1] = (testing_monitor.setSizePix[1] / 2) - (screen_size[1] / 2)

window = visual.Window(size = screen_size, units='pix', monitor = testing_monitor, color = [-1,-1,-1], \
       colorSpace = 'rgb', blendMode = 'avg', useFBO = True, allowGUI = \
       False,fullscr=True, pos=center)

break_msg = visual.TextStim(win=window,
Пример #19
0
# indetify the monitors
#create two monitors 
#display text on one or the other or both


from psychopy import visual,event,monitors,core


# Monitor parameters
MON_DISTANCE = 16  # Distance between subject's eyes and monitor
MON_WIDTH = 20  # Width of your monitor in cm
#MON_SIZE = (2560,1440)
MON_SIZE = [2048,1536] # Pixel-dimensions of your monitor

#1. creates window in which the grating will be placed (background)
monitor0 = monitors.Monitor('mon0', width=MON_WIDTH, distance=MON_DISTANCE)  # Create monitor object from the variables above. This is needed to control size of stimuli in degrees.
monitor0.setSizePix(MON_SIZE)


# create stimulus window
win0 = visual.Window(
    monitor=monitor0,
    screen = 2,
    size=MON_SIZE,
    color=[0.169,0.169, 0.169], #Color of background as [r,g,b].Each take values between -1.0 and 1.0.
    units="deg",
    fullscr=True
)

# create stimulus window
win1 = visual.Window(
Пример #20
0
from psychopy import visual, core, monitors

mon = monitors.Monitor('iMac-bgur')
mon.setSizePix = (4023 ,2304)
mon.setWidth = 47.57
mon.setDistance = 57

refresh_rate = 60.0

pix_cm = mon.getSizePix()[0]/mon.getWidth()


total_degrees = 5

# Setup stimulus
win = visual.Window(
    size=(500 , 500), fullscr=False, 
    screen=0, winType='pyglet',useRetina=True,
    monitor=mon, color=[0,0,0], colorSpace='rgb')
# grating = visual.GratingStim(win, tex='sin', sf=5, name='grating',size=(1,1))


velocity = 2.5 # dps
spatial_wavelength = 2.5

sf = 1/spatial_wavelength
grating = visual.GratingStim(
            win=win, name='grating',tex='sin', 
            size=(total_degrees, total_degrees), 
            sf=sf,units='degFlat')
Пример #21
0
if quitFinder:
    import os
    applescript = "\'tell application \"Finder\" to quit\'"
    shellCmd = 'osascript -e '+applescript
    os.system(shellCmd)

numDisksToPresent = 10
SOAms = 100
letterDurMs = 1000
bgColor = 'white'
stimColor = 'black'

monitorname = 'testmonitor'
waitBlank = False
# relying on  monitorwidth cm (39 for Mitsubishi to do deg calculations) and gamma info in calibratn
mon = monitors.Monitor(monitorname, width=monitorwidth, distance=viewdist)
mon.setSizePix((widthPix, heightPix))
units = 'deg'  # 'cm'

def openMyStimWindow():  # make it a function because have to do it several times, want to be sure is identical each time
    myWin = visual.Window(monitor=mon, size=(widthPix, heightPix), allowGUI=allowGUI, units=units, color=bgColor,colorSpace='rgb', fullscr=fullscr, screen=scrn, waitBlanking=waitBlank)  # Holcombe lab monitor
    return myWin


myWin = openMyStimWindow()
refreshMsg2 = ''
if not checkRefreshEtc:
    refreshMsg1 = 'REFRESH RATE WAS NOT CHECKED'
    refreshRateWrong = False
else:  # checkRefreshEtc
    runInfo = psychopy.info.RunTimeInfo(
Пример #22
0
#There's no lowercase in sloan
if cueType is 'lowerCase':
    font = 'Arial'

viewdist = 57.  #cm

monitorname = 'testmonitor'

waitBlank = False

widthPix = 1680  #monitor width in pixels of Agosta
heightPix = 1050  #800 #monitor height in pixels
monitorwidth = 40.5

mon = monitors.Monitor(
    monitorname, width=monitorwidth, distance=viewdist
)  #relying on  monitorwidth cm (39 for Mitsubishi to do deg calculations) and gamma info in calibratn

mon.setSizePix((widthPix, heightPix))

units = 'deg'  #'cm'

scrn = 1

doStaircase = False

screenValues = {
    'widthPix': widthPix,  #monitor width in pixels of Agosta
    'heightPix': heightPix,  #800 #monitor height in pixels
    'monitorwidth': 40.5,  #monitor width in cm
    'scrn':
Пример #23
0
    print('scrn = ', scrn, ' from dialog box')
    fullscrn = infoFirst['Fullscreen (timing errors if not)']
    refreshRate = infoFirst['Screen refresh rate']

    #monitor parameters
    widthPix = 1280  #1440  #monitor width in pixels
    heightPix = 1024  #900 #monitor height in pixels
    monitorwidth = 40.5  #28.5 #monitor width in centimeters
    viewdist = 55.
    #cm
    pixelperdegree = widthPix / (atan(monitorwidth / viewdist) / np.pi * 180)
    bgColor = [-1, -1, -1]  #black background
    monitorname = 'testMonitor'  # 'mitsubishi' #in psychopy Monitors Center

    mon = monitors.Monitor(
        monitorname, width=monitorwidth,
        distance=viewdist)  #fetch the most recent calib for this monitor
    mon.setSizePix((widthPix, heightPix))
    myWin = openMyStimWindow(mon, widthPix, heightPix, bgColor, allowGUI,
                             units, fullscrn, scrn, waitBlank)
    myWin.setRecordFrameIntervals(False)

    trialsPerCondition = 2  #default value

    refreshMsg2 = ''
    if not checkRefreshEtc:
        refreshMsg1 = 'REFRESH RATE WAS NOT CHECKED'
        refreshRateWrong = False
    else:  #checkRefreshEtc
        runInfo = psychopy.info.RunTimeInfo(
            win=
Пример #24
0
from psychopy import visual, event, core, monitors
import pandas as pd

monitor_name = "ObiMonitor"
scnWidth, scnHeight = monitors.Monitor(monitor_name).getSizePix()

mywin = visual.Window([scnWidth-10, scnHeight-10], units="pix",
                  monitor=monitor_name, fullscr=False, waitBlanking=False, allowGUI=True)
                  
circle = visual.Circle(
    win=mywin,
    units="pix",
    radius=2,
    fillColor=[-1, -1, -1],
    lineWidth=0)

line = visual.Line(mywin, lineColor=[-1, -1, -1], lineWidth=5)


def draw(file_name, xLoc):
    """ Takes in filename and column location of x coordinates """
    
    df = pd.read_excel(file_name)
    df = df.fillna("None")  # fill all nan values with "None" string
    length = len(df) - 1
    
    for i in range(length):  # loop through rows of points
    
        drawLine = False
        drawCircle = False
        firstPoint = tuple([df[xLoc][i], df[xLoc + 1][i]])  # xLoc + 1 = yLoc ==> column location of y coordinates