Ejemplo n.º 1
0
def get_config():
    # 读取配置文件
    try:
        config = fromFile('config.pickle')
    except Exception as e:
        config = {'姓名': 'user01', '性别': ['男', '女'], '年龄': 18, '测试次数': 100}
    finally:
        now = datetime.now()
        config['测试时间'] = now.strftime('%Y-%m-%d %H:%M:%S')
    # 获取用户输入
    try:
        dlg = gui.DlgFromDict(config,
                              title='请输入测试相关信息',
                              order=['姓名', '性别', '年龄', '测试次数', '测试时间'],
                              fixed=['测试次数', '测试时间'])
        if dlg.OK:
            assert config['性别'] in ['男', '女']  # 判断输入是否有误,有误则抛出异常
            assert isinstance(config['年龄'], int)
            assert isinstance(config['测试次数'], int)
            toFile('config.pickle', config)
            return config
        else:
            core.quit()
            sys.exit()
    except Exception as e:
        print(e)
        print('输入有误,请重新启动程序后输入')
        core.quit()
        sys.exit()
def CoolDown():
    
    # display cool-down message
    message1.setText("That's the end! ")
    message2.setText("Press 'q' or 'escape' to end the session.")
    win.logOnFlip(level=logging.EXP, msg='Display TheEnd')
    win.callOnFlip(SendMessage,'DisplayTheEnd')
    message1.draw()
    message2.draw()
    win.flip()
    thisKey = event.waitKeys(keyList=['q','escape'])
    
    """
    # stop recording SMI via serial port
    myTracker.stop_recording()
    
    # save result
    myTracker.save_data(path=(filename+'.idf'))
    
    # close serial port
    myTracker.cleanup()
    """
    #"""
    # End EyeLink recording: add 100 msec of data to catch final events
    pylink.endRealTimeMode()
    pumpDelay(100)
    getEYELINK().stopRecording()
    while getEYELINK().getkey(): # not sure what this is for
        pass
    
    # File transfer and cleanup!
    getEYELINK().setOfflineMode()                          
    msecDelay(500)                 
    
    message1.setText("Sending EyeLink File...")
    message2.setText("Please Wait.")
    win.logOnFlip(level=logging.EXP, msg='Display SendingFile')
    message1.draw()
    message2.draw()
    win.flip()
    #Close the file and transfer it to Display PC
    getEYELINK().closeDataFile()
    getEYELINK().receiveDataFile(edfHostFileName, edfFileName)
    getEYELINK().close();
    
    #Close the experiment graphicss
    pylink.closeGraphics()
    #"""
    
    # stop sound
#    fullSound.stop()
    whiteNoiseSound.stop()
    pageSound.stop()
    
    # save experimental info (if we reached here, we didn't have an error)
    expInfo['tSound'] = tSound
    toFile(expInfoFilename, expInfo) # save params to file for next time
    
    # exit
    core.quit()
def CoolDown():
    # display cool-down message
    message1.setText("That's the end! ")
    message2.setText("Press 'q' or 'escape' to end the session.")
    win.logOnFlip(level=logging.EXP, msg='Display TheEnd')
#    win.callOnFlip(SendMessage,'Display TheEnd')
    message1.draw()
    message2.draw()
    win.flip()
    thisKey = event.waitKeys(keyList=['q','escape'])
    
    # save experimental info (if we reached here, we didn't have an error)
    toFile(expInfoFilename, expInfo) # save params to file for next time
    
    # exit
    core.quit()
Ejemplo n.º 4
0
def CoolDown():
    # display cool-down message
    message1.setText("That's the end! ")
    message2.setText("Press 'q' or 'escape' to end the session.")
    win.logOnFlip(level=logging.EXP, msg='Display TheEnd')
    #    win.callOnFlip(SendMessage,'Display TheEnd')
    message1.draw()
    message2.draw()
    win.flip()
    thisKey = event.waitKeys(keyList=['q', 'escape'])

    # save experimental info (if we reached here, we didn't have an error)
    toFile(expInfoFilename, expInfo)  # save params to file for next time

    # exit
    core.quit()
Ejemplo n.º 5
0
	def __init__(self, guiID=True, logging=True, display=False, shorten=True):
		# import test images
		try:  
		    self.expInfo = fromFile('lastParams.pickle')
		except:  
		    # create dictionary of robots that are needed
		    self.expInfo = {
		    "robot_1":"robot_imgs/stevie-rs.png",
		    "robot_2":"robot_imgs/pr2-rs.png",
		    "robot_3":"robot_imgs/pepper-rs.png",
		    "robot_4":"robot_imgs/sciprr-rs.png",
		    "robot_5":"robot_imgs/icub-rs.png",
		    "robot_6":"robot_imgs/flash-rs.png",
		    "robot_7":"robot_imgs/g5-rs.png",
		    "robot_8":"robot_imgs/poli-rs.png",
		    "button":"robot_imgs/button.png",
		    "robots": ["robot_1","robot_2","robot_3","robot_4","robot_5","robot_6","robot_7","robot_8"],
		    "testing_list": ["stevie","pr2","pepper","sciprr","icub","flash","g5","poli"]
		    }
		    self.expInfo['dateStr'] = data.getDateStr() 
		    toFile('lastParams.pickle', self.expInfo)

		# prompt for ID - needs to be before win opened
		if (guiID==True):    
			self.ID  = self.getID()
		else:
			self.ID = 'dummy'

		# setup window
		self.win = visual.Window(
			size=[1440/2, 900], 
			fullscr=display, 
			screen=0,
			units='pix')

		# setup clock and mouse events events
		self.clock = core.Clock()
		self.mouse = event.Mouse(visible=True,newPos=False,win=self.win)
Ejemplo n.º 6
0
from __future__ import division

from psychopy import core, visual, gui, data, event
from psychopy.tools.filetools import fromFile, toFile
import time, numpy

try:  # try to get a previous parameters file
    expInfo = fromFile('lastParams.pickle')
except:  # if not there then use a default set
    expInfo = {'observer': 'jwp', 'refOrientation': 0}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())  # add the current time

