def compute_node_levels(nodes: dict, use_tarjan=True): graph = nx.MultiDiGraph() level_map = defaultdict(lambda: float('inf')) target_names = [] for name, node in nodes.items(): if node.node_type == "compute" and len( list(node._succs.keys()) + list(node._preds.keys())) > 0: target_names.append(name) for v in node._succs.values(): graph.add_edge(name, v.name) for target in target_names: lengths = list(nx.single_target_shortest_path_length(graph, target)) for name, length in lengths: if name == target or name in target_names: continue level_map[name] = min(level_map[name], length) level_map.update({t: 0 for t in target_names}) max_val = int(max(level_map.values())) rev_map = {i: max_val - i for i in range(max_val + 1)} node_levels = defaultdict(list) for k, v in level_map.items(): node_levels[rev_map[v]].append(k) return node_levels
def get_destination_interfaces_for_subnet(self, subnet, forwarding_graph): dst_routers = set( ) # all routers that are directly connected to the sink all_destinations = set() destinations = dict() interfaces = list() for router in forwarding_graph.predecessors("sink"): interfaces.extend( self.network.get_interfaces_for_subnet(router, subnet)) for dst_router, dst_interface in interfaces: dst_routers.add(dst_router) policy_destination = PolicyDestination(dst_router, dst_interface, subnet) all_destinations.add(policy_destination) for node, _ in nx.single_target_shortest_path_length( forwarding_graph, dst_router): if node not in destinations: destinations[node] = [policy_destination] else: destinations[node].append(policy_destination) return all_destinations, destinations, dst_routers
def shortest_distance(model, reaction, reactions=None, remove=[]): """ Returns the unweighted shortest path distance from a list of reactions to a reaction. Distances are the number of required reactions. If there is no pathway between the reactions the distance is inf· :param model: A model or a Simulator instance. :param str reaction: target reaction. :param list reactions: List os source reactions. Defaults to None, in which case all model reactions are considered. :param list remove: List os metabolites not to be included. May be used to remove path that include \ cofactores such as ATP/ADP, NAD(P)(H), and acetyl-CoA/CoA. :returns: A dictionary of distances. """ if not isinstance(model, Simulator): container = get_simulator(model) else: container = model rxns = reactions if reactions else container.reactions if reaction not in rxns: rxns.append(reaction) G = create_metabolic_graph(container, reactions=rxns, remove=remove) sp = dict(nx.single_target_shortest_path_length(G, reaction)) distances = {} for rxn in rxns: if rxn in sp: distances[rxn] = sp[rxn] // 2 else: distances[rxn] = np.inf return distances
def _cut_upper_levels(self, limit): """ Удаляет вершины, длина кратчайшего пути от которых к POV превышает limit. """ length = dict(nx.single_target_shortest_path_length(self.nx_graph, self.pov_id)) for node_id in length: if length[node_id] > limit: self.nx_graph.remove_node(node_id)
def test_metabolite_network_tiny(self): eids = ["1.1.4.13", "2.3.1"] qc = {"ecno": {"$in": eids}} m = qrymtntx.get_metabolite_network(qc) self.assertAlmostEqual(563, len(m.nodes()), delta=20) self.assertAlmostEqual(661, len(m.edges()), delta=20) import networkx as nx r = nx.single_target_shortest_path_length(m, "Betanin", cutoff=4) assert ('celosianin I', 3) in list(r)
def get_shortest_direct_parent_path_lengths(self, reference_node: str) -> dict: """ This function computes the path lengths from a given reference to all other via direct parent edges reachable nodes. It does NOT convert the graph to a undirected version before and respects directions. Dict form is {node_id: distance}. """ g = self.deepcopy().remove_edge_type( RR.ULTIMATE) # TODO: What about BRANCH? return dict(nx.single_target_shortest_path_length(g.g, reference_node))
def _load_dependencies_up(self, levels_counter): """ Подгружает связи в графе на levels_counter уровней вверх. """ # ищем крайние вершины графа upper_periphery = set() length = dict(nx.single_target_shortest_path_length(self.nx_graph, self.pov_id)) for node_id in length: if length[node_id] == self.levels_up: upper_periphery.add(node_id) # используем набор крайних вершин как отправную точку для поиска rising_failed = [] for node in self._storage.get_group_of_nodes_by_ids(upper_periphery): rising_failed.append(self._explore_upper_nodes(node, levels_counter)) return all(rising_failed)
def _level_computation(subgraph, root_node: str) -> dict: """ This function computes the levels with respect to the given root node by using single target shortest path algorithm from networkx. It returns a dictionary of node ids with the computed depth in the graph. """ compute_graph = subgraph.remove_edge_type(rel_type=RR.ULTIMATE) distances = nx.single_target_shortest_path_length(compute_graph.g, target=root_node) distances = dict(distances) distances.update({ node: 'no_parent' for node in subgraph.nodes if not distances.get(node) and node is not root_node }) distances.update({root_node: 0}) return distances
def _recalc(self): """ Обходит граф, считая максимальные длины путей в центральную вершину и из неё. """ path_down = nx.single_source_shortest_path_length(self.nx_graph, self.pov_id) path_up = dict(nx.single_target_shortest_path_length(self.nx_graph, self.pov_id)) self.levels_down = max([length for length in path_down.values()]) self.levels_up = max([length for length in path_up.values()]) # поиск вершин без потомков for node in self.nx_graph.node: self.nx_graph.node[node]["is_blind"] = (not list(self.nx_graph.successors(node))) # поиск циклов, проходящих через точку отсчёта cycles = simple_cycles(self.nx_graph) cycles = list(filter(lambda cycle: self.pov_id in cycle, cycles)) for node in set([node for cycle in cycles for node in cycle]): self[node]["in_cycle"] = True
# keep only is_a and part_of edges for (a, b, t) in list(go_graph.edges): if t not in ["is_a", "part_of"]: go_graph.remove_edge(a, b, t) # calculate the distance from the three different roots bp_distance = pd.DataFrame( [ { "go_id": source, "distance_from_root": distance, "aspect": "biological_process", } for source, distance in nx.single_target_shortest_path_length( go_graph, target="GO:0008150" ) if go_graph.nodes[source]["namespace"] == "biological_process" ] ) mf_distance = pd.DataFrame( [ { "go_id": source, "distance_from_root": distance, "aspect": "molecular_function", } for source, distance in nx.single_target_shortest_path_length( go_graph, target="GO:0003674" ) if go_graph.nodes[source]["namespace"] == "molecular_function"