Commits

Richard Gerkin committed 1dac141

Refactoring code

Comments (0)

Files changed (16)

D2.py

-#   Discrimination Training
-#   By Ryan Brackney
-#   04/20/2013
-
-import pygame, os.path, sys, time, random
-from pygame.locals import *
-
-FPS = 15 #Number of Window updates per second
-WINDOWWIDTH = 640
-WINDOWHEIGHT = 480
-CELLSIZE = 20
-assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
-assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
-CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
-CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)
-BLACK     = (  0,   0,   0)
-BGCOLOR = BLACK
-
-
-def main():
-    global gSessClock, DISPLAYSURF, BASICFONT, SESSTARTTIME, OUTDATAFILE, SESTIMER
-    pygame.init()
-    gSessClock = pygame.time.Clock() #need to decide the benefits of using the pygame clock over the python clock (if at all)
-    pygame.display.set_caption('MouseWatering')
-    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
-    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
-    SESTIMER = time.clock() #SESTIMER will be used as the reference for all timing events
-    OUTDATAFILE = 'sample.txt' #Where the session data is written to. Need to add a function to ask for the name, location, ect later
-    
-    while True:
-        runSession()
-
-def runSession():
-
-    durationIti = 5; #ITI time in seconds
-
-    while True:
-        SESTIMER = time.clock()
-
-        if bITIstart == False:
-            endTimeIti = SESTIMER + durationIti
-            bITIstart = True
-
-        if sesTime > endTimeIti:
-            startTrial()
-
-
-
-
-
-
-def startTrial():
-    try:
-        trialNum = next(advanceTrial)
-    except:
-        trialOrder, trialNum = startNewTrialBlock()
-        
-    if trialNum > len(trialOrder):
-        trialOrder, trialNum = startNewTrialBlock()
-
-    trialType = int(trialOrder([trialNum-1]))
-    
-
-    
-    #something about the response mode here
-    
-        
-
-
-
-def startNewTrialBlock
-    trialNum = 1
-    trialOrder = determineTrialBlockOrder
-    advanceTrial(trialNum)
-    return trialOrder, trialNum
-
-
-
-def advanceTrial(curTrial):
-##    trialBlockSize = len(trialOrder)
-    while True:      
-        yield curTrial
-        curTrial += 1
-
-
-##def determineTrialType(trialOrder, curTrial, x):
-##    trialBlockSize = len(trialOrder)
-##    while True:      
-##        yield int(trialOrder([curTrial-1])
-##        curTrial += 1
-
-def determineTrialBlockOrder():
-    trialCount = 20
-    trialTypes = [1,2] * (trialCount // 2)
-    return trialOrder = random.sample(trialTypes, trialCount)
+from __init__ import *
+
+class Phase1(InternalEvent):
+    '''
+    This class handles all the contigencies for 'Phase 1' training.     
+    The class should be instantiated when Phase 1 starts, 
+    which changes a boolean to 'true' in the main timer in primary
+    which will call the 'update' method.
+    '''
+    
+    #THIS DOESN"T NEED a LICK, just head entry, LICKS ARE JUST FOT HITS OR MISSES
+    def __init__(self, maxTrials):
+        super(Phase1, self).__init__() 
+        self.initVars()
+        self.maxTrials = maxTrials
+        self.startIti(self.itiTime)        
+
+    def initVars(self):
+        self.trialCnt = 0
+        self.bFirstHeadEntry = False
+        self.misses = 0
+        self.hits = 0
+        self.itiTime = 1
+
+    def update(self):
+        if self.bITI == True:
+            #print self.ItiTimerRun.countDownTime()
+            if self.ItiTimerRun.countDownComplete():
+                self.endIti()
+                self.bFirstHeadEntry = False
+                self.bTrialStart = True
+            else:
+                pass
+                #Primary.lcdItiTime.display(self.ItiTimerRun.countDownTime)
+        if self.bTrialStart == True:
+            if self.bHeadIn == True:                          
+                self.bFirstHeadEntry = True
+            if self.bFirstHeadEntry == True:
+                if self.bHeadIn == False:
+                    self.misses += 1
+                    print(self.misses)
+                    self.endTrial()                
+                if self.bLickOn == True:
+                    self.hits += 1
+                    print(self.hits)
+                    self.reinforcement = Reinforcement(0.1)
+                    self.bReinforcement = True
+                    self.endTrial()
+                    
+        if self.bReinforcement == True:
+            self.bReinforcement = self.reinforcement.update() #returns true as long as the reinforcer is on.
+    
+        self.lickOff()
+        return self.bContinuePhase, self.hits, self.misses    
+       
+    def endTrial(self):
+        self.bTrialStart = False
+        self.bFirstHeadEntry == False
+        print 'end trial'
+        #Primary.outsideController.lightOff()
+        self.trialCnt += 1
+        if self.trialCnt >= self.maxTrials: #need to make sure this works
+            print 'end phase'
+            self.bContinuePhase = False
+        else:
+            self.startIti(self.itiTime)
+from __init__ import *
+
+class Phase3(InternalEvent):
+    '''
+    Phase 3 - designed to copy the BASIC Phase3 as close as possible. 
+    The update method should be called from the main qTimer after the class is 
+    instantiated.
+    ''' 
+    def __init__(self): #add something to allow the starting block to be differnet
+        super(Phase3, self).__init__() 
+        self.initVars()
+        self.finalValveOn()
+        #self.startIti(self.itiTime)      
+        
+    def initVars(self):
+        self.trialLengthByBlock = [0.2,0.2,0.4,0.4,0.6,0.6,0.8,1.0,1.2,1.2,]
+        self.itiTime = [0.5,1,1,2,2,3,3,4,4,5]
+        #self.trialLengthByBlock = [1.2]
+        self.blockCount = self.trialLengthByBlock.__len__()
+        self.curBlock = 1
+        #this should start short and get longer first
+        
+
+        self.curBlockHits = 0 #met the interval threshold
+        self.curBlockMisses = 0 #missed the interval threshold
+        self.curBlockAbstain = 0 #made the interval but didn't lick
+        self.hitCriterion = 20
+        self.bTrialFinished = False
+        self.binRespList = 0
+        self.bReinforcement = False
+        self.bReinforcementAvailable = False
+        self.csPlusValve = 1        
+        
+        #assert self.itiTime.__len__() == self.trialLengthByBlock.__len__()
+        
+        self.startIti(self.itiTime[self.curBlock -1])
+        
+        
+    def update(self):
+        if self.bITI == True:
+            #print self.ItiTimerRun.countDownTime()
+            if self.ItiTimerRun.countDownComplete():
+                self.endIti()            
+        if self.bTrialStart == True:
+            self.runTrial()
+               
+        if self.bReinforcement == True:
+            self.bReinforcement = self.reinforcement.update() #returns true as long as the reinforcer is on.
+    
+        self.lickOff()
+        return self.bContinuePhase
+        
+    def runTrial(self):
+            self.bTrialFinished, self.bReinforcementAvailable, self.binRespList = self.curTrialRun.update(self.bHeadIn)
+            
+            if self.bHeadIn == True:
+                if self.valveState[self.csPlusValve - 1] == 0:
+                    self.valveOn(self.csPlusValve)     
+            
+            if self.bTrialFinished == True:
+                if self.bReinforcementAvailable == True:
+                    if self.bHeadIn == False: #if they leave without licking, done
+                        self.bReinforcementAvailable = False
+                        print('abstain')
+                        self.curBlockAbstain += 1
+                        self.endTrial()
+                    if self.bLickOn == True:
+                        self.bReinforcementAvailable = False
+                        print('hit')
+                        self.curBlockHits += 1
+                        self.reinforcement = Reinforcement(0.3) 
+                        self.bReinforcement = True
+                       
+
+                        self.endTrial()
+                else:
+                    print('miss')
+                    self.curBlockMisses += 1
+                    self.endTrial()
+                    
+    
+    def endTrial(self):
+        self.bTrialStart = False
+        self.bTrialFinished = False
+        print 'end trial'
+        self.lightOff()
+        self.valveOff(self.csPlusValve)
+        self.finalValveOn()
+        self.checkBlockCount()
+
+
+        del self.curTrialRun    
+        
+        if self.bContinuePhase == True:
+            self.startIti(self.itiTime[self.curBlock -1])
+            
+    def checkBlockCount(self):
+        if self.curBlockHits >= self.hitCriterion:
+            #write to a file
+            self.curBlockHits = 0
+            self.curBlockMisses = 0
+            self.curBlockAbstain = 0
+            self.curBlock += 1
+            print 'end of block'
+        if self.curBlock > self.blockCount:
+            self.bContinuePhase = False
+            print'end of Phase'
+    
+    def endIti(self):
+        print('itiEnd')
+        self.bITI = False
+        del self.ItiTimerRun
+        self.trialStart()        
+
+    def trialStart(self):
+        self.lightOn()
+        self.finalValveOff()
+        self.bFirstHeadEntry = False
+        self.bTrialStart = True
+        trialInterval = self.trialLengthByBlock[self.curBlock - 1]
+        self.curTrialRun = HeadInIntervalCount(trialInterval)
+        print 'trial start'

Stage1.py

-# Stage 1
-# By Ryan Brackney
-
-#Todo: Make ITI interval end check function, make sure it works. Adjust wrappers
-
-import pygame, os.path, sys, time, random
-from pygame.locals import *
-
-FPS = 15 #Number of Window updates per second
-WINDOWWIDTH = 640
-WINDOWHEIGHT = 480
-CELLSIZE = 20
-assert WINDOWWIDTH % CELLSIZE == 0, "Window width must be a multiple of cell size."
-assert WINDOWHEIGHT % CELLSIZE == 0, "Window height must be a multiple of cell size."
-CELLWIDTH = int(WINDOWWIDTH / CELLSIZE)
-CELLHEIGHT = int(WINDOWHEIGHT / CELLSIZE)
-BLACK     = (  0,   0,   0)
-BGCOLOR = BLACK
-
-def main():
-    global gSessClock, DISPLAYSURF, BASICFONT, SESSTARTTIME, OUTDATAFILE, SESTIMER
-
-    pygame.init()
-    gSessClock = pygame.time.Clock() #need to decide the benefits of using the pygame clock over the python clock (if at all)
-    pygame.display.set_caption('MouseWatering')
-    DISPLAYSURF = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
-    BASICFONT = pygame.font.Font('freesansbold.ttf', 18)
-    SESTIMER = time.clock() #SESTIMER will be used as the reference for all timing events
-    OUTDATAFILE = 'sample.txt' #Where the session data is written to. Need to add a function to ask for the name, location, ect later
-    
-    while True:
-        runSession()
-
-            
-
-
-def runSession():
-    lickCounter = 0
-    lickFont = BASICFONT
-    bItiElapsed = False
-    bReinforceOnLick = False
-    requiredLickInterval = 2
-        
-    while True:
-        SESTIMER = time.clock()
-        for event in pygame.event.get(): #event handling loop
-
-##            if bViStarted == False: #Determine if a the interval for the next reward delivery has been selected yet
-##                intervalStartTime = SESTIMER
-##                reinforcerIntervalEndTime = sampleFromVI(intervalStartTime)    #determine the next interval                       
-##                bViStarted = True
-##            elif bViStarted == True and SESTIMER >= reinforcerIntervalEndTime:  #when that interval has elapsed, allow reinforcement
-##                bReinforceOnLick = True
-            if bItiElapsed == False:
-                #just record responses
-                pass
-            elif bItiElapsed == True:
-                #check to se if responses complete            
-                #reinforce, deliver 
-                pass
-            if event.type == QUIT: #this isn't working yet
-                #save data
-                terminate()
-            elif event.type == KEYDOWN: #right now, responses are simulated by pressing "r" on the keyboard. This is a placeholder for the control board response
-                if (event.key == K_r):
-                    outText = 'respTime: ' + str(SESTIMER)
-                    writeData(OUTDATAFILE, outText)
-                    lickCounter += 1
-                    lickCountText = 'licks: ' + str(lickCounter) + ' at ' + str(SESTIMER) + '   next reinforcer at ' # + str(reinforcerIntervalEndTime)
-                    print(lickCountText)                    
-                    (withinLicks, bFinishedBlock) = lickContingencyManagement(requiredLickInterval)
-                    strFinishBlock = 'Block Complete?' + str(bFinishedBlock)
-                    print(strFinishBlock)
-                    if bFinishedBlock == True:  #right now there's an error with reseting the Variable interval. Needs to be tracked down
-                        bFinishedBlock = False
-                        bViStarted = False
-                elif (event.key == K_q and event.key == K_LCTRL):  #this isn't working yet
-                    print('Response Q')
-                    terminate()
-                    
-
-
-        pygame.display.update() #updates the display
-        gSessClock.tick(FPS)
-
-
-        if SESTIMER > 100: #terminate the session after 100 seconds have passed (will change later)
-            terminate()
-        
-
-
-
-
-
-def writeData(fileName = 'default.txt', inputText = ''):
-    if os.path.isfile(fileName) == False:
-        with open(fileName, 'w', encoding = 'utf-8') as dataOutFile:
-            dataOutFile.write(inputText)
-    else:
-        with open(fileName, 'a', encoding = 'utf-8') as dataOutFile:
-            dataOutFile.write('\n')
-            dataOutFile.write(inputText)
-
-def showScreen():
-    titleFont = pygame.font.Font('freesansbold.ttf', 100)
-    titleName = titleFont.render('Mouse', True, WHITE)
-    while True:
-        DISPLAYSURF.fill(BGCOLOR)
-        pygame.display.update()
-        gSessClock.tick(FPS)      
-
-##def sampleFromVI(intervalStartTime): 
-##    intervalList = [1,5,10,15,20,25,30] #placeholder interval list
-##    intervalTime = random.sample(intervalList,1)
-##    intervalEndTime = intervalStartTime + intervalTime[0]
-##    return intervalEndTime
-
-##def contingencyVI(bReinforceOnLick):
-##    if bReinforceOnLick == True:
-##        print('water delivery!')
-##        outText = 'reinfTime: ' + str(SESTIMER)
-##        writeData(OUTDATAFILE, outText)
-##        #code for water delivery here
-
-def deliverSr(): #deliver reinforcer stimulus (sr)
-    #placeholder for controller card activation
-    print('water delivery!')
-    outText = 'reinfTime: ' + str(SESTIMER)
-    writeData(OUTDATAFILE, outText)
-
-
-def getITI(stage):
-
-    
-    #as with the BBC code, creates an ITI which advances in length as stage 1 training progresses
-    stageItiAdd = [.1, 2,5, 8] #the base ITI value depending on the stage
-    
-    addToIti = float(stageItiAdd[stage-1])
-    #need code in here for a variable ITI type depending on part of stage 1 training we're in
-    listIti1 = [1, 2, 3, 4, 5] 
-    randomlySampledTime = random.sample(listIti1,1)
-    intervalTime = randomlySampledTime[0] + addToIti
-    return intervalTime
-
-
-
-
-def lickContingencyManagement(requiredLickInterval = 2): #requiredLickInterval is the number of seconds of straight licking required
-    withinLicks = 0 #number of licks emitted while in this loop
-    binCount = int(requiredLickInterval / 2 * 10 - 1) #space the bins by 0.2 s
-    startTime = time.clock() #or whatever function we need here for clock time
-    responseInBin = [0]*(binCount + 1);
-    responseInBin[0] = 1
-    bCompletedInterval = False
-    
-    while True:
-        curTime = time.clock()
-        curBin = int((curTime - startTime) / 2 * 10)
-        if curBin > 0:
-            if responseInBin[curBin - 1] == 0:
-                print('end bins')
-                break
-        if curBin > binCount:
-            bCompletedInterval = True
-            break
-        for event in pygame.event.get():
-            if event.type == KEYDOWN and event.key == K_r:
-                #right now, responses are simulated by pressing "r" on the keyboard. This is a placeholder for the control board response
-                    responseInBin[curBin] = 1
-                    strRespInBin = 'Binned Resps: ' + str(responseInBin)
-                    print(strRespInBin)
-        
-    withinLicks = sum(responseInBin)    
-    return withinLicks, bCompletedInterval 
-    
-
-def terminate():
-    pygame.quit()
-    sys.exit()
-
-##def drawSesInfo():
-
-
-
-from qt import *
-
-############ Program Logic #################
-
-if __name__ == "__main__":
-	main()
-
-def mouseLick():
-    TurnLickLightGreen()
+# -*- coding: utf-8 -*-
+"""
+Created on Sat Jun 29 17:45:39 2013
+
+@author: Dar
+"""
+
+import time
+import os
+import outside_events
+
+# Create the python template from the design file each time the program runs.  
+# This will only take few ms and make sure the design changes are reflected immediately.  
+os.chdir(os.path.dirname(__file__))
+#os.system('pyuic4 qt/gui.ui > qt/gui.py')
+
+class InternalEvent(object):
+    '''
+    InternalEvent is the parent class of Phase1, Phase3, and other classes 
+    that control experimental continngencies. It contains generic methods for
+    experimental events.
+    
+    '''    
+    
+    def __init__(self):
+        self.bITI = False
+        self.bLickOn = False
+        self.bHeadIn = False
+        self.bReinforcement = False
+        self.reinforcerTime = 0.2
+        self.reinforcerCount = 0
+        self.bContinuePhase = True
+        self.bTrialStart = False
+        self.bTrialFinished = False
+        self.valveState = [0,0,0,0]
+        self.outsideEvent = outside_events.OutsideEvent()
+
+        
+    def startIti(self, ItiDuration):        
+        self.ItiDuration = ItiDuration
+        self.ItiTimerRun = RunInternalTimer(ItiDuration)
+        self.bITI = True
+        print('startIti')
+        #Primary.DataFile.writeData('Iti Start')
+                
+    def endIti(self):
+        print('itiEnd')
+        self.bITI = False
+        del self.ItiTimerRun        
+        #Primary.DataFile.writeData('ITI End')
+    
+    def lickOn(self):
+        self.bLickOn= True
+        print('lickOn')
+        
+        
+    def lickOff(self):
+        self.bLickOn = False
+       # print('lickoff')
+
+    def toggleHeadEntry(self):
+        if self.bHeadIn== False:
+           self.headIn()
+        else:
+            self.headOut()
+    
+    def headIn(self):
+        self.bHeadIn = True
+#        self.DataFile.writeData('H In')
+        print 'head in'       
+        
+        
+    def headOut(self):
+        self.bHeadIn = False
+#        self.DataFile.writeData('H Out')
+        print 'head out'
+        
+    def finalValveOn(self):
+        self.bFinalValve = True
+        self.outsideEvent.finalValveOn()
+   
+    def finalValveOff(self):
+        self.bFinalValve = False
+        self.outsideEvent.finalValveOff()
+        
+    def lightOn(self):
+        self.outsideEvent.lightOn()        
+
+    def lightOff(self):
+        self.outsideEvent.lightOff()
+#    
+    def valveOn(self, valveNum):
+        self.outsideEvent.valveOn(valveNum)
+        self.valveState[valveNum - 1] = 1
+
+    def valveOff(self, valveNum):
+        self.outsideEvent.valveOff(valveNum)
+        self.valveState[valveNum - 1] = 0
+
+
+class Reinforcement():
+    '''
+    Reinforcement() controls the timing of the water pump. Instantiting the
+    function sets the duration. Calling the update method will return a boolean
+    indicating whether the pump is now on, or off. Should be used in conjuction
+    with a timer, which calls the update every tic.
+    '''
+    def __init__(self, duration):
+        self.duration = duration
+        self.outsideEvent = outside_events.OutsideEvent()
+        self.reinforceOn(self.duration)
+
+    def reinforceOn(self, duration):
+        self.reinfTimerRun = RunInternalTimer(duration)
+        self.outsideEvent.reinforceOn()
+
+        
+    def update(self):
+        if self.reinfTimerRun.countDownComplete:
+            self.outsideEvent.reinforceOff()
+            return False
+        else:
+            return True
+
+
+class RunInternalTimer:
+    '''
+    RunInternalTimer is designed primarily for counting down over a specific
+    duration. Instatiating it will set the current time at the duration, and count
+    down from there. The countDownComplete method returns a boolean that indicates
+    whether the timer has elapsed, or not. This class is heavily used in the 
+    olfaction program.
+    
+    '''
+    def __init__(self, duration = 0):
+        self.startTime = time.time()    
+        self.duration = duration
+    def curTime(self):
+        return time.time()    
+    
+    def timeSince(self):
+        return self.curTime() - self.startTime
+    
+    def countDownTime(self):
+        a = self.duration
+        b = self.timeSince()
+        return a - b
+        
+    def countDownComplete(self):
+        if self.countDownTime() <= 0:
+            return True
+        else:
+            return False       
+
+
+class HeadInIntervalCount():
+    '''
+    Whenever a new trial starts in phase 3 (or similar), this counts the number 
+    of licks over an interval. The interval is divided into bins. If there is
+    a head entry noted in every bin, the update function returns that
+    reinforcement should now be made available. The update function also
+    returns whether the trial is ongoing or finished, and the current status of
+    the trial.
+    '''
+    #counts off an interval, divided into bins of a set duration.
+    # If a response doesn't occur in a bin, the interval ends
+    def __init__(self,intervalLength =1.2, binDuration = 0.2):
+        self.curBin = 0
+        self.intervalLength = intervalLength
+        self.binDuration = binDuration
+        self.binCountTotal = int(self.intervalLength / self.binDuration)
+        self.binList = [0]*self.binCountTotal
+        
+        self.bResp = False
+        self.bContinue = True
+        self.lickDuration = 0
+        self.newBin()
+        self.bReinforcementAvailable = False
+        self.headEntryCount = 0 #simply looks to see if there have been head entries before
+        self.bTrialFinished = False
+        
+       
+    def newBin(self):
+        print('newBin')
+        self.curBin += 1
+        if self.curBin > self.binCountTotal:
+            self.bReinforcementAvailable = True
+            self.endInterval()
+#        del self.binTimer
+        self.binTimer =RunInternalTimer(self.binDuration)
+
+    def endOfBin(self, curBinResp):        
+        if curBinResp > 0:
+            self.newBin()
+        else:
+            self.endInterval()
+        
+    def endInterval(self):
+        self.mouseHeadInDuration = self.binList.count(1) * self.binDuration
+        self.bTrialFinished = True
+        print('end interval')
+           
+    def update(self, bHeadIn):
+        bUpdate = self.addHeadEntryCount(bHeadIn)
+        if bUpdate:
+            if self.bTrialFinished == False:
+                if bHeadIn == True:
+                    self.binList[self.curBin - 1] = 1
+                if self.binTimer.countDownComplete():
+                    curBinResp = int(self.binList[self.curBin-1])
+                    self.endOfBin(curBinResp)
+        return self.bTrialFinished, self.bReinforcementAvailable, self.binList
+        
+    def addHeadEntryCount(self,bHeadIn):
+        if bHeadIn == True:
+            self.headEntryCount += 1
+        if self.headEntryCount > 0:
+            return True
+        else:
+            return False
+            
+
+            
+            
+            
+
+class OutputData():
+    def __init__(self, fileName = 'default',subjectName = 'mouse' ,experimentName = 'experiment',techName = 'anonymous'):
+        self.fileName = str(fileName) + '.txt'
+        startTime = time.asctime(time.localtime(time.time()))
+        
+        if os.path.isfile(self.fileName) == False:
+            self.file = open(self.fileName,'w')
+            self.file.write(startTime)
+            self.file.close()
+        else:
+            self.writeData('new Session')
+            self.writeData(startTime)
+            
+        self.writeData(subjectName)
+        self.writeData(experimentName)
+        self.writeData(techName)        
+
+    def writeData(self, inputText =''):
+        self.file = open(self.fileName, 'a')
+        self.file.write('\n')
+        self.file.write(inputText)
+        self.file.close()

Binary file modified.

Binary file modified.

Binary file modified.

Binary file modified.

+# -*- coding: utf-8 -*-
+"""
+Created on Mon Jul 01 16:59:51 2013
+
+@author: admin
+"""
+
+##Examples using ctypes to communicate with ACCES I/O products
+##Examples below are tested with USB-IIRO-16 and USB-IDIO-16 modules,
+##but can be modified to work with other USB modules using the ACCES AIOUSB driver
+##Chris Allen 2012
+
+import time
+from ctypes import *
+
+
+###############################################################################
+##This determines the device address/addresses
+def GET_DEVICES():
+    DEVICES=windll.AIOUSB.VBGetDevices()
+    print DEVICES
+    BIT=0
+    while 1 << BIT <= DEVICES:
+        STATE=(DEVICES & (1 << BIT)) >> BIT
+        if STATE==1:
+            print "Device present at address ", BIT
+        else:
+            pass
+        BIT += 1
+
+        
+###############################################################################
+##Initialise the USB IO Module and ensure all outputs are off
+def INITIALIZE():
+    global DEVICE
+    ##Set this value to our device ID- usually 0 if only one device is connected
+    DEVICE=0
+
+    resetall=c_long(65535)
+
+    DIO=windll.AIOUSB.VBDIO_WriteAll(DEVICE, pointer(resetall))
+    IO_ERROR(DIO)
+
+
+def IO_ERROR(value):
+    VALUE=value
+    if VALUE==0:
+        print "SUCCESS"
+        pass
+    else:
+        print "ERROR, DEVICE NOT FOUND. ERROR:",VALUE
+###############################################################################
+##GET THE IO STATUS FROM THE DEVICE using ReadAll
+def GET_IO_STATUS():
+
+    readback=c_long(0)
+    
+    DIO=windll.AIOUSB.VBDIO_ReadAll(DEVICE, pointer(readback))
+    IO_ERROR(DIO)
+    
+    ##OUTPUTS
+    ##NOTE: For some reason the outputs seem inverted-
+    ##for example an output returns 1 when the output is off, but 0 when the output is on
+    ##Likewise when you wish to turn an output on- 0 is on, 1 is off
+    OUT_0=(readback.value>>0)&1
+    OUT_1=(readback.value>>1)&1
+    OUT_2=(readback.value>>2)&1
+    OUT_3=(readback.value>>3)&1
+    OUT_4=(readback.value>>4)&1
+    OUT_5=(readback.value>>5)&1
+    OUT_6=(readback.value>>6)&1
+    OUT_7=(readback.value>>7)&1
+    OUT_8=(readback.value>>8)&1
+    OUT_9=(readback.value>>9)&1
+    OUT_10=(readback.value>>10)&1
+    OUT_11=(readback.value>>11)&1
+    OUT_12=(readback.value>>12)&1
+    OUT_13=(readback.value>>13)&1
+    OUT_14=(readback.value>>14)&1
+    OUT_15=(readback.value>>15)&1
+    ##print the value of out outputs
+    print "OUTPUTS: \t", OUT_0, OUT_1, OUT_2, OUT_3, OUT_4, OUT_5, OUT_6,\
+        OUT_7, OUT_8, OUT_9, OUT_10, OUT_11, OUT_12, OUT_13, OUT_14, OUT_15
+    ##INPUTS
+    IN_0=(readback.value>>16)&1
+    IN_1=(readback.value>>17)&1
+    IN_2=(readback.value>>18)&1
+    IN_3=(readback.value>>19)&1
+    IN_4=(readback.value>>20)&1
+    IN_5=(readback.value>>21)&1
+    IN_6=(readback.value>>22)&1
+    IN_7=(readback.value>>23)&1
+    IN_8=(readback.value>>24)&1
+    IN_9=(readback.value>>25)&1
+    IN_10=(readback.value>>26)&1
+    IN_11=(readback.value>>27)&1
+    IN_12=(readback.value>>28)&1
+    IN_13=(readback.value>>29)&1
+    IN_14=(readback.value>>30)&1
+    IN_15=(readback.value>>31)&1
+    ##print the value of our inputs
+    print "INPUTS: \t", IN_0, IN_1, IN_2, IN_3, IN_4, IN_5, IN_6,\
+        IN_7, IN_8 , IN_9, IN_10, IN_11, IN_12, IN_13, IN_14, IN_15
+
+
+###############################################################################
+##SETUP VARIABLES FOR OUTPUTS
+OUT0=0
+OUT1=1
+OUT2=2
+OUT3=3
+OUT4=4
+OUT5=5
+OUT6=6
+OUT7=7
+OUT8=8
+OUT9=9
+OUT10=10
+OUT11=11
+OUT12=12
+OUT13=13
+OUT14=14
+OUT15=15
+
+ON=0##Note to turn an output ON, the value must be 0
+OFF=1##Note to turn an output OFF, the value must be 1
+
+##Turns OUT_0 on for 5 seconds, then turns it off again using DIO_Write1
+def TOGGLE_OUT_0():
+    GET_IO_STATUS()
+    print "Lets turn OUT_0 ON for 5 seconds"
+    time.sleep(1)
+
+    DIO=windll.AIOUSB.VBDIO_Write1(DEVICE, OUT0, ON)
+    IO_ERROR(DIO)
+    print "Now check to see if it did indeed turn on..."
+    GET_IO_STATUS()
+    time.sleep(5)
+
+    DIO=windll.AIOUSB.VBDIO_Write1(DEVICE, OUT0, OFF)
+    IO_ERROR(DIO)
+
+    print "Now lets check the IO Status to see that OUT_0 is off..."
+    GET_IO_STATUS()
+    
+
+###############################################################################
+##Uses DIO_WriteAll to toggle all outputs on in sequence then switch them all off
+def TOGGLE_OUTPUTS_ON():
+    for i in xrange(0, 17):
+        thisbit=65535<<i
+        print "thisbit: ", thisbit
+        outputs=c_short(thisbit)
+        DIO=windll.AIOUSB.VBDIO_WriteAll(DEVICE, pointer(outputs))
+        IO_ERROR(DIO)
+        GET_IO_STATUS()
+        time.sleep(1)
+    print "Switch all outputs off again..."
+    outputs=c_short(65535)
+    DIO=windll.AIOUSB.VBDIO_WriteAll(DEVICE, pointer(outputs))
+    GET_IO_STATUS()
+
+    
+##############################################################################
+##Uses arguments to select the output and state to switch
+##for example SWITCH_OUTPUT(OUT1, ON) will turn output 1 on
+def SWITCH_OUTPUT(output, state):
+    OUT = output
+    STATUS = state
+    if STATUS==0:
+        TSTATE="ON"
+    else:
+        TSTATE="OFF"
+    print "Turning OUT_",OUT , TSTATE
+    DIO=windll.AIOUSB.VBDIO_Write1(DEVICE, OUT, STATUS)
+    IO_ERROR(DIO)
+    
+  
+

outside_events.py

+# -*- coding: utf-8 -*-
+"""
+Created on Sat Jun 29 19:53:54 2013
+
+@author: Dar
+"""
+
+class OutsideEvent: #this should eventually go into another file that's imported
+    '''
+    This is an empty wrapper for controlling the microcontroller.
+    '''
+    def lightOn(self):
+        print('light on')
+    
+    def lightOff(self):
+        print('light off')
+        
+    def reinforceOn(self):
+        print('reinforcer on')        
+
+    def reinforceOff(self):
+        print('reinforcer off')     
+
+    def valveOn(self, valveNum):
+        print('valve',str(valveNum), 'on')
+
+    def valveOff(self, valveNum):
+        print('valve',str(valveNum), 'off')
+        
+    def finalValveOn(self):
+        print('FinalValve on')
+    
+    def finalValveOff(self):
+        print('FinalValve off')
+# -*- coding: utf-8 -*-
+
+# Form implementation generated from reading ui file 'kernelUI.ui'
+#
+# Created: Mon Jun 24 15:44:10 2013
+#      by: PyQt4 UI code generator 4.9.6
+#
+# WARNING! All changes made in this file will be lost!
+
+from PyQt4 import QtCore, QtGui
+
+try:
+    _fromUtf8 = QtCore.QString.fromUtf8
+except AttributeError:
+    def _fromUtf8(s):
+        return s
+
+try:
+    _encoding = QtGui.QApplication.UnicodeUTF8
+    def _translate(context, text, disambig):
+        return QtGui.QApplication.translate(context, text, disambig, _encoding)
+except AttributeError:
+    def _translate(context, text, disambig):
+        return QtGui.QApplication.translate(context, text, disambig)
+
+class Ui_MainWindow(object):
+    def setupUi(self, MainWindow):
+        MainWindow.setObjectName(_fromUtf8("MainWindow"))
+        MainWindow.resize(800, 600)
+        self.centralwidget = QtGui.QWidget(MainWindow)
+        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
+        self.rbHeadIn = QtGui.QRadioButton(self.centralwidget)
+        self.rbHeadIn.setGeometry(QtCore.QRect(30, 90, 82, 17))
+        self.rbHeadIn.setObjectName(_fromUtf8("rbHeadIn"))
+        self.rbLick = QtGui.QRadioButton(self.centralwidget)
+        self.rbLick.setGeometry(QtCore.QRect(30, 110, 82, 17))
+        self.rbLick.setObjectName(_fromUtf8("rbLick"))
+        self.btnStartSession = QtGui.QPushButton(self.centralwidget)
+        self.btnStartSession.setGeometry(QtCore.QRect(30, 20, 75, 23))
+        self.btnStartSession.setObjectName(_fromUtf8("btnStartSession"))
+        self.btnStartIti = QtGui.QPushButton(self.centralwidget)
+        self.btnStartIti.setGeometry(QtCore.QRect(30, 50, 75, 23))
+        self.btnStartIti.setObjectName(_fromUtf8("btnStartIti"))
+        self.lbReinfCnt = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lbReinfCnt.setGeometry(QtCore.QRect(180, 20, 191, 20))
+        self.lbReinfCnt.setFrameShape(QtGui.QFrame.Panel)
+        self.lbReinfCnt.setObjectName(_fromUtf8("lbReinfCnt"))
+        self.lblHeadIn = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblHeadIn.setGeometry(QtCore.QRect(180, 50, 191, 20))
+        self.lblHeadIn.setFrameShape(QtGui.QFrame.Panel)
+        self.lblHeadIn.setObjectName(_fromUtf8("lblHeadIn"))
+        self.lblLickinTrialCnt = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblLickinTrialCnt.setGeometry(QtCore.QRect(180, 80, 191, 20))
+        self.lblLickinTrialCnt.setFrameShape(QtGui.QFrame.Panel)
+        self.lblLickinTrialCnt.setObjectName(_fromUtf8("lblLickinTrialCnt"))
+        self.lblEct1 = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblEct1.setGeometry(QtCore.QRect(10, 400, 100, 20))
+        self.lblEct1.setFrameShape(QtGui.QFrame.Panel)
+        self.lblEct1.setObjectName(_fromUtf8("lblEct1"))
+        self.lblEct2 = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblEct2.setGeometry(QtCore.QRect(10, 430, 100, 20))
+        self.lblEct2.setFrameShape(QtGui.QFrame.Panel)
+        self.lblEct2.setObjectName(_fromUtf8("lblEct2"))
+        self.lblEct3 = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblEct3.setGeometry(QtCore.QRect(10, 460, 100, 20))
+        self.lblEct3.setFrameShape(QtGui.QFrame.Panel)
+        self.lblEct3.setObjectName(_fromUtf8("lblEct3"))
+        self.lblEct4 = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblEct4.setGeometry(QtCore.QRect(10, 490, 100, 20))
+        self.lblEct4.setFrameShape(QtGui.QFrame.Panel)
+        self.lblEct4.setObjectName(_fromUtf8("lblEct4"))
+        self.lblEct5 = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblEct5.setGeometry(QtCore.QRect(10, 520, 100, 20))
+        self.lblEct5.setFrameShape(QtGui.QFrame.Panel)
+        self.lblEct5.setObjectName(_fromUtf8("lblEct5"))
+        self.lcdRespCnt = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdRespCnt.setGeometry(QtCore.QRect(20, 160, 64, 23))
+        self.lcdRespCnt.setObjectName(_fromUtf8("lcdRespCnt"))
+        self.lcdTimeCnt = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdTimeCnt.setGeometry(QtCore.QRect(730, 10, 64, 23))
+        self.lcdTimeCnt.setObjectName(_fromUtf8("lcdTimeCnt"))
+        self.lblTimeLabel = Qwt5.QwtTextLabel(self.centralwidget)
+        self.lblTimeLabel.setGeometry(QtCore.QRect(620, 10, 100, 20))
+        self.lblTimeLabel.setContextMenuPolicy(QtCore.Qt.NoContextMenu)
+        self.lblTimeLabel.setAccessibleName(_fromUtf8(""))
+        self.lblTimeLabel.setAccessibleDescription(_fromUtf8(""))
+        self.lblTimeLabel.setFrameShape(QtGui.QFrame.NoFrame)
+        self.lblTimeLabel.setObjectName(_fromUtf8("lblTimeLabel"))
+        self.lcdItiTime = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdItiTime.setGeometry(QtCore.QRect(20, 190, 64, 23))
+        self.lcdItiTime.setObjectName(_fromUtf8("lcdItiTime"))
+        MainWindow.setCentralWidget(self.centralwidget)
+        self.menubar = QtGui.QMenuBar(MainWindow)
+        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 21))
+        self.menubar.setObjectName(_fromUtf8("menubar"))
+        MainWindow.setMenuBar(self.menubar)
+        self.statusbar = QtGui.QStatusBar(MainWindow)
+        self.statusbar.setObjectName(_fromUtf8("statusbar"))
+        MainWindow.setStatusBar(self.statusbar)
+
+        self.retranslateUi(MainWindow)
+        QtCore.QMetaObject.connectSlotsByName(MainWindow)
+
+    def retranslateUi(self, MainWindow):
+        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow", None))
+        MainWindow.setStatusTip(_translate("MainWindow", "z", None))
+        MainWindow.setWhatsThis(_translate("MainWindow", "z", None))
+        self.rbHeadIn.setText(_translate("MainWindow", "Head In Sim", None))
+        self.rbLick.setText(_translate("MainWindow", "Lick Sim", None))
+        self.btnStartSession.setText(_translate("MainWindow", "Start Session", None))
+        self.btnStartIti.setText(_translate("MainWindow", "Start ITI", None))
+
+from PyQt4 import Qwt5
+
+if __name__ == "__main__":
+    import sys
+    app = QtGui.QApplication(sys.argv)
+    MainWindow = QtGui.QMainWindow()
+    ui = Ui_MainWindow()
+    ui.setupUi(MainWindow)
+    MainWindow.show()
+    sys.exit(app.exec_())
+

