Exemplo n.º 1
0
 def didClickSubmitButton(self, event):
     print(self.imageFilePath)
     img = img_as_ubyte(io.imread(CLUSTER_IMAGE_FILENAME))
     roi_img = spectral_roi.extract_roi(img, gui_checkbox_handlers.getSelectedClusters())
     roi_img_filename = "{}.png".format(Helper.generate_random_id())
     io.imsave(roi_img_filename, roi_img)
     Display.show_image(roi_img, roi_img_filename)
Exemplo n.º 2
0
def generate_music_list(softlist_xml_list):
    found_music = []

    selected_softlist_xml = None
    for softlist_xml in softlist_xml_list.findall('softwarelist'):
        if softlist_xml.attrib['name'] == "vgmplay":
            selected_softlist_xml = softlist_xml
            break

    found_qty = 0

    for soft_xml in selected_softlist_xml:
        item = FilterSoftware.get(soft_xml)
        if item is None:
            continue

        for part_xml in item.get_soft_xml().findall('part'):
            part_item = Item()
            part_item.set_soft_xml(item.get_soft_xml())
            part_item.set_part_xml(part_xml)
            found_music.append(part_item)

        if len(found_music) > found_qty + 1000:
            found_qty = len(found_music)
            Display.print_text("Found " + str(len(found_music)) + " musics")

    return found_music
Exemplo n.º 3
0
def get(soft_list_list):
    global item_list
    global first_pass
    if len(item_list) == 0:
        if first_pass is False and Config.auto_quit is True:
            return None
        first_pass = False

        item_list = CommandGeneratorMusic.generate_music_list(soft_list_list)
        Display.print_text("Found " + str(len(item_list)) + " musics")
        time.sleep(1.5)

    if len(item_list) == 0:
        return None

    if Config.linear is True:
        rand = 0
    else:
        rand = random.randrange(len(item_list))

    selected_item = item_list[rand]
    item_list.pop(rand)
    print(str(len(item_list)), "softwares left")

    return selected_item
Exemplo n.º 4
0
 def __init__(self):
     """ Creates display and initial menu """
     # nothing much to do here yet until display is better
     self.b = Board()
     self.d = Display(self.b)
     self.n = 0
     self.forced = False
Exemplo n.º 5
0
 def display(self):
     try:
         return self._display
     except AttributeError:
         self._display = Display()
         self._display.start()
         return self._display
Exemplo n.º 6
0
def parse_what(neurota, com_name, com):

	if len(com) != 4 or ':' not in com[3]:
  	  Tools.syntax_abort(neurota.args, "wrong # of commands in what statement",
    			                     "what is <attribute> of <topic:table>")
	elif com[2] != 'of':
  	  Tools.syntax_abort(neurota.args, "wrong # of commands in what statement",
    			                     "what is <attribute> of <topic:table>")		
  	else:
  		topic, table = Tools.split_topic(com[3])	
  		attribute = com[1]
    	if topic not in neurota.db.keys():
      		Tools.display("topic: %s not found!" % Tools.color(topic, "green"))
    	elif table not in neurota.db[topic].keys():
        	Tools.display("table: %s not found!" % Tools.color(table, "green"))
      	else:      		
      		found = False ; i = 0
        	for node in neurota.db[topic][table]:
        		if node.item == attribute:
        			max_len = len(node.item) ; found = True
        			Display.show_node(i, node, max_len, times=False, show_note=True)
        			break
        		i += 1
        	if not found:
        		Tools.display("%s not found!" % Tools.color(attribute, "green"))
def question(se, question):
    """
    question(search_engine, question)
    The function to generate result for a question
    """
    # Analyze the question in the query first
    term = Answer.get_term(question)
    author_query = Answer.get_query(term, 'author')
    business_person_query = Answer.get_query(term, 'business_person')

    # Queries for author and business person
    author_result = se.get_mql_result(author_query)
    if author_result is None:
        print 'Error in author search'
        return
    business_person_result = se.get_mql_result(business_person_query)
    if business_person_result is None:
        print 'Error in business person search'
        return

    # Extract and format the information
    author_answer = Answer.get_answer(author_result, 'author')
    business_person_answer = Answer.get_answer(business_person_result, 'business_person')
    author_answer.extend(business_person_answer)
    if author_answer is not None and len(author_answer) > 0:
        author_answer = sorted(author_answer, key=itemgetter(0))
        if not question.endswith('?'):
            question = question + '?'
        Display.draw_answer(author_answer, question)
    else:
        print 'There is no result for \'' + question + '\'!'
Exemplo n.º 8
0
 def __init__(self):
     self.display = Display()
     self.map_player = Map()
     self.needle = Item("needle", 4, self.map_player)
     self.map_player.put_item_on_map(self.needle)
     self.ether = Item("ether", 5, self.map_player)
     self.map_player.put_item_on_map(self.ether)
     self.tube = Item("tube", 6, self.map_player)
     self.map_player.put_item_on_map(self.tube)
     self.mac_gyver = Player(self.map_player)
     self.display.load_wall()
     self.display.load_ground()
     self.display.load_player_display()
     self.display.load_jailer()
     self.display.load_items()
     self.display.load_font()
     self.display.refresh(self.map_player, self.mac_gyver)
     self.display.show_inventory(self.mac_gyver)
     self.items_in_game = [self.needle, self.ether, self.tube]
     self.keyboard_list_movements = [
         pygame.K_UP, pygame.K_DOWN, pygame.K_LEFT, pygame.K_RIGHT
     ]
     self.keyboard_functions = [
         self.mac_gyver.move_up, self.mac_gyver.move_down,
         self.mac_gyver.move_left, self.mac_gyver.move_right
     ]
Exemplo n.º 9
0
    def move(self, board, n, newDisplay):
        """
		The main function for this class.  Returns the point the AI wants to move in.
		"""

        self.updateAll(board, n, newDisplay, -1000)

        # check for four in a row on both sides
        move = self.assuredMove()
        if self.decided:
            if move == False:
                print "Chris has been trying to recreate this bug for a while,"
                print "Please get all this info to him if possible."
                print "Moves: ", self.b.moveList
                print "Players: ", self.n, self.o
                print "Move, assured, decided, scared: ", move, self.assured, self.decided, self.scared
                print "Board:"
                newD = Display(self.b, [None], [None])
                newD.displayShittyBoard()
                print "Possible moves: ", self.moves

            return move

        move = self.weakLookAhead()

        return move
Exemplo n.º 10
0
def extract_roi(img, labels_to_keep=[1, 2]):
    '''
    Given a wheat image, this method returns an image containing only the region
    of interest.

    Args:
        img: input image.

        labels_to_keep: cluster labels to be kept in image while pixels
            belonging to clusters besides these ones are removed.

    Return:
        roi_img: Input image containing only the region
        of interest.
    '''
    label_img = segmentation.slic(img, compactness=30, n_segments=6)
    labels = np.unique(label_img)
    print(labels)
    gray = rgb2gray(img)

    for label in labels:
        if (label not in labels_to_keep):
            logicalIndex = (label_img == label)
            gray[logicalIndex] = 0

    Display.show_image(gray)
    return gray
