def get_AList(start=None, end=None, final=None, dens_const=True, transitions=gg.numTransitionGraphs): if start is not None: gg.main(transitions, start=start, end=end, final=final, dens_const=dens_const) else: gg.main(transitions) f = open("adjacency matrices.txt", "r") AList = [] ATemp = [] for line in f: if not line.strip() and len(ATemp) == len(ATemp[0]): AList.append(ATemp) ATemp = [] continue line = [float(i) for i in line.strip().split('\t')] ATemp.append(line) f.close() if final is None: # last_element = AList[len(AList)-1] # AList = AList[::5] # AList.append(last_element) AList = AList + list(reversed(AList)) return np.array(AList), np.array(gg.freqs)
def run(file_path, inv_name, firm_id, inv_amt, degree_run, eigen_run, between_run, close_run, load_run, subgraph_run, harmonic_run): inv_name = inv_name.get() firm_id = firm_id.get() inv_amt = inv_amt.get() df = gg.read_file(file_path, inv_name, firm_id, inv_amt) edgelist = gg.generate_edgelist(df) graph = gg.generate_graph(edgelist) adj_mat = gg.generate_matrix(graph) cent_df_list = [] degree_df = C.get_degree(graph, degree_run.get()) eigen_df = C.get_eigenvector(graph, eigen_run.get()) between_df = C.get_betweenness(graph, between_run.get()) close_df = C.get_closeness(graph, close_run.get()) load_df = C.get_load(graph, load_run.get()) subgraph_df = C.get_subgraph(graph, subgraph_run.get()) harmonic_df = C.get_harmonic(graph, harmonic_run.get()) cent_df_list.append(degree_df) cent_df_list.append(eigen_df) cent_df_list.append(between_df) cent_df_list.append(close_df) cent_df_list.append(load_df) cent_df_list.append(subgraph_df) cent_df_list.append(harmonic_df) cent_df = pd.concat(cent_df_list) cent_df = cent_df.transpose() gg.export_graph(cent_df, 'centralitymeasures.csv') gg.export_graph(edgelist, 'edgelist.csv') gg.export_graph(adj_mat, 'adjacencymatrix.csv')
def __init__(self, mapMsg, graphFile, source, target): # Setup member variables self.source = source self.target = target self.manager = ObstacleManager(mapMsg) # Generate the Graph on the fly if required self.radius = 100 if graphFile is None: n = 500 bases = [2, 3, 5] lower = [0, 0, 0] upper = [64, 75, 2 * numpy.pi] G = GraphGenerator.euclidean_halton_graph(n, self.radius, bases, lower, upper, source, target, mapMsg) nx.write_graphml(G, "haltonGraph.graphml") self.graph = nx.read_graphml("haltonGraph.graphml") else: # Check if graph file exists if not os.path.isfile(graphFile): print "ERROR: map file not found!" quit() self.graph = nx.read_graphml(graphFile) if source is not None: GraphGenerator.insert_vertices(self.graph, [source], self.radius) if target is not None: GraphGenerator.insert_vertices(self.graph, [target], self.radius)
def __init__(self, mapMsg, graphFile, source, target): # Setup member variables self.source = source self.target = target self.manager = ObstacleManager(mapMsg) # Generate the Graph on the fly if required self.radius = 100 if graphFile is None: n = 500 bases = [2,3,5] # Should be prime numbers lower = [0,0,0] # The lowest possible values for the config upper = [64,75,2*numpy.pi] # The highest possible values for the config G = GraphGenerator.euclidean_halton_graph(n, self.radius, bases, lower, upper, source, target, mapMsg) # Create the graph nx.write_graphml(G, "haltonGraph.graphml") # Save the graph self.graph = nx.read_graphml("haltonGraph.graphml") # Read the graph (that we just saved, probably not necessary) else: # Check if graph file exists print(os.path.isfile(graphFile)) if not os.path.isfile(graphFile): print "ERROR: graph file not found!" quit() self.graph = nx.read_graphml(graphFile) # Load the graph print "graph loaded" # Insert source and target if provided if source is not None: GraphGenerator.insert_vertices(self.graph, [source], self.radius) if target is not None: GraphGenerator.insert_vertices(self.graph, [target], self.radius)
def generateGraph(self, area, nodeNum, minDegree): self.generator = GraphGenerator() graph = self.generator.generate(area, nodeNum, minDegree) for i in range(0, len(graph.vertices)): graph.vertices[i].id = i graph.toAjacencyForm() #graph.displayAjacencyForm() return graph
def main(): g = GraphGenerator() b = Benchmark() amount = 10 vertices = 3000 connection_density = 3 graphs = g.get_graphs(amount, vertices, connection_density) b.unsortedPrim(graphs, amount, vertices) b.heapPrim(graphs, amount, vertices)
def get_ICs(f=None, removeMean=False): if f is not None: ICs = gg.readMatrixFromFile(f) if removeMean: return ICs[0] - np.mean(ICs[0]) else: return ICs[0] else: init_phases = np.array(getRandomDistribution(N, -np.pi, np.pi, rd.uniform)) init_freqs = np.array(gg.getRandomDistribution(N, -gg.freqBound, gg.freqBound)) if removeMean: init_phases -= np.mean(init_phases) init_freqs -= np.mean(init_freqs) return init_phases
def tsp_data(self): xs = [] ys = [] yps = [] for x in range(self.change, self.num_data): #Generate 1M datapoints GG = GraphGenerator.GraphGenerator(self.size, self.max_value) if directed: GG.directed_graph( ) #check if adjacency matrix is directed or undirected else: GG.undirected_graph() g = np.array( GG.get_adjacency_matrix()) #Create undirected adjacency matrix matrx = g.copy() g[g == 0] = 999 path = tsp.tsp_dp_solve(g) #solve the tsp tsp_val = tsp.tour_len(self.path, g) #get the tsp cost yps.append(path) ys.append(tsp_val) #Add the data to the arrays xs.append(list(matrx.flatten())) pickle_file = open('xs.pickle', 'wb') #Pickle the data for later use pickle.dump(xs, pickle_file) pickle_file.close() pickle_file = open('yps.pickle', 'wb') pickle.dump(ys, pickle_file) pickle_file.close() pickle_file = open('ys.pickle', 'wb') pickle.dump(ys, pickle_file) pickle_file.close()
def generate(self, nodesNo, edgesNo): self.nodesNo = nodesNo self.edgesNo = edgesNo graphGenerator = GraphGenerator(nodesNo, edgesNo) self.edges = graphGenerator.edges self.nodes = graphGenerator.nodes self.labels = self.__createLabels__()
def setup_complex(self): import GraphGenerator as graphgen # importing my random graph generator module random_graph = graphgen.ComplexGraph( ) # compositon used to access random graph class random_graph.setup_nodes() # random graph being set up random_graph.setup_neighbours() self.display_data(random_graph.graph)
def main(): edges = [5000, 10000, 50000, 100000, 200000, 300000, 400000, 500000, 600000, 700000] nodes = 1000 max_weight = 1000000 source = 0 for test_no in range(len(edges)): for graph_no in range(20): file_id = "{}{}".format(test_no, graph_no) print("Running test number {}, iteration {}".format(test_no, graph_no)) if graph_no < 10: GraphGenerator.generate_graph("{}/graph{}.txt".format(DATA_FOLDER_NAME, file_id), nodes, edges[test_no], source, max_weight) else: GraphGenerator.generate_graph_probability("{}/graph{}.txt".format(DATA_FOLDER_NAME, file_id), nodes, edges[test_no]/(nodes*nodes), source, max_weight) graph = Graph() graph.read_from_file("{}/graph{}.txt".format(DATA_FOLDER_NAME, file_id), True) run_algorithms(graph, file_id)
def __init__(self, map_service_name, halton_points, disc_radius, collision_delta, source_topic, target_topic, pub_topic, service_topic, car_width, car_length, pose_topic): print("[Planner Node] Getting map from service...") rospy.wait_for_service(map_service_name) self.map_msg = rospy.ServiceProxy(map_service_name, GetMap)().map print("[Planner Node] ...got map") print("[Planner Node] Generating graph file...") graph_file = GraphGenerator.generate_graph_file( self.map_msg, halton_points, disc_radius, car_width, car_length, collision_delta) print("[Planner Node] ..graph generated") self.environment = HaltonEnvironment(self.map_msg, graph_file, None, None, car_width, car_length, disc_radius, collision_delta) self.planner = HaltonPlanner(self.environment) self.source_pose = None self.source_updated = False self.source_yaw = None self.source_lock = Lock() self.target_pose = None self.target_updated = False self.target_yaw = None self.target_lock = Lock() self.cur_plan = None self.plan_lock = Lock() self.orientation_window_size = 21 self.big_plan = np.array([]) self.count = 0 self.count2 = 0 if pub_topic is not None: self.plan_pub = rospy.Publisher(pub_topic, PoseArray, queue_size=1) self.source_sub = rospy.Subscriber(source_topic, PoseWithCovarianceStamped, self.source_cb, queue_size=1) self.target_sub = rospy.Subscriber(target_topic, PoseStamped, self.target_cb, queue_size=1) else: self.plan_pub = None if service_topic is not None: self.plan_service = rospy.Service(service_topic, GetPlan, self.get_plan_cb) else: self.plan_service = None print '[Planner Node] Ready to plan'
def testPlanar(self): # Generate K(4) graph p_graph = GraphGenerator.make_planar_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(p_graph) GraphUtils.draw_graph(p_graph, "planar_test", bad_graph) # print "Test on planar graph:", 'PASS' if planar else 'FAIL' self.assertTrue(planar) # True means graph is planar
def testK5(self): # Generate K(5) graph k5 = GraphGenerator.make_k5_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(k5) GraphUtils.draw_graph(k5, "K5", bad_graph) # print "Test on K(5):", 'FAIL' if planar else 'PASS' self.assertFalse(planar) # False means K(5) subgraph was found
def testK33(self): # Generate K(3, 3) graph k33 = GraphGenerator.make_k33_graph() # Test graph planar, bad_graph = KuratowskiPlanarity.find_planarity(k33) GraphUtils.draw_graph(k33, "K33", bad_graph) # print "Test on K(3, 3):", 'FAIL' if planar else 'PASS' self.assertFalse(planar) # False means K(3, 3) subgraph was found
def main(): """ Entry point into the program. """ num_nodes = 20 # Use binomial coefficient to find algorithm runtime (algorithm is O(n choose 6 + n choose 5)) # K33 check complexity complexity_k33 = math.factorial(num_nodes) / ( math.factorial(6) * math.factorial(num_nodes - 6)) # K5 check complexity complexity_k5 = math.factorial(num_nodes) / (math.factorial(5) * math.factorial(num_nodes - 5)) # Overall complexity formatted with commas complexity = GraphUtils.format_commas(complexity_k5 + complexity_k33) print "[kuratowski] Iterations (worst case) for %s nodes: %s" % ( num_nodes, complexity, ) # Random graph, usually nonplanar solve_random_graph(num_nodes, 0.7, "graph1") # Graph is likely to be nonplanar # Random graph, usually planar solve_random_graph(8, 0.4, "graph2") # Graph is usually planar # K(3, 3) graph k33 = GraphGenerator.make_k33_graph() solve_graph(k33, "k33") # K(5) graph k5 = GraphGenerator.make_k5_graph() solve_graph(k5, "k5") # Guaranteed planar graph planar_graph = GraphGenerator.make_planar_graph() solve_graph(planar_graph, "planar_graph") # Display each graph (blocking command, run last) plt.show()
def runTest(self): """ Use the randomly generated array to test the graph generator """ cycleConstraint = Constraint.cycleConstraint() generator = gg.GraphGenerator() generator.registerConstraints(cycleConstraint) generator.generateGraph(self.testArray, 0.1) #generator.outputGraph(3, "testGraph") graph = generator.getGraphObject() print nx.info(graph)
def run(numTrials, AList, ICs, a, M, freqs, ss_diffs_file, ta_OP_file, hm_file=None, end_state=None): for i in range(numTrials): OP, ta_OP, end_theta, end_freq, pairwise_map = runSim( AList, ICs, freqs, a, M) ss_diffs_file.write( str(0) + "\t" + str(a) + "\t" + str(M) + "\t" + str(get_ss_diff(ta_OP))) ss_diffs_file.write("\n") gg.printArrayToFile(ta_OP, ta_OP_file) if hm_file is not None: gg.printMatrixToFile(pairwise_map, hm_file) if end_state is not None: for i in range(numTrials): end_state.append((end_theta, end_freq))
def FillUserInteractions(n_vertices, n_edges, day): """ Create a csv file with the information of the interactions of the user with the platform, it selects the user ID from the demographic_data.csv file, fill the info of the data """ pd_usersID = pd.read_csv('demographic_data.csv', usecols=['User']) #print(pd_usersID.head()) with open('{}_app_data.csv'.format(day), 'w') as csvFile: print( '***** Creating the data base for user interactions in skynetapp ******' ) interaction_Labels = ['User', 'N Steps', 'Total Time', 'Steps'] writer = csv.DictWriter(csvFile, fieldnames=interaction_Labels) writer.writeheader() index = 0 total_users = len(pd_usersID['User']) for user in pd_usersID['User']: index += 1 #index = pd.Index(pd_usersID['User']).get_loc(user) #print(user, index) if index % 1000 == 0.0: print('{}/{}'.format(index, total_users)) if index % 2 == 0: continue n_visits = random.randint(1, 10) for visit in range(1, n_visits): gr = nx.MultiDiGraph( gr_maker.CreateRandomGraph(n_vertices, n_edges)) interactions = gr.edges(data=True) total_time = GetTotalTime(interactions) data = [{ 'User': user, 'N Steps': len(interactions), 'Total Time': total_time, 'Steps': interactions }] writer.writerows(data) csvFile.close()
def ToyModel(n_vertices, n_edges): """ Crea un grafo aleatorio, con pesos aleatorios Regresa un dictionario con la representacion """ with open('test_data.csv', 'w') as csvFile: Step_Labels = [ 'User', 'Gender', 'Age', 'Social Level', 'Salary', 'N Steps', 'Steps', 'Total Time', 'Time' ] fields = Step_Labels writer = csv.DictWriter(csvFile, fieldnames=fields) writer.writeheader() for user in range(1, 1000): gr1 = grafo_maker.CreateGraph(n_vertices, n_edges) user_ID = 'U_%d' % random.randint(1, 1000) ObtainPath(gr1, user_ID, csvFile, writer) csvFile.close()
def __init__( self, map_service_name, halton_points, disc_radius, collision_delta, pub_topic, car_width, car_length, pose_arr, start_waypoint_topic, #for visualization in rviz good_waypoint_topic, #for visualization in rviz bad_waypoint_topic, #for visualization in rviz start_waypoint_pose, #for visualization in rviz good_waypoint_pose, #for visualization in rviz bad_waypoint_pose #for visualization in rviz ): print("[Planner Node] Getting map from service...") rospy.wait_for_service(map_service_name) self.map_msg = rospy.ServiceProxy(map_service_name, GetMap)().map print("[Planner Node] ...got map") print("[Planner Node] Generating graph file...") graph_file = GraphGenerator.generate_graph_file( self.map_msg, halton_points, disc_radius, car_width, car_length, collision_delta) print("[Planner Node] ..graph generated") self.environment = HaltonEnvironment(self.map_msg, graph_file, None, None, car_width, car_length, disc_radius, collision_delta) self.planner = HaltonPlanner(self.environment) self.source_yaw = None #0 self.target_yaw = None #0 self.cur_plan = None self.plan_lock = Lock() self.pose_arr = pose_arr self.orientation_window_size = 21 self.start_waypoint_pose = start_waypoint_pose self.good_waypoint_pose = good_waypoint_pose self.bad_waypoint_pose = bad_waypoint_pose #waypoints visualization purpose self.start_waypoint_pub = rospy.Publisher(start_waypoint_topic, Marker, queue_size=100) self.good_waypoint_pub = rospy.Publisher(good_waypoint_topic, MarkerArray, queue_size=100) self.bad_waypoint_pub = rospy.Publisher(bad_waypoint_topic, MarkerArray, queue_size=100) print('pub topic: ', pub_topic) if pub_topic is not None: self.plan_pub = rospy.Publisher(pub_topic, PoseArray, queue_size=1) else: self.plan_pub = None print '[Planner Node] Ready to plan'
def main(): G = gg.Graph() set1 = G.create_nodes(200, {"clustId": 1}, 0) set2 = G.create_nodes(400, {"clustId": 2}, 0) set3 = G.create_nodes(50, {"clustId": 3}, 0) set4 = G.create_nodes(50, {"clustId": 3}, 0) for i in range(10): G.create_random_edges(2500, [set1, set2, set3, set4], [[0.29, 0.01, 0, 0], [0, 0.5, 0, 0], [0, 0, 0.10, 0], [0, 0, 0, 0.10]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) for i in range(10, 15): G.create_random_edges( 500, [set1, set2, set3, set4], [[0.1, 0, 0.4, 0], [0, 0.1, 0, 0.4], [0, 0, 0, 0], [0, 0, 0, 0]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) for i in range(15, 25): G.create_random_edges( 500, [set1, set2, set3, set4], [[0.2, 0, 0, 0], [0, 0.2, 0, 0], [0, 0, 0, 0.6], [0, 0, 0, 0]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) # set5 = G.create_nodes(50, {"clustId":5}, 2) # G.create_random_edges( 200, # [set5], # [[1]], # [gg.UniformDistrib()], # 2) # G.create_random_edges( 200, # [set5], # [[1]], # [gg.UniformDistrib()], # 3) # G.create_random_edges( 100, # [set5], # [[1]], # [gg.UniformDistrib()], # 4) # learn_parameters(G) # cdr = cd.CommunityDetector(G, sorted_results[-1][1]["tr"], sorted_results[-1][1]["h"], sorted_results[-1][1]["d"], sorted_results[-1][1]["p"]) cdr = cd.CommunityDetector(G, 10, 100, 5, 10000) cdr.run(False, False) # G.create_random_edges(200, [set1, set2], [[0,1],[0,0]], [gg.UniformDistrib(), gg.UniformDistrib()],4) # G.create_random_edges(200, [set1, set2, set3, set4], [[0,0,0,0.5],[0,0,0.5,0],[0,0,0,0],[0,0,0,0]], [gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib()],5) # G.create_random_edges(400, [set1, set2], [[0.49,0.02],[0.,0.49]], [gg.UniformDistrib(), gg.UniformDistrib()],10) # G.plot_sequence() # G = gg.Graph(True) # set1 = G.create_nodes(100) # set2 = G.create_nodes(80) # G.create_random_edges(500, [set1, set2], [[0.49,0.01],[0.01,0.49]], [gg.UniformDistrib(), gg.UniformDistrib()]) # G.plot_sequence() # tree = st.SegmentTree() # elements = [(0,5),(0,5),(0,10),(0,7),(5,10),(15,20),(12,st.SegmentTree.infinite)] # for i in range(len(elements)): # tree.insert(i, elements[i]) # # query = [0,3,5,7,11,12,20,98] # # for q in query: # # print "query=",q," - result=",tree.query(q) # # pdb.set_trace() # to_delete = range(len(elements)) # random.shuffle(to_delete) # print to_delete # for d in to_delete: # tree.delete(d, elements[d]) # print "query=",elements[d][1]," - result=",tree.query(elements[d][1]) # pdb.set_trace()
def main(factor): G = gg.Graph() set1 = G.create_nodes(200, {"clustId": 1}, 0) set2 = G.create_nodes(200, {"clustId": 2}, 0) set3 = G.create_nodes(200, {"clustId": 2}, 0) set4 = G.create_nodes(50, {"clustId": 4}, 0) set5 = G.create_nodes(50, {"clustId": 5}, 0) for i in range(4): G.create_random_edges( 500 * factor, [set1, set2, set3, set4, set5], [[0.303, 0.005, 0.005, 0.001, 0.001], [0, 0.17, 0.24, 0.001, 0.001], [0, 0, 0.17, 0.001, 0.001], [0, 0, 0, 0.05, 0.001], [0, 0, 0, 0, 0.05]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) for i in range(4, 7): G.create_random_edges( 40 * factor, [set1, set2, set3, set4, set5], [[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 1], [0, 0, 0, 0, 0]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) for i in range(7, 9): G.delete_random_edges( 200 * factor, [set1, set2, set3, set4, set5], [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], i) G.delete_random_edges(0, [set1, set2, set3, set4, set5], [[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], [ gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib() ], 9) # for i in range(9,14): # G.delete_random_edges( 40*factor, # [set1, set2, set3, set4, set5], # [[0 ,0 ,0 ,0 ,0 ], # [0 ,0 ,1 ,0 ,0 ], # [0 ,0 ,0 ,0 ,0 ], # [0 ,0 ,0 ,0 ,0 ], # [0 ,0 ,0 ,0 ,0 ]], # [gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib(), gg.UniformDistrib()], # i) cdr = cd.CommunityDetector(G, 10, 100, 5, 10000) cdr.run(True, True, False, 0, 4) G.update_nodes(set5, {"clustId": 4}) cdr.run(True, True, False, 4, 7) G.update_nodes(set3, {"clustId": 3}) cdr.run(True, True, False, 7, 12)
import GraphGenerator as GG import Graph as G import RandomWalk graph = GG.generate_graph("twenty_nodes.brite") #graph = G.generateGraph(100,5) src = 1 dest = 4 print graph print "src : " + str(src) print "dest : " + str(dest) print "random walk path is :", RandomWalk.randomWalk(graph, src, dest) print "shortest path: ", G.shortest_path(graph, src, dest)
def solve(n,m, item): graph = GraphGenerator.generateGraph(n,m) if item=="a" : # ALGORITMO FORCA BRUTA # O vertice de partida sera sempre o numero 1 (indice 0) indexes = [i for i in range(1,n)] auxPaths = itertools.permutations(indexes, n-1) # Gerando todos os caminhos possiveis paths = [] for i in auxPaths: paths.append([0] + list(i) + [0]) # Percorrendo todos os caminhos possiveis global minCost, minCostPath,existeCaminho minCost= 0 minCostPath = 0 existeCaminho = False for p in paths: auxCost = 0 for step in range(0,n): i = p[step] j = p[step+1] if graph[i][j] == -1: break auxCost = auxCost + graph[i][j] # Quando encontramos um caminho valido, o armazenamos e calculamos o seu custo if p[j] == p[0]: existeCaminho = True if (minCost == 0 or minCost > auxCost): minCost = auxCost minCostPath = p # ALGORITMO HELD-KARP (PROGRAMACAO DINAMICA) hkTimeStart = timeit.default_timer() global memoria memoria = 0 #Matriz de memoization M = [[-1 for i in range(0,pow(2,n))] for j in range(0,n)] memoria = pow(2,n)*n # Vertice de partida sendo o 1 (indice 0) v_inicial = 0 # Setar a bitmask do noh final v_mask = 2**n - 2 memoria += 2 def tsp( c, b): if b == 0: return graph[c][v_inicial] if M[c][b] != -1: return M[c][b] result = 1000 global memoria memoria += 2 for i in range(0,n) : if (((b & (1 << i)) != 0) & (i != c) & (graph[c][i]!=-1)) : a = tsp(i, b & ~(1 << i)) memoria += 1 if (a != -1): result = min(result, graph[c][i] + a) M[c][b] = result return result minCostHK = tsp(v_inicial,v_mask) memoria+=1 hkTime = timeit.default_timer() - hkTimeStart #Retornando os resultados if item == "a": print "O grafo gerado eh" for i in range(0,n): print graph[i] print "Por forca bruta,", if existeCaminho: print "o caminho desejado eh:", minCostPath, print " e o custo minimo associado eh:", minCost else: print "nao existe caminho minimo" print "Por Held-Karp", if minCostHK == 1000 : print "o grafo eh nao-hamiltoniano" else: print "o custo minimo associado eh:", minCostHK if item == "b": return hkTime if item == "c": return memoria
def solve(n, m, item): graph = GraphGenerator.generateGraph(n, m) if item == "a": # ALGORITMO FORCA BRUTA # O vertice de partida sera sempre o numero 1 (indice 0) indexes = [i for i in range(1, n)] auxPaths = itertools.permutations(indexes, n - 1) # Gerando todos os caminhos possiveis paths = [] for i in auxPaths: paths.append([0] + list(i) + [0]) # Percorrendo todos os caminhos possiveis global minCost, minCostPath, existeCaminho minCost = 0 minCostPath = 0 existeCaminho = False for p in paths: auxCost = 0 for step in range(0, n): i = p[step] j = p[step + 1] if graph[i][j] == -1: break auxCost = auxCost + graph[i][j] # Quando encontramos um caminho valido, o armazenamos e calculamos o seu custo if p[j] == p[0]: existeCaminho = True if (minCost == 0 or minCost > auxCost): minCost = auxCost minCostPath = p # ALGORITMO HELD-KARP (PROGRAMACAO DINAMICA) hkTimeStart = timeit.default_timer() global memoria memoria = 0 #Matriz de memoization M = [[-1 for i in range(0, pow(2, n))] for j in range(0, n)] memoria = pow(2, n) * n # Vertice de partida sendo o 1 (indice 0) v_inicial = 0 # Setar a bitmask do noh final v_mask = 2**n - 2 memoria += 2 def tsp(c, b): if b == 0: return graph[c][v_inicial] if M[c][b] != -1: return M[c][b] result = 1000 global memoria memoria += 2 for i in range(0, n): if (((b & (1 << i)) != 0) & (i != c) & (graph[c][i] != -1)): a = tsp(i, b & ~(1 << i)) memoria += 1 if (a != -1): result = min(result, graph[c][i] + a) M[c][b] = result return result minCostHK = tsp(v_inicial, v_mask) memoria += 1 hkTime = timeit.default_timer() - hkTimeStart #Retornando os resultados if item == "a": print "O grafo gerado eh" for i in range(0, n): print graph[i] print "Por forca bruta,", if existeCaminho: print "o caminho desejado eh:", minCostPath, print " e o custo minimo associado eh:", minCost else: print "nao existe caminho minimo" print "Por Held-Karp", if minCostHK == 1000: print "o grafo eh nao-hamiltoniano" else: print "o custo minimo associado eh:", minCostHK if item == "b": return hkTime if item == "c": return memoria
SA_Files, SA_Sparse_Files, mod_Files, freq_mod_Files, sparsefreq_mod_Files, dense_mod_Files = [], [], [], [], [], [] ICs, ER_Graphs, ER_Dense_Graphs, ER_Sparse_Graphs, SA_Graphs, SA_Sparse_Graphs, = [], [], [], [] ,[], [] MA_Graphs, mod_Graphs, freq_mod_Graphs, sparsefreq_mod_Graphs, dense_mod_Graphs = [], [], [], [], [] for i in range(25): ER_Files.append(open(os.path.join(path_ER + str(i) + ".txt"), "r")) ER_Dense_Files.append(open(os.path.join(path_ER_dense + str(i) + ".txt"), "r")) ER_Sparse_Files.append(open(os.path.join(path_ER_sparse+str(i)+".txt"),"r")) SA_Files.append(open(os.path.join(path_SA + str(i) + ".txt"), "r")) SA_Sparse_Files.append(open(os.path.join(path_SA_sparse+str(i)+".txt"),"r")) arg_1 = 0 ER_Sparse_Graphs.append(gg.readMatrixFromFile(ER_Sparse_Files[arg_1])) SA_Sparse_Graphs.append(gg.readMatrixFromFile(SA_Sparse_Files[arg_1])) ER_Graphs.append(gg.readMatrixFromFile(ER_Files[arg_1])) SA_Graphs.append(gg.readMatrixFromFile((SA_Files[arg_1]))) ER_Dense_Graphs.append(gg.readMatrixFromFile(ER_Dense_Files[arg_1])) AList, freqs = get_AList(ER_Sparse_Graphs[0], ER_Dense_Graphs[0], dens_const=False) ICs = get_ICs(open(path_random_ICs + str(arg_1) + ".txt", "r")) freqs = gg.readMatrixFromFile(open(path_random_nat_freqs+str(arg_1)+".txt", "r"))[0] runSim(AList, ICs, freqs) timeArray = [dt* i for i in range(len(standardOPData))] ta_OP = averagedOPData f4 = plt.figure(4) plt.xlabel('Graph')
while True: num = int( input( "Which graph would you like to check? \n Press ( 1 ) for asymptamatic \n Press ( 2 ) for symptamatic \n Press ( 3 ) for hospitalised \n Press ( 4 ) for ICU-ed \n Press ( 5 ) for ventilator cases \n Press ( 6 ) for death \n Press ( 7 ) for immune \n Press ( 8 ) for recovered \n Press ( 9 ) to exit" )) if num is 9: break age = int( input( "Press ( 1 ) for checking the trend among kids \n Press ( 2 ) for checking the trend among the youth \n Press ( 3 ) for checking the trend among the adults \n Press ( 4 ) to check overall trend " )) if num is 1: if age is 1: graph.generate(sim, sim.asympKidNum) if age is 2: graph.generate(sim, sim.asympYoungNum) if age is 3: graph.generate(sim, sim.asympAdultNum) if age is 4: graph.generate(sim, sim.asympNum) if num is 2: if age is 1: graph.generate(sim, sim.sympKidNum) if age is 2: graph.generate(sim, sim.sympYoungNum) if age is 3: graph.generate(sim, sim.sympAdultNum) if age is 4:
misaligned_files.append( open(os.path.join(path_misaligned) + str(i) + ".txt", "r")) # mod_Files.append(open(os.path.join(path_modular) + str(i) + ".txt", "r")) dense_mod_Files.append( open(os.path.join(path_dense_mod) + str(i) + ".txt", "r")) SA_Files.append(open(os.path.join(path_SA + str(i) + ".txt"), "r")) SA_Sparse_Files.append( open(os.path.join(path_SA_sparse + str(i) + ".txt"), "r")) freq_mod_Files.append( open(os.path.join(path_freq_mod + str(i) + ".txt"), "r")) # sparsefreq_mod_Files.append(open(os.path.join(path_sparsefreq_mod+str(i)+".txt"), "r")) # arg_1 = int(sys.argv[1]) - 1 #Job number, ranging from 0 to 255 arg_1 = 0 dense_mod_Graphs.append(gg.readMatrixFromFile(dense_mod_Files[arg_1])) ER_Sparse_Graphs.append(gg.readMatrixFromFile(ER_Sparse_Files[arg_1])) SA_Sparse_Graphs.append(gg.readMatrixFromFile(SA_Sparse_Files[arg_1])) ER_Graphs.append(gg.readMatrixFromFile(ER_Files[arg_1])) SA_Graphs.append(gg.readMatrixFromFile((SA_Files[arg_1]))) ER_Dense_Graphs.append(gg.readMatrixFromFile(ER_Dense_Files[arg_1])) # MA_Graphs.append(gg.readMatrixFromFile(misaligned_files[0])) freq_mod_Graphs.append(gg.readMatrixFromFile(freq_mod_Files[arg_1])) AList, freqs = get_AList(ER_Graphs[0], dense_mod_Graphs[0], dens_const=True) ICs = get_ICs() # freqs = gg.readMatrixFromFile(open(path_random_nat_freqs+str(arg_1)+".txt", "r"))[0]
def set_source_and_target(self, source, target): self.source = source self.target = target GraphGenerator.insert_vertices(self.graph, [source, target], self.radius)
import itertools import GraphGenerator n = 6 m = 10 graph = GraphGenerator.generateGraph(n,m) # O vertice de partida sera sempre o numero 1 (indice 0) indexes = [i for i in range(1,n)] auxPaths = itertools.permutations(indexes, n-1) # Gerando todos os caminhos possiveis paths = [] for i in auxPaths: paths.append([0] + list(i) + [0]) # Percorrendo todos os caminhos possiveis minCost = 0 minCostPath = 0 existeCaminho = False for p in paths: auxCost = 0 for step in range(0,n): i = p[step] j = p[step+1] if graph[i][j] == -1: break auxCost = auxCost + graph[i][j] # Quando encontramos um caminho valido, o armazenamos e calculamos o seu custo if p[j] == p[0]: existeCaminho = True
def find_planarity(G): """ Searches *graph* for any subgraphs isomorphic to K(3, 3) or K(5). Complexity: O((n choose 6) + (n choose 5)) Args: graph (networkx.Graph): The graph to be searched Returns: bool, networkx.Graph: Planarity of the graph and either None or the detected Kuratowski graph """ planar = True offending_subgraph = None # Optimization step: # Remove nodes from graph with edge count > 1 and assign to new graph (don't alter original) outdeg = G.degree() to_keep = [n for n in outdeg if outdeg[n] > 1] graph = G.subgraph(to_keep) num_nodes = len(graph.nodes()) it = 0 k33 = GraphGenerator.make_k33_graph() k5 = GraphGenerator.make_k5_graph() if num_nodes > 5: # Test if graph contains a K(3, 3) subgraph. for subgraph_nodes in itertools.combinations(graph.nodes(), 6): it += 1 subgraph = graph.subgraph(subgraph_nodes) # If the subgraph is bipartite, get each set if bipartite.is_bipartite(graph): # subgraph? set1, set2 = bipartite.sets(graph) # subgraph? # If one set in a 6-node bipartite graph has 3 nodes, then the other # set has 3 nodes, making it a K(3, 3) graph. if len(set1) == 3: planar = False offending_subgraph = subgraph # Test for isomorphism if nx.is_isomorphic(subgraph, k33): planar = False offending_subgraph = subgraph if planar and num_nodes > 4: # Test if graph contains a K(5) subgraph. for subgraph_nodes in itertools.combinations(graph.nodes(), 5): it += 1 subgraph = graph.subgraph(subgraph_nodes) # If the graph is complete, it's a K(5) graph if GraphUtils.check_completeness(subgraph): planar = False offending_subgraph = subgraph # Test isomorphism if nx.is_isomorphic(subgraph, k5): planar = False offending_subgraph = subgraph print "Iterations (actual):", GraphUtils.format_commas(it) return planar, offending_subgraph