# present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='simple JND Exp', fixed=['date'])
if dlg.OK:
    toFile('lastParams.pickle', expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# make a text file to save data
fileName = expInfo['observer'] + dateStr
dataFile = open(fileName + '.txt', 'w')
dataFile.write('targetSide	oriIncrement	correct\n')

# create window and stimuli
globalClock = core.Clock()  # to keep track of time
trialClock = core.Clock()  # to keep track of time
win = visual.Window([800, 600],
                    allowGUI=False,
                    monitor='testMonitor',
                    units='deg')
Ejemplo n.º 7
0
probe2_options = ('Very aware','Somewhat aware','Neutral','Somewhat unaware','Very unaware')

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastSimonParams.pickle')
    expInfo['session'] +=1 # automatically increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Numerical SART task', fixed=['date'], order=['subject','session'])
if dlg.OK:
    toFile('lastSimonParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

#make a log file to save parameter/event  data
fileName = 'Simon-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='fileName: %s'%fileName)
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i'%isPractice)
logging.log(level=logging.INFO, msg='skipInstructions: %i'%skipInstructions)
logging.log(level=logging.INFO, msg='tSessionMax: %d'%tSessionMax)
logging.log(level=logging.INFO, msg='nBlocks: %d'%nBlocks)
    'fullScreen': True,       # run in full screen mode?
    'screenToShow': 1,        # display on primary screen (0) or secondary (1)?
    'fixCrossSize': 10,       # size of cross, in pixels
    'fixCrossPos': [0,0],     # (x,y) pos of fixation cross displayed before each stimulus (for gaze drift correction)
    'screenColor':(128,128,128) # in rgb255 space: (r,g,b) all between 0 and 255
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params) # save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
scriptName = os.path.basename(__file__)
try: # try to get a previous parameters file
    expInfo = fromFile('%s-lastExpInfo.pickle'%scriptName)
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except: # if not there then use a default set
    expInfo = {
        'subject':'1', 
        'session': 1, 
        'skipPrompts':False, 
        'paramsFile':['DEFAULT','Load...']}
Ejemplo n.º 9
0
    random.shuffle(newOrder)
    questions_all = [questions_all[i] for i in newOrder]
    options_all = [options_all[i] for i in newOrder]
    answers_all = [answers_all[i] for i in newOrder]
    params['questionOrder'] = newOrder
#    logging.log(level=logging.INFO, msg='questionOrder: ' + str(newOrder))

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)# save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile(expInfoFilename)
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'paramsFile':['DEFAULT','Load...']}
# overwrite if you just saved a new parameter set
if saveParams:
    expInfo['paramsFile'] = [newParamsFilename,'Load...']
dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time
Ejemplo n.º 10
0
    'usePhotodiode': False  # add sync square in corner of screen
    #'textBoxSize': [800,600] # [640,360]# [700, 500]   # width, height of text box (in pixels)
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(
        prompt='Save Params...',
        initFilePath=os.getcwd() + '/Params',
        initFileName=newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None:  # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)  # save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  #try to get a previous parameters file
    expInfo = fromFile('lastSingInfo.pickle')
    expInfo['session'] += 1  # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'], 'Load...']
except:  #if not there then use a default set
    expInfo = {
        'subject': '1',
        'session': 1,
        'paramsFile': ['DEFAULT', 'Load...']
    }
# overwrite if you just saved a new parameter set
Ejemplo n.º 11
0
 def getUser(self):
     print("Verify subject's information.")
     font = "Bookman"
     height = .5
     winIdx = 2
     win = self.windows[winIdx]
     prompt = visual.TextStim(
         win=win,
         height=height,
         pos=win.viewPos + np.array((0, 0)),
         flipHoriz=win.flipHoriz,
         font=font,
         alignHoriz='center',
         text='Please wait while we verify your information....')
     self.present(prompt)
     try:  # load the users file
         print('Reading file %s' %
               os.path.join(self.config.dataPath, self.config.userFile))
         allUsers = fromFile(
             os.path.join(self.config.dataPath, self.config.userFile))
     except:  # if not there then use a default set
         allUsers = []
     # prepare the dialoge
     #labels = {'Acuity':'Acuity: \t20/'}
     labels = {}
     order = [
         'Name', 'Age', 'Far Acuity', 'Near Acuity', 'IPD', 'ID', 'Date'
     ]
     self.userInfo = getattr(self.config, 'userInfo', None)
     if self.userInfo is None:
         self.userInfo = {'Name': '', 'Age': 20}
         self.userInfo['Date'] = [data.getDateStr()]  # add the current time
         self.userInfo['ID'] = len(allUsers)
         self.userInfo['Far Acuity'] = getattr(
             self.config, 'acuity',
             20)  #acuity if acuity is not None else '20'
         self.userInfo['Near Acuity'] = getattr(
             self.config, 'nearacuity',
             20)  #acuity if acuity is not None else '20'
         self.userInfo['IPD'] = getattr(
             self.config, 'ipd', 60)  #ipd if ipd is not None else '60'
         fixed = ['Date', 'ID']
         if getattr(self.config, 'acuity', None) is not None:
             fixed.append('Far Acuity')
         if getattr(self.config, 'nearacuity', None) is not None:
             fixed.append('Near Acuity')
         if getattr(self.config, 'ipd', None) is not None:
             fixed.append('IPD')
     else:
         # we have user info - need to update Date with a new trial
         self.userInfo['Date'].append(data.getDateStr())
         fixed = order
         try:
             user = [u for u in allUsers
                     if u['ID'] == self.userInfo['ID']][0]
             user['Date'] = self.userInfo['Date']
             self.newUser = False
         except IndexError:
             pass
         if 'Far Acuity' not in self.userInfo:
             self.userInfo['Far Acuity'] = self.userInfo['Acuity']
         if 'Near Acuity' not in self.userInfo:
             self.userInfo['Near Acuity'] = getattr(self.config,
                                                    'nearacuity', 20)
     # present a dialogue to change params
     dlg = gui.DlgFromDict(self.userInfo,
                           labels=labels,
                           title='User Info',
                           order=order,
                           fixed=fixed)
     if dlg.OK:
         if self.newUser:
             allUsers.append(self.userInfo)
         toFile(os.path.join(self.config.dataPath, self.config.userFile),
                allUsers)  # save users to file for next time
     else:
         self.userInfo = None
     self.clear(prompt)
Ejemplo n.º 12
0
     360]  # [854, 480] # [700, 500]   # width, height of movie (in pixels)
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(
        prompt='Save Params...',
        initFilePath=os.getcwd() + '/Params',
        initFileName=newParamsFilename,
        allowed="PICKLE files (*.pkl);;All files (*.*)")
    newParamsFilename = dlgResult
    if newParamsFilename is None:  # keep going, but don't save
        saveParams = False
    else:
        print("Saving %s" % newParamsFilename)
        toFile(newParamsFilename, params)  # save it!

# Pilot-only parameters
skipDur = 5.0  # the time (in seconds) that you can skip back or forward by pressing < or >

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  #try to get a previous parameters file
    expInfo = fromFile('lastMovieInfo.pkl')
    expInfo['session'] += 1  # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'], 'Load...']
except:  #if not there then use a default set
    expInfo = {
        'subject': '1',
        'session': 1,
Ejemplo n.º 13
0
import numpy, random, csv
from win32api import GetSystemMetrics
import numpy
import os
import sys

try: #tries to get a previous paramters file
    expInfo = fromFile('lastParams.pickle')
except : #if file doesn't exist, use default set 
    expInfo = {'Observer': 'Initials', 'SessionNum' :0, "Date": data.getDateStr()[:-5]}


#present dialogue box to change parameters
dbox = gui.DlgFromDict(expInfo, title = 'TestExperiment',order=["Observer", "SessionNum", "Date"])
if dbox.OK:
    toFile('lastParams.pickle', expInfo) 
else:
    core.quit() 
fileName = expInfo["Observer"] + expInfo["Date"]
answerFile = open(fileName+'.csv', 'w+')

def isTarget(stimName):
    return "target" in stimName   

class ExperimentRuntime(ioHubExperimentRuntime):
    '''Create an experiment using psychopy and the ioHub framework by extending 
    the ioHubExperimentRuntime class and implementing the run() method.
    '''
    def run(self, *args):
        ###---Set up the iohub events for monitoring---###
    # Get some iohub devices for future access.
probe2_options = ('Very aware', 'Somewhat aware', 'Neutral',
                  'Somewhat unaware', 'Very unaware')

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
try:  #try to get a previous parameters file
    expInfo = fromFile('lastSequenceLearningParams.pickle')
except:  #if not there then use a default set
    expInfo = {'subject': 'abc', 'session': '1'}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())  #add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Sequence Learning task', fixed=['date'])
