def shortest_paths(self, src_sid=None, dst_sid=None, ignore_notfound=False, exclude=[]): nv = GraphData() try: if src_sid is None and dst_sid is None: raise Exception('src_sid or dst_sid must be set') elif src_sid is None and dst_sid is not None: dst = self.__resolve_sid_to_id(dst_sid) if dst is None: raise Exception('SID not found!') res = shortest_path(self.graph, target=dst) for k in res: self.__result_path_add(nv, res[k], exclude=exclude) elif src_sid is not None and dst_sid is not None: dst = self.__resolve_sid_to_id(dst_sid) if dst is None: raise Exception('SID not found!') src = self.__resolve_sid_to_id(src_sid) if src is None: raise Exception('SID not found!') try: res = shortest_path(self.graph, src, dst) self.__result_path_add(nv, res, exclude=exclude) except nx.exception.NetworkXNoPath: pass elif src_sid is not None and dst_sid is None: src = self.__resolve_sid_to_id(src_sid) if src is None: raise Exception('SID not found!') try: res = shortest_path(self.graph, src) for k in res: self.__result_path_add(nv, res[k], exclude=exclude) except nx.exception.NetworkXNoPath: pass else: raise Exception('Not implemented!') return nv except nx.exception.NodeNotFound: if ignore_notfound is True: return nv raise
def calculate_moves(G): """ Calculate the moves neccessary to draw the provided graph. """ # Take a copy of the input graphs nodes, so we can remove nodes as we go without affecting pathfinding. rgiant = list(G.nodes) n = 0 start = (0, 0) last_node = start def distance(n): # Note: start is modified by the loop. return math.sqrt( (n[0]-start[0])**2 + (n[1]-start[1])**2 ) while rgiant: n += 1 dnode = min(rgiant, key=distance) rgiant.remove(dnode) path = shortest_path(G, start, dnode, weight='weight') last_node = start # Traverse the path, yield all the steps required to get there. for node in path[1:]: # Yield this step to draw it (x & y can be > 1), may require multiple steps. yield (node[0] - last_node[0], node[1] - last_node[1]) # Keep reference of where we've been for later, increase weight to discourage re-drawing. G.edges[(node, last_node)]['weight'] = G.edges[(node, last_node)].get('weight', 1) * 2 last_node = node # Chop away to avoid redundant paths. rgiant = set(rgiant) - set(path) # Update to our new position start = dnode # Plot and yield final path to home (0,0). path = shortest_path(G, last_node, (0, 0), weight='weight') for node in path[1:]: # Yield this step to draw it (x & y can be > 1), may require multiple steps. yield (node[0] - last_node[0], node[1] - last_node[1]) last_node = node
def run_car_in_subgraph(data, graph, start, subgraph): # print data.max_time closest_node, cost = compute_closest_in_subgraph(graph, subgraph, start) # print cost path = shortest_path(graph, start, closest_node) nodes = subgraph.nodes(data=True) intersections = map( lambda node: st.Intersection(node[1]["lat"], node[1]["long"]), nodes) index_map = {} inverse_index_map = {} for i in xrange(len(nodes)): index_map[nodes[i][0]] = i inverse_index_map[i] = nodes[i][0] roads = map( lambda edge: st.Road( index_map[edge[0]], index_map[edge[1]], edge[2]["cost"], edge[2]["distance"], edge[2]["one_way"]), subgraph.edges(data=True)) new_data = st.Data( intersections, roads, data.max_time - cost, index_map[closest_node], 1) path2 = greedy_run(new_data)[0] path2.pop(0) for i in xrange(len(path2)): path2[i] = inverse_index_map[path2[i]] # print "%d -> %d" % (path[-1], path2[0]) return path + path2
def partTwo(inp): orbits = nx.Graph() for orbit in inp.split('\n'): center, orb = orbit.strip().split(')') orbits.add_edge(center, orb) # -3, because you substract YOU and SAN, and you need to count interval, not nodes. return len(shortest_path(orbits, 'YOU', 'SAN')) - 3
def test_graph_shortest_path_method(self): """ Test Dijkstra shortest path method """ from networkx.algorithms.shortest_paths.generic import shortest_path from networkx.algorithms.traversal.depth_first_search import dfs_preorder_nodes print(shortest_path(self.nx, 8, 10)) print(list(dfs_preorder_nodes(self.nx, 8))) # In a mixed directed graph where 7 connects to 8 but not 8 to 7 self.assertEqual(dijkstra_shortest_path(self.graph, 8, 10), [8, 3, 4, 5, 6, 9, 10]) self.assertEqual(list(dfs_paths(self.graph, 8, 10)), [[8, 3, 4, 5, 6, 9, 10]]) self.assertEqual(list(dfs_paths(self.graph, 8, 10, method='bfs')), [[8, 3, 4, 5, 6, 9, 10]]) # Fully connect 7 and 8 self.graph.add_edge(8, 7, directed=True) self.assertEqual(dijkstra_shortest_path(self.graph, 8, 10), [8, 7, 6, 9, 10]) self.assertEqual(list(dfs_paths(self.graph, 8, 10)), [[8, 7, 6, 9, 10], [8, 3, 4, 5, 6, 9, 10]]) self.assertEqual(list(dfs_paths(self.graph, 8, 10, method='bfs')), [[8, 7, 6, 9, 10], [8, 3, 4, 5, 6, 9, 10]])
def get_path(self, u, v): nodes = shortest_path(self.g, u, v) edges = [] if len(nodes) > 1: for i in range(len(nodes) - 1): edges.append(self.get_edge_attr(nodes[i], nodes[i + 1])) return nodes, edges
def dynamic_routing(links, flow_paths, graph): # must check_flow() prior to running this function # a new flow will automatically use new_path since old_path will be = [] # for each existing flow check if there is a new better path if so change to that for src_mac in list(flow_paths.keys()): for dst_mac in list(flow_paths[src_mac].keys()): last_changed_sum = flow_paths[src_mac][dst_mac]['last_changed'] print('{} : {} - last_changed: {}'.format(src_mac, dst_mac, last_changed_sum)) if last_changed_sum > 20: delete_all_flows(src_mac, dst_mac, flow_paths) del flow_paths[src_mac][ dst_mac] # must remove full connection from list continue new_path = shortest_path(graph, src_mac, dst_mac, weight='weight') old_path = flow_paths[src_mac][dst_mac]['path'] if new_path != old_path: flow_paths[src_mac][dst_mac]['path'] = new_path delete_all_flows(src_mac, dst_mac, flow_paths) add_all_flows(src_mac, dst_mac, new_path.copy(), links) print('new path for {} to {}: \n\t{} \n\t{}'.format(\ src_mac, dst_mac, new_path, old_path))
def shortest_path(self, start, stop, n_interpolate): """ creates a path by linearly interpolating additional steps within the optimal path parameters ---------- start: tuple params corresponding to the starting distribution stop: tuple params corresponding to the final distribution n_interpolate: int number of points to interpolate at each step. steps=1 returns the best path returns ------- list of tuples params for the optimal path using the uniform step rule. """ self._check_graph_generated() short_path = shortest_path(self.graph, start, stop, weight='cost') path = [short_path[0]] for start, stop in zip(short_path[:-1], short_path[1:]): params = [] for q in range(self.dimension): params.append( np.linspace(start[q], stop[q], n_interpolate + 1)[1:]) params = unzip(params) # change the index to steps params = map(tuple, params) # change lists to tuples path += params # save the changes return np.array(path)
def test_lca_small(self): '''Test lowest common ancestor computation in a small pedigree.''' p = io_pedigree.read(itu.SMALL_FILE) # Direct siblings self.__compute_and_check_lca(p, 6, 7, [4, 5], 2) # Far siblings u = 6 v = 8 w = self.__compute_and_check_lca(p, u, v, [3], 3) assert_equal(shortest_path(p.graph, w, u), [3, 5, 6], 'Wrong shorted path from ancestor to node u') assert_equal(shortest_path(p.graph, w, v), [3, 8], 'Wrong shorted path from ancestor to node v') # No common ancestor exists self.__compute_and_check_lca(p, 1, 2, [None], Infinity)
def get_spot_prices_in_eth_from_dune(swaps, pool_ids, token_info, block_interval = 1): from_block = min(s['block_number'] for s in swaps) to_block = max(s['block_number'] for s in swaps) reserves = get_reserves_from_dune(from_block - 1, to_block, pool_ids, token_info) reserves = compute_reserves_for_blocks(range(from_block, to_block + 1), reserves) token_graph = Graph(list(reserves.keys())) for t1, t2 in reserves.keys(): block = list(reserves[t1, t2].keys())[0] token_graph[t1][t2]['weight'] = -reserves[t1, t2][block][0] * reserves[t1, t2][block][1] WETH = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2" tokens = {t1 for (t1, _) in reserves.keys()} | {t2 for (_, t2) in reserves.keys()} tokens = {t for t in tokens if has_path(token_graph, t, WETH)} exchange_paths = {t: shortest_path(token_graph, t, WETH) for t in tokens} prices = {} for block in tqdm(range(from_block, to_block + 1, block_interval), "Setting spot prices for every block"): block_prices = {} for t in tokens: xrate = compute_exchange_rate(exchange_paths[t], reserves, block) if xrate is None: continue block_prices[t] = xrate prices[block] = block_prices return prices
def get_shortest_route(self, point_a, point_b): """ Get the shortest route between two points. :returns: list of one hop routes for the shortest route """ return shortest_path(self.G, point_a, point_b, "distance")
def compute_rotation(self, source, destination): """ Returns the rotation to another node. Returns the identity rotation if the other node is this node. Parameters ---------- source : int Integer id for the source node to rotate from destination : int Integer id for the node to rotate into from the source node Returns ------- rotation : Object Returns either a TimeDependentRotation object or ConstantRotation object depending on the number of rotations being multiplied together """ if source == destination: return ConstantRotation(np.array([0, 0, 0, 1]), source, destination) path = shortest_path(self, source, destination) rotations = [ self.edges[path[i], path[i + 1]]['rotation'] for i in range(len(path) - 1) ] rotation = rotations[0] for next_rotation in rotations[1:]: rotation = next_rotation * rotation return rotation
def get_multiplier(self, unit1: str, unit2: str, unit_type: str = None): """retrieves the multiplier to convert unit1 to unit2""" # Get used type name used_unit_type: str if unit_type is not None: if unit_type in self.convertor_dictionary: used_unit_type = unit_type self.validate_units([unit1, unit2], unit_type) else: raise TypeNotFound(unit_type) else: units = [unit1, unit2] possible_types = self.get_possible_types(units) used_unit_type = self.validate_possible_type(units, possible_types) # Get the unit graph unit_graph = self.convertor_dictionary[used_unit_type] # If it is fully constructed, it is a simple lookup if unit_graph.is_constructed: multiplier = unit_graph[unit1][unit2]["weight"] return ((unit1, unit2), used_unit_type, multiplier) # If it is not fully constructed, we calculate it manually path: List[str] = shortest_path(unit_graph, unit1, unit2, weight="weight") multiplier = 1 for i in range(len(path) - 1): multiplier = multiplier * unit_graph[path[i]][path[i + 1]]["weight"] return ((unit1, unit2), used_unit_type, multiplier)
def last_time_dependent_frame_between(self, source, destination): """ Find the last time dependent frame between the source frame and the destination frame. Parameters ---------- source : int Integer id of the source node destination : int Integer of the destination node Returns ------- : tuple, None Returns the source node id, destination node id, and edge dictionary which contains the rotation from source to destination. """ path = shortest_path(self, source, destination) # Reverse the path to search bottom up to find the last time dependent # frame between the source and destination path.reverse() for i in range(len(path) - 1): edge = self.edges[path[i + 1], path[i]] if isinstance(edge['rotation'], TimeDependentRotation): return path[i + 1], path[i], edge return None
def findroutes(self, startNode, endNode): sp = shortest_path(self.graph, startNode, endNode) i = 1 sum = 0 while i < len(sp): edge_by_nodes = (sp[i-1], sp[i]) edges = self.graph[edge_by_nodes[0]][edge_by_nodes[1]] # import pdb;pdb.set_trace() if len(edges.keys()) > 1: if edges[0]['edge'].getLength() > edges[1]['edge'].getLength(): sum = sum + edges[1]['edge'].getLength() else: sum = sum + edges[0]['edge'].getLength() else: sum = sum + edges[0]['edge'].getLength() i = i + 1 self.MAXIMUM_LENGTH = sum * DISTANCE_FACTOR startLabel = Label(startNode, parentLabel=None, parentEdge=None, endNode = endNode, routeFinder = self, length=0, star=startNode.getOutEdges()) self.expand(startLabel, self.MAXIMUM_LENGTH, MINIMUM_LENGTH, endNode) return self.results
def _precompute_single_level_paths(parsed): """Transform the parsed input into another graph, corresponding to a single recursion level. Nodes are the portal (with their inner-outer suffix) Edges are weighted by the length of the shortest path + 1 step for going through the portal. We keep the +1 on the length, as it simplifies the computation of the whole length of path in part 2. Of course, most (and probably all) inputs will generate non-connected graphs.""" # First, construct the graph of the maze itself. Dots = nx.Graph() portal_positions = dict() for pos, cell in parsed.items(): if cell == '.': for neigh in [left(pos), right(pos), up(pos), down(pos)]: if neigh in parsed: Dots.add_edge(pos, neigh) else: portal_positions[pos] = cell # Now, construct the output graph Portals = nx.Graph() for p1, p1_name in portal_positions.items(): for p2, p2_name in portal_positions.items(): if p1 != p2: try: path_length = len(shortest_path(Dots, p1, p2)) Portals.add_edge(p1_name, p2_name, weight=path_length) except nx.NetworkXNoPath: pass return Portals
def get_solution(self): solution_nodes = shortest_path(self.graph, self.start, '') solution = [] for i in range(len(solution_nodes)-1): source, target = solution_nodes[i:i+2] solution.append(self.graph[source][target]['move']) return solution
def pre_process_car_stat_add_route(car_stat, dest, DG, by_what='capacity'): for des in dest: path = alg.shortest_path(DG, source=des[0], target=des[1], weight=by_what, method='dijkstra') idx = car_stat.index()
def pre_process_car_stat_v2(cars, DG, by_what='capacity'): stat = [] dest = [] for car in cars: car_dest = (car['from'], car['to']) if car_dest in dest: idx = dest.index((car['from'], car['to'])) # 位置 car_stat = stat[idx] car_stat['count'] += 1 if car_stat['maxSpeed'] < car['speed']: car_stat['maxSpeed'] = car['speed'] if car_stat['minSpeed'] > car['speed']: car_stat['minSpeed'] = car['speed'] if car_stat['maxPlanTime'] < car['planTime']: car_stat['maxPlanTime'] = car['planTime'] if car['speed'] >= 5: car_stat['v>=5'] += 1 else: car_stat['v<5'] += 1 else: dest.append(car_dest) car_stat = {} car_stat['from'] = car_dest[0] car_stat['to'] = car_dest[1] car_stat['count'] = 1 car_stat['maxSpeed'] = car['speed'] car_stat['minSpeed'] = car['speed'] car_stat['maxPlanTime'] = car['planTime'] car_stat['v>=5'] = 0 car_stat['v<5'] = 0 if car['speed'] >= 5: car_stat['v>=5'] = 1 else: car_stat['v<5'] = 1 path = alg.shortest_path(DG, source=car_dest[0], target=car_dest[1], weight=by_what, method='dijkstra') car_stat['crossPath'] = path edge_route = [] length = 0 min_flow = 10000 # 给个最大值 for u, v in zip(path[:-1], path[1:]): edge = DG.edges[u, v] length += edge[by_what] # 根据什么统计最短路径长度 if min_flow > edge['capacity']: # 路线最窄处容量,可以理解为最小流量 min_flow = edge['capacity'] edge_route.append(edge['roadId']) car_stat['edgePath'] = edge_route car_stat['length'] = length car_stat['minFlow'] = min_flow stat.append(car_stat) for s in stat: print(s) print("有%s个不同的出发地点" % str(len(stat))) return stat
def get_one_route_to_switch(self, switch, new_swithes_list): comm_routes = {} route = 0 for s1 in new_swithes_list: if (s1 == switch): continue route = shortest_path(self.tree.graph, s1, switch) comm_routes[s1] = route return comm_routes
def _get_complete_path_and_cost(self, tour): complete_path = [tour[0]] cost = 0 for i, u in enumerate(tour[:len(tour) - 1]): v = tour[i + 1] cells_in_path = shortest_path(self.graph, source=u, target=v) cost += len(cells_in_path) for cell in cells_in_path[1:]: complete_path.append(cell) return complete_path, cost
def _find_pivot_lang(self, langs): langs = [l.lower() for l in langs] lang_graph = self.seg_map.get_lang_graph() path_len = shortest_path_length(lang_graph, langs[0], langs[1]) if path_len != 2: return None # Find shortest path path = shortest_path(lang_graph, langs[0], langs[1]) assert (len(path) == 3) # Get a pivot language and scan all pivot segments return path[1]
def pre_process_all_shortest_path(DG, dest, by_what='weight'): routes = [] for des in dest: path = alg.shortest_path(DG, source=des[0], target=des[1], weight=by_what, method='dijkstra') # print(path) routes.append(path) return routes
def path_length(adj_mat): """Calculate shortest path length from an adjacency matrix.""" n_node = adj_mat.shape[0] G = nx.from_numpy_matrix(adj_mat) gpath = shortest_path(G) pathlen = np.zeros((n_node, n_node)) for source, pathdict in gpath.items(): for target, pathlist in pathdict.items(): pathlen[source, target] = len(pathlist) - 1 return pathlen
def _all_paths_from_node(graph, source_node, targets): """Find all nodes on a (shortest) path from source to targets Return all the node ids that are either in targets or are in a path from source node to any of targets :rtype: list """ vertices_ids = targets paths = shortest_path(graph._g, source=source_node) vertices_ids.update(*[set(paths.get(n, [])) for n in targets]) return vertices_ids
def __find_predecessor__(i, j, g): """ Finds a predecessor, k, in the path between two nodes, i and j, in the graph, g. We assume g is connected, and there is a path between i and j (ignoring the direction of the edges). We want to find a k, that is a parent of j, that is in the path between i and j. In some cases, we may not find such a k. :param i: Index of node. :param j: Index of node. :param g: Graph. :return: Returns predecessor, if any, or None. """ parents = list(g.predecessors(j)) u = __convert_to_undirected_graph__(g) for pa in parents: try: shortest_path(u, pa, i) return pa except nx.NetworkXNoPath: pass return None
def find_predecessor(i, j, g): """ Finds a predecessor, k, in the path between two nodes, i and j, in the graph, g. """ parents = list(g.predecessors(j)) u = convert_to_undirected_graph(g) for pa in parents: try: path = shortest_path(u, pa, i) return pa except: pass return None
def get_contigs(graph, inode, outnode): tuple_list = [] for nodin in inode: for nodout in outnode: if len(list(nt.all_simple_paths(graph, nodin, nodout))) != 0: path = shortest_path(graph, nodin, nodout) contig = path[0] for i in range(1, len(path)): contig += path[i][-1] tuples = [] tuples.append(contig) tuples.append(len(contig)) tuple_list.append(tuple(tuples)) return tuple_list
def render_graph(): global nodes_count global matrix i = 0 g = nx.Graph() for node in range(nodes_count): g.add_node(node) for element in matrix: if element != 0 and i // nodes_count != i % nodes_count: g.add_edge(i // nodes_count, i % nodes_count, weight=element) i += 1 for node1 in g.nodes: for node2 in g.nodes: ttk.Label(root, text=shortest_path(g, node1, node2)).grid()
def spkmerge_config_string(dep_tree, output_spk, bodies, lsk, start, stop): """ Create the contents of an spkmerge config file that will produce a spk that completely defines the state of a list of bodies for a time range. Parameters ---------- dep_tree : nx.DiGraph Dependency tree from create_kernel_dependency_tree that contains information about what the state of different bodies are relative to and where that information is stored. output_spk : str The path to the SPK that will be output by spkmerge bodies : list The list of body ID codes that need to be defined in the kernel created by spkmerge lsk : str The absolute path to the leap second kernel to use start : str The UTC start time for the kernel created by spkmerge stop : str The UTC stop time for the kernel created by spkmerge Returns ------- : str The contents of an spkmerge config file that will produce a kernel that defines the state of the input bodies for the input time range. """ input_kernels = set() all_bodies = set(bodies) for body in bodies: # Everything is ultimately defined relative to # SOLAR SYSTEM BARYCENTER (0) so find the path to it print('DEP: ', dep_tree.nodes()) print('BOD: ', body) dep_path = shortest_path(dep_tree, body, 0) all_bodies.update(dep_path) for i in range(len(dep_path) - 1): input_kernels.add(dep_tree[dep_path[i]][dep_path[i + 1]]['kernel']) config = f"LEAPSECONDS_KERNEL = {lsk}\n" config += f"SPK_KERNEL = {output_spk}\n" config += f" BODIES = {', '.join([str(b) for b in all_bodies])}\n" config += f" BEGIN_TIME = {start}\n" config += f" END_TIME = {stop}\n" for kernel in input_kernels: config += f" SOURCE_SPK_KERNEL = {kernel}\n" config += f" INCLUDE_COMMENTS = no\n" return config
def convert(quantity, sourceUnit, destUnit): # Kludge: if both units are rates per second, convert using the size portion # of the rate if sourceUnit[-2:] == 'ps' and destUnit[-2:] == 'ps': sourceUnit = sourceUnit[:-2] destUnit = destUnit[:-2] nodes = shortest_path(CONVERSIONS, sourceUnit, destUnit) edges = [] for i in xrange(1, len(nodes)): conversionFunction = CONVERSIONS[nodes[i-1]][nodes[i]]["function"] quantity = conversionFunction(quantity) return quantity
def convert(quantity, sourceUnit, destUnit): # Kludge: if both units are rates per second, convert using the size portion # of the rate if sourceUnit[-2:] == 'ps' and destUnit[-2:] == 'ps': sourceUnit = sourceUnit[:-2] destUnit = destUnit[:-2] nodes = shortest_path(CONVERSIONS, sourceUnit, destUnit) edges = [] for i in xrange(1, len(nodes)): conversionFunction = CONVERSIONS[nodes[i - 1]][nodes[i]]["function"] quantity = conversionFunction(quantity) return quantity
def get_solution(self, partial=False): """ Find a solution from the graph of moves. @param partial: If True, a partial solution will be returned if no solution exists. @return: a list of strings describing each move. Each string is two digits describing the domino that moved plus a letter to show the direction. """ solution = [] goal = self.closest if partial else '' solution_nodes = shortest_path(self.graph, self.start, goal) for i in range(len(solution_nodes)-1): source, target = solution_nodes[i:i+2] solution.append(self.graph[source][target]['move']) return solution
def get_solution(self, return_partial=False): """ Find a solution from the graph of moves. @param return_partial: If True, a partial solution will be returned if no solution exists. @return: a list of strings describing each move. Each string is two digits describing the domino that moved plus a letter to show the direction. """ solution = [] goal = self.closest if return_partial else self.last or '' solution_nodes = shortest_path(self.graph, self.start, goal) for i in range(len(solution_nodes) - 1): source, target = solution_nodes[i:i + 2] solution.append(self.graph[source][target]['move']) return solution
def construct_full_graph(self): """Constructs the full unit graph""" units = self.get_units() units_combination = combinations(units, 2) # Initialize the unit convertor used in calculation for unit_pair in units_combination: if self.has_edge(unit_pair[0], unit_pair[1]): continue path = shortest_path(self, unit_pair[0], unit_pair[1]) multiplier = 1 for i in range(len(path) - 1): multiplier = multiplier * self[path[i]][path[i + 1]]["weight"] self.add_conversion(unit_pair[0], unit_pair[1], multiplier) self.is_constructed = True
routes = session.query(Route)\ .filter(Route.source == location.city_name) # If we're arriving from a previous route, eliminate nonconnectables if type(location._route) == Route: routes = routes.filter(Route.depart > location._route.arrive) routes = routes.all() for route in routes: next_location = Location(route) G.add_edge(location, next_location, weight=route.fare) if(next_location.city_name == END.city_name): G.add_edge(next_location, FINAL) else: populate_edges(next_location) populate_edges(START) path = shortest_path(G, source=START,target=FINAL, weight='weight') for node in path: print(node._route)
def get_choice_counts(self): solution_nodes = shortest_path(self.graph, self.start, '') return [len(self.graph[node]) for node in solution_nodes[:-1]]
from random import uniform jobs = [(1696863, 'grenoble'), (1502558, 'lille'), (74715, 'luxembourg')] logger.info('Retrieving hosts used for jobs %s', ', '.join([style.host(site) + ':' + style.emph(job_id) for job_id, site in jobs])) hosts = [get_host_shortname(h) for job_id, site in jobs for h in get_oar_job_nodes(job_id, site)] logger.info(hosts_list(hosts)) logger.info('Creating topological graph') g = g5k_graph(elements=hosts) i, j = int(uniform(1, len(hosts))), int(uniform(1, len(hosts))) path = shortest_path(g, hosts[i], hosts[j]) logger.info('Communication between %s and %s go through ' 'the following links: \n%s', style.host(hosts[i]), style.host(hosts[j]), ' -> '.join(path)) logger.info('Active links between nodes %s and %s are: \n%s', style.host(path[0]), style.host(path[1]), {k: v for k, v in g.edge[path[0]][path[1]].items() if v['active']}) logger.info('Generating graphical representation') plt = treemap(g) plt.show()
conceptjson=conceptnet.query_lookup("chennai") pprint.pprint(conceptjson) print "========================================" print "Related Concepts Ranked Descending by Distance Score" print "========================================" similarconcepts=conceptnet.related('chennai') pprint.pprint("Concepts related to Chennai") pprint.pprint(similarconcepts) similarconcepts=conceptnet.related('computer science') pprint.pprint("Concepts related to computer science") pprint.pprint(similarconcepts) print "========================================" print "ConceptNet Distance - Common Ancestor algorithm" print "========================================" distance=conceptnet.conceptnet_least_common_ancestor_distance('chennai','delhi') sp=shortest_path(distance,'chennai','delhi') pprint.pprint("Distance:"+str(len(sp))) pprint.pprint("Shortest Path:") pprint.pprint(sp) distance=conceptnet.conceptnet_least_common_ancestor_distance('fructify','fruitful') sp=shortest_path(distance,'fructify','fruitful') pprint.pprint("Distance:"+str(len(sp))) pprint.pprint("Shortest Path:") pprint.pprint(sp) distance=conceptnet.conceptnet_least_common_ancestor_distance('medicine','chemical') sp=shortest_path(distance,'medicine','chemical') pprint.pprint("Distance:"+str(len(sp))) pprint.pprint("Shortest Path:") pprint.pprint(sp) distance=conceptnet.conceptnet_least_common_ancestor_distance('tree','forest') sp=shortest_path(distance,'tree','forest')