def infobox(se, query):
    """
    infobox(search_engine, query)
    The function to generate infobox for the query
    """
    json = se.get_search_result(query)
    if json is None:
        print 'Error in search'
        return

    info_list = None

    for element in json:
        topic_id = element['mid']
        topic = se.get_topic_result(topic_id)
        if topic is None:
            continue

        # Parse and analyze the topic
        # Get out of the loop if the topic is valid
        # Otherwise, continue to check the next topic
        title = query.title()
        info_list = Analyser.build_infobox(topic, title)
        if len(info_list) > 0:  # Nonempty result
            # print info_list
            break

    if info_list is not None and len(info_list) > 0:
        Display.draw_infobox(info_list)
    else:
        print 'There is no result for \'' + query + '\'!'
Exemplo n.º 12
0
    def __init__(self, id=None, name=None, parent=None):
        Layout.Vertical.__init__(self, id, name, parent)
        self.addClass("WebElementActionBox")

        self.header = self.addChildElement(Display.Label())
        self.header.addClass("WebElementActionBoxHeader")

        self.actions = self.addChildElement(Display.List())
Exemplo n.º 13
0
	def __init__(self, isDisplay=True):
		self.__isDisplay = isDisplay
		if isDisplay:
			self.display = Display()
		self.genetic = Genetic()
		self.tetrisList = []
		self.population = []
		self.generation = 0
Exemplo n.º 14
0
 def list_drink(self):
     drink_items = []
     for key in self.items:
         obj = self.items[key]
         if type(obj) == type(Drink()):
             table_row = obj.list_for_table()
             drink_items.append(table_row)
     Display.table_to_console(self.table_header(), drink_items)
Exemplo n.º 15
0
 def onClickPesticide(self):
     arduinoControl.make_connection()
     #arduinoControl.kill_weeds()
     if arduinoControl.no_connection() is None:
         Display.displayWarning(self, 'Arduino was unable to initialize.')
         return
     self.log('Pesticide')
     arduinoControl.close_connection()
Exemplo n.º 16
0
class GFXEngine :

	"""
	This class draws the gfx
	"""

	def __init__ (self, lll, viewspace, mymap):
	
		self.lll = lll
		self.display = Display ()
		self.viewspace = viewspace
		self.mymap = mymap
		self.terrainset = TerrainSet ()
		
		# Test
		self.settsurf = Surface ()
		self.settsurf.loadFromFile ("gfx/protosettler.png")
		self.settsurf.cols = 16
		self.settsurf.rows = 16

		self.sprites = []
		
	def create_settler(self, x, y):
		""" Adds a settler to be drawn on the screen at position x, y and returns a reference to this settler. """

		sprite = Sprite (self.viewspace, self.settsurf)
		sprite.x = x
		sprite.y = y
		sprite.configAnimation (True, 0, 24, 25)
		self.sprites.append(sprite)
		return sprite

	
	def tick (self):
	
		"""
		tick() executes all actions which must be done by the GFX-Engine in one Game-Loop-cycle
		This is: clearing the screen, drawing all objects, showing the new game-frame
		"""
	
		self.display.clear ()
		self.draw ()
		for sprite in self.sprites:
			sprite.drawToDisplay (self.display)
		self.display.showFrame ()

	def draw (self):
	
		self.drawLandscape ()
	
	def drawLandscape (self):
	
		self.drawTerrain ()

	def drawTerrain (self):
	
		self.lll.view.DrawTerrain (self.mymap.terra.asCArray (), self.mymap.mapsize, TRIA_W, TRIA_H,
			TEX_FACTOR, self.terrainset.asCArray(), self.mymap.getVertarray().asCArray())
Exemplo n.º 17
0
def parse_search(neurota, com_name, com):

    # scan for optional keywords.  remove if found.

    times = Tools.scan_option("times", com)
    sort = Tools.scan_option("sort", com)

    if len(com) == 2 and com[0].find(':') != -1:
        topic, table = Tools.split_topic(com[0])
        pattern = com[1]
        if topic not in neurota.db.keys():
            Tools.display("topic: %s not found!" % Tools.color(topic, "green"))
        else:
            if table not in neurota.db[topic].keys():
                Tools.display("table: %s not found!" %
                              Tools.color(table, "green"))
            else:
                search_results = []

                # Search title and note of node for search term.
                # If found, highlight the search pattern.

                reg = re.compile(pattern, re.IGNORECASE)

                for node in neurota.db[topic][table]:

                    found_in_node = False
                    # This searches the title of the node.
                    if reg.search(node.item):
                        found_in_node = True
                        node.item = node.item.replace(
                            pattern, Tools.color(pattern, "green"))

                    # This searches the note of the node.
                    i = 0
                    for i in range(len(node.note)):
                        if reg.search(node.note[i]):
                            found_in_node = True
                            node.note[i] = node.note[i].replace(
                                pattern, Tools.color(pattern, "green"))

                    if found_in_node:
                        search_results.append(node)

                if len(search_results) == 0:
                    print
                    Tools.display("Search pattern: %s not found in:" % pattern)
                Display.show_table(topic, table, search_results, sort, times)

    elif len(com) == 2 and com[0] == 'topics':

        pattern = com[1]
        reg = re.compile(pattern, re.IGNORECASE)

        for k in neurota.db.keys():
            if reg.search(k):
                Display.show_topic(k)
Exemplo n.º 18
0
 def StringToType(argument):
     i = 1
     t = Display.TypeToString(i)
     while t is not None:
         if argument.strip().lower() == t.strip().lower():
             return i
         i += 1
         t = Display.TypeToString(i)
     return None
Exemplo n.º 19
0
def show_single_photo():
	if PhotoThread.photo_load_threads()[0].is_alive():
		Output.debug("PLT is still running. Sleeping 0.5s before trying again.")
		Display.root().after(500, show_single_photo)
		return
	Display.show_single_photo()
	Output.debug("Display.show_single_photo() returned")
	Settings.WAIT_FOR_BUTTON_PRESS = True
	Settings.ON_BUTTON_PRESS = lambda: Settings.main_script.start()
Exemplo n.º 20
0
 def _checkRoll(roll, key):
     updRoll = Game.randomRoll() if roll == None else int(roll)
     if updRoll < 1 or updRoll > 6:
         Display.error(
             f'{hl(key)} value {NOT} valid: {updRoll}. Must be between {hl(1)} and {hl(6)}'
         )
         return None
     else:
         return updRoll
Exemplo n.º 21
0
 def elmination(self):
     for player in self.players:
         if player.stack == 0:
             self.players.remove(player)
     if len(self.players) == 1:
         self.players[0].justWon = True
         Display.displayGameState(self)
         raw_input("Play again?")
         self.__init__(*newGameParams)