if dlg.OK:
    toFile('lastSequenceLearningParams.pickle',
           expInfo)  #save params to file for next time
else:
    core.quit()  #the user hit cancel so exit

#make a text file to save data
fileName = 'SequenceLearning-' + expInfo['subject'] + '-' + expInfo[
    'session'] + '-' + dateStr
dataFile = open(fileName + '.txt', 'w')
dataFile.write('key	RT	AbsTime\n')

#create window and stimuli
globalClock = core.Clock()  #to keep track of time
trialClock = core.Clock()  #to keep track of time
win = visual.Window([800, 600],
                    allowGUI=False,
                    monitor='testMonitor',
Ejemplo n.º 15
0
            'Number of test mixed blocks [i.e. number of times trials in .xlsx '
            'file will be repeated. To set trial number and proportion of '
            'stop vs. go edit the .xlsx file]',
            'Full Screen':
            'Do you want to run the task with Full Screen - recommended'
        })
    if not dlg.OK: core.quit()
else:
    # Parameters with multiple options need their default selecting
    more_task_info[1]['Response Key'] = 'space'

if more_task_info[1][
        'Remember Parameters']:  #if participant selects 'remember parameters'
    # print and save that information into the working directory
    print('storing parameters for later')
    toFile("more_task_info1.pickle", more_task_info[0])
    toFile("more_task_info2.pickle", more_task_info[1])

#---------------------------------------------------
# Further Additional Parameters Outside of the GUIs
#---------------------------------------------------
# This section is to adjust parameters that are not available in the GUIs
# These parameters are more technical and affect the task quite dramatically
# Do not change these parameters without fully considering their implications

# Bar_top: how many cm above the centre of the screen (x = 0 y = 0) the top of the bar will be drawn.
Bar_top = more_task_info[1]['Total Bar Height (in cm)'] / 2

# Target_pos: position of target line relative to total bar height (default is 80% of bar height)
Target_pos = (.8 * more_task_info[1]['Total Bar Height (in cm)']) - Bar_top
Ejemplo n.º 16
0
    'fullScreen': True,       # run in full screen mode?
    'screenToShow': 0,        # display on primary screen (0) or secondary (1)?
    'fixCrossSize': 10,       # size of cross, in pixels
    'movieVolume': 0.5,       # the volume (0-1) of the movie audio
    'movieSize': [854, 480] # [640,360]# [700, 500]   # width, height of movie (in pixels)
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)# save it!

# Pilot-only parameters
skipDur = 20 # the time (in seconds) that you can skip back or forward by pressing < or >


# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastVidLecInfo.pickle')
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'paramsFile':['DEFAULT','Load...']}
# overwrite if you just saved a new parameter set
# display the dialog with fixed values greyed out
dlg = gui.DlgFromDict(exptInfo, title='Experiment details', 
                    fixed=['19. Date and time',
                    '03. Probes to use (1-4)',
                    '04. Probe separation (cm)',
                    '06. First ISOI (ms)',
                    '07. Probe activation duration (ms)',
                    '08. Number of staircases',
                    '09. Number of trials per staircase',
                    '10. Practice ISOIs',
                    '11. Min ISOI (ms)',
                    '12. Max ISOI (ms)',
                    '16. Device orientation (0 or 1)'])
if dlg.OK:
    toFile(parameterFile, exptInfo) # save params to file for next time
else:
    core.quit() # the user hit cancel so exit
    

stimToUse = [int(i) for i in exptInfo['03. Probes to use (1-4)'].split(',')]
try:
    preISOI = [int(i) for i in exptInfo['10. Practice ISOIs'].split(',')]
except:
    preISOI = []
## ----