File contents unchanged.

qt/conversiondirections.txt

+at command prompt
+pyuic4 gui.ui > gui.py
+# -*- coding: utf-8 -*-
+
+# Form implementation generated from reading ui file 'qt/gui.ui'
+#
+# Created: Mon Jul  1 16:38:39 2013
+#      by: PyQt4 UI code generator 4.9.4
+#
+# WARNING! All changes made in this file will be lost!
+
+from PyQt4 import QtCore, QtGui
+
+try:
+    _fromUtf8 = QtCore.QString.fromUtf8
+except AttributeError:
+    _fromUtf8 = lambda s: s
+
+class Ui_MainWindow(object):
+    def setupUi(self, MainWindow):
+        MainWindow.setObjectName(_fromUtf8("MainWindow"))
+        MainWindow.resize(800, 600)
+        self.centralwidget = QtGui.QWidget(MainWindow)
+        self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
+        self.rbHeadIn = QtGui.QRadioButton(self.centralwidget)
+        self.rbHeadIn.setGeometry(QtCore.QRect(30, 90, 82, 17))
+        self.rbHeadIn.setObjectName(_fromUtf8("rbHeadIn"))
+        self.rbLick = QtGui.QRadioButton(self.centralwidget)
+        self.rbLick.setGeometry(QtCore.QRect(30, 110, 82, 17))
+        self.rbLick.setObjectName(_fromUtf8("rbLick"))
+        self.btnStartSession = QtGui.QPushButton(self.centralwidget)
+        self.btnStartSession.setGeometry(QtCore.QRect(30, 20, 75, 23))
+        self.btnStartSession.setObjectName(_fromUtf8("btnStartSession"))
+        self.btnStartIti = QtGui.QPushButton(self.centralwidget)
+        self.btnStartIti.setGeometry(QtCore.QRect(30, 50, 75, 23))
+        self.btnStartIti.setObjectName(_fromUtf8("btnStartIti"))
+        self.lcdRespCnt = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdRespCnt.setGeometry(QtCore.QRect(20, 160, 64, 23))
+        self.lcdRespCnt.setObjectName(_fromUtf8("lcdRespCnt"))
+        self.lcdTimeCnt = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdTimeCnt.setGeometry(QtCore.QRect(730, 10, 64, 23))
+        self.lcdTimeCnt.setObjectName(_fromUtf8("lcdTimeCnt"))
+        self.lcdItiTime = QtGui.QLCDNumber(self.centralwidget)
+        self.lcdItiTime.setGeometry(QtCore.QRect(20, 190, 64, 23))
+        self.lcdItiTime.setObjectName(_fromUtf8("lcdItiTime"))
+        MainWindow.setCentralWidget(self.centralwidget)
+        self.menubar = QtGui.QMenuBar(MainWindow)
+        self.menubar.setGeometry(QtCore.QRect(0, 0, 800, 22))
+        self.menubar.setObjectName(_fromUtf8("menubar"))
+        MainWindow.setMenuBar(self.menubar)
+        self.statusbar = QtGui.QStatusBar(MainWindow)
+        self.statusbar.setObjectName(_fromUtf8("statusbar"))
+        MainWindow.setStatusBar(self.statusbar)
+
+        self.retranslateUi(MainWindow)
+        QtCore.QMetaObject.connectSlotsByName(MainWindow)
+
+    def retranslateUi(self, MainWindow):
+        MainWindow.setWindowTitle(QtGui.QApplication.translate("MainWindow", "MainWindow", None, QtGui.QApplication.UnicodeUTF8))
+        MainWindow.setStatusTip(QtGui.QApplication.translate("MainWindow", "z", None, QtGui.QApplication.UnicodeUTF8))
+        MainWindow.setWhatsThis(QtGui.QApplication.translate("MainWindow", "z", None, QtGui.QApplication.UnicodeUTF8))
+        self.rbHeadIn.setText(QtGui.QApplication.translate("MainWindow", "Head In Sim", None, QtGui.QApplication.UnicodeUTF8))
+        self.rbLick.setText(QtGui.QApplication.translate("MainWindow", "Lick Sim", None, QtGui.QApplication.UnicodeUTF8))
+        self.btnStartSession.setText(QtGui.QApplication.translate("MainWindow", "Start Session", None, QtGui.QApplication.UnicodeUTF8))
+        self.btnStartIti.setText(QtGui.QApplication.translate("MainWindow", "Start ITI", None, QtGui.QApplication.UnicodeUTF8))
+
+<?xml version="1.0" encoding="UTF-8"?>
+<ui version="4.0">
+ <class>MainWindow</class>
+ <widget class="QMainWindow" name="MainWindow">
+  <property name="geometry">
+   <rect>
+    <x>0</x>
+    <y>0</y>
+    <width>800</width>
+    <height>600</height>
+   </rect>
+  </property>
+  <property name="windowTitle">
+   <string>MainWindow</string>
+  </property>
+  <property name="statusTip">
+   <string>z</string>
+  </property>
+  <property name="whatsThis">
+   <string>z</string>
+  </property>
+  <widget class="QWidget" name="centralwidget">
+   <widget class="QRadioButton" name="rbHeadIn">
+    <property name="geometry">
+     <rect>
+      <x>30</x>
+      <y>90</y>
+      <width>82</width>
+      <height>17</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Head In Sim</string>
+    </property>
+   </widget>
+   <widget class="QRadioButton" name="rbLick">
+    <property name="geometry">
+     <rect>
+      <x>30</x>
+      <y>110</y>
+      <width>82</width>
+      <height>17</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Lick Sim</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="btnStartSession">
+    <property name="geometry">
+     <rect>
+      <x>30</x>
+      <y>20</y>
+      <width>75</width>
+      <height>23</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Start Session</string>
+    </property>
+   </widget>
+   <widget class="QPushButton" name="btnStartIti">
+    <property name="geometry">
+     <rect>
+      <x>30</x>
+      <y>50</y>
+      <width>75</width>
+      <height>23</height>
+     </rect>
+    </property>
+    <property name="text">
+     <string>Start ITI</string>
+    </property>
+   </widget>
+   <widget class="QLCDNumber" name="lcdRespCnt">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>160</y>
+      <width>64</width>
+      <height>23</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QLCDNumber" name="lcdTimeCnt">
+    <property name="geometry">
+     <rect>
+      <x>730</x>
+      <y>10</y>
+      <width>64</width>
+      <height>23</height>
+     </rect>
+    </property>
+   </widget>
+   <widget class="QwtTextLabel" name="lblTimeLabel">
+    <property name="geometry">
+     <rect>
+      <x>620</x>
+      <y>10</y>
+      <width>100</width>
+      <height>20</height>
+     </rect>
+    </property>
+    <property name="contextMenuPolicy">
+     <enum>Qt::NoContextMenu</enum>
+    </property>
+    <property name="accessibleName">
+     <string/>
+    </property>
+    <property name="accessibleDescription">
+     <string/>
+    </property>
+    <property name="frameShape">
+     <enum>QFrame::NoFrame</enum>
+    </property>
+   </widget>
+   <widget class="QLCDNumber" name="lcdItiTime">
+    <property name="geometry">
+     <rect>
+      <x>20</x>
+      <y>190</y>
+      <width>64</width>
+      <height>23</height>
+     </rect>
+    </property>
+   </widget>
+  </widget>
+  <widget class="QMenuBar" name="menubar">
+   <property name="geometry">
+    <rect>
+     <x>0</x>
+     <y>0</y>
+     <width>800</width>
+     <height>22</height>
+    </rect>
+   </property>
+  </widget>
+  <widget class="QStatusBar" name="statusbar"/>
+ </widget>
+ <customwidgets>
+  <customwidget>
+   <class>QwtTextLabel</class>
+   <extends>QFrame</extends>
+   <header>qwt_text_label.h</header>
+   <container>1</container>
+  </customwidget>
+ </customwidgets>
+ <resources/>
+ <connections/>
+</ui>
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.