def run(self,*args,**kwargs): """ psychopy code is taken from an example psychopy script in the coder documentation. """ #report process affinities print "Current process affinities (experiment proc, ioHub proc):", Computer.getProcessAffinities() # create 'shortcuts' to the devices of interest for this experiment self.mouse=self.hub.devices.mouse self.kb=self.hub.devices.kb self.expRuntime=self.hub.devices.experimentRuntime self.display=self.hub.devices.display # let's print out the public method names for each device type for fun. #print "ExperimentPCkeyboard methods:",self.kb.getDeviceInterface() #print "ExperimentPCmouse methods:",self.mouse.getDeviceInterface() #print "ExperimentRuntime methods:",self.expRuntime.getDeviceInterface() #print "Display methods:",self.display.getDeviceInterface() # create fullscreen pyglet window at current resolution, as well as required resources / drawings self.createPsychoGraphicsWindow() # create stats numpy arrays, set experiment process to high priority. self.initStats() # enable high priority mode for the experiment process Computer.enableHighPriority() #draw and flip to the updated graphics state. ifi=self.drawAndFlipPsychoWindow() # START TEST LOOP >>>>>>>>>>>>>>>>>>>>>>>>>> while self.numEventRequests < self.totalEventRequestsForTest: # send an Experiment Event to the ioHub server process self.hub.sendMessageEvent("This is a test message %.3f"%self.flipTime) # check for any new events from any of the devices, and return the events list and the time it took to # request the events and receive the reply self.events,callDuration=self.checkForEvents() if self.events: # events were available self.updateStats(self.events, callDuration, ifi) #draw and flip to the updated graphics state. ifi=self.drawAndFlipPsychoWindow() # END TEST LOOP <<<<<<<<<<<<<<<<<<<<<<<<<< # close necessary files / objects, disable high priority. self.spinDownTest() # plot collected delay and retrace detection results. self.plotResults()
def runTest(): dataFile = open(os.path.join(ioHub.IO_HUB_DIRECTORY,"examples","labjacktest.dat"), mode = 'w') Computer.enableHighPriority(False) # MAX_REQUESTS is the number of packets to be read. MAX_REQUESTS = 100 #NUM_CHANNELS is the number of channels to read from NUM_CHANNELS=4 #SCAN_RATE = Hz to scan all channels at. So NUM_CHANNELS * SCAN_RATE == SAMPLING_FREQ SCAN_RATES=[500,1000,1500,2000,4000,8000,10000,12000,14000] SCAN_RATE_GAIN=1.01 SETTLING_FACTORS=[0,1] RESOLUTION_INDEX=[1,] d = u6.U6() # ## For applying the proper calibration to readings. d.getCalibrationData() # print "configuring U6 stream" # dataFile.write("scan_rate\tsettling_factor\tres_index\tread_time\tAIN_1V_E\tAIN_5V_I\tAIN_9V_E\tAIN_GND_I\n") for scan_rate in SCAN_RATES: for settling_factor in SETTLING_FACTORS: for res_index in RESOLUTION_INDEX: try: d.streamConfig( NumChannels = NUM_CHANNELS, ChannelNumbers = range(NUM_CHANNELS), ChannelOptions = [ 0, 0, 0 , 0 ], SettlingFactor = settling_factor, ResolutionIndex = res_index, ScanFrequency = scan_rate*SCAN_RATE_GAIN ) output = cStringIO.StringIO() print "started stream with scan_rate %d, settling_factor %d, res_index %d for %d packets."%(scan_rate, settling_factor,res_index,MAX_REQUESTS) missed = 0 dataCount = 0 packetCount = 0 stop=0 d.streamStart() start = default_timer() print "Start Time: ", start for r in d.streamData(): read_time=default_timer() if r is not None: # Our stop condition if dataCount >= MAX_REQUESTS: d.streamStop() print "stream stopped." break if r['errors'] != 0: print "Error: %s ; " % r['errors'], default_timer() if r['numPackets'] != d.packetsPerRequest: print "----- UNDERFLOW : %s : " % r['numPackets'], () if r['missed'] != 0: missed += r['missed'] print "+++ Missed ", r['missed'] try: for ia in xrange(len(r['AIN0'])): output.write("%d\t%d\t%d\t%.6f\t%.9f\t%.9f\t%.9f\t%.9f\n"%(scan_rate,settling_factor,res_index,read_time,r['AIN0'][ia],r['AIN1'][ia],r['AIN2'][ia],r['AIN3'][ia])) except: print 'ERROR SAVING DATA:', len(r['AIN1']) print "".join(i for i in traceback.format_exc()) #print "Average of" , len(r['AIN0']), "AIN0," , len(r['AIN1']) , "AIN1 reading(s):", len(r['AIN2']) , "AIN2 reading(s):", len(r['AIN3']) , "AIN3 reading(s):", #print sum(r['AIN0'])/len(r['AIN0']) , "," , sum(r['AIN1'])/len(r['AIN1']), "," , sum(r['AIN2'])/len(r['AIN2']), "," , sum(r['AIN3'])/len(r['AIN3']) dataCount += 1 packetCount += r['numPackets'] else: # Got no data back from our read. # This only happens if your stream isn't faster than the # the USB read timeout, ~1 sec. print "No data", default_timer() except: print "".join(i for i in traceback.format_exc()) finally: stop = default_timer() runTime = (stop-start) dataFile.write(output.getvalue()) output.close() sampleTotal = packetCount * d.streamSamplesPerPacket scanTotal = sampleTotal / NUM_CHANNELS #sampleTotal / NumChannels print "%s requests with %s packets per request with %s samples per packet = %s samples total." % ( dataCount, (float(packetCount) / dataCount), d.streamSamplesPerPacket, sampleTotal ) print "%s samples were lost due to errors." % missed sampleTotal -= missed print "Adjusted number of samples = %s" % sampleTotal print "Scan Rate : %s scans / %s seconds = %s Hz" % ( scanTotal, runTime, float(scanTotal)/runTime ) print "Sample Rate : %s samples / %s seconds = %s Hz" % ( sampleTotal, runTime, float(sampleTotal)/runTime ) print "The condition took %s seconds." % runTime print '----------------------------------------------------' d.close() dataFile.close()
""" Name: noise.py Intended Device: U6 Desc: An example program that will calculate the values that can be found in Appendix B of the U6 User's Guide. """ import ioHub from ioHub.devices import Computer import pylabjack from pylabjack import u6 # Import the u6 class import math # Need math for square root and log. default_timer = ioHub.highPrecisionTimer Computer.enableHighPriority(False) # The size of the various ranges ranges = [20, 2, 0.2, 0.02] # A nice string representation of each range strRanges = ["+/- 10", "+/- 1", "+/- 0.1", "+/- 0.01"] # Numerical versions of range that the LabJack expects vRanges = range(4) def calcNoiseAndResolution(d, resolutionIndex, voltageRange): """ Takes 128 readings and calculates noise and resolution """ # Make a list to hold our readings readings = []
def run(self, *args, **kwargs): """ The run method contains your experiment logic. It is equal to what would be in your main psychopy experiment script.py file in a standard psychopy experiment setup. That is all there is too it really. """ # PLEASE REMEMBER , THE SCREEN ORIGIN IS ALWAYS IN THE CENTER OF THE SCREEN, # REGARDLESS OF THE COORDINATE SPACE YOU ARE RUNNING IN. THIS MEANS 0,0 IS SCREEN CENTER, # -x_min, -y_min is the screen bottom left # +x_max, +y_max is the screen top right # # RIGHT NOW, ONLY PIXEL COORD SPACE IS SUPPORTED. THIS WILL BE FIXED SOON. # Let's make some short-cuts to the devices we will be using in this 'experiment'. tracker = self.hub.devices.tracker display = self.hub.devices.display kb = self.hub.devices.kb mouse = self.hub.devices.mouse tracker.runSetupProcedure() self.hub.clearEvents("all") self.hub.wait(0.050) current_gaze = [0, 0] # Create a psychopy window, full screen resolution, full screen mode, pix units, with no boarder, using the monitor # profile name 'test monitor, which is created on the fly right now by the script window = FullScreenWindow(display) # Hide the 'system mouse cursor' so we can display a cool gaussian mask for a mouse cursor. mouse.setSystemCursorVisibility(False) # Create an ordered dictionary of psychopy stimuli. An ordered dictionary is one that returns keys in the order # they are added, you you can use it to reference stim by a name or by 'zorder' psychoStim = OrderedDict() psychoStim["grating"] = visual.PatchStim(window, mask="circle", size=75, pos=[-100, 0], sf=0.075) psychoStim["fixation"] = visual.PatchStim( window, size=25, pos=[0, 0], sf=0, color=[-1, -1, -1], colorSpace="rgb" ) psychoStim["gazePosText"] = visual.TextStim( window, text=str(current_gaze), pos=[100, 0], height=48, color=[-1, -1, -1], colorSpace="rgb", alignHoriz="left", wrapWidth=300, ) psychoStim["gazePos"] = visual.GratingStim( window, tex=None, mask="gauss", pos=current_gaze, size=(50, 50), color="purple" ) [psychoStim[stimName].draw() for stimName in psychoStim] Computer.enableHighPriority(True) # self.setProcessAffinities([0,1],[2,3]) tracker.setRecordingState(True) self.hub.wait(0.050) # Clear all events from the ioHub event buffers. self.hub.clearEvents("all") # Loop until we get a keyboard event while len(kb.getEvents()) == 0: # for each loop, update the grating phase psychoStim["grating"].setPhase(0.05, "+") # advance phase by 0.05 of a cycle # and update the gaze contingent gaussian based on the current gaze location current_gaze = tracker.getLastGazePosition() current_gaze = int(current_gaze[0]), int(current_gaze[1]) psychoStim["gazePos"].setPos(current_gaze) psychoStim["gazePosText"].setText(str(current_gaze)) # this is short hand for looping through the psychopy stim list and redrawing each one # it is also efficient, may not be as user friendly as: # for stimName, stim in psychoStim.itervalues(): # stim.draw() # which does the same thing if you like and is probably just as efficent. [psychoStim[stimName].draw() for stimName in psychoStim] # flip the psychopy window buffers, so the stim changes you just made get displayed. flip_time = window.flip() # send a message to the iohub with the message text that a flip occurred and what the mouse position was. # since we know the ioHub server time the flip occurred on, we can set that directly in the event. self.hub.sendMessageEvent("Flip %s" % (str(current_gaze),), sec_time=flip_time) # a key was pressed so the loop was exited. We are clearing the event buffers to avoid an event overflow ( currently known issue) self.hub.clearEvents("all") tracker.setRecordingState(False) # wait 250 msec before ending the experiment (makes it feel less abrupt after you press the key) self.hub.wait(0.250) tracker.setConnectionState(False) # _close neccessary files / objects, 'disable high priority. window.close()
def enableHighPriority(self,disable_gc=True): Computer.enableHighPriority(disable_gc)
# the default ioHub devices: Keyboard, Mouse, and Display. # The first arg is the experiment code to use for the ioDataStore Event storage, # the second arg is the session code to give to the current session of the # experiment. Session codes must be unique for a given experiment code within an # ioDataStore hdf5 event file. import random io=quickStartHubServer("exp_code","sess_%d"%(random.randint(1,10000))) # By default, keyboard, mouse, and display devices are created if you # do not pass any config info to the ioHubConnection class above. mouse=io.devices.mouse display=io.devices.display keyboard=io.devices.keyboard # Lets switch to high priority on the psychopy process. Computer.enableHighPriority() # Create a psychopy window, full screen resolution, full screen mode, pix units, # with no boarder, using the monitor default profile name used by ioHub, # which is created on the fly right now by the script. (ioHubDefault) psychoWindow = visual.Window(display.getPixelResolution(), monitor=display.getPsychopyMonitorName(), units=display.getCoordinateType(), fullscr=True, allowGUI=False, screen=display.getIndex()) # Hide the 'system mouse cursor' so we can display a cool gaussian mask for a mouse cursor. mouse.setSystemCursorVisibility(False) # Set the mouse position to 0,0, which means the 'center' of the screen.