Exemplo n.º 1
0
    def update(self, time):
        if InputManager.getPressed("up"):
            self.selectionID -= 1
            if self.selectionID < 0:
                self.selectionID = 5
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
        elif InputManager.getPressed("down"):
            self.selectionID = (self.selectionID + 1) % 6
            AudioManager.sounds["menu"]["menuSound.ogg"].play()

        if InputManager.getPressed("enter"):
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
            AudioManager.unloadSfxSet("menu")
            if self.selectionID == 0:
                self.enter_game()
            elif self.selectionID == 1:
                self.enter_map()
            elif self.selectionID == 2:
                self.enter_highscore()
            elif self.selectionID == 3:
                self.enter_settings()
            elif self.selectionID == 4:
                self.enter_main()
            elif self.selectionID == 5:
                self.exit_game()
        if InputManager.getPressed("esc"):
            self.enter_game()
        self.time += time
        if self.time < PauseScreen.FADEINTIME:
            ratio = self.time / PauseScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
Exemplo n.º 2
0
 def update(self, time):
     if InputManager.getAction("jump") or InputManager.getAction("enter"):
         self.enter_main()
     self.time += time
     if self.time < TitleScreen.FADEINTIME and self.FADEIN:
         if not self.GGames and not self.soundPlaying:
             self.text = "Astoria"
             AudioManager.sounds["title"]["staticRustle.ogg"].play()
             self.soundPlaying = True
         ratio = self.time / TitleScreen.FADEINTIME
         value = int(ratio * 255)
         self.color = pygame.color.Color(value, value, value)
     elif self.time < TitleScreen.FADEOUTTIME and not self.FADEIN:
         ratio = 1.0 - self.time / TitleScreen.FADEOUTTIME
         value = int(ratio * 255)
         self.color = pygame.color.Color(value, value, value)
     else:
         self.time = 0
         if not self.FADEIN:
             if self.GGames:
                 self.GGames = False
                 TitleScreen.FADEINTIME = 4.0
             else:
                 self.enter_main()
         self.FADEIN = not self.FADEIN
     self.width, self.height = Globals.FONT.size(self.text)
     self.temp = Globals.FONT.render(self.text, True, self.color)
Exemplo n.º 3
0
    def __init__(self):
        self.eventManager = EventManager()
        self.running = True

        self.uid = 0

        self.game = None
        self.state = PlayerState.chooseName
        self.inputManager = InputManager()
        self.gameState = None

        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self.serverHost = Server.host
        self.serverPort = Server.port
        self.clientHost = "192.168.0.106"
        self.clientPort = 5002
        self.sock.bind((self.clientHost, self.clientPort))

        self.lock = threading.Lock()
        self.packets = Queue()
        self.networkingThread = threading.Thread(target=self.networking)
        self.networkingThread.daemon = True
        self.networkingThread.start()

        self.sendAlive = Server.checkAlive - 1 / 2
        self.nextAlive = 0

        print "Client started"
Exemplo n.º 4
0
def run_motif_scan(testFile, saliencyMapFile):
    testset = im.getSequences(testFile, 1, 1002, silent=True)
    trainset = im.getSequences(
        '/home/zzegs/workspace/dagw/toxicity_DL/data/train_data_file.dat.domain.toxin',
        1,
        1002,
        silent=True)

    config = tf.ConfigProto(allow_soft_placement=True)
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)

    saver = tf.train.import_meta_graph(
        '/home/zzegs/workspace/dagw/toxicity_DL/rr/BASF_code/parameters/seq_model/test_190705-110204'
        + '.meta')
    saver.restore(
        sess,
        tf.train.latest_checkpoint(
            '/home/zzegs/workspace/dagw/toxicity_DL/rr/BASF_code/parameters/seq_model/'
        ))
    runFromSession(0,
                   sess,
                   trainset,
                   testset,
                   useRef=True,
                   outF=saliencyMapFile)

    fastaFile, posSaliencyFile = selectPosSeqFromFile(saliencyMapFile)
    visualizeSaliencyMapFile(posSaliencyFile, 'seq_temp')
    sess.close()
Exemplo n.º 5
0
    def update(self, time):
        if InputManager.getPressed("up"):
            self.selectionID -= 1
            if self.selectionID < 0:
                self.selectionID = 3
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
        elif InputManager.getPressed("down"):
            self.selectionID = (self.selectionID + 1) % 4
            AudioManager.sounds["menu"]["menuSound.ogg"].play()

        if InputManager.getPressed("enter"):
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
            AudioManager.unloadSfxSet("menu")
            if self.selectionID == 0:
                self.enter_game()
            elif self.selectionID == 1:
                Globals.STATE = SkillScreen.SkillScreen()
            elif self.selectionID == 2:
                Globals.STATE = MapScreen.MapScreen()
            elif self.selectionID == 3:
                self.enter_main()
        self.time += time
        if self.time < WinScreen.FADEINTIME:
            ratio = self.time / WinScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
Exemplo n.º 6
0
    def update(self, time):
        if InputManager.getPressed("up"):
            self.selectionID -= 1
            if self.selectionID < 0:
                self.selectionID = 2
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
        elif InputManager.getPressed("down"):
            self.selectionID = (self.selectionID + 1) % 3
            AudioManager.sounds["menu"]["menuSound.ogg"].play()

        if InputManager.getPressed("enter"):
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
            AudioManager.unloadSfxSet("menu")
            if self.selectionID == 0:
                self.enter_csetup()
            elif self.selectionID == 1:
                Globals.LASTSCREENSETTING = True
                Globals.STATE = ControlScreen.ControlScreen()
            elif self.selectionID == 2:
                self.enter_back()
        if InputManager.getPressed("esc"):
            self.enter_back()
        self.time += time
        if self.time < SettingScreen.FADEINTIME:
            ratio = self.time / SettingScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
Exemplo n.º 7
0
    def __init__(self, uid, pos, name):
        # Unique ID associated with character
        self.uid = uid
        self.pos = pos
        self.name = name

        self.player = None
        self.game = None

        self.health = maxHealth

        self.vel = [0.0, 0.0]
        # Velocity delta
        self.velDel = [1.5, 1.5]
        self.velMax = [10, 10]
        # How much the velocity retains per frame
        self.velRed = [0.8, 0.8]

        self.width = width
        self.height = height
        self.setRect()

        self.mainAbility = Ability(0.5)
        self.reallySmallNumber = 0.0001
        self.inputManager = InputManager()
Exemplo n.º 8
0
    def __init__(self):
        application = self

        #global initialization
        pyxel.init(255, 255, caption="Nearym Quest", scale=3)
        self.debugOverlay = False
        self.camera = Camera()
        self.streamingArea = Box()
        self.streamingArea.size = Vector2f(512, 512)
        self.streamingArea.center = Vector2f(0, 0)
        self.renderer = Renderer()
        self.physics = Physics()
        random.seed(0)

        # Event Manager
        self.inputManager = InputManager()
        self.inputManager.addInput(
            Input(InputType.BUTTON, InputNotify.PRESSED, [pyxel.KEY_F1],
                  'debug'))

        # world and player
        self.LoadMap()

        self.draw_count = 0

        # has to be completely at the end of init
        pyxel.run(self.update, self.draw)
Exemplo n.º 9
0
def run(testParameters):
    trainDatasetFile, validDatasetFile, testDatasetFile, hierarchy_file = testParameters.datafiles
    print(trainDatasetFile, validDatasetFile, testDatasetFile)
    ### Read in training, validation and test sets ##
    #train_set,valid_set = im.getSequences(trainDatasetFile,testParameters.ngramsize,testParameters.maxLength,
    #                                      testPartDiv=testParameters.testPartDiv,sets_returned = 2)
    train_set = im.getSequences(trainDatasetFile, testParameters.ngramsize,
                                testParameters.maxLength)
    valid_set = im.getSequences(validDatasetFile, testParameters.ngramsize,
                                testParameters.maxLength)
    test_set = im.getSequences_without_shuffle(testDatasetFile,
                                               testParameters.ngramsize,
                                               testParameters.maxLength)

    ### Build the topology as described in the input file ###
    nn = buildNetworkTopology(type=testParameters.type,
                              maxLength=testParameters.maxLength,
                              ngramsize=testParameters.ngramsize,
                              filterSizes=testParameters.filterSizes,
                              filterAmounts=testParameters.filterAmounts,
                              maxPoolSizes=testParameters.maxPoolSizes,
                              sizeOfFCLayers=testParameters.sizeOfFCLayers,
                              n_of_outputs=train_set.getClassCounts(),
                              dynMaxPoolSize=testParameters.dynMaxPoolSize,
                              term_indices_file=hierarchy_file,
                              ppi_vectors=testParameters.ppi_vectors,
                              hierarchy=testParameters.hierarchy,
                              embeddingDepth=testParameters.embeddingDepth,
                              embeddingType=testParameters.embeddingType,
                              GRU_state_size=testParameters.GRUSize)

    ### Trains the network (and at the end, stores predictions on the test set) ###
    tp = TrainingProcedure(
        network_object=nn,
        train_dataset=train_set,
        valid_dataset=valid_set,
        test_dataset=test_set,
        batch_size=testParameters.batchsize,
        start_learning_rate=testParameters.start_learning_rate,
        validationFunction=testParameters.validationFunction,
        update=testParameters.update,
        dropoutRate=testParameters.dropout,
        l1reg=testParameters.l1reg,
        lossFunction=testParameters.lossFunction)

    sess, auROC, auPRC, Fmax, mcc = tp.trainNetwork(testParameters.epochs)

    ### if called from the SingleTermWorkflow.py, get the full training set (train + valid) and test_set, for
    ### usage with integrated gradients (the full train set is used for the baseline there)
    import sys
    if sys.argv[0] == 'ToxDL.py':
        full_train_set = im.getSequences(trainDatasetFile,
                                         testParameters.ngramsize,
                                         testParameters.maxLength)
        test_set = im.getSequences(
            testDatasetFile, testParameters.ngramsize, testParameters.maxLength
        )  # this should not be here, but trying if this fixes a bug
        return sess, full_train_set, test_set, auROC, auPRC, Fmax, mcc
    else:
        sess.close()
Exemplo n.º 10
0
 def update(self, time):
     if InputManager.getPressed("enter") or InputManager.getPressed("jump"):
         pygame.mixer.music.stop()
         Globals.STATE = GameScreen.GameScreen()
         return
     self.time += time
     if self.time < EnterFinalScreen.FADEINTIME:
         ratio = self.time / EnterFinalScreen.FADEINTIME
Exemplo n.º 11
0
class Game :

	"""
	The main game class manages everything and runs the game loop
	"""

	def __init__ (self):
	
		self.lll = LowLevelLib ()
		self.inputmanager = InputManager (self)
		
		#self.display = Display ()
		self.viewspace = ViewSpace ()
		self.curmap = Map (40)
		# just for test
		self.curmap.heights.setHeight(2,3,-1)
		self.curmap.heights.setHeight(2,5,1)
		self.curmap.heights.setHeight(4,5,-1)
		self.gfxengine = GFXEngine (self.lll, self.viewspace, self.curmap)
		self.gamecontroller = GameController (self)
		self.running = False
		self.starttime = 0
				
	def run (self):
	
		"""
		Run the game.
		"""
	
		self.running = True

		frames = 0
		lasttick = pygame.time.get_ticks ()

		while self.running :
		
			self.inputmanager.process ()
			self.gamecontroller.tick ()
			self.gfxengine.tick ()
			
			frames += 1
			if pygame.time.get_ticks() - lasttick >= 1000:
				print str(frames)+" fps"+(" - below 40 fps :-( !" if frames<40 else "")
				frames = 0
				lasttick = pygame.time.get_ticks ()


	def getGfxengine(self):
		"""
		@return: the instance of the gfxengine of the game
		"""
		return self.gfxengine

	def getInputmanager(self):
		"""
		@return: the instance of the inputmanager of the game
		"""
		return self.inputmanager
