def triggerPeak(self, pinNumber): if self.disabled: return for k in range(20): parallel.setPin(pinNumber, 1) # trigger on for k in range(20): parallel.setData(0) # trigger off
def OpenTriggerPort(port=0x0378): """ Opens connection to triggerport **Author** : Wanja Mössing, WWU Münster | [email protected] \n *August 2018* Parameters: ---------- port: hexadecimal port number. default is 0x0378 """ parallel.setPortAddress(port) parallel.setData(0) return (parallel)
def OpenTriggerPort(port=0x0378): """ Opens connection to triggerport **Author** : Wanja Mössing, WWU Münster | [email protected] \n *August 2018* Parameters: ---------- port: hexadecimal port number. default is 0x0378 """ parallel.setPortAddress(port) parallel.setData(0) return(parallel)
def SendTrigger(triggervalue=0, duration=0.001, parallel=parallel): """Sends a specific trigger to the port **Author** : Wanja Mössing, WWU Münster | [email protected] \n *August 2018* Parameters: ---------- triggervalue: integer, 0-255 duration: float, default 0.001 (i.e., 1ms) """ parallel.setData(triggervalue) wait(duration) parallel.setData(0)
def _send_data(self, trigger): triggers = { 1: "00000001", 2: "00000010", 3: "00000011", 4: "00000100", 5: "00000101", 6: "00000110", } if CONF['satori']['port_address']: parallel.setData( int(triggers[trigger], 2) ) core.wait(0.01) parallel.setData(0)
def initializeExperiment(self): # Experiment Clocks self.expTimer = core.Clock() splash = visual.ImageStim(self.experiment.win, image='splash.png', mask=None, interpolate=False) splash.draw() self.experiment.win.flip() generateTrials.main(self.experiment.subjVariables['subjCode'], self.experiment.subjVariables["howMany"], self.experiment.subjVariables['seed']) #core.wait(2) showText(self.experiment.win, "packaging soundfiles, please wait", color='black', waitForKey=False) """This loads all the stimili and initializes the trial sequence""" self.fixSpot = visual.TextStim(self.experiment.win, text="+", height=30, color="black") self.fixSpotReady = visual.TextStim(self.experiment.win, text="+", height=50, color="red") self.fixSpotPlay = visual.TextStim(self.experiment.win, text="+", height=30, color="blue") self.pictureMatrix = loadFiles('stimuli', 'png', 'image', self.experiment.win) self.soundMatrix = loadFiles('stimuli', 'wav', fileType="sound") self.arrowChars = {'right': u"\u2192", 'left': u"\u2190"} #u"\u2192" #self.arrowChars = {'left':"<", 'right':">"} (self.trialList, self.fieldNames) = importTrials( 'trials/trialList_Flanker_' + self.experiment.subjVariables["subjCode"] + '.csv', method="sequential") (self.practTrialList, self.fieldNamesPract) = importTrials( 'trials/trialListFlankerPract.csv', method="sequential") self.locations = { 'top': [0, 275], 'bottom': [0, -275], 'left': [-275, 0], 'right': [275, 0], 'center': [0, 0] } if self.experiment.subjVariables['useParallel'] == 'yes': parallel.setData(0)
def playSentenceAndTrigger(self, win, soundFile, trigger1Time, trigger2Time, curTrial, trigDuration=.1): #triggerWord=visual.TextStim(win, text='#########') #triggerWord.draw() sDuration = soundFile.getDuration() soundFile.play() core.wait(trigger1Time) #wait till trigger time #win.flip() #send Trigger parallel.setData(122) writeToFile(self.experiment.eventTracker, [curTrial, self.expTimer.getTime(), "standard", 122]) core.wait(trigDuration) #win.flip() #wait for minimum duration needed for tigger recording parallel.setData(0) core.wait((trigger2Time - trigger1Time) - trigDuration) #triggerWord.draw() #win.flip() ########################################################THIS WILL GO AWAY WHEN NO NEED OF VISUAL PRES parallel.setData(150) writeToFile(self.experiment.eventTracker, [curTrial, self.expTimer.getTime(), "deviant", 122]) core.wait(trigDuration) #win.flip() parallel.setData(0) core.wait( (sDuration - trigger2Time) - trigDuration) #wait till end of sentence return
def initializeExperiment(self): # Experiment Clocks self.expTimer = core.Clock() splash = visual.ImageStim(self.experiment.win, image='splash.png',mask=None,interpolate=False) splash.draw() self.experiment.win.flip() core.wait(2) showText(self.experiment.win, "packaging soundfiles, please wait",color='black',waitForKey=False) """This loads all the stimili and initializes the trial sequence""" self.fixSpot = visual.TextStim(self.experiment.win,text="+",height = 30,color="black") self.fixSpotReady = visual.TextStim(self.experiment.win,text="+",height = 50,color="red") self.fixSpotPlay = visual.TextStim(self.experiment.win,text="+",height = 30,color="blue") self.pictureMatrix = loadFiles('stimuli','png','image',self.experiment.win) self.soundMatrix = loadFiles('stimuli','wav',fileType="sound") (self.trialList,self.fieldNames) = importTrials('trials/trialList_'+self.experiment.subjVariables["subjCode"]+'.csv',method="sequential") (self.practTrialList,self.fieldNamesPract) = importTrials('trials/trialListPract_'+self.experiment.subjVariables["subjCode"]+'.csv',method="sequential") self.locations = {'top':[0,275], 'bottom':[0,-275], 'left':[-275,0], 'right':[275,0], 'center':[0,0]} parallel.setData(0)
def initializeExperiment(self): # Experiment Clocks self.expTimer = core.Clock() splash = visual.ImageStim(self.experiment.win, image='splash.png',mask=None,interpolate=False) splash.draw() self.experiment.win.flip() generateTrials.main(self.experiment.subjVariables['subjCode'],self.experiment.subjVariables["howMany"],self.experiment.subjVariables['seed']) #core.wait(2) showText(self.experiment.win, "packaging soundfiles, please wait",color='black',waitForKey=False) """This loads all the stimili and initializes the trial sequence""" self.fixSpot = visual.TextStim(self.experiment.win,text="+",height = 30,color="black") self.fixSpotReady = visual.TextStim(self.experiment.win,text="+",height = 50,color="red") self.fixSpotPlay = visual.TextStim(self.experiment.win,text="+",height = 30,color="blue") self.pictureMatrix = loadFiles('stimuli','png','image',self.experiment.win) self.soundMatrix = loadFiles('stimuli','wav',fileType="sound") #self.arrowChars = {'right':u"\u2192",'left':u"\u2190"} self.arrowChars = {'right':u"\u21E8",'left':u"\u21E6"} #u"\u2192" #self.arrowChars = {'left':"<", 'right':">"} (self.trialList,self.fieldNames) = importTrials('trials/trialList_Flanker_'+self.experiment.subjVariables["subjCode"]+'.csv',method="sequential") (self.practTrialList,self.fieldNamesPract) = importTrials('trials/trialListFlankerPract.csv',method="sequential") self.locations = {'top':[0,275], 'bottom':[0,-275], 'left':[-275,0], 'right':[275,0], 'center':[0,0]} if self.experiment.subjVariables['useParallel']=='yes': parallel.setData(0)
def playSentenceAndTrigger(self,win,soundFile,trigger1Time, trigger2Time,curTrial,trigDuration=.1): #triggerWord=visual.TextStim(win, text='#########') #triggerWord.draw() sDuration=soundFile.getDuration() soundFile.play() core.wait(trigger1Time) #wait till trigger time #win.flip() #send Trigger parallel.setData(122) writeToFile(self.experiment.eventTracker,[curTrial,self.expTimer.getTime(),"standard",122]) core.wait(trigDuration) #win.flip() #wait for minimum duration needed for tigger recording parallel.setData(0) core.wait((trigger2Time-trigger1Time)-trigDuration) #triggerWord.draw() #win.flip() ########################################################THIS WILL GO AWAY WHEN NO NEED OF VISUAL PRES parallel.setData(150) writeToFile(self.experiment.eventTracker,[curTrial,self.expTimer.getTime(),"deviant",122]) core.wait(trigDuration) #win.flip() parallel.setData(0) core.wait((sDuration-trigger2Time)-trigDuration) #wait till end of sentence return
secs=0.1, stereo=True, volume=0.5, loops=0, sampleRate=44100, bits=16, hamming=False, start=0, stop=-1, name="", autoLog=False, ) parallel.setPortAddress(0xDFF8) # for stimpc-08, August 2016 try: parallel.setData(1) except RuntimeError: def setParallelData(code=0): pass print "Parallel port not working, check address?, Proceeding without..." else: parallel.setData(0) setParallelData = parallel.setData win = visual.Window(monitor="testMonitor", units="deg", fullscr=False) message1 = visual.TextStim(win, pos=[0, +3], text="Press any key to start...") message2 = visual.TextStim(win, pos=[0, -3], text="")
import time import numpy as np from numpy import random import os import math import pandas send_eegtriggers = False trigger_on_time = .01 if send_eegtriggers: # Address for the parallel port in the biosemi setup parallel.setPortAddress(0xC020) # this sends the trigger, usually initialize it at zero # then the trigger, then a wait-function for e.g. 30 ms, and zero again parallel.setData(0) time.sleep(trigger_on_time) #define amounts of everything Nstim = 2 Nresp = 2 Ntrials = 50 #Initialize data response = 0 print('initialization_ok') #make data file info = {"ppnr": 0}
def __init__(self,): if CONF['satori']['port_address']: parallel.setPortAddress(CONF['satori']['port_address']) # self.port = parallel.ParallelPort(address=CONF['satori']['port_address']) parallel.setData(0)
def RestState(): global data_frame, restTime, blockCounter, restingTrig data_frame = open(data_frame.name, "a") data_frame.write( "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % (tmpData, tmpOra, subj, age, gender, "REST", "REST", "REST", "REST", "REST", restingTrig[blockCounter - 1], blockCounter)) rest_state_intro = visual.TextStim(win, font="lucida sans typewriter", text=u"The break will now start.\n\ \nContact the experimenter.", units="pix", height=30, pos=(0, 0), color='black', alignHoriz='center', alignVert='center') rest_state_intro.draw() win.flip() event.waitKeys(keyList=['return']) rest_state_intro.setText(u"The break will start in a couple of seconds.\n\ \nRelax and stare at the 'X' at the center of the screen.") rest_state_intro.draw() win.flip() core.wait(10) event.clearEvents() rest_fix = visual.TextStim(win, text="x", units="pix", height=88, pos=(0, 5), font="lucida sans typewriter", color='black', alignHoriz='center', alignVert='center') rest_fix.draw() try: parallel.setData( restingTrig[blockCounter - 1] ) #trigger rest_state-------------------------------------------RM except: pass win.flip() clock.reset() while 1: if clock.getTime() >= restTime: core.wait(0.1) try: parallel.setData(40) except: pass core.wait(0.2) try: parallel.setData(0) except: pass break if event.getKeys(keyList=['return']): try: parallel.setData(40) except: pass core.wait(0.2) try: parallel.setData(0) except: pass break if event.getKeys(keyList=['escape']): data_frame.close() try: parallel.setData(0) except: pass core.quit()
# -*- coding: utf-8 -*- """ Test trigger latency of LabJack U3-LV (USB) vs. parallel port This will only work on a suitably ancient Win-machine (XP, 32-bit) """ from psychopy import core, logging, gui, event, visual from psychopy import parallel from labjack import u3 parallel.setPortAddress(0x378) #address for parallel port on many machines # Figure out whether to flip pins or fake it try: parallel.setData(1) except RuntimeError: def setParallelData(code=1): if code > 0: logging.exp('TRIG %d (Fake)' % code) pass else: parallel.setData(0) setParallelData = parallel.setData def trigger_parallel(code=1, trigDuration=0.010): """ Here the wait is based on time.sleep(), in which "the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps" [http://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process] This leads to variability of the trigger durations if used in threaded mode,
# -*- coding: utf-8 -*- """ Test trigger latency of LabJack U3-LV (USB) vs. parallel port This will only work on a suitably ancient Win-machine (XP, 32-bit) """ from psychopy import core, logging, gui, event, visual from psychopy import parallel from labjack import u3 import numpy as np import sys parallel.setPortAddress(0xDFF8)#address for parallel port on many machines # Figure out whether to flip pins or fake it try: parallel.setData(1) except RuntimeError: def setParallelData(code=1): if code > 0: logging.exp('TRIG %d (Fake)' % code) pass else: parallel.setData(0) setParallelData = parallel.setData if sys.platform == 'win32': import winsound def playSound(wavfile): winsound.PlaySound(wavfile, winsound.SND_FILENAME | winsound.SND_NOWAIT)
def playSentenceAndTriggerNonVisual(win, soundFile, onsetDet, waitForDetOffset, waitForNounOffset, waitForEnd, trigDet, trigOffsetNoun, eventFile, curTrial, timer): # int1=onsetDet # int2=onsetNoun-onsetDet # int3=offsetNoun-onsetNoun # int4=totalLen-int3 #triggerWord=visual.TextStim(win, text='+') #Better to implement this via a fixation cross/dot that changes colour. #triggerWord.draw() sDuration = soundFile.getDuration() parallel.setData(1) core.wait(.001) soundFile.play() parallel.setData(0) #parallel.setData(0) print 'startSent' sentStart = timer.getTime() #writeToFile(eventFile,[curTrial,timer.getTime(),"sentStart"]) core.wait(onsetDet) #wait till trigger time parallel.setData(trigDet) t1 = timer.getTime() print 'onsetDet' #writeToFile(eventFile,[curTrial,timer.getTime(),"onsetDet",trigDet]) core.wait(waitForDetOffset) parallel.setData(0) t2 = timer.getTime() print 'onsetNoun' #writeToFile(eventFile,[curTrial,timer.getTime(),"onsetNoun"]) core.wait(waitForNounOffset) parallel.setData(trigOffsetNoun) t3 = timer.getTime() print 'offsetNoun' #writeToFile(eventFile,[curTrial,timer.getTime(),"offsetNoun",trigOffsetNoun]) core.wait(waitForEnd) parallel.setData(0) t4 = timer.getTime() print 'endSentence' #writeToFile(eventFile,[curTrial,timer.getTime(),"endSentence"]) writeToFile(eventFile, [ curTrial['trialIndex'], curTrial['filename'], curTrial['relatedness'], curTrial['speaker'], curTrial['part'], curTrial['sentID'], sentStart, "sentStart" ]) writeToFile(eventFile, [ curTrial['trialIndex'], curTrial['filename'], curTrial['relatedness'], curTrial['speaker'], curTrial['part'], curTrial['sentID'], t1, "onsetDet", trigDet ]) writeToFile(eventFile, [ curTrial['trialIndex'], curTrial['filename'], curTrial['relatedness'], curTrial['speaker'], curTrial['part'], curTrial['sentID'], t2, "onsetNoun" ]) writeToFile(eventFile, [ curTrial['trialIndex'], curTrial['filename'], curTrial['relatedness'], curTrial['speaker'], curTrial['part'], curTrial['sentID'], t3, "offsetNoun", trigOffsetNoun ]) writeToFile(eventFile, [ curTrial['trialIndex'], curTrial['filename'], curTrial['relatedness'], curTrial['speaker'], curTrial['part'], curTrial['sentID'], t4, "endSentence" ]) return
nCycles = 2 parallel.setPortAddress(0x378) # address for parallel port on many machines pinNumber = 2 # choose a pin to write to (2-9). # setup the stimuli and other objects we need win = visual.Window([1280, 1024], allowGUI=False) # make a window win.flip() # present it myStim = visual.GratingStim(win, tex=None, mask=None, color='white', size=2) myClock = core.Clock() # just to keep track of time # present a stimulus for EXACTLY 20 frames and exactly 5 cycles for cycleN in range(nCycles): for frameN in range(nFramesOff): # don't draw, just refresh the window win.flip() parallel.setData(0) # sets all pins low for frameN in range(nFramesOn): myStim.draw() win.flip() # immediately *after* screen refresh set pins as desired parallel.setPin(2, 1) # sets just this pin to be high # report the mean time afterwards print('total time=%0.6f' % myClock.getTime()) print('avg frame rate=%0.3f' % win.fps()) # set pins back to low win.flip() parallel.setData(0) # sets all pins low again
# START/STOP megStim ==(START)================================= # Quick description: controls when stimuli is played and stops # if: (1) on first frame (frame 0) # (2) the stimuli has not started playing # then: (1) clear the parallel pins # (2) record start time in seconds (t) # (3) record start time in frames (frameN) # (4) play the stimuli # (5) set the parallel pins if frameN >= 0 and megStim.status == NOT_STARTED: # PARALLEL CLEAR parallel.setData(0) # sets all pins low # keep track of start time/frame for later megStim.tStart = t # underestimates by a little under one frame megStim.frameNStart = frameN # exact frame index megStim.play() # start the sound (it finishes automatically) # PARALLEL SET parallel.setData(trigg_code) # sends trigg_code from conditions file # START/STOP megStim ==(END)=================================== # UPDATE/DRAW COMPONENTS ON EACH FRAME ==(END)=================== # ENDING TASKS ==(START)=========================================
def reset(self): if self.disabled: return for k in range(20): parallel.setData(0) # trigger off
def showTestTrial(self, curTrial, trialIndex, whichPart): #s=sound.Sound(self.soundMatrix[curTrial['label']]) print str(curTrial['congruent'] ) + "_" + curTrial['direction'] + "_" + curTrial['part'] responseInfoReminder = visual.TextStim( self.experiment.win, text=self.experiment.responseInfoReminder, pos=(0, -200), height=30, color="blue") tooSlowText = visual.TextStim(self.experiment.win, text=self.experiment.tooSlow, pos=(0, -200), height=30, color="red") #target=visual.TextStim(self.experiment.win,text=curTrial['direction'],pos=(0,0),height=30,color="black") flankers = [] #flankerPos = [-60,-40, -20, 20, 40, 60] flankerPos = [-40, -20, 20, 40] if curTrial['congruent'] == 1: flankDir = curTrial['direction'] elif curTrial['congruent'] == 2 and curTrial['direction'] == 'left': flankDir = 'right' elif curTrial['congruent'] == 2 and curTrial['direction'] == 'right': flankDir = 'left' target = visual.TextStim(self.experiment.win, text=self.arrowChars[curTrial['direction']], pos=(0, 0), height=20, font='Arial', color='black') for i in range(0, len(flankerPos)): flankers.append( visual.TextStim(self.experiment.win, pos=[flankerPos[i], 0], height=20, text=self.arrowChars[flankDir], font='Arial', color='black')) response = 99 isRight = 99 rt = 99 setAndPresentStimulus(self.experiment.win, [responseInfoReminder, target, flankers]) #Parallel Port here if self.experiment.subjVariables['useParallel'] == 'yes': parallel.setData(curTrial['trigCode']) flankOnset = self.expTimer.getTime() (response, rt) = getKeyboardResponse(self.experiment.validResponses.keys()) if self.experiment.subjVariables['useParallel'] == 'yes': parallel.setData(0) flankOffset = self.expTimer.getTime() if rt >= .9: isRight = 99 if whichPart == 'practice': playAndWait(self.soundMatrix['buzz']) setAndPresentStimulus(self.experiment.win, tooSlowText) core.wait(1) else: if self.experiment.validResponses[response] == curTrial[ 'direction']: isRight = 1 if whichPart == 'practice': playAndWait(self.soundMatrix['bleep']) else: isRight = 0 if whichPart == 'practice': playAndWait(self.soundMatrix['buzz']) fieldVars = [] for curField in self.fieldNames: fieldVars.append(curTrial[curField]) [header, curLine] = createRespNew(self.experiment.optionList, self.experiment.subjVariables, self.fieldNames, fieldVars, a_expTimer=self.expTimer.getTime(), b_whichPart=curTrial['part'], c_trialIndex=trialIndex, f_response=response, g_isRight=isRight, h_rt=rt * 1000) writeToFile(self.experiment.testFile, curLine) writeToFile(self.experiment.eventTracker, [ curTrial['direction'], curTrial['congruent'], curTrial['dirCode'], curTrial['part'], curTrial['trigCode'], flankOnset ]) writeToFile(self.experiment.eventTracker, [ curTrial['direction'], curTrial['congruent'], curTrial['dirCode'], curTrial['part'], "0", flankOffset ]) #write the header with col names to the file if trialIndex == 0: print "Writing header to file..." dirtyHack = {} dirtyHack['trialNum'] = 1 writeHeader(dirtyHack, header, 'header_' + self.experiment.expName)
from numpy import random import os import math import pandas send_eegtriggers = False trigger_on_time = .04 core.rush(True) if send_eegtriggers: # Address for the parallel port in the biosemi setup parallel.setPortAddress(0xC020) # this sends the trigger, usually initialize it at zero # then the trigger, then a wait-function for e.g. 30 ms, and zero again parallel.setData(0) core.wait(trigger_on_time) #define amounts of everything Ngratings = 2 Nresp = 2 Nfeedback = 2 Nrules = 2 Nparts = 8 #per block Nblocks = 2 mean_switch = 30 std_switch = 15 #range around mean switch Nreversals = Nparts - 1 Ntrials = mean_switch * Nparts * Nblocks #make data file
def playSentenceAndTriggerNonVisual(win,soundFile,onsetDet,waitForDetOffset,waitForNounOffset,waitForEnd,trigDet, trigOffsetNoun, eventFile,curTrial,timer): # int1=onsetDet # int2=onsetNoun-onsetDet # int3=offsetNoun-onsetNoun # int4=totalLen-int3 #triggerWord=visual.TextStim(win, text='+') #Better to implement this via a fixation cross/dot that changes colour. #triggerWord.draw() sDuration=soundFile.getDuration() parallel.setData(1) core.wait(.001) soundFile.play() parallel.setData(0) #parallel.setData(0) print 'startSent' sentStart=timer.getTime() #writeToFile(eventFile,[curTrial,timer.getTime(),"sentStart"]) core.wait(onsetDet) #wait till trigger time parallel.setData(trigDet) t1=timer.getTime() print 'onsetDet' #writeToFile(eventFile,[curTrial,timer.getTime(),"onsetDet",trigDet]) core.wait(waitForDetOffset) parallel.setData(0) t2=timer.getTime() print 'onsetNoun' #writeToFile(eventFile,[curTrial,timer.getTime(),"onsetNoun"]) core.wait(waitForNounOffset) parallel.setData(trigOffsetNoun) t3=timer.getTime() print 'offsetNoun' #writeToFile(eventFile,[curTrial,timer.getTime(),"offsetNoun",trigOffsetNoun]) core.wait(waitForEnd) parallel.setData(0) t4=timer.getTime() print 'endSentence' #writeToFile(eventFile,[curTrial,timer.getTime(),"endSentence"]) writeToFile(eventFile,[curTrial['trialIndex'],curTrial['filename'],curTrial['relatedness'],curTrial['speaker'],curTrial['part'],curTrial['sentID'],sentStart,"sentStart"]) writeToFile(eventFile,[curTrial['trialIndex'],curTrial['filename'],curTrial['relatedness'],curTrial['speaker'],curTrial['part'],curTrial['sentID'],t1,"onsetDet",trigDet]) writeToFile(eventFile,[curTrial['trialIndex'],curTrial['filename'],curTrial['relatedness'],curTrial['speaker'],curTrial['part'],curTrial['sentID'],t2,"onsetNoun"]) writeToFile(eventFile,[curTrial['trialIndex'],curTrial['filename'],curTrial['relatedness'],curTrial['speaker'],curTrial['part'],curTrial['sentID'],t3,"offsetNoun",trigOffsetNoun]) writeToFile(eventFile,[curTrial['trialIndex'],curTrial['filename'],curTrial['relatedness'],curTrial['speaker'],curTrial['part'],curTrial['sentID'],t4,"endSentence"]) return
def MotorTask(stim): global resp, RT, blockCounter random.shuffle(stim) tgt = visual.TextStim(win, font="lucida sans typewriter", text="target", units="pix", height=50, pos=(0, 0), color='black', alignHoriz='center', alignVert='center') core.wait(1) #task trialcounter = 0 for i in stim: tgt.setText("%s%s%s%s" % (i[0], i[1], i[2], i[3])) tetracounter = 0 trialcounter += 1 RT4 = [] acc4 = [] win.flip() core.wait(float(random.randrange(1500, 2500, 100)) / 1000.0) #-random jitter 1500-2500 ms by 100 ms event.clearEvents() clock.reset() clock4.reset() tgt.setAutoDraw(1) while 1: win.flip() if clock.getTime() >= 2: tgt.setAutoDraw(0) resp = event.getKeys(keyList=['1', '2', '3', '4']) if resp != []: RT0 = clock4.getTime() RT = ('%.4f' % RT0).replace('.', ',') RT4.append(RT) if resp[0] == i[tetracounter]: # tgt.setAutoDraw(0) acc = 1 print "correct", RT win.flip() else: # tgt.setAutoDraw(0) acc = 0 print "error", RT win.flip() acc4.append(acc) clock4.reset() tetracounter += 1 print tetracounter event.clearEvents() if tetracounter == 4: tgt.setAutoDraw(0) win.flip() break if event.getKeys(keyList=['escape']): data_frame.close() try: parallel.setData(0) except: pass core.quit() if clock.getTime() >= maxTime: # remove if not pretesting resp = ['X'] tgt.setAutoDraw(0) if len(RT4) < 4: for el in range(4 - len(RT4)): RT4.append(0) acc4.append('miss') #print acc,RT win.flip() break for n in range(4): data_frame.write( "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % (tmpData, tmpOra, subj, age, gender, i[n], (n + 1), trialcounter, RT4[n], acc4[n], "bo", blockCounter)) win.flip()
def send_triggers(port_address=0xC020, trigger_time=.03, init=False, sending=True, value=None): """ :param port_address: The address of the parallel port Hex :param trigger_time: How long a trigger has to be sent, keeping in mind the sampling rate Integer :param init: Initialize the EEG triggers if set to True Boolean :param sending: Send a trigger if set to True, will send the integer defined in the parameter value Boolean :param value: The trigger value sent if value is set to '255', then [255 0] will appear when looking at the ActiChamp window when triggers are sent Integer :return: Depends on the use: - Initialize triggers - Send a specific integer as trigger value :example use: send_triggers(init = True, # initialize triggers sending = False) send_triggers(value = 160) # sends trigger with value '160' Note that an error will occur if both sending and init are set to True """ try: if sending and init: raise ValueError( 'You cannot both initialize the triggers, and send at the same time' ) return 1 # fail elif not sending and not init: raise ValueError( 'You did not specify what you want to do with this function') return 1 # fail else: if init: parallel.setPortAddress( port_address ) # address of the parallel port in the Biosemi setup parallel.setData(0) # set all pins to low core.wait(trigger_time) # wait for x seconds else: if value is None: raise Exception('No value for trigger defined') return 1 # fail if not isinstance(value, int): raise Exception('Trigger value should be an integer') return 1 # fail parallel.setData(value) # sets all pins high core.wait(trigger_time) # wait for x seconds parallel.setData(0) # sets all pins low return 0 # success! except RuntimeError or NameError: print('\nLOG: sending of EEG trigger failed\nAn error occured') return 2 # exception
# -*- coding: utf-8 -*- """ Test trigger latency of LabJack U3-LV (USB) vs. parallel port This will only work on a suitably ancient Win-machine (XP, 32-bit) """ from psychopy import core, logging, gui, event, visual from psychopy import parallel from labjack import u3 parallel.setPortAddress(0x378)#address for parallel port on many machines # Figure out whether to flip pins or fake it try: parallel.setData(1) except RuntimeError: def setParallelData(code=1): if code > 0: logging.exp('TRIG %d (Fake)' % code) pass else: parallel.setData(0) setParallelData = parallel.setData def trigger_parallel(code=1,trigDuration=0.010): """ Here the wait is based on time.sleep(), in which "the substantive part of the sleep operation is wrapped in a Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS block, allowing other threads to continue to execute while the current one sleeps" [http://stackoverflow.com/questions/92928/time-sleep-sleeps-thread-or-process] This leads to variability of the trigger durations if used in threaded mode, but likely give the experiment excellent timing. """ setParallelData(code)
def showTestTrial(self,curTrial, trialIndex,whichPart): #s=sound.Sound(self.soundMatrix[curTrial['label']]) print "Trial: "+str(curTrial['trialIndex'])+"_"+str(curTrial['congruent'])+"_"+curTrial['direction']+"_"+curTrial['part'] responseInfoReminder = visual.TextStim(self.experiment.win,text=self.experiment.responseInfoReminder,pos=(0,-200), height = 30,color="blue") tooSlowText = visual.TextStim(self.experiment.win,text=self.experiment.tooSlow,pos=(0,-200), height = 30,color="red") #target=visual.TextStim(self.experiment.win,text=curTrial['direction'],pos=(0,0),height=30,color="black") flankers=[] #flankerPos = [-60,-40, -20, 20, 40, 60] flankerPos = [-40, -20, 20, 40] if curTrial['congruent']==1: flankDir=curTrial['direction'] elif curTrial['congruent']==2 and curTrial['direction']=='left': flankDir='right' elif curTrial['congruent']==2 and curTrial['direction']=='right': flankDir='left' target=visual.TextStim(self.experiment.win,text=self.arrowChars[curTrial['direction']],pos=(0,0),height=30,font='Arial',color='black') for i in range(0,len(flankerPos)): flankers.append(visual.TextStim(self.experiment.win,pos=[flankerPos[i],0],height=30,text=self.arrowChars[flankDir],font='Arial',color='black')) response=99 isRight=99 rt=99 setAndPresentStimulus(self.experiment.win,[responseInfoReminder,target,flankers]) #Parallel Port here if self.experiment.subjVariables['useParallel']=='yes': parallel.setData(curTrial['trigCode']) flankOnset=self.expTimer.getTime() (response,rt) = getKeyboardResponse(self.experiment.validResponses.keys()) if self.experiment.subjVariables['useParallel']=='yes': parallel.setData(0) flankOffset=self.expTimer.getTime() if rt>=.9: isRight=99 if whichPart=='practice': playAndWait(self.soundMatrix['buzz']) setAndPresentStimulus(self.experiment.win,tooSlowText) core.wait(1) else: if self.experiment.validResponses[response]==curTrial['direction']: isRight=1 if whichPart=='practice': playAndWait(self.soundMatrix['bleep']) else: isRight=0 if whichPart=='practice': playAndWait(self.soundMatrix['buzz']) fieldVars=[] for curField in self.fieldNames: fieldVars.append(curTrial[curField]) [header, curLine] = createRespNew(self.experiment.optionList, self.experiment.subjVariables, self.fieldNames, fieldVars, a_expTimer = self.expTimer.getTime(), b_whichPart = curTrial['part'], c_trialIndex = trialIndex, f_response = response, g_isRight = isRight, h_rt = rt*1000) writeToFile(self.experiment.testFile,curLine) writeToFile(self.experiment.eventTracker,[curTrial['direction'],curTrial['congruent'],curTrial['dirCode'], curTrial['part'],curTrial['trigCode'],flankOnset]) writeToFile(self.experiment.eventTracker,[curTrial['direction'],curTrial['congruent'],curTrial['dirCode'],curTrial['part'],"0",flankOffset]) #write the header with col names to the file if trialIndex==0: print "Writing header to file..." dirtyHack = {} dirtyHack['trialNum']=1 writeHeader(dirtyHack, header,'header_'+self.experiment.expName)
win.close() core.quit() win.flip() if flag == 1: myMouse.setVisible(0) core.wait(0.5) # trial结束 core.wait(random.randrange(20, 41, step=1) / 10. - 0.5) # 开始屏 txt.text = '按【空格键】开始实验' txt.draw() win.flip() event.waitKeys(keyList=['space']) event.clearEvents() parallel.setData(0) myMouse = event.Mouse() myMouse.setVisible(0) # 开始 flag = 0 x1 = 0 y1 = 0 clk = core.Clock() clk2 = core.Clock() for ii in range(5): # 开始记录眼动数据 getEYELINK().startRecording(1, 1, 1, 1) # 如果记录的是双眼的数据则改为记录左眼; eye_used = getEYELINK().eyeAvailable() if eye_used == 1: getEYELINK().sendMessage("EYE_USED 1 RIGHT")
font="lucida sans typewriter", color='black', alignHoriz='center', alignVert='center') #create save folder if not os.path.exists("Results"): os.makedirs("Results") #Assign labels and keys if subj % 2 == 1: labels = [['Positiva', 'f', 'P'], ['Negativa', 'j', 'N']] elif subj % 2 == 0: labels = [['Negativa', 'f', 'N'], ['Positiva', 'j', 'P']] parallel.setData(0) #------------IMPORT STIMULI with open("Lists/practice_stim.csv") as g: reader = csv.reader(g, delimiter=';') practice_stim = [] counter = 0 for row in reader: if counter > 0: practice_stim.append(row) counter += 1 random.shuffle(practice_stim) with open("Lists/Trials_PP_%i.csv" % (subj)) as f: reader = csv.reader(f, delimiter=';')
nFramesOff = 30 nCycles = 2 parallel.setPortAddress(0x378) #address for parallel port on many machines pinNumber = 2 #choose a pin to write to (2-9). #setup the stimuli and other objects we need myWin = visual.Window([1280, 1024], allowGUI=False) #make a window myWin.flip() #present it myStim = visual.PatchStim(myWin, tex=None, mask=None, color='white', size=2) myClock = core.Clock() #just to keep track of time #present a stimulus for EXACTLY 20 frames and exactly 5 cycles for cycleN in range(nCycles): for frameN in range(nFramesOff): #don't draw, just refresh the window myWin.flip() parallel.setData(0) #sets all pins low for frameN in range(nFramesOn): myStim.draw() myWin.flip() #immediately *after* screen refresh set pins as desired parallel.setPin(2, 1) #sets just this pin to be high #report the mean time afterwards print 'total time=', myClock.getTime() print 'avg frame rate=', myWin.fps() #set pins back to low myWin.flip() parallel.setData(0) #sets all pins low again
def AffPriming(stim): global resp, RT, corr_practice, fix pause = visual.TextStim(win, font="lucida sans typewriter", text="Puoi fare una breve pausa.\n\ \n\ RICORDA:\n\ F = %s\t J= %s\n\ \n\ Per continuare premi F o J." % (labels[0][0], labels[1][0]), units="pix", height=30, pos=(0, 0), color='black', alignHoriz='center', alignVert='center') prime = visual.TextStim(win, text="", units="pix", height=53, font="lucida sans typewriter", pos=(0, -5), color='black', alignHoriz='center', alignVert='center') tgt = visual.TextStim(win, text="", units="pix", height=63, font="lucida sans typewriter", pos=(0, 0), color='black', alignHoriz='center', alignVert='center') label_L = visual.TextStim(win, text=labels[0][0], units="pix", height=40, pos=(-250, 250), color='black', alignHoriz='center', alignVert='center') label_R = visual.TextStim(win, text=labels[1][0], units="pix", height=40, pos=(250, 250), color='black', alignHoriz='center', alignVert='center') trialcounter = 0 corr_practice = 0 core.wait(1) for i in stim: prime.setText(i[0]) tgt.setText(i[1]) trialcounter += 1 if trialcounter % 28 == 0 and trialcounter != 324: pause.draw() win.flip() parallel.setData(2) event.waitKeys(keyList=[labels[0][1], labels[1][1]]) parallel.setData(0) core.wait(float(random.randrange(1000, 2000, 100)) / 1000) fix.setAutoDraw(1) for x in range(30): #--FIXATION (500 ms) win.flip() fix.setAutoDraw(0) for x in range(11): #--BLANK (200 ms) win.flip() win.callOnFlip(parallel.setData, 7) # <---trigger Prime prime.setAutoDraw(1) for x in range(9): #--PRIME (150 ms) win.flip() win.callOnFlip(parallel.setData, 0) prime.setAutoDraw(0) for x in range(6): #--BLANK (100 ms) -counting extra frame win.flip() event.clearEvents() frames = 0 clock.reset() tgt.setAutoDraw(1) win.callOnFlip(parallel.setData, int(i[6])) # <---trigger while 1: win.flip() frames += 1 if frames >= 18: # --TARGET (300 ms) tgt.setAutoDraw(0) if frames == 6: win.callOnFlip(parallel.setData, 0) resp = event.getKeys(keyList=['f', 'j']) if resp != []: RT0 = clock.getTime() RT = ('%.4f' % RT0).replace('.', ',') if resp[0] == 'f' and i[4] == labels[0][2] or resp[ 0] == 'j' and i[4] == labels[1][2]: parallel.setData(100) tgt.setAutoDraw(0) acc = 1 if int(i[7]) == 0: corr_practice += 1 print "correct", RT win.flip() else: parallel.setData(150) # <---trigger ERROR tgt.setAutoDraw(0) acc = 0 print "error", RT win.flip() break if clock.getTime() >= 1.8: parallel.setData(200) # <---trigger No RESP resp = ['X'] RT = 0 acc = 2 print acc, RT win.flip() break if event.getKeys(keyList=['escape']): data_frame.close() parallel.setData(0) core.quit() data_frame.write( "%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s;%s\n" % (tmpData, tmpOra, subj, age, gender, prime.text, tgt.text, i[2], i[3], i[4], i[5], trialcounter, RT, acc, labels[0][1:3], resp[0], i[6], i[7])) for frm in range(5): #counting the flip before if frm == 4: win.callOnFlip(parallel.setData, 0) win.flip() core.wait(float(random.randrange(900, 1900, 100)) / 1000) #-random jitter 800-1200 ms by 100 ms
core.rush(True) #give psychopy priority during stimulus presentation fixation.draw() win.flip() if corrected_SOA < 0: #auditory then visual #beep beep.play() fixation.draw() win.flip() fixation.draw() win.flip() parallel.setData(SOA[2]) #SOA for frameN in range(-1 * corrected_SOA - 2): fixation.draw() win.flip() if frameN == 0: parallel.setData(0) #flash flash.draw() fixation.draw() win.flip() if corrected_SOA == -2: # then for loop above won't be entered, so set all pins to 0 here
from psychopy import visual,data,event,core,gui,parallel import time import numpy as np from numpy import random import os import math import pandas send_eegtriggers = True trigger_on_time = .03 if send_eegtriggers: # Address for the parallel port in the biosemi setup parallel.setPortAddress(0xC020) # this sends the trigger, usually initialize it at zero # then the trigger, then a wait-function for e.g. 30 ms, and zero again parallel.setData(0) time.sleep(trigger_on_time) # trigger of beginning of the experiment parallel.setData(int(np.binary_repr(1, 8), 2)) time.sleep(trigger_on_time) parallel.setData(int(np.binary_repr(0, 8), 2)) #define amounts of everything Ngratings=2 Nresp=2 Nfeedback=2 Nrules=2 Nparts=10 mean_switch=40 std_switch=20 #range around mean switch