def create_graph(G: Graph) -> None: print('\n[1] Read points from file') print('[2] Generate random points') if G.repr_type != RepresentationType.EMPTY: G.repr_type = RepresentationType.EMPTY print('\nOld graph has been deleted') points = [] option = input("\nChoose option\n") if option == '1': print("\nOk. Now put the file name.") filename = input('Filename: ') points = np.loadtxt(os.path.dirname(__file__) + '/' + filename, usecols=(0, 1)) G.load_data(get_graph_from_points(points), RepresentationType.ADJACENCY_MATRIX) print('\nGraph created!\n') if option == '2': print('\nPut number of points') num = int(input('Number: ')) for _ in range(num): points.append((2000 * random() - 1000, 2000 * random() - 1000)) G.load_data(get_graph_from_points(points), RepresentationType.ADJACENCY_MATRIX) print('\nGraph created!\n') return points
def display_submenu(G: Graph) -> None: """ Submenu of main menu. Let user to go to convert handler or plot graph or print current graph or go back to main menu. """ operations_choice = '' while operations_choice != 'q': print(50 * '-') print("[1] Convert") print("[2] Plot") print("[3] Print current graph") print("[b] Go back to menu") operations_choice = input("Pick the option:\n") if operations_choice == 'b': G.clear_grah() return if operations_choice == '1': handle_convert(G) elif operations_choice == '2': GraphPlotter.plot_graph(G) elif operations_choice == '3': print_graph(G)
def kosaraju(G: Graph) -> list: """ Finds strongly connected components in directed graphs using Kosaraju algorithm. """ G.to_adjacency_list() visited = [False for _ in range(len(G.repr))] stack = [] for i in range(len(G.repr)): if visited[i] == False: dfs(G.repr, i, visited, stack) T = transpose(G) stack.reverse() visited = [False for _ in range(len(G.repr))] groups = [0 for _ in range(len(G.repr))] group = [] index = 0 for i in stack: if visited[i] == False: dfs(T.repr, i, visited, group) for x in group: groups[x] = index # print_group(group, index) group = [] index += 1 return groups
def hamilton(G: Graph, initial_vertex: int = 0) -> str: G.to_adjacency_matrix() path = [-1] * (len(G.repr) + 1) path[0] = path[-1] = initial_vertex return '[' + ' - '.join([str(x + 1) for x in path]) + ']' if hamilton_inner( G.repr, path, 1) else str([])
def randomTree(G): # assumption: nodes labelled 0 to n-1 n = len(G) nodes = np.arange(n) visited = np.zeros(n, dtype=np.bool) hitTime = np.zeros(n, dtype=np.int) x = [np.random.choice(nodes)] visited[x[0]] = True hitTime[x[0]] = 0 # random walk i = 0 while (visited.sum() < n): nbh = G.GetNeighbours(x[i]) r = np.random.choice(nbh) if (not visited[r]): hitTime[r] = i + 1 visited[r] = True # end if x = x + [r] i = i + 1 # end random walk T = Graph(n) for i in range(n): if (i == x[0]): continue p, q = hitTime[i] - 1, hitTime[i] T.AddEdge(x[p], x[q]) return T
def __init__(self, n, G=None): self._n = n if G: self._G = G else: g = Graph(n) g.SetComplete() self._G = g
def handle_read_from_file(G: Graph, repr_type: int, file_name: str = ""): """ Reading graph from file. File must be inside the folder where Lab01_console.py is. """ if repr_type == 1 or repr_type == 2 or repr_type == 3: G.create_representation(os.path.dirname( __file__) + "/" + file_name, RepresentationType(repr_type)) else: print("\nInvalid file type have been chosen.")
def generate_with_probability_menu(G: Graph) -> None: num_of_nodes = input("Put number of nodes:\n") probability = input("Put probability from range: (0;1):\n") data = get_graph_with_probability(int(num_of_nodes), float(probability)) G.load_data(data=data, representation_type=RepresentationType.ADJACENCY_MATRIX) display_submenu(G)
def generate_with_vertices_and_edges_menu(G: Graph) -> None: num_of_vertices = input("Put number of vertices:\n") num_of_edges = input("Put number of edges:\n") data = get_graph_by_vertices_and_edges(int(num_of_vertices), int(num_of_edges)) G.load_data(data=data, representation_type=RepresentationType.INCIDENCE_MATRIX) display_submenu(G)
def present_k_regular_graphs() -> None: """ Finds k-regular graph for given k and vertices number. """ vertices = int(input('\nNumber of vertices: ')) k = int(input('Put k-parameter: ')) randomizations = int(input("Put number of randomizations: ")) G = Graph() G.create_k_regular_with_n_vertices(k, vertices) randomize(G, randomizations) GraphPlotter.plot_graph(G)
def construct_truck_graph(env, params): truck_dist_matrix = env["truck_dist_matrix"] truck_nodes = env["truck_nodes"] g_truck = Graph() for i in range(truck_dist_matrix.shape[0]): edge_list = { tuple(truck_nodes[ni]): np.round(dist / params["truck_settings"]['vel'], 2) for ni, dist in enumerate(truck_dist_matrix[i]) if dist != np.inf and ni != i } g_truck.add_vertex(tuple(truck_nodes[i]), edge_list) return g_truck
def transpose(G: Graph) -> Graph: """ Creates transpose graph of given directed graph. """ T = Graph() adjlist = [[] for _ in range(len(G.repr))] for i in range(len(G.repr)): for x in G.repr[i]: adjlist[x - 1].append(i + 1) T.load_data(adjlist, RepresentationType.ADJACENCY_LIST) return T
def test_constrained_cov_0(): n = 10 for _ in range(10): g = Graph(n) g.SetRandom() a = g.GetAdjM()[np.triu_indices(n, 1)] T = np.random.random((n,n)) C = T.transpose() @ T C_star = constrained_cov(g.GetDOL(), C, np.eye(n)) K = np.linalg.inv(C_star) b = (abs(K[np.triu_indices(n, 1)]) > 1e-10).astype(int) assert((a == b).all())
def _graph_from_binarr(self, n, a): triu_l = np.vstack(np.triu_indices(n, 1)).transpose() dol = {i: [] for i in range(n)} for i, j in triu_l[np.where(a)[0]]: dol[i].append(j) dol[j].append(i) return Graph(n, dol)
def test_generate_data(): np.random.seed(123) for _ in range(10): n = 10 m = 10000 g = Graph(n) g.SetRandom() X = generate_data(n, m, g, threshold=1e-6) a = g.GetAdjM()[np.triu_indices(n, 1)] b = (np.abs(np.linalg.inv((X.transpose() @ X) / (m-1))[np.triu_indices(n, 1)]) > 0.1).astype(int) threshold = n assert(np.sum(a != b) < threshold) # Larger matrices require very large number of samples for it to converge to the correct graph
def present_eulerian_graphs() -> None: """ Generates Eulerian Graph sequence and finds Eulerian Cycle. """ randomizations = 100 v = int(input('\nNumber of vertices: ')) G = Graph() if generate_euler_graph_sequence(G, v): print('Graphical sequence of graph: ' + str(G)) G.to_adjacency_matrix() randomize(G, randomizations) print('Euler Cycle: ' + euler_cycle(G)) GraphPlotter.plot_graph(G) else: print("Error while generating euler graph sequence")
def present_hamiltonian_graphs() -> None: """ Chceck if graph generated by 'get_graph_with_probability' with parameters given by user is Hamiltonian. """ vertices = int(input('\nNumber of vertices: ')) probability = float(input("Put probability (0;1):\n")) G = Graph() G.load_data(get_graph_with_probability(vertices, probability), RepresentationType.ADJACENCY_MATRIX) cycle = hamilton(G) if cycle == '[]': print("Graph is not hamiltonian") else: print("Graph is hamiltonian") print(cycle) GraphPlotter.plot_graph(G)
def present_graphical_sequence() -> list: """ Presents graphical sequence inserting and checking [1]. Returns sequence as a list if sequence is graphical. Otherwise - [] - empty list. """ G = Graph() print('\nInsert sequence of integers') sequence = [int(x) for x in input('Your sequence: ').split()] if G.load_data(sequence, RepresentationType.GRAPH_SEQUENCE): print('Your sequence is graphical! Here is one of possible solutions\n') GraphPlotter.plot_graph(G) else: print('Sequence is not graphical\n') return [] return sequence
def get_all_graphs(n): G_list = [] m = int(n * (n-1) / 2) triu_idx = np.triu_indices(n,1) for i in range(np.power(2, m)): b = format(i,'0' + str(m) + 'b') G_list.append(Graph(n)) for j in range(len(b)): if int(b[j]): G_list[-1].AddEdge(triu_idx[0][j], triu_idx[1][j]) return G_list
def compare_median_graphs(configs, threshold=.5, how=None): config_l = get_config_l(configs) varying_k, varying_v = _get_varying(configs) paths = [config_to_path(c) for c in config_l] cols = len(paths) fig, axs = plt.subplots(1, cols + 1, figsize=(10 * (cols + 1), 10)) n, n_obs, true_g = config_l[0]['n'], config_l[0]['n_obs'], config_l[0]['true_graph'] pos = Graph(n).GetCirclePos() with open(f"data/graph_{true_g}_{n}_{n_obs}.pkl", 'rb') as handle: g = pickle.load (handle) if how == 'circle': g.Draw(ax=axs[0], pos=pos) else: g.Draw(ax=axs[0]) axs[0].set_title('true_graph', fontsize=20) for i in range(cols): with open(config_to_path(config_l[i]), 'rb') as handle: sampler = pickle.load(handle) adjm = str_list_to_median_graph(n, sampler.res['SAMPLES'], threshold=threshold) g_ = Graph(n) g_.SetFromAdjM(adjm) if how == 'circle': g_.Draw(ax = axs[i + 1], pos=pos) else: g_.Draw(ax = axs[i + 1]) axs[i + 1].set_title(f"{varying_k}: {varying_v[i]}", fontsize=20) plt.show()
def laplace_approx(G, delta, D, as_log_prob=True, diag=False): """ Log of Laplace approximation of G-Wishart normalization constant Log of the Laplace approximation of the normalization constant of the G-Wishart distribution outlined by Lenkoski and Dobra (2011, doi:10.1198/jcgs.2010.08181) """ from utils.Graph import Graph G = Graph(len(G), G) G = igraph.Graph.Adjacency(G.GetAdjM().tolist(), mode=1) df = delta rate = D if rate is None: # If the rate matrix is the identity matrix (I_p), then the mode of the # G-Wishart distribution is (df - 2) * I_p such that the Laplace approximation simplifies. p = G.vcount() n_e = G.ecount() return 0.5 * ( (p*(df - 1.0) + n_e)*np.log(df - 2.0) - p*(df - 2.0) \ + p*np.log(4.0 * np.pi) + n_e*np.log(2.0 * np.pi) ) return log_gwish_norm_laplace_cpp(G.__graph_as_capsule(), df, rate, diag)
def present_graph_from_file(G: Graph) -> None: operations_choice = '' v = len(G.repr) while operations_choice != 'b': display_submenu() operations_choice = input("Pick the option:\n") try: if operations_choice == '1': cycle = hamilton(G) if cycle == '[]': print('Graph is not Hamiltonian') else: print('Graph is Hamiltonian') print(cycle) if operations_choice == '2': cycle = euler_cycle(G) if cycle == '[]': print('Graph is not Eulerian') else: print('Graph is Eulerian') print(euler_cycle(G)) if operations_choice == '3': G.to_adjacency_matrix() for k in range(1, v): if G.is_k_regular(k): print('Graph is ' + str(k) + '-regular') break if k == v - 1: print('Graph is not k-regular') if operations_choice == '4': G.to_adjacency_matrix() randomizations = int(input('Number of randomizations: ')) randomize(G, randomizations) if operations_choice == '5': G.to_adjacency_list() groups = get_components(G) print_sorted_components(G, groups) GraphPlotter.plot_graph(G, False, False, groups) if operations_choice == '6': GraphPlotter.plot_graph(G) except: print("Something went wrong. Try again!")
def main(): parser = argparse.ArgumentParser() parser.add_argument('instance', type=argparse.FileType('r'), help='filename for CARP instance') args = parser.parse_args() cd = CARPData() cd.read_file(args.instance) # print(cd) g = Graph(cd) print(g) g.floyd() print("---After Floyd---") print(g) [print(x) for x in g.get_distances(1)] Graph.draw(cd)
def johnson_algorithm(graph: DirectedGraph) -> list: if graph.repr_type != RepresentationType.ADJACENCY_MATRIX: graph.to_adjacency_matrix() g = graph.repr # add vertex to graph and add edges of value 0 from this vertex to the rest g.append([0]) for i in range(len(g) - 2): g[len(g) - 1].append(0) for i in range(len(g)): g[i].append(None) graph.to_adjacency_list() edges = bellman_ford(graph, len(g)) edges.pop(len(g)) graph.to_adjacency_matrix() new_g = [[0 for x in range(len(g) - 1)] for y in range(len(g) - 1)] for i in range(len(new_g)): for j in range(len(new_g[i])): if g[i][j] is not None: new_g[i][j] = (g[i][j] + edges[i + 1] - edges[j + 1]) graph.repr.pop() for i in range(len(graph.repr)): graph.repr[i].pop() graph_for_dijkstra = Graph() data = get_graph_with_probability(len(graph.repr), 0.5) graph_for_dijkstra.load_data( data=data, representation_type=RepresentationType.ADJACENCY_MATRIX_WITH_WEIGHTS) for i in range(len(graph.repr)): for j in range(len(graph.repr[i])): graph_for_dijkstra.repr[i][j] = new_g[i][j] dist_matrix = [] for s in range(len(graph_for_dijkstra.repr)): print(f"For node [{s+1}]:") from_point = find_shortest_path( G=graph_for_dijkstra.get_weighted_adjacency_list(), start=s + 1, verbose=True) dist_matrix.append([]) for node in from_point: dist_matrix[s].append(from_point[node]) print() return dist_matrix
def generate_euler_graph_sequence(G: Graph, vertices: int) -> bool: """ Generates graphical sequence of Eulerian Graph for given number of vertices and loads it to graph given as a parameter. Returns True if generating was successful in one of num_samples iterations. """ num_samples = 100 iteration = 0 while iteration < num_samples: graphical_sequence = [(randint(2, vertices - 1) // 2) * 2 for _ in range(vertices)] if G.load_data(graphical_sequence, RepresentationType.GRAPH_SEQUENCE): return True iteration += 1 return False
def present_graph_randomization() -> None: """ Presents graph randomization for graph using graphical sequence and randomizations parameter. """ print('\nLet\'s start with Your own graphical sequence.\n') sequence = present_graphical_sequence() if sequence != []: randomizations = int(input('Number of randomizations: ')) G = Graph() G.load_data(sequence, RepresentationType.GRAPH_SEQUENCE) G.to_adjacency_matrix() randomize(G, randomizations) GraphPlotter.plot_graph(G)
def present_components_finding() -> None: """ Presents finding graph components for graph generated by 'get_graph_with_probability' with parameters given by user. """ vertices = int(input('\nNumber of vertices: ')) probability = float(input("Put probability (0;1):\n")) G = Graph() G.load_data(get_graph_with_probability(vertices, probability), RepresentationType.ADJACENCY_MATRIX) G.to_adjacency_list() groups = get_components(G) print_sorted_components(G, groups) GraphPlotter.plot_graph(G, False, False, groups)
def load_graph_from_file_menu() -> None: """ Loading graph from file. """ G = Graph() print("\nWhat representation type is in the file?") print("[1] Adjancency matrix") print("[2] Adjacency list") print("[3] Incidence matrix\n") representation_type = input("Pick the type:\n") print("\nOk. Now put the file name.") file_name = input("File name:\n") print() if representation_type and file_name: handle_read_from_file(G, int(representation_type), file_name) if not G.repr: print("Reading file failure.") return present_graph_from_file(G)
def handle_convert(G: Graph) -> None: """ Graph representation type convert handler. """ convert_repr_type = '' print("\nPick representation type:") print("[1] Adjancency matrix") print("[2] Adjacency list") print("[3] Incidence matrix") convert_repr_type = input() if convert_repr_type == '1': G.to_adjacency_matrix() print_graph(G) elif convert_repr_type == '2': G.to_adjacency_list() print_graph(G) elif convert_repr_type == '3': G.to_incidence_matrix() print_graph(G) else: print("\nPut a valid option.")
import os, sys import numpy as np currentdir = os.path.dirname(os.path.realpath(__file__)) parentdir = os.path.dirname(currentdir) sys.path.append(parentdir) from utils.Graph import Graph, RepresentationType from utils.graph_plotter import GraphPlotter from utils.graph_generators import randomize if __name__ == "__main__": G = Graph() G.create_k_regular_with_n_vertices(k=2, vertices=7) randomize(G, 100) GraphPlotter.plot_graph(G)