Exemplo n.º 22
0
 def do_move(self, arg):
     [player_name, roll1, roll2] = Commands._unpack(arg, 3)
     player_label = hl(player_name)
     if player_name in players:
         roll1 = Commands._checkRoll(roll1, 'roll1')
         roll2 = Commands._checkRoll(roll2, 'roll2')
         if roll1 is not None and roll2 is not None:
             Display.text(Game.action(player_name, roll1, roll2))
     else:
         Display.error(f'Player {player_label} {NOT} found')
Exemplo n.º 23
0
	def run(self):
		Output.debug("PhotoLoadThread " + str(self.index) + " starting...")
		# Load the photo
		Output.debug("PhotoLoadThread " + str(self.index) + ": Opening...")
		self.image = Image.open(self.filename)
		Output.debug("PhotoLoadThread " + str(self.index) + ": Fitting...")
		self.image = ImageOps.fit(self.image, (Display.image_size(self.fullsize), Display.image_size(self.fullsize)))
		Output.debug("PhotoLoadThread " + str(self.index) + ": TKing...")
		images()[self.index] = ImageTk.PhotoImage(self.image)
		Output.debug("PhotoLoadThread " + str(self.index) + " finished.")
Exemplo n.º 24
0
 def __init__(self, parent=None):
     super(self.__class__, self).__init__(parent)
     self.setupUi(self)
     self.centerOnScreen()
     self.BTN_SelFolder.clicked.connect(self.browse_folder)
     self.BTN_Process.clicked.connect(self.process_folder)
     self.actionAuthors.triggered.connect(self.show_authors)
     self.form2 = ProgressClass(self)
     self.form3 = Display(self)
     self.magic = magic.open(magic.MAGIC_MIME)
     self.magic.load()
Exemplo n.º 25
0
 def __init__(self):
     self.square = Square(SQUARE_X, SQUARE_Y, SQUARE_HEIGHT, SQUARE_WIDTH,
                          [0, 0], SQUARE_SPEED)
     self.missiles = []
     self.display = Display(SCREEN_WIDTH, SCREEN_HEIGHT)
     self.done_game = True
     self.done_all = False
     self.time_between_missiles = TIME_BETWEEN_MISSILES
     self.time_last_missile = 0
     self.score = 0
     self.client = Client()
Exemplo n.º 26
0
 def awardPot(self, winners):
     potSplit = self.pot / len(winners)
     potExtra = self.pot % len(winners)
     for winner in winners:
         winner.justWon = True
     Display.displayGameState(self)
     raw_input("Press ENTER to continue")
     for winner in winners:
         winner.justWon = False
         winner.stack += potSplit
     choice(winners).stack += potExtra
Exemplo n.º 27
0
def load_machine_list():
    Display.print_text("Get machines XML")

    file_name = get_listxml_file_name()

    if os.path.isfile(file_name) is False:
        print("Creating", file_name)
        fd = open(file_name, "w")
        subprocess.run([Config.mame_binary, '-listxml'],
                       stdout=fd)
    else:
        print(file_name, "already exists")
Exemplo n.º 28
0
def load_soft_list():
    Display.print_text("Get software list XML")

    file_name = get_softlist_file_name()

    if os.path.isfile(file_name) is False:
        print("Creating", file_name)
        fd = open(file_name, "w")
        subprocess.run([Config.mame_binary, '-getsoftlist'],
                       stdout=fd)
    else:
        print(file_name, "already exists")
Exemplo n.º 29
0
def extract_roi(img, labels_to_keep=[1,2]):
    label_img = segmentation.slic(img, compactness=30, n_segments=6)
    labels = np.unique(label_img);print(labels)
    gray = rgb2gray(img);

    for label in labels:
        if(label not in labels_to_keep):
            logicalIndex = (label_img == label)
            gray[logicalIndex] = 0;

    Display.show_image(gray)
    io.imsave("grayy.png", gray)
Exemplo n.º 30
0
    def __init__(self, id, name=None, parent=None):
        Layout.Vertical.__init__(self, id, name, parent=parent)

        self.inputContainer = self.addChildElement(Layout.Horizontal())

        self.label = self.inputContainer.addChildElement(Display.Label())
        self.fieldActions = self.inputContainer.addChildElement(Layout.Box())
        self.addChildElementsTo = self.fieldActions
        self.userInput = self.inputContainer.addChildElement(Base.Invalid())

        errorContainer = self.addChildElement(Layout.Horizontal())
        self.formError = errorContainer.addChildElement(
            Display.FormError(id, parent=self))
Exemplo n.º 31
0
def loose_search_machine_list(machine_list):
    new_machine_list = []

    for desc in Config.description:
        found_qty = 2

        for machine in machine_list:
            if exact_search_machine(machine, desc) is True:
                found_machine = machine
                found_qty = 1
                break

        # Trying to find a single machine matching the most word in Config.description
        desc_list = desc.split(' ')
        word_qty = 0

        while found_qty > 1:
            # Build a search string from words in Config.description starting from last word and adding the previous one by one.
            word_qty += 1

            if word_qty > len(desc_list):
                # Unable to find a single machine corresponding to all words in Config.description
                found_qty = 0
                break

            # s = ".*"
            s = ""
            for j in range(-word_qty, 0):
                s += desc_list[j]
                s += ' '

            # remove last ' '
            search_string = s[:-1]

            found_qty = 0

            for machine in machine_list:
                if loose_search_machine(machine, search_string) is True:
                    found_qty += 1
                    found_machine = machine
                    if found_qty > 1:
                        break

        if found_qty == 1:
            new_machine_list.append(found_machine)
            Display.print_text("Loose search find " +
                               str(len(new_machine_list)) + " machines")
        else:
            print("No loose match for", search_string)

    return new_machine_list
Exemplo n.º 32
0
 def newRound(self):
     self.deck = Deck.Deck()
     self.activePlayers = list(self.players)
     for player in self.activePlayers:
         player.hand = Deck.Hand(self.deck)
         player.active = True
         player.playerBet = 0
     self.pot = 0
     self.activeBet = 0
     self.phase = 0
     self.community = []
     self.roundOver = False
     Prediction.predictRound(self)
     Display.displayGameState(self)
Exemplo n.º 33
0
def add_next_tetromino(game):
    """ Attempts to add a new tetromino for a game. If the tetromino cannot be added then the game is over """
    global falling_tetrominoes
    global board
    new_tetromino = get_next_tetromino(game)
    falling_tetrominoes.append(new_tetromino)
    heuristic_queue.append(new_tetromino)
    if tetromino_collides(new_tetromino, board):
        return False  # Game over

    add_tetromino_to_display(new_tetromino)
    Display.update_display(board_display)

    return True
