def add_region_no_backup(app, _zone, _country, region):
    tmp_zone = clss.Zone(_zone)
    tmp_country = clss.Country(_country)

    tmp_country.add_region(region)
    tmp_zone.add_country(tmp_country)

    app.zones_list.append(tmp_zone)
    app.zones_num += 1
def add_location_no_backup(app, _zone, _country, _region, location):
    tmp_zone = clss.Zone(_zone)
    tmp_country = clss.Country(_country)
    tmp_region = clss.Region(_region)

    tmp_region.add_location(location)
    tmp_country.add_region(tmp_region)
    tmp_zone.add_country(tmp_country)
    app.zones_list.append(tmp_zone)
    app.zones_num += 1
Esempio n. 3
0
def Draw_Next_Card(Screen,there):
	if there <= 4:
		Card = Classes.Card()
		B_Card = Classes.Button(120*there,420,100,150,(255,255,255),Screen)
		B_Card.Do()
		if Card.value != 10:
			Print_On(B_Card,215,str(Card.value),(0,255,0),Screen)
		else:
			Print_At(120*there,460,100,200,215/2,"10",(0,255,0),Screen)
		return [there+1,Card.value]
Esempio n. 4
0
def ReadFile(path):
    commands=[]
    for line in open(path):
        terms=line.split()
        position = cl.position(float(terms[5]), float(terms[6]), float(terms[7]),float(terms[8]),
                    float(terms[9]),float(terms[10]),float(terms[11]))
        command=cl.motion(terms[1],position,float(terms[0]),float(terms[4]),terms[3])
        commands.append(command)
    
    return commands
def add_sport_zone_backup(backup_zone, _country, _region, _location, sport):
    tmp_country = clss.Country(_country)
    tmp_region = clss.Region(_region)
    tmp_location = clss.Location(_location)

    tmp_location.add_sport(sport)
    tmp_region.add_location(tmp_location)
    tmp_country.add_region(tmp_region)

    backup_zone.add_country(tmp_country)
    def crossoverAPX(self, pai1, pai2):

        filho1 = []
        filho2 = []
        tamanho = numpy.size(pai1)
        Herdado = False

        for i in range(tamanho):
            if(numpy.size(filho1) < tamanho):

                for j in filho1:
                    if(j == pai1[i]):
                        Herdado = True
                        break
                if(Herdado == True):
                    Herdado = False
                    for j in filho1:
                        if(j == pai2[i]):
                            Herdado = True
                            break
                    if(Herdado == False):
                        filho1.append(pai2[i])
                else:
                    filho1.append(pai1[i])
            else:
                break

        for i in range(tamanho):
            if(numpy.size(filho2) < tamanho):

                for j in filho2:
                    if(j == pai2[i]):
                        Herdado = True
                        break
                if(Herdado == True):
                    Herdado = False
                    for j in filho2:
                        if(j == pai1[i]):
                            Herdado = True
                            break
                    if(Herdado == False):
                        filho2.append(pai1[i])
                else:
                    filho2.append(pai2[i])
            else:
                break

        resultado = []
        solucao = Classes.Solucao()
        solucao.caminho = filho1
        resultado.append(solucao)
        solucao = Classes.Solucao()
        solucao.caminho = filho2
        resultado.append(solucao)
        return resultado
def Difficulty_Menu():
    flag = True
    main_frame = display.set_mode(resolution)

    # create and group sprites
    game_label = cl.Button("Welcome to MasterMind!", 540, 120, fontsize=50)
    easy_button = cl.Button("Easy", 540, 200, fontsize=30)
    medium_button = cl.Button("Medium", 540, 240, fontsize=30)
    hard_button = cl.Button("Hard", 540, 280, fontsize=30)
    back_button = cl.Button("Back to Menu", 10, 680, fontsize=24, align="left")
    diff_menu_labels = Group(game_label)
    diff_menu_buttons = Group(easy_button, medium_button, hard_button,
                              back_button)

    while flag:
        main_frame.fill(cl.grey)
        diff_menu_labels.draw(main_frame)
        diff_menu_buttons.draw(main_frame)
        display.update()

        for ev in event.get():

            # button hovering implementation
            for sprite in diff_menu_buttons:
                if sprite.rect.collidepoint(mouse.get_pos()):
                    sprite.change_colour(cl.white)
                else:
                    sprite.change_colour(cl.black)

            # checks for event type quit
            if ev.type == QUIT:
                pygame.quit()
                exit()

            # check for event type mouse button down
            elif ev.type == MOUSEBUTTONDOWN:

                # back button implementation
                if back_button.rect.collidepoint(mouse.get_pos()):
                    flag = False

                # easy button implementation
                elif easy_button.rect.collidepoint(mouse.get_pos()):
                    Game_Menu("easy")
                    flag = False

                # medium button implementation
                elif medium_button.rect.collidepoint(mouse.get_pos()):
                    Game_Menu("medium")
                    flag = False

                # hard button implementation
                elif hard_button.rect.collidepoint(mouse.get_pos()):
                    Game_Menu("hard")
                    flag = False
Esempio n. 8
0
def main(ip, port):
    try:
        motionProxy = Classes.MotionProxy(ip, port)
        visionProxy = Classes.VisionProxy(ip, port)
        memoryProxy = Classes.MemoryProxy(ip, port)
        speakProxy = Classes.SpeakProxy(ip, port)
        postureProxy = Classes.PostureProxy(ip, port)
    except Exception, e:
        print "ERROR:"
        print e
        sys.exit(1)
Esempio n. 9
0
    def team_screen(self):

        self.window.close_window(self.selected_window)

        self.class_window = self.window.create_window(15, 30, 0, 5,
                                                      'select your team')

        self.log_w = self.window.create_window(50, 8, 0, 42, 'Log')
        self.log = ui.Log(self.log_w, 48, 6)
        self.log_w.add_elem(self.log)

        menu = ui.Control_Menu(self.class_window, 13, 28, 'classes')
        self.class_window.add_elem(menu)

        self.create_squad()

        warrior = Ui.Text_Button(menu, 10, 1, 'warrior', Color.WHITE,
                                 Color.BLACK, self.select_class,
                                 [Classes.Warrior()])
        menu.add_elem(warrior)

        archer = Ui.Text_Button(menu, 10, 1, 'archer', Color.WHITE,
                                Color.BLACK, self.select_class,
                                [Classes.Archer()])
        menu.add_elem(archer)

        assasin = Ui.Text_Button(menu, 10, 1, 'assasin', Color.WHITE,
                                 Color.BLACK, self.select_class,
                                 [Classes.Assasin()])
        menu.add_elem(assasin)

        sage = Ui.Text_Button(menu, 10, 1, 'sage', Color.WHITE, Color.BLACK,
                              self.select_class, [Classes.Sage()])
        menu.add_elem(sage)

        mage = Ui.Text_Button(menu, 10, 1, 'mage', Color.WHITE, Color.BLACK,
                              self.select_class, [Classes.Mage()])
        menu.add_elem(mage)

        start = Ui.Text_Button(menu, 10, 1, 'Begin', Color.LBLUE, Color.GREEN,
                               self.validate_team, None)
        menu.add_elem(start)

        self.set_state(2)  #4: selection_screen

        self.menu_w = self.window.create_window(30, 50, 49, 0, "Menu")
        self.charamenu = ui.Soft_Menu(self.menu_w, 28, 48, 'Menus')
        self.menu_w.add_elem(self.charamenu)
        self.squad_ui = ui.Squad_Ui(self.charamenu, self.squad, self)
        self.charamenu.add_elem(self.squad_ui)

        self.select_window(self.class_window)

        self.window.build('erase')
Esempio n. 10
0
def parse_wb(wb, wb_name="", addr_offset="0", name_prefix=""):
    spaces_list = []
    chip_registers_list = []

    reached_data = False

    if 'Spaces' in wb.sheetnames and not wb_name:
        for row in tuple(wb["Spaces"].rows):

            # skip top part of excel sheet, usually not relevant
            if reached_data is False:
                for cell in row:
                    if cell.value == "type":
                        reached_data = True
                        break  # goto next row/line (with actual data), and look at whole row
            else:
                # print(cell.value, end=" ") if cell.value else "" # print only non empty cells
                if (row[2].value is None) or (row[0].value != "reg_block"
                                              and row[0].value != "reg_space"
                                              and row[0].value != "ext_block"
                                              ):  ##ak fixme extblock???
                    continue
                spaces_list.append(
                    Classes.Spaces(row[0].value, row[1].value, row[2].value,
                                   row[3].value, row[4].value)
                )  # type,name,space_addr,bits,description):
                # pprint(vars(Spaces_list[-1]))
                # print(" ... ")
    else:
        if wb_name in wb.sheetnames:
            # print("adding ", wb_name, " to spaces list")
            spaces_list.append(
                Classes.Spaces("reg_block", wb_name, addr_offset, "32",
                               ""))  # type,name,space_addr,bits,description):
        else:
            raise NameError
    """ Parse all spaces in Spaces_list - 
	go over each one, open the specific tab, and add the tab's content 
	to the register_list"""
    for space in spaces_list:
        if space.space_type == "remark":
            continue
        # print("Iterating space " + space.name)
        if space.space_addr.startswith("0x"):
            space.space_addr = space.space_addr.split("x")[1]
        size_of_addr = len(space.space_addr)  # num of bytes
        # chip_registers_list = [*chip_registers_list, *parse_tab(wb, space.name, int(bin(int(str(space.space_addr), 16))[size_of_addr*4-int(space.bits)+2:size_of_addr*4+2], 2) << (32 - int(space.bits)), name_prefix)]
        chip_registers_list = [
            *chip_registers_list, *parse_tab(
                wb, space.name,
                int(str(space.space_addr), 16) <<
                (32 - int(size_of_addr) * 4), name_prefix)
        ]
    return chip_registers_list
Esempio n. 11
0
def Die():
    global Level, Asteroids, Explosions, p1
    Explosions.append(Classes.Explosion("Self", 1, p1.position))
    p1.speed = [0.0, 0.0]
    for x in xrange(540):
        Move()
        Update()
        Draw()
    p1 = Classes.Player()
    Level = 0
    Asteroids = []
    Explosions = []
Esempio n. 12
0
def init():
	global initialized
	if (initialized):
		return
	Classes.init()
	configPath = os.path.join(os.path.dirname(__file__), "data", "profiles.cfg")
	configDict = ConfigFile.readFile(configPath)
	for profName in configDict.keys():
		if (type(configDict[profName]) != type({})):
			continue
		profiles[profName] = Profile(configDict[profName])
	initialized = True
Esempio n. 13
0
def comparePlayers(pstring):
    import Classes as c
    players = pstring.split(" ")
    p1 = c.Player(players[0])
    p2 = c.Player(players[1])
    out = "Player Comparison: \n\n"
    out += p1.name + ":\n" + str(p1.getWinPercent()) + "% winrate\n" + str(
        p1.getDrinks()) + " drinks\n" + str(
            p1.getRacks()) + " racks purchased\n\n"
    out += p2.name + ":\n" + str(p2.getWinPercent()) + "% winrate\n" + str(
        p2.getDrinks()) + " drinks\n" + str(p2.getRacks()) + " racks purchased"
    return out
