def make_graphs(min_edges, max_edges): graphs = [] for j in range(min_edges, max_edges + 1): for sparse6 in generate_multigraphs(j): G = Graph(sparse6) G.build_img() graphs.append(G) return graphs
def main(): grid = Graph(Vector2(7, 7)) #Graph size grid.make_nodes() #makes nodes grid.nodes[23].can_traverse = False #wall 1 grid.nodes[24].can_traverse = False #wall 2 grid.nodes[25].can_traverse = False #wall 3 s = grid.nodes[10] #starting node g = grid.nodes[38] #goal node p = algorithm(s, g, grid) # astar where the start, goal, and graph are taken in
def testing_astar(): '''Algorithm testing''' grid = Graph(Vector2(7, 7)) grid.make_nodes() grid.nodes[23].can_traverse = False grid.nodes[24].can_traverse = False grid.nodes[25].can_traverse = False s = grid.nodes[10] g = grid.nodes[38] p = algorithm(s, g, grid) a = 0
def init_graph_mfriend(k): jfile = mfriend(k) vertices = [Vertex(j.name) for j in jfile] edges = [] for j in jfile: for u in vertices: if j.name == u.name: for f in j.friend_list: for v in vertices: if v.name == f: uv = Edge((u, v), directed=False) edges.append(uv) for e in edges: if (uv.source.name, uv.target.name) == ( e.source.name, e.target.name) or ( uv.target.name, uv.source.name) == (e.source.name, e.target.name): pass graph = Graph() init_graph(graph, vertices, edges) return graph
def random_model(n1, n2, k, cap): """ create a graph with the partition A of size n1 and partition B of size n2 using the random model :param n1: size of partition A :param n2: size of partition B :param k: length of preference list for vertices in A :param cap: capacity of a vertex in partition B :return: bipartite graph with above properties """ def order_by_master_list(l, master_list): return sorted(l, key=master_list.index) g = Graph() # create the sets R and H, r_1 ... r_n1, h_1 .. h_n2 R = set('r{}'.format(i) for i in range(1, n1 + 1)) H = set('h{}'.format(i) for i in range(1, n2 + 1)) for res in R: g.residents.append(Resident(res)) for hosp in H: g.hospitals.append(Hospital(hosp, 0, cap)) # prepare a master list # master_list = list(h for h in H) # random.shuffle(master_list) pref_lists_H, pref_lists_R = collections.defaultdict(list), {} for resident in R: r_ind = resident[1:] pref_list = random.sample(H, min( len(H), k)) # random.randint(1, len(H))) # sample houses pref_lists_R[ resident] = pref_list # order_by_master_list(pref_list, master_list) # add these residents to the preference list for the corresponding hospital for hospital in pref_list: h_ind = hospital[1:] pref_lists_H[hospital].append(resident) g.edges.append(Edge(r_ind, h_ind)) res = g.get_resident(resident) for hosp in pref_lists_R[resident]: res.pref.append(g.get_hospital(hosp)) for hospital in H: random.shuffle(pref_lists_H[hospital]) hosp = g.get_hospital(hospital) for res in pref_lists_H[hospital]: hosp.pref.append(g.get_resident(res)) return g
def main(): nodelist = [(8, 2), (5, 9), (4, 3), (2, 6), (1, 7), (9, 2), (5, 5), (8, 3), (11, 8), (6, 14)] n = len(nodelist) edges = edge_list(nodelist, n) g = Graph(n) for i in range(0, edges.shape[0]): g.add_edge(int(edges[i][0]), int(edges[i][1]), edges[i][2]) g.toString() start_node = 0 global visited visited = [False] * n plot_graph(nodelist, start_node)
def init_graph_toy_clique_problem(): name = 'abcdef' vertices = [Vertex(n) for n in name] e1 = Edge((vertices[0], vertices[1]), directed=False) e2 = Edge((vertices[1], vertices[2]), directed=False) e3 = Edge((vertices[2], vertices[3]), directed=False) e4 = Edge((vertices[3], vertices[0]), directed=False) e5 = Edge((vertices[0], vertices[4]), directed=False) e6 = Edge((vertices[4], vertices[5]), directed=False) e7 = Edge((vertices[5], vertices[0]), directed=False) graph = Graph() edges = [e1, e2, e3, e4, e5, e6, e7] init_graph(graph, vertices, edges) return graph
def init_graph_johnson(): w = Vertex('w') x = Vertex('x') y = Vertex('y') z = Vertex('z') e1 = Edge((w, z), weight=2) e2 = Edge((z, x), weight=-7) e3 = Edge((x, w), weight=6) e4 = Edge((x, y), weight=3) e5 = Edge((y, z), weight=5) e6 = Edge((z, y), weight=-3) e7 = Edge((y, w), weight=4) graph = Graph() vertices = [w, x, y, z] edges = [e1, e2, e3, e4, e5, e6, e7] init_graph(graph, vertices, edges) return graph
def earliest_ancestor(ancestors, starting_node): graph = Graph() # For each pair for i in ancestors: # Add a vertices graph.add_vertex(i[0]) # Parent graph.add_vertex(i[1]) # Child # Add an edge between the parent and the child graph.add_edge(i[1],i[0]) q = Queue() visited = set() longest_path = 1 parent_end = -1 q.enqueue([starting_node]) while q.size() > 0: path = q.dequeue() vertex = path[-1] if len(path) >= longest_path and vertex < parent_end or len(path) > longest_path: parent_end = vertex visited.add(vertex) for neighbor in graph.vertices[vertex]: path_add = path.copy() path_add.append(neighbor) q.enqueue(path_add) return parent_end
from dfs import dfs from graph_class import Graph from check_connected_dfs import find_all_group, check_connected_num_dfs G1 = Graph(13) print(G1.nodes) print(G1.adj_of_node) G1.build_undirected_edge(0, 1) G1.build_undirected_edge(0, 9) G1.build_undirected_edge(1, 0) G1.build_undirected_edge(1, 8) G1.build_undirected_edge(2, 3) G1.build_undirected_edge(3, 2) G1.build_undirected_edge(3, 4) G1.build_undirected_edge(3, 5) G1.build_undirected_edge(3, 7) G1.build_undirected_edge(4, 3) G1.build_undirected_edge(5, 3) G1.build_undirected_edge(5, 6) G1.build_undirected_edge(6, 5) G1.build_undirected_edge(6, 7) G1.build_undirected_edge(7, 3) G1.build_undirected_edge(7, 8) G1.build_undirected_edge(7, 10) G1.build_undirected_edge(7, 11) G1.build_undirected_edge(8, 1) G1.build_undirected_edge(8, 7) G1.build_undirected_edge(8, 9) G1.build_undirected_edge(9, 0) G1.build_undirected_edge(9, 8) G1.build_undirected_edge(10, 7)
def verification(directory): g = Graph() g.create_graph(directory) generate_max_card_lp(g, directory + '/max_card_lp.txt') print(len(g.edges))
# edges.append((node, neighbour)) # return edges # #print(generate_edges(graph)) # #def find_isolated_nodes(graph): # ''' return a list of isolated nodes ''' # isolated = [] # for node in graph: # if not graph[node]: # isolated += node # return isolated # #print(find_isolated_nodes(graph)) graph = Graph(g) print('All path from vertex "A" to vertex "D":') paths = graph.find_all_paths("A", "D") print(paths) path_len = [] shortest_path = [] for path in paths: path_len.append(len(path)) for path in paths: if len(path) == min(path_len): shortest_path.append(path) print("The shortest paths are ", shortest_path) #print('The path from vertex "A" to vertex "F":') #path = graph.find_path("A", "F") #print(path)
# + # # matrix genaration # matrix1 = graph1.create_matrix(amount_nodes) # edges1 = graph1.generate_edges(amount_nodes, percent_edges) # matrix1 = graph1.add_edges(matrix1, edges1) # list_edges = graph1.make_list_edges_distances(matrix1) # netxgraph1 = graph1.build_networkx_graph(list_edges) # + # matrix1 # - # This initializes regular SOM grid matrix, it needs to be passes instead of matrix1 for it to work # Also one needs to experiment with sigma to achieve good results learning rate graph2 = Graph() matrix2 = graph2.standard_som_distance_matrix(length, width) list_edges = graph2.make_list_edges_distances(matrix2) netxgraph2 = graph2.build_networkx_graph(list_edges) map1 = MapClass(data, length, width, learning_rate, number_epochs, matrix2, sigma, data_lables, batch_size, shuffle, netxgraph2, special_shape_map) # + # ### Drawing configuration # drawtype="rbg" tries to draw colors on map - needs an input data with 3 dimensions or columns (colors) # drawtype="black-white" draws black-white - needs an input data with one dimension or column (gray_colors) # drawtype="networkx" graph drawing using the networkx library
def seat_model_generator(n1, n2, k_low, k_up): """ create a graph with the partition R of size n1 and partition H of size n2 :param n1: size of partition R :param n2: size of partition H :param k_low, k_up: range for length of resident preference lists """ def order_by_master_list(l, master_list): return sorted(l, key=master_list.index) possible_credits = [5, 10, 15, 20] # set up geometric distribution among above possible hospital credits probs = np.random.geometric(p=0.10, size=len(possible_credits)) probs = probs / np.sum(probs) def get_hosp_credits(): return list( np.random.choice(possible_credits, size=1, replace=False, p=probs))[0] def get_hosp_capacity_uniform(): # returns the average hospital capacity based on resident, hospital credits res_cap_sum = 0 hosp_cred_sum = 0 for r in g.residents: res_cap_sum += r.uq for h in g.hospitals: hosp_cred_sum += h.credits return int(np.ceil((1.5 * res_cap_sum) / hosp_cred_sum)) def get_hosp_capacity_non_uniform(cap): low = int(np.ceil(0.3 * cap)) high = int(np.ceil(1.7 * cap)) return random.randint(low, high) g = Graph() # default hospital capacity cap = 60 # create the sets R and H, r_1 ... r_n1, h_1 .. h_n2 R = list('r{}'.format(i) for i in range(1, n1 + 1)) H = list('h{}'.format(i) for i in range(1, n2 + 1)) for res in R: g.residents.append(Resident(res)) for hosp in H: g.hospitals.append(Hospital(hosp, 0, cap, get_hosp_credits())) # prepare a master list master_list = list(r for r in R) random.shuffle(master_list) # setup a probability distribution over the hospitals p = np.random.geometric(p=0.10, size=len(H)) # normalize the distribution p = p / np.sum(p) # p is a ndarray, so this operation is correct prob_dict = dict(zip(H, p)) master_list_h = sorted(H, key=lambda h: prob_dict[h], reverse=True) pref_H, pref_R = collections.defaultdict(list), {} for r in R: # sample hospitals according to the probability distribution and without replacement k = random.randint(k_low, k_up) pref_R[r] = list( np.random.choice(H, size=min(len(H), k), replace=False, p=p)) # add these residents to the preference list for the corresponding hospitals for h in pref_R[r]: pref_H[h].append(r) for r in R: pref_R[r] = order_by_master_list(pref_R[r], master_list_h) # random.shuffle(pref_R[r]) res = g.get_resident(r) for hosp in pref_R[r]: res.pref.append(g.get_hospital(hosp)) for h in H: pref_H[h] = order_by_master_list(pref_H[h], master_list) # random.shuffle(pref_H[h]) hosp = g.get_hospital(h) for res in pref_H[h]: hosp.pref.append(g.get_resident(res)) g.init_resident_capacities() # get average capacity for hospitals cap = get_hosp_capacity_uniform() for h in g.hospitals: h.uq = get_hosp_capacity_non_uniform(cap) # initialize class constraints for residents g.init_all_resident_class() # initialize master class constraints applicable to all residents g.init_master_classes_disjoint() return g
for i in G.adj_of_node[out_element]: indegree_list[i] -= 1 if indegree_list[i] == 0: no_incoming_set.add(i) if all((G.nodes_visited)): return toporder_list else: return 'NOT A VALID DAG' #print(str(all_set)) #print(str(edge_to_set)) #print(str(no_incoming_set)) #print(str(indegree_list)) #print(toporder_list) DAG1 = Graph(8) DAG1.build_directed_edge(1, 4) DAG1.build_directed_edge(1, 6) DAG1.build_directed_edge(2, 7) DAG1.build_directed_edge(3, 4) DAG1.build_directed_edge(3, 7) DAG1.build_directed_edge(4, 5) DAG1.build_directed_edge(7, 5) DAG1.build_directed_edge(7, 6) #print(topsort_dfs(DAG1)) print(topsort_kahn(DAG1)) DAG2 = Graph(8) DAG2.build_directed_edge(0, 6) DAG2.build_directed_edge(1, 2) DAG2.build_directed_edge(1, 4)
##una_cmap = [colormap_builder(1,unacceptable[0],6),colormap_builder(1,unacceptable[1],7)] ## ##build_average_graph(7, 1) ##build_average_graph(31, 1) ##build_average_graph(93, 1) ##build_average_graph(186, 1) ##build_bearing_graph(7, 1) #build_fft_graph(filenames,48,1/500) #print(cbar) frame = Graph_Frame(r'/usr/local/RVMD/GUI/Ch3_Graphs/') #graph_X = Graph(ID, *kwargs) graph_1 = Graph('Ch3_AVG', has_cbar=True, has_gradient=True) graph_2 = Graph('Ch3_AVG', has_cbar=True, has_gradient=True) graph_3 = Graph('Ch3_AVG', has_cbar=True, has_gradient=True) graph_4 = Graph('Ch3_AVG', has_cbar=True, has_gradient=True) graph_5 = Graph('Ch3_LOOSE', fill_color='lightsteelblue') graph_6 = Graph('Ch3_LOOSE', fill_color='lightsteelblue') graph_7 = Graph('Ch3_LOOSE', fill_color='lightsteelblue') graph_8 = Graph('Ch3_LOOSE', fill_color='lightsteelblue') graph_9 = Graph('Ch3_MISA', fill_color='honeydew') graph_10 = Graph('Ch3_MISA', fill_color='honeydew') graph_11 = Graph('Ch3_MISA', fill_color='honeydew') graph_12 = Graph('Ch3_MISA', fill_color='honeydew') graph_13 = Graph('Ch3_BEAR', fill_color='limegreen')
gray_colors_lables = [[0.1], ["black"], ["white"], [0.125], [0.529], [0.9], [0.33], [0.4], [0.67], [.33], [.5]] # + # Graph setup # - # for now amount_verticies has to be a multiplication of length and width amount_nodes = 100 percent_edges = 0.2 # + # using graph class to generate matrix graph1 = Graph() # + # matrix genaration matrix1 = graph1.create_matrix(amount_nodes) edges1 = graph1.generate_edges(amount_nodes, percent_edges) matrix1 = graph1.add_edges(matrix1, edges1) list_edges = graph1.make_list_edges_distances(matrix1) netxgraph1 = graph1.build_networkx_graph(list_edges) # - # + # matrix1 # +
def mahadian_model(n1, n2, k, cap): """ create a graph with the partition R of size n1 and partition H of size n2 using the model as described in Marriage, Honesty, and Stability Immorlica, Nicole and Mahdian, Mohammad Sixteenth Annual ACM-SIAM Symposium on Discrete Algorithms :param n1: size of partition R :param n2: size of partition H :param k: length of preference list for the residents :param cap: capacity of the hospitals :return: bipartite graph with above properties """ def order_by_master_list(l, master_list): return sorted(l, key=master_list.index) g = Graph() # create the sets R and H, r_1 ... r_n1, h_1 .. h_n2 R = list('r{}'.format(i) for i in range(1, n1 + 1)) H = list('h{}'.format(i) for i in range(1, n2 + 1)) # prepare a master list master_list = list(r for r in R) random.shuffle(master_list) for res in R: g.residents.append(Resident(res)) for hosp in H: g.hospitals.append(Hospital(hosp, 0, cap)) # setup a probability distribution over the hospitals p = np.random.geometric(p=0.10, size=len(H)) # normalize the distribution p = p / np.sum(p) # p is a ndarray, so this operation is correct prob_dict = dict(zip(H, p)) master_list_h = sorted(H, key=lambda h: prob_dict[h], reverse=True) # print(prob_dict, master_list_h, sep='\n') pref_H, pref_R = collections.defaultdict(list), {} for r in R: # sample women according to the probability distribution and without replacement pref_R[r] = list( np.random.choice(H, size=min(len(H), k), replace=False, p=p)) # add these man to the preference list for the corresponding women r_ind = r[1:] for h in pref_R[r]: h_ind = h[1:] pref_H[h].append(r) g.edges.append(Edge(r_ind, h_ind)) for r in R: pref_R[r] = order_by_master_list(pref_R[r], master_list_h) res = g.get_resident(r) for hosp in pref_R[r]: res.pref.append(g.get_hospital(hosp)) for h in H: pref_H[h] = order_by_master_list(pref_H[h], master_list) #random.shuffle(pref_H[h]) hosp = g.get_hospital(h) for res in pref_H[h]: hosp.pref.append(g.get_resident(res)) return g
gray_colors_lables = [[0.1], ["black"], ["white"], [0.125], [0.529], [0.9], [0.33], [0.4], [0.67], [.33], [.5]] # + # Graph setup # - # for now amount_verticies has to be a multiplication of length and width amount_nodes = 400 percent_edges = 0.5 # + # using graph class to generate matrix graph1 = Graph() # + # matrix genaration matrix1 = graph1.create_matrix(amount_nodes) edges1 = graph1.generate_edges(amount_nodes, percent_edges) matrix1 = graph1.add_edges(matrix1, edges1) list_edges = graph1.make_list_edges_distances(matrix1) netxgraph1 = graph1.build_networkx_graph(list_edges) # + # matrix1 # - # This initializes regular SOM grid matrix, it needs to be passes instead of matrix1 for it to work
"""Exercise 2: Get all unique nodes using a Graph class (2 way Digraph Class) The below code is set to test our understanding of what is a unique node, knowing that the Graph class sets to Edge classes in a two way fashion (bi-directional). Run the following code by running the file with `python exercise_2_graphs.py` """ from graph_class import Node, Graph, Edge nodes = [] nodes.append(Node("ABC")) # nodes[0] nodes.append(Node("ACB")) # nodes[1] nodes.append(Node("BAC")) # nodes[2] nodes.append(Node("BCA")) # nodes[3] nodes.append(Node("CAB")) # nodes[4] nodes.append(Node("CBA")) # nodes[5] g = Graph() for n in nodes: g.addNode(n) g.addEdge(Edge(g.getNode('ABC'), g.getNode('ACB'))) g.addEdge(Edge(g.getNode('ABC'), g.getNode('BAC'))) g.addEdge(Edge(g.getNode('ACB'), g.getNode('CAB'))) g.addEdge(Edge(g.getNode('BAC'), g.getNode('BCA'))) g.addEdge(Edge(g.getNode('BCA'), g.getNode('CBA'))) g.addEdge(Edge(g.getNode('CAB'), g.getNode('CBA'))) if __name__ == "__main__": print(g)
## #CREATE GRAPH FRAME OBJECTS THAT WILL STORE THE GRAPH OBJECTS ## frame_0 = Graph_Frame(r'/usr/local/RVMD/GUI/Ch0_Graphs/') frame_1 = Graph_Frame(r'/usr/local/RVMD/GUI/Ch1_Graphs/') frame_2 = Graph_Frame(r'/usr/local/RVMD/GUI/Ch2_Graphs/') frame_3 = Graph_Frame(r'/usr/local/RVMD/GUI/Ch3_Graphs/') #graph_X = Graph(ID, *kwargs) ## #CREATE GRAPH OBJECTS FOR FRAME_0 ## graph_1_f0 = Graph('Ch0_AVG', has_cbar=True, has_gradient=True) graph_2_f0 = Graph('Ch0_AVG', has_cbar=True, has_gradient=True) graph_3_f0 = Graph('Ch0_AVG', has_cbar=True, has_gradient=True) graph_4_f0 = Graph('Ch0_AVG', has_cbar=True, has_gradient=True) graph_5_f0 = Graph('Ch0_LOOSE', fill_color='lightsteelblue') graph_6_f0 = Graph('Ch0_LOOSE', fill_color='lightsteelblue') graph_7_f0 = Graph('Ch0_LOOSE', fill_color='lightsteelblue') graph_8_f0 = Graph('Ch0_LOOSE', fill_color='lightsteelblue') graph_9_f0 = Graph('Ch0_MISA', fill_color='lightsteelblue') graph_10_f0 = Graph('Ch0_MISA', fill_color='lightsteelblue') graph_11_f0 = Graph('Ch0_MISA', fill_color='lightsteelblue') graph_12_f0 = Graph('Ch0_MISA', fill_color='lightsteelblue') graph_13_f0 = Graph('Ch0_BEAR', fill_color='lightsteelblue')
exit("Program closed!") def loop(tkroot): """ Main loop of program """ global element_indexes element_indexes = draw_graph(graph, graph_canvas, element_indexes) tkroot.mainloop() if __name__ == "__main__": focused_object_index = None # For deleting elements and moving vertices dragged_object_index = None # For creating edges element_indexes = dict() # Dictionary of IDs of elements on canvas and object instances of graph components graph = Graph() # Main graph instance for visualization # Example of adding components to graph _test_dict = { "A": ["B"], "B": ["D"], "C": [], "D": ["A", "C"] } graph.add_from_neighbors_list(_test_dict) root = setup() loop(root)
[.33, .33, .33], [.5, .5, .5], [.66, .66, .66]] color_names = \ ['black', 'blue', 'darkblue', 'skyblue', 'greyblue', 'lilac', 'green', 'red', 'cyan', 'violet', 'yellow', 'white', 'darkgrey', 'mediumgrey', 'lightgrey'] # + # Graph setup # - amount_vertecies = 100 percent_edges = 0.5 graph1 = Graph() matrix1 = graph1.create_matrix(amount_vertecies) edges1 = graph1.generate_edges(amount_vertecies, percent_edges) matrix1 = graph1.add_edges(matrix1, edges1) # + # Network configuration data = rgb_colors data_lables = color_names batch_size = 2 length = 10
from graph_class import Vertex from graph_class import Graph g = Graph() for i in range(6): g.addVertex(i) g.vertList g.addEdge(0, 1, 5) g.addEdge(0, 5, 2) g.addEdge(1, 2, 4) g.addEdge(2, 3, 9) g.addEdge(3, 4, 7) g.addEdge(3, 5, 3) g.addEdge(4, 0, 1) g.addEdge(5, 4, 8) g.addEdge(5, 2, 1) for v in g: for w in v.getConnections(): print("( %s , %s )" % (v.getId(), w.getId()))