give_training_db, Instructions, onflip_work, clear_port) from .viz import plot_quest_plus if exp['use trigger']: from ctypes import windll # set logging dm = DataManager(exp) exp = dm.update_exp(exp) exp['numTrials'] = 560 # ugly hack, CHANGE exp['targetTime'] = [1] exp['SMI'] = [2] log_path = dm.give_path('l', file_ending='log') lg = logging.LogFile(f=log_path, level=logging.WARNING, filemode='w') # TODO: add eeg baseline (resting-state)! # TODO: add some more logging? # create object for updating experimenter about progress exp_info = ExperimenterInfo(exp, stim, main_text_pos=(0, 0.90), sub_text_pos=(0, 0.78)) # from dB and to dB utility functions: from_db = lambda x: 10 ** (x / 10.) to_db = lambda x: 10 * np.log10(x)
20: INFO 10: DEBUG So setting to DEBUG level will include all possible messages, setting to ERROR will include only the absolutely essential messages. """ from __future__ import division from builtins import range from psychopy import logging, core, visual globalClock = core.Clock() # if this isn't provided the log times will reflect secs since python started logging.setDefaultClock(globalClock) logging.console.setLevel(logging.DEBUG) # receive nearly all messages logDat = logging.LogFile('logLastRun.log', filemode='w', # if you set this to 'a' it will append instead of overwriting level=logging.WARNING) # errors, data and warnings will be sent to this logfile # the following will go to any files with the appropriate minimum level set logging.info('Something fairly unimportant') logging.data('Something about our data. Data is likely very important!') logging.warning('Handy while building your experiment - highlights possible flaws in code/design') logging.error("You might have done something that PsychoPy can't handle! But hopefully this gives you some idea what.") # some things should be logged timestamped on the next video frame # For instance the time of a stimulus appearing is related to the flip: win = visual.Window([400, 400]) for n in range(5): win.logOnFlip('frame %i occured' %n, level=logging.EXP) if n in [2, 4]: win.logOnFlip('an even frame occured', level=logging.EXP)
#oprava 1.10.2014 # Store info about the experiment session expName = 'MenrotIII' # from the Builder filename that created this script expInfo = {u'session': u'001', u'participant': u''} dlg = gui.DlgFromDict(dictionary=expInfo, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Setup files for saving if not os.path.isdir('data'): os.makedirs('data') # if this fails (e.g. permissions) we will get error filename = 'data' + os.path.sep + '%s_%s' % (expInfo['participant'], expInfo['date']) logFile = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) # Start Code - component code to be run before the window creation
saveDir = os.path.join(os.getcwd(), 'data', 'subject_' + str(expInfo['subject'])) if not os.path.exists(saveDir): os.makedirs(saveDir) payFile = os.path.join(os.getcwd(), 'data', 'payFile.csv') dgQuizFile = os.path.join(os.getcwd(), 'stim', 'anm1_dgQuiz.csv') pdQuizFile = os.path.join(os.getcwd(), 'stim', 'anm1_pdQuiz.csv') # generate names for data and session log files saveFilename = os.path.join(saveDir, "%04d_%s_%s.csv") % (int( expInfo['subject']), expInfo['startTime'], expInfo['expName']) logFilename = os.path.join(saveDir, "%04d_%s_%s.log") % (int( expInfo['subject']), expInfo['startTime'], expInfo['expName']) logfile = logging.LogFile( logFilename, filemode='w', level=logging.EXP ) #set logging information (core.quit() is required at the end of experiment to store logging info!!!) # create clocks for timing globalClock = core.Clock() blockClock = core.Clock() rtClock = core.Clock() ### settings for experimental tasks # file paths for images respOptsImage = os.path.join("stim", "respOpts.png") # subjectConds = condCombos[expInfo['counterbalance']] # subjectPartners = partnerCombos[partnerCounterbalance] ### partner cue settings
if not os.path.exists(os.path.join(trialsDir, expt_name)): os.makedirs(os.path.join(trialsDir, expt_name)) fileName = os.path.join(dataDir, expt_name, subject + '_' + timeAndDateStr) if not demo and not exportImages: dataFile = open(fileName + '.txt', 'w') saveCodeCmd = 'cp \'' + \ sys.argv[0] + '\' ' + os.path.join(codeDir, expt_name, subject + '_' + timeAndDateStr) + '.py' os.system(saveCodeCmd ) # save a copy of the code as it was when that subject was run logFname = os.path.join(logsDir, expt_name, subject + '_' + timeAndDateStr) + '.log' ppLogF = logging.LogFile( logFname, filemode= 'w', # if you set this to 'a' it will append instead of overwriting level=logging.INFO ) # errors, data and warnings will be sent to this logfile # DEBUG means set console to receive nearly all messges, INFO next level, EXP, DATA, WARNING and ERROR logging.console.setLevel(logging.ERROR) if fullscr and not demo and not exportImages: runInfo = psychopy.info.RunTimeInfo( # if you specify author and version here, it overrides the automatic detection of __author__ and __version__ in your script #author='<your name goes here, plus whatever you like, e.g., your lab or contact info>', #version="<your experiment version info>", win= myWin, # a psychopy.visual.Window() instance; None = default temp window used; False = no win, no win.flips() refreshTest= 'grating', # None, True, or 'grating' (eye-candy to avoid a blank screen)
filename = _thisDir + os.sep + u'data' + os.sep + '%s_%s' % ( expInfo['participant'], expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler( name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath= u'/Users/patrickbissett/OneDrive/Poldrack/TrainedInhibition/PsychoPy/ShapeLearningTaskFeedback5.psyexp', savePickle=True, saveWideText=True, dataFileName=filename) #save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.WARNING) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation # Setup the Window win = visual.Window( size=(1920, 1080), fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor',
print(expInfo) else: print(expInfo) core.quit() #check if data folder exists directory = os.path.join(os.getcwd(), 'data') if not os.path.exists(directory): os.makedirs(directory) #create file name for storing data fileName = os.path.join( 'data', '%s_%s_%s' % (expName, expInfo['participant'], expInfo['date'])) #save a log file logFile = logging.LogFile(fileName + '.log', level=logging.DEBUG) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file #create a window mywin = Window(screen_size, units='pix', color=background_color, fullscr=full_screen) #create some stimuli safe_gamble = TextStim(win=mywin, color=text_color, pos=(-options_x_offset, 0), height=text_height) risky_gamble = TextStim(win=mywin,
filename = _thisDir + os.sep + u'data/%s.comp' % (expInfo['participant']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename + '/' + expInfo['participant'] + '.' + expInfo['episode'] + expInfo['condition']) # save a log file for detail verbose info logFile = logging.LogFile(filename + '/' + expInfo['participant'] + '.' + expInfo['episode'] + expInfo['condition'] + '.log', level=logging.EXP) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation wavDirName = filename + '/audio' if not os.path.isdir(wavDirName): os.makedirs(wavDirName) # to hold .wav files # Setup the Window win = visual.Window(size=(1280, 800), fullscr=True, screen=0,
font="Arial", wrapWidth=1000, autoLog=True) #get some startup information from the user info = {'participant_id': '', 'session': ''} dlg = gui.DlgFromDict(info, title='Word Task Startup') if not dlg.OK: core.quit() prefix = 'sub-%s_ses-%s_task-word' % (info['participant_id'], info['session']) #logging data # overwrite (filemode='w') a detailed log of the last run in this dir errorLog = logging.LogFile(prefix + "_errorlog.log", level=logging.DATA, filemode='w') #win.logonFlip(msg=' ', level=logging.DATA) # in the data source, there are three columns: Time, StimType and Stim # load in our stimulus timing xlsx file TRIAL_LIST = data.importConditions(fileName=parent_dir + "Run" + info['session'] + ".xlsx") totalTrials = len(TRIAL_LIST) def check_exit(): #abort if esc was pressed if event.getKeys('escape'): win.close() core.quit()
end_txt = visual.TextStim(win, text='This is the end of the experiment.\n' 'Thanks for participating!', color=txt_color, wrapWidth=1.8) trialtxt = visual.TextStim(win, text='', color=txt_color, height=0.1) #set clocks RT = core.Clock() exp_time = core.Clock() # set default log file logging.setDefaultClock(exp_time) log_fn_def = 'logs/' + sub_id[0] + '_default.log' lastLog = logging.LogFile(log_fn_def, level=logging.INFO, filemode='a') # set custom log file log_fn_cus = 'logs/' + sub_id[0] + '_custom.csv' logfile = open(log_fn_cus, 'w') logfile.write("subject,trialCode,code,number,name,rhythm,harmony," "condition,block,startTime,response,rt,trigger\n") # make function to loop over trials and present the stimuli def block_run(s_dict, s_order, b_sounds, breaks=[]): """ s_dict: dictionary containing the stimulus list and metadata, as loaded from a csv file. Must contain the lists: 'trial_code': code of the trial before randomization
] stimuli['REST'] = [{'value': 'REST', 'message': 'REST'}] * 10 # set up the pseudo-randomized order of the trials for runs 1 and 2 for stim_type in stimuli: random.shuffle(stimuli[stim_type]) runs = [[ stimuli['value'].pop(), stimuli['value'].pop(), stimuli['control'].pop(), stimuli['control'].pop() ]] # setup logging # log_file = logging.LogFile("logs/%s.log" % (subj_id), level=logging.DATA, filemode="w") globalClock = core.Clock() logging.setDefaultClock(globalClock) def do_run(run_number, trials): # 1. add ready screen and wait for trigger ready_screen.draw() win.flip() event.waitKeys(keyList='space') # reset globalClock globalClock.reset()
time = core.Clock() STIMDIR = "stim" RESDIR = "res" RESDIR = pjoin(RESDIR, subj) if not pexists(RESDIR): os.makedirs(RESDIR) log_fn = config['log_template'].format( subj=subj, task_name=config['task_name'], runnr=part, timestamp=ptime.strftime(time_template), ) log_fn = pjoin(RESDIR, log_fn) log_responses = logging.LogFile(log_fn, level=logging.INFO) def move_halted_log(fn): # flush log logging.flush() shutil.move(fn, fn.replace('.txt', '__halted.txt')) # quit core.quit() # set up global key for quitting; if that happens, log will be moved to # {log_fn}__halted.txt event.globalKeys.add(key='q', modifiers=['ctrl'], func=move_halted_log, func_args=[log_fn],
import time import math import numpy as np from __init__ import tobii_controller import pandas as pd subject_id = '-1' calib_state = '-1' con = 1 #calibration_failed = 0 input_file_dir = 'input.csv' logfile = logging.LogFile(f='Error Results.txt', level=30, filemode='a', logger=None, encoding='utf8') #not working #create global shutdown key prefs.general['shutdownKey'] = 'q' ''' ############################################################################### # Constants DIR = os.path.dirname(__file__) # users should know the display well. DISPSIZE = (1280, 1024) # define calibration points CALINORMP = [(-0.4, 0.4), (-0.4, -0.4), (0.0, 0.0), (0.4, 0.4), (0.4, -0.4)] CALIPOINTS = [(x * DISPSIZE[0], y * DISPSIZE[1]) for x, y in CALINORMP] '''
def timelog(datalog_fn): logFile = logging.LogFile(datalog_fn + '.log', level=logging.EXP) logging.console.setLevel(logging.WARNING)
input_dict['ses_id'], 'log') # create a output file that collects all variables output_file = os.path.join('sub-{:02d}', 'ses-{}', '{}', logFileID + '.csv').format(input_dict['sub_id'], input_dict['ses_id'], 'beh') # save the current settings per session, so that the data files stay slim settings_file = os.path.join('sub-{:02d}', 'ses-{}', '{}', logFileID + '.json').format( input_dict['sub_id'], input_dict['ses_id'], 'settings') # make output directories for f in [log_file, output_file, settings_file]: os.makedirs(os.path.dirname(f), exist_ok=True) os.system('cp {} {}'.format(jsonfile, settings_file)) lastLog = logging.LogFile(log_file, level=logging.INFO, filemode='w') # init logger: update the constant values (things that wont change) trial_info = { "sub_id": input_dict['sub_id'], "ses_id": input_dict['ses_id'], 'logFileID': logFileID } # add variables to the logfile that are defined in config file for vari in logging_info['logVars']: trial_info[vari] = param[vari] ########################################### ### PREPARE EXPERIMENTAL SEQUENCE #### ###########################################
def start(self, data_folder, mode=u'Демо', test_screen=None): logging.console.setLevel(logging.WARNING) log = logging.LogFile('data/' + data_folder + '/' + self.name + '.log', level=logging.INFO, filemode='w') self.init_attr() # Make output folder DATA_FILE = 'data/' + data_folder + '/' + self.name + '.csv' self.data_file = open(DATA_FILE, mode='w') self.data_file.write(';'.join(self.varnames) + '\n') self.test_screen = test_screen self.init_devices() self.init_instr_stimuli() self.init_trial_stimuli() # -------------------------------------------------------------------- # Start the test # 1. Instruction self.vars['series'] = 'training' # We will need this for demonstration self.training_trials = self.trial_dict.pop('training') try: self.start_demonstration() except FinishTest: self.exit() return self.keys = [x['cor_resp'] for x in self.training_trials] trials = data.TrialHandler(self.training_trials, self.nreps, method='random') core.wait(1) maxtrials = self.maxtrain for trial in trials: if self.totalN > maxtrials: self.status = 'interrupted' self.exit() # Run trial self.trial_seq += 1 self.totalN += 1 self.vars['n'] = self.totalN self.vars['trial'] = trials.thisN + 1 for i, v in trial.iteritems(): self.vars[i] = v self.run_trial(trial) self.write_data() # Check status if self.trial_seq >= self.mintrain: if float(self.ncorrect) / self.trial_seq >= self.mincorrect: break else: try: self.check_status() except FinishTest: self.exit() return logging.flush() # -------------------------------------------------------------------- # 2. Main series if mode == u'Демо': maxtrials = self.ndemo else: maxtrials = self.maxtrials self.totalN = 0 try: self.instr_stimuli['start_main'].draw() self.test_screen.flip() self.suspend(wait=None) except FinishTest: self.exit() return except GoOn: pass for series in self.trial_dict: self.nfailed = 0 self.invalidstrike = 0 self.ncorrect = 0 self.trial_seq = 0 self.vars['series'] = series self.keys = [x['cor_resp'] for x in self.trial_dict[series]] trials = data.TrialHandler(self.trial_dict[series], self.nreps, method='random') core.wait(1) for trial in trials: if self.totalN + 1 > maxtrials: self.status = 'complete' break if self.trial_seq >= self.mintrain: try: self.check_status() except FinishTest: self.exit() return # break after breaktrials number of trials if self.totalN > 0 and (self.totalN % self.breaktrials) == 0: self.make_a_break(self.breaktime) self.trial_seq += 1 self.totalN += 1 self.vars['n'] = self.totalN self.vars['trial'] = trials.thisN + 1 for i, v in trial.iteritems(): self.vars[i] = v self.run_trial(trial) self.write_data() logging.flush() else: self.status = 'complete' self.exit() return
logFolderName = dataFolderName + os.path.sep + 'Logging' if not os.path.isdir(logFolderName): os.makedirs(logFolderName) logFileName = logFolderName + os.path.sep + '%s_%s_Run%s_%s' % ( expInfo['participant'], expInfo['expName'], expInfo['run'], expInfo['date']) # Name and create specific folder for pickle output outFolderName = dataFolderName + os.path.sep + 'Output' if not os.path.isdir(outFolderName): os.makedirs(outFolderName) outFileName = outFolderName + os.path.sep + '%s_%s_Run%s_%s' % ( expInfo['participant'], expInfo['expName'], expInfo['run'], expInfo['date']) # save a log file and set level for msg to be received logFile = logging.LogFile(logFileName + '.log', level=logging.INFO) logging.console.setLevel(logging.WARNING) # set console to receive warnings # %% MONITOR AND WINDOW # set monitor information: distanceMon = 29.5 # [99 for Nova coil] widthMon = 35 # [30 for Nova coil] PixW = 1920.0 # [1920.0] in scanner PixH = 1200.0 # [1200.0] in scanner moni = monitors.Monitor('testMonitor', width=widthMon, distance=distanceMon) moni.setSizePix([PixW, PixH]) # [1920.0, 1080.0] in psychoph lab # log monitor info logFile.write('MonitorDistance=' + unicode(distanceMon) + 'cm' + '\n')
def setup(self): """ Setup experiment info, log file and window """ self._thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(self._thisDir) expName = 'SemanticIntegration' # from the Builder filename that created this script expInfo = { 'mode': 'experiment', 'participant': '', 'session': '001', 'run': '1', 'list': 'generate', 'screen': '0', 'Send triggers': 'yes' } dlg = gui.DlgFromDict(dictionary=expInfo, sortKeys=False, title=expName) if dlg.OK == False: core.quit() # user pressed cancel expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName expInfo['psychopyVersion'] = self.psychopyVersion filename = self._thisDir + os.sep + u'data/%s_%s_%s_%s' % ( expInfo['participant'], expName, expInfo['run'], expInfo['date']) self.thisExp = data.ExperimentHandler( name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=self._thisDir + os.sep + 'SemanticIntegration.py', savePickle=True, saveWideText=True, dataFileName=filename) self.logFile = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel(logging.WARNING) #self.serial = serial.Serial(self.serialPort, 19200, timeout=1) self.win = visual.Window(size=(1024, 768), fullscr=True, screen=int(expInfo['screen']), winType='pyglet', allowGUI=False, allowStencil=False, monitor='testMonitor', color='black', colorSpace='rgb', blendMode='avg', useFBO=True, units='height') # fixation cross self.fixation = visual.TextStim(win=self.win, name='fixation', text='+', font='Arial', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=0.0) self.fixation.autoDraw = False self.message = visual.TextStim(win=self.win, name='message', text='Press key to start', font='Arial', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=0.0) self.expInfo = expInfo self.expName = expName if expInfo['Send triggers'] == "yes": setupTriggers(self, MODE_EXP) else: setupTriggers(self, MODE_DEV)
###### # set up trial handler blocks = [{ 'cond': cond[0], 'cnum': i + 1, 'items': cond[1] } for i, cond in enumerate(statement_lists)] trials = data.TrialHandler(blocks, 1, method='sequential') print blocks # setup logging # log_file = logging.LogFile("logs/%s.log" % ('demo'), level=logging.DATA, filemode="w") ################ # Set up window # ################ useFullScreen = True win = visual.Window([800, 600], monitor="testMonitor", units="deg", fullscr=useFullScreen, allowGUI=False) ################ # Set up stimuli #
stimTime = 60 # stimuli time for presenting each image # Initialization of button press globalClock = core.Clock() keys = event.getKeys(keyList=None, timeStamped=globalClock) # Prepare PsychoPy log log_base = time.strftime('%m-%d-%y_%H-%M') logWritePath = subject_path + '\\' + subjID + '\\PsychoPyLog_subjID_' + str( subjID) + '_day_' + str(expDay) + '_' + str(log_base) + '.csv' logWritePathKey = subject_path + '\\' + subjID + '\\keypress_subjID_' + str( subjID) + '_day_' + str(expDay) + '_' + str(log_base) + '.csv' # globalClock.reset() logging.LogFile(logWritePath, level=logging.EXP, filemode='w') # logging.setDefaultClock(globalClock) logging.console = True logging.LogFile(logWritePathKey, level=logging.DATA, filemode='w') # Log file for button press only logging.setDefaultClock(globalClock) logging.console = True def log(msg): """Prints messages in the promt and adds msg to PsychoPy log file. """ logging.log(level=logging.EXP, msg=msg) def closeWin():
STIM_DIR = 'stimuli' DEBUG = True use_fullscreen = False ############################# # set up clocks and logging # ############################# globalClock = core.Clock() localClock = core.Clock() if not os.path.exists('logs'): os.mkdir('logs') logging.LogFile('logs/test.log', level=logging.DATA, filemode='w') logging.setDefaultClock(globalClock) instructions = [ '''In this task, you are going to watch a series of video clips of two people who are auditioning for a news anchor position. ### The local news station auditioning the news anchors is trying a new format. They want to see if combining humor with regular news stories will change how viewers respond to the news.''', '''You will see the old and new formats in the news clips. You will watch 16 clips in total. ### Please pay attention to them as you will be asked for your opinions about them latter.''' ]
subdata['simulated_response'] = False subdata['onset'] = '/Users/' + info[ 'computer'] + '/Documents/2019_bevel_pilot/efficiency/onset_' + info['run'] subdata['jitter'] = '/Users/' + info[ 'computer'] + '/Documents/2019_bevel_pilot/efficiency/jitter_' + info['run'] subdata['conds'] = '/Users/' + info[ 'computer'] + '/Documents/2019_bevel_pilot/efficiency/conds_' + info['run'] subdata['quit_key'] = 'q' ####################################### dataFileName = '/Users/' + info[ 'computer'] + '/Documents/2019_bevel_pilot/output/bevel_%s_%s_%s_training_subdata.log' % ( info['participant'], info['run'], subdata['datestamp']) logging.console.setLevel(logging.INFO) logfile = logging.LogFile(dataFileName, level=logging.DATA) ratings_and_onsets = [] key_responses = [] correct_response = [] flip = [] ####################################### # Serial connection and commands setup ser = serial.Serial(port=info['port'], baudrate=19200, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS) if not ser.isOpen(): ser.open() # time.sleep(1)
# print params to Output print 'params = {' for key in sorted(params.keys()): print " '%s': %s" % (key, params[key] ) # print each value as-is (no quotes) print '}' # save experimental info toFile('%s-lastExpInfo.psydat' % scriptName, expInfo) #save params to file for next time #make a log file to save parameter/event data dateStr = ts.strftime("%b_%d_%H%M", ts.localtime()) # add the current time filename = '%s-%s-%d-%s' % (scriptName, expInfo['subject'], expInfo['session'], dateStr) # log filename 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) # log everything in the params struct for key in sorted(params.keys()): # in alphabetical order logging.log(level=logging.INFO, msg='%s: %s' % (key, params[key])) # log each parameter logging.log(level=logging.INFO, msg='---END PARAMETERS---') # ========================== # # ===== GET SCREEN RES ===== # # ========================== #
def vaff(participant_id: str, session: str, run_number: str, is_first: bool): """ Run the value affirmation task for the smoking study. :param participant_id: Participant identifier such as ASH999 :param session: Session number (should be 1 or 2) :param run_number: Run number (should be 1, 2, 3, 4) :param is_first: True if the first run in a block, False if not :return: None """ # Ensure that relative paths start from the same directory as this script _thisDir = os.path.dirname(os.path.abspath(__file__)) os.chdir(_thisDir) # Store info about the experiment session psychopyVersion = '2021.1.2' expName = 'value_affirmation' # from the Builder filename that created this script expInfo = {'participant': participant_id, 'session': session, 'run_number': run_number} expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName expInfo['psychopyVersion'] = psychopyVersion # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath='/Users/pnovak2/src/smoking/value_affirmation/value_affirmation_lastrun.py', savePickle=True, saveWideText=True, dataFileName=filename) # save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.DEBUG) logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp frameTolerance = 0.001 # how close to onset before 'same' frame # Start Code - component code to be run after the window creation # Setup the Window win = visual.Window( size=[2560, 1440], fullscr=True, screen=0, winType='pyglet', allowGUI=False, allowStencil=False, monitor='testMonitor', color=[-1, -1, -1], colorSpace='rgb', blendMode='avg', useFBO=True, units='height') # store frame rate of monitor if we can measure it expInfo['frameRate'] = win.getActualFrameRate() if expInfo['frameRate'] != None: frameDur = 1.0 / round(expInfo['frameRate']) else: frameDur = 1.0 / 60.0 # could not measure, so guess # create a default keyboard (e.g. to check for escape) defaultKeyboard = keyboard.Keyboard() # Initialize components for Routine "setup" setupClock = core.Clock() if is_first: start_text_str = 'Calibrating scanner' start_text_duration = 120 end_text_str = 'The task has ended. The next task will start in a few seconds.' end_text_duration = 10 else: start_text_str = '' start_text_duration = 0.1 end_text_str = 'The task has ended. Waiting for researcher to start next task.' end_text_duration = 3600 conditions_file = os.path.join('conditions', f'VAFF_{expInfo["participant"]}_Session{expInfo["session"]}_Run{expInfo["run_number"]}.csv') # session 0 is a practice session if expInfo['session'] == '0': conditions_file = os.path.join('conditions', 'conditions_practice.csv') start_text_str = 'Practice for message task' start_text_duration = 20 # Initialize components for Routine "instructions" instructionsClock = core.Clock() title_text = visual.TextStim(win=win, name='title_text', text='The Message Task', font='Open Sans', pos=(0, 0), height=0.1, wrapWidth=None, ori=0.0, color='white', colorSpace='rgb', opacity=None, languageStyle='LTR', depth=0.0); start_text = visual.TextStim(win=win, name='start_text', text=start_text_str, font='Helvetica', pos=(0, 0), height=0.05, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=-1.0); start_trigger = keyboard.Keyboard() # Initialize components for Routine "trial" trialClock = core.Clock() value_message_text = visual.TextStim(win=win, name='value_message_text', text='', font='Helvetica', pos=(0, 0), height=0.05, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=-1.0); rating_text = visual.TextStim(win=win, name='rating_text', text='How helpful is this message to help you quit smoking?', font='Helvetica', pos=(0, 0.2), height=0.05, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=-2.0); value_rating = visual.Slider(win=win, name='value_rating', size=(1.0, 0.025), pos=(0, -0.3), units=None, labels=['not at all', 'extremely'], ticks=(1, 2, 3, 4, 5), granularity=0, style='rating', styleTweaks=('triangleMarker',), opacity=1, color='LightGray', fillColor='Red', borderColor='White', colorSpace='rgb', font='Helvetica', labelHeight=0.05, flip=False, depth=-3, readOnly=False) value_keyboard = keyboard.Keyboard() # Initialize components for Routine "iti" itiClock = core.Clock() intertrial_interval = visual.ImageStim( win=win, name='intertrial_interval', image=None, mask=None, ori=0, pos=(0, 0), size=(0.5, 0.5), color=[1, 1, 1], colorSpace='rgb', opacity=1, flipHoriz=False, flipVert=False, texRes=128, interpolate=True, depth=0.0) # Initialize components for Routine "end" endClock = core.Clock() end_text = visual.TextStim(win=win, name='end_text', text=end_text_str, font='Helvetica', pos=(0, 0), height=0.05, wrapWidth=None, ori=0, color='white', colorSpace='rgb', opacity=1, languageStyle='LTR', depth=0.0); end_key_resp = keyboard.Keyboard() # Create some handy timers globalClock = core.Clock() # to track the time since experiment started routineTimer = core.CountdownTimer() # to track time remaining of each (non-slip) routine # ------Prepare to start Routine "setup"------- continueRoutine = True # update component parameters for each repeat # keep track of which components have finished setupComponents = [] for thisComponent in setupComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") setupClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "setup"------- while continueRoutine: # get current time t = setupClock.getTime() tThisFlip = win.getFutureFlipTime(clock=setupClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in setupComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "setup"------- for thisComponent in setupComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) # the Routine "setup" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # ------Prepare to start Routine "instructions"------- continueRoutine = True # update component parameters for each repeat start_trigger.keys = [] start_trigger.rt = [] _start_trigger_allKeys = [] # keep track of which components have finished instructionsComponents = [title_text, start_text, start_trigger] for thisComponent in instructionsComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") instructionsClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "instructions"------- while continueRoutine: # get current time t = instructionsClock.getTime() tThisFlip = win.getFutureFlipTime(clock=instructionsClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *title_text* updates if title_text.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance: # keep track of start time/frame for later title_text.frameNStart = frameN # exact frame index title_text.tStart = t # local t and not account for scr refresh title_text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(title_text, 'tStartRefresh') # time at next scr refresh title_text.setAutoDraw(True) if title_text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > title_text.tStartRefresh + 2.0 - frameTolerance: # keep track of stop time/frame for later title_text.tStop = t # not accounting for scr refresh title_text.frameNStop = frameN # exact frame index win.timeOnFlip(title_text, 'tStopRefresh') # time at next scr refresh title_text.setAutoDraw(False) # *start_text* updates if start_text.status == NOT_STARTED and tThisFlip >= 2 - frameTolerance: # keep track of start time/frame for later start_text.frameNStart = frameN # exact frame index start_text.tStart = t # local t and not account for scr refresh start_text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(start_text, 'tStartRefresh') # time at next scr refresh start_text.setAutoDraw(True) if start_text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > start_text.tStartRefresh + start_text_duration - frameTolerance: # keep track of stop time/frame for later start_text.tStop = t # not accounting for scr refresh start_text.frameNStop = frameN # exact frame index win.timeOnFlip(start_text, 'tStopRefresh') # time at next scr refresh start_text.setAutoDraw(False) # *start_trigger* updates waitOnFlip = False if start_trigger.status == NOT_STARTED and tThisFlip >= 2 - frameTolerance: # keep track of start time/frame for later start_trigger.frameNStart = frameN # exact frame index start_trigger.tStart = t # local t and not account for scr refresh start_trigger.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(start_trigger, 'tStartRefresh') # time at next scr refresh start_trigger.status = STARTED # keyboard checking is just starting waitOnFlip = True win.callOnFlip(start_trigger.clock.reset) # t=0 on next screen flip win.callOnFlip(start_trigger.clearEvents, eventType='keyboard') # clear events on next screen flip if start_trigger.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > start_trigger.tStartRefresh + start_text_duration - frameTolerance: # keep track of stop time/frame for later start_trigger.tStop = t # not accounting for scr refresh start_trigger.frameNStop = frameN # exact frame index win.timeOnFlip(start_trigger, 'tStopRefresh') # time at next scr refresh start_trigger.status = FINISHED if start_trigger.status == STARTED and not waitOnFlip: theseKeys = start_trigger.getKeys(keyList=['apostrophe'], waitRelease=False) _start_trigger_allKeys.extend(theseKeys) if len(_start_trigger_allKeys): start_trigger.keys = _start_trigger_allKeys[-1].name # just the last key pressed start_trigger.rt = _start_trigger_allKeys[-1].rt # a response ends the routine continueRoutine = False # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in instructionsComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "instructions"------- for thisComponent in instructionsComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) thisExp.addData('title_text.started', title_text.tStartRefresh) thisExp.addData('title_text.stopped', title_text.tStopRefresh) # the Routine "instructions" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # set up handler to look after randomisation of conditions etc trials = data.TrialHandler(nReps=1, method='sequential', extraInfo=expInfo, originPath=-1, trialList=data.importConditions(conditions_file), seed=None, name='trials') thisExp.addLoop(trials) # add the loop to the experiment for thisTrial in trials: currentLoop = trials # ------Prepare to start Routine "trial"------- continueRoutine = True routineTimer.add(10.000000) # update component parameters for each repeat value_message_text.setText(thisTrial['message']) value_rating.reset() value_keyboard.keys = [] value_keyboard.rt = [] _value_keyboard_allKeys = [] # keep track of which components have finished trialComponents = [value_message_text, rating_text, value_rating, value_keyboard] for thisComponent in trialComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") trialClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "trial"------- while continueRoutine and routineTimer.getTime() > 0: # get current time t = trialClock.getTime() tThisFlip = win.getFutureFlipTime(clock=trialClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # Update marker position and slider rating # when there are keypresses of the rating buttons r = convert_key_to_rating(value_keyboard.keys) value_rating.markerPos = r # confirm rating by setting to current markerPos value_rating.rating = r # *value_message_text* updates if value_message_text.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance: # keep track of start time/frame for later value_message_text.frameNStart = frameN # exact frame index value_message_text.tStart = t # local t and not account for scr refresh value_message_text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(value_message_text, 'tStartRefresh') # time at next scr refresh value_message_text.setAutoDraw(True) if value_message_text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > value_message_text.tStartRefresh + 6 - frameTolerance: # keep track of stop time/frame for later value_message_text.tStop = t # not accounting for scr refresh value_message_text.frameNStop = frameN # exact frame index win.timeOnFlip(value_message_text, 'tStopRefresh') # time at next scr refresh value_message_text.setAutoDraw(False) # *rating_text* updates if rating_text.status == NOT_STARTED and tThisFlip >= 6 - frameTolerance: # keep track of start time/frame for later rating_text.frameNStart = frameN # exact frame index rating_text.tStart = t # local t and not account for scr refresh rating_text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(rating_text, 'tStartRefresh') # time at next scr refresh rating_text.setAutoDraw(True) if rating_text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > rating_text.tStartRefresh + 4 - frameTolerance: # keep track of stop time/frame for later rating_text.tStop = t # not accounting for scr refresh rating_text.frameNStop = frameN # exact frame index win.timeOnFlip(rating_text, 'tStopRefresh') # time at next scr refresh rating_text.setAutoDraw(False) # *value_rating* updates if value_rating.status == NOT_STARTED and tThisFlip >= 6 - frameTolerance: # keep track of start time/frame for later value_rating.frameNStart = frameN # exact frame index value_rating.tStart = t # local t and not account for scr refresh value_rating.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(value_rating, 'tStartRefresh') # time at next scr refresh value_rating.setAutoDraw(True) if value_rating.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > value_rating.tStartRefresh + 4 - frameTolerance: # keep track of stop time/frame for later value_rating.tStop = t # not accounting for scr refresh value_rating.frameNStop = frameN # exact frame index win.timeOnFlip(value_rating, 'tStopRefresh') # time at next scr refresh value_rating.setAutoDraw(False) # *value_keyboard* updates waitOnFlip = False if value_keyboard.status == NOT_STARTED and tThisFlip >= 6 - frameTolerance: # keep track of start time/frame for later value_keyboard.frameNStart = frameN # exact frame index value_keyboard.tStart = t # local t and not account for scr refresh value_keyboard.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(value_keyboard, 'tStartRefresh') # time at next scr refresh value_keyboard.status = STARTED # keyboard checking is just starting waitOnFlip = True win.callOnFlip(value_keyboard.clock.reset) # t=0 on next screen flip win.callOnFlip(value_keyboard.clearEvents, eventType='keyboard') # clear events on next screen flip if value_keyboard.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > value_keyboard.tStartRefresh + 4 - frameTolerance: # keep track of stop time/frame for later value_keyboard.tStop = t # not accounting for scr refresh value_keyboard.frameNStop = frameN # exact frame index win.timeOnFlip(value_keyboard, 'tStopRefresh') # time at next scr refresh value_keyboard.status = FINISHED if value_keyboard.status == STARTED and not waitOnFlip: theseKeys = value_keyboard.getKeys(keyList=['5', '6', '7', '8', '9'], waitRelease=False) _value_keyboard_allKeys.extend(theseKeys) if len(_value_keyboard_allKeys): value_keyboard.keys = _value_keyboard_allKeys[-1].name # just the last key pressed value_keyboard.rt = _value_keyboard_allKeys[-1].rt # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in trialComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "trial"------- for thisComponent in trialComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) rating_text.tStopRefresh = tThisFlipGlobal value_rating.tStopRefresh = tThisFlipGlobal value_keyboard.tStopRefresh = tThisFlipGlobal trials.addData('value_message_text.started', value_message_text.tStartRefresh) trials.addData('value_message_text.stopped', value_message_text.tStopRefresh) trials.addData('rating_text.started', rating_text.tStartRefresh) trials.addData('rating_text.stopped', rating_text.tStopRefresh) trials.addData('value_rating.response', value_rating.getRating()) trials.addData('value_rating.started', value_rating.tStartRefresh) trials.addData('value_rating.stopped', value_rating.tStopRefresh) # check responses if value_keyboard.keys in ['', [], None]: # No response was made value_keyboard.keys = None trials.addData('value_keyboard.keys', value_keyboard.keys) if value_keyboard.keys != None: # we had a response trials.addData('value_keyboard.rt', value_keyboard.rt) trials.addData('value_keyboard.started', value_keyboard.tStartRefresh) trials.addData('value_keyboard.stopped', value_keyboard.tStopRefresh) # ------Prepare to start Routine "iti"------- continueRoutine = True # update component parameters for each repeat # keep track of which components have finished itiComponents = [intertrial_interval] for thisComponent in itiComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") itiClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "iti"------- while continueRoutine: # get current time t = itiClock.getTime() tThisFlip = win.getFutureFlipTime(clock=itiClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *intertrial_interval* updates if intertrial_interval.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance: # keep track of start time/frame for later intertrial_interval.frameNStart = frameN # exact frame index intertrial_interval.tStart = t # local t and not account for scr refresh intertrial_interval.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(intertrial_interval, 'tStartRefresh') # time at next scr refresh intertrial_interval.setAutoDraw(True) if intertrial_interval.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > intertrial_interval.tStartRefresh + thisTrial['iti'] - frameTolerance: # keep track of stop time/frame for later intertrial_interval.tStop = t # not accounting for scr refresh intertrial_interval.frameNStop = frameN # exact frame index win.timeOnFlip(intertrial_interval, 'tStopRefresh') # time at next scr refresh intertrial_interval.setAutoDraw(False) # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in itiComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "iti"------- for thisComponent in itiComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) trials.addData('intertrial_interval.started', intertrial_interval.tStartRefresh) trials.addData('intertrial_interval.stopped', intertrial_interval.tStopRefresh) # the Routine "iti" was not non-slip safe, so reset the non-slip timer routineTimer.reset() thisExp.nextEntry() # completed 1 repeats of 'trials' # ------Prepare to start Routine "end"------- continueRoutine = True # update component parameters for each repeat end_key_resp.keys = [] end_key_resp.rt = [] _end_key_resp_allKeys = [] # keep track of which components have finished endComponents = [end_text, end_key_resp] for thisComponent in endComponents: thisComponent.tStart = None thisComponent.tStop = None thisComponent.tStartRefresh = None thisComponent.tStopRefresh = None if hasattr(thisComponent, 'status'): thisComponent.status = NOT_STARTED # reset timers t = 0 _timeToFirstFrame = win.getFutureFlipTime(clock="now") endClock.reset(-_timeToFirstFrame) # t0 is time of first possible flip frameN = -1 # -------Run Routine "end"------- while continueRoutine: # get current time t = endClock.getTime() tThisFlip = win.getFutureFlipTime(clock=endClock) tThisFlipGlobal = win.getFutureFlipTime(clock=None) frameN = frameN + 1 # number of completed frames (so 0 is the first frame) # update/draw components on each frame # *end_text* updates if end_text.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance: # keep track of start time/frame for later end_text.frameNStart = frameN # exact frame index end_text.tStart = t # local t and not account for scr refresh end_text.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(end_text, 'tStartRefresh') # time at next scr refresh end_text.setAutoDraw(True) if end_text.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > end_text.tStartRefresh + end_text_duration - frameTolerance: # keep track of stop time/frame for later end_text.tStop = t # not accounting for scr refresh end_text.frameNStop = frameN # exact frame index win.timeOnFlip(end_text, 'tStopRefresh') # time at next scr refresh end_text.setAutoDraw(False) # *end_key_resp* updates waitOnFlip = False if end_key_resp.status == NOT_STARTED and tThisFlip >= 0.0 - frameTolerance: # keep track of start time/frame for later end_key_resp.frameNStart = frameN # exact frame index end_key_resp.tStart = t # local t and not account for scr refresh end_key_resp.tStartRefresh = tThisFlipGlobal # on global time win.timeOnFlip(end_key_resp, 'tStartRefresh') # time at next scr refresh end_key_resp.status = STARTED # keyboard checking is just starting waitOnFlip = True win.callOnFlip(end_key_resp.clock.reset) # t=0 on next screen flip win.callOnFlip(end_key_resp.clearEvents, eventType='keyboard') # clear events on next screen flip if end_key_resp.status == STARTED: # is it time to stop? (based on global clock, using actual start) if tThisFlipGlobal > end_key_resp.tStartRefresh + asarray(end_text_duration) - frameTolerance: # keep track of stop time/frame for later end_key_resp.tStop = t # not accounting for scr refresh end_key_resp.frameNStop = frameN # exact frame index win.timeOnFlip(end_key_resp, 'tStopRefresh') # time at next scr refresh end_key_resp.status = FINISHED if end_key_resp.status == STARTED and not waitOnFlip: theseKeys = end_key_resp.getKeys(keyList=['space'], waitRelease=False) _end_key_resp_allKeys.extend(theseKeys) if len(_end_key_resp_allKeys): end_key_resp.keys = _end_key_resp_allKeys[-1].name # just the last key pressed end_key_resp.rt = _end_key_resp_allKeys[-1].rt # a response ends the routine continueRoutine = False # check for quit (typically the Esc key) if endExpNow or defaultKeyboard.getKeys(keyList=["escape"]): core.quit() # check if all components have finished if not continueRoutine: # a component has requested a forced-end of Routine break continueRoutine = False # will revert to True if at least one component still running for thisComponent in endComponents: if hasattr(thisComponent, "status") and thisComponent.status != FINISHED: continueRoutine = True break # at least one component has not yet finished # refresh the screen if continueRoutine: # don't flip if this routine is over or we'll get a blank screen win.flip() # -------Ending Routine "end"------- for thisComponent in endComponents: if hasattr(thisComponent, "setAutoDraw"): thisComponent.setAutoDraw(False) thisExp.addData('end_text.started', end_text.tStartRefresh) thisExp.addData('end_text.stopped', end_text.tStopRefresh) # check responses if end_key_resp.keys in ['', [], None]: # No response was made end_key_resp.keys = None thisExp.addData('end_key_resp.keys', end_key_resp.keys) if end_key_resp.keys != None: # we had a response thisExp.addData('end_key_resp.rt', end_key_resp.rt) thisExp.addData('end_key_resp.started', end_key_resp.tStartRefresh) thisExp.addData('end_key_resp.stopped', end_key_resp.tStopRefresh) thisExp.nextEntry() # the Routine "end" was not non-slip safe, so reset the non-slip timer routineTimer.reset() # Flip one final time so any remaining win.callOnFlip() # and win.timeOnFlip() tasks get executed before quitting win.flip() # these shouldn't be strictly necessary (should auto-save) thisExp.saveAsWideText(filename + '.csv', delim='auto') thisExp.saveAsPickle(filename) logging.flush() # make sure everything is closed down thisExp.abort() # or data files will save again on exit win.close() core.quit()
def main(fCue,fInterval,fTest,fPause,tPerBlock,stimType,arraySize,targPresent,numTrials,participant,session): fCue = fCue fInterval = fInterval fTest = fTest fPause = fPause tPerBlock = tPerBlock stimType = stimType arraySize = arraySize targPresent = targPresent numTrials = numTrials _thisDir = "C:/Users/micah/Documents/Honors Project/Visual Search Task/" # Store info about the experiment session expName = 'Visual Search Task.py' expInfo = {'session': session, 'participant': participant} expInfo['date'] = data.getDateStr() # add a simple timestamp expInfo['expName'] = expName # Data file name stem = absolute path + name; later add .psyexp, .csv, .log, etc filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date']) thisExp = data.ExperimentHandler(name=expName, version='0.1', extraInfo={'participant': participant}, runtimeInfo=None, originPath=None, savePickle=True, saveWideText=True, dataFileName=filename) # save a log file for detail verbose info logFile = logging.LogFile(filename+'.log', level=logging.EXP) logging.console.setLevel(logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp win = visual.Window([1600, 900], units = 'height', fullscr=True) clock = core.Clock() # KEYBOARD STUFF # iohub is broken currently events = event.getKeys() # INITIALIZE # trialN : number of trial # trialResp : their response on each trial # correctResp : if their response was correct # responseTime : the amount of time it took for them to respond on each trial m = 0 trialN = [-1 for x in range(numTrials)] trialResp = [9 for x in range(numTrials)] correctResp = [9 for x in range(numTrials)] responseTime = [0 for x in range(numTrials)] respChar = [['r','i'],['f','j']] numSet = 100 rectangles = not stimType pauseText = visual.TextStim(win, text = "Press the Spacebar to Continue", font=u'Arial', pos=(0, 0), height=0.1, wrapWidth=None, ori=0, color=u'white', colorSpace='rgb', opacity=1, depth=0.0) for t in range(numTrials): trialTime = time.time() if (t % tPerBlock == 0) & (t > 1): event.clearEvents(eventType='keyboard') waiting = [] tStart = time.time() while not 'space' in waiting: waiting = event.getKeys(keyList=['space']) pauseText.draw() win.flip() pauseTime = time.time() - tStart thisExp.addData('pauseTime', pauseTime) trialN[t] = t + 1 # STIM PRESENTATION randTrial = random.randint(1,100) cueName = 'stimType%d_arraySize%d_targPresent%d_order%d (%d).png' % (stimType, arraySize[t], targPresent[t], 0, randTrial) cueDir = '%d%d%d/' % (targPresent[t], stimType, arraySize[t]) + cueName cueStim = visual.ImageStim(win, image = cueDir) stimName = 'stimType%d_arraySize%d_targPresent%d_order%d (%d).png' % (stimType, arraySize[t], targPresent[t], 1, randTrial) stimDir = '%d%d%d/' % (targPresent[t], stimType, arraySize[t]) + stimName arrayStim = visual.ImageStim(win, image = stimDir) # presents array for frameN in range(fCue + 1): cueStim.draw() win.flip() for frameN in range(fInterval + 1): win.flip() startT = time.time() for frameN in range(fTest + 1): theseKeys = event.getKeys(keyList=['f','j']) if len(theseKeys) > 0: # at least one key was pressed trialResp[t] = theseKeys[-1] # just the last key pressed responseTime[t] = time.time() - startT arrayStim.draw() win.flip() for frameN in range(fPause + 1): win.flip() # f means no target, j means yes target if targPresent[t]: correctResp[t] = trialResp[t] == 'j' else: correctResp[t] = trialResp[t] == 'f' # OUTPUT thisExp.addData('stimType', stimType) thisExp.addData('arraySize', arraySize[t]) thisExp.addData('targPresent', targPresent[t]) thisExp.addData('startTime', trialTime) thisExp.addData('responseTime', responseTime[t]) thisExp.addData('trialKeyPress', trialResp[t]) thisExp.addData('correctResponse',correctResp[t]) thisExp.addData('trialNumber', trialN[t]) thisExp.addData('stimulusHandle', stimName) thisExp.nextEntry() # these shouldn't be strictly necessary (should auto-save) thisExp.saveAsWideText(filename+'.csv') thisExp.saveAsPickle(filename) logging.flush() # make sure everything is closed down thisExp.abort() # or data files will save again on exit win.close() core.quit() # these shouldn't be strictly necessary (should auto-save) thisExp.saveAsWideText(filename+'.csv') thisExp.saveAsPickle(filename) logging.flush() # make sure everything is closed down thisExp.abort() # or data files will save again on exit win.close() core.quit()
count_txt = ['Listen', 'Listen', 'Imagine', 'Imagine'] #durs = [550,600,550,600] durs = [400, 400, 400, 400] fixationCross = visual.TextStim(win, text='+', color=col, height=0.2) # create a silent sound to prevent buffer issues silentDur = .5 silent = sound.Sound('C', secs=silentDur, volume=0, sampleRate=44100, stereo=False) # start log file: filename = log_dir + '/' + sub_id[0] + '_localizer_iEEG.log' lastLog = logging.LogFile(filename, level=logging.INFO, filemode='w') ############################################################################## ############################# Start the task ################################# instructions.draw() win.flip() event.waitKeys() fixationCross.draw() win.flip() silent.play() core.wait(0.5) nextFlip = win.getFutureFlipTime(clock='ptb') for s in seq: win.callOnFlip(setParallelData, int(s))
if os.path.isdir('.' + os.sep + 'dataRaw'): dataDir = 'dataRaw' else: msg = 'dataRaw directory does not exist, so saving data in present working directory' print(msg) logging.info(msg) dataDir = '.' timeAndDateStr = time.strftime("%d%b%Y_%H-%M", time.localtime()) fileNameWithPath = dataDir + os.sep + subject + '_' + expname + timeAndDateStr if not demo and not exportImages: saveCodeCmd = 'cp \'' + sys.argv[0] + '\' ' + fileNameWithPath + '.py' os.system(saveCodeCmd ) #save a copy of the code as it was when that subject was run logF = logging.LogFile( fileNameWithPath + '.log', filemode= 'w', #if you set this to 'a' it will append instead of overwriting level=logging.INFO ) #info, data, warnings, and errors will be sent to this logfile if demo or exportImages: logging.console.setLevel( logging.ERROR) #only show this level's and higher messages logging.console.setLevel( logging.WARNING ) #DEBUG means set the console to receive nearly all messges, INFO is for everything else, INFO, EXP, DATA, WARNING and ERROR if refreshRateWrong: logging.error(refreshMsg1 + refreshMsg2) else: logging.info(refreshMsg1 + refreshMsg2) longerThanRefreshTolerance = 0.27 longFrameLimit = round(1000. / refreshRate * (1.0 + longerThanRefreshTolerance),
@port.setter def port(self, p): if p is not None: try: self.__port = parallel.ParallelPort(address=p) except FileNotFoundError: self.__port = None else: self.__port = None def send(self, triggertype, triggername, io=None): value = self.trigger[triggertype][triggername] logging.log('{}\t{}\t{}'.format(value, triggertype, triggername), level=logging.getLevel('TRIG')) if not io is None: io.sendMessageEvent(format(value), category='TRIGGER') if self.port is not None: sendTime = core.getTime() self.port.setData(value) while core.getTime() < sendTime + .004: self.port.setData(0) if __name__ == '__main__': logging.LogFile(f='triggers.tsv', level=logging.getLevel('TRIG')) trigger = Trigger() trigger.send('acquisition', 'start') trigger.send('acquisition', 'end')
filename = _thisDir + os.sep + u'data/%s_%s_%s' % (expInfo['participant'], expName, expInfo['date']) # An ExperimentHandler isn't essential but helps with data saving thisExp = data.ExperimentHandler( name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath= 'C:\\Users\\Taylor\\Downloads\\CSN Lab\\projects\\round_robin\\scripts\\scanner_portion\\psychopy_scripts\\runA\\runA.py', savePickle=True, saveWideText=True, dataFileName=filename) # save a log file for detail verbose info logFile = logging.LogFile(filename + '.log', level=logging.EXP) logfile = logging.LogFile(filename + '_data.log', level=logging.DATA) logging.console.setLevel( logging.WARNING) # this outputs to the screen, not a file endExpNow = False # flag for 'escape' or other condition => quit the exp # Start Code - component code to be run before the window creation # Setup the Window win = visual.Window(size=[1920, 1080], fullscr=True, screen=0, allowGUI=False, allowStencil=False, monitor='testMonitor',
text="Curl your tongue.", pos=[0, 0], color="black", height=50, font="Arial") null_txt = visual.TextStim(win, text="+", pos=[0, 0], color="black", height=50, font="Arial") #logging data # overwrite (filemode='w') a detailed log of the last run in this dir lastLog = logging.LogFile("lastRun.log", level=logging.INFO, filemode='w') # in the data source, there are two columns: Time (0-502) and StimType (1-6) # Link the numbers in StimType to the names of the text displays STIM = { 1: Rhand_txt, 2: Lhand_txt, 3: Rfoot_txt, 4: Lfoot_txt, 5: tongue_txt, 6: null_txt } # load in our stimulus timing csv file TRIAL_LIST = data.importConditions(fileName=parent_dir + "localizer_datasource.csv")