Esempio n. 14
0
def BreakAsteroid(a):
    Explosions.append(Classes.Explosion("Asteroid",a.size,a.position))
    if a.size == 1:
        add_object = random.choice(["Powerup", False, False, False, False, False, False, False, False, False, False, False, False, False, False])
        if add_object == "Powerup":
            PowerUps.append(Classes.PowerUp(a.position))
    else:
        add_asteroid_size = a.size-1
        if add_asteroid_size <= 0: add_asteroid_size = 1
        Asteroids.append(Classes.Asteroid(a.position[0],a.position[1],add_asteroid_size))
        Asteroids.append(Classes.Asteroid(a.position[0],a.position[1],1))
        Asteroids.append(Classes.Asteroid(a.position[0],a.position[1],1))
    Asteroids.remove(a)
Esempio n. 15
0
def as_class(dct):
    """
  Decodes classes encoded into the above format.
  """
    if '__Desire__' in dct:
        if dct['__Desire__']:
            return cls.Have(dct['name'], int(dct['position']))
        else:
            return cls.Want(dct['name'], int(dct['position']))
    elif '__Pair__' in dct:
        return cls.Pair(dct['have'], dct['want'], int(dct['id']))
    else:
        return dct
Esempio n. 16
0
    def onMessage(self, payload, isBinary):
        folder = json.loads(payload.decode('utf8'))
        if "type" in folder and folder['type'] == 'newF':
            object = Classes.newF(folder['name'], folder['privilege'], folder['path'])
            os.system("echo 'include = /etc/samba/conf."+object.name+"' | sudo tee --append /etc/samba/smb.conf")    
            os.system("echo '["+object.name+"]\n read only = "+object.privilege+"\n path= "+object.path+"' | sudo tee --append /etc/samba/conf."+object.name)

        if "type" in folder and folder['type'] == 'delF':
            object = Classes.delF(folder['name'], folder['privilege'], folder['path'])
            os.system("sudo sed -i '/"+object.name+"/d' /etc/samba/smb.conf" )
            os.system("sudo rm /etc/samba/conf."+object.name)
            
        self.sendMessage(payload, isBinary)
Esempio n. 17
0
def make_command_from_db(app, line):
    # Makes the command from "line" into the application "app".
    if line[0] == "add":
        if line[1] == "zone":
            app.add_zone(clss.Zone(line[2]))
        elif line[1] == "sport":
            app.add_sport(clss.Sport(line[2], line[3], line[4], [line[5], line[6]]), line[7], line[8], line[9],
                          line[10])
        elif line[1] == "country":
            app.add_country(clss.Country(line[2]), line[3])
        elif line[1] == "region":
            app.add_region(clss.Region(line[2]), line[3], line[4])
        elif line[1] == "location":
            app.add_location(clss.Location(line[2]), line[3], line[4], line[5])
Esempio n. 18
0
def parse_data(data):

    txt = data['text'].lower()

    if (txt.find('!stats ') == 0):
        play = c.Player(txt[7:])
        stats = play.getStats()
        msg = formatStats(stats)
        send_message(msg)
    elif (txt.find("!game ") == 0):
        gme = c.Game(txt[6:])
        gme.gameUpdate()
        del gme
        msg = "apex!\ngame logged sucessfully"
        send_message(msg)
    elif (txt.find("!lead") == 0):
        msg = spreadsheet.showLeaderboard()
        send_message(msg)
    elif (txt.find("!racks -f") == 0):
        msg = spreadsheet.showRacks(True)
        send_message(msg)
    elif (txt.find("!racks") == 0):
        if (len(txt) > 6):
            play = c.Player(txt[7:])
            play.setRacks()
            msg = "Updated!\nRacks purchased this season: " + str(
                play.getRacks())
        else:
            msg = spreadsheet.showRacks()
        send_message(msg)
    elif (txt.find("!compare ") == 0):
        msg = spreadsheet.comparePlayers(txt[9:])
        send_message(msg)
        return 0
    elif (txt.find("!add ") == 0):
        plrname = txt[5:]
        spreadsheet.addPlayer(plrname)
        send_message(plrname + " added!")
    elif (txt.find("!miami") == 0):
        phrase = ["apex!", "hookah vibes", "broo"]
        send_message(phrase[random.randint(0, 2)])
    elif (txt.find("!jewtax") == 0):
        msg = "It's not a jew tax... You just pay more because you are jewish"
        send_message(msg)
    elif (txt.find("!drinks") == 0):
        msg = spreadsheet.getTotalDrinks()
        send_message(msg)

    else:
        return 0
Esempio n. 19
0
def main():
    Cl.load_files_to_genetic_algorithm(4)
    start_genetic_algorithm(0.00, 0.6, 0, 100, 100, 4, 3, 1)
    # l.sort(key=lambda x: x.value)
    #start_genetic_algorithm(0.12, 0.75, 15, 100, 100, 2, 0, 50)
    #start_genetic_algorithm_points(0.10, 0.8, 15, 100, 100, np.arange(1,10,1), 0, 50)
    #start_genetic_algorithm_pm(np.arange(0, 0.5, 0.05), 0.75, 15, 100, 100, 2, 0, 50)
    #start_genetic_algorithm_px(0.15, np.arange(0, 1, 0.1), 15, 100, 100, 2, 0, 50)
    start_genetic_algorithm_tour(0.15, 0.8, np.arange(5, 50, 5), 100, 100, 2,
                                 0, 50)
    start_genetic_algorithm_popsize(0.15, 0.8, 15, np.arange(50, 551, 50), 100,
                                    2, 0, 50)

    pass
Esempio n. 20
0
def produceGeneration(population=Classes.Population()):

    new_population = Classes.Population()

    for x in range(population.populationLimit):

        newChild = CrossOverAndMutation.crossOver(population)

        Fit = Fitness.CalculateFitness(newChild)
        newChild.fitness = (Fit[0] + Fit[1] + Fit[2]) * -1

        new_population.chromosomeList.append(newChild)

    return new_population
Esempio n. 21
0
def updateLiteral(sym):
    global lit_no
    flag = 0
    for i in Lit_Table:
        if i.name == sym:
            flag = 1
    if flag == 0:
        if (myIsDigit(sym)):
            val = int(sym)
            l = C.Literal(lit_no, sym, val)
        else:
            l = C.Literal(lit_no, sym, ord(sym))
        lit_no += 1
        Lit_Table.append(l)
Esempio n. 22
0
def Human_Player_Test():
    land = c.Map('plateau.txt')
    rob = c.Robot(land, "Twonky")
    player1 = c.Joueur_Humain(rob, 'Pierre')
    while not player1.robot.win and player1.robot.life > 0:
        player1.pick_cards()
        print('Picked cards ', player1.choice)
        player1.make_program()
        player1.menu_execute()
        print('Vie du Robot : ', player1.robot.life)
    if player1.robot.life <= 0:
        print('looser')
    else:
        print("Félicitation Maitre")
Esempio n. 23
0
def populate(combinations, potential):
    for i in range(g.width):
        for j in range(g.width):
            potential[j][i] = c.Value(1, 0, 0)

    curIndex = 0
    for i in range(g.width):
        for j in range(g.width):
            #Check Horizontal wins
            if (j + (g.n - 1) < g.width):
                combinations.append([0] * g.n)

                for k in range(g.n):
                    combinations[curIndex][k] = (c.CoordinatePair(j + k, i))
                    potential[j + k][i].thirdPriority += 1

                curIndex += 1

            #Check Vertical wins
            if (i + (g.n - 1) < g.width):
                combinations.append([0] * g.n)

                for k in range(g.n):
                    combinations[curIndex][k] = (c.CoordinatePair(j, i + k))
                    potential[j][i + k].thirdPriority += 1

                curIndex += 1

            #Check Up-Right wins
            if (j + (g.n - 1) < g.width and i - (g.n - 1) >= 0):
                combinations.append([0] * g.n)

                for k in range(g.n):
                    combinations[curIndex][k] = (c.CoordinatePair(
                        j + k, i - k))
                    potential[j + k][i - k].thirdPriority += 1

                curIndex += 1

            #Check Down-Right wins
            if (j + (g.n - 1) < g.width and i + (g.n - 1) < g.width):
                combinations.append([0] * g.n)

                for k in range(g.n):
                    combinations[curIndex][k] = (c.CoordinatePair(
                        j + k, i + k))
                    potential[j + k][i + k].thirdPriority += 1

                curIndex += 1
Esempio n. 24
0
def loadBridge(bridgeID):
    jointList = []
    bridgeFile, dif, land = BridgeData.getBridgeFile(bridgeID)
    bridgeFile = eval(bridgeFile.strip("'"))
    jointNum = len(bridgeFile)
    materialStack = []
    added = False
    for joint in bridgeFile:
        jointX, jointY = bridgeFile[joint]['location']
        jointList.append({
            'index': int(joint),
            'point': (jointX * 20, 600 - jointY * 20)
        })
    for joint in bridgeFile:
        joint1 = int(joint)
        for connectedJoint in bridgeFile[joint]['connectedJoints']:
            joint2 = int(connectedJoint['joint'])
            for material in materialStack:
                if (material.getJoint1() == joint1 and material.getJoint2()
                        == joint2) or (material.getJoint1() == joint2
                                       and material.getJoint2() == joint1):
                    added = True
            if added == False:
                if connectedJoint['material'] == 'Steel':
                    item = Classes.Steel()
                elif connectedJoint['material'] == 'Wood':
                    item = Classes.Wood()
                elif connectedJoint['material'] == 'Road':
                    item = Classes.Road()
                elif connectedJoint['material'] == 'Rope':
                    item = Classes.Rope()
                elif connectedJoint['material'] == 'Cable':
                    item = Classes.Cable()
                item.setjoint1(joint1)
                item.setjoint2(joint2)
                materialStack.append(item)
            else:
                added = False

    for material in materialStack:
        for joint in jointList:
            if int(material.getJoint1()) == int(joint['index']):
                jointX, jointY = joint['point']
                material.setCo1(jointX, jointY)
            elif int(material.getJoint2()) == int(joint['index']):
                jointX, jointY = joint['point']
                material.setCo2(jointX, jointY)

    return [materialStack, jointList, jointNum, dif, land]
def reset_backup():
    global found_zone
    global found_country
    global found_region
    global found_location
    found_zone = found_country = found_region = found_location = False

    global backup_zone
    global backup_country
    global backup_region
    global backup_location
    backup_zone = clss.Zone("")
    backup_country = clss.Country("")
    backup_region = clss.Region("")
    backup_location = clss.Location("")
