def start_iohub(sess_code=None): import time, os # Create initial default session code if sess_code is None: sess_code='S_{0}'.format(long(time.mktime(time.localtime()))) # Ask for session name / hdf5 file name save_to = fileSaveDlg(initFilePath=os.path.dirname(__file__),initFileName=sess_code, prompt="Set Session Output File", allowed="ioHub Datastore Files (*.hdf5)|*.hdf5") if save_to: # session code should equal results file name fdir, sess_code = os.path.split(save_to) sess_code=sess_code[0:min(len(sess_code),24)] if sess_code.endswith('.hdf5'): sess_code = sess_code[:-5] if save_to.endswith('.hdf5'): save_to = save_to[:-5] else: save_to = sess_code exp_code='wintab_evts_test' kwargs={'experiment_code':exp_code, 'session_code':sess_code, 'datastore_name':save_to, 'wintab.WintabTablet':{'name':'tablet', 'mouse_simulation': {'enable':False, 'leave_region_timeout':2.0 } } } return launchHubServer(**kwargs)
def save(self, event=None): """save header + row x col data to a pickle file """ self.getData(True) # update self.data adjustedNames = False for i, paramName in enumerate(self.data[0]): newName = paramName # ensure its legal as a var name, including namespace check: if self.parent: msg, enable = self.parent._checkName(name=paramName) if msg: # msg not empty means a namespace issue newName = self.parent.exp.namespace.makeValid( paramName, prefix='param') adjustedNames = True elif not valid_var_re.match(paramName): msg, enable = _translate( "Name must be alpha-numeric or _, no spaces"), False newName = _nonalphanumeric_re.sub('_', newName) adjustedNames = True else: msg, enable = "", True # try to ensure its unique: while newName in self.data[0][:i]: adjustedNames = True newName += 'x' # might create a namespace conflict? self.data[0][i] = newName self.header[i].SetValue(newName) # displayed value if adjustedNames: self.tmpMsg.SetLabel( _translate('Param name(s) adjusted to be legal. Look ok?')) return False if hasattr(self, 'fileName') and self.fileName: fname = self.fileName else: self.newFile = True fname = self.defaultFileName if self.newFile or not os.path.isfile(fname): fullPath = gui.fileSaveDlg(initFilePath=os.path.split(fname)[0], initFileName=os.path.basename(fname), allowed="Pickle files (*.pkl)|*.pkl") else: fullPath = fname if fullPath: # None if user canceled if not fullPath.endswith('.pkl'): fullPath += '.pkl' f = open(fullPath, 'w') pickle.dump(self.data, f) f.close() self.fileName = fullPath self.newFile = False # ack, sometimes might want relative path if self.parent: self.parent.conditionsFile = fullPath return True
def save(self, event=None): """save header + row x col data to a pickle file """ self.getData(True) # update self.data adjustedNames = False for i, paramName in enumerate(self.data[0]): newName = paramName # ensure its legal as a var name, including namespace check: if self.parent: msg, enable = self.parent._checkName(name=paramName) if msg: # msg not empty means a namespace issue newName = self.parent.exp.namespace.makeValid( paramName, prefix='param') adjustedNames = True elif not _valid_var_re.match(paramName): msg, enable = _translate( "Name must be alpha-numeric or _, no spaces"), False newName = _nonalphanumeric_re.sub('_', newName) adjustedNames = True else: msg, enable = "", True # try to ensure its unique: while newName in self.data[0][:i]: adjustedNames = True newName += 'x' # might create a namespace conflict? self.data[0][i] = newName self.header[i].SetValue(newName) # displayed value if adjustedNames: self.tmpMsg.SetLabel(_translate( 'Param name(s) adjusted to be legal. Look ok?')) return False if hasattr(self, 'fileName') and self.fileName: fname = self.fileName else: self.newFile = True fname = self.defaultFileName if self.newFile or not os.path.isfile(fname): fullPath = gui.fileSaveDlg(initFilePath=os.path.split(fname)[0], initFileName=os.path.basename(fname), allowed="Pickle files (*.pkl)|*.pkl") else: fullPath = fname if fullPath: # None if user canceled if not fullPath.endswith('.pkl'): fullPath += '.pkl' f = open(fullPath, 'w') pickle.dump(self.data, f) f.close() self.fileName = fullPath self.newFile = False # ack, sometimes might want relative path if self.parent: self.parent.conditionsFile = fullPath return True
def save_raw_file(self, saveAtMoment=False): self.scanClient.stop_sending_data() default_name = time.strftime("eeg_epoch_%Y_%m_%d_%Hh%Mm%Ss.mat", time.localtime()) fullPath = fileSaveDlg(initFilePath="D:\\temp\\EEG_DATA", initFileName=default_name, prompt='保存 EEG Epoch 数据', allowed="Matlab file (*.mat)") self.saveFileName = fullPath if saveAtMoment: self._save_raw_file(fullPath)
def start_iohub(sess_code=None): import time, os # Create initial default session code if sess_code is None: sess_code = 'S_{0}'.format(long(time.mktime(time.localtime()))) # Ask for session name / hdf5 file name save_to = fileSaveDlg(initFilePath=os.path.dirname(__file__), initFileName=sess_code, prompt="Set Session Output File", allowed="ioHub Datastore Files (*.hdf5)|*.hdf5") if save_to: # session code should equal results file name fdir, sess_code = os.path.split(save_to) sess_code = sess_code[0:min(len(sess_code), 24)] if sess_code.endswith('.hdf5'): sess_code = sess_code[:-5] if save_to.endswith('.hdf5'): save_to = save_to[:-5] else: save_to = sess_code exp_code = 'wintab_evts_test' kwargs = { 'experiment_code': exp_code, 'session_code': sess_code, 'datastore_name': save_to, 'wintab.WintabTablet': { 'name': 'tablet', 'mouse_simulation': { 'enable': False, 'leave_region_timeout': 2.0 } } } return launchHubServer(**kwargs)
'Watch', # 'Test', # option in PromptTools.GetPrompts (options are ['Watch','Test']) # declare other stimulus parameters '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': [640, 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 ===== # # ========================== #
True, # shuffle order of cues randomly (without replacement) # other stimulus parameters '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) '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...']
myWin.update() #run the staircase for trialN in range(info['nTrials']): for stairCase in stairCases: thisGamma = stairCase.next() t = globalClock.getTime() myWin.gamma = [thisGamma, thisGamma, thisGamma] direction = num.random.randint(0, 2) * 2 - 1 # a random number -1 or 1 presentStimulus(direction) #print direction, thisGamma ans = getResponse(direction) stairCase.addData(ans) myWin.update() core.wait(0.5) myWin.close() #save data fileName = gui.fileSaveDlg('.', '%s_%s' % (info['observer'], info['timeStr'])) stairCases[1].saveAsPickle(fileName + 'hi') stairCases[1].saveAsText(fileName + 'hi') stairCases[0].saveAsPickle(fileName + 'lo') stairCases[0].saveAsText(fileName + 'lo') print 'That took %.1fmins' % (globalClock.getTime() / 60.0)
#then blank the screen myWin.update() #run the staircase for trialN in range(info['nTrials']): for stairCase in stairCases: thisGamma=stairCase.next() t = globalClock.getTime() myWin.gamma = [thisGamma,thisGamma,thisGamma] direction=num.random.randint(0,2)*2-1 # a random number -1 or 1 presentStimulus(direction) #print direction, thisGamma ans=getResponse(direction) stairCase.addData(ans) myWin.update() core.wait(0.5) myWin.close() #save data fileName=gui.fileSaveDlg('.','%s_%s' %(info['observer'], info['timeStr'])) stairCases[1].saveAsPickle(fileName+'hi') stairCases[1].saveAsText(fileName+'hi') stairCases[0].saveAsPickle(fileName+'lo') stairCases[0].saveAsText(fileName+'lo') print 'That took %.1fmins' %(globalClock.getTime()/60.0)
for k in range(5, 8): Verb2[i][k] = int(Verb2[i][k]) for j in range(9, 12): Verb2[i][j] = float(Verb2[i][j]) relstats = reliability(Verb1, Verb2) doneDlg = gui.Dlg(title="Calculations complete!", labelButtonOK="Yes", labelButtonCancel="No") doneDlg.addText("Weighted percentage agreement: " + str(relstats['WeightedPercentageAgreement'])) doneDlg.addText("Cohen's Kappa: " + str(relstats['CohensKappa'])) doneDlg.addText("Average observer agreement: " + str(relstats['AverageObserverAgreement'])) doneDlg.addText("Pearson's R: " + str(relstats['PearsonsR'])) doneDlg.addText("Save output?") doneDlg.show() if doneDlg.OK: sDlg = gui.fileSaveDlg(initFilePath=os.getcwd(), initFileName=str(thisInfo[0]) + '_' + str(thisInfo[1]) + '_Stats.csv') if type(sDlg) is not NoneType: headers3 = [ 'WeightedPercentageAgreement', 'CohensKappa', 'AverageObserverAgreement', 'PearsonsR' ] outputWriter4 = csv.DictWriter(open(sDlg, 'w'), fieldnames=headers3, extrasaction='ignore', lineterminator='\n') outputWriter4.writeheader() outputWriter4.writerow(relstats)
'imageSuffix': '.jpg', # images will be selected randomly (without replacement) from all files in imageDir that end in imageSuffix. # declare prompt and question files 'skipPrompts': False, # go right to the scanner-wait page 'promptDir': 'Text/', # directory containing prompts and questions files 'promptFile': 'SamplePrompts.txt', # Name of text file containing prompts # declare display parameters '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
instruct_text.text = instruct_text._start_rec_txt pen_trace = wintabgraphics.PenTracesStim(myWin, PEN_TRACE_LINE_WIDTH, PEN_TRACE_LINE_COLOR, PEN_TRACE_LINE_OPACITY) pen_pos = wintabgraphics.PenPositionStim( myWin, PEN_POS_GFX_MIN_OPACITY, PEN_POS_HOVER_COLOR, PEN_POS_TOUCHING_COLOR, PEN_POS_ANGLE_COLOR, PEN_POS_ANGLE_WIDTH, PEN_POS_GFX_MIN_SIZE, PEN_POS_GFX_SIZE_RANGE, PEN_POS_TILTLINE_SCALAR) return evt_text, instruct_text, pen_trace, pen_pos if __name__ == '__main__': # Ask for session name / hdf5 file name save_to = fileSaveDlg(initFilePath=os.path.dirname(__file__), initFileName=DEFAULT_SESSION_CODE, prompt="Set Session Output File", allowed="ioHub Data Files (*.hdf5)|*.hdf5") myWin = visual.Window(units='pix', color=DEFAULT_SCREEN_COLOR, colorSpace='rgb255', fullscr=True, allowGUI=False) # Start iohub process and create shortcut variables to the iohub devices # used during the experiment. io = start_iohub(DEFAULT_SESSION_CODE, save_to) keyboard = io.devices.keyboard mouse = io.devices.mouse pen = io.devices.pen
try: os.mkdir('data') print("Directory Created!") except FileExistsError: print("Directory Exist!") if info.OK: save_file_name = 'data/' + show_info[0] + show_info[1] + '_' + \ show_info[2] + '_ep_experiment.csv' save_file_name_backup = 'data/' + show_info[0] + show_info[1] + '_' + \ show_info[2] + '_backup_orientation.csv' else: print("User Cancelled") # Create Save Path save_path = gui.fileSaveDlg(initFileName=save_file_name, prompt='Select Save File') # Create a Backup file for all orientation in the set # Refer to the gaborset function backup_file = open(save_file_name_backup, 'w') # calibrating monitor and creating window for experiment mon = monitors.Monitor(monitor_name) mon.setWidth(screen_width) mon.setDistance(view_distance) win = visual.Window(size=screen_resolution, color='#C0C0C0', fullscr=True, monitor=mon, allowGUI=True)
reps[2].append(repeatNs[2]) reps[3].append(repeatNs[0]) reps[3].append(repeatNs[1]) reps[3].append(repeatNs[2]) for i in range( len( reps ) ): reps[i] = sorted(reps[i], key = lambda *args: random.random() ) for item in ruleset: print item rows.append( (item, reps[item].pop()) ) print rows #json generation data = {'set': {'stimpath': setpath, 'blocks':[]}} for i in rows: data['set']['blocks'].append( {'rule': i[0], 'reps': i[1]} ) jsontext = json.dumps(data) print jsontext saveFile = gui.fileSaveDlg(initFilePath='.'+s+'configs'+s+'sets'+s, allowed='JSON | .json' ) if saveFile: sf = open( saveFile, 'w' ) sf.write( jsontext ) sf.close()
# clear last screen if testing if iscodetest: r = ResponseEmulator([(1, 'space')]) r.start() task.wait_for_scanner(['space'], 'Finished!') task.win.close() # save results to recall.csv inside datadir namesarray = [subjid, vdate_str(), tasktype, str(timepoint)] # add runs to output file name if non-standard if settings['firstrun'] != 1 or \ settings['lastrun'] != nruns_opt[host_tasktype()]: namesarray.append('runs%d-%d' % (settings['firstrun'], settings['lastrun'])) namesarray.append('recall-%s_%s.csv' % (imgset, seconds)) csvfilename = "_".join(namesarray) saveas = os.path.join(datadir, csvfilename) # save file in data directory. might be read only :( isSaved = False while not isSaved: try: recall_trials.data.to_csv(saveas) isSaved = True except: saveas = gui.fileSaveDlg(initFilePath='/Users/danielamejia/Desktop/', initFileName=csvfilename, prompt=u'Data is readonly, save where?') print('saved %s' % saveas)