Exemplo n.º 12
0
 def update(self, time):
     if InputManager.getPressed("enter") or InputManager.getPressed("jump"):
         pygame.mixer.music.stop()
         Globals.STATE = GameScreen.GameScreen()
         return
     self.time += time
     if self.time < EnterSnowScreen.FADEINTIME:
         ratio = self.time / EnterSnowScreen.FADEINTIME
     if self.sceneTime > 2.0:
         self.state = (self.state + 1) % 2
         self.sceneTime = 0.0
     self.sceneTime += time
 def update(self, time):
     if InputManager.getPressed("enter") or InputManager.getPressed("jump"):
         #pygame.mixer.music.fadeout(1000)
         Globals.STATE = HighScoreInputScreen.HighScoreInputScreen()
         return
     self.time += time
     if self.time < CompletedGameScreen.FADEINTIME:
         ratio = self.time / CompletedGameScreen.FADEINTIME
     if self.sceneTime > 1.0:
         self.state = (self.state + 1) % 2
         self.sceneTime = 0.0
     self.sceneTime += time
Exemplo n.º 14
0
def mainProcessErrorHandler(exceptionType, exceptionValue, exceptionTraceback):

    #Print error
    print(format_exception(exceptionType, exceptionValue, exceptionTraceback))

    #End sampling process
    tco.orderToStopProcess()

    #Tell PyQt system to quit (otherwise the windows hang)
    im.closeWindowsOnCrash()

    #End main process
    sys.exit(0)
def openDisplaySettingsMenu():

    global displaySettingsWrapper, colorButtons

    #First, pause session so applying any changes don't have a chance of affecting performance
    if im.playMode == im.PlayMode.ACQUISITION and ts.currentSession:
        im.setPlaying(False)

    #Create the display settings menu (using the Qt Designer-generated Ui_displaySettings)
    displaySettingsWindow = QDialog()
    displaySettingsWrapper = dsw.Ui_displaySettingsWindow()
    displaySettingsWrapper.setupUi(displaySettingsWindow)

    #Detects when the "Restore Defaults" or "OK" buttons are pressed respectively (0x08000000 used instead of QtGui.QDialogButtonBox.Reset due to import issues[They are interchangable])
    displaySettingsWrapper.buttonBox.button(0x08000000).clicked.connect(
        restoreDisplayDefaults)
    displaySettingsWrapper.buttonBox.accepted.connect(saveDisplaySettings)

    #Keep track of the color buttons in tuple format for easier access
    colorButtons = (displaySettingsWrapper.backgroundColorButton,
                    displaySettingsWrapper.dataColorButton,
                    displaySettingsWrapper.textColorButton,
                    displaySettingsWrapper.stimulusColorButton,
                    displaySettingsWrapper.axisColorButton,
                    displaySettingsWrapper.onsetArrowColorButton,
                    displaySettingsWrapper.offsetArrowColorButton)

    #Detects when the color buttons are pressed
    colorButtons[0].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.BACKGROUND))
    colorButtons[1].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.DATA))
    colorButtons[2].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.TEXT))
    colorButtons[3].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.STIMULUS))
    colorButtons[4].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.AXIS))
    colorButtons[5].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.ONSET))
    colorButtons[6].clicked.connect(
        lambda: colorButtonPressed(ColorAttribute.OFFSET))

    #Make the menu not resizable
    displaySettingsWindow.setFixedSize(displaySettingsWindow.size())

    #Set the values of these settings to the currently selected values
    showDisplaySettings()

    #Display the menu
    displaySettingsWindow.exec()
Exemplo n.º 16
0
	def __init__ (self):
	
		self.lll = LowLevelLib ()
		self.inputmanager = InputManager (self)
		
		#self.display = Display ()
		self.viewspace = ViewSpace ()
		self.curmap = Map (40)
		# just for test
		self.curmap.heights.setHeight(2,3,-1)
		self.curmap.heights.setHeight(2,5,1)
		self.curmap.heights.setHeight(4,5,-1)
		self.gfxengine = GFXEngine (self.lll, self.viewspace, self.curmap)
		self.gamecontroller = GameController (self)
		self.running = False
		self.starttime = 0
Exemplo n.º 17
0
    def __init__(self, sprite, position, fake=False):
        self.spriteName = sprite

        self.fake = fake

        self.loadSprites()

        self.position = position
        self.currentSelectedUnit = None
        self.secondSelectedUnit = None
        self.currentHoveredUnit = None
        self.currentHoveredTile = None
        self.camera_follow = None

        self.fluid_helper = InputManager.FluidScroll(
            cf.OPTIONS['Cursor Speed'])

        self.movePath = []

        self.drawState = 0  # If cursor will be drawn

        self.back_pressed = False
        self.spriteOffset = [0, 0]
        self.already_stopped_at_move_border = False  # Only applies during MoveState in StateMachine
        self.border_position = None  # Where the arrow stopped at the border
Exemplo n.º 18
0
 def update(self, time):
     if Globals.WIN:
         if Globals.CURRENT_LEVEL == "five":
             if self.bossWinTimer > 0.0:
                 self.bossWinTimer -= time
             else:
                 self.exitFinal()
                 return
         else:
             if Globals.TIME > 0:
                 Globals.SCORE = Globals.SCORE + 10 * int(Globals.TIME)
             self.exitGame()
             return
     if Globals.PLAYER.isDead:
         self.timer -= time
         if self.timer <= 0:
             self.deadScreen()
             return
     if InputManager.getPressed("esc"):
         self.exitScreen()
         return
     Globals.TIME = Globals.TIME - time
     World.update(time)
     if not Globals.CHECKPOINT_SET and\
             Globals.CURRENT_LEVEL in Globals.CHECKPOINT_POS:
         if Globals.PLAYER.rect.x > Globals.getCheckpointPos()[0]:
             Globals.CHECKPOINT_SET = True
Exemplo n.º 19
0
    def update(self, time):
        if InputManager.getPressed("up"):
            self.selectionID -= 1
            if self.selectionID < 0:
                self.selectionID = (Globals.LEVELS_BEAT + 1)
        elif InputManager.getPressed("down"):
            self.selectionID =\
                (self.selectionID + 1) % (Globals.LEVELS_BEAT + 2)

        if InputManager.getPressed("enter"):
            if self.selectionID == 0:
                World.cleanupCompletely()
                Globals.PLAYER = None
                Globals.STATE = EntryScreen.EntryScreen()
                Globals.CURRENT_LEVEL = "one"
            elif self.selectionID == 1 and Globals.LEVELS_BEAT > 0:
                World.cleanupCompletely()
                Globals.PLAYER = None
                Globals.STATE = EnterMountainScreen.EnterMountainScreen()
                Globals.CURRENT_LEVEL = "two"
            elif self.selectionID == 2 and Globals.LEVELS_BEAT > 1:
                World.cleanupCompletely()
                Globals.PLAYER = None
                Globals.STATE = EnterCaveScreen.EnterCaveScreen()
                Globals.CURRENT_LEVEL = "three"
            elif self.selectionID == 3 and Globals.LEVELS_BEAT > 2:
                World.cleanupCompletely()
                Globals.PLAYER = None
                Globals.STATE = EnterSnowScreen.EnterSnowScreen()
                Globals.CURRENT_LEVEL = "four"
            elif self.selectionID == 4 and Globals.LEVELS_BEAT > 3:
                World.cleanupCompletely()
                Globals.PLAYER = None
                Globals.STATE = EnterFinalScreen.EnterFinalScreen()
                Globals.CURRENT_LEVEL = "five"
            elif self.selectionID == (Globals.LEVELS_BEAT + 1):
                self.enter_back()
        if InputManager.getPressed("esc"):
            self.enter_back()
        self.time += time
        if self.time < MapScreen.FADEINTIME:
            ratio = self.time / MapScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
Exemplo n.º 20
0
def captureCurrentTrial():
    #Capture graph (i.e. capture trial)
    trialCapture = im.capture("Graph", True)

    #Resize capture (mode specifies to do it without any smoothing to save performance)
    trialCapture = trialCapture.scaled(trialWidth, trialHeight, transformMode = Qt.FastTransformation)

    return trialCapture
Exemplo n.º 21
0
    def update(self, time):
        if InputManager.getPressed("up"):
            self.selectionID -= 1
            if self.selectionID < 0:
                self.selectionID = 4
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
        elif InputManager.getPressed("down"):
            self.selectionID = (self.selectionID + 1) % 5
            AudioManager.sounds["menu"]["menuSound.ogg"].play()

        if InputManager.getPressed("enter"):
            AudioManager.sounds["menu"]["menuSound.ogg"].play()
            AudioManager.unloadSfxSet("menu")
            if self.selectionID == 0:
                self.enter_game()
            elif self.selectionID == 1:
                self.enter_entry()
            elif self.selectionID == 2:
                self.enter_highScore()
            elif self.selectionID == 3:
                self.enter_settings()
            elif self.selectionID == 4:
                self.exit_title()
        if InputManager.getPressed("esc"):
            self.exit_title()
        self.time += time
        if self.time < MainScreen.FADEINTIME:
            ratio = self.time / MainScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
        self.astoriaToggleTime += time
        if self.astoriaToggleTime < self.astoriaToggleTimeInterval:
            ratio = self.astoriaToggleTime / self.astoriaToggleTimeInterval
            self.astoriaOpacity = int(ratio * 255)
        elif self.astoriaToggleTime < self.astoriaToggleTimeInterval * 2:
            ratio = self.astoriaToggleTime / self.astoriaToggleTimeInterval
            ratio = 1 -\
                (self.astoriaToggleTime - self.astoriaToggleTimeInterval) /\
                self.astoriaToggleTimeInterval
            self.astoriaOpacity = int(ratio * 255)
        else:
            self.astoriaToggleTime = 0
 def __init__(self):
     self.selectionID = 0
     self.color = pygame.color.Color("white")
     self.selectedColor = pygame.color.Color(127, 255, 127)
     Globals.SCREEN.fill(pygame.color.Color("black"))
     self.cExists = InputManager.initController()
     self.index = 0
     self.iText = "default"
     self.wait = 0.0
Exemplo n.º 23
0
def endTrialStartITI():

    global previousITI, duringITI, itiCountdown, countdownLabel, done

    #End trial
    displayTimer.stop()

    #Save trial
    JSONConverter.saveTrial(data, float(previousITI))

    #Don't start ITI because that was the last trial we just finished
    if ts.currentSession.currentTrial >= ts.currentSession.trialCount:
        done = True

        #Pause upon completion
        im.setPlaying(False)

        #Completion message...
        mainWindow.trialInfoLabel.setText(
            "SESSION COMPLETE!\n\nPRESS STOP TO SAVE")

        #Also, don't allow restart of data acquisition (functionality not supported)
        mainWindow.playButton.setEnabled(False)

        #Return before ITI starts
        return

    #Create countdown label "Next trial in..."
    mainWindow.trialInfoLabel.setText("NEXT TRIAL IN...\n\n")

    #Wait for start of ITI updates (if it takes TCO more than 3 seconds then raise hell!)
    itiCountdown = tco.itiQueue.get(timeout=3)
    previousITI = itiCountdown

    if itiCountdown > 0:
        #Create countdown label "Next trial in... X.X"
        mainWindow.trialInfoLabel.setText(
            "NEXT TRIAL IN...\n\n{:5.1f}".format(itiCountdown))

        #Begin ITI
        duringITI = True
        itiTimer.start(100)  #Parameter is millisecond interval between updates
    else:
        endITIStartTrial()
Exemplo n.º 24
0
 def __new__(cls):
     if cls.__instance is None:
         cls.__instance = super(Managers, cls).__new__(cls)
         cls.__instance.app = QtWidgets.QApplication(sys.argv)
         cls.__instance.input = inputManager.InputManager()
         cls.__instance.scene = scene.SceneManager()
         cls.__instance.scene.resize(1550, 1000)
         cls.__instance.objects = objMan.ObjectManager(cls.__instance.scene)
         cls.__instance.collisionDetection = collision.CollisionDetection(
             cls.__instance.objects)
     return cls.__instance
