def setUp(self): self.n = { 'a': Noeud(0, 0, 'a'), 'b': Noeud(0, 1, 'b'), 'c': Noeud(1, 0, 'c'), 'd': Noeud(-1, 0, 'd'), 'e': Noeud(0, -1, 'e'), } self.g1 = Graphe( [self.n['a'], self.n['b'], self.n['c'], self.n['d'], self.n['e']], [(self.n['a'], self.n['b'], 1), (self.n['a'], self.n['c'], 1), (self.n['a'], self.n['d'], 1)])
def Aetoil(initRow, initCol, endRow, endCol, wallStates): noeudInitial = Noeud(([initRow,initCol]), 0, None) goalStates = [endRow,endCol] frontiere = [(noeudInitial.cost + manhattan(noeudInitial.position, goalStates), noeudInitial)] reserve = {} noeudCourant = noeudInitial while frontiere != [] and not noeudCourant.position == goalStates: (min_f, noeudCourant) = heapq.heappop(frontiere) if noeudCourant.position == goalStates: break next_row = noeudCourant.position[0] next_col = noeudCourant.position[1] if ((next_row, next_col) not in wallStates) and next_row >= 0 and next_row < game.spriteBuilder.rowsize and next_col > 0 and next_col < game.spriteBuilder.colsize: if noeudCourant.identifiantNoeud() not in reserve: reserve[noeudCourant.identifiantNoeud()] = noeudCourant.cost nouveauxNoeuds = noeudCourant.expand() for noeud in nouveauxNoeuds: f = noeud.cost + manhattan(noeud.position, goalStates) heapq.heappush(frontiere, (f, noeud)) return noeudCourant
def test_distance(self): n1 = Noeud(0, 0, "1") n2 = Noeud(0, 1, "2") n3 = Noeud(1, 0, "3") n4 = Noeud(1, 1, "4") self.assertEqual(n1.distance(n2), 1) self.assertEqual(n1.distance(n3), 1) self.assertEqual(n1.distance(n4), sqrt(2))
def __init__(self, length, nb_e, nb_s): self.length = length self.contenu = [Individu(nb_e,nb_s, i) for i in range(length)] self.oldGen = [] self.nb_e = nb_e self.nb_s = nb_s self.noeuds = [Noeud(i, "entree") for i in range(nb_e)] self.noeuds.extend([Noeud(i,"sortie") for i in range(nb_e, nb_e + nb_s)]) self.generationCount = 0 self.indiceInnovation = 0 self.lastIndId = length self.lastEspId = 0 self.averageFitness = None self.averageRawFitness = None self.historique = [] self.especes = [] self.histEspeces = [] self.bestDisplay = 10 self.best = [] # self.especesFig, self.especesAx = plt.subplots(figsize=(20, 20*500/860)) """Cette liste contiendra les différentes opérations génétiques structurelles
def main(): # création de la chaine liste = Liste_Doublement_Chainee() for i in range(5): n = Noeud() n.cle = i liste.add_noeud_fin(n) # déclaration et affectation des variables moyenne = 0.0 fini_en_moins_de_trois = 0.0 nb_iterations = 100000 # boucle qui permet de répéter les test pendant "nb_iterations" for i in range(nb_iterations): # Sélection aléatoire du noeud de départ noeud_markov = liste.get_noeud(random.randint(1, 3)) compteur = 0 # boucle qui effectue le test de deplacement aléatoire jusqu'a se retrouver dans un état absorbant while True: noeud_markov = deplacement_aleatoire(noeud_markov) compteur = compteur + 1 # état absorbant if noeud_markov.suivant is None or noeud_markov.precedent is None: break # évaluation du moment ou le test prends fin if compteur == 1 or compteur == 2: fini_en_moins_de_trois = fini_en_moins_de_trois + 1 moyenne = moyenne + compteur # affichage des statistiques des tests effectués moyenne = moyenne / nb_iterations print "moyenne:", moyenne print "pourcentage qui ont finis apres trois pas ou plus:", (1 - ( fini_en_moins_de_trois / nb_iterations)) * 100, "%"
def create_graph(graph_id, path_file): with open(path_file, newline='') as csv_file: reader = csv.reader(csv_file, delimiter='\t') Graphe1 = GrapheOriente(graph_id) nb_node = next(reader) for i in range(1, int(nb_node[0]) + 1): Graphe1.ajouterNoeud(Noeud(i)) for row in reader: Graphe1.ajouterLien(Lien(int(row[0]), int(row[1]), float(row[2]))) return Graphe1
def mutationNoeud(self, ind): con = ut.randomPick(list(ind.genome.connexions.values())) while ind.estRecursive(con): con = ut.randomPick(list(ind.genome.connexions.values())) idNouvNoeud = len(self.noeuds) for i in range(self.indiceInnovation): t1, e1, s1 = self.historique[i] if t1 == 1: t2, e2, s2 = self.historique[i+1] if e1 == con.entree and s2 == con.sortie and (s1 not in ind.idToPos): ind.insertNoeud(con, 1, con.poids, i, s1) break else: ind.insertNoeud(con, 1, con.poids, self.indiceInnovation, idNouvNoeud) self.historique.append((1,con.entree,idNouvNoeud)) self.historique.append((2,idNouvNoeud,con.sortie)) self.noeuds.append(Noeud(idNouvNoeud, "cachee")) self.indiceInnovation += 2
def test_eq(self): n1 = Noeud(1, 2, "blah") n2 = Noeud(1, 2, "blah") n3 = Noeud(1, 2, "lah") n4 = Noeud(1, 3, "blah") n5 = Noeud(2, 2, "blah") n6 = Noeud(2, 3, "lah") self.assertEqual(n1, n2) self.assertFalse(n1 == n3) self.assertFalse(n1 == n4) self.assertFalse(n1 == n5) self.assertFalse(n1 == n6)
def setUp(self): self.n = { 'a': Noeud(0, 0, 'a'), 'b': Noeud(0, 2, 'b'), 'c': Noeud(2, 2, 'c'), 'd': Noeud(3, 4, 'd'), 'e': Noeud(4, 2, 'e'), 'f': Noeud(4, 4, 'f'), } self.g1 = Graphe([ self.n['a'], self.n['b'], self.n['c'], self.n['d'], self.n['e'], self.n['f'] ], [(self.n['a'], self.n['b'], self.n['a'].distance(self.n['b'])), (self.n['a'], self.n['c'], self.n['a'].distance(self.n['c'])), (self.n['b'], self.n['d'], self.n['b'].distance(self.n['d'])), (self.n['d'], self.n['f'], self.n['d'].distance(self.n['f'])), (self.n['c'], self.n['d'], self.n['c'].distance(self.n['d'])), (self.n['c'], self.n['e'], self.n['c'].distance(self.n['e'])), (self.n['e'], self.n['f'], self.n['e'].distance(self.n['f']))])
def main(): #for arg in sys.argv: iterations = 100 # default if len(sys.argv) == 2: iterations = int(sys.argv[1]) print("Iterations: ") print(iterations) init() #------------------------------- # Building the matrix #------------------------------- # on localise tous les états initiaux (loc du joueur) initStates = [o.get_rowcol() for o in game.layers['joueur']] print("Init states:", initStates) # on localise tous les objets ramassables goalStates = [o.get_rowcol() for o in game.layers['ramassable']] print("Goal states:", goalStates) # on localise tous les murs wallStates = [w.get_rowcol() for w in game.layers['obstacle']] #print ("Wall states:", wallStates) #------------------------------- # Building the best path with A* #------------------------------- noeudInitial = Noeud(list(initStates[0]), 0, None) frontiere = [ (noeudInitial.cost + manhattan(noeudInitial.position, goalStates[0]), noeudInitial) ] reserve = {} noeudCourant = noeudInitial while frontiere != [] and not noeudCourant.position == goalStates[0]: (min_f, noeudCourant) = heapq.heappop(frontiere) if noeudCourant.position == list(goalStates[0]): break next_row = noeudCourant.position[0] next_col = noeudCourant.position[1] if ( (next_row, next_col) not in wallStates ) and next_row >= 0 and next_row <= 20 and next_col >= 0 and next_col <= 20: if noeudCourant.identifiantNoeud() not in reserve: reserve[noeudCourant.identifiantNoeud()] = noeudCourant.cost nouveauxNoeuds = noeudCourant.expand() for noeud in nouveauxNoeuds: f = noeud.cost + manhattan(noeud.position, goalStates[0]) heapq.heappush(frontiere, (f, noeud)) #------------------------------- # Moving along the path #------------------------------- # bon ici on fait juste un random walker pour exemple... row, col = initStates[0] #row2,col2 = (5,5) """for i in range(iterations): x_inc,y_inc = random.choice([(0,1),(0,-1),(1,0),(-1,0)]) next_row = row+x_inc next_col = col+y_inc if ((next_row,next_col) not in wallStates) and next_row>=0 and next_row<=20 and next_col>=0 and next_col<=20: player.set_rowcol(next_row,next_col) print ("pos 1:",next_row,next_col) game.mainiteration() col=next_col row=next_row """ moves = [] while noeudCourant != None: moves.insert(0, [noeudCourant.position[0], noeudCourant.position[1]]) noeudCourant = noeudCourant.father for i in moves: player.set_rowcol(i[0], i[1]) game.mainiteration() # si on a trouvé l'objet on le ramasse if (row, col) == goalStates[0]: o = game.player.ramasse(game.layers) game.mainiteration() print("Objet trouvé!", o) break ''' #x,y = game.player.get_pos() ''' pygame.quit()
from noeud import Noeud from graphe import Graphe from dfs import DFSSolver from bfs import BFSSolver from astar import AStarSolver # Les villes villes = { 'Lausanne': Noeud(110, 260, 'Lausanne'), 'Geneve': Noeud(40, 300, 'Geneve'), 'Sion': Noeud(200, 300, 'Sion'), 'Neuchatel': Noeud(150, 170, 'Neuchatel'), 'Bern': Noeud(210, 280, 'Bern'), 'Basel': Noeud(230, 65, 'Basel'), 'Fribourg': Noeud(175, 200, 'Fribourg'), 'Zurich': Noeud(340, 90, 'Zurich'), 'Aarau': Noeud(290, 95, 'Aarau'), 'Luzern': Noeud(320, 155, 'Luzern'), 'St-Gallen': Noeud(85, 455, 'St-Gallen'), 'Thun': Noeud(235, 210, 'Thun'), } # Les routes. routes = [ (villes['Lausanne'], villes['Geneve'], villes['Lausanne'].distance(villes['Geneve'])), (villes['Sion'], villes['Lausanne'], villes['Sion'].distance(villes['Lausanne'])), (villes['Neuchatel'], villes['Lausanne'], villes['Neuchatel'].distance(villes['Lausanne'])), (villes['Fribourg'], villes['Lausanne'], villes['Fribourg'].distance(villes['Lausanne'])), (villes['Fribourg'], villes['Bern'], villes['Fribourg'].distance(villes['Bern'])), (villes['Sion'], villes['Thun'], villes['Sion'].distance(villes['Thun'])),
nb_node = next(reader) for i in range(1, int(nb_node[0]) + 1): Graphe1.ajouterNoeud(Noeud(i)) for row in reader: Graphe1.ajouterLien(Lien(int(row[0]), int(row[1]), float(row[2]))) return Graphe1 #def dijkstra(id_node_source, id_node_dest): # nodes_list = [] noeud1 = Noeud(11) noeud2 = Noeud(22) noeud3 = Noeud(33) noeud4 = Noeud(4444) lien1 = Lien(11, 22, 10) lien2 = Lien(22, 33, 11) lien4 = Lien(11, 4444, 11) g1 = GrapheOriente(10) g1.ajouterNoeud(noeud1) g1.ajouterNoeud(noeud2) g1.ajouterNoeud(noeud3) g1.ajouterNoeud(noeud4)
from noeud import Noeud from graphe import Graphe from dfs import DFSSolver from bfs import BFSSolver from astar import AStarSolver # les noeuds du graphe noeuds = { 'A': Noeud(0, 16, 'A'), 'B': Noeud(5, 13, 'B'), 'C': Noeud(0, 10, 'C'), 'D': Noeud(5, 8, 'D'), 'E': Noeud(11, 18, 'E'), 'F': Noeud(15, 13, 'F'), 'G': Noeud(29, 18, 'G'), 'H': Noeud(26, 0, 'H'), 'I': Noeud(12, 10, 'I'), 'J': Noeud(17, 7, 'J'), 'K': Noeud(11, 3, 'K'), 'L': Noeud(22, 16, 'L'), 'M': Noeud(25, 12, 'M'), 'N': Noeud(24, 6, 'N'), 'O': Noeud(20, 0, 'O'), 'P': Noeud(5, 0, 'P'), } # les arcs arcs = [(noeuds['A'], noeuds['B'], noeuds['A'].distance(noeuds['B'])), (noeuds['A'], noeuds['E'], noeuds['A'].distance(noeuds['E'])), (noeuds['B'], noeuds['C'], noeuds['B'].distance(noeuds['C'])),
def ajoutLien(self,Lien): self._dictLiens.append(Lien) Noeud.ajoutIdentifiantLien(Lien,Lien.getId())
chemin_final = parcours_en_profondeur(grid, grid[0][0], chemin) return chemin_final #Construction de la grille graphique width = 30 height = 30 xvalues = [i for i in range(width)] yvalues = [j for j in range(height)] xx, yy = np.meshgrid(xvalues, yvalues) plt.plot(xx, yy, color='k', linestyle='none') plt.gca().invert_yaxis() plt.gca().xaxis.set_ticks_position('top') #Construction de la grille en terme de noeud rows = height - 1 cols = width - 1 grid = [[Noeud(i, j) for j in range(cols)] for i in range(rows)] #Construction du labyrinthe, algorithme de Prim prim_algorithm(grid, width, height, [], True) #Update du labyrinthe dans la grille graphique draw_borders(grid) #ShowOff plt.show() #SolveOff draw_way_out(trouver_le_chemin(grid), grid)
def ajouterNoeud(self,Noeud): self._nbrNoeuds+=1 self._dictNoeuds[Noeud.getId()]=Noeud