Exemplo n.º 34
0
    def __init__(self, id=None, name=None, parent=None):
        Layout.Vertical.__init__(self, id + "NestedSelect", name, parent)

        self.groupLabel = self.addChildElement(Display.Label())
        self.groupSelect = self.addChildElement(Inputs.Select(id))
        self.groupSelect.addJavascriptEvent(
            'onclick', CallBack(self, "jsPopulateItemSelect"))
        self.groupSelect.connect('selectionChanged', None, self, 'updateItems')

        self.itemLabel = self.addChildElement(Display.Label())
        self.itemSelect = self.addChildElement(Inputs.Select(id + "Items"))

        self.groups = []
        self.items = {}
Exemplo n.º 35
0
 def onClickWater(self):
     arduinoControl.make_connection()
     arduinoControl.ser.flushInput()
     arduinoControl.flush_read()
     #arduinoControl.water_cycle()
     arduinoControl.water()
     if arduinoControl.no_connection() is None:
         Display.displayWarning(self, 'Arduino was unable to initialize.')
         return
     arduinoControl.wait(1)
     start = time.time()
     while time.time() - start < 2:
         message = arduinoControl.read_message()
     self.log('Water')
     arduinoControl.close_connection()
Exemplo n.º 36
0
 def runSimulation(self):
     if len(self.networkFrames.getInputNetworks()) > 0:
         
         print "Recreating Input Network..."
         # Set the initial configuration
         start_frame = self.networkFrames.getInputNetworkAt(0)
         
         for iteration in range(self.iterations):
             print str(iteration+1),
             focus_frame = start_frame.copy()
             self.addGraphToSimulatedNetwork(focus_frame)
             attempt_data_display = Display.display(False)
             
             frame_number = 0
             while frame_number < len(self.networkFrames.getInputNetworks())-1:
                 rewriting_event = None
                 
                 attempts = 0
                 while rewriting_event is None:
                     extraction_subgraph = self.extraction.performExtraction(focus_frame)
                     rewriting_event = self.rewriting.performRewriting(extraction_subgraph)
                     attempts += 1
                 
                 attempt_data_display.addInputValue(attempts)
                 self.networkFrames._decompress(focus_frame, rewriting_event)
                 self.addGraphToSimulatedNetwork(focus_frame)
                 frame_number += 1
                 
             self.storeSimulatedNetwork()
             self.clearSimulatedNetwork()
             self.UESFrequencyList.append(copy.deepcopy(self.rewriting.getDisplayData()))
             self.rewriting.resetDataDisplay()
 
         print "Done."
         self.processSimulationData()
         print "UES Mean BD: " + str(self.UES_BDMean)
         print "UES Std BD: " + str(self.UES_BDStd)
         #self.meanNetwork.writeSpecificGraphs("generatedOutputMeanNetwork.graphML", self.meanNetwork.getDecompressedFrames())
         ues_display = Display.display(False)
         ues_display.addInputValues([], self.UESFrequencyList[0].getHistInputData())
         ues_display.addExperimentalValues([] ,self.UESMeanFrequencyList)
         ues_display.UESBarPlot('Unique Extraction Subgraph Comparison', 'Times Selected', 'Subgraph Groups', self.UESMeanFrequencyList, self.UESStdFrequencyList, self.UES_BDMean)
         self.bhattacharyyaDegreeDisplay.lineGraph("Bhattacharyya Distance - Cumulative Degree Distribution", "Time Step", "Bhattacharyya Distance", multiLine=True)
         self.cumulativeDegreeDist.lineGraph("Cumulative Degree Distribution", "Degree (d)", "P(x >= d)")
         self.densityDisplay.lineGraph("Graph Density", "Time Step", "Graph Density", legloc="upper right", multiLine=True)
         self.avgShortestPathDisplay.lineGraph("Average Shortest Path Length", "Time Step", "Avg. Shortest Path", multiLine=True)
         self.avgClusteringDisplay.lineGraph("Average Clustering", "Time Step", "Average Clustering", legloc= "upper right", multiLine=True)
Exemplo n.º 37
0
def init(script_to_run):
	"""Initializes the photo booth."""
	global filename_schema, photo_thread
	check_things()

	filename_schema = "photos/this-should-not-happen---{}.jpg"
	
	Settings.main_script = script_to_run
	
	Settings.runs = 0

	photo_thread = PhotoThread.PhotoThread()
	GPIO.setmode(GPIO.BOARD)
	GPIO.setup(Settings.GPIO, GPIO.IN)
	GPIO.add_event_detect(Settings.GPIO, GPIO.RISING, callback=button_pressed, bouncetime=300)

	Display.init(lambda: script_to_run.start())
Exemplo n.º 38
0
 def __init__(self):
     self.network = NetworkFrames.NetworkFrames()
     self.subgraphPair = []
     self.leftSubgraphs = []
     self.rightSubgraphs = []
     self.uniqueExtractionSubgraphs = {}
     self.firstRun = True
     self.dataDisplay = Display.display(False)
     self.utility = Utility.utility()
Exemplo n.º 39
0
	def __init__(self, playerObj, num):
		self.playerObj = playerObj
		self.menuObject = None
		self.maxRooms = num
		self.currRoomIndex = 0
		for i in xrange(0, self.maxRooms):
			self.listRooms.append(Room(self, Display.returnRandomColor(), random.randint(0,1)))
			if self.numRooms > 1:
				self.addRoomToDungeon(self.listRooms[self.numRooms - 1])
		for j in xrange(0, self.maxRooms):
			self.connectNeighboringRooms(self.listRooms[j])
Exemplo n.º 40
0
 def draw_everything(self):
     self.display.fill(WHITE)
     for ship in self.ship_list:
         self.draw_ship(ship)
     for bullet in self.bullet_list:
         self.draw_bullet(bullet)
     i = 0
     while i < len(self.debris):
         debra = self.debris[i]
         loc = (debra[0][0] + debra[1][0], debra[0][1] + debra[1][1])
         dur = debra[2] - 1
         self.debris[i] = (loc, debra[1], dur, debra[3], debra[4], debra[5], debra[6], debra[7])
         debra = self.debris[i]
         Display.draw_circle(self.display, self.camera, debra[7], debra[0], int((debra[6]-debra[2])*debra[3]) + debra[4], debra[5])
         if self.debris[i][2]<=0:
             self.debris.remove(self.debris[i])
         else:
             i+=1
     for wall in self.wall_list:
         self.draw_wall(wall)
     pygame.display.update()
Exemplo n.º 41
0
 def draw_ship(self, ship):
     if not ship.isDead():
         Display.draw_triangle(self.display, self.camera, BLACK, ship.location, ship.bounds, ship.direction, 2)
         if ship.moved:
             Display.draw_triangle_offset(self.display, self.camera, RED, (ship.location[0], ship.location[1]+ship.bounds[1]*3/2), (ship.bounds[0]/2, ship.bounds[1]/2), ship.direction-180, ship.location, 2)
         if ship.shield_obj:
             Display.draw_rect(self.display, self.camera, GREEN, ship.shield_obj, 2)
