def __init__(self, v, sol): self.v = v self.solution = sol self.Kru = Kruskal(sol.g) cityvector = copy.deepcopy(self.solution.visited) cityvector.append(0) try: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) except ValueError: villeproche = 0 else: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) try: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) except ValueError: orgtoville = 0 else: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) self.heuristic_cost = self.Kru.getMSTCost( self.solution) + villeproche + orgtoville
def kruskal(): #request body = {"messages" : [ {"message":"hola"}, {"message" : "hola"}]} graph = Graph() for m in request.json["edges"]: From = m["from"] To = m["to"] Weight = m["weight"] graph.edges.append(Edge(From, To, Weight)) ret = Kruskal(graph) return ret.toJSON()
def get_h(input, num_of_nodes): """ Given unvisited nodes return the cost of MST """ #print(input) ob=Kruskal(num_of_nodes) input_converted = convert_input_into_readable_form_by_graph(input) #print(input_converted) ob.add_edges(input_converted) #need to convert input into running numbers cost = ob.KruskalMST() return cost
def main(): G = Graph() t1 = datetime.now() G.createGraphG1() t2 = datetime.now() print("Time to create sparse graph G1 ", t2 - t1) print("Source, Destination", "\t\t\t", "Dijkstra With Heap", "\t\t\t", "Dijkstra without Heap ", "\t\t\t", "Kruskal") for i in range(5): num1 = random.randint(0, V - 1) num2 = random.randint(0, V - 1) if num1 == num2: continue t3 = datetime.now() bw = dijkstra(G, num1, num2) t4 = datetime.now() t5 = datetime.now() bw1 = dijkstraWithHeap(G, num1, num2) t6 = datetime.now() t7 = datetime.now() bw2 = Kruskal(G, num1, num2) t8 = datetime.now() print(num1, num2, "\t\t\t", bw, t4 - t3, "\t\t\t", bw1, t6 - t5, "\t\t\t", bw2, t8 - t7) t1 = datetime.now() T = Graph() T.createGraphG2() t2 = datetime.now() print("Time to create dense graph G2 ", t2 - t1) print("Source, Destination", "\t\t\t", "Dijkstra With Heap", "\t\t\t", "Dijkstra without Heap", "\t\t\t", "Kruskal") for i in range(5): num1 = random.randint(0, V - 1) num2 = random.randint(0, V - 1) if num1 == num2: continue t3 = datetime.now() bw = dijkstra(T, num1, num2) t4 = datetime.now() t5 = datetime.now() bw1 = dijkstraWithHeap(T, num1, num2) t6 = datetime.now() t7 = datetime.now() bw2 = Kruskal(T, num1, num2) t8 = datetime.now() print(num1, num2, "\t\t\t", bw, t4 - t3, "\t\t\t", bw1, t6 - t5, "\t\t\t", bw2, t8 - t7)
def Otree(graph_ini, position=0, choice='Prim'): """Retourne un 1-tree de cout minimal.""" # les paremetres sont initialise cost_1 = float('inf') # cout modifie 1 cost_2 = float('inf') # cout modifie 1 real_1 = float('inf') # cout reel de l arete 1 real_2 = float('inf') # cout reel de l arete 2 key_1 = None # autre noeud de l arete 1 key_2 = None # autre noeud de l arete 2 G = deepcopy(graph_ini) # une copie du graphe original est faite mat = G.mat_adj # Les deux arretes de poids modifies minimales incidentes au noeud choisi # seront sauvegardes pour le 1-tree for node in G.get_neighbors(G.nodes[position]): if cost_1 > mat[G.nodes[position]][node].get_vcost(): # v cost_2 = deepcopy(cost_1) real_2 = deepcopy(real_1) key_2 = node cost_1 = deepcopy(mat[G.nodes[position]][node].get_vcost()) # v real_1 = deepcopy(mat[G.nodes[position]][node].cost) key_1, key_2 = key_2, key_1 elif cost_2 > mat[G.nodes[position]][node].get_vcost(): # v cost_2 = deepcopy(mat[G.nodes[position]][node].get_vcost()) # v real_2 = deepcopy(mat[G.nodes[position]][node].cost) key_2 = node # le noeud choisi est efface G.delete_node(G.nodes[position]) new_node = deepcopy(graph_ini.nodes[position]) # un arbre de recouvrement est fait selon le choix de lutilisateur if str.lower(choice) == 'kruskal': One_tree = Kruskal(G) elif str.lower(choice) == 'prim': if position >= len(G.nodes): position = len(G.nodes) - 1 One_tree = Prim(G, G.nodes[position]) # le noeud efface est rajoute au 1-tree One_tree[1].add_node(new_node) node_OT = One_tree[1].nodes for node in node_OT: if node.get_id() == key_1.get_id(): key_1 = node elif node.get_id() == key_2.get_id(): key_2 = node # les deux aretes minimales sont rajoute au 1-tree pour finir sa creation One_tree[1].add_edge(Edge(start=new_node, end=key_1, cost=real_1)) One_tree[1].add_edge(Edge(start=new_node, end=key_2, cost=real_2)) # le cout modifier ainsi que le graphe sont retourne return One_tree[1], One_tree[1].get_vcost()
def Rsl(G, root=None, choice='prim'): """Retourne le parcours en preordre de larbre de recouvrement mininmal.""" if str.lower(choice) == 'prim': cost, arbre_min = Prim(G, root) elif str.lower(choice) == 'kruskal': cost, arbre_min = Kruskal(G) if root is None: # si la racine nest pas donne le premier noeud est pris order, temp = dfs_visit(arbre_min, arbre_min.nodes[0]) else: order, temp = dfs_visit(arbre_min, root) c = 0 cycle = Graph() # un graphe est cree for node in order: # les noeuds sont ajouter au grpahe cycle.add_node(node) for i in xrange(len(order) - 1): # les aretes sont ajouter au graphe # a laide du cycle obtenue de dfs_visit temp_c = G.get_edge_copy(order[i], order[i + 1]).get_cost() cycle.add_edge(Edge(start=order[i], end=order[i + 1], cost=temp_c)) c += temp_c return cycle, c
def question3(G): kruskal_obj = Kruskal(G) mst = kruskal_obj.buildMST() return kruskal_obj.adjacencyList(mst)
def __init__(self): self.master = tk.Tk() super().__init__(self.master) self.master.title("Labyrinth") self.BREITE = 700 self.HOEHE = 700 self.RAND = 10 self.zeilen = 20 self.spalten = 20 self.ungeloest = True self.lab_maker = Kruskal() self.lab_maker.labyrinth_erstellen(self.zeilen, self.spalten) self.waende = self.lab_maker.spielbrett_waende() self.suche = None # Einfuegen der tkinter Objekte self.pack() self.menuleiste = tk.Frame(self) self.menuleiste.pack(side="top") self.quit = tk.Button(self.menuleiste, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="left") self.next = tk.Button(self.menuleiste, text="Next", command=self.naechstes_labyrinth) self.next.pack(side="left") self.solve = tk.Button(self.menuleiste, text="Solve", command=self.loesen) self.solve.pack(side="left") self.create = tk.Button(self.menuleiste, text="Create", command=self.aufbau) self.create.pack(side="left") self.label_zeilen = tk.Label(self.menuleiste, text="Zeilen:") self.label_zeilen.pack(side="left") self.zeilen_eingabe = tk.Entry(self.menuleiste, width=3) self.zeilen_eingabe.insert(0, str(self.zeilen)) self.zeilen_eingabe.pack(side="left") self.label_spalten = tk.Label(self.menuleiste, text="Spalten:") self.label_spalten.pack(side="left") self.spalten_eingabe = tk.Entry(self.menuleiste, width=3) self.spalten_eingabe.insert(0, str(self.spalten)) self.spalten_eingabe.pack(side="left") self.label_arrow = tk.Label(self.menuleiste, text="Arrow") self.label_arrow.pack(side="left") self.pfeile_eingabe = tk.IntVar() self.pfeile_checkbutton = tk.Checkbutton(self.menuleiste, variable=self.pfeile_eingabe) self.pfeile_checkbutton.pack(side="left") self.label_slider = tk.Label(self.menuleiste, text="Speed:") self.label_slider.pack(side="left") self.slider = tk.Scale(self.menuleiste, from_=1, to=1000, orient=tk.HORIZONTAL) self.slider.set(1) self.slider.pack() self.zeichenbrett = tk.Canvas(self, width=self.BREITE + 2 * self.RAND, height=self.HOEHE + 2 * self.RAND) self.zeichenbrett.pack(side="bottom") self.aktueller_knoten = None self.master.bind('q', lambda event: self.master.destroy()) self.master.bind('n', lambda event: self.naechstes_labyrinth()) self.master.bind('s', lambda event: self.loesen()) self.zeichne() self.master.mainloop()
class GUILabyrinth(tk.Frame): """Erstellt mit tkinter eine GUI für die Tiefensuche in einem Labyrinth""" def __init__(self): self.master = tk.Tk() super().__init__(self.master) self.master.title("Labyrinth") self.BREITE = 700 self.HOEHE = 700 self.RAND = 10 self.zeilen = 20 self.spalten = 20 self.ungeloest = True self.lab_maker = Kruskal() self.lab_maker.labyrinth_erstellen(self.zeilen, self.spalten) self.waende = self.lab_maker.spielbrett_waende() self.suche = None # Einfuegen der tkinter Objekte self.pack() self.menuleiste = tk.Frame(self) self.menuleiste.pack(side="top") self.quit = tk.Button(self.menuleiste, text="QUIT", fg="red", command=self.master.destroy) self.quit.pack(side="left") self.next = tk.Button(self.menuleiste, text="Next", command=self.naechstes_labyrinth) self.next.pack(side="left") self.solve = tk.Button(self.menuleiste, text="Solve", command=self.loesen) self.solve.pack(side="left") self.create = tk.Button(self.menuleiste, text="Create", command=self.aufbau) self.create.pack(side="left") self.label_zeilen = tk.Label(self.menuleiste, text="Zeilen:") self.label_zeilen.pack(side="left") self.zeilen_eingabe = tk.Entry(self.menuleiste, width=3) self.zeilen_eingabe.insert(0, str(self.zeilen)) self.zeilen_eingabe.pack(side="left") self.label_spalten = tk.Label(self.menuleiste, text="Spalten:") self.label_spalten.pack(side="left") self.spalten_eingabe = tk.Entry(self.menuleiste, width=3) self.spalten_eingabe.insert(0, str(self.spalten)) self.spalten_eingabe.pack(side="left") self.label_arrow = tk.Label(self.menuleiste, text="Arrow") self.label_arrow.pack(side="left") self.pfeile_eingabe = tk.IntVar() self.pfeile_checkbutton = tk.Checkbutton(self.menuleiste, variable=self.pfeile_eingabe) self.pfeile_checkbutton.pack(side="left") self.label_slider = tk.Label(self.menuleiste, text="Speed:") self.label_slider.pack(side="left") self.slider = tk.Scale(self.menuleiste, from_=1, to=1000, orient=tk.HORIZONTAL) self.slider.set(1) self.slider.pack() self.zeichenbrett = tk.Canvas(self, width=self.BREITE + 2 * self.RAND, height=self.HOEHE + 2 * self.RAND) self.zeichenbrett.pack(side="bottom") self.aktueller_knoten = None self.master.bind('q', lambda event: self.master.destroy()) self.master.bind('n', lambda event: self.naechstes_labyrinth()) self.master.bind('s', lambda event: self.loesen()) self.zeichne() self.master.mainloop() def zeichne(self): self.zeichenbrett.delete("all") self.zeichenbrett.focus_set() # Mit spielfeld ist ein Feld gemeint spielfeld_breite = self.BREITE / self.spalten spielfeld_hoehe = self.HOEHE / self.zeilen x = self.RAND + spielfeld_breite / 2 y = self.RAND + spielfeld_hoehe / 2 self.aktueller_knoten = self.zeichenbrett.create_oval(x - 2, y - 2, x + 2, y + 2, width=0, fill='red') # Umrandung mit Ausgaengen self.zeichenbrett.create_line(self.RAND + spielfeld_breite, self.RAND, self.BREITE + self.RAND, self.RAND) self.zeichenbrett.create_line(self.BREITE + self.RAND, self.RAND, self.BREITE + self.RAND, self.HOEHE + self.RAND) self.zeichenbrett.create_line( self.BREITE + self.RAND - spielfeld_breite, self.HOEHE + self.RAND, self.RAND, self.HOEHE + self.RAND) self.zeichenbrett.create_line(self.RAND, self.HOEHE + self.RAND, self.RAND, self.RAND) # Waende zeichnen for wand in self.waende: # Eine Kante besteht aus zwei Knoten # Ein Knoten besteht aus einer x und y Koordinate auf dem Spielbrett knoten_1 = wand[0] knoten_2 = wand[1] # Startkoordinaten berechnen start_x = self.RAND + spielfeld_breite * knoten_2[1] start_y = self.RAND + spielfeld_hoehe * knoten_2[0] # Frage ob es eine waagerechte Kante ist if knoten_1[0] + 1 == knoten_2[0]: self.zeichenbrett.create_line(start_x, start_y, start_x + spielfeld_breite, start_y) else: self.zeichenbrett.create_line(start_x, start_y, start_x, start_y + spielfeld_hoehe) def naechstes_labyrinth(self): if self.next['state'] == 'normal': self.solve['state'] = 'normal' self.create['state'] = 'normal' self.ungeloest = True self.zeilen = int(self.zeilen_eingabe.get()) self.spalten = int(self.spalten_eingabe.get()) self.lab_maker.labyrinth_erstellen(self.zeilen, self.spalten) self.waende = self.lab_maker.spielbrett_waende() self.zeichne() def loesen(self): self.solve['state'] = 'disabled' self.create['state'] = 'disabled' if self.ungeloest: # Graph auslesen und speichern matrix = self.lab_maker.matrix() graph = Graph(len(matrix)) graph.matrix_eingabe(matrix) # Tiefensuche self.suche = Tiefensuche(graph) self.suche.start(0) self.ungeloest = False weg = self.suche.weg_zu(self.zeilen * self.spalten - 1) if self.pfeile_eingabe.get() == 1: weg.reverse() # Weg einzeichnen self.weg_zeichnen(weg, 'red') def aufbau(self): self.create['state'] = 'disabled' self.ungeloest = False # Graph auslesen und speichern matrix = self.lab_maker.matrix() graph = Graph(len(matrix)) graph.matrix_eingabe(matrix) # Tiefensuche self.suche = Tiefensuche(graph) baum = self.suche.knoten_abfolge(0) # Weg einzeichnen self.aufbau_zeichnen(baum, 'gold', 'blue') def spielfeld_koordinaten(self, nummer): """Berechnet zu einer Spielfeldnummer die Koordinaten Das Spielfeld ist durchnummeriert. Bei 3 Zeilen und 4 Spalten 0 1 2 3 4 5 6 7 8 9 10 11 So kann man zwischen Zeilen/Spalten und Matrix hin un her wechseln """ zeile = nummer // self.spalten spalte = nummer % self.spalten x = self.RAND + (spalte + 0.5) * self.BREITE / self.spalten y = self.RAND + (zeile + 0.5) * self.HOEHE / self.zeilen return x, y def weg_zeichnen(self, weg, color): if self.next['state'] == 'normal': self.next['state'] = 'disabled' self.weg_schritt(weg, 0, color) def weg_schritt(self, weg, i, color): if i < len(weg) - 1: startknoten = weg[i] zielknoten = weg[i + 1] start_x, start_y = self.spielfeld_koordinaten(startknoten) ziel_x, ziel_y = self.spielfeld_koordinaten(zielknoten) arrow_value = None if self.pfeile_eingabe.get() == 1: arrow_value = tk.LAST self.zeichenbrett.create_line(start_x, start_y, ziel_x, ziel_y, fill=color, arrow=arrow_value, width=5) self.zeichenbrett.coords(self.aktueller_knoten, ziel_x - 2, ziel_y - 2, ziel_x + 2, ziel_y + 2) self.after(self.slider.get(), self.weg_schritt, weg, i + 1, color) else: self.next['state'] = 'normal' # TODO: Die naechsten zwei Methoden sind zu nah an den bisherigen zwei Methoden und sollten umgeschrieben werden def aufbau_zeichnen(self, weg, color_1, color_2): if self.next['state'] == 'normal': self.next['state'] = 'disabled' besuchte_knoten = set() besuchte_knoten.add(weg[0]) self.aufbau_schritt(weg, 0, color_1, color_2, besuchte_knoten) def aufbau_schritt(self, weg, i, color_1, color_2, besuchte_knoten): if i < len(weg) - 1: startknoten = weg[i] zielknoten = weg[i + 1] start_x, start_y = self.spielfeld_koordinaten(startknoten) ziel_x, ziel_y = self.spielfeld_koordinaten(zielknoten) arrow_value = None if zielknoten in besuchte_knoten: color = color_2 if self.pfeile_eingabe.get() == 1: arrow_value = tk.LAST else: color = color_1 besuchte_knoten.add(zielknoten) self.zeichenbrett.create_line(start_x, start_y, ziel_x, ziel_y, fill=color, arrow=arrow_value, width=3) self.zeichenbrett.coords(self.aktueller_knoten, ziel_x - 2, ziel_y - 2, ziel_x + 2, ziel_y + 2) self.after(self.slider.get(), self.aufbau_schritt, weg, i + 1, color_1, color_2, besuchte_knoten) else: self.next['state'] = 'normal'
def setUp(self): graph_file = "test_data/graph_data.txt" with open(graph_file) as stream: self.graph = Graph(stream) self.mst = Kruskal(self.graph).get_minimum_spaning_tree()
""" main.py """ import graphviz import loader from dijkstra import Dijkstra from graph import Graph from kruskal import Kruskal from prim import Prim g = Graph(loader.load_graph_from_file('./graph_examples/graph.csv')) kruskal = Kruskal(g) dijkstra = Dijkstra(g) prim = Prim(g) algorithms = [kruskal, dijkstra, prim] for algorithm in algorithms: mst = algorithm.run() sum_weight = sum([int(edge.weight) for edge in mst]) print('Sum for {}: {}'.format(algorithm.__class__.__name__, sum_weight)) graph = graphviz.Graph(name=algorithm.__class__.__name__ + '_MST', format='pdf') for vertex in g.vertices: graph.node(vertex, label=vertex) for edge in mst: graph.edge(edge.v1, edge.v2, label=edge.weight) graph.render(directory='mst_output')
from tabulate import tabulate import matplotlib.pyplot as plt from kmeans import KMeans from kruskal import Kruskal from prim import Prim K = 7 input_data = open("data/data.txt", "r") data = np.loadtxt(input_data) input_classes = open("data/classes.txt", "r") classes = np.loadtxt(input_classes) methods = dict({ "Kruskal": Kruskal(data, K), "Prim": Prim(data, K), "KMeans": KMeans(data, K) }) # PRINT READABLE OUTPUT table_headers = [ "Method", "Silhouette Coefficient", "Rand Index", "Delta Time" ] output = [] for key, value in methods.items(): output.append([ key, value.silhouette, adjusted_rand_score(classes, value.classes), value.time ])
from grafo import Grafo from conexos import Conexos from kruskal import Kruskal arq = "kruskal.txt" arq_conexos = "conexos.txt" g1 = Grafo(arq) g1.le_grafo() g2 = Grafo(arq_conexos) g2.le_grafo() print("Teste conexos") conexos = Conexos(g2) conexos.cacula_conexos() print("Teste kruskal") kruskal = Kruskal(g1) kruskal.arvore_minima()
class Node(object): def __init__(self, v, sol): self.v = v self.solution = sol self.Kru = Kruskal(sol.g) cityvector = copy.deepcopy(self.solution.visited) cityvector.append(0) try: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) except ValueError: villeproche = 0 else: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) try: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) except ValueError: orgtoville = 0 else: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) self.heuristic_cost = self.Kru.getMSTCost( self.solution) + villeproche + orgtoville #self.heuristic_cost = self.Kru.getMSTCost(self.solution) #villeproche = np.amin(np.delete(self.solution.edgecosts[self.v,:], self.solution.visited)) #print(self.solution.g.costs) #orgtoville = np.amin(np.delete(self.solution.g.costs[0, :], self.solution.visited)) #print(orgtoville) def __lt__(self, other): return isN2betterThanN1(other, self) def explore_node(self): #Returns all possible nodes connected to this one in a form of a list NextNodes = [] if (len(self.solution.not_visited) == 1): nn = copy.deepcopy(Node(self.v, self.solution)) nn.solution.add_edge(nn.v, 0) nn.v = 0 nn.update_heuristic_cost() NextNodes.append(nn) else: for i in self.solution.not_visited: if i != 0: nn = copy.deepcopy(Node(self.v, self.solution)) nn.solution.add_edge(nn.v, i) nn.v = i nn.update_heuristic_cost() NextNodes.append(nn) return NextNodes def update_heuristic_cost(self): #updates the cost of the heuristic for the Node, used in the explore_node method to update the heuristic cost before returning the new nodes cityvector = copy.deepcopy(self.solution.visited) cityvector.append(0) try: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) except ValueError: villeproche = 0 else: villeproche = np.amin( np.delete(self.solution.edgecosts[self.v, :], cityvector)) try: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) except ValueError: orgtoville = 0 else: orgtoville = np.amin( np.delete(self.solution.g.costs[0, :], cityvector)) self.heuristic_cost = self.Kru.getMSTCost( self.solution) + villeproche + orgtoville
print('Exercício 3: ') out_ex3 = ex3.ciclo_euleriano() output_exercicios.exercicio3(out_ex3) print("----------------------------") print('Exercício 4: ') out_ex4 = ex4.bellman_ford(1) output_exercicios.exercicio4(out_ex4) print("----------------------------") print('Exercício 5: ') out_ex5 = ex5.floyd_warshall() output_exercicios.exercicio5(out_ex5) """ """-----------------------------------------------------------------------------------------------------------------""" print('Atividade 2\nGabriel Wesz e Matheus Eyng') ex6 = Conexos(g1) ex7 = Ordenacao(g1) ex8 = Kruskal(g1) print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=') print('Exercício 1: ') ex6.calcula_conexos() print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=') print('Exercício 2: ') out_ex7 = ex7.ordenacao_topologica() output_exercicios.exercicio7(out_ex7) print('-=-=-=-=-=-=-=-=-=-=-=-=-=-=') print('Exercício 3: ') ex8.arvore_minima()
from kruskal import Kruskal nodes = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] edges = [['a', 'd', 5], ['d', 'f', 6], ['f', 'g', 11], ['g', 'e', 9], ['e', 'c', 5], ['c', 'b', 8], ['b', 'a', 7], ['d', 'b', 9], ['d', 'e', 15], ['f', 'e', 8], ['b', 'e', 7]] # Instanciamos la clase Kruskal app_tree = Kruskal() tree = app_tree.apply_kruskal(nodes, edges) # El resultado de aplicar kruskal es cost = 0 print(tree) for leaf in tree: cost += leaf[2] print(f"El costo de recorrer todos los nodos usando kruskal es: {cost}") # edges = [ # ['a', 'd', 5], # ['e', 'c', 5], # ['d', 'f', 6], # ['b', 'a', 7], # ['b', 'e', 7] # ['c', 'b', 8], # ['f', 'e', 8], # ['d', 'b', 9], # ['g', 'e', 9], # ['f', 'g', 11], # ['d', 'e', 15], # ]