Esempio n. 26
0
def simpleCrossOver(parent1=Classes.Chromosome(),
                    parent2=Classes.Chromosome()):

    child = Classes.Chromosome()

    for x in range(parent1.geneList.__len__()):

        z = np.random.random()

        if (z <= 0.5):
            child.geneList.append(parent1.geneList[x])

        elif (z > 0.5):
            child.geneList.append(parent2.geneList[x])

    return child
Esempio n. 27
0
def GetInput():
    key = pygame.key.get_pressed()
    for event in pygame.event.get():
        if event.type == QUIT or key[K_ESCAPE]:
            pygame.quit()
            sys.exit()
    if key[K_SPACE]:
        if p1.weapon_reloading_time == 0 and p1.energy >= 2.5:
            Fire("Forwards")
            if p1.fire_direction == "Forwards, Backward":
                Fire("Backwards")
            elif p1.fire_direction == "Forwards, Sides":
                Fire("Sides")
            elif p1.fire_direction == "Forwards, Backwards, Sides":
                Fire("Sides")
                Fire("Backwards")
            p1.energy -= 2.5
    if key[K_b]:
        if p1.bomb_reload_time == 100 and p1.bomb_ammo >= 1:
            Bombs.append(Classes.Bomb(p1, Images.BombImage))
            p1.bomb_ammo -= 1
            p1.bomb_reload_time = 0
    if key[K_s] and p1.energy >= p1.shield_discharge_rate:
        p1.shielded = True
    else:
        p1.shielded = False
    if key[K_LEFT]: p1.rotation += 1 * (IdealFPS / TargetFPS)
    if key[K_RIGHT]: p1.rotation -= 1 * (IdealFPS / TargetFPS)
    if key[K_UP]:
        p1.speed[0] -= p1.thrust * cos(radians(p1.rotation))
        p1.speed[1] -= p1.thrust * sin(radians(p1.rotation))
    if key[K_DOWN]:
        p1.speed[0] *= .99
        p1.speed[1] *= .99
Esempio n. 28
0
    def getUserForScannerID(self, p_scannerID):

        cursor = self.DB.cursor()

        cursor.execute(
            """
				SELECT *
				FROM TB_Users
				WHERE TB_Users.Index = (SELECT TB_Scanners.Index
							FROM TB_Scanners
							WHERE ScannerID = %s)
				""", (p_scannerID, ))

        results = cursor.fetchone()

        if (results == None):
            return None

        results = list(results)

        cursor.close()

        return Classes.User(str(results[0]), str(results[1]), str(results[2]),
                            str(results[3]), str(results[4]), str(results[5]),
                            str(results[6]), str(results[7]))
Esempio n. 29
0
 def initEnigma(mode, reflector, rotor1, rotor2, rotor3, pos1, pos2, pos3,
                p11, p12, p21, p22, p31, p32, p41, p42, p51, p52, p61, p62,
                p71, p72, p81, p82, p91, p92, p01, p02):
     #No two rotors can be the same.
     if rotor1.get() == rotor2.get() or rotor2.get() == rotor3.get(
     ) or rotor1.get() == rotor3.get():
         EnigmaProblem_label = Label(root, text='Problem Occurred!')
         EnigmaProblem_label.place(x=173, y=470)
     #in case the rotors are unique for one-another, we initialise the enigma machine object.
     else:
         r = findReflector(reflector.get())
         r1 = findRotor(rotor1.get())
         r2 = findRotor(rotor2.get())
         r3 = findRotor(rotor3.get())
         p1 = findPositioning(pos1.get())
         p2 = findPositioning(pos2.get())
         p3 = findPositioning(pos3.get())
         plugboard = [[p11.get(), p12.get()], [p21.get(),
                                               p22.get()],
                      [p31.get(), p32.get()], [p41.get(),
                                               p42.get()],
                      [p51.get(), p52.get()], [p61.get(),
                                               p62.get()],
                      [p71.get(), p72.get()], [p81.get(),
                                               p82.get()],
                      [p91.get(), p92.get()], [p01.get(),
                                               p02.get()]]
         m = mode.get()
         global Enigma
         Enigma = Classes.Enigma(m, r, r1, r2, r3, p1, p2, p3, plugboard)
         Enigmainit_label = Label(root, text='Enigma Started Successfully!')
         Enigmainit_label.place(x=143, y=470)
Esempio n. 30
0
def LoadMessagesFromDB(MessageDict):
    db = SqliteDatabase(Globals.EmailsFileName)
    if not db.OpenConnection():
        return

    query = "select FromID, ToID, EmailDate, Subject, Attachments, Size, TotalRecipients, `Group`, Label, DocID, FilePath, AttachmentsPath from " + Constants.EmailsTable + " order by EmailDate;"
    rows = db.FetchAllRows(query)

    #print 'query len ', len(rows)
    for row in rows:
        #totalAttachments = row[3].split(",")
        msg = Classes.EmailMessage()
        msg.Sender = row[0]
        msg.Recipient = row[1]
        msg.Date = row[2]
        msg.Subject = row[3]
        msg.Attachments = row[4]
        msg.Size = int(row[5])
        msg.TotalRecipients = int(row[6])
        msg.Group = int(row[7])
        msg.Label = row[8]
        msg.DocID = int(row[9])
        msg.filePath = row[10]
        msg.attachmentsPath = row[11]

        if MessageDict.has_key(row[2].lower()):
            MessageDict[row[2].lower()].append(msg)
        else:
            MessageDict[row[2].lower()] = [msg]

    #print 'msg dict ', len(MessageDict)
    db.CloseConnection()
Esempio n. 31
0
def text_parse(line, lno, curr_pos):
    global sym_no, use, taddr, stext
    flag = 0
    if (line == "section .text"):
        pass

    else:
        line = list(filter(lambda a: a != "", re.split(" |\t|,", line)))
        #For external function calling
        if (line[0] == "global" or line[0] == "extern"):
            #line = list(filter(lambda a: a != "" ,re.split(" |,",line[1])))
            for i in range(1, len(line)):
                sym_no += 1
                s = C.SymTab(sym_no, line[i], "-", "-", "LDEF", 0, lno, "TEXT",
                             taddr)
                Symbol_Table.append(s)
        #From main
        elif (len(line) == 1):
            if (line[0].endswith(":")):
                line[0] = line[0].replace(":", "")
                checkSym(line[0], lno)

        elif (len(line) >= 2):
            if (line[0].endswith(":")):
                line[0] = line[0].replace(":", "")
                checkSym(line[0], lno)
                inst_parse(line[1:4], lno)

            else:
                inst_parse(line[0:3], lno)
    taddr += 1
    stext += 2
Esempio n. 32
0
def kbb(T, k, Phi_mat, b, J):
    N = len(k)
    D = len(k[0])
    I2 = [[[] for j in range(D)] for i in range(N)]
    I3 = np.zeros((N, D, len(b)), float)
    Beta = Phi_mat.dot(b)
    for i in range(N):
        for j in range(D):
            Beta_ij = Beta[(i * (J + 1)) : (i * (J + 1) + J + 1), j]
            # on calcule pour k_ij, la matrice des k(s,t) pour s,t dans la grille de [0,Ti]
            grid = T[i] * 1.0 * np.arange(J + 1) / J
            vecarg = cg.expandnp([grid, grid])
            k_ij = np.apply_along_axis(k[i][j], 0, *(vecarg.T)).reshape(J + 1, J + 1)
            k_ij[0, :] = k_ij[0, :] * 0.5
            k_ij[J, :] = k_ij[J, :] * 0.5
            k_ij[:, 0] = k_ij[:, 0] * 0.5
            k_ij[:, J] = k_ij[:, J] * 0.5
            # On calcule alors l'intégrale Phi(s,Ti) k(s,t) Beta(t,Ti) sur [0,Ti]²
            I3[i, j, :] = (
                Beta_ij.dot(k_ij).dot(Phi_mat[(i * (J + 1)) : (i * (J + 1) + J + 1), :]) * (T[i] ** 2) / (J ** 2)
            )
            # Ainsi que l'intégrale k(s,t) Beta(s,Ti) Beta(t,Ti) sur [0,Ti]²
            # I2[i][j]=  Beta_ij.dot(k_ij).dot(Beta_ij)  * 1.*(T[i]**2)/(J**2)
            I2[i][j] = I3[i, j, :].dot(b)
    return (I2, I3)
Esempio n. 33
0
def median_operation(sk_sum, auths, dp):
    
    from numpy.random import laplace   
    
    proto = Classes.get_median(sk_sum, min_b = 0, max_b = 1000, steps = 20) #Compute Median
    plain = None
    total_noise = 0
    while True:
        v = proto.send(plain)
        if isinstance(v, int):
            break
        
        plain = collective_decryption(v, auths)
        
        if (conf.DP and dp):
            #print "sksum:" + str(sk_sum.epsilon)
            if sk_sum.epsilon != 0 and sk_sum.delta != 0:
                noise = 0
                #print conf.DP and dp
                scale = float(sk_sum.d) / float(sk_sum.epsilon)
                #print sk_sum.d
                #print sk_sum.epsilon
                noise = int(round(laplace(0, scale)))
                #print "noise: " + str(noise)
                plain += noise
                total_noise += noise
            
        #print "*: " + str(plain)

    #print "Estimated median: " + str(v)
    #print "Total Noise Added: " + str(total_noise)
    return str(v)
Esempio n. 34
0
def ISE(numbeta, Beta_fonc_est, b_learned, T, nb=40, plot_beta=False, resolution=100):
    ise = 0.0
    Tmax = np.max(T)
    Tmin = np.min(T)
    Tgrid = np.linspace(Tmin, Tmax, nb, retstep=True)
    step = Tgrid[1]
    Tgrid = Tgrid[0]
    grille = np.vstack((Tgrid, np.arange(nb)))
    count = 0
    for T_, i in grille.T:
        for t_ in np.arange(0.01, T_, step, float):
            count += 1
            true_b = cg.beta_fonc(t_, T_, numbeta)
            est_b = Beta_fonc_est(*([t_, T_] + list(b_learned[:, 0])))
            ise = ise + (true_b - est_b) ** 2
    ise = ise / count
    print("ISE : " + str(ise))
    if plot_beta:
        x = np.linspace(0.1, np.max(T), num=resolution)
        y = np.linspace(0.1, np.max(T), num=resolution)
        arr = [x, y]
        Grid = cg.expandnp(arr)
        x = Grid[:, 0]
        y = Grid[:, 1]
        arrV = np.zeros(resolution ** 2, float)
        n = 0
        for i in range(resolution):
            for j in range(resolution):
                if j <= i:
                    arrV[n] = Beta_fonc_est[0](x[n], y[n])
                n += 1
        Xfig = x.reshape((resolution, resolution))
        Yfig = y.reshape((resolution, resolution))
        Zfig = arrV.reshape((resolution, resolution))
        fig = plt.figure().add_subplot(111)
        plt.imshow(
            Zfig,
            vmin=Zfig.min(),
            vmax=Zfig.max(),
            origin="lower",
            extent=[Yfig.min(), Yfig.max(), Xfig.min(), Xfig.max()],
        )
        plt.colorbar()
    return ise