Exemplo n.º 25
0
def saveMatrixAsImage():

    #Take picture of the grid
    matrixAsImage = matrixViewWrapper.gridWidget.grab()

    #Pop up "Save As" window to retrieve file name and type to save as
    nameAndType = QFileDialog.getSaveFileName(parent = im.mainWindow.centralwidget, caption = "Save Trial Matrix Capture As", filter = "PNG (*.png);;JPG (*.jpg)")

    #If user didn't click cancel on "Save As", save screenshot using "Save As" options
    if len(nameAndType[0]) > 0:
        matrixAsImage.save(nameAndType[0], im.extractFileType(nameAndType[1]))
Exemplo n.º 26
0
    def update(self, time):
        if not Globals.LASTSCREENSETTING:
            if InputManager.getPressed("enter") or\
                    InputManager.getPressed("jump"):
                Globals.STATE = EntryScreen.EntryScreen()
            elif InputManager.getPressed("esc"):
                Globals.STATE = MainScreen.MainScreen()
        else:
            if InputManager.getPressed("enter") or\
                    InputManager.getPressed("jump") or\
                    InputManager.getPressed("esc"):
                Globals.STATE = SettingScreen.SettingScreen()
                Globals.LASTSCREENSETTING = False

        self.time += time
        if self.time < ControlScreen.FADEINTIME:
            ratio = self.time / ControlScreen.FADEINTIME
            value = int(ratio * 255)
            halfValue = int(ratio * 127)
            self.color = pygame.color.Color(value, value, value)
            self.selectedColor =\
                pygame.color.Color(halfValue, value, halfValue)
        self.astoriaToggleTime += time
        if self.astoriaToggleTime < self.astoriaToggleTimeInterval:
            ratio = self.astoriaToggleTime / self.astoriaToggleTimeInterval
            self.astoriaOpacity = int(ratio * 255)
        elif self.astoriaToggleTime < self.astoriaToggleTimeInterval * 2:
            ratio = self.astoriaToggleTime / self.astoriaToggleTimeInterval
            ratio = 1 -\
                (self.astoriaToggleTime - self.astoriaToggleTimeInterval) /\
                self.astoriaToggleTimeInterval
            self.astoriaOpacity = int(ratio * 255)
        else:
            self.astoriaToggleTime = 0
Exemplo n.º 27
0
    def __init__(self):
        wx.Frame.__init__(self, None, title="Otter Share")
        panel = wx.Panel(self)

        nb = wx.Notebook(panel)
        tab1 = Tab(nb)
        tab2 = Tab(nb)
        tab3 = Tab(nb)
        tab4 = Tab(nb)
        nb.AddPage(tab1, "Tab1")
        nb.AddPage(tab2, "Tab2")
        nb.AddPage(tab3, "Tab3")
        nb.AddPage(tab4, "Tab4")
        # Set noteboook in a sizer to create the layout
        sizer = wx.BoxSizer()
        sizer.Add(nb, 1, wx.EXPAND)
        panel.SetSizer(sizer)

        self.tbIcon = TaskBarIcon(self)

        self.Bind(wx.EVT_ICONIZE, self.OnMinimize)
        self.Bind(wx.EVT_CLOSE, self.OnClose)

        self.Show()

        # Add some events to the keyboard
        #WinKeyboard.add_handler(print_event)
        #WinKeyboard.add_handler(screenshot_handler)

        #InputManager.add_hook(self.mouse.generate_hook())

        # Start listening on input
        worker = None
        InputManager.add_input(WinMouse())
        InputManager.add_input(WinKeyboard())

        # Split the Message Pumping onto its own thread.
        if not worker:
            worker = threading.Thread(target=InputManager.listener())
            worker.start()
Exemplo n.º 28
0
 def update(self, entity, interval):
     if entity.posx > Globals.WIN_POS:
         Globals.WIN = True
     entity.regen_time += interval
     if entity.regen_time >= Globals.PLAYER_REGEN_TIME:
         if entity.health < Globals.PLAYER_MAX_HEALTH:
             entity.health += 1
         if entity.mp < Globals.PLAYER_MAX_MP:
             entity.mp += 1
         entity.regen_time = 0.0
     if InputManager.getPressed("debugMode"):
         Globals.DEBUG_MODE = not Globals.DEBUG_MODE
     if InputManager.getAction("cheat1") and Globals.DEBUG_MODE:
         entity.health = Globals.PLAYER_MAX_HEALTH
     if InputManager.getPressed("cheat2") and Globals.DEBUG_MODE:
         Globals.WIN = True
         if Globals.CURRENT_LEVEL == "five":
             Globals.GAMECOMPLETED = True
     if InputManager.getPressed("cheat3") and Globals.DEBUG_MODE:
         Globals.MINI_SUNS += 1
     if InputManager.getPressed("cheatPos") and Globals.DEBUG_MODE:
         print Globals.PLAYER.rect.x, Globals.PLAYER.rect.y
    def update(self, interval):
        if InputManager.getPressed("esc"):
            Globals.STATE = SettingScreen.SettingScreen()
        if self.cExists:
            if self.index < len(InputManager.cList):
                self.iText = "Press button/axis for " +\
                    InputManager.cList[self.index]

            if self.wait == 0.0 and self.index < len(InputManager.cList):
                cInput = InputManager.getControllerInput()
                if cInput[0] != 0:
                    InputManager.cBindings[cInput] =\
                        InputManager.cList[self.index]
                    self.index += 1
                    self.wait = 1.0
            elif self.wait == 0.0:
                InputManager.cConfigured = True
                Globals.STATE = SettingScreen.SettingScreen()
            else:
                self.wait -= interval
                if self.wait < 0.0:
                    self.wait = 0.0
Exemplo n.º 30
0
def run_prediciton(testFile, predictions_save_dest='dl.score', save=True):
    test_dataset = im.getSequences_without_shuffle(testFile,
                                                   1,
                                                   1002,
                                                   silent=True)

    config = tf.ConfigProto(allow_soft_placement=True)
    config.gpu_options.allow_growth = True
    sess = tf.Session(config=config)

    saver = tf.train.import_meta_graph(
        'parameters/test_200114-153051/test_200114-153051' + '.meta')
    saver.restore(sess,
                  tf.train.latest_checkpoint('parameters/test_200114-153051/'))
    #saver = tf.train.import_meta_graph('/home/zzegs/workspace/dagw/toxicity_DL/rr/BASF_code/parameters/seq_model/test_190705-110204' +'.meta')
    #saver.restore(sess, tf.train.latest_checkpoint('/home/zzegs/workspace/dagw/toxicity_DL/rr/BASF_code/parameters/seq_model/'))
    graph = tf.get_default_graph()
    prediction_logits = graph.get_tensor_by_name("my_logits:0")
    X_placeholder = graph.get_tensor_by_name("X_placeholder:0")
    Y_placeholder = graph.get_tensor_by_name("Y_placeholder:0")
    seqlen_ph = graph.get_tensor_by_name("seqlen_placeholder:0")
    vec_placeholder = graph.get_tensor_by_name("vec_placeholder:0")

    sigmoid_f = tf.sigmoid(prediction_logits)
    #sess.run(output_tensor, feed_dict={.....})
    test_label, test_pred = [], []
    if save:
        a = open('dl.score', 'w')
    batches_done = False
    while not batches_done:
        batch_x, lengths_x, batch_y, vector_x, epoch_finished = test_dataset.next_batch_without_shuffle(
            512)
        sigmoids = sess.run(sigmoid_f,
                            feed_dict={
                                X_placeholder: batch_x,
                                Y_placeholder: batch_y,
                                vec_placeholder: vector_x,
                                seqlen_ph: lengths_x
                            })
        for p, c in zip(sigmoids, batch_y):
            if save:
                print(','.join([str(x) for x in p]), file=a)
                print(','.join([str(x) for x in c]), file=a)
            #else:
            test_label.append(c[0])
            test_pred.append(p[0])
        if epoch_finished:
            batches_done = True
    sess.close()
    #if not save:
    return np.array(test_label), np.array(test_pred)
Exemplo n.º 31
0
def run(profName=""):
    global settings
    global profile
    global inputFaker
    global bciDevice
    global current
    global keycodelistlabels
    global niaDirectFeedbackApp
    inputFaker = OutputManager.InputFaker()
    if inputFaker == -1:
        print "Import-Error: You need either Win32con (Windows) or XLib (Linux, Mac)"
    else:
        keycodelistlabels = sorted(
            ["Action: " + each for each in inputFaker.actions.keys()])
        profile = ProfileSettings()

        if (profName == ""):
            if len(sys.argv) == 2:
                profilefile = sys.argv[1]
                if os.path.exists(profilefile + ".feedback"):
                    workfile = open(profilefile + ".feedback", "r")
                    profile = pickle.load(workfile)
                    workfile.close()
                else:
                    print "no " + profilefile + ".feedback" + " file found"
                    selection = WXElements.selection(
                        "Select your Device",
                        InputManager.SupportedDevices.keys()[0],
                        InputManager.SupportedDevices.keys())
                    profile.deviceName = selection
            else:
                selection = WXElements.selection(
                    "Select your Device",
                    InputManager.SupportedDevices.keys()[0],
                    InputManager.SupportedDevices.keys())
                profile.deviceName = selection
        else:
            profilefile = profName
            if os.path.exists(profilefile + ".feedback"):
                workfile = open(profilefile + ".feedback", "r")
                profile = pickle.load(workfile)
                workfile.close()
            else:
                profile.profileName = profilefile
        bciDevice = InputManager.BCIDevice(profile.deviceName)
        current = Current_Data()
        niaDirectFeedbackApp = NiaDirectFeedbackApp()
        niaDirectFeedbackApp.MainLoop()
        bciDevice.quit()
Exemplo n.º 32
0
Arquivo: Game.py Projeto: joe42/yasc
	def __init__ (self):
	
		self.lll = LowLevelLib ()
		self.inputmanager = InputManager (self)
		#self.display = Display ()
		self.viewspace = ViewSpace ()
		self.curmap = Map (40)
		# just for test
		self.curmap.heights.setHeight(2,3,-1)
		self.curmap.heights.setHeight(2,5,1)
		self.curmap.heights.setHeight(4,5,-1)
		self.gfxengine = GFXEngine (self.lll, self.viewspace, self.curmap)
		self.gamecontroller = GameController (self)
		self.running = False
		self.starttime = 0
Exemplo n.º 33
0
 def imp_lib(self, filename):
     """
     Import an external library to the default directory
     :param filename: str - path of the library directory
     :return:
     """
     try:
         library_name = os.path.basename(filename)
         # e = InputManager.import_library(filename, library_name)
         e = InputManager.imp_new_library(filename)
         OutputManager2.create_library(self.dir_path, library_name)
         OutputManager.save_library(e)
         return e
     except Exception:
         return FileNotFoundError(filename)
    def update(self, interval):
        if InputManager.getPressed("up"):
            self.ulet = chr(ord(self.ulet) - 1)
        elif InputManager.getPressed("down"):
            self.ulet = chr(ord(self.ulet) + 1)
        elif InputManager.getPressed("enter"):
            self.name.append(self.ulet)
            self.ulet = 'A'
        elif InputManager.getPressed("left"):
            self.name = self.name[:-1]
            self.ulet = 'A'

        if self.ulet < 'A':
            self.ulet = 'Z'
        elif self.ulet > 'Z':
            self.ulet = 'A'

        if len(self.name) == 3:
            f = open('highScores.txt', 'a')
            f.write(self.name[0] + self.name[1] + self.name[2] +
                    " " + str(Globals.SCORE) + "\n")
            f.close()
            Globals.SCORE = 0
            self.exit_screen()