## -- make folder/files to save data --
if exptInfo['09. Number of trials per staircase'] > 0:
    dataFolder = './'+exptInfo['15. Folder for saving data']+'/'
    if not os.path.exists(dataFolder):
    ),  # (x,y) pos of fixation cross displayed before each page (for drift correction)
    'fixColor': '#FF0000'  # hex color of fixation cross
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(
        prompt='Save Params...',
        initFilePath=os.getcwd() + '/Params',
        initFileName=newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None:  # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)  # save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  #try to get a previous parameters file
    expInfo = fromFile('lastMultiTaskAvInfo.pickle')
    expInfo['session'] += 1  # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'], 'Load...']
except:  #if not there then use a default set
    expInfo = {
        'subject': '1',
        'session': 1,
        'paramsFile': ['DEFAULT', 'Load...']
    }
# overwrite if you just saved a new parameter set
Ejemplo n.º 19
0
from psychopy import visual, core, data, event, gui
from psychopy.tools.filetools import fromFile, toFile
import numpy as np
import random

# ---- Data Collection

pt_name = ""

expInfo = {'observer': 'jwp', 'presstime': 0}

expInfo['dateStr'] = data.getDateStr()

dlg = gui.DlgFromDict(expInfo, title='N-back test', fixed=['dateStr'])
if dlg.OK:
    toFile(f"{pt_name}", expInfo)
else:
    core.quit()

filename = expInfo['observer'] + expInfo['dateStr']

dataFile = open(fileName + '.csv', 'w')  # may need to be w+
dataFile.write('noidea,fixthis\n')

globalTime = core.Clock()  # option 2
trialTime = core.Clock()

event.getKeys(timeStamped=True)

#----Window Setup ----#
mywin = visual.Window(fullscr=True,
Ejemplo n.º 20
0
from psychopy import sound

params = {
    'ID number': '1',
    'frameRate': 120,
    'primeduration': 0.033,
    'ISI1': 0.5,
    'probeduration': 0.2,
    'fp': 0.2,
    'task': 'wordPrimingTask',
    'computer': 'raylan'
}

dlg = gui.DlgFromDict(params, title='wordPrimingTask', fixed=['dateStr'])
if dlg.OK:
    toFile('lastParams.pickle', params)  #save params to file for next time
else:
    core.quit()  #the user hit cancel so exit

fileName = params['ID number'] + '_WPTArb1'
dataFile = open('/home/zahrahussain/Documents/psychopy/data/wordPriming/' +
                fileName + '.txt',
                'a')  #a simple text file with 'comma-separated-values'
#dataFile = open(fileName+'.txt', 'a')
dataFile.write(
    'word, cue, stimulus, condition,distractorType, subjectResp, accuracy, RT\n'
)

# Create a visual window:
#win = visual.Window(fullscr=True, allowGUI = True, monitor = 'testmonitor', units = 'deg')
win = visual.Window(fullscr=True,
try:#try to get a previous parameters file
    expinfo = fromFile(os.path.join(datadir, 'last_params.pickle'))
except:#if not there then use a default set
    expinfo = {'subject_id':'', 'session':'', 'condition':''}

expinfo['date']= data.getDateStr() #add the current time

instr={}
execfile(instruction_file, instr)
instructions=instr['instructions']

#present a dialogue to change params
if not debug:
    dlg = gui.DlgFromDict(expinfo, title='Body SART', fixed=['dateStr'])
    if dlg.OK:
        toFile(os.path.join(datadir, 'last_params.pickle'), expinfo)#save params to file for next time
    else:
        core.quit()#the user hit cancel so exit

#make a text file to save data
fname = os.path.join('./data/%03i_%s_%s.csv'%(int(expinfo['subject_id']),
                                              expinfo['session'], expinfo['date']))
datafile = open(fname, 'w')
# write header
datafile.write('# subject_id={subject_id}\n# date={date}\n# session={session}\n# condition={condition}\n'.format(**expinfo))
datafile.flush()


## window
monitor=monitors.Monitor("Tromso", distance=100, width=52)
monitor.setSizePix([1920,1200])
probe2_options = ('Very aware','Somewhat aware','Neutral','Somewhat unaware','Very unaware')

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastTappingParams.pickle')
    expInfo['session'] +=1 # increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':'1'}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Rhythmic tapping task', fixed=['date'], order=['subject','session'])
if dlg.OK:
    toFile('lastTappingParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# Start log file
fileName = 'Tapping-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='nBlocks: %d'%nBlocks)
logging.log(level=logging.INFO, msg='fixDur: %f'%fixDur)
logging.log(level=logging.INFO, msg='toneInterval: %f'%toneInterval)
logging.log(level=logging.INFO, msg='nTones: %d'%nTones)
logging.log(level=logging.INFO, msg='blockDurMin: %f'%blockDurMin)
        '12. Max ISOI (ms)': 500,
        '13. Use GO button': True,
        '14. Provide feedback': True,
        '15. Folder for saving data': 'test',
        '16. Device orientation (0 or 1)': 0,
        '17. Arduino serial port': '/dev/cu.usbmodem1411',
        '18. Print arduino messages': False
    }
exptInfo['19. Date and time'] = data.getDateStr(
    format='%Y-%m-%d_%H-%M-%S')  #add the current time

dlg = gui.DlgFromDict(exptInfo,
                      title='Experiment details',
                      fixed=['19. Date and time'])
if dlg.OK:
    toFile('lastParams.pickle', exptInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

stimToUse = [int(i) for i in exptInfo['03. Probes to use (1-4)'].split(',')]
try:
    preISOI = [int(i) for i in exptInfo['10. Practice ISOIs'].split(',')]
except:
    preISOI = []
## ----

## -- make folder/files to save data --
if exptInfo['09. Number of trials per staircase'] > 0:
    dataFolder = './' + exptInfo['15. Folder for saving data'] + '/'
    if not os.path.exists(dataFolder):
        os.makedirs(dataFolder)
    def __init__(self, guiID=True, logging=True, display=False, shorten=True):
        # import test images
        try:
            self.expInfo = fromFile('lastParams.pickle')
        except:
            # create dictionary of robots that are needed
            self.expInfo = {
                "robot_1":
                "robot_imgs/stevie-rs.png",
                "robot_2":
                "robot_imgs/pr2-rs.png",
                "robot_3":
                "robot_imgs/pepper-rs.png",
                "robot_4":
                "robot_imgs/sciprr-rs.png",
                "robot_5":
                "robot_imgs/icub-rs.png",
                "robot_6":
                "robot_imgs/flash-rs.png",
                "robot_7":
                "robot_imgs/g5-rs.png",
                "robot_8":
                "robot_imgs/poli-rs.png",
                "button":
                "robot_imgs/button.png",
                "robots": [
                    "robot_1", "robot_2", "robot_3", "robot_4", "robot_5",
                    "robot_6", "robot_7", "robot_8"
                ],
                "testing_list": [
                    "stevie", "pr2", "pepper", "sciprr", "icub", "flash", "g5",
                    "poli"
                ]
            }
            self.expInfo['dateStr'] = data.getDateStr()
            toFile('lastParams.pickle', self.expInfo)

        self.expInfo['dateStr'] = data.getDateStr()  # add the current time

        # used for outputting to log file
        self.voiceLookup = {
            "robot_0": "r2d2",
            "robot_1": "stevie",
            "robot_2": "pr2",
            "robot_3": "pepper",
            "robot_4": "sciprr",
            "robot_5": "icub",
            "robot_6": "flash",
            "robot_7": "g5",
            "robot_8": "poli",
            "button": "reset"
        }

        # index voices with images
        self.soundLink = {
            "stevie": [1],  # CEREPROC GILES
            "pr2": [2, 4],  # DAVID
            "pepper": [3],  # PEPPER DEFAULT
            "sciprr": [4, 2],  # DAVID
            "icub": [5, 7],  # ACAPELA ROD
            "flash": [6],  # CEREPROC SCOTTISH
            "g5": [7, 5],  # ACAPELA ROD
            "poli": [8]
        }  # AMAZON POLLY KIMBERLY

        # prompt for ID - needs to be before win opened
        if (guiID == True):
            self.ID = self.getID()
        else:
            self.ID = 'dummy'

        # Open log file
        if (logging == True):
            self.openLogFile()

        # setup window
        self.win = visual.Window(size=[1440 / 2, 900],
                                 fullscr=display,
                                 screen=0,
                                 units='pix')

        # setup clock and mouse events events
        self.clock = core.Clock()
        self.mouse = event.Mouse(visible=True, newPos=False, win=self.win)

        # setting for debugging
        if shorten:
            self.shorten = True
        else:
            self.shorten = False
Ejemplo n.º 25
0
def run_exp():
    """ Runs psychophysics experiment to determine threshold for distortion for ensemble
    and individual mode. 
    
    After starting, you will be prompted for subject name and experiment type
    for experiment type put either "ensemble" or "single"
    """

    DIR_DATA = '../data'
    save_dir = op.join(DIR_DATA, 'perceptual_experiment')

    # create folder for psychophysics data if not there already

    safe_mkdir(save_dir)

    # params 
    numTrials = 60
    alphaMin = 0
    alphaMax = 60
    alphaStart = 40
    alphaSteps = [10, 5, 5, 2, 2]
    images = ['church', 'dog', 'fish', 'horn', 'truck']

    # set file name
    info = {'Subject': 'ld', 'Experiment Type': 'ensemble'}
    info['dateStr'] = data.getDateStr()  # add the current time
    # present a dialogue to change params
    dlg = gui.DlgFromDict(info, title='Percpetual Exp', fixed=['dateStr'])
    if dlg.OK:
        toFile(op.join(save_dir, 'lastParams.pickle'), info)  # save params to file for next time
    else:
        core.quit()  # the user hit cancel so exit

    # make a text file to save data    
    fileName = save_dir + '/Experiment_' + info['Experiment Type'] + '_' + info['Subject'] + '_' + info['dateStr']
    dataFile = open(fileName + '.csv', 'w')  # a simple text file with 'comma-separated-values'
    dataFile.write('distortedSide, trialNum,image, alpha, correct, experimentType\n')

    # create a window
    win = visual.Window([1000, 600], monitor="testMonitor", units="deg")

    # create some stimuli
    dist_ind, dist_ensemble = create_distortions()
    preprocessed_images = load_images()
    fixation = visual.GratingStim(win=win, size=0.5, pos=[0, 0], sf=0, color=-1)

    # display instructions
    message1 = visual.TextStim(win, pos=[0, +3], text='Hit a key when ready.')
    message2 = visual.TextStim(win, pos=[0, -3],
                               text="Then press left or right to indicate which image was more distorted.")
    message3 = visual.TextStim(win, pos=[0, +3], text="press left or right")

    message1.draw()
    message2.draw()
    fixation.draw()
    win.flip()
    event.waitKeys()

    # setup stair procedure
    stairs = []
    info['baseImages'] = images
    for imgName in info['baseImages']:
        thisInfo = copy.copy(info)
        thisInfo['imgName'] = imgName
        thisStair = data.StairHandler(startVal=alphaStart,
                                      extraInfo=thisInfo,
                                      nTrials=100, nUp=1, nDown=2, nReversals=5,
                                      minVal=alphaMin, maxVal=alphaMax,
                                      stepSizes=alphaSteps)
        stairs.append(thisStair)

    for trial in np.arange(numTrials):

        # shuffle stairs
        shuffle(stairs)
        # print('Trial Num:', trial)

        for thisStair in stairs:

            thisAlpha = next(thisStair)  # get the alpha value for this trial
            thisImage = thisStair.extraInfo['imgName']  # which image are we on

            dist_ind, dist_ensemble = create_distortions()
            preprocessed_images = load_images()

            if info['Experiment Type'] == 'ensemble':
                base_image, distorted_image = random_trial(preprocessed_images, dist_ind, dist_ensemble,
                                                           alpha=thisAlpha, img=thisImage, ensemble=1)
            if info['Experiment Type'] == 'single':
                base_image, distorted_image = random_trial(preprocessed_images, dist_ind, dist_ensemble,
                                                           alpha=thisAlpha, img=thisImage)

            distortedImg = visual.ImageStim(win=win, image=distorted_image, units='pix', size=260, ori=180)
            baseImg = visual.ImageStim(win=win, image=base_image, units='pix', size=260, ori=180)

            # randomly assign side on screen to images
            targetSide = np.random.choice([-1, 1])
            distortedImg.setPos([250 * targetSide, 0])
            baseImg.setPos([-250 * targetSide, 0])

            # randomize which image is presented first
            order = np.random.choice([-1, 1])

            # Trial
            if order == 1:
                # draw first stimulus
                fixation.draw()
                distortedImg.draw()
                win.flip()

                # wait 1s
                core.wait(1.0)

                # draw second stimulus
                fixation.draw()
                baseImg.draw()
                win.flip()

            else:
                # draw first stimulus
                fixation.draw()
                baseImg.draw()
                win.flip()

                # wait 1s
                core.wait(1.0)

                # draw second stimulus
                fixation.draw()
                distortedImg.draw()
                win.flip()

            # wait 1s
            core.wait(1.0)

            # blank screen
            message3.draw()
            fixation.draw()
            win.flip()

            # get response
            thisResp = None
            while thisResp == None:
                allKeys = event.waitKeys()
                for thisKey in allKeys:
                    if thisKey == 'left':
                        if targetSide == -1:
                            thisResp = 1  # correct
                        else:
                            thisResp = -1  # incorrect
                    elif thisKey == 'right':
                        if targetSide == 1:
                            thisResp = 1  # correct
                        else:
                            thisResp = -1  # incorrect
                    elif thisKey in ['q', 'escape']:
                        core.quit()  # abort experiment
                event.clearEvents()  # clear other (eg mouse) events - they clog the buffer

            # adjust stairs
            thisStair.addData(thisResp)

            # save responses
            to_write = f"{targetSide:d}, {trial:d}, {thisImage:s}, {thisAlpha:.3f}, {thisResp:d}," \
                       f" {info['Experiment Type']} \n"
            dataFile.write(to_write)
            core.wait(0.5)

    # close file
    dataFile.close()

    win.clearBuffer()  # make screen black
    endText = visual.TextStim(win, pos=[0, +3], text='Thanks!  You have finished the experiment.')
    endText.draw()
    win.flip()
    win.close()
    core.quit()
    return
Ejemplo n.º 26
0

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastAudSartParams.pickle')
    expInfo['session'] +=1 # automatically increment session number
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'target letter':targetLetter}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Numerical SART task', fixed=['date'], order=['subject','session','target letter'])
if dlg.OK:
    toFile('lastAudSartParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# get volume from dialogue
targetLetter = expInfo['target letter']

#make a log file to save parameter/event  data
fileName = 'AudSart-%s-%d-%s'%(expInfo['subject'], expInfo['session'], dateStr) #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName+'.log'), level=logging.INFO)#, mode='w') # w=overwrite
logging.log(level=logging.INFO, msg='---START PARAMETERS---')
logging.log(level=logging.INFO, msg='subject: %s'%expInfo['subject'])
logging.log(level=logging.INFO, msg='session: %s'%expInfo['session'])
logging.log(level=logging.INFO, msg='date: %s'%dateStr)
logging.log(level=logging.INFO, msg='isPractice: %i'%isPractice)
logging.log(level=logging.INFO, msg='blockLengths: %s'%blockLengths)
Ejemplo n.º 27
0
def initialize_run():
    """Initalize settings and log file for this run of the experiment.

    Returns
    -------
    settings : dict
        Contains various experimental settings such as MR imaging parameters

        subject : Subject code use for loading/saving data, e.g. 's1'
        run : integer from 1-20
        debug : If true, don't display in full-screen mode
        TR : Time between acquisitions
        volumes : Number of whole-brain 3D volumes to collect this run
        sync : Character to use as the sync timing event; assumed to come at
               start of a volume
        resp : binary array indicating which blocks should be followed by a
               response probe
        skip : Number of volumes lacking a sync pulse at start of scan (for T1
               stabilization)
        scan_sound : In test mode only, play a tone as a reminder of scanner
                     noise
    """
    logging.console.setLevel(logging.DEBUG)
    if prefs.general['audioLib'][0] == 'pyo':
        # if pyo is the first lib in the list of preferred libs then we could
        # use small buffer
        # pygame sound is very bad with a small buffer though
        sound.init(16384, buffer=128)
    print 'Using %s(with %s) for sounds' % (sound.audioLib, sound.audioDriver)

    # settings for launchScan:
    try:
        settings = fromFile('settings.pickle')
    except:
        settings = {
            'subject': 's0',  # Subject code use for loading/saving data
            'run': 1,  # int from 1-20
            'debug': True,  # If true, print extra info
            'TR': 1.7,  # Time between acquisitions
            'volumes': 371,  # Number of whole-brain 3D volumes / frames
            # this will be updated when known
            'sync': '5',  # Character to use as the sync timing event;
            # assumed to come at start of a volume
            'resp': ['0', '0', '0'],  # Blocks after which response is made
            'skip': 0,  # Number of volumes lacking a sync pulse at
            # start of scan (for T1 stabilization)
            'sound': True  # In test mode only, play a tone as a
            # reminder of scanner noise
        }
    # First, confirm subject number and run number
    subandrun = {'sub': settings['subject'], 'run': settings['run']}
    info_dlg = gui.DlgFromDict(subandrun)
    sub = subandrun['sub']
    run = subandrun['run']
    # Load order info from file
    run_info = np.load(path.join(sub, sub + '_run' + str(run) +
                                 'order.npy')).item()
    settings['subject'] = sub
    settings['run'] = run
    settings['volumes'] = int(run_info['vols'])
    settings['resp'] = run_info['resp']
    # Confirm all settings
    info_dlg = gui.DlgFromDict(settings,
                               title='settings',
                               order=['subject', 'run', 'volumes', 'debug'])
    # Save settings for next run
    if info_dlg.OK:
        next_settings = settings.copy()
        if settings['run'] == 20:
            next_settings['run'] = 1  # Reset run when experiment is over
        else:
            next_settings['run'] += 1  # Increment for the next run
        toFile('settings.pickle', next_settings)
    else:
        core.quit()
    sub = settings['subject']
    run = settings['run']
    # Load order info again incase sub/run was altered in previous dialog box
    run_info = np.load(path.join(sub, sub + '_run' + str(run) +
                                 'order.npy')).item()
    settings['stimuli'] = run_info['stimuli']
    settings['lang'] = run_info['lang']

    # Create dated log file
    date_str = time.strftime("%b_%d_%H%M", time.localtime())
    logfname = path.join(
        'logs', "%s_run%s_log_%s.log" %
        (settings['subject'], settings['run'], date_str))
    log = logging.LogFile(logfname, level=logging.INFO, filemode='a')

    return settings
    'screenToShow': 1,        # display on primary screen (0) or secondary (1)?
    'fixCrossSize': 10,       # size of cross, in pixels
    'fixCrossPos': [-600, 472], # (x,y) pos of fixation cross displayed before each page (for drift correction)
    'screenColor':(128,128,128),
    'usePhotodiode': False    # add sync square in corner of screen
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)# save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastDistractionPracticeInfo_behavior.pickle')
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'skipPrompts':False, 'paramsFile':['DEFAULT','Load...']}
# overwrite if you just saved a new parameter set
if saveParams:
    expInfo['paramsFile'] = [newParamsFilename,'Load...']
dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time
Ejemplo n.º 29
0
# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  # try to get a previous parameters file
    expInfo = fromFile("lastSartParams.pickle")
    expInfo["session"] += 1  # automatically increment session number
except:  # if not there then use a default set
    expInfo = {"subject": "1", "session": 1, "target digit": 3}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())  # add the current time

# present a dialogue to change params
dlg = gui.DlgFromDict(
    expInfo, title="Numerical SART task", fixed=["date"], order=["subject", "session", "target digit"]
)
if dlg.OK:
    toFile("lastSartParams.pickle", expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# get volume from dialogue
targetDigit = expInfo["target digit"]

# make a log file to save parameter/event  data
fileName = "Sart-%s-%d-%s" % (
    expInfo["subject"],
    expInfo["session"],
    dateStr,
)  #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName + ".log"), level=logging.INFO)  # , mode='w') # w=overwrite
logging.log(level=logging.INFO, msg="---START PARAMETERS---")
logging.log(level=logging.INFO, msg="subject: %s" % expInfo["subject"])
try:  #try to get a previous parameters file
    expinfo = fromFile(os.path.join(datadir, 'last_params.pickle'))
except:  #if not there then use a default set
    expinfo = {'subject_id': '', 'session': '', 'condition': ''}

expinfo['date'] = data.getDateStr()  #add the current time

instr = {}
execfile(instruction_file, instr)
instructions = instr['instructions']

#present a dialogue to change params
if not debug:
    dlg = gui.DlgFromDict(expinfo, title='Body SART', fixed=['dateStr'])
    if dlg.OK:
        toFile(os.path.join(datadir, 'last_params.pickle'),
               expinfo)  #save params to file for next time
    else:
        core.quit()  #the user hit cancel so exit

#make a text file to save data
fname = os.path.join(
    './data/%03i_%s_%s.csv' %
    (int(expinfo['subject_id']), expinfo['session'], expinfo['date']))
datafile = open(fname, 'w')
# write header
datafile.write(
    '# subject_id={subject_id}\n# date={date}\n# session={session}\n# condition={condition}\n'
    .format(**expinfo))
datafile.flush()

## window
    'calGoFast': False, # Go quickly from point to point (True) or slower and more precise (False [default]).
    'calCheckLevel': 3 #calibration check level (0=none,1=weak,2=medium,3=strong [default])
}

# save parameters
if saveParams:
    print("Opening save dialog:")
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/params', initFileName = newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    print("dlgResult: %s"%dlgResult)
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
        print("Didn't save params.")
    else:
        toFile(newParamsFilename, params)# save it!
        print("Saved params to %s."%newParamsFilename)
#    toFile(newParamsFilename, params)
#    print("saved params to %s."%newParamsFilename)

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile(expInfoFilename)
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'skipPrompts':False, 'tSound':0.0, 'paramsFile':['DEFAULT','Load...']}
# overwrite if you just saved a new parameter set
if saveParams:
Ejemplo n.º 32
0
    'fullScreen': True,       # run in full screen mode?
    'screenToShow': 0,        # display on primary screen (0) or secondary (1)?
    'fixCrossSize': 50,       # size of cross, in pixels
    'fixCrossPos': (0,0), # (x,y) pos of fixation cross displayed before each page (for drift correction)
    'usePhotodiode': False     # add sync square in corner of screen
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(prompt='Save Params...',initFilePath = os.getcwd() + '/Params', initFileName = newParamsFilename,
        allowed="PSYDAT files (*.psydat);;All files (*.*)")
    newParamsFilename = dlgResult
    if newParamsFilename is None: # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)# save it!


# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastVisSpeedInfo.psydat')
    expInfo['session'] +=1 # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'],'Load...']
except:#if not there then use a default set
    expInfo = {'subject':'1', 'session':1, 'paramsFile':['DEFAULT','Load...']}
# overwrite if you just saved a new parameter set
if saveParams:
    expInfo['paramsFile'] = [newParamsFilename,'Load...']
dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time
                '08. Number of staircases':1,
                '09. Number of trials per staircase':40, 
                '10. Practice ISOIs':'500,300', 
                '11. Min ISOI (ms)':5,
                '12. Max ISOI (ms)':500,
                '13. Use GO button':True,
                '14. Provide feedback':True,
                '15. Folder for saving data':'test', 
                '16. Device orientation (0 or 1)':0, 
                '17. Arduino serial port':'/dev/cu.usbmodem1411', 
                '18. Print arduino messages':False}
exptInfo['19. Date and time']= data.getDateStr(format='%Y-%m-%d_%H-%M-%S') #add the current time

dlg = gui.DlgFromDict(exptInfo, title='Experiment details', fixed=['19. Date and time'])
if dlg.OK:
    toFile('lastParams.pickle', exptInfo) # save params to file for next time
else:
    core.quit() # the user hit cancel so exit
    

stimToUse = [int(i) for i in exptInfo['03. Probes to use (1-4)'].split(',')]
try:
    preISOI = [int(i) for i in exptInfo['10. Practice ISOIs'].split(',')]