Esempio n. 35
0
 def envoyerFlotte(self):
     if(self.vue.choisirNbVaisseaux.get() > 0):
         self.modele.humain.listeFlottes.append(Classes.flotteDeVaisseaux(self.vue.choisirNbVaisseaux.get(), self.modele.listeEtoiles[self.modele.etoileDepart], self.modele.listeEtoiles[self.modele.etoileArrivee], 1, self.modele.temps_courant))
         self.modele.listeEtoiles[self.modele.etoileDepart].nbVaisseaux -= self.vue.choisirNbVaisseaux.get()
         etoileDepart = None
         etoileDepart = None
         self.vue.surfaceJeu.delete("selection")
         self.vue.choisirNbVaisseaux.set(0)
         self.vue.choisirNbVaisseaux.place_forget()
         self.vue.boutonEnvoyerFlotte.place_forget()
Esempio n. 36
0
    def __init__(self):
        C.logandprint("Started initialization!")

        #defines what characters define comments
        commentchars = [";", "$", "#", "/", "!", "@"]

        #opens the config file about the maps
        firstmap = open("..\\config\\firstmap.txt", "r")

        #Filters comments from the first line and gets the map's name
        firstlvl = firstmap.readline()
        if commentchars.__contains__(firstlvl[1]):
            firstlvl = firstmap.readline()
        if firstlvl[len(firstlvl)-2:] == "\n":
            firstlvl = firstlvl[:-2]

        #Starts renderer
        self.renderer = R.GameRender()

        #Starts the new game
        Thegame = C.Game(firstlvl, self)

        #starts tickloop of renderer
        self.renderer.render()

        C.logandprint("Finished initialization!")
        C.logandprint("=========================\n")
        #Starts tickloop of new game
        Thegame.Tick()
Esempio n. 37
0
def saveRGBValues(image,fromDevice):
    im = 0
    imageWidth = 320
    imageHeight = 240
    imgFile = ""
    
    if fromDevice == 'NAO':
        imageWidth = image[0]                                           # width of the image
        imageHeight = image[1]                                          # height of the image
        imageData = image[6]                                            # array of pixel values
        imgFile = "image.txt"
    
        im = Image.frombytes("RGB", (imageWidth, imageHeight), imageData)
        im = im.resize((imageWidth / 10, imageHeight / 10))
        #im = im.rotate(180) --> use this when you have normal nao with normal cam ! :P
    elif fromDevice == 'WEBCAM':
        #im = Image.fromstring("RGB", cv.GetSize(image), image.tostring())
        imgFile = "image1.txt"
        im = image
        im = im.resize((imageWidth / 10, imageHeight / 10))
    #im.show()
    

    px = im.load()
    
    with open(imgFile, "w") as imageFile:
        width, height = im.size
        for x in range(width):
            for y in range(height):
                if (2*px[x,y][0] - px[x,y][1] - px[x,y][2]) / 2 < 50:
                    px[x,y] = (0,0,0)
                else:
                    px[x,y] = (255,255,255)
                    
        for pixel in im.getdata():
            p1 = Classes.inputCode(pixel[0])
            p2 = Classes.inputCode(pixel[1])
            p3 = Classes.inputCode(pixel[2])
            imageFile.write(str(p1) + "\n" + str(p2) + "\n" + str(p3) + "\n")
Esempio n. 38
0
def Pre_Comp_YX(L, T, Xdata, Y, Kbeta, J):
    t = sy.Symbol("t")
    s = sy.Symbol("s")
    # Récupération des variables et paramètres
    N = len(L)
    D = len(L[0])
    # ----------------- Construction de la base fonctionnelle
    syPhi = sy.ones(Kbeta ** 2, 1)
    syb = sy.ones(1, Kbeta ** 2)
    v = [np.arange(Kbeta), np.arange(Kbeta)]
    expo = cg.expandnp(v)
    Phi_fonc = [[] for j in range(Kbeta ** 2)]
    for x in range(len(expo[:, 0])):
        syPhi[x] = (t ** expo[x, 0]) * (s ** expo[x, 1])
        Phi_fonc[x] = sy.lambdify((t, s), syPhi[x], "numpy")
        syb[x] = sy.Symbol("b" + str(x))
    syBeta = syb * syPhi
    Phi_mat = Comp_Phi(Phi_fonc, T, J)
    I_pen = J22_fast(syPhi, np.max(T), 50)[3]
    # ----------------- Construction des noyaux et leurs dérivées
    # Construction de la forme du noyau
    el1 = sy.Symbol("el1")
    per1 = sy.Symbol("per1")
    sig1 = sy.Symbol("sig1")
    args1 = [el1, per1, sig1]
    el2 = sy.Symbol("el2")
    sig2 = sy.Symbol("sig2")
    args2 = [el2, sig2]
    syk = cg.sy_Periodic((s, t), *args1) + cg.sy_RBF((s, t), *args2)
    args = [t, s] + args1 + args2
    # Dérivation et construction des fonctions vectorielles associées
    k_fonc = sy.lambdify(tuple(args), syk, "numpy")
    n_par = len(args) - 2
    k_der = [[] for i in range(n_par)]
    for i in range(n_par):
        func = syk.diff(args[i + 2])
        k_der[i] = sy.lambdify(tuple(args), func, "numpy")
    return (Phi_mat, k_fonc, k_der, I_pen)
Esempio n. 39
0
def PhiK(L, T, k, Phi_mat, J):
    N = len(L)
    D = len(L[0])
    Ints = [[[] for j in range(D)] for i in range(N)]
    for i in range(N):
        for j in range(D):
            Phi_mat_i = Phi_mat[(i * (J + 1)) : (i * (J + 1) + J + 1), :].T
            t = L[i][j]
            grid = T[i] * 1.0 * np.arange(J + 1) / J
            vecarg = cg.expandnp([t, grid])
            K_ij = np.apply_along_axis(k[i][j], 0, *(vecarg.T)).reshape(J + 1, len(t))
            K_ij[0, :] = K_ij[0, :] * 0.5
            K_ij[J, :] = K_ij[J, :] * 0.5
            Ints[i][j] = (T[i] / J) * Phi_mat_i.dot(K_ij)
    return Ints
def draw_rectangles(orig_img, save_img, rects):

    from PIL import Image,ImageDraw


    bb_img = Image.open(orig_img)
    # print orig_img
    for bb_rect in rects:
    ################ Adding Rectangle ###################
        dr = ImageDraw.Draw(bb_img)
        cor = (bb_rect.x1,bb_rect.y1,bb_rect.x2 ,bb_rect.y2) # DA VERIFICARE Try_2 (x1,y1, x2,y2) cor = (bb_rect.left() ,bb_rect.right(),bb_rect.bottom(),bb_rect.top()) Try_1
        if bb_rect.silhouetteID is  -1:
            outline_class=(240,255,240)
        else :  
            outline_class=Classes.code_to_color(bb_rect.silhouetteID)
        dr.rectangle(cor, outline=outline_class)
    # print save_img  
    bb_img.save(save_img)
Esempio n. 41
0
def construct_beta(Kbeta):
    # symbole associé au petit t (c'est à dire l'instant dans la période de suivi)
    t = sy.Symbol("t")
    # smbole associé au grand T (c'est à dire la durée de suivie)
    s = sy.Symbol("s")
    syPhi = sy.ones(Kbeta, 1)
    syb = sy.ones(1, Kbeta)
    b = [[] for k in range(Kbeta)]
    v = [np.arange(np.sqrt(Kbeta)), np.arange(np.sqrt(Kbeta))]
    expo = cg.expandnp(v)
    for x in range(len(expo[:, 0])):
        syPhi[x] = (t ** expo[x, 0]) * (s ** expo[x, 1])
        syb[x] = sy.Symbol("b" + str(x))
        b[x] = sy.Symbol("b" + str(x))
    syBeta = syb * syPhi
    syBeta = syBeta[0, 0]
    arg = [t, s] + b
    Beta_fonc_est = sy.lambdify(tuple(arg), syBeta, "numpy")
    return Beta_fonc_est
Esempio n. 42
0
def Comp_Psi(L, k_fonc, Theta, Gamma, i_subset=None):
    N = len(L)
    D = len(L[0])
    Psi = [[[] for j in range(D)] for i in range(N)]
    Det = np.ones((N, D), float)
    if i_subset is None:
        veci = range(N)
    else:
        veci = i_subset
    for i in veci:
        for j in range(D):
            t_ij = L[i][j]
            m_ij = len(t_ij)
            vec = cg.expandnp([t_ij, t_ij])
            args = list(vec.T) + list(Theta[i, j, :])
            K = np.apply_along_axis(k_fonc, 0, *args).reshape((m_ij, m_ij))
            Psi[i][j] = sc.linalg.inv(K + np.eye(m_ij) * Gamma[i, j] ** 2)
            Det[i, j] = sc.linalg.det(K + np.eye(m_ij) * Gamma[i, j] ** 2, check_finite=False)
            if Det[i, j] == 0.0:
                Det[i, j] = 0.01
    return (Psi, Det)
Esempio n. 43
0
def Ct_dec_unit_test(plaintext):

        G = EcGroup()
        x_1 = G.order().random()
        y_1 = x_1 * G.generator()
    
        E1 = Classes.Ct.enc(y_1, plaintext)
        E = copy(E1)

        return (E.dec(x_1) == plaintext)




for trunc in range(1,0,-1):
	Classes.reload_tables(trunc, conf.FN_I_TABLE[:-3] + "_" + str(trunc) + ".db", conf.FN_N_TABLE[:-3] + "_" + str(trunc) + ".db")     
	print "size: " + str(len(Classes._table))
	total = 0
	for i in range(100):
		print "."
		num = randint(conf.LOWER_LIMIT,conf.UPPER_LIMIT)
		tic = time.clock()
		Ct_dec_unit_test(num)
		toc = time.clock()
		total += (toc - tic)
		
		
	print str(trunc) + ": " + str(total/5)

Esempio n. 44
0
Bullets = []
Bombs = []

Level = 0

Font = pygame.font.SysFont("Times New Roman", 8)
Font2 = pygame.font.SysFont("Times New Roman", 10)
Font3 = pygame.font.SysFont("Times New Roman", 16)

Clock = pygame.time.Clock()
TargetFPS = 50.0  # 200.0, 100.0, 50.0, 25.0, 13.0
IdealFPS = 200.0

import Images, Classes

Classes.init(Screen)

p1 = Classes.Player()