Exemplo n.º 35
0
 def __init__(self):
     self.game_constants = Counter()
     self.game_constants['level'] = 0
     # Set up blitting surfaces
     self.generic_surf = Engine.create_surface((GC.WINWIDTH, GC.WINHEIGHT))
     # Build starting stateMachine
     self.stateMachine = StateMachine.StateMachine(['start_start'], [])
     self.input_manager = InputManager.InputManager()
     # Menu slots
     self.activeMenu = None
     self.childMenu = None
     self.background = None
     # Surface holder
     self.info_surf = None
     # playtime
     self.playtime = 0
     # mode
     self.mode = self.default_mode()
Exemplo n.º 36
0
    def __init__(self, sprite, position, fake=False):
        self.spriteName = sprite

        self.fake = fake

        self.loadSprites()

        self.position = position
        self.currentSelectedUnit = None
        self.secondSelectedUnit = None
        self.currentHoveredUnit = None
        self.currentHoveredTile = None
        self.camera_follow = None

        self.fluid_helper = InputManager.FluidScroll(
            cf.OPTIONS['Cursor Speed'])

        self.movePath = []

        self.drawState = 0  # If cursor will be drawn

        self.spriteOffset = [0, 0]
Exemplo n.º 37
0
    def imp_col(self, file_path, library_name):
        try:
            lib = self.libraries[library_name]
        except Exception:
            return LibraryNotOpenedError(library_name)

        try:
            filereader = open(file_path, 'r')
        except Exception:
            return FileNotFoundError(file_path)

        file = filereader.read().split("\n")
        # Path of file with data
        col_path = file[0]
        # Name of collection
        col_name = file[1]
        # Name of object
        obj_name = file[2]
        # Object attributes
        obj_attr = file[3]

        # Convert the object attributes to a string
        att = obj_attr.split(",")
        att_dict = {}
        for a in att:
            split = a.split(":")
            att_dict[split[0]] = split[1]

        obj = ObjectType(obj_name, att_dict)
        data_types = obj.get_obj_data_types()
        try:
            col = InputManager.import_collection(col_path,
                                                 Collection(col_name, obj),
                                                 data_types)
        except Exception:
            return FileNotFoundError(col_path)

        lib.add_collection(col)
        OutputManager2.create_collection(self.dir_path, library_name, col)
Exemplo n.º 38
0
Arquivo: main.py Projeto: Acruxx/ARS
    def __init__(self):
        self.BOARD_SIZE = 720
        
        self.size = width, height = self.BOARD_SIZE, self.BOARD_SIZE
        self.speed = [0.2, 0.2]
        self.black = 0, 0, 0
        
        self.screen = pygame.display.set_mode(self.size)
        self.roundaboutImage = pygame.image.load("media/roundaboutNew.png")
        #roundabout = pygame.image.load("ball.gif")
        self.readyImg = pygame.image.load("media/readyScreen.png")
        
        self.roundaboutImage = pygame.transform.scale(self.roundaboutImage, self.size);
        self.readyImg = pygame.transform.scale(self.readyImg, self.size);

        self.roundaboutRect = self.roundaboutImage.get_rect()
        self.readyBox = self.readyImg.get_rect()
        
        self.inputManager = InputManager()
        
        self.player = Player(0, 200);
        
        self.currentTrack = GhostTrack();
        self.currentOffset = 0
        
        self.oldCars = []
        self.oldTracks = []
        self.oldOffsets = []
        
        self.doneLaps = 0

        self.framesToRun = 1000

        self.waves = 0

        self.state = STATE_MENU

        self.explosionSound = pygame.mixer.Sound("media/Explosion.wav")
Exemplo n.º 39
0
    def openLibrary(self, library_name):
        """
        Creates an instance of a library so that a user can
        use commands to manage it
        :param library_name: str - library name
        :return: None
        """

        if library_name in self.libraries:
            return LibraryOpenedError(library_name)

        # library = InputManager2.import_library(self.dir_path + "/" + library_name, library_name)
        library = InputManager.imp_new_library('Directory/' + library_name)

        if isinstance(library, Error):
            return library

        self.libraries[library_name] = library
        collections = library.get_collection_list()
        for col in collections:
            obj = col.get_obj_def().get_obj_type()
            if not obj in self.objects:
                self.objects[obj] = col.get_obj_def()
Exemplo n.º 40
0
Arquivo: main.py Projeto: Acruxx/ARS
class Game:
    def __init__(self):
        self.BOARD_SIZE = 720
        
        self.size = width, height = self.BOARD_SIZE, self.BOARD_SIZE
        self.speed = [0.2, 0.2]
        self.black = 0, 0, 0
        
        self.screen = pygame.display.set_mode(self.size)
        self.roundaboutImage = pygame.image.load("media/roundaboutNew.png")
        #roundabout = pygame.image.load("ball.gif")
        self.readyImg = pygame.image.load("media/readyScreen.png")
        
        self.roundaboutImage = pygame.transform.scale(self.roundaboutImage, self.size);
        self.readyImg = pygame.transform.scale(self.readyImg, self.size);

        self.roundaboutRect = self.roundaboutImage.get_rect()
        self.readyBox = self.readyImg.get_rect()
        
        self.inputManager = InputManager()
        
        self.player = Player(0, 200);
        
        self.currentTrack = GhostTrack();
        self.currentOffset = 0
        
        self.oldCars = []
        self.oldTracks = []
        self.oldOffsets = []
        
        self.doneLaps = 0

        self.framesToRun = 1000

        self.waves = 0

        self.state = STATE_MENU

        self.explosionSound = pygame.mixer.Sound("media/Explosion.wav")

    
    def restartGame(self):
        self.oldTracks.append(self.currentTrack)
        self.oldOffsets.append(self.currentOffset)
    
        #Restart the game and spawn some stuff
        self.oldCars.append(GhostCar())
    
        for track in self.oldTracks:
            track.reset_count()
    
        self.startGame()

        
    
    def startGame(self):
        self.currentOffset = random.random() * math.pi * 2
        self.currentTrack = GhostTrack()

        self.player.resetCar();
        self.player.setAng(self.currentOffset);

        self.currentFrame = 0

        self.state = STATE_COUNTDOWN
        self.startTime = time.time()
        
        self.waves += 1

        self.coin = Coin()
    
    
    def main(self):
        while 1:
            self.screen.fill(self.black)

            for event in pygame.event.get():
                if event.type == pygame.QUIT: sys.exit()
                
                self.inputManager.onEvent(event);
        
            if self.state == STATE_GAME:
                self.player.update(self.inputManager);
        
                self.currentTrack.add_pos(self.player.getAng(), self.player.getRad())

                self.currentFrame += 1
        
                if self.currentFrame >= self.framesToRun:
                    self.restartGame()
        
                for i in range(0, len(self.oldCars)):
                    oldPos = self.oldTracks[i].get_next_pos()

                    self.oldCars[i].setAng(oldPos[0])
                    self.oldCars[i].setRad(oldPos[1] + self.oldOffsets[i])
                    self.oldCars[i].update()
                    self.oldCars[i].setFuture(self.oldTracks[i].get_future_pos(60))

                    if self.oldCars[i].checkCollision(self.player):
                        self.player.shakeSound.stop()

                        score = self.player.score
                        
                        self.explosionSound.play()

                        print "You died, final score: {}".format(score)

                        pygame.display.quit()

                        if(score >= highScore.getLowest()):
                            name = raw_input("New high score, what's your name?\n")

                            highScore.addScore(name, score)

                        highScore.save()
                        return


                self.coin.update(self.player)

            elif self.state == STATE_COUNTDOWN:
                if(time.time() > self.startTime + 1): 
                    self.state = STATE_GAME

                for car in self.oldCars:
                    car.updateGraphics()

                self.player.updateGraphics()
                self.coin.updateGraphics()

        
            #self.screen.blit(self.roundaboutImage, screenshaker.offset.getTuple(), self.roundaboutRect)
            self.screen.blit(self.roundaboutImage, screenshaker.offset.getTuple(), self.roundaboutRect)
            self.player.draw(self.screen);

            for car in self.oldCars:
                car.draw(self.screen)

            self.coin.draw(self.screen)

            if self.state == STATE_COUNTDOWN:
                self.screen.blit(self.readyImg, self.readyBox)

            pygame.display.flip()