Exemplo n.º 42
0
	def next_step(self):
		Settings.WAIT_FOR_BUTTON_PRESS = False
		Settings.AFTER_ID = None
		delay, command, additional, target_branch = self.lines[self.line]
		self.line += 1
		if self.line>=len(self.lines):
			self.line = 0

		if command=="text":
			if target_branch is not None:
				Settings.ON_BUTTON_PRESS = lambda: target_branch.start()
				Settings.WAIT_FOR_BUTTON_PRESS = True
			Display.display_text(additional)
		elif command=="photo":
			Output.debug("Photo! Number " + str(additional))
			functions.call_photo_thread(additional)
		elif command=="overview":
			if target_branch is not None:
				Settings.ON_BUTTON_PRESS = lambda: target_branch.start()
				Settings.WAIT_FOR_BUTTON_PRESS = True
			Display.show_overview()
		elif command=="clear":
			Display.clear()
		elif command=="branch":
			Display.root().after(delay, lambda: target_branch.start())
			return
		elif command=="wait":
			Settings.ON_BUTTON_PRESS = self.next_step
			Settings.WAIT_FOR_BUTTON_PRESS = True
			return
		elif command=="init_run":
			functions.start_run(self)
			return

		# check if the next command is a "photo"
		if self.lines[self.line][1]=="photo":
			delay = max(delay - Settings.PHOTO_DELAY, 1)

		if Settings.DEBUG_SHORT_DELAYS:
			delay = delay / 100 + 1
			
		#Output.debug("Waiting: " + str(delay))

		Settings.AFTER_ID = Display.root().after(delay, self.next_step)
Exemplo n.º 43
0
 def __init__(self):
     self.inputFrames = []  # List of graphs that have been added during simulation or read in from graphML
     self.stateName = None  # String name of state used in input graph
     self.processedFrames = []  # List of graphs that the user has added with calculations performed on each frame
     self.compressedFrames = []  # The compressed list of graphs with the initial graph and the subsequent differences
     self.extractionSubgraphs = []  # List of LHS (left hand side) subgraphs that turn into the full compressed frame
     self.decompressedFrames = []  # The uncompressed list of graphs generated from decompressing the compressed frames
     self.graphML = nx.readwrite.graphml  # The internal networkx graphML object
     self.frameKey = 0  # The frame key used to created unique graph id's for the inputNetwork graphs
     self.compressedFrameKey = 0  # The frame key used to created unique graph id's for the compressed graphs
     self.decompressedFrameKey = 0  # The frame key used to created unique graph id's for the decompressed graphs
     self.processedFrameKey = 0  # The frame key used to create unique graph id's for the processed graphs
     self.extractionSubgraphKey = 0  # The subgraph key used to create unique graph id's for the extraction subgraphs
     self.nodesAddedWhenEdgesData = Display.display(False)
Exemplo n.º 44
0
	def __init__ (self, lll, viewspace, mymap):
	
		self.lll = lll
		self.display = Display ()
		self.viewspace = viewspace
		self.mymap = mymap
		self.terrainset = TerrainSet ()
		
		# Test
		self.settsurf = Surface ()
		self.settsurf.loadFromFile ("gfx/protosettler.png")
		self.settsurf.cols = 16
		self.settsurf.rows = 16

		self.sprites = []
Exemplo n.º 45
0
 def __init__(self):
     self.network = NetworkFrames.NetworkFrames()
     self.util = Utility.utility()
     self.prev_extraction = Extraction.Extraction()
     self.rewriting = Rewriting.Rewriting()
     self.sample_num = 0
     self.sample_motifs = []
     self.extractionMap = []
     self.extractionPool = {}
     self.gtrieExtractionPool = {}
     self.proportionalSelection = []
     self.display = Display.display()
     self.gtrie = GTrie.GTrie()
     self.gtrie.createGTrieWithFour()
     self.simulationgtrie = GTrie.GTrie()
     self.usedRewritingRules = {}
     self.avg_changes = 0.
Exemplo n.º 46
0
 def __init__(self, extraction, rewriting, utility, networkFrames):
     self.iterations = 1
     self. extraction = extraction
     self.rewriting = rewriting
     self.utility = utility
     self.networkFrames = networkFrames
     self.avgShortestPathDisplay = Display.display(True)
     self.densityDisplay = Display.display(True)
     self.nodesDisplay = Display.display(True)
     self.edgesDisplay = Display.display(True)
     self.avgClusteringDisplay = Display.display(True)
     self.cumulativeDegreeDist = Display.display(True)
     self.bhattacharyyaDegreeDisplay = Display.display()
     self.simulationNetwork = []
     self.simulationNetworkList = []
     self.UESFrequencyList = []
     self.UESMeanFrequencyList = []
     self.UESStdFrequencyList = []
     self.UES_BDList = []
     self.AttemptList = []
     self.BDMeanIndex = 0
     self.UES_BDMean = 0.
     self.UES_BDStd = 0.
     self.simulationInputKey = 0
Exemplo n.º 47
0
def _analyse(ui, fileUrls, algorithm):
    global output
    if len(fileUrls)!=0:
        algorithmClass= _loadAlgorithmClass(algorithmsFolder,algorithm)()
        if len(str(ui.qwtPlot.title().text()))==0:
            ui.curveX, ui.curveY = preparePlot(ui, algorithm)

        for fileUrl in fileUrls:
            print fileUrl
            video, i,j = cv2.VideoCapture(fileUrl), 0,0
            ret, frame = video.read()
            algorithmClass._initiateRegisters(frame)
            display1 = Display(ui.label_17)
            display2 = Display(ui.label_18)
            display3 = Display(ui.label_7)
            avaragePeriod, outlierDistance = ui.spinBox.value(), ui.spinBox_2.value()
            opencvPreview = ui.checkBox_2.isChecked()
            ui.resultDict = {}
            while ret:
                display1.display(frame)
                algorithmClass.analyze(frame, avaragePeriod)
                display2.display(algorithmClass.processedFrame)
                frame2= algorithmClass.processedFrame
                if not opencvPreview:
                    frame2 = np.zeros((100,100,3), dtype=np.uint8)
                cv2.imshow("raw preview ", frame2)
                if 0xFF & cv2.waitKey(5) == 27:
                   break
                ret, frame = video.read()
                if i%ui.spinBox.value()==0 and i>0:
                    ui.resultDict = algorithmClass.getResultDict(i, outlierDistance)
                    output.append(ui.resultDict)
                    #print "output len ", sys.getsizeof(output)

                    if j==0:
                        printAlgorithmResultsKeys(ui, j)
                        j+=1
                i+=1
            video.release()
