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 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 _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 __init__(self, n, G=None): self._n = n if G: self._G = G else: g = Graph(n) g.SetComplete() self._G = g
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 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 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 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 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 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 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_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 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 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 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)
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 get_graph_with_probability, get_graph_by_vertices_and_edges if __name__ == "__main__": G = Graph() data = get_graph_with_probability(7, 0.5) G.load_data(data=data, representation_type=RepresentationType.ADJACENCY_MATRIX) print(G) GraphPlotter.plot_graph(G) G = Graph() data = get_graph_by_vertices_and_edges(5, 8) G.load_data(data=data, representation_type=RepresentationType.INCIDENCE_MATRIX) G.to_adjacency_matrix() print(G) GraphPlotter.plot_graph(G)
def Sample(self): p = np.random.permutation(self._n) T = Graph(self._n) for i in range(self._n - 1): T.AddEdge(p[i], p[i + 1]) return T
def run(self) -> None: self.console.print("[bold]Hello, user!") is_generated = False G = DirectedGraph() groups = None network = get_flow_network(4) main_choice = '' try: while main_choice != 'q': self.newline() self.print_options() self.newline() main_choice = input("What would you like to do? ") if main_choice == 'q': exit_program() elif main_choice == '1': try: n_layers = int(input("Number of layers: ")) network = get_flow_network(n=n_layers) self.console.print( "[bold green]Success:[/bold green] Graph generated." ) is_generated = True except: self.err("Something went wrong") # GraphPlotter.plot_graph(G, draw_wages=True, draw_arrows=True) elif main_choice == '3': if not is_generated: self.err("Network not created. Generate it first") continue plotter = FlowNetworkPlotter() plotter.load_network(network) network_copy = copy.deepcopy(network) print( network_copy.ford_fulkerson(network_copy.source_node, network_copy.target_node)) network.flow_matrix = network_copy.flow_matrix plotter = FlowNetworkPlotter() plotter.load_network(network) label = "flow capacity" plotter.plot(rand_offset_factor=0.6, edge_labels=label) elif main_choice == '4': if not is_generated: self.err( "Can't clear non existing network! Generate it first" ) continue network.clear_flow_network() is_generated = False elif main_choice == '2': try: self.console.print( "generating graph from inputs/network.txt") G = Graph() G.create_representation( os.path.dirname(__file__) + '/inputs/network.txt', RepresentationType.ADJACENCY_MATRIX) network = get_flow_network(n=2) network.repr = G.repr network.source_node = 0 network.target_node = 5 is_generated = True self.console.print( "[bold green]Success:[/bold green] Graph generated." ) except: self.err("Something went wrong") elif main_choice == 'p': plotter = FlowNetworkPlotter() plotter.load_network(network) plotter.plot(rand_offset_factor=0.6) else: self.err("Unrecognized option") self.newline() except: self.err("Critical error. Exiting..") self.newline()
def Sample(self): v = np.random.choice(np.arange(self._n)) return Graph(self._n, hub(self._n, v))
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)
def construct_drone_graph(env, params, one_package=True): drone_checkpoints, truck_nodes = env["drone_checkpoints"], env[ "truck_nodes"] g_drone = Graph() battery_time = params["drone_settings"]["full_battery_time"] drone_vel = params["drone_settings"]["vel"] rrt_list = [] if one_package: nodes = truck_nodes else: nodes = np.concatenate([truck_nodes, drone_checkpoints]) for pi, p in enumerate(drone_checkpoints): print(f'Calculating RRT: {pi+1}/{len(drone_checkpoints)}') dists = np.round(np.linalg.norm(nodes - p, axis=1), 2) times = dists / drone_vel reachable_nodes_idx = (0 < times) & (times < battery_time) reachable_nodes = nodes[reachable_nodes_idx] edge_list = {} for node in reachable_nodes: drone_path = plan_rrt_star(env["search_space"], env["obstacles"], tuple(node), tuple(p), show=False) if drone_path is None: continue # Add RRT path to list rrt_list.append(drone_path) dist = calc_path_length(drone_path) time_to_travel = np.round(dist / drone_vel, 2) if time_to_travel < battery_time: edge_list[tuple(node)] = time_to_travel if len(edge_list): g_drone.add_vertex(tuple(np.array(p, dtype='int')), edge_list) # drone_flight_range = params["env_struct"]["drone_flight_range"] # for pi, p in enumerate(drone_checkpoints): # print(f'Calculating RRT: {pi+1}/{len(drone_checkpoints)}') # if params["env_struct"]["rrt_flight_range"]: # edge_list = {} # dists = np.round(np.linalg.norm(truck_nodes - p, axis=1), 2) # reachable_truck_nodes_idx = dists < drone_flight_range # reachable_truck_nodes = truck_nodes[reachable_truck_nodes_idx] # for node in reachable_truck_nodes: # drone_path = plan_rrt_star(env["search_space"], env["obstacles"], # tuple(node), tuple(p), show=False) # if drone_path is None: # continue # dist = calc_path_length(drone_path) # if dist < drone_flight_range: # time_to_travel = dist / params["drone_vel"] # edge_list[tuple(node)] = time_to_travel # else: # dists = np.round(np.linalg.norm(truck_nodes - p, axis=1), 2) # reachable_truck_nodes_idx = dists < drone_flight_range # reachable_truck_nodes = truck_nodes[reachable_truck_nodes_idx] # reachable_truck_nodes_dists = dists[reachable_truck_nodes_idx] # edge_list = {tuple(n): np.round(reachable_truck_nodes_dists[ni] / params["drone_vel"], 2) for ni, n in enumerate(reachable_truck_nodes)} # # if len(edge_list): # g_drone.add_vertex(tuple(np.array(p, dtype='int')), edge_list) return g_drone, rrt_list