Exemplo n.º 41
0
    def setupUi(self, MainWindow):
        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(1324, 758)
        font = QtGui.QFont()
        font.setFamily("MS Sans Serif")
        MainWindow.setFont(font)
        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        self.rootHorizontalLayout = QtWidgets.QHBoxLayout(self.centralwidget)
        self.rootHorizontalLayout.setObjectName("rootHorizontalLayout")
        self.scrollArea = QtWidgets.QScrollArea(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.scrollArea.sizePolicy().hasHeightForWidth())
        self.scrollArea.setSizePolicy(sizePolicy)
        self.scrollArea.setMinimumSize(QtCore.QSize(500, 0))
        self.scrollArea.setFocusPolicy(QtCore.Qt.NoFocus)
        self.scrollArea.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOn)
        self.scrollArea.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.scrollArea.setWidgetResizable(True)
        self.scrollArea.setObjectName("scrollArea")
        self.scrollAreaWidgetContents = QtWidgets.QWidget()
        self.scrollAreaWidgetContents.setGeometry(QtCore.QRect(0, 0, 490, 801))
        self.scrollAreaWidgetContents.setObjectName("scrollAreaWidgetContents")
        self.formLayout_2 = QtWidgets.QFormLayout(self.scrollAreaWidgetContents)
        self.formLayout_2.setObjectName("formLayout_2")
        self.sessionSettings = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(22)
        font.setBold(True)
        font.setWeight(75)
        self.sessionSettings.setFont(font)
        self.sessionSettings.setObjectName("sessionSettings")
        self.formLayout_2.setWidget(0, QtWidgets.QFormLayout.LabelRole, self.sessionSettings)
        self.sessionName = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.sessionName.setFont(font)
        self.sessionName.setObjectName("sessionName")
        self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.LabelRole, self.sessionName)
        self.sampleIntervalLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.sampleIntervalLabel.setFont(font)
        self.sampleIntervalLabel.setObjectName("sampleIntervalLabel")
        self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.LabelRole, self.sampleIntervalLabel)
        self.sampleIntervalSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        self.sampleIntervalSpinBox.setEnabled(True)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.sampleIntervalSpinBox.setFont(font)
        self.sampleIntervalSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.sampleIntervalSpinBox.setSuffix("")
        self.sampleIntervalSpinBox.setMinimum(1)
        self.sampleIntervalSpinBox.setMaximum(1000)
        self.sampleIntervalSpinBox.setProperty("value", 1)
        self.sampleIntervalSpinBox.setObjectName("sampleIntervalSpinBox")
        self.formLayout_2.setWidget(7, QtWidgets.QFormLayout.FieldRole, self.sampleIntervalSpinBox)
        self.trialCountLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.trialCountLabel.setFont(font)
        self.trialCountLabel.setObjectName("trialCountLabel")
        self.formLayout_2.setWidget(8, QtWidgets.QFormLayout.LabelRole, self.trialCountLabel)
        self.trialCountSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.trialCountSpinBox.setFont(font)
        self.trialCountSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.trialCountSpinBox.setMinimum(1)
        self.trialCountSpinBox.setMaximum(10000000)
        self.trialCountSpinBox.setSingleStep(5)
        self.trialCountSpinBox.setProperty("value", 60)
        self.trialCountSpinBox.setObjectName("trialCountSpinBox")
        self.formLayout_2.setWidget(8, QtWidgets.QFormLayout.FieldRole, self.trialCountSpinBox)
        spacerItem = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(9, QtWidgets.QFormLayout.LabelRole, spacerItem)
        self.itiLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.itiLabel.setFont(font)
        self.itiLabel.setObjectName("itiLabel")
        self.formLayout_2.setWidget(10, QtWidgets.QFormLayout.LabelRole, self.itiLabel)
        self.itiSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.itiSpinBox.setFont(font)
        self.itiSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.itiSpinBox.setSuffix("")
        self.itiSpinBox.setMaximum(9999)
        self.itiSpinBox.setProperty("value", 15)
        self.itiSpinBox.setObjectName("itiSpinBox")
        self.formLayout_2.setWidget(10, QtWidgets.QFormLayout.FieldRole, self.itiSpinBox)
        self.itiVarianceLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.itiVarianceLabel.setFont(font)
        self.itiVarianceLabel.setObjectName("itiVarianceLabel")
        self.formLayout_2.setWidget(11, QtWidgets.QFormLayout.LabelRole, self.itiVarianceLabel)
        self.itiVarianceSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.itiVarianceSpinBox.setFont(font)
        self.itiVarianceSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.itiVarianceSpinBox.setSuffix("")
        self.itiVarianceSpinBox.setMaximum(9999)
        self.itiVarianceSpinBox.setProperty("value", 3)
        self.itiVarianceSpinBox.setObjectName("itiVarianceSpinBox")
        self.formLayout_2.setWidget(11, QtWidgets.QFormLayout.FieldRole, self.itiVarianceSpinBox)
        spacerItem1 = QtWidgets.QSpacerItem(20, 10, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(12, QtWidgets.QFormLayout.LabelRole, spacerItem1)
        self.trialSettings = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(22)
        font.setBold(True)
        font.setWeight(75)
        self.trialSettings.setFont(font)
        self.trialSettings.setObjectName("trialSettings")
        self.formLayout_2.setWidget(13, QtWidgets.QFormLayout.LabelRole, self.trialSettings)
        self.trialDurationLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.trialDurationLabel.setFont(font)
        self.trialDurationLabel.setObjectName("trialDurationLabel")
        self.formLayout_2.setWidget(14, QtWidgets.QFormLayout.LabelRole, self.trialDurationLabel)
        self.trialDurationSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.trialDurationSpinBox.setFont(font)
        self.trialDurationSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.trialDurationSpinBox.setSuffix("")
        self.trialDurationSpinBox.setMinimum(0)
        self.trialDurationSpinBox.setMaximum(10000000)
        self.trialDurationSpinBox.setSingleStep(1000)
        self.trialDurationSpinBox.setProperty("value", 3000)
        self.trialDurationSpinBox.setObjectName("trialDurationSpinBox")
        self.formLayout_2.setWidget(14, QtWidgets.QFormLayout.FieldRole, self.trialDurationSpinBox)
        self.baselineDurationLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.baselineDurationLabel.setFont(font)
        self.baselineDurationLabel.setObjectName("baselineDurationLabel")
        self.formLayout_2.setWidget(15, QtWidgets.QFormLayout.LabelRole, self.baselineDurationLabel)
        self.baselineDurationSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.baselineDurationSpinBox.setFont(font)
        self.baselineDurationSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.baselineDurationSpinBox.setSuffix("")
        self.baselineDurationSpinBox.setMinimum(0)
        self.baselineDurationSpinBox.setMaximum(10000000)
        self.baselineDurationSpinBox.setSingleStep(1000)
        self.baselineDurationSpinBox.setProperty("value", 1000)
        self.baselineDurationSpinBox.setObjectName("baselineDurationSpinBox")
        self.formLayout_2.setWidget(15, QtWidgets.QFormLayout.FieldRole, self.baselineDurationSpinBox)
        spacerItem2 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(16, QtWidgets.QFormLayout.LabelRole, spacerItem2)
        self.csNameLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.csNameLabel.setFont(font)
        self.csNameLabel.setObjectName("csNameLabel")
        self.formLayout_2.setWidget(17, QtWidgets.QFormLayout.LabelRole, self.csNameLabel)
        self.csNameLineEdit = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.csNameLineEdit.setFont(font)
        self.csNameLineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.csNameLineEdit.setText("")
        self.csNameLineEdit.setObjectName("csNameLineEdit")
        self.formLayout_2.setWidget(17, QtWidgets.QFormLayout.FieldRole, self.csNameLineEdit)
        self.csDurationLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.csDurationLabel.setFont(font)
        self.csDurationLabel.setObjectName("csDurationLabel")
        self.formLayout_2.setWidget(18, QtWidgets.QFormLayout.LabelRole, self.csDurationLabel)
        self.csDurationSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.csDurationSpinBox.setFont(font)
        self.csDurationSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.csDurationSpinBox.setSuffix("")
        self.csDurationSpinBox.setMinimum(0)
        self.csDurationSpinBox.setMaximum(10000000)
        self.csDurationSpinBox.setSingleStep(100)
        self.csDurationSpinBox.setProperty("value", 100)
        self.csDurationSpinBox.setObjectName("csDurationSpinBox")
        self.formLayout_2.setWidget(18, QtWidgets.QFormLayout.FieldRole, self.csDurationSpinBox)
        spacerItem3 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(19, QtWidgets.QFormLayout.LabelRole, spacerItem3)
        self.interstimulusIntervalLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.interstimulusIntervalLabel.setFont(font)
        self.interstimulusIntervalLabel.setObjectName("interstimulusIntervalLabel")
        self.formLayout_2.setWidget(20, QtWidgets.QFormLayout.LabelRole, self.interstimulusIntervalLabel)
        self.interstimulusIntervalSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.interstimulusIntervalSpinBox.setFont(font)
        self.interstimulusIntervalSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.interstimulusIntervalSpinBox.setSuffix("")
        self.interstimulusIntervalSpinBox.setMaximum(10000000)
        self.interstimulusIntervalSpinBox.setSingleStep(500)
        self.interstimulusIntervalSpinBox.setProperty("value", 500)
        self.interstimulusIntervalSpinBox.setObjectName("interstimulusIntervalSpinBox")
        self.formLayout_2.setWidget(20, QtWidgets.QFormLayout.FieldRole, self.interstimulusIntervalSpinBox)
        spacerItem4 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(21, QtWidgets.QFormLayout.LabelRole, spacerItem4)
        self.usNameLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setFamily("MS Sans Serif")
        font.setPointSize(14)
        self.usNameLabel.setFont(font)
        self.usNameLabel.setObjectName("usNameLabel")
        self.formLayout_2.setWidget(22, QtWidgets.QFormLayout.LabelRole, self.usNameLabel)
        self.usNameLineEdit = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.usNameLineEdit.setFont(font)
        self.usNameLineEdit.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.usNameLineEdit.setText("")
        self.usNameLineEdit.setObjectName("usNameLineEdit")
        self.formLayout_2.setWidget(22, QtWidgets.QFormLayout.FieldRole, self.usNameLineEdit)
        self.usDurationLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setFamily("MS Sans Serif")
        font.setPointSize(14)
        self.usDurationLabel.setFont(font)
        self.usDurationLabel.setObjectName("usDurationLabel")
        self.formLayout_2.setWidget(23, QtWidgets.QFormLayout.LabelRole, self.usDurationLabel)
        self.usDurationSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.usDurationSpinBox.setFont(font)
        self.usDurationSpinBox.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.usDurationSpinBox.setSuffix("")
        self.usDurationSpinBox.setMinimum(0)
        self.usDurationSpinBox.setMaximum(10000000)
        self.usDurationSpinBox.setSingleStep(100)
        self.usDurationSpinBox.setProperty("value", 100)
        self.usDurationSpinBox.setObjectName("usDurationSpinBox")
        self.formLayout_2.setWidget(23, QtWidgets.QFormLayout.FieldRole, self.usDurationSpinBox)
        self.subjectAgeLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.subjectAgeLabel.setFont(font)
        self.subjectAgeLabel.setObjectName("subjectAgeLabel")
        self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.LabelRole, self.subjectAgeLabel)
        self.subjectAgeSpinBox = QtWidgets.QSpinBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.subjectAgeSpinBox.setFont(font)
        self.subjectAgeSpinBox.setMaximum(999)
        self.subjectAgeSpinBox.setProperty("value", 30)
        self.subjectAgeSpinBox.setObjectName("subjectAgeSpinBox")
        self.formLayout_2.setWidget(4, QtWidgets.QFormLayout.FieldRole, self.subjectAgeSpinBox)
        self.subjectSexLabel = QtWidgets.QLabel(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.subjectSexLabel.setFont(font)
        self.subjectSexLabel.setObjectName("subjectSexLabel")
        self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.LabelRole, self.subjectSexLabel)
        self.subjectSexComboBox = QtWidgets.QComboBox(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.subjectSexComboBox.setFont(font)
        self.subjectSexComboBox.setObjectName("subjectSexComboBox")
        self.formLayout_2.setWidget(5, QtWidgets.QFormLayout.FieldRole, self.subjectSexComboBox)
        spacerItem5 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(6, QtWidgets.QFormLayout.LabelRole, spacerItem5)
        spacerItem6 = QtWidgets.QSpacerItem(20, 5, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.formLayout_2.setItem(3, QtWidgets.QFormLayout.LabelRole, spacerItem6)
        self.sessionNameLineEdit = QtWidgets.QLineEdit(self.scrollAreaWidgetContents)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.sessionNameLineEdit.setFont(font)
        self.sessionNameLineEdit.setMaxLength(12)
        self.sessionNameLineEdit.setObjectName("sessionNameLineEdit")
        self.formLayout_2.setWidget(2, QtWidgets.QFormLayout.FieldRole, self.sessionNameLineEdit)
        self.scrollArea.setWidget(self.scrollAreaWidgetContents)
        self.rootHorizontalLayout.addWidget(self.scrollArea)
        self.middleVerticalLine = QtWidgets.QFrame(self.centralwidget)
        self.middleVerticalLine.setFrameShape(QtWidgets.QFrame.VLine)
        self.middleVerticalLine.setFrameShadow(QtWidgets.QFrame.Raised)
        self.middleVerticalLine.setLineWidth(2)
        self.middleVerticalLine.setMidLineWidth(0)
        self.middleVerticalLine.setObjectName("middleVerticalLine")
        self.rootHorizontalLayout.addWidget(self.middleVerticalLine)
        self.rightSide = QtWidgets.QVBoxLayout()
        self.rightSide.setObjectName("rightSide")
        self.graphButtonLayout = QtWidgets.QHBoxLayout()
        self.graphButtonLayout.setObjectName("graphButtonLayout")
        self.lockButton = QtWidgets.QPushButton(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.lockButton.sizePolicy().hasHeightForWidth())
        self.lockButton.setSizePolicy(sizePolicy)
        self.lockButton.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.lockButton.setText("")
        icon = QtGui.QIcon()
        icon.addPixmap(QtGui.QPixmap("Images/Unlocked Button.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.lockButton.setIcon(icon)
        self.lockButton.setIconSize(QtCore.QSize(100, 75))
        self.lockButton.setObjectName("lockButton")
        self.graphButtonLayout.addWidget(self.lockButton)
        self.playButton = QtWidgets.QPushButton(self.centralwidget)
        self.playButton.setEnabled(False)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.playButton.sizePolicy().hasHeightForWidth())
        self.playButton.setSizePolicy(sizePolicy)
        self.playButton.setFocusPolicy(QtCore.Qt.StrongFocus)
        self.playButton.setAutoFillBackground(False)
        self.playButton.setText("")
        icon1 = QtGui.QIcon()
        icon1.addPixmap(QtGui.QPixmap("Images/Play Button.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.playButton.setIcon(icon1)
        self.playButton.setIconSize(QtCore.QSize(100, 75))
        self.playButton.setCheckable(False)
        self.playButton.setObjectName("playButton")
        self.graphButtonLayout.addWidget(self.playButton)
        spacerItem7 = QtWidgets.QSpacerItem(75, 10, QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Minimum)
        self.graphButtonLayout.addItem(spacerItem7)
        self.stopButton = QtWidgets.QPushButton(self.centralwidget)
        self.stopButton.setEnabled(False)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Preferred)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.stopButton.sizePolicy().hasHeightForWidth())
        self.stopButton.setSizePolicy(sizePolicy)
        self.stopButton.setFocusPolicy(QtCore.Qt.ClickFocus)
        self.stopButton.setText("")
        icon2 = QtGui.QIcon()
        icon2.addPixmap(QtGui.QPixmap("Images/Stop Button.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off)
        self.stopButton.setIcon(icon2)
        self.stopButton.setIconSize(QtCore.QSize(100, 75))
        self.stopButton.setObjectName("stopButton")
        self.graphButtonLayout.addWidget(self.stopButton)
        spacerItem8 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.graphButtonLayout.addItem(spacerItem8)
        self.sessionInfoLabel = QtWidgets.QLabel(self.centralwidget)
        font = QtGui.QFont()
        font.setPointSize(16)
        font.setBold(True)
        font.setWeight(75)
        self.sessionInfoLabel.setFont(font)
        self.sessionInfoLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.sessionInfoLabel.setObjectName("sessionInfoLabel")
        self.graphButtonLayout.addWidget(self.sessionInfoLabel)
        spacerItem9 = QtWidgets.QSpacerItem(40, 20, QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Minimum)
        self.graphButtonLayout.addItem(spacerItem9)
        spacerItem10 = QtWidgets.QSpacerItem(20, 100, QtWidgets.QSizePolicy.Minimum, QtWidgets.QSizePolicy.Fixed)
        self.graphButtonLayout.addItem(spacerItem10)
        self.rightSide.addLayout(self.graphButtonLayout)
        self.horizontalLine = QtWidgets.QFrame(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Fixed)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.horizontalLine.sizePolicy().hasHeightForWidth())
        self.horizontalLine.setSizePolicy(sizePolicy)
        self.horizontalLine.setFrameShape(QtWidgets.QFrame.HLine)
        self.horizontalLine.setFrameShadow(QtWidgets.QFrame.Sunken)
        self.horizontalLine.setObjectName("horizontalLine")
        self.rightSide.addWidget(self.horizontalLine)
        self.graphWidget = GraphicsLayoutWidget(self.centralwidget)
        sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Preferred, QtWidgets.QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.graphWidget.sizePolicy().hasHeightForWidth())
        self.graphWidget.setSizePolicy(sizePolicy)
        self.graphWidget.setObjectName("graphWidget")
        self.rightSide.addWidget(self.graphWidget)
        self.rootHorizontalLayout.addLayout(self.rightSide)
        MainWindow.setCentralWidget(self.centralwidget)
        self.menubar = QtWidgets.QMenuBar(MainWindow)
        self.menubar.setGeometry(QtCore.QRect(0, 0, 1324, 37))
        font = QtGui.QFont()
        font.setPointSize(14)
        self.menubar.setFont(font)
        self.menubar.setObjectName("menubar")
        self.menuFile = QtWidgets.QMenu(self.menubar)
        self.menuFile.setObjectName("menuFile")
        self.menuEdit = QtWidgets.QMenu(self.menubar)
        self.menuEdit.setObjectName("menuEdit")
        MainWindow.setMenuBar(self.menubar)
        self.statusbar = QtWidgets.QStatusBar(MainWindow)
        self.statusbar.setObjectName("statusbar")
        MainWindow.setStatusBar(self.statusbar)
        self.actionOpen = QtWidgets.QAction(MainWindow)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.actionOpen.setFont(font)
        self.actionOpen.setObjectName("actionOpen")
        self.actionPrint = QtWidgets.QAction(MainWindow)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.actionPrint.setFont(font)
        self.actionPrint.setObjectName("actionPrint")
        self.actionClose = QtWidgets.QAction(MainWindow)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.actionClose.setFont(font)
        self.actionClose.setObjectName("actionClose")
        self.actionDisplaySettings = QtWidgets.QAction(MainWindow)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.actionDisplaySettings.setFont(font)
        self.actionDisplaySettings.setObjectName("actionDisplaySettings")
        self.actionScreenCapture = QtWidgets.QAction(MainWindow)
        font = QtGui.QFont()
        font.setPointSize(14)
        self.actionScreenCapture.setFont(font)
        self.actionScreenCapture.setObjectName("actionScreenCapture")
        self.menuFile.addAction(self.actionOpen)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionScreenCapture)
        self.menuFile.addAction(self.actionPrint)
        self.menuFile.addSeparator()
        self.menuFile.addAction(self.actionClose)
        self.menuEdit.addAction(self.actionDisplaySettings)
        self.menubar.addAction(self.menuFile.menuAction())
        self.menubar.addAction(self.menuEdit.menuAction())

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)
        MainWindow.setTabOrder(self.sessionNameLineEdit, self.subjectAgeSpinBox)
        MainWindow.setTabOrder(self.subjectAgeSpinBox, self.subjectSexComboBox)
        MainWindow.setTabOrder(self.subjectSexComboBox, self.sampleIntervalSpinBox)
        MainWindow.setTabOrder(self.sampleIntervalSpinBox, self.trialCountSpinBox)
        MainWindow.setTabOrder(self.trialCountSpinBox, self.itiSpinBox)
        MainWindow.setTabOrder(self.itiSpinBox, self.itiVarianceSpinBox)
        MainWindow.setTabOrder(self.itiVarianceSpinBox, self.trialDurationSpinBox)
        MainWindow.setTabOrder(self.trialDurationSpinBox, self.baselineDurationSpinBox)
        MainWindow.setTabOrder(self.baselineDurationSpinBox, self.csNameLineEdit)
        MainWindow.setTabOrder(self.csNameLineEdit, self.csDurationSpinBox)
        MainWindow.setTabOrder(self.csDurationSpinBox, self.interstimulusIntervalSpinBox)
        MainWindow.setTabOrder(self.interstimulusIntervalSpinBox, self.usNameLineEdit)
        MainWindow.setTabOrder(self.usNameLineEdit, self.usDurationSpinBox)
        MainWindow.setTabOrder(self.usDurationSpinBox, self.lockButton)
        MainWindow.setTabOrder(self.lockButton, self.playButton)

        #Set up the input manager
        import InputManager as im
        im.initialSetUp(self, icon1, icon)

        #Set up the graph
        import TheGraph as tg
        tg.initialSetUp(self)
        
        #Complete set up of the main window (this file)
        self.subjectSexComboBox.addItem("MALE")
        self.subjectSexComboBox.addItem("FEMALE")
Exemplo n.º 42
0
def createTrialGraph(editStatus=True):

    #Variables that persist outside this function call
    global iteration, curve, trialGraph, dataSize, data, graphInitialized, done, previousITI

    #Start with clean slate before we do anything
    graphWindow.clear()

    #Set background color
    graphWindow.setBackground(backgroundColor)

    if editStatus:
        #Update the session info label in the main window to reflect trial number
        im.updateSessionInfoLabel()

        #Create data array (this array will be displayed as the line on the graph)
        dataSize = ts.currentSession.trialLengthInSamples  #Array size
        data = np.full(
            shape=dataSize, fill_value=-5,
            dtype=np.float32)  #initialized to -5 (so they're off-screen)

    #Create empty graph
    trialGraph = graphWindow.addPlot()

    #Plot line in graph
    if dsm.shading:
        curve = trialGraph.plot(y=data, fillLevel=-0.3, brush=dataColor)
    else:
        curve = trialGraph.plot(y=data, fillLevel=-0.3, pen=dataColor)

    #Add graph labels
    trialGraph.setLabel(
        'bottom', "<span style = \"color: " + htmlColorString(textColor) +
        "; font-size:18px\">Time (ms)</span>")
    trialGraph.setLabel(
        'left', "<span style = \"color: " + htmlColorString(textColor) +
        "; font-size:18px\">Response Amplitude (VDC)</span>")

    #Axis line/tick color
    trialGraph.getAxis('bottom').setPen(axisColor)
    trialGraph.getAxis('left').setPen(axisColor)

    #Axis limits on graph
    trialGraph.setLimits(xMin=0,
                         xMax=dataSize,
                         yMin=0,
                         yMax=5,
                         minXRange=10,
                         minYRange=5)

    #Scale x axis ticks to measure milliseconds instead of samples
    trialGraph.getAxis('bottom').setScale(ts.currentSession.sampleInterval)

    #Removes default "A" button on bottom left corner used for resetting the zoom on the graph
    trialGraph.hideButtons()

    #Disables the context menu you see when right-clicking on the graph
    trialGraph.setMenuEnabled(False)

    #Determine what stimuli (CS and/or US) the trial has
    if ts.currentSession.paradigm == ts.Paradigm.PSEUDO:
        hasCS = ts.currentSession.pseudoTrialOrdering[
            ts.currentSession.currentTrial - 1]
        hasUS = not hasCS
    else:
        hasCS = True
        hasUS = ts.currentSession.usStartInSamples >= 0

    #Create CS lines and shaded area between lines
    if hasCS:
        csStart = ts.currentSession.csStartInSamples
        csEnd = ts.currentSession.csEndInSamples
        csRegion = pg.LinearRegionItem(values=[csStart, csEnd],
                                       brush=stimulusColor,
                                       movable=False)
        csRegion.lines[0].setPen(stimulusColor)
        csRegion.lines[1].setPen(stimulusColor)
        trialGraph.addItem(csRegion)

    #Same for US
    if hasUS:
        usStart = ts.currentSession.usStartInSamples
        usEnd = ts.currentSession.usEndInSamples
        usRegion = pg.LinearRegionItem(values=[usStart, usEnd],
                                       brush=stimulusColor,
                                       movable=False)
        usRegion.lines[0].setPen(stimulusColor)
        usRegion.lines[1].setPen(stimulusColor)
        trialGraph.addItem(usRegion)

    #Add CS and US text labels
    stimulusTicks = []
    if hasCS:
        stimulusTicks.append(((csStart + csEnd) / 2, "CS"))
    if hasUS:
        stimulusTicks.append(((usStart + usEnd) / 2, "US"))
    trialGraph.getAxis('top').setTicks([stimulusTicks])
    trialGraph.getAxis('top').setTickFont(im.popUpFont)
    trialGraph.getAxis('top').setHeight(-5)
    trialGraph.showAxis('top', True)
    trialGraph.getAxis('top').setPen(axisColor)

    #Launch graph based on play mode
    if im.playMode == im.PlayMode.PLAYBACK:

        #Update graph with array of samples for trial
        data = JSONConverter.openTrial()
        curve.setData(data)

        #Render onset arrows
        onsets = JSONConverter.getOnsets()
        for x in range(len(onsets)):
            addArrow(onsets[x] - 1)

        #Render offset arrows
        if (dsm.renderOffset):
            offsets = JSONConverter.getOffsets()
            for x in range(len(offsets)):
                addArrow(offsets[x] - 1, False)

    #Data Acquisition
    else:

        if editStatus:
            #Regularly sample data (according to sample rate defined in session settings)
            iteration = 0
            if ts.currentSession.currentTrial == 1:
                tco.orderToStartSession()
                previousITI = 0  #First trial's previous ITI is 0

            #Regularly update display (according to display rate defined in display settings)
            displayTimer.start(1000 / dsm.displayRate)
        else:
            displayTimer.setInterval(1000 / dsm.displayRate)

    #Done initializing/creating/launching the graph
    if editStatus:
        done = False  #As in done with session, which we are not (we are just starting the session!!!)
        graphInitialized = True
Exemplo n.º 43
0
    def update(self, entity, interval):
        if entity.stunTimeout > 0:
            entity.state = 5
            entity.sAnim = 0
            if entity.isGrounded:
                entity.velx = 0
        else:
            if InputManager.getPressed("attack1") and not entity.isAttacking:
                if entity.equipType == CAttach.ZORD:
                    entity.state = 4
                    entity.sAnim = 0
                    entity.asAnimEnd = 2
                elif entity.equipType == CAttach.BOW and\
                        self.bowCooldown == 0.0:
                    entity.state = 3
                    entity.sAnim = 0
                    entity.asAnimEnd = 2

                    aimg = ImageManager.levelRes["player"]["Arrow.png"]
                    if entity.faceRight:
                        vel = Globals.ARROW_VELOCITY
                    else:
                        vel = -Globals.ARROW_VELOCITY
                        aimg = pygame.transform.flip(aimg, True, False)
                    arrow = Entity.Entity()
                    arrow.componentList.append(CPhysics.CPhysics())
                    arrow.componentList.append(CCollision.CCollision())
                    arrow.componentList.append(CProjectile.CProjectile(
                        aimg,
                        (entity.posx + 3.0, entity.posy + 60.0),
                        (vel, -5.0),
                        (0.0, 9.0),
                        Globals.ARROW_HITS))
                    arrow.componentList.append(
                        CDamage.CDamage(Globals.ARROW_DAMAGE))
                    arrow.initialize()
                    World.groups["pProjectile"].add(arrow)
                    self.bowCooldown = Globals.BOW_COOLDOWN
                entity.isAttacking = True
            if InputManager.getAction("left"):
                entity.velx = - MOVE_AMOUNT
                if entity.isGrounded and not entity.isAttacking:
                    entity.state = 1
                entity.faceRight = False
            elif InputManager.getAction("right"):
                entity.velx = MOVE_AMOUNT
                if entity.isGrounded and not entity.isAttacking:
                    entity.state = 1
                entity.faceRight = True
            elif not entity.isAttacking:
                entity.velx = 0
                if entity.isGrounded:
                    entity.state = 0
            if InputManager.getPressed("jump") and\
                    entity.isGrounded and not entity.isAttacking:
                entity.vely = - Globals.PLAYER_JUMP
                entity.isGrounded = False
                entity.state = 2
            if InputManager.getPressed("sword"):
                World.groups["equipment"].empty()

                zord = Entity.Entity()
                zord.componentList.append(CAnimation.CAnimation(
                    ImageManager.levelRes["player"]["Zord_Spritesheet.png"],
                    6, 6, 0, 0))
                zord.componentList.append(CPhysics.CPhysics())
                zord.accy = 0
                zord.componentList.append(CAttach.CAttach(entity, 53))
                World.groups["equipment"].add(zord)
                zord.initialize()
            elif InputManager.getPressed("bow"):
                World.groups["equipment"].empty()

                bow = Entity.Entity()
                bow.componentList.append(CAnimation.CAnimation(
                    ImageManager.levelRes[
                        "player"]["BowArrow_Spritesheet.png"],
                    6, 6, 0, 0))
                bow.componentList.append(CPhysics.CPhysics())
                bow.accy = 0
                bow.componentList.append(
                    CAttach.CAttach(entity, 28, CAttach.BOW))
                World.groups["equipment"].add(bow)
                bow.initialize()
        self.bowCooldown -= interval
        if self.bowCooldown < 0.0:
            self.bowCooldown = 0.0
Exemplo n.º 44
0
def reAnalyze():

    #Save the values that the user entered in the analysis settings window
    overwrite = windowWrapper.radioButton_Overwrite.isChecked()
    newFile = windowWrapper.radioButton_GenerateNew.isChecked()
    customName = windowWrapper.lineEdit_customSaveName.text()
    stdDevNumber = windowWrapper.spinBox_StdDev.value()
    minDuration = windowWrapper.spinBox_MinDuration.value()
    minVoltage = windowWrapper.spinBox_MinVoltage.value()

    nameError = False

    #Check to see if the user is saving with a valid file name
    if not overwrite or newFile:
        if ("\\" in customName or "/" in customName or ":" in customName
                or "<" in customName or ">" in customName or "*" in customName
                or "?" in customName or "\"" in customName
                or "|" in customName):
            nameError = True
            invalidSettingsNotice = QMessageBox()
            invalidSettingsNotice.setText(
                "Filename may not contain any of the following characters: \\ / : * ? \" < > |\n"
            )
            invalidSettingsNotice.setWindowTitle("Invalid Filename")
            invalidSettingsNotice.setStandardButtons(QMessageBox.Ok)
            invalidSettingsNotice.setIcon(QMessageBox.Warning)
            invalidSettingsNotice.setFont(im.popUpFont)
            invalidSettingsNotice.exec()
            return

    #Remember current trial that is open
    currentTrial = ts.currentSession.currentTrial

    #Remove '.json' if the user put it in the custom name
    if ".json" in customName:
        customName = customName.replace(".json", "")

    #Create JSON object
    fileCopy = jsCon.jsonObject

    #Update the threshold parameters
    fileCopy["header"]["thresholdSD"] = stdDevNumber
    fileCopy["header"]["thresholdMinDuration"] = minDuration
    fileCopy["header"]["minVoltage"] = minVoltage

    #Go through all of the trials, calculate the new stats, and store the newly generated data
    numTrials = int(fileCopy["header"]["trialCount"])
    for x in range(numTrials):
        fileCopy["trials"][x]["stats"] = da.getTrialStats(
            minVoltage, stdDevNumber, minDuration,
            fileCopy["trials"][x]["samples"])

    #Convert the saved data to a JSON readable format
    fileString = json.dumps(fileCopy)

    #Open the old file
    oldFileName = jsCon.getCurrentFilename()

    #Replace oldFilename with customName (should be the same if 'Overwrite Current File' is enabled)
    newFilename = jsCon.saveFilename.replace(oldFileName, customName)

    #Open the file, write the json data, then close the file
    saveFile = open(newFilename, "w")
    saveFile.write(fileString)
    saveFile.close()

    #Open the newly created session
    im.openSession(newFilename)
    im.loadTrial(currentTrial)
    if not nameError:
        closeWindow()
Exemplo n.º 45
0
 def imp_command(self, command_name, pyfile):
     print('Please enter a description for "{}" command.'.format(
         command_name))
     cmd_des = input('>>>') + ' '
     e = InputManager.imp_cmd(command_name, pyfile, cmd_des)
     return e
Exemplo n.º 46
0
class App:
    application = None

    def __init__(self):
        application = self

        #global initialization
        pyxel.init(255, 255, caption="Nearym Quest", scale=3)
        self.debugOverlay = False
        self.camera = Camera()
        self.streamingArea = Box()
        self.streamingArea.size = Vector2f(512, 512)
        self.streamingArea.center = Vector2f(0, 0)
        self.renderer = Renderer()
        self.physics = Physics()
        random.seed(0)

        # Event Manager
        self.inputManager = InputManager()
        self.inputManager.addInput(
            Input(InputType.BUTTON, InputNotify.PRESSED, [pyxel.KEY_F1],
                  'debug'))

        # world and player
        self.LoadMap()

        self.draw_count = 0

        # has to be completely at the end of init
        pyxel.run(self.update, self.draw)
        #pyxel.run_with_profiler(self.update, self.draw)

    def update(self):
        start = time.time()
        self.inputManager.update()
        self.camera.center = self.player.center
        self.streamingArea.center = self.player.center
        self.world.updateRegions(
            self.streamingArea, self.streamingArea.inflated(Vector2f(100,
                                                                     100)))

        if self.inputManager.CheckInputTrigger('debug'):
            self.debugOverlay = not self.debugOverlay

        deadEntities = []
        for entity in self.world.scriptedEntities:
            if not self.world.isValidEntity(entity):
                deadEntities.append(entity)
                continue
            scripts = entity.getComponent('Scripts')
            if scripts:
                for s in scripts:
                    s.update()
        for e in deadEntities:
            self.world.removeEntity(e)
            self.world.removeDynamicEntity(e)
            self.world.removeScriptedEntity(e)

        # physics
        if self.debugOverlay:
            self.physics.renderer = self.renderer
        else:
            self.physics.renderer = None
        self.physics.specialEntity = self.player
        self.physics.update(self.world)

        self.world.updateLoading()

        #print(math.floor(1000*(time.time() - start)))

    def draw(self):
        # clear the scene
        pyxel.cls(Color.Black)
        self.renderer.resetStat()

        #debug overlay or standard rendering
        if self.debugOverlay:
            self.renderer.renderTileMap(self.camera, self.world, 16)
            self.renderer.renderColliderOverlay(self.camera, self.world)
            self.renderer.renderFlagOverlay(self.camera, self.world)
        else:
            self.renderer.renderTileMap(self.camera, self.world)

        # same for entities
        self.renderer.renderEntities(self.camera, self.world)

        self.renderer.drawGizmos(self.camera)
        if self.debugOverlay:
            for r in self.world.querryRegions(
                    Box(self.player.position, self.player.size)):
                self.world.regions[r].quadtree.draw(self.camera, Color.Red)
            self.renderer.renderEntitiesPivot(self.camera, self.world)
            self.renderer.renderEntitiesColliders(self.camera, self.world)

        #debug hud overlay
        if self.debugOverlay:
            self.drawDebugHUD()
        self.renderer.gizmos.clear()

        #print("dynamic : " + str(len(self.world.dynamicEntities)) + " ; scripted : " + str(len(self.world.scriptedEntities)))

    def LoadMap(self):
        # load world
        self.world = World(Vector2i(257, 257))
        Entity.WORLD = self.world
        self.world.loadBanks("ressources/map3tileset.json",
                             'ressources/animationBank.json', 0, 0)
        self.world.updateRegions(self.streamingArea, self.streamingArea)
        while len(self.world.loadingJobs):
            self.world.updateLoading()

        self.player = self.world.factory.instanciate("player")
        #self.player.addComponent('Scripts', [PlayerController()])
        self.player.position = self.streamingArea.center

        entitiesCount = 0
        for i in range(-3, 4):
            for j in range(-3, 4):
                continue

                if i == 0 and j == 0:
                    continue
                dog = self.world.factory.instanciate("wolf")
                dog.position = self.player.position + Vector2f(32 * i, 32 * j)
                dog.getComponent('Scripts')[0].target = self.player
                self.world.addEntity(dog)
                entitiesCount += 1

        self.player.position = self.streamingArea.center - Vector2f(6, 2)
        self.world.addEntity(self.player)
        print("Entities count " + str(entitiesCount + 1))

    def drawDebugHUD(self):
        # player position
        pyxel.rect(32, 236, 74, 245, 6)
        pyxel.rectb(32, 236, 74, 245, 5)
        pyxel.text(35, 238, 'position', 0)

        pyxel.rect(32, 246, 128, 254, 6)
        pyxel.rectb(32, 246, 128, 254, 5)
        pyxel.text(
            35, 248,
            str(
                Vector2f(
                    math.floor(10 * self.player.position.x) / 10.0,
                    math.floor(10 * self.player.position.y) / 10.0)), 0)

        # player actual region
        pyxel.rect(212, 236, 254, 245, 6)
        pyxel.rectb(212, 236, 254, 245, 5)
        pyxel.text(216, 238, 'region', 0)

        pyxel.rect(160, 246, 254, 254, 6)
        pyxel.rectb(160, 246, 254, 254, 5)

        region = self.world.querryRegions(Box(self.player.center))[0]

        regionPos = Vector2i(math.floor(region / self.world.regionsArray.y),
                             region % int(self.world.regionsArray.y))
        pyxel.text(164, 248, str(region) + ' : ' + str(regionPos), 0)

        # rendering statistics
        pyxel.rect(212, 0, 254, 8, 6)
        pyxel.rectb(212, 0, 254, 8, 5)
        pyxel.text(216, 2, 'rendering', 0)

        pyxel.rect(196, 9, 254, 17, 6)
        pyxel.rectb(196, 9, 254, 17, 5)
        pyxel.text(200, 11, 'tiles ' + str(self.renderer.tileDrawn), 0)

        pyxel.rect(196, 18, 254, 26, 6)
        pyxel.rectb(196, 18, 254, 26, 5)
        pyxel.text(200, 20, 'sptites ' + str(self.renderer.entitiesDrawn), 0)

        pyxel.rect(196, 27, 254, 35, 6)
        pyxel.rectb(196, 27, 254, 35, 5)
        pyxel.text(200, 29, 'total ' + str(self.renderer.primitiveDrawn), 0)
Exemplo n.º 47
0
def run(profName=""):
    global profile
    global inputFaker
    global bciDevice
    global keycodelistlabels
    global current
    global fannToOutputApp
    global ann
    inputFaker = OutputManager.InputFaker()
    if inputFaker == -1:
        print "Import-Error: You need either Win32con (Windows) or XLib (Linux, Mac)"
    else:
        profilefile = "" 
        keycodelistlabels = sorted(["Action: "+each for each in inputFaker.actions.keys()])
        if (profName==""):
            if len(sys.argv)<2:
                path = os.getcwd()
                fileList = os.listdir(path)
                profileList = []
                for fileName in fileList:
                    if fileName[-7:] == "profile":
                        profileList.append(fileName[:-8])
                if len(profileList) > 0:
                    profilefile = str(WXElements.selection("Select your Profile",profileList[0], profileList))
                else:
                    print "Error: no profiles found"
            else:
                profilefile = sys.argv[1]
    
            if len(profilefile)==0:
                print "Error: no profile name given.\nExample: python nia-Triathlon-Player.py myProfile"
            else:
                if len(profilefile)==0:
                    profilefile = sys.argv[1] 
                profileLoaded = False
                netLoaded = False
                if os.path.exists(profilefile+".profile"):
                    workfile = open(profilefile+".profile", "r")
                    profile = pickle.load(workfile)
                    workfile.close()
                    profileLoaded = True
                else:
                    print "no "+profilefile+".profile"+" file found"
                ann = libfann.neural_net()
                if os.path.exists(profilefile+".net"):
                    ann.create_from_file(profilefile+".net")
                    netLoaded = True
                else:
                    print "no "+profilefile+".net"+" file found"
                if (profileLoaded and netLoaded):
                    bciDevice =  InputManager.BCIDevice(profile.deviceName)
                    current = Current_Data()
                    fannToOutputApp = FannToOutputApp()
                    fannToOutputApp.MainLoop()
                    bciDevice.quit()
                else:
                    print "Cannot start without .profile and .net files"
        else:
            profilefile=profName
            workfile = open(profilefile+".profile", "r")
            profile = pickle.load(workfile)
            workfile.close()
            ann = libfann.neural_net()
            ann.create_from_file(profilefile+".net")
            bciDevice =  InputManager.BCIDevice(profile.deviceName)
            current = Current_Data()
            fannToOutputApp = FannToOutputApp()
            fannToOutputApp.MainLoop()
            bciDevice.quit()
Exemplo n.º 48
0
    app = QtWidgets.QApplication(sys.argv)

    #Removes the "?" button from all windows
    #QtWidgets.QApplication.setAttribute(Qt.AA_DisableWindowContextHelpButton)

    #Create and set up the main window
    MainWindow = QtWidgets.QMainWindow()
    ui = mw.Ui_MainWindow()
    ui.setupUi(MainWindow)

    #If there's an error in the main process, we need special error handling to close the child process (the sampling process), so it doesn't become a zombie.
    sys.excepthook = mainProcessErrorHandler

    #Perform all necessary set up including launching the time critical (sampling) process
    #Comments on side indicate dependencies in ordering of start up calls
    dsm.initialSetUp()
    im.initialSetUp(ui)
    tg.initialSetUp(ui)  #Uses DSM and IM
    jc.initialSetUp(ui)
    tco.initialSetUp()

    #Start of program
    MainWindow.show()
    app.exec_()  #Run the main Qt Event loop (for listening to UI input)

    #Make sure the sampling process terminates
    tco.orderToStopProcess()

    #Exit program with no errors
    sys.exit(0)
Exemplo n.º 49
0
    elif GameState.s.getPickedUpPiece()=="kingwhite":
        piece = pygame.image.load("kingwhite.png").convert_alpha()
        window.blit(piece,(posx,posy))



#Event Loop
while done == False:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
        if event.type == pygame.MOUSEBUTTONDOWN:
            pos = pygame.mouse.get_pos()
            
            InputManager.dispatch(pos)
            
            
            

    Board.drawBoard(window)
    
# If gamestate is 0, we will call drawSetup    
    if GameState.s.getGameState() == 0:
        Menu.drawSetup(window)
# if gamestate is 1, we will call drawCustomSetup
    elif GameState.s.getGameState() == 1:
        Menu.drawCustomSetup(window)
# if gamestate is 2, we will call drawGame
    elif GameState.s.getGameState() == 2:
        Menu.drawGame(window)
Exemplo n.º 50
0
def InitLoopManager(cScene):
    # Create cSM wrapper
    cSM = pylSoundManager.SoundManager(cScene.GetSoundManagerPtr())

    # Create the states (these three sequences are common to all)
    lSeq_chSustain = LoopSequence('chSustain', [
        Loop('chSustain1', 'chSustain1_head.wav', 5, 1., 'chSustain1_tail.wav')
    ])
    lSeq_bass = LoopSequence(
        'bass', [Loop('bass', 'bass1_head.wav', 5, 1., 'bass1_tail.wav')])
    lSeq_drums = LoopSequence(
        'drums', [Loop('drum1', 'drum1_head.wav', 5, 1., 'drum1_tail.wav')])

    # State 1 just plays lead1, lead2, lead1, lead2...
    s1 = DrawableLoopState(
        'One', {
            lSeq_chSustain, lSeq_bass, lSeq_drums,
            LoopSequence('lead', [
                Loop('lead1', 'lead1.wav'),
                Loop('lead2', 'lead2_head.wav', 5, 1., 'lead2_tail.wav')
            ], itertools.cycle)
        })

    # State 2 just plays lead3, lead4, lead3, lead4...
    s2 = DrawableLoopState(
        'Two', {
            lSeq_chSustain, lSeq_bass, lSeq_drums,
            LoopSequence(
                'lead',
                [Loop('lead3', 'lead3.wav'),
                 Loop('lead4', 'lead4.wav')], itertools.cycle)
        })

    # State 3 plays lead5, lead6, lead7, lead7...
    s3 = DrawableLoopState(
        'Three', {
            lSeq_chSustain, lSeq_bass, lSeq_drums,
            LoopSequence('lead', [
                Loop('lead5', 'lead5.wav'),
                Loop('lead6', 'lead6.wav'),
                Loop('lead7', 'lead7.wav'),
                Loop('lead7', 'lead7.wav')
            ], itertools.cycle)
        })

    s4 = DrawableLoopState('Four', {lSeq_bass, lSeq_drums})
    s5 = DrawableLoopState(
        'Five',
        {lSeq_bass,
         LoopSequence('drums2', [Loop('drum2', 'drum2.wav')])})

    # Store all nodes in a list
    nodes = [s1, s2, s3, s4, s5]

    # Create the directed graph; all nodes connect and self connect
    G = nx.DiGraph()
    G.add_edges_from(itertools.product(nodes, nodes))

    # The advance function just returns a random neighbor
    def fnAdvance(SG):
        # Cartesian product
        def dot(A, B):
            return sum(a * b
                       for a, b in itertools.zip_longest(A, B, fillvalue=0))

        # Return the target of the edge out of activeState whose pathVec is most in line with stim
        return max(SG.G.out_edges_iter(SG.activeState, data=True),
                   key=lambda edge: dot(SG.stim, edge[2]['pathVec']))[1]

    # Define the vectors between edges
    # (used during dot product calculation, SG.stim is one of these)
    diEdges = {n: [1 if n == nn else 0 for nn in nodes] for n in nodes}
    for n in nodes:
        for nn in G.neighbors(n):
            G[n][nn]['pathVec'] = diEdges[nn]

    # Construct the StateGraph with an attribute 'stim' of s1's stimulus,
    # as well as a reference to the scene, so the states can use it
    SG = StateGraph(G, fnAdvance, s1, stim=diEdges[s1], cScene=cScene)

    # Init audio spec
    if cSM.Configure({'freq': 44100, 'channels': 1, 'bufSize': 4096}) == False:
        raise RuntimeError('Invalid aud config dict')

    # Voices (anything that makes sound) need a unique int ID
    voiceID = 0
    diLoopToVoiceID = dict()

    # get the samples per mS
    sampPerMS = int(cSM.GetSampleRate() / 1000)

    # For each loop in the state's loop sequences
    for loopState in nodes:
        # The state's trigger res is its longest loop
        loopState.triggerRes = 0
        for lSeq in loopState.diLoopSequences.values():
            for l in lSeq.loops:
                # Set tailfile to empty string if there is None
                if l.tailFile is None:
                    l.tailFile = ''
                # Add the loop
                if cSM.RegisterClip(l.name, l.headFile, l.tailFile,
                                    int(sampPerMS * l.fadeMS)) == False:
                    raise IOError(l.name)

                # If successful, get a handle to c loop and store head/tail duration
                l.uNumHeadSamples = cSM.GetNumSamplesInClip(l.name, False)
                l.uNumTailSamples = cSM.GetNumSamplesInClip(
                    l.name, True) - l.uNumHeadSamples

                # The state's trigger res is its longest loop
                if l.uNumHeadSamples > loopState.triggerRes:
                    loopState.triggerRes = l.uNumHeadSamples

                # Give this loop a voice ID and inc
                if l not in diLoopToVoiceID.keys():
                    diLoopToVoiceID[l] = voiceID
                    voiceID += 1
                l.voiceID = diLoopToVoiceID[l]

    # This dict maps the number keys to edge vectors defined in diEdges
    # (provided there are less than 10 nodes...)
    # the edge vectors are used during state advancement for the graph
    diKeyToStim = {
        SDLK.SDLK_1 + i: diEdges[n]
        for i, n in zip(range(len(nodes)), nodes)
    }

    # The stimulus update function assigns the stim
    # member of the stategraph based on what the
    # button maps to in the dict
    def fnStimKey(btn, keyMgr):
        nonlocal diKeyToStim
        nonlocal SG
        if btn.code in diKeyToStim.keys():
            SG.stim = diKeyToStim[btn.code]

    liButtons = [Button(k, None, fnStimKey) for k in diKeyToStim.keys()]

    arpClip = Loop('arp', 'arplead1.wav', 5, 1., 'arplead1.wav')
    arpClip.voiceID = voiceID + 1
    if cSM.RegisterClip(arpClip.name, arpClip.headFile, arpClip.tailFile,
                        int(sampPerMS * arpClip.fadeMS)) == False:
        raise IOError(arpClip.name)

    # Hard coded test for now
    def fnOneShotKey(btn, keyMgR):
        nonlocal cSM
        nonlocal arpClip
        t = (arpClip.name, arpClip.voiceID, arpClip.vol,
             int(cSM.GetMaxSampleCount() / 4))
        cSM.SendMessage((pylSoundManager.CMDOneShot, t))

    liButtons.append(Button(SDLK.SDLK_f, None, fnOneShotKey))

    # The escape key callback tells the scene to quit
    def fnEscapeKey(btn, keyMgr):
        nonlocal cScene
        cScene.SetQuitFlag(True)

    liButtons.append(Button(SDLK.SDLK_ESCAPE, None, fnEscapeKey))

    # The space key callback tells the loop manager to play/pause
    def fnSpaceKey(btn, keyMgr):
        nonlocal cSM
        cSM.PlayPause()

    liButtons.append(Button(SDLK.SDLK_SPACE, None, fnSpaceKey))

    # Create the input manager (no mouse manager needed)
    inputManager = InputManager(cScene, KeyboardManager(liButtons),
                                MouseManager([]))

    # Create the sound manager
    loopManager = LoopManager(cScene, SG, inputManager)

    # Start the active loop seq
    activeState = loopManager.GetStateGraph().GetActiveState()
    messageList = [(pylSoundManager.CMDStartLoop, (l.name, l.voiceID, l.vol,
                                                   0))
                   for l in activeState.GetActiveLoopGen()]
    cSM.SendMessages(messageList)

    # return the sound manager
    return loopManager