Exemplo n.º 48
0
Arquivo: main.py Projeto: ArildF/rogie
    config = Config.getConfig()
    
    protocol = config.getString("login", "protocol")
    
    #init the protocol we are going to use
    Protocol.initProtocol( protocol )
    
    protocol = Protocol.getProtocol()   
    
    
    #first get the cookie and id's     
    nick = config.getString( "login", "username" )
    passwd = config.getString( "login", "password" )

    events = Events.getEvents()
    events.addListener( Display.getDisplay() )
    events.addListener( SpamFilter.getInstance() )

    #create the socket
    sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
    sock.settimeout( 120.0 )
    chatserver = config.getString( "login", "chatserver" )
    chatport = config.getInt( "login", "chatport" ) 


    #recreate the acl?
    if sys.argv.count( "-newacl" ):
        os.unlink( Acl.ACLFILE )

    chatRoom = config.getString( "login", "chatroom" )
Exemplo n.º 49
0
class Shift:
	# Define wPi GPIO
	SER = 0		# Valeur
	RCLK = 0	# Validateur
	SRCLK = 0	# Suivant

	display = 0
	leds = [Led(), Led(), Led(), Led(), Led()]

	array = [[0, 0, 0],
			 [0, 0, 0],
			 [0, 0, 0],
			 [0, 0, 0],
			 [0, 0, 0],
			 [0, 0, 0, 0, 0, 0, 0, 0]]

	def __init__(self, SER = 7, RCLK = 9, SRCLK = 8):
	#def __init__(self, SER = 1, RCLK = 16, SRCLK = 15):
		self.SER = SER
		self.RCLK = RCLK
		self.SRCLK = SRCLK

		wPi.wiringPiSetup()

		wPi.pinMode(self.SER, OUT)
		wPi.pinMode(self.RCLK, OUT)
		wPi.pinMode(self.SRCLK, OUT)

		self.loadDisplay()
		self.loadLeds()
		#self.leds = [0, 0, 0, 0, 0]

## LOADING ##
	def loadLeds(self):
		self.leds = [Led(), Led(), Led(), Led(), Led()]

		print "Leds initialized!"

	def loadDisplay(self):
		self.display = Display()
		self.clearDisplay()

		print "Display initialized!"

	def addLed(self, position, led):
		self.leds[position] = led

## SETTING LEDs COLORS ##

	## One LED ##
	def setLedColor(self, led, color, state):
		if color == 'r' or color == 'red':
			self.setLedR(led, state)
		elif color == 'g' or color == 'green':
			self.setLedG(led, state)
		elif color == 'b' or color == 'blue':
			self.setLedB(led, state)	

	def setLedColors(self, led, r, g, b):
		self.leds[led].setColors(r, g, b)

	def setLedR(self, led, r):
		self.leds[led].setR(r)

	def setLedG(self, led, g):
		self.leds[led].setG(g)

	def setLedB(self, led, b):
		self.leds[led].setB(b)

	def toggleLed(self, led):
		self.leds[led].toggleAll()

	def toggleLedColor(self, led, color):
		self.leds[led].toggleColor(color)
		self.apply()

	def applyLedColors(self, led):
		self.array[led] = self.leds[led].getColors()

	## All LEDs ##
	def setLedsColors(self, r, g, b):
		for i in range(0, 5):
			self.leds[i].setColors(r, g, b)

	def setLedsR(self, state):
		for i in range(0, 5):
			self.leds[i].setR(state)

	def setLedsG(self, state):
		for i in range(0, 5):
			self.leds[i].setG(state)

	def setLedsB(self, state):
		for i in range(0, 5):
			self.leds[i].setB(state)

	def toggleLeds(self):
		for i in range(0, 5):
			self.leds[i].toggleAll()

	def toggleLedsColor(self, color):
		for i in range(0, 5):
			self.leds[i].toggleColor(color)

	def applyLedsColors(self):
		for i in range(0, 5):
			self.array[4-i] = list(self.leds[i].getColors())

## SETTING DISPLAY ##

	def setNumber(self, x):
		self.array[5] = self.display.getNumber(x)

		if self.array == 0:
			print "Nombre saisi incorrect!"

	def setNumbers(self):
		return self.display.getNbSelected()

	def clearDisplaye(self):
		self.array[5] = self.display.clear()

## APPLY CHANGE ##
	def apply(self):
		wPi.digitalWrite(self.RCLK, DOWN)
		
		for j in reversed(self.array[5]):
			wPi.digitalWrite(self.SRCLK, DOWN)
			wPi.digitalWrite(self.SER, j)
			wPi.digitalWrite(self.SRCLK, UP)

		for i in range(0, 5):
			for j in reversed(self.array[i]):
				wPi.digitalWrite(self.SRCLK, DOWN)
				wPi.digitalWrite(self.SER, j)
				wPi.digitalWrite(self.SRCLK, UP)

		wPi.digitalWrite(self.RCLK, UP)

## CLEAR ##
	def clearDisplay(self):
		for i in range(0, 6):
			wPi.digitalWrite(self.RCLK, DOWN)
			for j in reversed(self.array[i]):
				wPi.digitalWrite(self.SRCLK, DOWN)
				wPi.digitalWrite(self.SER, DOWN)
				wPi.digitalWrite(self.SRCLK, UP)
			#	print j,
			wPi.digitalWrite(self.RCLK, UP)
			#print ""
		print "Display cleaned!"

	def clearData(self):
		for i in range(0, 6):
			for j in reversed(self.array[i]):
				self.array[i][j] = 0
		print "Data cleaned!"

## LOADINGS EFFETCS ##
	def loading(self, color):
		self.setLedColor(0, color, 1)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

		self.setLedColor(1, color, 1)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)
		
		self.setLedColor(0, color, 0)
		self.setLedColor(2, color, 1)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

		self.setLedColor(1, color, 0)
		self.setLedColor(3, color, 1)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

		self.setLedColor(2, color, 0)
		self.setLedColor(4, color, 1)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

		self.setLedColor(3, color, 0)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

		self.setLedColor(4, color, 0)
		self.applyLedsColors()
		self.apply()
		sleep(0.2)

	def trimble(self):
		#self.clearData()
		#self.apply()
		color = ['r', 'g', 'b']
		for i in range(0, 3):
			print 'Set ' + str(0) + ' to ' + str(1)
			print ''
			self.setLedColor(0, color[i], 1)
			self.setNumber(randint(0, 6))
			self.applyLedsColors()
			self.apply()
			sleep(0.1)
			self.setNumber(randint(0, 6))
			self.apply()
			sleep(0.1)

			print 'Set ' + str(1) + ' to ' + str(1)
			print ''
			self.toggleLedColor(1, color[i])
			self.setNumber(randint(0, 6))
			self.applyLedsColors()
			self.apply()
			sleep(0.1)
			self.setNumber(randint(0, 6))
			self.apply()
			sleep(0.1)

			for j in range(2, 5):
				print 'Set ' + str(j-2) + ' to ' + str(0)
				print 'Set ' + str(j) + ' to ' + str(1)
				print ''
				self.toggleLedColor(j-2, color[i])
				self.toggleLedColor(j, color[i])
				self.setNumber(randint(0, 6))
				self.applyLedsColors()
				self.apply()
				sleep(0.1)
				self.setNumber(randint(0, 6))
				self.apply()
				sleep(0.1)

			print 'Set ' + str(3) + ' to ' + str(0)
			print ''
			self.toggleLedColor(3, color[i])
			self.setNumber(randint(0, 6))
			self.applyLedsColors()
			self.apply()
			sleep(0.1)
			self.setNumber(randint(0, 6))
			self.apply()
			sleep(0.1)

			print 'Set ' + str(4) + ' to ' + str(0)
			self.toggleLedColor(4, color[i])
			self.setNumber(randint(0, 6))
			self.applyLedsColors()
			self.apply()
			sleep(0.1)