def Fire(direction):
    if direction == "Sides":
        Bullets.append(Classes.Bullet(p1, "Left Side", -p1.rotation))
        Bullets.append(Classes.Bullet(p1, "Right Side", -p1.rotation))
    elif direction == "Forwards":
        if p1.forward_fire_type == "Single Shot":
            Bullets.append(Classes.Bullet(p1, direction, -p1.rotation))
        elif p1.forward_fire_type == "Double Shot":
            Bullets.append(Classes.Bullet(p1, direction, -p1.rotation - 5))
            Bullets.append(Classes.Bullet(p1, direction, -p1.rotation + 5))
        elif p1.forward_fire_type == "Triple Shot":
Esempio n. 45
0
from time import sleep
import Classes as C
from visual import *
C.logandprint("Finished importing VPython!")
import wx
C.logandprint("Finished importing wx!")

app = wx.App(False)
scsize = wx.GetDisplaySize()

class baseRendererClass(object):
    pass

class RendererBrush(baseRendererClass):
    def __init__(self, corrbrush, corrbox):
        self.brush = corrbrush
        self.box = corrbox

    def Tick(self):
        renderx, rendery, renderz = self.brush.x, self.brush.y, self.brush.z
        self.box.pos = (renderx, renderz, rendery)
        self.box.width, self.box.lenght, self.box.height = self.brush.breadth, self.brush.width, self.brush.height

class RendererActor(baseRendererClass):
    def __init__(self, corractor, corrsphere):
        self.actor = corractor
        self.sphere = corrsphere

    def Tick(self):
        renderx, rendery, renderz = self.actor.x, self.actor.y, self.actor.z
        self.sphere.pos = (renderx, renderz, rendery)
def parse_XML_lightweight_txt(bb_XML_file_list, path_val_folder, path_dataset):

    count_rect = 0
    count_img = 0

    progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',progressbar.Percentage(), ' ',progressbar.ETA()])

    print "Start Processing & Building Dataset... may take a while..."

    path_mltcl_bb_file=path_dataset+'/'+string_mltcl_bb_file # Create this file in .dataset/airplane/airplane_bb_mltcl_file_list.txt
    path_mltcl_class_code_file=path_dataset+'/'+string_mltcl_class_code_file
    path_mltcl_class_name_file=path_dataset+'/'+string_mltcl_class_name_file
    path_mltcl_chall_code_file=path_dataset+'/'+string_mltcl_chall_code_file

    for file_name in progress(bb_XML_file_list):
        with open(file_name, 'rt') as f:
            tree = ElementTree.parse(f)
            for obj in tree.findall('object'):
                name = obj.find('name').text
                class_code= name
                name = Classes.code_to_class_string(name)

                if name in ["nothing"]:
                    continue
                else:
                    
                    same_label=0
                    #The files with the original data path are made in both: multiclass e single class
                    
                    
                    path_bb_file=path_dataset+'/'+name+'/'+ name+string_bb_file
                    path_class_code_file= path_dataset+'/'+name+'/'+name+string_class_code_file
                    path_class_name_file= path_dataset+'/'+name+'/'+name+string_class_name_file
                    path_chall_code_file= path_dataset+'/'+name+'/'+name+string_chall_code_file


                    path_orig_file=path_val_folder

                    
                    jump=0
                    
                    image_single_class= Picture_Info()
                    image_single_class.dataset_path= path_val_folder

                    image_multi_class= Picture_Info()
                    image_multi_class.dataset_path= path_val_folder


                    rectangle_single= BB_Rectangle()
                    rectangle_multi= BB_Rectangle()
                    
                    #xmin x1 letf
                    #ymin y1 bottom
                    #xmax x2 right
                    #ymax y2 top
                
                    for node in tree.iter():
                        tag=str(node.tag)
            
                        if tag in ["folder"]:
                            path_orig_file=path_orig_file+'/'+str(node.text)
                            image_single_class.folder= str(node.text)                            
                            image_multi_class.folder= str(node.text)

                        if tag in ["filename"]:
                            image_single_class.filename=str(node.text)+'.PNG'
                            image_multi_class.filename=str(node.text)+'.PNG'

                            path_orig_file=path_orig_file+'/'+str(node.text)+'.JPEG'

                        if tag in ['name']:
                            if str(Classes.code_to_class_string(str(node.text))) in ["nothing"]:
                                jump = 1
                            else : 
                                jump=0
                                rectangle_multi.label_chall=int(Classes.class_string_to_comp_code(str(Classes.code_to_class_string(str(node.text)))))
                                rectangle_multi.label_code=str(node.text)
                                rectangle_multi.label=Classes.code_to_class_string(str(node.text))

                                if str(node.text) == class_code: 
                                    same_label = 1
                                    rectangle_single.label_chall=int(Classes.class_string_to_comp_code(str(Classes.code_to_class_string(str(node.text)))))
                                    rectangle_single.label_code=str(node.text)
                                    rectangle_single.label=Classes.code_to_class_string(str(node.text))
                                else: same_label = 0
                                
                        if tag in ["xmax"]:
                            if jump == 0:
                                rectangle_multi.x2=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                                if same_label==1:
                                    rectangle_single.x2=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                        if tag in ["xmin"]:
                            if jump == 0:
                                rectangle_multi.x1=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                                if same_label==1:
                                    rectangle_single.x1=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                        if tag in ["ymax"]:
                            if jump == 0:
                                rectangle_multi.y2=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))                            
                                image_multi_class.append_rect(rectangle_multi) 
                                count_rect=count_rect+1
                                if same_label==1:
                                    rectangle_single.y2=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                                    image_single_class.append_rect(rectangle_single)
                        if tag in ["ymin"]:
                            if jump == 0:    
                                rectangle_multi.y1=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))
                                if same_label==1:
                                    rectangle_single.y1=float(Utils_Image.transform_point(image_multi_class.width,image_multi_class.height,width, height,float(node.text), False))

                    if jump == 0:
                        
                        count_img=count_img+1

                        out_stream = open(path_mltcl_bb_file, "a")
                        out_stream.write(image_multi_class.get_info_string()+ os.linesep)
                        
                        out_stream = open(path_mltcl_class_code_file, "a")
                        out_stream.write(image_multi_class.get_rects_code()+ os.linesep)
                        
                        out_stream = open(path_mltcl_class_name_file, "a")
                        out_stream.write(image_multi_class.get_rects_labels()+ os.linesep)
                        
                        out_stream = open(path_mltcl_chall_code_file, "a")
                        out_stream.write(image_multi_class.get_rects_chall() + os.linesep)

                        if same_label==1:
                            out_stream = open(path_bb_file, "a")
                            out_stream.write(image_single_class.get_info_string()+ os.linesep)
                            
                            out_stream = open(path_class_code_file, "a")
                            out_stream.write(image_single_class.get_rects_chall()+ os.linesep)
                            
                            out_stream = open(path_class_name_file, "a")
                            out_stream.write(image_single_class.get_rects_labels()+ os.linesep)
                            
                            out_stream = open(path_chall_code_file, "a")
                            out_stream.write(image_single_class.get_rects_code() + os.linesep)
                    break
    print "SUMMARY:"
    print "Parsed: %d BB Files"%len(bb_XML_file_list)
    print "Added: %d Object Rectangles"%count_rect
    print "Added: %d Images"%count_img
    if count_img>0: 
        print "Ratio BB_Files/Images: %.2f"%(float(count_img)/float(len(bb_XML_file_list)))
    if count_rect>0:
        print "Ratio Images/Object_Rectangles: %.2f"%(float(count_img)/float(count_rect))
