def main(): initials = raw_input('Your initials: ') pp_nr = 0 while not 0 < pp_nr < 101: pp_nr = int(raw_input('Participant number: ')) if not 0 < pp_nr < 101: print('Number must be between 1 and 100. What is the participant number?: ') scanner = 'y' tracker_on = False language = '' while language not in ['en', 'nl']: language = raw_input('What language do you want to use (en/nl)?: ') if language not in ['en', 'nl']: print('I don''t understand that. Please enter ''en'' or ''nl''. What language do you want to use (' 'en/nl)?: ') sess = FlashPracticeSession(subject_initials=initials, index_number=pp_nr, scanner=scanner, tracker_on=tracker_on, language=language) # Launch dummy scanner sess.scanner = launchScan(win=sess.screen, settings={'TR': TR, 'volumes': 10000, 'sync': 't'}, mode='Test') sess.run()
def MRI(self): from psychopy.hardware.emulator import launchScan MR_settings = { 'TR': 2.000, # duration (sec) per volume 'volumes': 210, # number of whole-brain 3D volumes / frames 'sync': 's', # character to use as the sync timing event; # assumed to come at start of a volume 'skip': 0, # number of volumes lacking a sync pulse at start of # scan (for T1 stabilization) 'sound': False, } launchScan( self.win, MR_settings, mode=u'Scan', # also takes 'Test' globalClock=self.globalClock, log=False)
def MRI(win): # Recieves MRI pulse, needed to sync timing with scanner MR_settings = { 'TR': 2.000, # duration (sec) per volume 'volumes': 210, # number of whole-brain 3D volumes / frames 'sync': 's', # character to use as the sync timing event; # assumed to come at start of a volume 'skip': 0, # number of volumes lacking a sync pulse at start # scan (for T1 stabilization) 'sound': False, } launchScan( win, MR_settings, mode=u'Scan', # also takes 'Test' globalClock=globalClock, log=False)
def launchTheScan(): # configure menu screen from psychopy function settings = dict([("TR", TR), ("volumes", 2000), ("sync", trigger)]) menu_screen = launchScan(window, settings, globalClock=CLOCK, simResponses=None, mode="Scan", esc_key="escape", instr="Select Scan or Test, press enter", wait_msg="Waiting for scanner...", wait_timeout=30, log=True)
output += '%d prescan skip (no sync)\n' % i key_code = MR_settings['sync'] counter = visual.TextStim(win, height=.05, pos=(0, 0), color=win.rgb + 0.5) output += " 0 0.000 %s start of scanning run, vol 0\n" % key_code pause_during_delay = (MR_settings['TR'] > .4) sync_now = False # can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time): simResponses = [(0, '5'), (2, '5'), (4, '5'), (6, '5'), (8, '5'), (10, '5'), (12, '5'), (14, '5'), (16, '5'), (18, '5'), (20, '5'), (22, '5')] # launch: operator selects Scan or Test (emulate); see API documentation vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=simResponses) infer_missed_sync = False # best if your script timing works without this, but this might be useful sometimes max_slippage = 0.02 # how long to allow before treating a "slow" sync as missed # any slippage is almost certainly due to timing issues with your script or PC, and not MR scanner duration = MR_settings['volumes'] * MR_settings['TR'] # note: globalClock has been reset to 0.0 by launchScan() #create stimuli #Initialise components for routine:PD fix = visual.TextStim(win=win, ori=0,
from psychopy import monitors my_monitor = monitors.Monitor(name=config.get('screen', 'monitor_name')) my_monitor.setSizePix(config.get('screen', 'size')) my_monitor.setWidth(config.get('screen', 'physical_screen_size')[0]) my_monitor.setDistance(config.get('screen', 'physical_screen_distance')) my_monitor.saveMon() # Set-up session sess = StopSignalSession('DEBUG', 1, run=1, tr=3, config=config) # EMULATOR from psychopy.hardware.emulator import launchScan scanner_emulator = launchScan(win=sess.screen, settings={ 'TR': 3, 'volumes': 30000, 'sync': 't' }, mode='Test') # run sess.run() # Load & dump data import cPickle as pkl from pprint import pprint with open(sess.output_file + '_outputDict.pkl', 'r') as f: a = pkl.load(f) pprint(a)
set_positions() set_timing() flash_init(win, fl_p, square_size=1, columns=10, rows=10) sync_now = False on = False # true when stim is on stim_switch = False # true when stim switches on or off last_change = 0 # summary of run timing, for each key press: data = {'vol': [], 'event': [], 'onset': [], 'duration': [], 'stim_on': []} key_code = MR_settings['sync'] # launch: operator selects Scan or Test (emulate); see API docuwmentation vol = launchScan(win, MR_settings, mode=mode, globalClock=globalClock) print('Scan start') print(u"%3d %7.3f %s\n" % (vol, 0, unicode(key_code))) duration = MR_settings['volumes'] * tr # note: globalClock has been reset to 0.0 by launchScan() while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key != MR_settings['sync']: onset = globalClock.getTime() print(u"%3d %7.3f %s\n" % (vol, onset, unicode(key))) data['vol'].append(vol) data['event'].append(unicode(key)) data['onset'].append(onset) data['duration'].append(.0001) data['stim_on'].append(on)
# Initialize Session sess = FlashSession(subject_initials='SM', index_number=1, scanner='n', tracker_on=True, language='nl', mirror=False, start_block=0, start_score=0) # Launch dummy scanner sess.scanner = launchScan(win=sess.screen, settings={ 'TR': TR, 'volumes': 10000, 'sync': 't' }, mode='Test') if sess.dummy_tracker: # annoyingly, launchScan sets mouseVisible to False - set it back to True for dummy tracking... sess.screen.setMouseVisible(True) # RUN sess.run() # Load and print latest data/events import cPickle as pickle from pprint import pprint from glob import glob data_file = glob('data/*_outputDict.pickle')[-1]
# create empty dataframe to accumulate data data = pd.DataFrame(columns=['Sub', 'Run', 'TR', 'time']) # Create the fixation dot, and initialize as white fill. fix = visual.Circle(mywin, units='deg', radius=0.05, pos=(0, 0), fillColor='white', lineColor='black', lineWidth=0.5, opacity=0.5, edges=128) # start global clock and fMRI pulses (start simulated or wait for real) print('Starting sub {} in run #{}'.format(IDnum, run)) vol = launchScan(mywin, MR_settings, simResponses=None, mode=scanmode, esc_key='escape', instr='select Scan or Test, press enter', wait_msg='waiting for scanner...', wait_timeout=300, log=True) image = visual.ImageStim( win=mywin, name='image', image='./carchair_exp_feedback/bedChair_1_5.png', 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=-4.0) backgroundImage = visual.ImageStim( win=mywin, name='image', image='./carchair_exp_feedback/greyBackground.png', mask=None,
# summary of run timing, for each key press: output = 'vol onset key\n' for i in range(-1 * MR_settings['skip'], 0): output += '%d prescan skip (no sync)\n' % i key_code = MR_settings['sync'] counter = visual.TextStim(win, height=.05, pos=(0,0), color=win.rgb+0.5) output += " 0 0.000 %s start of scanning run, vol 0\n" % key_code pause_during_delay = (MR_settings['TR'] > .4) sync_now = False # can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time): simResponses = [(0.123, 'a'), (4.789, 'c'), (2.456, 'b')] # launch: operator selects Scan or Test (emulate); see API documentation vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=simResponses) infer_missed_sync = False # best if your script timing works without this, but this might be useful sometimes max_slippage = 0.02 # how long to allow before treating a "slow" sync as missed # any slippage is almost certainly due to timing issues with your script or PC, and not MR scanner duration = MR_settings['volumes'] * MR_settings['TR'] # note: globalClock has been reset to 0.0 by launchScan() while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key != MR_settings['sync']: output += "%3d %7.3f %s\n" % (vol-1, globalClock.getTime(), str(key)) if 'escape' in allKeys: output += 'user cancel, ' break
def present_stimuli(stimuli, settings): """Present stimuli in the specified order timed by scanner triggers. Uses psychopy's launchScan module which adds a test/scan switch on the first window. If in test mode, launchScan immitates the scanner by sending triggers (key press '5') and playing scanner noise when the scanner would be acquiring a volume (if settings['sound'] == True). The inner function parse_keys() is called regularly to listen for key presses and update the dictionary of state variables accordingly. The rest of the function uses various state variables to determine what actions to take, e.g. play a sound, present a response probe, rest. Saves the following files in a directory called 'run_data' in the subject directory. [subject]_run[run]_all_keys_[date].txt: All key presses recorded [subject]_run[run]_resp_blocks_[date].txt: Task performance [subject]_run[run]_stimuli_timing_[date].txt: Stim name and onset time [subject]_run[run]_settings_[date].npy: settings dict used this run [subject]_run[run]_stimuli_onsets_[date].npy: Stim name and onset time [subject]_run[run]_vol_onsets_[date].npy: Onset time of all triggers An automated log file is also saved in logs/ Parameters ---------- stimuli : ndarray of psychopy.sound.SoundPyo objects Sounds to be presented in this run in the order in which they are to be presented. As determined by order.py settings : dict Contains various experimental settings such as MR imaging parameters TODO: - present stimuli is too complex """ if settings['debug']: win = visual.Window(fullscr=False) else: win = visual.Window(allowGUI=False, monitor='testMonitor', fullscr=True) fixation = visual.ShapeStim(win, vertices=((0, -0.055), (0, 0.055), (0, 0), (-0.045, 0), (0.045, 0)), lineWidth=2, closeShape=False, lineColor='black') global_clock = core.Clock() # summary of run timing, for each key press: out = u'vol onset key\n' for i in range(-1 * settings['skip'], 0): out += u'%d prescan skip (no sync)\n' % i vol_onsets = np.zeros(settings['volumes']) # Stimulus log stim_log = u'onset stimulus_idx\n' stim_onsets = np.zeros(len(stimuli)) # Response log n_resp = sum(settings['resp']) cor = 0 resp_log = u'resp_onset block correct/incorrect \n' # Key press log key_code = settings['sync'] resp_text = visual.TextStim(win, height=.15, pos=(0, 0), color='black', bold=True) question = u"Which language did the last block sound like? " options = u"Press: \n 1 (Dutch) \n 2 (English) \n 3 (German)" resp_text.setText(question + options) out += u" 0 0.000 %s [Start of scanning run, vol 0]\n" % key_code # Best if your script timing works without this, but this might be useful # sometimes infer_missed_sync = False # How long to allow before treating a "slow" sync as missed. Any slippage # is almost certainly due to timing issues with your script or PC, and not # MR scanner max_slippage = .5 # Timing variables n_tr = 0 block = 0 base1tr = 5 stimtr = 35 waithrftr = 6 responsetr = 2 resttr = 11 base2tr = 11 stim = None # Dict to maintain state of the program state = { 'sync_now': False, 'rest': False, 'response': False, 'playblock': False, 'baseline_start': True, 'baseline_end': False, 'listen_for_resp': False, 'responded': False } # wait 5 TRs after the last stimulus duration = settings['volumes'] * settings['TR'] # launch: operator selects Scan or Test (emulate); see API documentation vol = launchScan(win, settings, globalClock=global_clock) fixation.draw() win.flip() def parse_keys(): core.wait(.0001, hogCPUperiod=0.00001) all_keys = event.getKeys() new_ntr = n_tr new_vol = vol newcorrect = cor newout = out newrl = resp_log now = global_clock.getTime() # Log all key preses for key in all_keys: if key != settings['sync']: newout = newout + u"%3d %7.3f %s\n" % (vol - 1, now, str(key)) # Let the user close the program if 'escape' in all_keys: newout = newout + u'user cancel, ' if stim: stim.stop() core.quit() sys.exit() # Detect sync or infer it should have happened: if settings['sync'] in all_keys: state['sync_now'] = key_code onset = now if infer_missed_sync: expected_onset = vol * settings['TR'] now = global_clock.getTime() if now > expected_onset + max_slippage: state['sync_now'] = u'(inferred onset)' onset = expected_onset if state['sync_now']: newout = newout + u"%3d %7.3f %s\n" % (vol, onset, state['sync_now']) vol_onsets[vol - 1] = onset # are we sure about -1 here? # Count tiggers to know when to present stimuli new_ntr = n_tr + 1 new_vol = vol + 1 print 'vol:', vol state['sync_now'] = False # Detect button press from subject, record performance on probes if state['listen_for_resp']: true_lang = unicode(settings['lang'][0, block - 1] + 1) if true_lang in all_keys: print 'correct response' newrl = resp_log + u'%7.3f %1.0f correct\n' % (now, block - 1) newout = newout + (u"%3d %7.3f correct ID of %s \n" % (vol - 1, now, true_lang)) newcorrect = newcorrect + 1 state['responded'] = True else: for r in ['1', '2', '3']: if r in all_keys: print 'incorrect response', r print 'true lang: ', true_lang newrl = newrl + u'%7.3f %1.0f incorrect\n' % ( now, block - 1) newout = newout + (u"%3d %7.3f incorrect:") % (vol - 1, now) newout = newout + (u" Pressed %s instead of %s \n" % (r, true_lang)) state['responded'] = True return state, newout, newrl, vol_onsets, new_ntr, new_vol, newcorrect print 'duration: ', duration print 'vol %f of %f' % (vol, settings['volumes']) while vol < settings['volumes']: if global_clock.getTime() > duration: print 'overdue' break state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() if state['baseline_start']: # Wait a few volumes before first stim while n_tr < base1tr: state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() n_tr = 0 state['baseline_start'] = False state['playblock'] = True if state['playblock']: # Play stimulus block print 'playblock' for stimi in range(block * 3, (block * 3) + 3): print settings['stimuli'][stimi] stim = stimuli[stimi] now = global_clock.getTime() stim.play() # Log onset time of stimulus presentation stim_log += u"%7.3f %s\n" % (now, settings['stimuli'][stimi]) print u"%7.3f %s\n" % (now, settings['stimuli'][stimi]) stim_onsets[stimi] = now while n_tr < stimtr: # Wait longer while stimuli are playing to let CPU catch up core.wait(.01, hogCPUperiod=0.001) state, out, resp_log, vol_onsets, n_tr, vol, cor = \ parse_keys() n_tr = 0 # Update state variables state['playblock'] = False if settings['resp'][block]: print settings['resp'][block] state['response'] = True elif block == 2 and not settings['resp'][block]: state['baseline_end'] = True else: state['rest'] = True block += 1 if state['response']: # Ask subject to respond to probe question print 'response' # Wait for HRF while n_tr < waithrftr: # Wait a few volumes before probe state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() state['listen_for_resp'] = True # Display task question n_tr = 0 resp_text.draw() win.flip() while n_tr < responsetr: state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() n_tr = 0 fixation.draw() win.flip() # Update state variables state['response'] = False # block will equal 3 after the last block of stims have played if block >= 3: state['baseline_end'] = True else: state['rest'] = True if state['rest']: # Rest (do nothing) between blocks print 'rest' while n_tr < resttr: if global_clock.getTime() > duration: print 'overdue' break state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() n_tr = 0 state['rest'] = False state['playblock'] = True # If no response was made, note as missed if state['listen_for_resp'] and not state['responded']: true_lang = unicode(settings['lang'][0, block - 1] + 1) print 'no response' print 'true lang: ', true_lang resp_log += u'%7.3f %1.0f no response\n' % (now, block - 1) out += (u"%3d %7.3f no response:") % (vol - 1, now) out += (u" Should have pressed %s \n" % (true_lang)) state['responded'] = False state['listen_for_resp'] = False if state['baseline_end']: # Wait a few volumes at the end of the run print 'begin baseline_end' # core.wait(settings['TR']*base2tr, hogCPUperiod=0.2) print 'vol %f of %f' % (vol, settings['volumes']) # if a response was asked on the last block, don't wait as long if block == 3 and settings['resp'][2]: base2tr = 5 while n_tr < base2tr: state, out, resp_log, vol_onsets, n_tr, vol, cor = parse_keys() # In the event that we are still waiting for trs that are not # coming, get out of loop if global_clock.getTime() > duration: break n_tr = 0 state['baseline_end'] = False # If no response was made, note as missed if state['listen_for_resp'] and not state['responded']: true_lang = unicode(settings['lang'][0, block - 1] + 1) print 'no response' print 'true lang: ', true_lang resp_log += u'%7.3f %1.0f no response\n' % (now, block - 1) out += (u"%3d %7.3f no response:") % (vol - 1, now) out += (u" Should have pressed %s \n" % (true_lang)) print 'vol %f of %f' % (vol, settings['volumes']) print 'end baseline_end' break # if settings['debug']: # counter.setText(u"%d volumes\n%.3f seconds" % (vol, onset)) # counter.draw() # win.flip() out += (u"End of scan (vol 0..%d = %d of %s).\n" % (vol - 1, vol, settings['volumes'])) total_dur = global_clock.getTime() date_str = time.strftime("%b_%d_%H%M", time.localtime()) out += u"Total duration = %7.3f sec (%7.3f min)" % (total_dur, total_dur / 60) print "Total duration = %7.3f s (%7.3f min)" % (total_dur, total_dur / 60) # Save data and log files datapath = path.join(settings['subject'], 'run_data') if not path.isdir(datapath): mkdir(datapath) # Write log of key presses/volumes fname = path.join( datapath, "%s_run%s_all_keys_%s" % (settings['subject'], settings['run'], date_str)) data_file = open(fname + '.txt', 'w') data_file.write(out) data_file.close() # Write log of resp trials resp_log += u'%1.0f out of %1.0f correct\n' % (cor, n_resp) fname = path.join( datapath, "%s_run%s_resp_blocks_%s" % (settings['subject'], settings['run'], date_str)) data_file = open(fname + '.txt', 'w') data_file.write(resp_log) data_file.close() # Write log of stimulus presentations fname = path.join( datapath, "%s_run%s_stimuli_timing_%s" % (settings['subject'], settings['run'], date_str)) data_file = open(fname + '.txt', 'w') data_file.write(stim_log) data_file.close() # Save numpy arrays of onset timing for easy analysis fname = path.join( datapath, "%s_run%s_stimuli_onsets_%s" % (settings['subject'], settings['run'], date_str)) np.save(fname, stim_onsets) # data4prts = np.concatenate( # (np.matrix(np.floor(stim_onsets / settings['TR'])), # np.matrix(order))).T # savedict = {'stimuliinfo': data4prts} # fname = path.join(datapath, # "%s_run%02d_data4prts_%s" % # (settings['subject'], int(settings['run']), date_str)) # sio.savemat(fname, savedict) fname = path.join( datapath, "%s_run%s_vol_onsets_%s" % (settings['subject'], settings['run'], date_str)) np.save(fname, vol_onsets) # Save settings for this run fname = path.join( datapath, "%s_run%s_settings_%s" % (settings['subject'], settings['run'], date_str)) np.save(fname, settings) core.quit()
autoLog=None) #creation of the duration variables task_duration, baseline_duration = 20, 20 end_stimuli = 420 #20*11baseline + 20*10baseline baselines_onset = np.arange(1, end_stimuli, 40) baselines_offset = baselines_onset + 19 task_onset = np.arange(21, end_stimuli - 20, 40) task_offset = task_onset + 19 globalClock = core.Clock() #clock initialization tot_vol = launchScan(win, MR_settings, globalClock=globalClock, esc_key='escape') fixation.draw() win.flip() #while tot_vol < MR_settings['volumes']: while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key == MR_settings['sync']: #update the total volumes counter print('Current volume: ', str(tot_vol))
def main(info): # save log of subjects write_subjectlog(subjectlog, info) run_nr = int(info['run_nr']) subj = info['subject_id'] fullscr = info['fullscr'] time = core.Clock() subj_dir = pjoin(RESDIR, 'sub-' + subj) if not pexists(subj_dir): os.makedirs(subj_dir) log_fn = config['log_template'].format( subj=subj, task_name=config['task_name'], runnr=run_nr, timestamp=ptime.strftime(time_template), ) log_fn = pjoin(subj_dir, log_fn) log_responses = logging.LogFile(log_fn, level=logging.INFO) # 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], name='quit experiment gracefully') # --- LOAD STIMULI ORDER FOR THIS PARTICIPANT --- stim_json = pjoin(PWD, 'cfg', 'sub-{0}_task-localizer_4runs.json'.format(subj)) # create stimulus order if not existing if not os.path.exists(stim_json): logging.warning("Creating stimulus order for {0}".format(subj)) MAKESTIMPY = pjoin(HERE, 'make_stim_order.py') cmd = "python {cmd} --subid {subj} --output {output} " \ "--nruns 4".format(cmd=MAKESTIMPY, subj=subj, output=dirname(stim_json)) logging.warning("Running '{0}'".format(cmd)) sp.check_call(cmd.split()) with open(stim_json, 'rb') as f: stimuli = json.load(f)[str(run_nr)] # ------------------------ print "Opening screen" tbegin = time.getTime() using_scanner = info['scanner?'] # Setting up visual size = [1280, 1024] scrwin = visual.Window(size=size, allowGUI=False, units='pix', screen=1, rgb=[-1, -1, -1], fullscr=fullscr) # load clips print "Loading stimuli" loading = visual.TextStim(scrwin, text="Loading stimuli...", height=31) loading.draw() scrwin.flip() stimuli_clip = dict() for stim in stimuli: if stim['stim_type'] != 'fixation': stim_fn = stim['stim_fn'] print("Loading {0}".format(stim_fn)) stimuli_clip[stim_fn] = \ visual.MovieStim3(scrwin, pjoin(PWD, stim_fn), size=(1280, 940), name=stim_fn, noAudio=True, loop=True) scrwin.flip() cross_hair = visual.TextStim(scrwin, text='+', height=31, pos=(0, 0), color='#FFFFFF') if using_scanner: intro_msg = "Waiting for trigger..." else: intro_msg = "Press Enter to start" intro_msg = instructions + '\n' + intro_msg intro = visual.TextStim(scrwin, text=intro_msg, height=31, wrapWidth=900) # Start of experiment intro.draw() scrwin.flip() # open up serial port and wait for first trigger if using_scanner: ser_port = '/dev/ttyUSB0' ser = serial.Serial(ser_port, 115200, timeout=.0001) ser.flushInput() trigger = '' while trigger != '5': trigger = ser.read() else: from psychopy.hardware.emulator import launchScan event.waitKeys(keyList=['return']) # XXX: set up TR here MR_settings = { 'TR': 1, 'volumes': 280, 'sync': '5', 'skip': 3, 'sound': False, } vol = launchScan(scrwin, MR_settings, globalClock=time, mode='Test') class FakeSerial(object): @staticmethod def read(): k = event.getKeys(['1', '2', '5']) return k[-1] if k else '' ser = FakeSerial() # set up timer for experiment starting from first trigger timer_exp = core.Clock() trunbegin = timer_exp.getTime() # setup bids log logbids("onset\tduration\tstim_type\trepetition") # duration will be filled later template_bids = '{onset:.3f}\t{duration:.3f}\t{stim_type}\t{stim_fn}\t' \ '{repetition}' # and now we just loop through the trials for trial in stimuli: stim_type = trial['stim_type'] stim_fn = trial['stim_fn'] duration = trial['duration'] logbids(template_bids.format( onset=timer_exp.getTime(), duration=duration, stim_type=stim_type, stim_fn=stim_fn, repetition=trial.get('repetition', 0)), ) trial_counter = core.CountdownTimer(duration) if stim_type == 'fixation': cross_hair.draw() scrwin.flip() logging.flush() while trial_counter.getTime() > 0: pass else: movie = stimuli_clip[stim_fn] while trial_counter.getTime() > 0: key = ser.read() if key in ['1', '2']: logbids(template_bids.format( onset=timer_exp.getTime(), duration=0., stim_type='button_press', stim_fn=None, repetition=0) ) if movie.status != visual.FINISHED: movie.draw() scrwin.flip() else: cross_hair.draw() scrwin.flip() logging.exp("Done in {0:.2f}s".format(timer_exp.getTime())) logging.flush() scrwin.close() core.quit()
def main(): # Load config import glob import datetime from exptools.utils.config import ExpToolsConfig config = ExpToolsConfig() # Set-up monitor on the fly from psychopy import monitors my_monitor = monitors.Monitor(name=config.get('screen', 'monitor_name')) my_monitor.setSizePix(config.get('screen', 'size')) my_monitor.setWidth(config.get('screen', 'physical_screen_size')[0]) my_monitor.setDistance(config.get('screen', 'physical_screen_distance')) my_monitor.saveMon() tr = 0 initials = raw_input('Your initials/subject number: ') index_num = int( raw_input('What is the pp num? [integer or I will crash]: ')) practice = raw_input('Start with practice? [y/n, default y]: ') or 'y' start_block = raw_input('Start block? [default 1]: ') or 1 if start_block > 1: pass # ToDo: find last run data to get points from scanner = raw_input('Are you in the scanner? [y/n, default n]: ') or 'n' while not scanner in ['n', 'y']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') scanner = raw_input( 'Are you in the scanner? [y/n, default n]: ') or 'n' simulate = 'n' if scanner == 'n': simulate = raw_input( 'Do you want to simulate scan pulses? [y/n, default n]: ') or 'n' while not simulate in ['n', 'y']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') simulate = raw_input( 'Do you want to simulate scan pulses? [y/n, default n]: ' ) or 'n' if scanner == 'y' or simulate == 'y': tr = float(raw_input('What is the TR?: ')) or 0 ### start practice? if practice == 'y': sess_prac = LearningSession(subject_initials=initials, index_number=index_num, tr=tr, start_block=start_block, config=config, practice=True) sess_prac.run() sess = LearningSession(subject_initials=initials, index_number=index_num, tr=tr, start_block=start_block, config=config, practice=False) if simulate == 'y': # Run with simulated scanner (useful for behavioral pilots with eye-tracking) from psychopy.hardware.emulator import launchScan scanner_emulator = launchScan(win=sess.screen, settings={ 'TR': tr, 'volumes': 30000, 'sync': 't' }, mode='Test') sess.run()
depth=0.01) msgExpter.draw() msgExpter.draw() win.flip() event.waitKeys(keyList=["q"]) # Initialize components for Routine "trigger" # summary of run timing, for each key press: output = u'vol onset key\n' for i in range(-1 * MR_settings['skip'], 0): output += u'%d prescan skip (no sync)\n' % i counter = visual.TextStim(win, height=.05, pos=(0, 0), color=win.rgb + 0.5) output += u" 0 0.000 sync [Start of scanning run, vol 0]\n" # launch: operator selects Scan or Test (emulate); see API documentation vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=None, mode='Scan') counter.setText(u"%d volumes\n%.3f seconds" % (0, 0.0)) counter.draw() win.flip() duration = MR_settings['volumes'] * MR_settings['TR'] #msgMachine = visual.TextStim(win,text="Waiting for the scanner.", pos=(0,0),colorSpace='rgb',color=1,height=0.1,wrapWidth=1.5,depth=0.01) #msgMachine.draw() #msgMachine.draw() ## CHANGE THIS TO CHANGE HOW THE TRIGGER COMES IN #event.waitKeys(keyList=["=","equal", "5", "5%", "%", "=+"]) # adding to wait 5 TR's at the start of everything #core.wait(10) # CHECK THIS
output += u'%d prescan skip (no sync)\n' % i counter = visual.TextStim(win, height=.15, pos=(0, 0), color=win.rgb + 0.5) # set window handler for finish finish = visual.TextStim(win, height=.06, pos=(0, 0), color=win.rgb + 0.5) #instructions = visual.TextStim(win, height=.25, pos=(0, 0), color=win.rgb + 0.5) output += u" 0 0.000 sync [Start of scanning run, vol 0]\n" # launch: operator selects Scan or Test (emulate); see API docuwmentation vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=None, mode=None, esc_key='escape', instr=file_contents) #counter.setText(u"%d volumes\n%.3f seconds" % (0, 0.0)) while True: if event.getKeys(MR_settings['sync']): onset = globalClock.getTime() counter.size = 10 log_msg(u"%3d %7.3f sync\n" % (vol, onset)) vol += 1 break else: time.sleep(0.001)
def empathyp(expe): #--------------------------------------- # Set Variables #--------------------------------------- TRIALS_FILE = 'run1.csv' # run2 PAUSE = 30 # Time to pause for hypnosis reinforcement STIM_SIZE = 0.5, 0.5 BACKGROUND_COLOR = [1,1,1] stimDuration = 2.5 start_expe = 0 #--------------------------------------- # Set Keys for responses and expe flow #--------------------------------------- if expe == 'behav': is_fmri = 0 keyInd = ['space'] # for induction picture keyGo = ['up', 'none'] # response to go stimuli keyPass = ['space'] # for passing screens elif expe == 'fmri': is_fmri = 1 keyPause = ['space'] # for induction picture keyGo = ['4', 'none'] # response to go stimuli keyPass = ['1'] # for passing screens else: print('Experience type can be behav or fmri only ') #--------------------------------------- # Set up parallel port for eye tracker #--------------------------------------- #parallel.setPortAddress(0x0378) #may need to be changed #pinNumber = 3 #parallel.setData(0) #--------------------------------------- # Create timers #--------------------------------------- globalClock = core.Clock() # to track the time since experiment started respTime = core.Clock() trialClock = core.Clock() #countDown= core.CountdownTimer() # to track time remaining of each (non-slip) routine #--------------------------------------- # Store info about the experiment session #--------------------------------------- expName = 'Empathyp' expInfo = {'participant':'', 'session': ''} 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 # Experiment handler thisExp = data.ExperimentHandler(name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=False, saveWideText=False) #prevent the experiment handler to write expe data upon termination (and overwriting our files) #--------------------------------------- # Load trial files #--------------------------------------- # read from csv file trialList = data.importConditions(TRIALS_FILE, returnFieldNames=False) trials = data.TrialHandler(trialList, nReps=1, method='sequential', extraInfo=expInfo) trials.data.addDataType('respKey') trials.data.addDataType('respTime') trials.data.addDataType('stimOnset') trials.data.addDataType('scanOnset') #--------------------------------------- # Setup files for logfile saving #--------------------------------------- if not os.path.isdir('Logdata'): os.makedirs('Logdata') # if this fails (e.g. permissions) we will get error filename = 'Logdata' + os.path.sep + '%s_%s' %(expInfo['participant'], expInfo['date']) logging.setDefaultClock(globalClock) logFileExp = logging.LogFile(filename +'.log', level=logging.EXP) logging.console.setLevel(logging.INFO) # this outputs to the screen, not a file #--------------------------------------- # Setup the Window #--------------------------------------- win = visual.Window([1280,1024],color = BACKGROUND_COLOR,monitor ='testMonitor', units='height', fullscr = False, colorSpace = 'rgb') #--------------------------------------- # Setup Paths to read files #--------------------------------------- im_dir = 'Stimuli' #--------------------------------------- # Setup instructions #--------------------------------------- #instrPracticeClock = core.Clock() instruct1 = visual.TextStim(win=win, ori=0, name='instruct1', text="Consignes : \n\n Pressez le bouton 4 uniquement lorsque l'image est celle d'une main gauche. \n\n Ne pressez pas le bouton lorsque l'image est une image de main droite. Appuyer sur le 1 pour continuer.", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1.0, depth=0.0) #--------------------------------------- # Setup end message #--------------------------------------- #instrPracticeClock = core.Clock() theEnd = visual.TextStim(win=win, ori=0, name='theEnd', text="Fin de l'experience, merci de votre participation !", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) pause = visual.TextStim(win=win, ori=0, name='pause', text="Vous pouvez faire une pause", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) pause2 = visual.TextStim(win=win, ori=0, name='pause', text="Fin de la premiere partie", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) #--------------------------------------- # Setup Fixation cross and circle #--------------------------------------- fixation_cross=visual.TextStim(win=win, ori=0, name='fixation_cross', text='+', font='Arial', pos=[0, 0], height=0.06, color='black') fixation_cross.setLineWidth = 0.4 if is_fmri == 1 : #--------------------------------------- # Settings for launch scan #--------------------------------------- MR_settings={ 'TR': 2.000, # duration (sec) per volume 'volumes':5, # number of whole-brain 3D volumes/frames 'sync': '5', # character used as sync timing event; assumed to come at start of a volume 'skip': 5, # number of volumes lacking a sync pulse at start of scan (for T1 stabilization) 'sound': False # True: in test mode only } #infoDlg = gui.DlgFromDict(MR_settings, title='FMRI parameters', order=['TR', 'volumes']) #if not infoDlg.OK: core.quit() globalClock = core.Clock() mode = 'Scan' #summary of run timing for each key press: output = 'vol onset key\n' for i in range (-1*MR_settings['skip'], 0): output += '%d prescan skip (no sync)\n' % i key_code = MR_settings['sync'] counter = visual.TextStim(win, height=.05, pos=(0,0), color=win.rgb+0.5) output += "00.000 %s start of scanning run, vol 0\n" % key_code pause_during_delay = (MR_settings['TR']>.4) sync_now = False # can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time): simResponses = [(0.123, 'a'), (4.789, 'c'), (2.456, 'b')] #--------------------------------------- # launch scanner # operator selects Scan or Test #--------------------------------------- vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=simResponses) infer_missed_sync = False # best no to use it but might be useful max_slippage = 0.02 # how long to afford before treating a slow sync as missed duration = MR_settings['volumes']*MR_settings['TR'] # globalClock has been reset to 0 by launchScan() while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key != MR_settings['sync']: output += "%3d %7.3f %s\n" % (vol-1, globalClock.getTime(), str(key)) if 'escape' in allKeys: output += 'user cancel,' break #detect sync or infer it shoul have happened: if MR_settings['sync'] in allKeys: sync_now = key_code #flag onset = globalClock.getTime() if infer_missed_sync: expected_onset = vol*MR_setting['TR'] now = globalClock.getTime() if now > expected_onset + max_slippage: sync_now = '(inferred onset)' # flag onset = expected_onset if sync_now: start_expe = 1 else: start_expe = 1 if start_expe == 1: #-------------------------------------- # Show Instructions #-------------------------------------- instruct1.draw(win) win.flip() event.waitKeys(keyList= keyPass) trialStart = 0 #-------------------------------------- # START EXPERIMENT #-------------------------------------- fixation_cross.draw() win.flip() core.wait(1) win.setRecordFrameIntervals(True) # frame time tracking globalClock.reset() trialStart = 1 if trialStart == 1: t = 0 frameN=-1 nDone=0 #-------------------------------------- # Run Trials #-------------------------------------- for thisTrial in trials: # save data for the trial loop using psychopy function trials.saveAsWideText(filename + '.csv', delim=',', appendFile = False) trials.addData('scanOnset', onset) thisResp = [] # to store resp key and resp time # parallel.setData(0) # sets all pins to low #-------------------------------------- # Load stimuli image and set trials # variables #-------------------------------------- if thisTrial['Stim'] != 'pause' and thisTrial['Stim'] != 'blank': stim = visual.ImageStim(win, image = os.path.join(im_dir, thisTrial['Stim']), size=(STIM_SIZE )) stimOnset = trialClock.getTime() #-------------------------------------- # Display trials #-------------------------------------- #if thisTrial['Stim'] != 'blank' and thisTrial['Stim'] != 'pause': # case trial is stimuli while trialClock.getTime() < stimOnset + stimDuration : fixation_cross.draw() stim.draw() win.flip() # parallel.setPin(pinNumber, 1) # sets pinNumber (variable defined at the beginning) to be high thisResp= getResponse(keyGo, stimDuration ) # evaluate response elif thisTrial['Stim'] == 'blank': # case trial is blank trial fixation_cross.draw() win.flip() stimOnset = trialClock.getTime() thisResp= getResponse(keyGo, stimDuration ) # evaluate response core.wait(5) elif thisTrial['Stim'] == 'pause': # case pause for hypnosis reinforcement pause.draw() win.flip() #core.wait(PAUSE) event.waitKeys(keyList= keyPause) fixation_cross.draw() win.flip() core.wait(0.5) fixation_cross.draw() win.flip() #parallel.setData(0) core.wait(thisTrial['ITI']) nDone +=1 # if(thisRespKeys == thisTrial['corrAns']) or (thisRespKeys == [] and thisTrial['corrAns'] =='n') : # respCorr = 1 # lookup response for go and no go trials # else: respCorr = 0 #-------------------------------------- # store trial data #-------------------------------------- if len(thisResp)>0 : trials.addData('respKey',thisResp[0]) trials.addData('respTime', thisResp[1]) # trials.addData('respCorr', respCorr) trials.addData('stimOnset', stimOnset) thisExp.nextEntry() # get names of stimulus parameters if trials.trialList in ([], [None], None): params = [] else: params = trials.trialList[0].keys() if event.getKeys(['q',' escape']): win.close() core.quit() #-------------------------------------- # End Experiment #-------------------------------------- core.wait(1) win.flip() if thisTrial['Run'] == 1 or thisTrial['Run']== 3: pause.draw(win) win.flip() event.waitKeys('space') elif thisTrial['Run'] == 2: pause2.draw(win) win.flip() event.waitKeys('space') else: theEnd.draw(win) win.flip() event.waitKeys('space') if is_fmri == 1: sync_now = False output+= "end of scan (vol 0..%d= %d of %s). duration = %7.3f" %(vol-1, vol, MR_settings['volumes'], globalClock.getTime()) logging.info(output) event.waitKeys('space') win.close() core.quit()
height=ExpParameters['TextSize'], wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=0.0) resp = event.BuilderKeyResponse() # create an object of type KeyResponse # Set up the clocks TrialClock = core.Clock() CountDownClock = core.CountdownTimer() ElapsedTimeClock = core.Clock() # PRESENT THE SCREEN TO WAIT FOR THE MRI TRIGGER vol = launchScan(win, MR_settings, mode='Scan') # Cross hair ElapsedTimeClock.reset() CountDownClock.reset() CountDownClock.add(ExpParameters['IntroOffDuration']) CrossHair.draw() win.flip() while CountDownClock.getTime() > 0: theseKeys = event.getKeys() if "escape" in theseKeys: win.flip() win.close() core.quit() for BlockNumber in range(0, NBlocks, 1):
def main(): # Load config import glob import datetime from exptools.utils.config import ExpToolsConfig config = ExpToolsConfig() # Set-up monitor on the fly from psychopy import monitors my_monitor = monitors.Monitor(name=config.get('screen', 'monitor_name')) my_monitor.setSizePix(config.get('screen', 'size')) my_monitor.setWidth(config.get('screen', 'physical_screen_size')[0]) my_monitor.setDistance(config.get('screen', 'physical_screen_distance')) my_monitor.saveMon() initials = raw_input('Your initials/subject number: ') if initials == 'pilot' or initials == 'practice': session_tr = 2 else: session_tr = int(raw_input('Session TR: ')) if initials == 'practice': start_block = 1 simulate = 'y' else: start_block = int( raw_input( 'At which block do you want to start? NB: 1 is the first block! ' )) if start_block > 1: # check if previous stairs exist now = datetime.datetime.now() opfn = now.strftime("%Y-%m-%d") expected_filename = initials + '_' + str(session_tr) + '_' + opfn fns = glob.glob('./data/' + expected_filename + '_*_staircases.pkl') fns.sort() if len(fns) == 0: raw_input( 'Could not find previous stairs for this subject today... Enter any key to verify you want ' 'to make new staircases. ') elif len(fns) == 1: print('Found previous staircase file: %s' % fns[0]) elif len(fns) > 1: print( 'Found multiple staircase files. Please remove the unwanted ones, otherwise I cannot run.' ) print(fns) core.quit() scanner = '' simulate = '' while scanner not in ['y', 'n']: scanner = raw_input('Are you in the scanner (y/n)?: ') if scanner not in ['y', 'n']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') if scanner == 'n': while simulate not in ['y', 'n']: simulate = raw_input( 'Do you want to simulate scan pulses? This is useful during behavioral pilots (y/n): ' ) if simulate not in ['y', 'n']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') sess = StopSignalSession(subject_initials=initials, index_number=session_tr, tr=session_tr, start_block=start_block, config=config) if simulate == 'y': # Run with simulated scanner (useful for behavioral pilots with eye-tracking) from psychopy.hardware.emulator import launchScan scanner_emulator = launchScan(win=sess.screen, settings={ 'TR': session_tr, 'volumes': 30000, 'sync': 't' }, mode='Test') sess.run()
if not infoDlg.OK: core.quit() win = visual.Window(fullscr=False) globalClock = core.Clock() # summary of run timing, for each key press: output = u'vol onset key\n' for i in range(-1 * MR_settings['skip'], 0): output += u'%d prescan skip (no sync)\n' % i counter = visual.TextStim(win, height=.05, pos=(0, 0), color=win.rgb + 0.5) output += u" 0 0.000 sync [Start of scanning run, vol 0]\n" # launch: operator selects Scan or Test (emulate); see API docuwmentation vol = launchScan(win, MR_settings, globalClock=globalClock) counter.setText(u"%d volumes\n%.3f seconds" % (0, 0.0)) counter.draw() win.flip() duration = MR_settings['volumes'] * MR_settings['TR'] # note: globalClock has been reset to 0.0 by launchScan() while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key == MR_settings['sync']: onset = globalClock.getTime() # do your experiment code at this point if you want it sync'd to the TR # for demo just display a counter & time, updated at the start of each TR counter.setText(u"%d volumes\n%.3f seconds" % (vol, onset)) output += u"%3d %7.3f sync\n" % (vol, onset)
def empathyp(expe): #--------------------------------------- # Set Variables #--------------------------------------- TRIALS_FILE = 'run1.csv' # run2 PAUSE = 30 # Time to pause for hypnosis reinforcement STIM_SIZE = 0.5, 0.5 BACKGROUND_COLOR = [1, 1, 1] stimDuration = 2.5 start_expe = 0 #--------------------------------------- # Set Keys for responses and expe flow #--------------------------------------- if expe == 'behav': is_fmri = 0 keyInd = ['space'] # for induction picture keyGo = ['up', 'none'] # response to go stimuli keyPass = ['space'] # for passing screens elif expe == 'fmri': is_fmri = 1 keyPause = ['space'] # for induction picture keyGo = ['4', 'none'] # response to go stimuli keyPass = ['1'] # for passing screens else: print('Experience type can be behav or fmri only ') #--------------------------------------- # Set up parallel port for eye tracker #--------------------------------------- #parallel.setPortAddress(0x0378) #may need to be changed #pinNumber = 3 #parallel.setData(0) #--------------------------------------- # Create timers #--------------------------------------- globalClock = core.Clock() # to track the time since experiment started respTime = core.Clock() trialClock = core.Clock() #countDown= core.CountdownTimer() # to track time remaining of each (non-slip) routine #--------------------------------------- # Store info about the experiment session #--------------------------------------- expName = 'Empathyp' expInfo = {'participant': '', 'session': ''} 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 # Experiment handler thisExp = data.ExperimentHandler( name=expName, version='', extraInfo=expInfo, runtimeInfo=None, originPath=None, savePickle=False, saveWideText=False ) #prevent the experiment handler to write expe data upon termination (and overwriting our files) #--------------------------------------- # Load trial files #--------------------------------------- # read from csv file trialList = data.importConditions(TRIALS_FILE, returnFieldNames=False) trials = data.TrialHandler(trialList, nReps=1, method='sequential', extraInfo=expInfo) trials.data.addDataType('respKey') trials.data.addDataType('respTime') trials.data.addDataType('stimOnset') trials.data.addDataType('scanOnset') #--------------------------------------- # Setup files for logfile saving #--------------------------------------- if not os.path.isdir('Logdata'): os.makedirs( 'Logdata') # if this fails (e.g. permissions) we will get error filename = 'Logdata' + os.path.sep + '%s_%s' % (expInfo['participant'], expInfo['date']) logging.setDefaultClock(globalClock) logFileExp = logging.LogFile(filename + '.log', level=logging.EXP) logging.console.setLevel( logging.INFO) # this outputs to the screen, not a file #--------------------------------------- # Setup the Window #--------------------------------------- win = visual.Window([1280, 1024], color=BACKGROUND_COLOR, monitor='testMonitor', units='height', fullscr=False, colorSpace='rgb') #--------------------------------------- # Setup Paths to read files #--------------------------------------- im_dir = 'Stimuli' #--------------------------------------- # Setup instructions #--------------------------------------- #instrPracticeClock = core.Clock() instruct1 = visual.TextStim( win=win, ori=0, name='instruct1', text= "Consignes : \n\n Pressez le bouton 4 uniquement lorsque l'image est celle d'une main gauche. \n\n Ne pressez pas le bouton lorsque l'image est une image de main droite. Appuyer sur le 1 pour continuer.", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1.0, depth=0.0) #--------------------------------------- # Setup end message #--------------------------------------- #instrPracticeClock = core.Clock() theEnd = visual.TextStim( win=win, ori=0, name='theEnd', text="Fin de l'experience, merci de votre participation !", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) pause = visual.TextStim(win=win, ori=0, name='pause', text="Vous pouvez faire une pause", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) pause2 = visual.TextStim(win=win, ori=0, name='pause', text="Fin de la premiere partie", font='Arial', pos=[0, 0], height=0.04, wrapWidth=None, color='black', colorSpace='rgb', opacity=1, depth=0.0) #--------------------------------------- # Setup Fixation cross and circle #--------------------------------------- fixation_cross = visual.TextStim(win=win, ori=0, name='fixation_cross', text='+', font='Arial', pos=[0, 0], height=0.06, color='black') fixation_cross.setLineWidth = 0.4 if is_fmri == 1: #--------------------------------------- # Settings for launch scan #--------------------------------------- MR_settings = { 'TR': 2.000, # duration (sec) per volume 'volumes': 5, # number of whole-brain 3D volumes/frames 'sync': '5', # character used as sync timing event; assumed to come at start of a volume 'skip': 5, # number of volumes lacking a sync pulse at start of scan (for T1 stabilization) 'sound': False # True: in test mode only } #infoDlg = gui.DlgFromDict(MR_settings, title='FMRI parameters', order=['TR', 'volumes']) #if not infoDlg.OK: core.quit() globalClock = core.Clock() mode = 'Scan' #summary of run timing for each key press: output = 'vol onset key\n' for i in range(-1 * MR_settings['skip'], 0): output += '%d prescan skip (no sync)\n' % i key_code = MR_settings['sync'] counter = visual.TextStim(win, height=.05, pos=(0, 0), color=win.rgb + 0.5) output += "00.000 %s start of scanning run, vol 0\n" % key_code pause_during_delay = (MR_settings['TR'] > .4) sync_now = False # can simulate user responses, here 3 key presses in order 'a', 'b', 'c' (they get sorted by time): simResponses = [(0.123, 'a'), (4.789, 'c'), (2.456, 'b')] #--------------------------------------- # launch scanner # operator selects Scan or Test #--------------------------------------- vol = launchScan(win, MR_settings, globalClock=globalClock, simResponses=simResponses) infer_missed_sync = False # best no to use it but might be useful max_slippage = 0.02 # how long to afford before treating a slow sync as missed duration = MR_settings['volumes'] * MR_settings['TR'] # globalClock has been reset to 0 by launchScan() while globalClock.getTime() < duration: allKeys = event.getKeys() for key in allKeys: if key != MR_settings['sync']: output += "%3d %7.3f %s\n" % ( vol - 1, globalClock.getTime(), str(key)) if 'escape' in allKeys: output += 'user cancel,' break #detect sync or infer it shoul have happened: if MR_settings['sync'] in allKeys: sync_now = key_code #flag onset = globalClock.getTime() if infer_missed_sync: expected_onset = vol * MR_setting['TR'] now = globalClock.getTime() if now > expected_onset + max_slippage: sync_now = '(inferred onset)' # flag onset = expected_onset if sync_now: start_expe = 1 else: start_expe = 1 if start_expe == 1: #-------------------------------------- # Show Instructions #-------------------------------------- instruct1.draw(win) win.flip() event.waitKeys(keyList=keyPass) trialStart = 0 #-------------------------------------- # START EXPERIMENT #-------------------------------------- fixation_cross.draw() win.flip() core.wait(1) win.setRecordFrameIntervals(True) # frame time tracking globalClock.reset() trialStart = 1 if trialStart == 1: t = 0 frameN = -1 nDone = 0 #-------------------------------------- # Run Trials #-------------------------------------- for thisTrial in trials: # save data for the trial loop using psychopy function trials.saveAsWideText(filename + '.csv', delim=',', appendFile=False) trials.addData('scanOnset', onset) thisResp = [] # to store resp key and resp time # parallel.setData(0) # sets all pins to low #-------------------------------------- # Load stimuli image and set trials # variables #-------------------------------------- if thisTrial['Stim'] != 'pause' and thisTrial[ 'Stim'] != 'blank': stim = visual.ImageStim(win, image=os.path.join( im_dir, thisTrial['Stim']), size=(STIM_SIZE)) stimOnset = trialClock.getTime() #-------------------------------------- # Display trials #-------------------------------------- #if thisTrial['Stim'] != 'blank' and thisTrial['Stim'] != 'pause': # case trial is stimuli while trialClock.getTime() < stimOnset + stimDuration: fixation_cross.draw() stim.draw() win.flip() # parallel.setPin(pinNumber, 1) # sets pinNumber (variable defined at the beginning) to be high thisResp = getResponse( keyGo, stimDuration) # evaluate response elif thisTrial['Stim'] == 'blank': # case trial is blank trial fixation_cross.draw() win.flip() stimOnset = trialClock.getTime() thisResp = getResponse(keyGo, stimDuration) # evaluate response core.wait(5) elif thisTrial[ 'Stim'] == 'pause': # case pause for hypnosis reinforcement pause.draw() win.flip() #core.wait(PAUSE) event.waitKeys(keyList=keyPause) fixation_cross.draw() win.flip() core.wait(0.5) fixation_cross.draw() win.flip() #parallel.setData(0) core.wait(thisTrial['ITI']) nDone += 1 # if(thisRespKeys == thisTrial['corrAns']) or (thisRespKeys == [] and thisTrial['corrAns'] =='n') : # respCorr = 1 # lookup response for go and no go trials # else: respCorr = 0 #-------------------------------------- # store trial data #-------------------------------------- if len(thisResp) > 0: trials.addData('respKey', thisResp[0]) trials.addData('respTime', thisResp[1]) # trials.addData('respCorr', respCorr) trials.addData('stimOnset', stimOnset) thisExp.nextEntry() # get names of stimulus parameters if trials.trialList in ([], [None], None): params = [] else: params = trials.trialList[0].keys() if event.getKeys(['q', ' escape']): win.close() core.quit() #-------------------------------------- # End Experiment #-------------------------------------- core.wait(1) win.flip() if thisTrial['Run'] == 1 or thisTrial['Run'] == 3: pause.draw(win) win.flip() event.waitKeys('space') elif thisTrial['Run'] == 2: pause2.draw(win) win.flip() event.waitKeys('space') else: theEnd.draw(win) win.flip() event.waitKeys('space') if is_fmri == 1: sync_now = False output += "end of scan (vol 0..%d= %d of %s). duration = %7.3f" % ( vol - 1, vol, MR_settings['volumes'], globalClock.getTime()) logging.info(output) event.waitKeys('space') win.close() core.quit()
#"""GUI""" #subjGUI = gui.Dlg(title="Pattern Separation Task") #subjGUI.addField('Subject ID:') #subjGUI.addField('Run:') #subjGUI.show() #if subjGUI.OK: # subjInfo = subjGUI.data #else: # print 'User cancelled' # #print subjInfo[0], subjInfo[1] # #os.chdir('subjects_new') #file = glob(str(subjInfo[0])+'/'+str(subjInfo[1])+'/*pc*txt') win = visual.Window([1024, 768], allowGUI = False, waitBlanking = True, color = 'white', winType = 'pyglet', units = 'deg', monitor = 'testMonitor') win.setRecordFrameIntervals(True) fixation = visual.TextStim(win, text = '+', height = 2, color = 'black') nTTL = [] MRI_settings = {'TR': 1.500, 'volumes': 190, 'sync': '5', 'skip': 0} #scanInfo = gui.DlgFromDict(MRI_settings, title = 'fMRI parameters', order = ['TR','volumes']) vol = launchScan(win, MRI_settings) while len(nTTL) < 10: nTTL.append(event.getKeys()) print nTTL fixation.draw() win.flip()
pos=[0, 0], height=0.2, wrapWidth=None, color=u'red', colorSpace=u'rgb', opacity=1, depth=0.0) ThankYouScreen = visual.TextStim(win=win, ori=0, name='text', text=u'Merci', font=u'Arial', pos=[0, 0], height=0.2, wrapWidth=None, color=u'white', colorSpace=u'rgb', opacity=1, depth=0.0) # CALCULATED PARAMETERS flashPeriod = 1/ExpParameters['flashRate'] #seconds for one B-W cycle (ie 1/Hz) BlockDur = ExpParameters['OffDuration'] + ExpParameters['OnDuration'] # PRESENT THE SCREEN TO WAIT FOR THE MRI TRIGGER vol = launchScan(win, MR_settings, mode='Scan') #vol = launchScan(win, MR_settings, globalClock=globalClock) # Reset the clocks globalClock.reset() ElapsedTimeClock.reset() globalClock.add(ExpParameters['IntroOffDuration']) FlashClock.reset() ElapsedTime = 0 # INTRO OFF PERIOD # Prepare the screen before the timing sequence starts CrossHair.draw() win.flip() while globalClock.getTime() > 0: if event.getKeys(keyList=["escape"]):
def main(): initials = raw_input('Your initials: ') pp_nr = 0 while not 0 < pp_nr < 101: pp_nr = int(raw_input('Participant number: ')) if not 0 < pp_nr < 101: print('Number must be between 1 and 100.') scanner = '' simulate = '' while scanner not in ['y', 'n']: scanner = raw_input('Are you in the scanner (y/n)?: ') if scanner not in ['y', 'n']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') if scanner == 'n': while simulate not in ['y', 'n']: simulate = raw_input( 'Do you want to simulate scan pulses? This is useful during behavioral pilots ' 'with eye-tracking (y/n): ') if simulate not in ['y', 'n']: print('I don' 't understand that. Please enter ' 'y' ' or ' 'n' '.') # track_eyes = None # while track_eyes not in ['y', 'n']: # track_eyes = raw_input('Are you recording gaze (y/n)?: ') # if track_eyes not in ['y', 'n']: # print('I don''t understand that. Please enter ''y'' or ''n''.') track_eyes = 'y' tracker_on = track_eyes == 'y' language = '' while language not in ['en', 'nl']: language = raw_input('What language do you want to use (en/nl)?: ') if language not in ['en', 'nl']: print('I don' 't understand that. Please enter ' 'en' ' or ' 'nl' '.') mirror = False block_n = -1 while block_n not in [0, 1, 2, 3, 4, 5]: block_n = int( raw_input( "What block do you want to start? Default is 0, last block is 5. " )) if block_n not in [0, 1, 2, 3, 4, 5]: print( 'I don' 't understand that. Please enter a number between 0 and 5 (incl).' ) if block_n > 1: try: file_dir = os.path.dirname(os.path.abspath(__file__)) # Find all files with data of this pp fn = glob( os.path.join(file_dir, 'data', initials + '_' + str(pp_nr) + '*.csv')) # Ignore files with practice data, and files with data from a single block fn = [x for x in fn if 'PRACTICE' not in x and '_block_' not in x] # Select last file fn = fn[-1] # Get score start_score = pd.read_csv(fn).tail(1)['score'].values[0] check = '' while check not in ['y', 'n']: print(fn) check = raw_input( "In the file printed above, it says that the participant scored %d points " "previously, is this correct? (y/n): " % start_score) if check not in ['y', 'n']: print('Enter y or n.') if check == 'n': start_score = None while not -1 < start_score < 561: start_score = int( raw_input( "If the subject performed a limbic block in the previous blocks, " "how many points did he earn there [0-560]?: ")) if not -1 < start_score < 561: print("That is not a number between 0 and 561.") except: print('Could not automatically find previous score...') start_score = None while not -1 < start_score < 561: start_score = int( raw_input( "If the subject performed a limbic block in the previous blocks, " "how many points did he earn there [0-560]?: ")) if not -1 < start_score < 561: print("That is not a number between 0 and 561.") else: start_score = 0 if simulate == 'y': # Run with simulated scanner (useful for behavioral pilots with eye-tracking) from psychopy.hardware.emulator import launchScan sess = FlashSession(subject_initials=initials, index_number=pp_nr, scanner='y', tracker_on=tracker_on, language=language, mirror=mirror, start_block=block_n, start_score=start_score) scanner_emulator = launchScan(win=sess.screen, settings={ 'TR': TR, 'volumes': 30000, 'sync': 't' }, mode='Test') else: # Run without simulated scanner (useful for a behavioral session with eye-tracking) sess = FlashSession(subject_initials=initials, index_number=pp_nr, scanner=scanner, tracker_on=tracker_on, language=language, mirror=mirror, start_block=block_n, start_score=start_score) sess.run()
ser.flushInput() trigger = '' while trigger != '5': trigger = ser.read() else: from psychopy.hardware.emulator import launchScan event.waitKeys(keyList=['return']) # XXX: set up TR here MR_settings = { 'TR': 1, 'volumes': 280, 'sync': '5', 'skip': 3, 'sound': False, } vol = launchScan(scrwin, MR_settings, globalClock=time, mode='Test') class FakeSerial(object): @staticmethod def read(): k = event.getKeys(['1', '2', '5']) return k[-1] if k else '' ser = FakeSerial() # set up timer for experiment starting from first trigger logging.exp("EXPERIMENT STARTING") timer_exp = core.Clock() trunbegin = timer_exp.getTime() lasttrigger = trunbegin cross_hair.draw() scrwin.flip()