def figure56(process, edge_densities, n): largest_scc = [] Sample = g.Graph(n, edge_densities[0] * n, process) for density in edge_densities: Sample.m = round(density * n) Sample.build() largest_scc.append(ranked_SCC(tarjan(Sample.edges)) / n) return largest_scc
def setUp(self): self.list_of_edges_uni = [(0, 1, 0.5), (0, 3, 1), (1, 2, 1), (2, 3, 0.1)] self.vertices_uni = {0, 1, 2, 3} self.list_of_edges_bi = [(0, 1, 1), (2, 3, 1)] self.vertices_bi = {0, 1, 2, 3, 4} self.udg_uni = gr.Graph(self.vertices_uni, self.list_of_edges_uni, directed=False) self.dg_uni = gr.Graph(self.vertices_uni, self.list_of_edges_uni, directed=True) self.udg_bi = gr.Graph(self.vertices_bi, self.list_of_edges_bi, directed=False) self.dg_bi = gr.Graph(self.vertices_bi, self.list_of_edges_bi, directed=True)
def setUp(self): self.list_of_edges_uni = [(0, 1, 0.5), (0, 3, 1), (1, 2, 1), (2, 3, 0.1)] self.vertices_uni = {0, 1, 2, 3} self.list_of_edges_bi = [(0, 1, 1), (2, 3, 1)] self.vertices_bi = {0, 1, 2, 3, 4} self.edges_simple = [(0, 1, 2)] self.verts_simple = {0, 1} self.uni = gr.Graph(self.vertices_uni, self.list_of_edges_uni, directed=False) self.bi = gr.Graph(self.vertices_bi, self.list_of_edges_bi, directed=False) self.simple = gr.Graph(self.verts_simple, self.edges_simple, directed=False)
def g_2(no_of_vertices): f = open("g2.dot", "w+") f.write("graph {\n") V = [] a_l = [] for i in range(no_of_vertices + 1): a_l.append(gp.Vertex(i)) for i in range(no_of_vertices + 1): V.append(i) g = gp.Graph(no_of_vertices) #g.add_vertices(V[1:]) g.add_vertices(V) edge_count = 0 for i in range(1, no_of_vertices): wt = g.add_edge(a_l[i], a_l[i + 1], i, i + 1) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (i, i + 1, wt, wt)) #print i,i+1 edge_count = edge_count + 1 wt = g.add_edge(a_l[no_of_vertices], a_l[1], no_of_vertices, 1) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (no_of_vertices, 1, wt, wt)) edge_count = edge_count + 1 #Dense graph start = time.time() for i in range(no_of_vertices): for j in range(i + 2, no_of_vertices): probab = random.randint(0, 100) if (i == 0 and j == no_of_vertices - 1): continue if (probab <= 20): wt = g.add_edge(a_l[i + 1], a_l[j + 1], i + 1, j + 1) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (i + 1, j + 1, wt, wt)) edge_count = edge_count + 1 adj_list = g.adjacencyList() adj_mat = g.adjacency_matrix print 'Dense graph generated. edge_count =', edge_count print 'It took', time.time() - start, 'seconds to generate the graph.' ret = [adj_list, adj_mat] f.write("}\n") f.close() return ret
def test_of_operation_connected_components(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") try: g1, g2 = graphs.Graph(g6), structure(g6) if g1.connected_components() != g2.connected_components(): print_error_and_quit(f"błędny wynik operacji dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu na grafie {g6} wystąpił wyjątek {e}")
def figure56(process,n,edge_densities,replicates): plt.figure(figsize=(5,4)) for replicate in range(replicates): largest_scc = [] Sample = g.Graph(n,round(edge_densities[0]*n),process) for density in edge_densities: Sample.m = round(density*n) Sample.build() largest_scc.append(ranked_SCC(tarjan(Sample.edges>0))/n) plt.plot(edge_densities,largest_scc) plt.title('Explosive percolation of %s process, n=%d' %(process,n)) plt.ylabel('Largest SCC') plt.xlabel('Edge density') plt.show()
def __init__(self, lattice_rows, lattice_cols): """ initializes a graph object """ self.__rows = lattice_rows self.__cols = lattice_cols self.__rowCells = self.__rows - 1 self.__colCells = self.__cols - 1 self.__latticeGraphDict = self.latticeGraphDictGenerator() self.__latticeGraph = graphs.Graph(self.__latticeGraphDict) self.__initCycle = [] self.__activePath = [] self.__activeCells = [] self.__splitPoints = [] self.__neighbourCycles = [] self.__splitCells = []
def test_of_operation_vertices_of_degree(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") try: g1, g2 = graphs.Graph(g6), structure(g6) for d in range(g1.number_of_vertices()): if g1.vertex_degree(d) != g2.vertex_degree(d): print_error_and_quit( f"błędny wynik operacji dla grafu {g6} i liczby {d}") except Exception as e: print_error_and_quit( f"podczas testu na grafie {g6} i liczbie {d} wystąpił wyjątek {e}" )
def test_of_operation_edge_contraction(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") try: g1, g2 = graphs.Graph(g6), structure(g6) for e1 in g1.edges(): if g1.edge_contraction(*e1) != g2.edge_contraction(*e1): print_error_and_quit( f"błędny wynik operacji dla grafu {g6} i krawędzi {e1}" ) except Exception as e: print_error_and_quit( f"podczas testu na grafie {g6} i krawędzi {e1} wystąpił wyjątek {e}" )
def figure8(process,n,edge_densities): first_scc,second_scc,third_scc = [],[],[] Sample = g.Graph(n,round(edge_densities[0]*n),process) for density in edge_densities: Sample.m = round(density*n) Sample.build() first_scc.append(ranked_SCC(tarjan(Sample.edges),rank=1)/n) second_scc.append(ranked_SCC(tarjan(Sample.edges),rank=2)/n) third_scc.append(ranked_SCC(tarjan(Sample.edges),rank=3)/n) plt.scatter(edge_densities,first_scc,label="Largest SCC") plt.scatter(edge_densities,second_scc,label="Second largest SCC") plt.scatter(edge_densities,third_scc,label="Third largest SCC") plt.title('%s process: SCC combination near critical edge density, n=%d' %(process,n)) plt.ylabel('Component size') plt.xlabel('Edge density') plt.legend() plt.show()
def test_of_operation_induced_subgraph(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") try: g1, g2 = graphs.Graph(g6), structure(g6) s = g1.vertices().copy() for u in g1.vertices(): s.discard(u) if g1.induced_subgraph(s) != g2.induced_subgraph(s): print_error_and_quit( f"błędny wynik operacji dla grafu {g6} i zbioru {s}") except Exception as e: print_error_and_quit( f"podczas testu na grafie {g6} i zbiorze {s} wystąpił wyjątek {e}" )
def main(): """ Determine the vertices that can be reached in 1 hop, 2 hops, and so on from a specific vertex and then display that information. :return: None """ # Get the command line arguments if len(sys.argv) != 3: print('Usage: {} file-name vertex-key'.format(sys.argv[0]), file=sys.stderr) graph_filename, start_vertex_key = sys.argv[1], sys.argv[2] try: with open(graph_filename, 'r') as graph_file: # Construct an empty graph graph = graphs.Graph() # Process the file data for line in graph_file: vertex_keys = line.split() if vertex_keys: k, neighbor_keys = vertex_keys[0], vertex_keys[1:] for neighbor_key in neighbor_keys: graph.add_edge(k, neighbor_key) print("Graph to be processed:") for key in sorted(graph.get_vertices()): print('{:>5}: {}'.format( key, ' '.join(sorted(graph.get_neighbors(key))))) # Determine the number of hops and then display the result hops_list = graphinfo.hops(graph, start_vertex_key) print('Hops from {}:'.format(start_vertex_key)) for i, sublist in enumerate(hops_list): if sublist: print('{:>5} hops: {}'.format(i, ', '.join(sorted(sublist)))) except FileNotFoundError: print('Could not open file {}.'.format(graph_filename), file=sys.stderr)
def test_of_operation_is_complete_bipartite(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") try: g1, g2 = graphs.Graph(g6), structure(g6) if g1.is_complete_bipartite() != g2.is_complete_bipartite(): print(format(g2.matrix(0), "064b")) print(format(g2.matrix(1), "064b")) print(format(g2.matrix(2), "064b")) print(format(g2.matrix(3), "064b")) print(g1.is_complete_bipartite()) print(g2.is_complete_bipartite()) print_error_and_quit(f"błędny wynik operacji dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu na grafie {g6} wystąpił wyjątek {e}")
def figure7(process,n_sizes,edge_density,replicates): jumps = [] for replicate in range(replicates): max_jump = [] # Sample = g.Graph(n_sizes[0],edge_density*n_sizes[0],process) for n in n_sizes: Sample = g.Graph(n,edge_density*n,process) Sample.build() max_jump.append(get_largest_jump(Sample)/n) jumps.append(max_jump) Jumps_array = np.asarray(jumps).reshape((replicates,len(jumps[0]))) Avg_jump= np.mean(Jumps_array, axis=0) Std_jump= np.std(Jumps_array, axis=0) plt.errorbar(n_sizes,Avg_jump,yerr=Std_jump, fmt='o') if process=="C-ODER": plt.axis([0,max(n_sizes)*1.1,0.25,0.45]) elif process=="ODER": plt.axis([0,max(n_sizes)*1.1,-0.05,0.20]) plt.title('Max jump size, %s' %process) plt.ylabel('Max jump') plt.xlabel('System size') plt.show()
def POST(self, data_json, source, end): data = json.loads(data_json) # listRes = dijkstra.Dijkstra.find_all_paths(data, source, end) g = {} for d in data: tmpKeys = list(data[d].keys()) g[d] = tmpKeys print(g) graph = graphs.Graph(g) print("Vertices of graph:") print(graph.vertices()) print("Edges of graph:") print(graph.edges()) print('All paths from vertex "a" to vertex "b":') path = graph.find_all_paths(source, end) print(path) return json.dumps(path, ensure_ascii=False)
def __init__(self): self._mongo = pymongo.MongoClient( 'mongodb+srv://lbonnage:[email protected]/test?retryWrites=true&w=majority', maxPoolSize=50, connect=False) self._db = pymongo.database.Database(self._mongo, 'test') self._nodes = pymongo.collection.Collection(self._db, 'node') self._graph = graphs.Graph(graphs.GRAPH_FILENAME) self.linear_model = models.LinearRainModel() # Demo XGBoost models on these nodes self.XGB_models = { 6: models.NodeFloodPredictor(6), 8: models.NodeFloodPredictor(8), 32: models.NodeFloodPredictor(32), 22: models.NodeFloodPredictor(22) } for model in self.XGB_models.values(): model.train() model.test()
def main(): tasks_callbacks = { 'moving-average': moving_average, 'parabolic': parabolic, 'median': median } parser = argparse.ArgumentParser() parser.add_argument('-m', '--method', action='store', required=True, help='anti-aliasing method', choices=tasks_callbacks.keys(), dest='method', type=str) parser.add_argument('-b1', action='store', required=True, help='main signal amplitude', dest='b1', type=float) parser.add_argument('-b2', action='store', required=True, help='noise amplitude', dest='b2', type=float) parser.add_argument('-n', action='store', required=False, help='counts', dest='n', type=int, default=512) args = parser.parse_known_args()[0] signals = generate_signals(args.b1, args.b2, args.n) amplitude_spectrum_before = DirectFourierTransformer( signals).get_amplitude_spectrum(len(signals) // 2) anti_aliased_signals = tasks_callbacks[args.method](signals) amplitude_spectrum_after = DirectFourierTransformer(anti_aliased_signals) \ .get_amplitude_spectrum(len(anti_aliased_signals) // 2) drawer = graphs.GraphDrawer() drawer.add_plot( graphs.Graph(range(len(signals)), signals, 'Original signals')) drawer.add_stem( graphs.Graph(range(len(amplitude_spectrum_before)), amplitude_spectrum_before, 'Original signals amplitude spectrum')) drawer.add_plot( graphs.Graph(range(len(anti_aliased_signals)), anti_aliased_signals, 'Anti-aliased signals')) drawer.add_stem( graphs.Graph(range(len(amplitude_spectrum_after)), amplitude_spectrum_after, 'Anti-aliased signals amplitude spectrum')) drawer.draw() drawer.show()
def test_structure(structure, g6_sequence): p1 = None for i, g6 in enumerate(g6_sequence): p2 = f"{(100 * i) / len( g6_sequence ):3.2f}" if p2 != p1: print(f"--> {(p1 := p2)}%") # Test konwersji z formatu g6. try: g, h = graphs.Graph(g6), structure(g6) except Exception as e: print_error_and_quit( f"podczas tworzenia grafu {g6} wystąpił wyjątek {e}") # Test funkcji number_of_vertices(). try: if g.number_of_vertices() != h.number_of_vertices(): print_error_and_quit( f"błąd funkcji number_of_vertices() dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji number_of_vertices() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji vertices(). try: pom = h.vertices() pom2 = g.vertices() if g.vertices() != h.vertices(): print_error_and_quit(f"błąd funkcji vertices() dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji vertices() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji number_of_edges(). try: if g.number_of_edges() != h.number_of_edges(): print(g.number_of_edges()) print(h.number_of_edges()) print(g.edges()) print(h.edges()) print(g.vertices()) print(h.vertices()) print_error_and_quit( f"błąd funkcji number_of_edges() dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji number_of_edges() dla grafu {g6} wystąpił wyjątek {e}" ) #Test funkcji edges(). try: if g.edges() != h.edges(): print(g.edges()) print(h.edges()) print(format(h.matrix(0), "064b")) print(format(h.matrix(1), "064b")) print(format(h.matrix(2), "064b")) print_error_and_quit(f"błąd funkcji edges() dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji edges() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji is_edge(). try: for u in range(64): for v in range(u): if g.is_edge(u, v) != h.is_edge(u, v): print(g.is_edge(u, v)) print(h.is_edge(u, v)) print_error_and_quit( f"błąd funkcji is_edge( {u}, {v} ) dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji is_edge() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji vertex_degree(). try: for u in range(g.number_of_vertices()): if g.vertex_degree(u) != h.vertex_degree(u): print(g.vertex_degree(u)) print(h.vertex_degree(u)) print_error_and_quit( f"błąd funkcji vertex_degree( {u} ) dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji vertex_degree() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji vertex_neighbors(). try: for u in range(g.number_of_vertices()): if g.vertex_neighbors(u) != h.vertex_neighbors(u): print(g.vertex_neighbors(u)) print(h.vertex_neighbors(u)) print_error_and_quit( f"błąd funkcji vertex_neighbors( {u} ) dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji vertex_neighbors() dla grafu {g6} wystąpił wyjątek {e}" ) # Test funkcji add_vertex()/delete_vertex(). try: for u in range(63): if u in g.vertices(): g.delete_vertex(u) h.delete_vertex(u) if g != h: print(g.edges()) print(g.vertices()) print(h.edges()) print(h.vertices()) print(format(h.matrix(0), "064b")) print(format(h.matrix(1), "064b")) print(format(h.matrix(2), "064b")) print_error_and_quit( f"błąd funkcji delete_vertex( {u} ) dla grafu {g6}" ) else: g.add_vertex(u) h.add_vertex(u) if g != h: print_error_and_quit( f"błąd funkcji add_vertex( {u} ) dla grafu {g6}") except Exception as e: print_error_and_quit( f"podczas testu funkcji add_vertex() / delete_vertex() dla grafu {g6} wystąpił wyjątek {e}" ) #! Test funkcji add_edge()/delete_edge(). try: g, h = graphs.Graph(g6), structure(g6) for u in range(g.number_of_vertices()): for v in range(u): if g.is_edge(u, v): g.delete_edge(u, v) h.delete_edge(u, v) if g != h: print_error_and_quit( f"błąd funkcji delete_edge( {u}, {v} ) dla grafu {g6}" ) g.add_edge(u, v) h.add_edge(u, v) if g != h: print(g.edges()) print(h.edges()) print(g.vertices()) print(h.vertices()) print_error_and_quit( f"błąd funkcji add_edge( {u}, {v} ) dla grafu {g6}" ) else: g.add_edge(u, v) h.add_edge(u, v) if g != h: print(g.edges()) print(h.edges()) print(g.vertices()) print(h.vertices()) print_error_and_quit( f"błąd funkcji add_edge( {u}, {v} ) dla grafu {g6}" ) g.delete_edge(u, v) h.delete_edge(u, v) if g != h: print_error_and_quit( f"błąd funkcji delete_edge( {u}, {v} ) dla grafu {g6}" ) except Exception as e: print_error_and_quit( f"podczas testu funkcji add_edge() / delete_edge() dla grafu {g6} wystąpił wyjątek {e}" )
import graphs if __name__ == '__main__': graph = graphs.Graph(dict()) graph.add_edge('a', 'b', 1) graph.add_edge('b', 'c', 1) graph.add_edge('c', 'd', 1) graph.add_edge('d', 'a', 1) print graph.print_graph() if graph.has_cycle(): print '\nThe above Graph has cycle' else: print '\nThe above Graph has no cycle' graph2 = graphs.Graph(dict()) graph2.add_edge(1, 2, 1) graph2.add_edge(1, 3, 1) graph2.print_graph() if graph2.has_cycle(): print '\nThe above graph has cycle' else: print '\nThe above graph has no cycle'
def main(): #Draw the display print("Starting up...") errorBack.draw(display) errorText.draw(display) timeBack.draw(display) timeLine.draw(display) curTimeText.draw(display) lastUpdateText.draw(display) global t0 global deltaT graphList = [] graphX = 0 graphY = 0 previousTimestamp = t0 #- 86400 * 1000 #One day if (configDict['GrabLastDay']): previousTimestamp = previousTimestamp - 86400 * 1000 #One day previous #Create graph objects graphIndex = 0 for graph in configDict['graphs']: if (graphIndex == 0): graphX = displaySize[0] // 4 graphY = displaySize[1] // 4 + configDict['padding'] if (graphIndex == 1): graphX = 3 * displaySize[0] // 4 graphY = displaySize[1] // 4 + configDict['padding'] elif (graphIndex == 2): graphX = displaySize[0] // 4 graphY = 3 * displaySize[1] // 4 - 3.5 * configDict['padding'] elif (graphIndex == 3): graphX = 3 * displaySize[0] // 4 graphY = 3 * displaySize[1] // 4 - 3.5 * configDict['padding'] graphList.append( graphs.Graph(display, Point(graphX, graphY - configDict['padding']), configDict['graphs'][graph]['size'][0], configDict['graphs'][graph]['size'][1], configDict['graphs'][graph]['midpoint'], configDict['graphs'][graph]['range'], configDict['graphs'][graph]['dataPoints'], configDict['graphs'][graph]['title'], configDict['graphs'][graph]['color'], configDict['graphs'][graph]['units'])) graphIndex = graphIndex + 1 #Observation loop, repeat for eternity, looking for new data print("Entering main loop...") #print(previousTimestamp) while (True): curTimeText.setText(f"Current Time: {epochToString(time.time()*1000)}") #Only check if it's time to check, as specified in the config if (deltaT >= pollingTime): t0 = round(time.time() * 1000) dataDicts = getDictFromURL(configDict['url'], (previousTimestamp + 1), t0) #print(dataDicts) #Check to see if we got a good response if (dataDicts != None and len(dataDicts) > 0 and dataDicts != { 'result': 'failure' }): #print(dataDicts) print("Requested data from server...") for dataDict in dataDicts: if (previousTimestamp < dataDict['e_time']): previousTimestamp = dataDict['e_time'] #Retrieve data from each data block (Each one holds 2 pieves of data) for datum in dataDict['data']: #Actually read in data previousTimestamp = datum['timestamp'] errorBack.undraw() errorText.undraw() graphList[0].addPoint(round(datum['temp'])) graphList[1].addPoint(round(datum['Dust'])) graphList[2].addPoint(round(datum['airQuality'])) graphList[3].addPoint(round(datum['MQ5'])) #print(epochToString(dataDict['timestamp']//100)) #if (previousTimestamp == datum['timestamp']): #print(previousTimestamp) lastUpdateText.setText( f"Last Sensor Update: {epochToString(previousTimestamp)}") #If we didn't retrieve any data, notify user elif (dataDicts != None and len(dataDicts) == 0): print("No new data to get!") errorBack.undraw() errorText.undraw() errorText.setText("Awaiting new data from Sensor...") #Check if window was closed try: errorBack.draw(display) errorText.draw(display) except: print("Window closed! Killing program...") exit() deltaT = round((time.time() * 1000 - t0))
def g_1(no_of_vertices): f = open("g1.dot", "w+") f.write("graph {\n") V = [] a_l = [] for i in range(no_of_vertices + 1): a_l.append(gp.Vertex(i)) for i in range(no_of_vertices + 1): V.append(i) g = gp.Graph(no_of_vertices) g.add_vertices(V[1:]) edge_count = 0 for i in range(1, no_of_vertices): wt = g.add_edge(a_l[i], a_l[i + 1], i, i + 1) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (i, i + 1, wt, wt)) #print i,i+1 edge_count = edge_count + 1 wt = g.add_edge(a_l[no_of_vertices], a_l[1], no_of_vertices, 1) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (no_of_vertices, 1, wt, wt)) edge_count = edge_count + 1 #Sparse graph avg_vertex_degree = 6 no_of_edges = (avg_vertex_degree / 2) * no_of_vertices start = time.time() def non_adjacent_vertices(index): p = [] if (index != no_of_vertices and index != 1): p = V[index + 2:] if (index == 1): p = V[index + 2:-1] return p non_adj_V = [] non_adj_V.append([]) for i in range(no_of_vertices): non_adj_V.append(non_adjacent_vertices(i + 1)) comb = [] for i in range(1, len(non_adj_V)): for j in range(len(non_adj_V[i])): comb.append([i, non_adj_V[i][j]]) if (len(comb) < no_of_edges - no_of_vertices): print "ERROR: Unable to achieve the required vertex degree."\ "Increase the number of vertices" exit(1) ee = random.sample(comb, no_of_edges - no_of_vertices) #ee = random.sample(comb, no_of_edges) for i in range(len(ee)): wt = g.add_edge(a_l[ee[i][0]], a_l[ee[i][1]], ee[i][0], ee[i][1]) f.write("%d -- %d[label=\"%d\", weight=\"%d\"];\n" % (ee[i][0], ee[i][1], wt, wt)) edge_count = edge_count + 1 adj_list = g.adjacencyList() adj_mat = g.adjacency_matrix print 'Sparse graph generated. edge_count =', edge_count print 'It took', time.time() - start, 'seconds to generate the graph.' ret = [adj_list, adj_mat] f.write("}\n") f.close() return ret
def algorithm3(g, s, t): list = g[0] mat = g[1] no_of_vertices = len(list) edgesHeap = maxHeap() for i in range(len(list)): for j in range(len(list[i])): u = i + 1 v = list[i][j] wt = mat[i][list[i][j] - 1] edgesHeap.Insert([u, v], wt) ret = edgesHeap.HeapSort() sorted_weights = ret[0] sorted_edges = ret[1] #print 'HeapSort of edges is done' b_l = [] V_1 = [] for i in range(no_of_vertices + 1): b_l.append(gp.Vertex(i)) for i in range(no_of_vertices + 1): V_1.append(i) MST = gp.Graph(no_of_vertices) MST.add_vertices(V_1[1:]) #MST.add_vertices(V_1) p = [] rank = [] dad = np.zeros(no_of_vertices + 1) dad1 = np.zeros(no_of_vertices + 1) for i in range(no_of_vertices + 1): p.append(0) rank.append(0) #print 'Initialization is done' def Find(v): w = v while (p[w] != 0): w = p[w] return w def Union(r1, r2): if (rank[r1] < rank[r2]): p[r1] = r2 if (rank[r1] > rank[r2]): p[r2] = r1 if (rank[r1] == rank[r2]): p[r1] = r2 rank[r2] = rank[r2] + 1 #flag = [] # #for i in range(no_of_vertices+1): # flag.append(0) #flag[0] = -1 #print flag #while(len(sorted_edges)!=0 and flag.count(1) != no_of_vertices):#Or all vertices are joined for edge in sorted_edges: #print flag #e = sorted_edges.pop(0) e = edge u = e[0] v = e[1] r_u = Find(u) r_v = Find(v) if (r_u != r_v): dad[v] = u dad1[u] = v MST.add_edge_mst(b_l[u], b_l[v]) #flag[u]=flag[v]=1 Union(r_u, r_v) mst_adj_list = (MST.adjacencyList()) mst_adj_list.insert(0, []) curr = s queue = [] status = np.zeros(no_of_vertices + 1) #un-visited status[s] = 1 #in-tree queue.append(s) path = [] dad = np.zeros(no_of_vertices) #print 'BFS started' while (curr != t): curr = queue.pop(0) path.append(curr) for i in range(len(mst_adj_list[curr])): nxt = mst_adj_list[curr][i] if (status[nxt] == 0): queue.append(nxt) status[nxt] = 1 dad[nxt - 1] = curr - 1 #print 'parent array generated for s to t path' max_bw_path = print_path(dad, mat, s, t) print print 'Using Kruskals algo' print 'max bw path in g from', s, 'to', t, 'is', ':', max_bw_path[0] print 'max bw = ', max_bw_path[1] print
digraph.add_edge('a', 'd', 1) digraph.add_edge('b', 'a', 3) digraph.add_edge('b', 'c', 1) digraph.add_edge('c', 'b', 1) digraph.add_edge('c', 'd', 5) digraph.add_edge('d', 'c', 1) digraph.add_edge('d', 'a', 6) print 'printing the digraph' digraph.print_graph() print print 'bft:' digraph.bft() print 'dft:' digraph.dft() print '\nprinting the graph' graph = graphs.Graph(dict()) graph.add_edge('a', 'b', 1) graph.add_edge('b', 'c', 1) graph.add_edge('c', 'd', 1) graph.add_edge('d', 'a', 1) graph.print_graph() print print 'bft:' graph.bft() print 'dft:' graph.dft()
def user_input(exec_type, visualization, agent_behaviour, emergency_evaluation): graph = None node_size = 0 resources = 0 emergencies = 0 cycles = 0 if(exec_type =="Simulation"): options = ['Uniform', 'Normal', 'Linear', 'Exponential'] distribution = click.prompt('Choose the distribution of emergencies throughout the program\n[Uniform, Normal, Linear, Exponential]') while distribution not in options: distribution = click.prompt('Invalid input\n. Choose the distribution of emergencies throughout the program\n[Uniform, Normal, Linear, Exponential]') graph = graphs.Graph(visualization) result = [] if distribution == 'Uniform': result = graph.initial_setup_simulation(distribution) elif distribution == 'Normal': result = graph.initial_setup_simulation(distribution) elif distribution == 'Linear': result = graph.initial_setup_simulation(distribution) elif distribution == 'Exponential': result = graph.initial_setup_simulation(distribution) resources = result[0] emergencies = result[1] cycles = result[2] node_size = result[3] print("\nYour chosen simulation will have parameters:\n") print("Graph node size: " + str(node_size)) print("Number of resources: " + str(resources)) print("Number of emergencies: " + str(emergencies)) print("Program cycles: " + str(cycles)) elif(exec_type == "Execution"): node_size = click.prompt('Choose the Graphs node size', type=int) while node_size <= 0: node_size = click.prompt('Not a positive Integer. Choose the Graphs node size', type=int) resources = click.prompt('Number of resources', type=int) while resources <= 0: resources = click.prompt('Not a positive Integer. Number of resources', type=int) emergencies = click.prompt('Number of emergencies', type=int) while emergencies <= 0: emergencies = click.prompt('Not a positive Integer. Number of emergencies', type=int) cycles = click.prompt('Program cycles', type=int) while cycles <= 0: cycles = click.prompt('Not a positive Integer. Program cycles', type=int) distribution = "Uniform" root = math.floor(math.sqrt(node_size)) graph = graphs.Graph(visualization) graph.initial_setup(emergencies,cycles) graph.generate_grid_graph(root,root) print("\nWelcome to our emergency resource management Multi-Agent system. You have chosen "+exec_type+" mode.") city_agent = agent.City_Agent() city_agent.initial_setup(graph, resources, agent_behaviour) graph.city_agent = city_agent graph.exec_type = exec_type graph.behaviour = agent_behaviour graph.distribution = distribution Loop(graph, resources, emergencies, cycles, city_agent, emergency_evaluation)