Esempio n. 47
0
def L_YX(
    P, Z, L, T, Xdata, Y, Phi_mat, k_fonc, k_der, Stochastic=False, Gradient=True, I_pen=None, Lambda=None, i_liste=None
):
    # Récupération des variables et paramètres
    N = len(L)
    D = len(L[0])
    p = Z.shape[1]
    Kbeta = Phi_mat.shape[1]  # Kbeta est ici la taille de la base complète
    J = int(-1 + Phi_mat.shape[0] / N)
    Alpha = P[0:p]
    b = P[p : (D * Kbeta + p)].reshape((Kbeta, D))
    Sigma2 = 1.0
    Eta = P[(D * Kbeta + p) : (N * D + D * Kbeta + p)].reshape((N, D))  # Sous forme d'array de taille (N,D)
    Gamma = P[(N * D + D * Kbeta + p) : (2 * N * D + D * Kbeta + p)].reshape(
        (N, D)
    )  # Sous forme d'array de taille (N,D)
    n_par = len(k_der)
    Theta = P[(2 * N * D + D * Kbeta + p) : ((2 + n_par) * N * D + D * Kbeta + p)].reshape(
        (N, D, n_par)
    )  # Sous forme d'array de taille (N,D,n_par)
    # --------------------------Options
    if Stochastic:
        # Si l'option stochastique est activée, on ne tient pas compte de la liste de i soumise
        I = np.random.randint(0, N)
        i_liste = [I]
    # Calcul des Psi, on ne calcule que ceux dont l'indice doit être évalué
    if i_liste is not None:
        (Psi, Det) = Comp_Psi(L, k_fonc, Theta, Gamma, i_subset=i_liste)
        seq_i = i_liste
        isit = np.array([(k in i_liste) for k in range(N)])
    else:
        (Psi, Det) = Comp_Psi(L, k_fonc, Theta, Gamma)
        seq_i = range(N)
        isit = np.ones(N, float)
    # Vecteurs contenant respectivement les espérances de Yi | Xi notées Ei et leurs variances Vi
    (EY, VY) = (np.zeros(N, float), np.ones(N, float))
    Beta = Phi_mat.dot(b)
    # Matrices contenant les Int_[0,Ti] E(F_ij(s)|X_ij)Beta_j(s,Ti) ds et les les Int_[0,Ti]² Cov(F_ij(s),F_ij(t)|X_ij) Beta_j(s,Ti)Beta_j(t,Ti) dsdt
    (EY_Int, VY_Int) = (np.zeros((N, D), float), np.ones((N, D), float))
    # Matrice des dEi/dbj et dVi/dbj
    (dEdb, dVdb) = (np.zeros((N, D, Kbeta), float), np.zeros((N, D, Kbeta), float))
    # Gradient
    (dEdEta, dLXdEta) = (np.zeros((N, D), float), np.zeros((N, D), float))
    (dEdGamma, dVdGamma, dLXdGamma) = (np.zeros((N, D), float), np.zeros((N, D), float), np.zeros((N, D), float))
    (dEdTheta, dVdTheta, dLXdTheta) = (
        np.zeros((N, D, n_par), float),
        np.zeros((N, D, n_par), float),
        np.zeros((N, D, n_par), float),
    )
    Dkij = np.zeros((n_par, J + 1, J + 1), float)
    XPsiX = np.zeros((N, D), float)
    # On prépare la matrice de rankisation
    Id = np.eye(Kbeta)
    add_diag = np.zeros(D, float)
    for j in range(D):
        add_diag[j] = b[:, j].dot(Id).dot(b[:, j])
    # Calcul des quantités pour dL/dEtaij
    Grad = np.zeros(len(P), float)
    Un = np.ones(J + 1, float)
    Un[0] = 0.5
    Un[J] = 0.5
    for i in seq_i:
        grid = T[i] * 1.0 * np.arange(J + 1) / J
        vecarg = cg.expandnp([grid, grid])
        Beta_i = Beta[(i * (J + 1)) : (i * (J + 1) + J + 1), :]
        Phi_mat_i = Phi_mat[(i * (J + 1)) : (i * (J + 1) + J + 1), :].T
        for j in range(D):
            Xij = Xdata[i][j]
            t_ij = L[i][j]
            m_ij = len(t_ij)
            # Moyenne de F_ij
            Etaij = Eta[i, j]
            # Evaluation du noyau k_ij sur la grille
            k_ij = np.apply_along_axis(k_fonc, 0, *(list(vecarg.T) + list(Theta[i, j, :]))).reshape((J + 1, J + 1))
            k_ij[0, :] = k_ij[0, :] * 0.5
            k_ij[J, :] = k_ij[J, :] * 0.5
            k_ij[:, 0] = k_ij[:, 0] * 0.5
            k_ij[:, J] = k_ij[:, J] * 0.5
            vecarg2 = cg.expandnp([t_ij, grid])
            K_ij = np.apply_along_axis(k_fonc, 0, *(list(vecarg2.T) + list(Theta[i, j, :]))).reshape(J + 1, m_ij)
            K_ij[0, :] = K_ij[0, :] * 0.5
            K_ij[J, :] = K_ij[J, :] * 0.5
            KPsi = K_ij.dot(Psi[i][j])
            PsiX = Psi[i][j].dot(Xij - Etaij)
            # Calcul de la composante de Ei selon la jème VFT
            Phi_EspFij = Phi_mat_i.dot(Etaij * Un + KPsi.dot(Xij - Etaij)) / J
            EY_Int[i, j] = b[:, j].dot(Phi_EspFij)
            # Calcul de la composante de Vi selon la jème VFT
            V_i = Phi_mat_i.dot(k_ij - KPsi.dot(K_ij.T)).dot(Phi_mat_i.T)
            Phi_CovFij = V_i.dot(b[:, j]) / (J ** 2)
            # Ajout d'une matrice diagonale faible pour rankiser V^i_j
            extra_butter = add_diag[j] * 0.01 * np.trace(V_i) / Kbeta
            VY_Int[i, j] = b[:, j].dot(Phi_CovFij)  # + extra_butter
            XPsiX[i, j] = (Xij - Etaij).dot(PsiX)

            if Gradient:
                # Calcul de l'intégrale de dEi/dbj
                dEdb[i, j, :] = Phi_EspFij
                # Calcul de l'intégrale de dEi/dbj
                dVdb[i, j, :] = 2 * Phi_CovFij
                # Evaluation de dérivées du noyau sur la grille
                vecarg3 = cg.expandnp([t_ij, t_ij])
                DK_ij = np.zeros((n_par, J + 1, m_ij), float)
                DKt_ij = np.zeros((n_par, m_ij, m_ij), float)
                for npa in range(n_par):
                    Dkij[npa, :, :] = np.apply_along_axis(
                        k_der[npa], 0, *(list(vecarg.T) + list(Theta[i, j, :]))
                    ).reshape((J + 1, J + 1))
                    DK_ij[npa, :, :] = np.apply_along_axis(
                        k_der[npa], 0, *(list(vecarg2.T) + list(Theta[i, j, :]))
                    ).reshape(J + 1, m_ij)
                    DKt_ij[npa, :, :] = np.apply_along_axis(
                        k_der[npa], 0, *(list(vecarg3.T) + list(Theta[i, j, :]))
                    ).reshape(m_ij, m_ij)
                Dkij[:, 0, :] = Dkij[:, 0, :] * 0.5
                Dkij[:, J, :] = Dkij[:, J, :] * 0.5
                Dkij[:, :, 0] = Dkij[:, :, 0] * 0.5
                Dkij[:, :, J] = Dkij[:, :, J] * 0.5
                DK_ij[:, 0, :] = DK_ij[:, 0, :] * 0.5
                DK_ij[:, J, :] = DK_ij[:, J, :] * 0.5
                # Calcul des quantités pour dL/dThetaij
                BetaDK_ij = Beta_i[:, j].dot(DK_ij)
                BetaKPsiDKt_ij = Beta_i[:, j].dot(np.transpose(KPsi.dot(DKt_ij), (1, 0, 2)))
                dEdTheta[i, j, :] = (BetaDK_ij + BetaKPsiDKt_ij).dot(PsiX) / J
                dVdTheta[i, j, :] = (Beta_i[:, j].dot(Dkij) + (-2 * BetaDK_ij + BetaKPsiDKt_ij).dot(KPsi.T)).dot(
                    Beta_i[:, j]
                ) / J ** 2
                dLXdTheta[i, j, :] = -PsiX.T.dot(DKt_ij).dot(PsiX) + np.trace(DKt_ij.dot(Psi[i][j]), axis1=1, axis2=2)
                # Calcul des quantités pour dL/dGammaij
                dEdGamma[i, j] = Beta_i[:, j].dot(KPsi.dot(PsiX)) / J
                dVdGamma[i, j] = Beta_i[:, j].dot(k_ij - KPsi.dot(KPsi.T)).dot(Beta_i[:, j]) / J ** 2
                dLXdGamma[i, j] = -(PsiX.T).dot(PsiX) + np.trace(Psi[i][j])
                # Calcul des quantités pour dL/dEtaij
                dEdEta[i, j] = Beta_i[:, j].dot(Un + KPsi.dot(np.ones(m_ij))) / J
                dLXdEta[i, j] = -2 * PsiX.T.dot(np.ones(m_ij)) + 2 * np.ones(m_ij).dot(Psi[i][j]).dot(np.ones(m_ij))

        # On calcule l'espérance de Y sachant X avec l'espérance de Y et le terme de conditionnement gaussien
        EY[i] = Z[i].dot(Alpha) + np.sum(EY_Int[i, :])
        # On calcule la variance de Y sachant X avec le terme de variance issu des VFT X^i_j et de l'erreur résiduelle
        VY[i] = np.sum(VY_Int[i, :]) + Sigma2
    # Calcul de la vraisemblance
    LYX = np.sum(isit * ((Y - EY) ** 2 / VY + np.log(VY))) + np.sum(XPsiX.reshape(-1)) + np.sum(np.log(Det.reshape(-1)))
    if Lambda is not None:
        (Pen, dPen) = Comp_Pen(I_pen, b.reshape(-1), D, Kbeta)
        LYX += Lambda * Pen
    if Gradient:
        # Calcul du Gradient
        a = isit * (-2 * (Y - EY) / VY)
        b = isit * ((np.ones(N, float) - (Y - EY) ** 2 / VY) / VY)
        # Par rapport à Alpha
        Grad[0:p] = np.ones(N, float).dot(a.repeat(p, axis=0).reshape((N, p)) * Z).reshape(-1)
        # Par rapport à b_j pour tout j de 1 à D
        dL_YlXdb = np.zeros((Kbeta, D))
        A = a.repeat(Kbeta, axis=0).reshape((N, Kbeta))
        B = b.repeat(Kbeta, axis=0).reshape((N, Kbeta))
        for j in range(D):
            Grad[(p + j * Kbeta) : (p + (j + 1) * Kbeta)] = np.ones(N, float).dot(A * dEdb[:, j, :] + B * dVdb[:, j, :])
        if Lambda is not None:
            Grad[p : (p + D * Kbeta)] += Lambda * dPen
        # Par rapport à Eta, Theta et Gamma
        # Eta
        A = (cg.expandnp([a, np.ones(D)]).T)[0].reshape(D, N).T
        B = (cg.expandnp([b, np.ones(D)]).T)[0].reshape(D, N).T
        Grad[(D * Kbeta + p) : (N * D + D * Kbeta + p)] = (A * dEdEta + dLXdEta).reshape(-1)
        # Gamma
        Grad[(D * Kbeta + p + N * D) : (D * Kbeta + p + 2 * N * D)] = (A * dEdGamma + B * dVdGamma + dLXdGamma).reshape(
            -1
        )
        # Theta
        A = np.transpose((cg.expandnp([a, np.ones(n_par * D)]).T)[0].reshape(n_par, D, N), (2, 1, 0))
        B = np.transpose((cg.expandnp([b, np.ones(n_par * D)]).T)[0].reshape(n_par, D, N), (2, 1, 0))
        Grad[(p + D * Kbeta + 2 * N * D) : ((2 + n_par) * N * D + D * Kbeta + p)] = (
            A * dEdTheta + B * dVdTheta + dLXdTheta
        ).reshape(-1)
        # On renvoie le critère ainsi que le gradient
        if Stochastic:
            return (LYX, Grad, I)
        else:
            return (LYX, Grad, None)
    else:
        if Stochastic:
            return (LYX, None, I)
        else:
            return (LYX, None, None)
