def test_pickle(self): _, path = mkstemp(dir=self.tmp_dir, suffix='.psydat') test_data = 'Test' with open(path, 'wb') as f: pickle.dump(test_data, f) assert test_data == fromFile(path)
def test_multiKeyResponses(self): dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat')) #test csv output dat.saveAsText(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), appendFile=False) utils.compareTextFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), pjoin(fixturesPath,'corrMultiKeyTrials.csv')) #test xlsx output dat.saveAsExcel(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), appendFile=False) utils.compareXlsxFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), pjoin(fixturesPath,'corrMultiKeyTrials.xlsx'))
def test_multiKeyResponses(self): pytest.skip() # temporarily; this test passed locally but not under travis, maybe PsychoPy version of the .psyexp?? dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat')) #test csv output dat.saveAsText(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), appendFile=False) utils.compareTextFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.csv'), pjoin(fixturesPath,'corrMultiKeyTrials.csv')) #test xlsx output dat.saveAsExcel(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), appendFile=False) utils.compareXlsxFiles(pjoin(self.temp_dir, 'testMultiKeyTrials.xlsx'), pjoin(fixturesPath,'corrMultiKeyTrials.xlsx'))
def test_json_dump_and_reopen_file(self): t = data.TrialHandler2(self.conditions, nReps=5) t.addData('foo', 'bar') t.__next__() _, path = mkstemp(dir=self.temp_dir, suffix='.json') t.saveAsJson(fileName=path, fileCollisionMethod='overwrite') t.origin = '' t_loaded = fromFile(path) assert t == t_loaded
def test_json_with_encoding(self): _, path_0 = mkstemp(dir=self.tmp_dir, suffix='.json') _, path_1 = mkstemp(dir=self.tmp_dir, suffix='.json') encoding_0 = 'utf-8' encoding_1 = 'utf-8-sig' test_data = 'Test' if PY3: with open(path_0, 'w', encoding=encoding_0) as f: json.dump(test_data, f) with open(path_1, 'w', encoding=encoding_1) as f: json.dump(test_data, f) else: with codecs.open(path_0, 'w', encoding=encoding_0) as f: json.dump(test_data, f) with codecs.open(path_1, 'w', encoding=encoding_1) as f: json.dump(test_data, f) assert test_data == fromFile(path_0, encoding=encoding_0) assert test_data == fromFile(path_1, encoding=encoding_1)
def test_json_dump_and_reopen_file(self): s = data.StairHandler(5) s.addResponse(1) s.addOtherData('foo', 'bar') s.__next__() _, path = mkstemp(dir=self.tmp_dir, suffix='.json') s.saveAsJson(fileName=path, fileCollisionMethod='overwrite') s.origin = '' s_loaded = fromFile(path) assert s == s_loaded
def test_cPickle(self): if PY3: pytest.skip('Skipping cPickle test on Python 3') else: import cPickle _, path = mkstemp(dir=self.tmp_dir, suffix='.psydat') test_data = 'Test' with open(path, 'wb') as f: cPickle.dump(test_data, f) assert test_data == fromFile(path)
def test_json_dump_and_reopen_file(self): q = data.QuestHandler(0.5, 0.2, pThreshold=0.63, gamma=0.01, nTrials=20, minVal=0, maxVal=1) q.addResponse(1) q.addOtherData('foo', 'bar') q.__next__() _, path = mkstemp(dir=self.tmp_dir, suffix='.json') q.saveAsJson(fileName=path, fileCollisionMethod='overwrite') q.origin = '' q_loaded = fromFile(path) assert q == q_loaded
def test_json_dump_and_reopen_file(self): p = data.PsiHandler(nTrials=10, intensRange=[0.1, 10], alphaRange=[0.1, 10], betaRange=[0.1, 3], intensPrecision=1, alphaPrecision=1, betaPrecision=0.5, delta=0.01) p.addResponse(1) p.addOtherData('foo', 'bar') p.__next__() _, path = mkstemp(dir=self.tmp_dir, suffix='.json') p.saveAsJson(fileName=path, fileCollisionMethod='overwrite') p.origin = '' p_loaded = fromFile(path) assert p == p_loaded
def csvFromPsydat(self, evt=None): from psychopy import gui from psychopy.tools.filetools import fromFile prompt = _translate("Select .psydat file(s) to extract") names = gui.fileOpenDlg(allowed='*.psydat', prompt=prompt) for name in names or []: filePsydat = os.path.abspath(name) print("psydat: {0}".format(filePsydat)) exp = fromFile(filePsydat) if filePsydat.endswith('.psydat'): fileCsv = filePsydat[:-7] else: fileCsv = filePsydat fileCsv += '.csv' exp.saveAsWideText(fileCsv) print(' -->: {0}'.format(os.path.abspath(fileCsv)))
def csvFromPsydat(self, evt=None): from psychopy import gui from psychopy.tools.filetools import fromFile names = gui.fileOpenDlg(allowed='*.psydat', prompt=_translate("Select .psydat file(s) to extract")) for name in names or []: filePsydat = os.path.abspath(name) print("psydat: {0}".format(filePsydat)) exp = fromFile(filePsydat) if filePsydat.endswith('.psydat'): fileCsv = filePsydat[:-7] else: fileCsv = filePsydat fileCsv += '.csv' exp.saveAsWideText(fileCsv) print(' -->: {0}'.format(os.path.abspath(fileCsv)))
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)
from psychopy import core, gui, data from psychopy.tools.filetools import fromFile, toFile import numpy, random, os, serial, pygame from math import * from am_arduino import * ## -- get input from experimenter -- try: exptInfo = fromFile('lastParams.pickle') # previous values except: # default values exptInfo = {'01. Participant Code':'P00', '02. Test number':1, '03. Probes to use (1-4)':'1,2,3,4', '04. Probe separation (cm)':20, '05. Stimulation site':'right foot', '06. First ISOI (ms)':200, '07. Probe activation duration (ms)':100, '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'])
#!/usr/bin/env python2 """measure your JND in orientation using a staircase method""" 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') foil = visual.GratingStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation']) target = visual.GratingStim(win, sf=1, size=4, mask='gauss', ori=expInfo['refOrientation'])
def test_multiKeyResponses2(self): pytest.skip( ) # temporarily; this test passed locally but not under travis, maybe PsychoPy version of the .psyexp?? dat = fromFile( os.path.join(fixturesPath, 'multiKeypressTrialhandler.psydat'))
# ====================== # # ===== PARAMETERS ===== # # ====================== # # Declare parameters ITI_min = 1 ITI_range = 1 tone_freq = 880 # in Hz tone_prob = 0.5 # probability that tone will be heard on a given trial tone_startvol = 0.01 # ========================== # # ===== SET UP STIMULI ===== # # ========================== # try:#try to get a previous parameters file expInfo = fromFile('lastThresholdParams.pickle') except:#if not there then use a default set expInfo = {'subject':'abc', '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='perceptual threshold staircase', fixed=['date']) if dlg.OK: toFile('lastThresholdParams.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 = 'GetThreshold-' + expInfo['subject'] + '-' + dateStr dataFile = open(fileName+'.txt', 'w') dataFile.write('isOn Increment correct\n')
# 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...']} # overwrite params struct if you just saved a new parameter set if saveParams: expInfo['paramsFile'] = [newParamsFilename,'Load...'] #present a dialogue to change select params dlg = gui.DlgFromDict(expInfo, title=scriptName, order=['subject','session','skipPrompts','paramsFile']) if not dlg.OK:
#and a combined psychometric function from the same data #on the right # from psychopy import data, gui, core from psychopy.tools.filetools import fromFile import pylab, scipy files = gui.fileOpenDlg('.') if not files: core.quit() #get the data from all the files allIntensities, allResponses = [],[] for thisFileName in files: thisDat = fromFile(thisFileName) assert isinstance(thisDat, data.StairHandler) allIntensities.append( thisDat.intensities ) allResponses.append( thisDat.data ) #plot each staircase pylab.subplot(121) colors = 'brgkcmbrgkcm' lines, names = [],[] for fileN, thisStair in enumerate(allIntensities): #lines.extend(pylab.plot(thisStair)) #names = files[fileN] pylab.plot(thisStair, label=files[fileN]) #pylab.legend() #get combined data
probe1_string = "Where was your attention focused just before this?" probe1_options = ( "Completely on the task", "Mostly on the task", "Not sure", "Mostly on inward thoughts", "Completely on inward thoughts", ) probe2_string = "How aware were you of where your attention was?" probe2_options = ("Very aware", "Somewhat aware", "Neutral", "Somewhat unaware", "Very unaware") # ========================== # # ===== 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
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)
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
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...'] } # 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 #present a dialogue to change params
from psychopy import core, gui, data from psychopy.tools.filetools import fromFile, toFile import numpy, random, os, serial, pygame from math import * from am_arduino import * ## -- get input from experimenter -- parameterFile = 'lastParams-tactvis.pickle' try: exptInfo = fromFile(parameterFile) # previous values except: # default values exptInfo = {'01. Participant Code':'P00', '02. Stimulation site':'right hand', '03. Session number':1, '04. Conditioning':['incongruent','congruent','off'], '05. Conditioning time (sec)':5, '06. Top-up time (sec)':5, '07. Number of trials':10, '08. Conditioning motors (1-6)':'1,2,3,4,5,6', '09. Conditioning lights (1-6)':'1,2,3,4,5,6', '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
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
probe1_string = "Where was your attention focused just before this?" probe1_options = ( "Completely on the task", "Mostly on the task", "Not sure", "Mostly on inward thoughts", "Completely on inward thoughts", ) 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")
# -*- coding: utf-8 -*- ''' stroop xxxxx 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']:
# -*- coding: utf-8 -*- """Determine screen gamma using motion-nulling method of Ledgeway and Smith, 1994, Vision Research, 34, 2727–2740 Instructions: on each trial press the up/down cursor keys depending on the apparent direction of motion of the bars.""" from psychopy import visual, core, event, gui, data from psychopy.tools.filetools import fromFile, toFile from psychopy import filters import numpy as num import time try: #try to load previous info 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)
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 lastInfo = fromFile('%s-lastExpInfo.pickle' % scriptName) expInfo = { 'subject': lastInfo['subject'], 'session': lastInfo['session'] + 1, 'condition': stimList['conditionList'], 'skipPrompts': lastInfo['skipPrompts'], 'paramsFile': [lastInfo['paramsFile'], 'Load...'] } except: # if not there then use a default set expInfo = { 'subject': '1', 'session': 1, 'condition': stimList['conditionList'], 'skipPrompts': False, 'paramsFile': ['DEFAULT', 'Load...'] }
# Calculate the visual angle and the pixel per angle VA = calc_VA(va_arg[0], va_arg[1]) display_size = [get_monitors()[0].width, get_monitors()[0].height] an2ra = 1 / VA # Doesn't use in this experiment an2px = round(display_size[1] / VA, 1) print("Visual Angle: {}, degree: {} pix, ".format(VA, an2px)) # Change working directory if not os.path.isfile(os.path.basename(__file__)): os.chdir("./experiments") # 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:
# get list of possible non-target letters #nontargets = list(set(['a','b','c','d','e','f','g','h','i','j'])-set(targetLetter)) # get all the letters a-j that aren't targetLetter. nontargets = list(set(['b','c','d','e','f','g','j','k','l','m'])-set(targetLetter)) # a, h, and i are said kind of strangely by the bot. # randomize list of block lengths if randomizeBlocks: np.random.shuffle(blockLengths) # ========================== # # ===== 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']
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, '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 #present a dialogue to change params dlg = gui.DlgFromDict(expInfo,
# Print a loaded dictionary in a format that could be used to recreate it in a script def PrintDict(dict, dictName='pickle'): # print header print '%s = {' % dictName # print keys for key in sorted(dict.keys()): if isinstance(dict[key], basestring): # if it's a string... print " '%s': '%s'" % (key, dict[key] ) # put quotes around the value else: # if it's not a string print " '%s': %s" % (key, dict[key]) # print the value as-is print '}' # ===================== # # === MAIN FUNCTION === # # ===================== # # get pickle filename dlgResult = gui.fileOpenDlg(prompt='Select parameters file', tryFilePath=os.getcwd(), allowed="PICKLE files (*.psydat);;All files (*.*)") # load and print pickle file if dlgResult is not None: # if they didn't hit cancel filename = dlgResult[0] # extract just the filename pickle = fromFile(filename) # load it print '=== Data extracted from %s: ===' % filename PrintDict(pickle)
#plot each staircase fig = Figure() canvas = FigureCanvas(fig) sc = fig.add_subplot(111) fig2 = Figure() canvas2 = FigureCanvas(fig2) ax = fig2.add_subplot(111) fig3 = Figure() canvas3 = FigureCanvas(fig3) ax2 = fig3.add_subplot(111) allData = [[],[],[],[]] #get the data from all the files for thisFileName in files: sc.clear() handler = fromFile(thisFileName) if isinstance(handler, data.staircase.MultiStairHandler): t1 = [] t3 = [] lat = [] for staircase in handler.staircases: if not staircase.condition.get('dummy',False): sc.plot(staircase.intensities, label=staircase.condition['label']) t1.append(staircase.otherData['extraLatency'][-1]) t3.append(staircase.otherData['totalLatency'][-1]) if staircase.condition['driveFrames'] == 0: di = staircase.condition['prime']-staircase.condition['stim'] la = staircase.otherData['totalLatency'][-1] lat.append((di,la)) #ax.plot(handler.data)
#!/usr/bin/env python # -*- coding: utf-8 -*- """utility for creating a .csv file from a .psydat file edit the file name, then run the script """ import os from psychopy.tools.filetools import fromFile # EDIT THE NEXT LINE to be your .psydat file, with the correct path: name = 'fileName.psydat' file_psydat = os.path.abspath(name) print("psydat: {0}".format(file_psydat)) # read in the experiment session from the psydat file: exp = fromFile(file_psydat) # write out the data in .csv format (comma-separated tabular text): if file_psydat.endswith('.psydat'): file_csv = file_psydat[:-7] else: file_csv = file_psydat file_csv += '.csv' exp.saveAsWideText(file_csv) print('-> csv: {0}'.format(os.path.abspath(file_csv)))
#!/usr/bin/env python2 """utility for creating a .csv file from a .psydat file edit the file name, then run the script """ import os from psychopy.tools.filetools import fromFile # EDIT THE NEXT LINE to be your .psydat file, with the correct path: name = 'fileName.psydat' file_psydat = os.path.abspath(name) print("psydat: {0}".format(file_psydat)) # read in the experiment session from the psydat file: exp = fromFile(file_psydat) # write out the data in .csv format (comma-separated tabular text): if file_psydat.endswith('.psydat'): file_csv = file_psydat[:-7] else: file_csv = file_psydat file_csv += '.csv' exp.saveAsWideText(file_csv) print('-> csv: {0}'.format(os.path.abspath(file_csv)))
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('lastColorVigInfo.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 if saveParams: expInfo['paramsFile'] = [newParamsFilename, 'Load...'] dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time #present a dialogue to change params dlg = gui.DlgFromDict(expInfo,
# 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 #present a dialogue to change params dlg = gui.DlgFromDict(expInfo, title='Visual Speed-Reading task', order=['subject','session','paramsFile']) if not dlg.OK: core.quit()#the user hit cancel so exit # find parameter file
np.random.shuffle(sequences[i]) # declare probe parameters probe_prob = 0 # probablilty that a given trial will be preceded by a probe probe1_string = 'Where was your attention focused just before this?' probe1_options = ('Completely on the task', 'Mostly on the task', 'Not sure', 'Mostly on inward thoughts', 'Completely on inward thoughts') 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
# probe_options.append(['Completely on the task','Mostly on the task','Not sure','Mostly on inward thoughts','Completely on inward thoughts']) # probe_strings.append('How aware were you of where your attention was?') # probe_options.append(['Very aware','Somewhat aware','Neutral','Somewhat unaware','Very unaware']) # enumerate constants arrowNames = ["Left", "Right"] # randomize list of block lengths if randomizeBlocks: 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"],
# -*- coding: utf-8 -*- """Determine screen gamma using motion-nulling method of Ledgeway and Smith, 1994, Vision Research, 34, 2727–2740 Instructions: on each trial press the up/down cursor keys depending on the apparent direction of motion of the bars.""" from psychopy import visual, core, event, gui, data from psychopy.tools.filetools import fromFile, toFile from psychopy import filters import numpy as num import time try: #try to load previous info 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)
RIGHT = 0 WRONG = 1 TOOSLOW = 2 # declare probe parameters probeProb = 0 # probablilty that a given block will be followed by a probe probe1_string = 'Where was your attention focused just before this?' probe1_options = ('Completely on the task','Mostly on the task','Not sure','Mostly on inward thoughts','Completely on inward thoughts') probe2_string = 'How aware were you of where your attention was?' 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
import os # set to 0.5 for Yes/No (or PSE). Set to 0.8 for a 2AFC threshold threshVal = 0.5 # set to zero for Yes/No (or PSE). Set to 0.5 for 2AFC expectedMin = 0.0 files = gui.fileOpenDlg('.') if not files: core.quit() # get the data from all the files allIntensities, allResponses = [], [] for thisFileName in files: thisDat = fromFile(thisFileName) assert isinstance(thisDat, data.StairHandler) allIntensities.append(thisDat.intensities) allResponses.append(thisDat.data) dataFolder = os.path.split(thisFileName)[0] # just the path, not file name # plot each staircase in left hand panel pylab.subplot(121) colors = 'brgkcmbrgkcm' lines, names = [], [] for fileN, thisStair in enumerate(allIntensities): # lines.extend(pylab.plot(thisStair)) # uncomment for a legend for files # names = files[fileN] pylab.plot(thisStair, label=files[fileN]) # pylab.legend()
# Flanker # Created 1/22/15 by David Jangraw based on NumericalSartTask.py # Updated 11/9/15 by David Jangraw - cleanup # Adapted February 2019 by Jade S Pickering and Marta Majewska using PsychoPy v1.90.3 # Last updated 07/05/19 by JSP and MM from psychopy import core, visual, gui, data, event, sound, logging from psychopy.tools.filetools import fromFile, toFile import time, random, csv, numpy as np #import AppKit # for monitor size detection # ========================== # # ===== 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
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 if saveParams: expInfo['paramsFile'] = [newParamsFilename,'Load...'] dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time #present a dialogue to change params dlg = gui.DlgFromDict(expInfo, title='Video Lecture task', order=['subject','session','paramsFile']) if not dlg.OK: core.quit()#the user hit cancel so exit # find parameter file
#!/usr/bin/env python2 # -*- coding: utf-8 -*- """ Measure your JND in orientation using a staircase method """ 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
np.random.shuffle(sequences[i]) # declare probe parameters probe_prob = 0 # probablilty that a given trial will be preceded by a probe probe1_string = 'Where was your attention focused just before this?' probe1_options = ('Completely on the task', 'Mostly on the task', 'Not sure', 'Mostly on inward thoughts', 'Completely on inward thoughts') 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
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 if saveParams: expInfo['paramsFile'] = [newParamsFilename, 'Load...'] dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time #present a dialogue to change params dlg = gui.DlgFromDict(expInfo,
#Read stimuli from text file stimuli_training = pd.read_csv('./stimuli_training.csv',header=None) stimuli_training=np.asarray(stimuli_training.values.tolist()) stimuli_training=stimuli_training.astype(int) stimuli_training.shape=(len(stimuli_training),) ##----------------------------------------------------------------------- ## setup config ##----------------------------------------------------------------------- if not os.path.exists(datadir): print "> creating ", datadir os.makedirs(datadir) 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:
# ====================== # # ===== PARAMETERS ===== # # ====================== # # Declare parameters nTrials = 10 ITI_min = 1 ITI_range = 1 tone_freq = 880 # in Hz 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
# 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 #present a dialogue to change params dlg = gui.DlgFromDict(expInfo, title='Distraction task', order=['subject','session','skipPrompts','paramsFile']) if not dlg.OK: core.quit()#the user hit cancel so exit # find parameter file
def test_multiKeyResponses2(self): pytest.skip() # temporarily; this test passed locally but not under travis, maybe PsychoPy version of the .psyexp?? dat = fromFile(os.path.join(fixturesPath,'multiKeypressTrialhandler.psydat'))
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 if saveParams: expInfo['paramsFile'] = [newParamsFilename, 'Load...'] dateStr = time.strftime("%b_%d_%H%M", time.localtime()) # add the current time #present a dialogue to change params dlg = gui.DlgFromDict(expInfo,
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, 'version': ['1', '2', '3', '4'], # group determining which stim is CS+ 'skipPrompts': False, 'sendPortEvents': True, 'paramsFile': ['DEFAULT', 'Load...'] } # overwrite params struct if you just saved a new parameter set if saveParams: expInfo['paramsFile'] = [newParamsFilename, 'Load...']
#Read stimuli from text file stimuli_training = pd.read_csv('./stimuli_training.csv', header=None) stimuli_training = np.asarray(stimuli_training.values.tolist()) stimuli_training = stimuli_training.astype(int) stimuli_training.shape = (len(stimuli_training), ) ##----------------------------------------------------------------------- ## setup config ##----------------------------------------------------------------------- if not os.path.exists(datadir): print "> creating ", datadir os.makedirs(datadir) 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
np.random.shuffle(sequences[i]) # declare probe parameters probe_prob = 0 # probablilty that a given trial will be preceded by a probe probe1_string = 'Where was your attention focused just before this?' probe1_options = ('Completely on the task','Mostly on the task','Not sure','Mostly on inward thoughts','Completely on inward thoughts') 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')
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: expInfo['paramsFile'] = [newParamsFilename,'Load...'] dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time #present a dialogue to change params dlg = gui.DlgFromDict(expInfo, title='Distraction task', order=['subject','session','skipPrompts','paramsFile']) if not dlg.OK: core.quit()#the user hit cancel so exit # find parameter file