#
Exemplo n.º 50
0
 def send( self, sock ):
     """override send to display the pm"""
     Packet.send( self, sock )
     Display.getDisplay().pmTo( self.destination, self.statement )
Exemplo n.º 51
0
	def loadDisplay(self):
		self.display = Display()
		self.clearDisplay()

		print "Display initialized!"
Exemplo n.º 52
0
import Display
import pygame
pygame.init()
screen = Display.pywindow(500, 500, 'Snake', 'None', backColor = (0,0,255))
screen.updateSysstat()
screen.updateScreen()
thing = Display.gameObject(True, False, 10, 10, 0, 0, 'minecraft_icon.bmp',(0,0,0))
while True:
     screen.update()
Exemplo n.º 53
0
def test_backlight():
    say('testing backlight')
    Display.set_cursor_position(0,2)
    Display.write('Backlight       ')
    Display.rgb(255,0,0)
    time.sleep(1)
    Display.rgb(0,255,0)
    time.sleep(1)
    Display.rgb(0,0,255)
    time.sleep(1)
    for i in range(0, 360):
        Display.hue(i/360.0)
        time.sleep(0.01)
    for i in range(0, 360):
        Display.sweep(i/360.0)
        time.sleep(0.01)

    Display.rgb(255,255,255)
    Display.set_cursor_position(0,2)
    Display.write('                ')
Exemplo n.º 54
0
def test_lights():
    say('Testing lights')
    Display.set_cursor_position(0,2)
    Display.write('Lights          ')

    say('Lamp 0 on')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 0 On       ')
    Lights.set_lamp(0, 1)
    time.sleep(3)

    say('Lamp 1 on')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 1 On       ')
    Lights.set_lamp(1, 1)
    time.sleep(3)

    say('Lamp 2 on')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 2 On       ')
    Lights.set_lamp(2, 1)
    time.sleep(3)

    say('Lamp 3 on')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 3 On      ')
    Lights.set_lamp(3, 1)
    time.sleep(3)

    say('Lamp 0 off')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 0 Off     ')
    Lights.set_lamp(0, 0)

    say('Lamp 1 off')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 1 Off     ')
    Lights.set_lamp(1, 0)
 
    say('Lamp 2 off')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 2 Off     ')
    Lights.set_lamp(2, 0)

    say('Lamp 3 off')
    Display.set_cursor_position(0,2)
    Display.write('Lamp 3 Off')
    Lights.set_lamp(3, 0)

    Display.set_cursor_position(0,2)
    Display.write('                ')
Exemplo n.º 55
0
def generateTrainingSamples(ui):
    if ui.listWidget_6.count() >0:
        display1 = Display(ui.label_17)
        #load the selected algorithms
        algorithms={}#, samples ={},{}
        outputTrainingDataName =''
        for i in range(ui.listWidget_6.count()):
            algorithmName = str(ui.listWidget_6.item(i).text().replace('.py',''))
            algorithm = _loadAlgorithmClass(algorithmsFolder, algorithmName)()
            algorithms[algorithmName] = algorithm
            #outputTrainingDataName+=str(algorithmName+'#')

        period = ui.spinBox.value()
        #print algorithms
        trainingSamples, responses =[], []
        for key in algorithms.keys():
            #iterate through environments
            for n in range(ui.listWidget_2.count()):
                environment = str(ui.listWidget_2.item(n).text())
                #iterate through environment sample videos
                filmUrlList = ui.filmSamples[environment]
                for filmUrl in filmUrlList:
                    print filmUrl
                    video, i = cv2.VideoCapture(filmUrl), 0
                    ret, frame = video.read()
                    #initiate the analysis algorithms
                    for algorithmName in algorithms.keys():
                        algorithms[algorithmName]._initiateRegisters(frame)
                    #iterate via frames in a film sample
                    while ret:
                        i += 1
                        display1.display(frame)
                        #for each algorithm
                        sample =[]
                        #for key in algorithms.keys():
                        algorithms[key].analyze(frame, period)
                        if i % period==0:
                            #distX, distY = algorithms[key].getDistribution(period)
                            #weightCenter = algorithms[key].getWeightCenter(distX[1], distY[1])
                            #sample = algorithms[key].getCharacteristicPointsVector()
                            #sample.append(weightCenter[0])
                            #sample.append(weightCenter[1])
                            if ui.radioButton_2.isChecked():
                                sample = np.array(algorithms[key].keyPointsVector).astype(np.float32)
                                #samples[environment].append(sample)
                            else:
                                sample=algorithms[key].keyPointsVector
                            trainingSamples.append(sample)
                            responses.append(n)


                        ret, frame = video.read()
            if ui.radioButton_2.isChecked():
                fileName = 'data/trainingData/'+ key +'.dat'
                with open(fileName, "w") as f:
                    print "Saved to ", fileName
                    pickle.dump([trainingSamples,responses],f)
            else:
                fileName = 'data/trainingData/'+key+ '.txt'
                with open(fileName, "w") as f:
                    print "Saved to ", fileName
                    f.write(str(trainingSamples)+"\nRESPONSES\n"+str(responses))
Exemplo n.º 56
0
def test_bargraph():
    say('testing bargraph')
    Display.set_cursor_position(0,2)
    Display.write('Bargraph        ')
    for intensity in range (0,100):
        Display.set_graph(intensity/100.0)
        time.sleep(.01)
    for intensity in range (100,0,-1):
        Display.set_graph(intensity/100.0)
        time.sleep(.01)
    Display.set_cursor_position(0,2)
    Display.write('                ')