Esempio n. 48
0
def pre_process_dataset(bb_XML_file_list, path_val_folder, path_dataset):

    with open(path_dataset+'/dataset_summary.txt', 'w') as summary:
        for class_code in CL.class_code_string_list:
            start_string="Starting making files for class code: %s ; name: %s, May take a while.... "%(class_code, Classes.code_to_class_string(class_code))
            staring_xml_string="Strating xml files: %d"%len(bb_XML_file_list)
            print start_string+ '/n', staring_xml_string+'/n'
            summary.write(start_string+ os.linesep+staring_xml_string+ os.linesep)
            progress = progressbar.ProgressBar(widgets=[progressbar.Bar('=', '[', ']'), ' ',progressbar.Percentage(), ' ',progressbar.ETA()])
            tot_rect_class=0
            count_xml=0
            bb_folder_path=path_dataset+'/annotations/'+class_code+'/'
            data_folder_path=path_dataset+'/data/'+class_code+'/'
            for file_name in progress(bb_XML_file_list): 
                removed=0            
                delete=False
                with open(file_name, 'rt') as f:
                    #print "File Opened: %s"%file_name
                    tree_new = ElementTree.parse(f)
                    root_new = tree_new.getroot()
                    parent_map_new = dict((c, p) for p in tree_new.getiterator() for c in p)
                    count_rect=0
                    # list so that we don't mess up the order of iteration when removing items.
                    for obj in list(tree_new.findall('object')):
                        obj_class_code = obj.find('name').text
                        if obj_class_code == str(class_code):
                            #print "Founded Object: %s"%Classes.code_to_class_string(obj_class_code)
                            #count_rect+1 there's an object of that class in the xml file
                            count_rect=count_rect+1
                            delete=True
                        else:
                            #eliminate node
                            #print "Eliminated Node: %s"%Classes.code_to_class_string(obj_class_code)
                            parent_map_new[obj].remove(obj)
                            removed=removed+1
                    if count_rect>0:
                        ### Means the file belongs to the class so we change filename and directory name and we copy the image to the dataset
                        for node in tree_new.iter():
                            tag=str(node.tag)
                            if tag in ["folder"]:
                                path_orig_file=path_val_folder+'/'+str(node.text)
                                node.text= data_folder_path
                                # print "Changed folder from: %s to : %s"%(path_orig_file, node.text)
                            if tag in ["filename"]:
                                path_orig_file=path_orig_file+'/'+str(node.text)+'.JPEG'
                                new_filename=class_code+'_'+str(000000+count_xml)+'.JPEG'
                                path_new_file=data_folder_path+new_filename
                                node.text= new_filename
                                # print "Changed Name from: %s to : %s"%(path_orig_file, path_new_file)
                        xml_filename=bb_folder_path+class_code+'_'+str(000000+count_xml)+'.xml'
                        tree_new.write(xml_filename)
                        shutil.copy2(path_orig_file, path_new_file)
                        # print "Saved New .xml file: %s"%xml_filename
                        # print "Saved New .jpeg image: %s"%path_new_file
                        if (removed == 0 ) & delete:
                            os.remove(path_orig_file)
                            # print "Removed image: %s"%(path_orig_file)
                        count_xml=count_xml+1
                        tot_rect_class=tot_rect_class+count_rect
                        ##TODO: Copy Image
                # print "Count_Rect %d"%count_rect
                # print "Removed %d"%removed
                if (removed == 0 ) & delete:
                    os.remove(file_name)
                    # print "Removed XML: %s"%(file_name)
                    bb_XML_file_list.remove(file_name)
                if (removed >0)&(count_rect>0):
                    with open(file_name, 'rt') as f:
                        tree_new = ElementTree.parse(f)
                        root_new = tree_new.getroot()
                        parent_map_new = dict((c, p) for p in tree_new.getiterator() for c in p)
                        for obj in list(tree_new.findall('object')):
                            obj_class_code = obj.find('name').text
                            if obj_class_code == str(class_code):
                                parent_map_new[obj].remove(obj)
                        tree_new.write(file_name)
            end_string="Ended with Success Process for class:%s"%class_code 
            parsed_bb_string="Parsed: %d BB Files"%count_xml
            added_rect_String="Added: %d Object Rectangles"%tot_rect_class
            print end_string+'/n',parsed_bb_string +'/n',added_rect_String+'/n'
            summary.write(end_string+ os.linesep+parsed_bb_string+ os.linesep+added_rect_String+ os.linesep)
Esempio n. 49
0
    while not memoryProxy.getData("RearTactilTouched"):
        image = visionProxy.getImage()
        image1 = getImageFromCam()
        
        saveRGBValues(image,'NAO')
        saveRGBValues(image1,'WEBCAM')

        naoJoints = motionProxy.getJointValues("Head")
        
        nn_run = subprocess.Popen("./backprop", shell=True, stdout=subprocess.PIPE)
        nn_run.wait()
        if nn_run.returncode == 0:
            relativeJoints = nn_run.stdout.read()
            relativeJoints = relativeJoints.split()
            relativeJoints = [float(x) for x in relativeJoints]
            relativeJoints = [Classes.outputDecode(x) for x in relativeJoints]
            
            joints = []
            for joint, nao in zip(relativeJoints, naoJoints):
                joints.append(joint + nao[1])
            
            if joints[0] < -2.0857 or joints[0] > 2.0857: # dolava dprava max
                continue
            if joints[1] < -0.6720 or joints[1] > 0.5149: #hore dole max
                continue
            
            motionProxy.setJointValues("Head", joints)
   
    postureProxy.initPose(4)
    speakProxy.saySomething("Bye Bye")
    motionProxy.stiffnessOff("Body")
Esempio n. 50
0
#-------------------------------------------------------------------------------
# Name:        PyBotLauncher
# Purpose:     Zero-player game where bots fights monsters
#
# Author:      Gustavo Ramos "Gustavo6046" Rehermann
#
# Created:     09/03/2016
# Copyright:   (c) Gustavo Ramos "Gustavo6046" Rehermann, 2016
# Licence:     CC-BY-SA
#-------------------------------------------------------------------------------

import Classes as C
C.logandprint("Finished importing Classes!")
from time import sleep
C.logandprint("Finished importing sleep from time!")
import Renderer as R
C.logandprint("Finished importing the VPython renderer!")

def main():
    GameStarter = StartGame()

class StartGame():

    def __init__(self):
        C.logandprint("Started initialization!")

        #defines what characters define comments
        commentchars = [";", "$", "#", "/", "!", "@"]

        #opens the config file about the maps
        firstmap = open("..\\config\\firstmap.txt", "r")
Esempio n. 51
0
def J22_fast(syPhi, Tmax, J):
    # taille de la base fonctionnelle
    Kbeta = len(syPhi)
    # symbole associé au petit t (c'est à dire l'instant dans la période de suivi)
    t = sy.Symbol("t")
    # smbole associé au grand T (c'est à dire la durée de suivie)
    s = sy.Symbol("s")

    deb = time.clock()
    Phi = sy.ones(Kbeta, 1)
    for i in range(Kbeta):
        Phi[i] = syPhi[i]
    # dérivation de la base fonctionnelle
    (Phi_dsds, Phi_dsdt, Phi_dtdt) = (Phi.diff(s, s), Phi.diff(s, t), Phi.diff(t, t))

    (Phi_mat_dsds, Phi_mat_dsdt, Phi_mat_dtdt) = (
        np.zeros(((J + 1) ** 2, Kbeta), float),
        np.zeros(((J + 1) ** 2, Kbeta), float),
        np.zeros(((J + 1) ** 2, Kbeta), float),
    )
    # Grille d'intégration carré (on retire le triangle supérieur plus loin)
    t_arg = sc.linspace(0, Tmax, J + 1)
    s_arg = t_arg
    args = cg.expandnp([t_arg, s_arg]).T
    for i in range(Kbeta):
        func = sy.lambdify((t, s), Phi_dsds[i], "numpy")
        Phi_mat_dsds[:, i] = np.apply_along_axis(func, 0, *args)
        func = sy.lambdify((t, s), Phi_dsdt[i], "numpy")
        Phi_mat_dsdt[:, i] = np.apply_along_axis(func, 0, *args)
        func = sy.lambdify((t, s), Phi_dtdt[i], "numpy")
        Phi_mat_dtdt[:, i] = np.apply_along_axis(func, 0, *args)

    (Is, Ic, It) = (np.zeros((Kbeta, Kbeta), float), np.zeros((Kbeta, Kbeta), float), np.zeros((Kbeta, Kbeta), float))
    Un = np.ones(J + 1, float)
    # matrice triangulaire inférieure d'intégration
    a = cg.expandnp([np.arange(J + 1), np.arange(J + 1)])
    triang = np.asarray(a[:, 0] <= a[:, 1], float).reshape((J + 1, J + 1))
    # Calcul des intégrales
    for i in range(Kbeta):
        for j in range(Kbeta):
            if i <= j:
                Is[i, j] = (
                    Un.dot(
                        Phi_mat_dsds[:, j].reshape((J + 1, J + 1)) * Phi_mat_dsds[:, i].reshape((J + 1, J + 1)) * triang
                    ).dot(Un)
                    * (Tmax ** 2)
                    / (J * (J + 1))
                )
                Ic[i, j] = (
                    Un.dot(
                        Phi_mat_dsdt[:, j].reshape((J + 1, J + 1)) * Phi_mat_dsdt[:, i].reshape((J + 1, J + 1)) * triang
                    ).dot(Un)
                    * (Tmax ** 2)
                    / (J * (J + 1))
                )
                It[i, j] = (
                    Un.dot(
                        Phi_mat_dtdt[:, j].reshape((J + 1, J + 1)) * Phi_mat_dtdt[:, i].reshape((J + 1, J + 1)) * triang
                    ).dot(Un)
                    * (Tmax ** 2)
                    / (J * (J + 1))
                )
            else:
                (Is[i, j], Ic[i, j], It[i, j]) = (Is[j, i], Ic[j, i], It[j, i])
    I_pen = Is + It + 2 * Ic
    I_pen = I_pen + np.eye(Kbeta) * 0.001 * np.trace(I_pen) / Kbeta
    return (Is, Ic, It, I_pen)