except:
    preISOI = []
## ----

## -- make folder/files to save data --
if exptInfo['09. Number of trials per staircase'] > 0:
    dataFolder = './'+exptInfo['15. Folder for saving data']+'/'
    if not os.path.exists(dataFolder):
Ejemplo n.º 34
0
    np.random.shuffle(blockLengths)

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  # try to get a previous parameters file
    expInfo = fromFile("lastFlankerParams.pickle")
    expInfo["session"] += 1  # automatically increment session number
except:  # if not there then use a default set
    expInfo = {"subject": "1", "session": 1}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())  # add the current time

# present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title="Flanker task", fixed=["date"], order=["subject", "session"])
if dlg.OK:
    toFile("lastFlankerParams.pickle", expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# make a log file to save parameter/event  data
fileName = "Flanker-%s-%d-%s" % (
    expInfo["subject"],
    expInfo["session"],
    dateStr,
)  #'Sart-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
logging.LogFile((fileName + ".log"), level=logging.INFO)  # , mode='w') # w=overwrite
logging.log(level=logging.INFO, msg="---START PARAMETERS---")
logging.log(level=logging.INFO, msg="subject: %s" % expInfo["subject"])
logging.log(level=logging.INFO, msg="session: %s" % expInfo["session"])
logging.log(level=logging.INFO, msg="date: %s" % dateStr)
logging.log(level=logging.INFO, msg="isPractice: %i" % isPractice)
# Try to get a previous parameters file
try:
    exp_info = fromFile("lastParams.pickle")
# If not there then use a default set
except:
    exp_info = {"Observer": "unknown", "Session": "1", "Type[1: RDK; 2: Grating]": "1"}
# Add the current time
exp_info["dateStr"] = data.getDateStr()

# Present a dialogue to change params
dlg = gui.DlgFromDict(
    exp_info, title="Peripheral Vision Search Experiment", fixed=["dateStr"]
)
# Save params to file for next time
if dlg.OK:
    toFile("lastParams.pickle", exp_info)
# The user hit cancel so exit
else:
    core.quit()


# Make a text file to save data
file_name = exp_info["Observer"] + "_" + exp_info["Session"] + "_" + exp_info["dateStr"]
# data_file = open(file_name+'.csv', 'w') # a simple text file with 'comma-separated- values'
# data_file.write('ori,sp,correct\n')


# Calculate eccentricities of stimuli
eccentricity_level_1 = round(np.sqrt(2), 1)
eccentricity_level_2 = round(np.roots([1, -2, -7]).max(), 1)
eccentricity_level_3 = round(
Ejemplo n.º 36
0
    info = fromFile('info_gamma.pickle')
    print info
except:
    #if no file use some defaults
    info={}
    info['lumModNoise']=0.5
    info['lumModLum']=0.1
    info['contrastModNoise']=1.0
    info['observer']=''
    info['highGamma']=3.0
    info['lowGamma']=0.8
    info['nTrials']=50
dlg = gui.DlgFromDict(info)
#save to a file for future use (ie storing as defaults)
if dlg.OK: 
    toFile('info_gamma.pickle',info)
else:
    core.quit() #user cancelled. quit
print info

info['timeStr']=time.strftime("%b_%d_%H%M", time.localtime())
nFrames=3
cyclesTime=2
cyclesSpace=2
pixels=128

myWin = visual.Window((1024,768), units='pix', allowGUI=True, bitsMode=None)
visual.TextStim(myWin, text='building stimuli').draw()

myWin.update()
Ejemplo n.º 37
0
2016-07-20
writed by leosun
'''
#load the modules used in this exp.
from psychopy import core, visual, gui, data, event, gamma, monitors, sound
from psychopy.tools.filetools import fromFile, toFile
from scipy.io import matlab
import time, os, math, csv

try: expInfo = fromFile('stropp_LastParams.pickle')#try to get a previous parameters file    
except: expInfo = {'observer':'01_syl', 'gender':['m','f'],'age':30}#if not there then use a default set        
dateStr = time.strftime("_20%y_%m_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Stroop', order=['observer','gender','age'])
if dlg.OK: toFile('stroop_LastParams.pickle', expInfo)#save params to file for next time
else: core.quit()#the user hit cancel so exit

#create the subject datafile
new_path = os.path.join(os.getcwd()+'/data/', expInfo['observer']+'_'+expInfo['gender']+str(expInfo['age']))
if not os.path.isdir(new_path): os.makedirs(new_path)

#create the formal experiment condition list
stimList = []
for word in ['R','G']:
    for color in ['red','green']:
        stimList.append( {'word':word,'color':color} )

#organise them with the trial handler
trials = data.TrialHandler(stimList, 10, method='random')#create the within-block random sequence
trials.data.addDataType( ['RT', 'accuracy'] )
Ejemplo n.º 38
0
    info = fromFile('info_gamma.pickle')
    print info
except:
    #if no file use some defaults
    info = {}
    info['lumModNoise'] = 0.5
    info['lumModLum'] = 0.1
    info['contrastModNoise'] = 1.0
    info['observer'] = ''
    info['highGamma'] = 3.0
    info['lowGamma'] = 0.8
    info['nTrials'] = 50
dlg = gui.DlgFromDict(info)
#save to a file for future use (ie storing as defaults)
if dlg.OK:
    toFile('info_gamma.pickle', info)
else:
    core.quit()  #user cancelled. quit
print info

info['timeStr'] = time.strftime("%b_%d_%H%M", time.localtime())
nFrames = 3
cyclesTime = 2
cyclesSpace = 2
pixels = 128

myWin = visual.Window((1024, 768), units='pix', allowGUI=True, bitsMode=None)
visual.TextStim(myWin, text='building stimuli').draw()

myWin.update()
probe2_string = "How aware were you of where your attention was?"
probe2_options = ("Very aware", "Somewhat aware", "Neutral", "Somewhat unaware", "Very unaware")

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
try:  # try to get a previous parameters file
    expInfo = fromFile("lastSequenceLearningParams.pickle")
except:  # if not there then use a default set
    expInfo = {"subject": "abc", "session": "1"}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())  # add the current time

# present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title="Sequence Learning task", fixed=["date"])
if dlg.OK:
    toFile("lastSequenceLearningParams.pickle", expInfo)  # save params to file for next time
else:
    core.quit()  # the user hit cancel so exit

# make a text file to save data
fileName = "SequenceLearning-" + expInfo["subject"] + "-" + expInfo["session"] + "-" + dateStr
dataFile = open(fileName + ".txt", "w")
dataFile.write("key	RT	AbsTime\n")

# create window and stimuli
globalClock = core.Clock()  # to keep track of time
trialClock = core.Clock()  # to keep track of time
win = visual.Window([800, 600], allowGUI=False, monitor="testMonitor", units="deg")
fixation = visual.GratingStim(win, color="black", tex=None, mask="circle", size=0.2)
message1 = visual.TextStim(
    win,
tone_prob = 0.5 # probability that tone will be heard on a given trial
#tone_volume = 0.0003

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastThresholdTone2afcParams.pickle')
except:#if not there then use a default set
    expInfo = {'subject':'abc', 'volume':1}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='threshold tone detection', fixed=['date'])
if dlg.OK:
    toFile('lastThresholdTone2afcParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

# get volume from dialogue
tone_volume = expInfo['volume']

#make a text file to save data
fileName = 'ThresholdTone2afc-' + expInfo['subject'] + '-' + dateStr
dataFile = open(fileName+'.txt', 'w')
dataFile.write('isOn	RT	correct\n')

#create window and stimuli
globalClock = core.Clock()#to keep track of time
trialClock = core.Clock()#to keep track of time
win = visual.Window([800,600],allowGUI=False, monitor='testMonitor', units='deg')
Ejemplo n.º 41
0
    'fixCrossPos':
    [0, 0],  # (x,y) pos of fixation cross displayed during each session
}

# allow user to save the parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(
        prompt='Save Params...',
        initFilePath=os.getcwd() + '/Params',
        initFileName=newParamsFilename,
        allowed="PICKLE files (.pickle)|.pickle|All files (.*)|")
    newParamsFilename = dlgResult
    if newParamsFilename is None:  # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)  # save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
try:  #try to get a previous parameters file
    expInfo = fromFile(expInfoFilename)
    expInfo['session'] += 1  # automatically increment session number
    expInfo['paramsFile'] = [expInfo['paramsFile'], 'Load...']
except:  #if not there then use a default set
    expInfo = {
        'subject': '1',
        'session': 1,
        'skipPrompts': False,
        'paramsFile': ['DEFAULT', 'Load...']
    }
Ejemplo n.º 42
0
    'vasScreenColor': (0, 0, 0),  # gray
    'vasTextColor': (-1, -1, -1),  # black
}

# save parameters
if saveParams:
    dlgResult = gui.fileSaveDlg(
        prompt='Save Params...',
        initFilePath=os.getcwd() + '/Params',
        initFileName=newParamsFilename,
        allowed="PSYDAT files (*.psydat);;All files (*.*)")
    newParamsFilename = dlgResult
    if newParamsFilename is None:  # keep going, but don't save
        saveParams = False
    else:
        toFile(newParamsFilename, params)  # save it!

# ========================== #
# ===== SET UP LOGGING ===== #
# ========================== #
scriptName = os.path.basename(__file__)
scriptName = os.path.splitext(scriptName)[0]  # remove extension
try:  # try to get a previous parameters file
    expInfo = fromFile('%s-lastExpInfo.psydat' % scriptName)
    expInfo['session'] += 1  # automatically increment session number
    expInfo['version'] = ['1', '2', '3', '4']
    expInfo['paramsFile'] = [expInfo['paramsFile'], 'Load...']
except:  # if not there then use a default set
    expInfo = {
        'subject': '1',
        'session': 1,
                '10. Conditioning reversed motors (1-6)':'3,4',
                '11. Test motors (1-6)':'3,4',
                '12. Test lights (1-6)':'',
                '13. ISOI (ms)':100, 
                '14. Duration (ms)':100,
                '15. Use GO button':True,
                '16. Folder for saving data':'Conditioning-Data', 
                '17. Device orientation (0 or 1)':0, 
                '18. Arduino serial port':'/dev/cu.usbmodem1421', 
                '19. Print arduino messages':False}
exptInfo['20. Date and time']= data.getDateStr(format='%Y-%m-%d_%H-%M-%S') #add the current time
dlg = gui.DlgFromDict(exptInfo, title='Experiment details', fixed=['20. Date and time'])
if dlg.OK:
    conditioningType = exptInfo['04. Conditioning']
    exptInfo['04. Conditioning'] = ['incongruent','congruent','off']
    toFile(parameterFile, exptInfo) # save params to file for next time
else:
    core.quit() # the user hit cancel so exit
## ----

## -- convert number lists to arrays --
try: condTactToUse = [int(i) for i in exptInfo['08. Conditioning motors (1-6)'].split(',')] 
except: condTactToUse = []
try: condVisToUse = [int(i) for i in exptInfo['09. Conditioning lights (1-6)'].split(',')]
except: condVisToUse = []
try: condTactRev = [int(i) for i in exptInfo['10. Conditioning reversed motors (1-6)'].split(',')]
except: condTactRev = []
if not conditioningType == 'incongruent':
    condTactRev = [] # only reverse if conditioning is incongruent
try: testTactToUse = [int(i) for i in exptInfo['11. Test motors (1-6)'].split(',')]
except: testTactToUse = []
Ejemplo n.º 44
0
probe2_string = 'How aware were you of where your attention was?'
probe2_options = ('Very aware','Somewhat aware','Neutral','Somewhat unaware','Very unaware')

# ========================== #
# ===== SET UP STIMULI ===== #
# ========================== #
try:#try to get a previous parameters file
    expInfo = fromFile('lastFourLetterParams.pickle')
except:#if not there then use a default set
    expInfo = {'subject':'abc', 'session':'1'}
dateStr = time.strftime("%b_%d_%H%M", time.localtime())#add the current time

#present a dialogue to change params
dlg = gui.DlgFromDict(expInfo, title='Four Letter Task', fixed=['date'])
if dlg.OK:
    toFile('lastFourLetterParams.pickle', expInfo)#save params to file for next time
else:
    core.quit()#the user hit cancel so exit

#make a text file to save data
fileName = 'FourLetter-' + expInfo['subject'] + '-' + expInfo['session'] + '-' + dateStr
dataFile = open(fileName+'.txt', 'w')
dataFile.write('key	RT	AbsTime\n')

#create window and stimuli
globalClock = core.Clock()#to keep track of time
trialClock = core.Clock()#to keep track of time
win = visual.Window([800,600],allowGUI=False, monitor='testMonitor', units='deg')
fixation = visual.GratingStim(win, color='black', tex=None, mask='circle',size=0.2)
message1 = visual.TextStim(win, pos=[0,+3],text="Memorize each sequence of 4 letters. Then an arrow will indicate whether the ordering is right-to-left or left-to-right. Next you'll see a letter - indicate its number in the given sequence and order.")
message2 = visual.TextStim(win, pos=[0,-3], text="When you're ready to begin, press any key.")
Ejemplo n.º 45
0
        mywin.flip()
    staircase.saveAsPickle('poly-' + str(sides) + '_' +
                           str(fillcolor == None) + '_' + str(radius))
    print('reversals:')
    print(staircase.reversalIntensities)
    approxThreshold = numpy.average(staircase.reversalIntensities[-6:])
    print('mean of final 6 reversals = %.3f' % (approxThreshold))


subject_name = {'Name': 'please enter your name'}
subject_name['time_and_date'] = data.getDateStr()
dlg = gui.DlgFromDict(subject_name,
                      title='Weber\'s Law Experiment',
                      fixed=['time_and_date'])
if dlg.OK:
    toFile('parameters.pickle', subject_name)
else:
    core.quit()

file_name = subject_name['Name'] + subject_name['time_and_date']
text_file = open(file_name + '.csv', 'w')
text_file.write('polygon,outline_or_filled, signal_size, test_size, correct\n')

mywin = visual.Window([1920, 1080],
                      allowGUI=True,
                      monitor='testMonitor',
                      units='deg')

#signal_radii = [5.5,0.5,3.5,1.0,2.0]

draw_polygon(text_file, sides=9, radius=5.5, fillcolor=True)