Exemplo n.º 57
0
	def _perform_action(self, action, playerObj, menuObject):
		if action == MOVE_LEFT:
			playerObj.moveLeft = True
			playerObj.direction = 'left'
		elif action == MOVE_RIGHT:
			playerObj.moveRight = True
			playerObj.direction = 'right'
		elif action == MOVE_DOWN:
			playerObj.moveDown = True
			playerObj.direction = 'down'
		elif action == MOVE_UP:
			playerObj.moveUp = True
			playerObj.direction = 'up'
		elif action == NO_MOVE_LEFT:
			playerObj.moveLeft = False
		elif action == NO_MOVE_RIGHT:
			playerObj.moveRight = False
		elif action == NO_MOVE_DOWN:
			playerObj.moveDown = False
			playerObj.currentWeapon.spriteObj.resetSpriteList()
		elif action == NO_MOVE_UP:
			playerObj.moveUp = False

		elif action == NORMAL_ATTACK:
			playerObj.isAttacking = 1
		elif action == NO_NORMAL_ATTACK:
			playerObj.isAttacking = 0
		elif action == RANGED_ATTACK:
			if playerObj.arrows > 0:
				playerObj.arrows -= 1
				print "Firing!"
				playerObj.rangedWeapon.shoot()
			else:
				print "No arrows!"
		elif action == CONTINIOUS_RANGED_ATTACK:
			if pygame.time.get_ticks() > playerObj.lastFired + 500 and playerObj.arrows > 0:
				playerObj.rangedWeapon.shoot()
				playerObj.lastFired = pygame.time.get_ticks()
				playerObj.arrows -= 1
			else:
				if playerObj.arrows < 1:
					print "No arrows!"
				else:
					print "Notching arrow!"
		elif action == SWITCH_WEAPON:
			playerObj.cycleWeapon()
		elif action == USE_POTION:
			playerObj.usePotion()
		elif action == PICKUP_OBJECT:
			playerObj.pickup = True
			if functions.playerInventory:
				playerObj.isTrading = True
		elif action == NO_PICKUP_OBJECT:
			playerObj.pickup = False
			playerObj.isTrading = False

		elif action == OPEN_MENU:
			self._log.debug('Opening menu')
			menuObject.activateText()
		elif action == PAUSE_GAME:
			if functions.paused:
				self._log.debug('Resuming game')
				functions.paused = False
			else:
				self._log.debug('Pausing game')
				functions.paused = True
		elif action == TAKE_SCREENSHOT:
			self._log.info('Taking screenshot')
			functions.screenshot()
		elif action == SET_FULLSCREEN:
			if Display.is_fullscreen:
				self._log.debug('Exiting fullscreen')
				Display.resetWindow()
				Display.is_fullscreen = 0
			else:
				self._log.debug('Entering fullscreen')
				Display.fullscreen()
				Display.is_fullscreen = 1

		elif action == RESTART_MATCH:
			self._log.info('Restarting match')
			playerObj.isDead = True
		elif action == QUIT_GAME:
			self._log.info('Quitting game')
			functions.terminate()
Exemplo n.º 58
0
 def runMotifSimulation(self, motifSize):
     if len(self.networkFrames.getInputNetworks()) > 0:    
         print "Recreating Input Network..."
         # Set the initial configuration
         self.extraction.generateExtractionTree()
         startFrame = self.networkFrames.getInputNetworkAt(0)
         bargraph = Display.display()
         for iteration in range(self.iterations):
             print str(iteration+1),
             focusFrame = startFrame.copy()
             self.addGraphToSimulatedNetwork(focusFrame)
             attemptDataDisplay = Display.display(False)
             motifSizeList = self.extraction.getMotifSizeList()
             
             frameNumber = 0
             while frameNumber < len(self.networkFrames.getInputNetworks())-1:
                 numchanges = 0
                 targetchanges = self.networkFrames.getNumberOfChanges(frameNumber+1)/motifSize
                 self.extraction.generateGTrieExtractionPool(focusFrame)
                 self.extraction.clearUsedRewritingRules()
                 self.extraction.resetRewritingRuleExclusionList()
                 self.extraction.generateProportionalSelectionData()
                 self.extraction.generateSampleComparisonData()
                 
                 while self.extraction.getSizeOfExtractionSubgraphGTrieMatch() > 0 and numchanges < targetchanges:
                     rewritingRule = None
                     extractionSubgraph = None
                     
                     while rewritingRule == None:
                         extractionSubgraph = self.extraction.chooseExtractionSubgraphGTrie(focusFrame)
                         rewritingRule = self.extraction.selectRewritingRuleGTrie(extractionSubgraph)
                         if rewritingRule == None:
                             self.extraction.removeExtractionSubgraphGTrieMatch(extractionSubgraph)
                             
                         if self.extraction.getSizeOfExtractionSubgraphGTrieMatch() == 0:
                             break
                             
                     if rewritingRule == None:
                         continue
                     
                     self.extraction.addUsedRewritingRules(rewritingRule)
                     self.networkFrames._decompress(focusFrame, rewritingRule)
                     numchanges += 1
                     
                 
                 #comparison = self.extraction.getComparisonData()
                 #bargraph.barCompare("Extraction Subgraph Compare", "Extraction Subgraph", "Frequency", comparison[0], comparison[1])
                 print "Number of changes: " + str(numchanges)
                 self.extraction.displayUsedRewritingRuleGraph()
                 self.addGraphToSimulatedNetwork(focusFrame)
                 frameNumber+=1
                 
             self.storeSimulatedNetwork()
             self.clearSimulatedNetwork()
             self.UESFrequencyList.append(copy.deepcopy(self.rewriting.getDisplayData()))
             self.rewriting.resetDataDisplay()
 
         print "Done."
         self.processSimulationData()
         print "UES Mean BD: " + str(self.UES_BDMean)
         print "UES Std BD: " + str(self.UES_BDStd)
         #self.meanNetwork.writeSpecificGraphs("generatedOutputMeanNetwork.graphML", self.meanNetwork.getDecompressedFrames())
         UES_Display = Display.display(False)
         UES_Display.addInputValues([],self.UESFrequencyList[0].getHistInputData())
         UES_Display.addExperimentalValues([],self.UESMeanFrequencyList)
         #UES_Display.UESBarPlot('Unique Extraction Subgraph Comparison', 'Times Selected', 'Subgraph Groups',self.UESMeanFrequencyList, self.UESStdFrequencyList, self.UES_BDMean)
         self.bhattacharyyaDegreeDisplay.lineGraph("Bhattacharyya Distance - Cumulative Degree Distribution", "Time Step", "Bhattacharyya Distance",multiLine=True)
         #self.cumulativeDegreeDist.loglogPlot("Cumulative Degree Distribution", "Degree (d)", "P(x >= d)", legloc="upper right",multiLine=False)
         self.densityDisplay.lineGraph("Graph Density", "Time Step", "Graph Density", legloc="upper right",multiLine=True)
         self.nodesDisplay.lineGraph("Number of Nodes", "Time Step", "Num Nodes", legloc="upper right", multiLine=True)
         self.edgesDisplay.lineGraph("Number of Edges","Time Step", "Num Edges", legloc="upper right", multiLine=True)
         self.avgShortestPathDisplay.lineGraph("Average Shortest Path Length", "Time Step", "Avg. Shortest Path",multiLine=True)
         self.avgClusteringDisplay.lineGraph("Average Clustering", "Time Step", "Average Clustering",legloc="upper right",multiLine=True)