Esempio n. 52
0
def Pre_Comp(L, T, Xdata, Y, Kbeta, J):
    t = sy.Symbol("t")
    s = sy.Symbol("s")
    # Récupération des variables et paramètres
    N = len(L)
    D = len(L[0])
    # ----------------- INFERENCES DES PARAMS LONGITUDINAUX
    # print("[   ] Inférence des paramètres fonctionnels")
    model = pyGPs.GPR()
    kern1 = pyGPs.cov.RBF(log_ell=0.0, log_sigma=0.0)
    kern2 = pyGPs.cov.Periodic(log_ell=0.0, log_p=0.0, log_sigma=0.0)
    kern = pyGPs.cov.SumOfKernel(kern1, kern2)
    m = pyGPs.mean.Const()
    model.setPrior(mean=m, kernel=kern)
    model.setNoise(log_sigma=-2.30258)
    Theta = np.zeros((N, D, len(model.covfunc.hyp)), float)
    Gamma = np.zeros((N, D), float)
    moy_est = np.zeros((N, D), float)
    for i in range(N):
        for j in range(D):
            y = np.asarray(Xdata[i][j])
            x = np.asarray(L[i][j])
            try:
                model.optimize(x, y)
                moy_est[i, j] = model.meanfunc.hyp[0]
                Theta[i, j, :] = np.array(np.exp(model.covfunc.hyp))
                Gamma[i, j] = np.exp(model.likfunc.hyp)
            except:
                # Problème d'inférence, paramètres défaut attribués
                moy_est[i, j] = np.mean(x)
                Theta[i, j, :] = np.array([0.05, np.std(x) ** 2, 0.05, 1.0, 0.0])
                Gamma[i, j] = 1.0
                pass

    # ----------------- RECUPERATION DES QUANTITES D'INTERET
    # print("[-  ]  Récupération des quantités d'intérêt")
    # Construction de la forme du noyau
    el1 = sy.Symbol("el1")
    sig1 = sy.Symbol("sig1")
    args1 = [el1, sig1]
    el2 = sy.Symbol("el2")
    per2 = sy.Symbol("per2")
    sig2 = sy.Symbol("sig2")
    args2 = [el2, per2, sig2]
    syk = cg.sy_RBF((s, t), *args1) + cg.sy_Periodic((s, t), *args2)
    args = [t, s] + args1 + args2
    k_fonc = sy.lambdify(tuple(args), syk, "numpy")
    Psi = Comp_Psi(L, k_fonc, Theta, Gamma)[0]
    # ----------------- Construction de la base fonctionnelle
    # print("[-- ]  Calcul des quantités d'intérêt")
    syPhi = sy.ones(Kbeta ** 2, 1)
    syb = sy.ones(1, Kbeta ** 2)
    v = [np.arange(Kbeta), np.arange(Kbeta)]
    expo = cg.expandnp(v)
    Phi_fonc = [[] for j in range(Kbeta ** 2)]
    for x in range(len(expo[:, 0])):
        syPhi[x] = (t ** expo[x, 0]) * (s ** expo[x, 1])
        Phi_fonc[x] = sy.lambdify((t, s), syPhi[x], "numpy")
        syb[x] = sy.Symbol("b" + str(x))
    syBeta = syb * syPhi
    I_pen = J22_fast(syPhi, np.max(T), 50)[3]
    # ----------------- Construction de l et V
    Un = np.ones(J + 1, float)
    Un[0] = 0.5
    Un[J] = 0.5
    Phi_mat = Comp_Phi(Phi_fonc, T, J)
    l = np.zeros((N, D * Kbeta ** 2), float)
    V = [[] for i in range(N)]
    vl = [[] for j in range(D)]
    for i in range(N):
        Phi_i = Phi_mat[(i * (J + 1)) : (i * (J + 1) + J + 1), :].T
        for j in range(D):
            Xij = Xdata[i][j]
            # Moyenne de F_ij estimée en amont
            Etaij = moy_est[i, j]
            t = L[i][j]
            grid = T[i] * 1.0 * np.arange(J + 1) / J
            vec = cg.expandnp([t, grid])
            args = list(vec.T) + list(Theta[i, j, :])
            K_ij = np.apply_along_axis(k_fonc, 0, *args).reshape(J + 1, len(t))
            K_ij[0, :] = K_ij[0, :] * 0.5
            K_ij[J, :] = K_ij[J, :] * 0.5
            KPsi = K_ij.dot(Psi[i][j])
            l[i, (j * Kbeta ** 2) : ((j + 1) * Kbeta ** 2)] = (
                Phi_i.dot(KPsi.dot(Xij - Etaij) + Etaij * Un).reshape(-1) / J
            )
            # on calcule pour k_ij, la matrice des k(s,t) pour s,t dans la grille de [0,Ti]
            vec = cg.expandnp([grid, grid])
            args = list(vec.T) + list(Theta[i, j, :])
            k_ij = np.apply_along_axis(k_fonc, 0, *args).reshape(J + 1, J + 1)
            k_ij[0, :] = k_ij[0, :] * 0.5
            k_ij[J, :] = k_ij[J, :] * 0.5
            k_ij[:, 0] = k_ij[:, 0] * 0.5
            k_ij[:, J] = k_ij[:, J] * 0.5
            Cov_FF = k_ij - KPsi.dot(K_ij.T)
            vl[j] = Phi_i.dot(Cov_FF).dot(Phi_i.T) / J ** 2
        V[i] = sc.sparse.block_diag(tuple(vl))
        # On ajoute une matrice diagonale pour rendre V[i] définie positive, mais on fait en sorte que ses valeurs propres soient petites par rapport à celles de V[i] pour ne pas trop affecter la vraisemblances sur l'espace autour de 0.
        # V[i]=V[i]+np.eye(D*Kbeta**2)*0.01*np.trace(V[i].toarray())/(D*Kbeta**2)
    return (l, V, I_pen)
Esempio n. 53
0
    def deroulerTour(self):
        #Tour des Gubrus
        if(not self.modele.gubrus.mort):
            #Envoyer flottes vers planete la plus proche
            self.modele.gubrus.listeFlottes.append(Classes.flotteDeVaisseaux(self.modele.listeEtoiles[self.modele.gubrus.etoileMere].nbVaisseaux,self.modele.listeEtoiles[self.modele.gubrus.etoileMere],self.modele.gubrus.strategieAttaque(self.modele),2,self.modele.temps_courant))
        
        #Tour des Czin

        #Si les Czins sont toujours en vie
        if(not self.modele.czin.mort):
        
            #Si les Czins sont en mode rassemblement_force
            if(self.modele.czin.rassemblement_force):

                #Si on possede une armada soit 3 x force_attaque
                if(self.modele.listeEtoiles[self.modele.czin.base].nbVaisseaux >= self.modele.czin.forceAttaque(self.modele.temps_courant)*3):
                    #Envoyer l'Armada vers la base prospective
                    self.modele.listeFlottes.append(Classes.flotteDeVaisseaux(self.modele.listeEtoiles[self.modele.czin.base].nbVaisseaux, self.modele.listeEtoiles[self.modele.czin.base], self.modele.czin.etablirBase(self.modele), 3, self.modele.temps_courant))
                    self.self.modele.listeEtoiles[self.modele.czin.base].nbVaisseaux = 0
                    self.modele.czin.listePossessionsFlottes.append(len(self.modele.listeFlottes)-1)
                    self.modele.czin.rassemblement_force = False
                    self.modele.czin.etablir_base = True
                
                #Si les Czins on plusieurs Etoiles
                elif(len(self.modele.czin.listePossessions) > 1):

                    planeteProche = False
                    
                    #Pour tous les numeros d'etoile que les Czins possedent
                    for numero in self.modele.czin.listePossession:
                        print("infinie")
                        
                        #Pour calculer la distance
                        differenceX = abs(self.modele.listeEtoiles[numero].posX - modele.listeEtoiles[sel.modele.czin.base].posX)
                        differenceY = abs(self.modele.listeEtoiles[numero].posY - modele.listeEtoiles[sel.modele.czin.base].posY)

                        #Calculer la distance a l'aide du theoreme de pythagore
                        distance=math.sqrt(math.pow(differenceX, 2)+math.pow(differenceY, 2))
                        
                        #Si les etoiles sont a distance rassemblement
                        if(distance <= 6):

                            planeteProche = True
                            
                            #Si le nombre de vaisseau sur cette etoile est plus grand que 3
                            if(self.modele.listeEtoile[numero] > 3):
                                
                                #Choisir le nombre de vaisseaux a envoyer sur la base soit nbVaisseaux - 3
                                vaisseauxAEnvoyer = self.modele.listeEtoile[numero].nbVaisseaux - 3
                            
                                #Creation de la flotte de Vaisseau
                                self.modele.listeFlottes.append(Classes.flotteDeVaisseaux(vaisseauxAEnvoyer, self.modele.listeEtoile[numero], self.modele.listeEtoile[self.modele.czin.base], 3, self.modele.temps_courant))
                                self.modele.listeEtoile[numero].nbVaisseaux -= vaisseauxAEnvoyer
                                self.modele.listeFlottes[len(self.modele.listeFlottes)-1].armada = True
                                self.modele.czin.listePossessionsFlottes.append(len(self.modele.listeFlottes)-1)
                            
                                #On enleve les vaisseaux sur l'etoile une fois la flotte creee
                                self.modele.listeEtoile[numero].nbVaisseaux = self.modele.listeEtoile[numero].nbVaisseaux - vaiseauxAEnvoyer

                    #Si il n'y a pas d'etoile a distance rassemblement de la base changer la base pour l'etoile mere
                    if(not planeteProche):
                        self.modele.czin.base = self.modele.czin.etoileMere
                            
                
            
            #Si on est en mode conquerir_grappe
            if(self.modele.czin.conquerir_grappe):

                etoileABonneDistance = False
                
                for etoileAConquerir in self.modele.listeEtoiles:

                    #Pour calculer la distance
                    differenceX = abs(etoile.posX - modele.listeEtoiles[sel.modele.czin.base].posX)
                    differenceY = abs(etoile.posY - modele.listeEtoiles[sel.modele.czin.base].posY)

                    #Calculer la distance a l'aide du theoreme de pythagore
                    distance=math.sqrt(math.pow(differenceX, 2)+math.pow(differenceY, 2))

                    #Si cette toile est a distance grappe 
                    if(distance <= self.czin.DISTANCE_GRAPPE):

                        #Si il y a une etoile a la bonne distance
                        etoileABonneDistance = True
                        
                        #Si le nombre de vaisseau sur la base est plus grand ou egal a froce_attaque
                        if(self.modele.listeEtoiles[self.modele.czin.base] >= self.modele.czin.forceAttaque(self.modele.temps_courant)):
                            self.modele.listeFlottes.append(Classes.flotteDeVaisseaux(self.modele.czin.forceAttaque(self.modele.temps_courant), self.modele.listeEtoile[self.modele.czin.base], etoileAConquerir, 3, self.modele.listeEtoiles.index(etoileAConquerir), self.modele.temps_courant))
                            self.modele.listeEtoile[self.modele.czin.base].nbVaisseaux -= self.modele.czin.forceAttaque(self.modele.temps_courant)
                            self.modele.czin.listePossessionsFlottes.append(len(self.modele.listeFlottes)-1)
                            

                        #Sinon on sort de la boucle puisqu'il n'y a pas assez de vaisseaux sur la base
                        else:
                            break

                    if(not etoileABonneDistance):
                        self.modele.czin.rassemblement_force = True
                        self.modele.czin.conquerir_grappe = False
                        
        #Evaluer chaque dixieme d'annee
        for i in range(0,10):

            #Pour chaque flotte Czin   
            for flotte in self.modele.czin.listeFlottes:
                #Si la flotte est arrivee a destination
                if(round(flotte.anneeArrivee, 1) == self.modele.temps_courant+(i/10)):
                    print("Une flotte Czin est arrivee!")
                    #Si la planete est ennemi
                    self.combatVaisseau(flotte, flotte.destination)
                        
                    if(flotte.armada):
                        self.modele.czin.etablir_base = False
                        self.modele.czin.conquerir_grappe = True

            #Pour chaque flotte Humaine 
            for flotte in self.modele.humain.listeFlottes:
                #Si la flotte est arrivee a destination
                if(round(flotte.anneeArrivee, 1) == self.modele.temps_courant+(i/10)):
                    print("Une flotte Humaine est arrivee!")
                    #Si la planete est ennemi
                    self.combatVaisseau(flotte, flotte.destination)

            #Pour chaque flotte Gubrus  
            for flotte in self.modele.gubrus.listeFlottes:
                #Si la flotte est arrivee a destination
                if(round(flotte.anneeArrivee, 1) == self.modele.temps_courant+(i/10)):
                    print("Une flotte Gubru est arrivee!")
                    #Si la planete est ennemi
                    self.combatVaisseau(flotte, flotte.destination)
                

        #Generer des vaisseaux
        for etoile in self.modele.listeEtoiles:
            etoile.genererVaisseau()
            print(etoile.nbVaisseaux)

        #Update les informations
        self.vue.choisirNbVaisseaux.place_forget()
        self.vue.boutonEnvoyerFlotte.place_forget()
        self.vue.surfaceJeu.delete("selection")
        self.vue.surfaceJeu.delete("info")
        self.modele.temps_courant += 1
        self.vue.labelAnnee.config(text="Annee : "+str(self.modele.temps_courant))

        #Update les logo ainsi que la map
        self.vue.afficherProprietaire(self.modele)
        self.vue.afficherMap(self.modele)