Python networkx.shortest_path_length() Examples
The following are 30
code examples of networkx.shortest_path_length().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
networkx
, or try the search function
.
Example #1
Source File: network_analysis.py From ditto with BSD 3-Clause "New" or "Revised" License | 6 votes |
def furtherest_node_miles(self, *args): """ Returns the maximum eccentricity from the source, in miles. .. warning:: Not working.... """ if args: if len(args) == 1: _net = args[0] _src = self.source elif len(args) == 2: _net, _src = args else: _net = self.G.graph _src = self.source dist = {} _net = _net.copy() if not _net.has_node(_src): _sp = nx.shortest_path(self.G.graph, _src, list(_net.nodes())[0]) for n1, n2 in zip(_sp[:-1], _sp[1:]): _net.add_edge(n1, n2, length=self.G.graph[n1][n2]["length"]) for node in _net.nodes(): dist[node] = nx.shortest_path_length(_net, _src, node, weight="length") return np.max(list(dist.values())) * 0.000621371 # Convert length to miles
Example #2
Source File: comment_tree.py From news-popularity-prediction with Apache License 2.0 | 6 votes |
def calculate_comment_tree_hirsch(comment_tree): comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph()) if len(comment_tree_nx) == 0: comment_tree_hirsch = 0.0 else: node_to_depth = nx.shortest_path_length(comment_tree_nx, 0) depth_to_nodecount = collections.defaultdict(int) for k, v in node_to_depth.items(): depth_to_nodecount[v] += 1 comment_tree_hirsch = max(node_to_depth.values()) while True: if depth_to_nodecount[comment_tree_hirsch] >= comment_tree_hirsch: break else: comment_tree_hirsch -= 1 return comment_tree_hirsch
Example #3
Source File: neo4j.py From Verum with Apache License 2.0 | 6 votes |
def get_topic_distance(self, sg, topic): """ :param sg: an egocentric subgraph in networkx format :param topic: a networkx graph of nodes representing the topic :return: a dictionary of key node name and value distance as integer """ distances = dict() # get all the distances for tnode in topic.nodes(): if tnode in sg.nodes(): distances[tnode] = nx.shortest_path_length(sg, source=tnode) # get the smallest distance per key min_dist = dict() for key in distances: for node in distances[key]: if node not in min_dist: min_dist[node] = distances[key][node] elif distances[key][node] < min_dist[node]: min_dist[node] = distances[key][node] # Return the dict return min_dist
Example #4
Source File: comment_tree.py From news-popularity-prediction with Apache License 2.0 | 6 votes |
def calculate_max_depth_over_max_width(comment_tree): comment_tree_nx = nx.from_scipy_sparse_matrix(comment_tree, create_using=nx.Graph()) if len(comment_tree_nx) == 0: max_depth_over_max_width = 0.0 else: node_to_depth = nx.shortest_path_length(comment_tree_nx, 0) depth_to_nodecount = collections.defaultdict(int) for k, v in node_to_depth.items(): depth_to_nodecount[v] += 1 max_depth = max(node_to_depth.values()) max_width = max(depth_to_nodecount.values()) max_depth_over_max_width = max_depth/max_width return max_depth_over_max_width
Example #5
Source File: dag.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def descendants(G, source): """Return all nodes reachable from `source` in `G`. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) source : node in `G` Returns ------- set() The descendants of `source` in `G` """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) spl = nx.shortest_path_length(G, source=source) des = set(spl) - set([source]) return des
Example #6
Source File: test_distance_measures.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_eccentricity(self): assert_equal(networkx.eccentricity(self.G, 1), 6) e = networkx.eccentricity(self.G) assert_equal(e[1], 6) sp = dict(networkx.shortest_path_length(self.G)) e = networkx.eccentricity(self.G, sp=sp) assert_equal(e[1], 6) e = networkx.eccentricity(self.G, v=1) assert_equal(e, 6) # This behavior changed in version 1.8 (ticket #739) e = networkx.eccentricity(self.G, v=[1, 1]) assert_equal(e[1], 6) e = networkx.eccentricity(self.G, v=[1, 2]) assert_equal(e[1], 6) # test against graph with one node G = networkx.path_graph(1) e = networkx.eccentricity(G) assert_equal(e[0], 0) e = networkx.eccentricity(G, v=0) assert_equal(e, 0) assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1) # test against empty graph G = networkx.empty_graph() e = networkx.eccentricity(G) assert_equal(e, {})
Example #7
Source File: test_generic.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def test_all_pairs_shortest_path_length(self): ans = dict(nx.shortest_path_length(self.cycle)) assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.all_pairs_shortest_path_length(self.cycle))) ans = dict(nx.shortest_path_length(self.grid)) assert_equal(ans[1][16], 6) # now with weights ans = dict(nx.shortest_path_length(self.cycle, weight='weight')) assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle))) ans = dict(nx.shortest_path_length(self.grid, weight='weight')) assert_equal(ans[1][16], 6) # weights and method specified ans = dict(nx.shortest_path_length(self.cycle, weight='weight', method='dijkstra')) assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.all_pairs_dijkstra_path_length(self.cycle))) ans = dict(nx.shortest_path_length(self.cycle, weight='weight', method='bellman-ford')) assert_equal(ans[0], {0: 0, 1: 1, 2: 2, 3: 3, 4: 3, 5: 2, 6: 1}) assert_equal(ans, dict(nx.all_pairs_bellman_ford_path_length(self.cycle)))
Example #8
Source File: dag.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def ancestors(G, source): """Return all nodes having a path to `source` in `G`. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) source : node in `G` Returns ------- set() The ancestors of source in G """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) spl = nx.shortest_path_length(G, target=source) anc = set(spl) - set([source]) return anc
Example #9
Source File: dag.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def ancestors(G, source): """Returns all nodes having a path to `source` in `G`. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) source : node in `G` Returns ------- set() The ancestors of source in G """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) anc = set(n for n, d in nx.shortest_path_length(G, target=source).items()) return anc - {source}
Example #10
Source File: dag.py From Carnets with BSD 3-Clause "New" or "Revised" License | 6 votes |
def descendants(G, source): """Returns all nodes reachable from `source` in `G`. Parameters ---------- G : NetworkX DiGraph A directed acyclic graph (DAG) source : node in `G` Returns ------- set() The descendants of `source` in `G` """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) des = set(n for n, d in nx.shortest_path_length(G, source=source).items()) return des - {source}
Example #11
Source File: common.py From QTop with GNU General Public License v3.0 | 6 votes |
def distance(self, type, node1, node2): if node1 in self.Dual[type].nodes() and node2 in self.Dual[type].nodes(): return nx.shortest_path_length(self.Dual[type], node1, node2) elif node1 in self.Dual[type].nodes() and node2 not in self.Dual[type].nodes(): node2 = self.External[type][node2]['measure'] return nx.shortest_path_length(self.Dual[type], node1, node2) + 1 elif node1 not in self.Dual[type].nodes() and node2 in self.Dual[type].nodes(): node1 = self.External[type][node1]['measure'] return nx.shortest_path_length(self.Dual[type], node1, node2) + 1 else: node1 = self.External[type][node1]['measure'] node2 = self.External[type][node2]['measure'] return nx.shortest_path_length(self.Dual[type], node1, node2) + 2 # Re-initializes Measurement qubits
Example #12
Source File: introduce_cycles_to_DAG.py From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License | 6 votes |
def add_cycle_edges_by_path(g,number_of_edges,path_length = 5): number = 0 num_nodes = g.number_of_nodes() nodes = g.nodes() extra_edges = [] while number < number_of_edges: u,v = np.random.randint(0,num_nodes,2) u = nodes[u] v = nodes[v] if nx.has_path(g,u,v): length = nx.shortest_path_length(g,source = u,target = v) if length <= path_length: extra_edges.append((v,u)) number += 1 if nx.has_path(g,v,u): length = nx.shortest_path_length(g,source = v,target = u) if length <= path_length: extra_edges.append((u,v)) number += 1 print("# extra edges added with path length <= %d: %d" % (path_length,len(extra_edges))) return extra_edges
Example #13
Source File: dag.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def ancestors(G, source): """Return all nodes having a path to `source` in G. Parameters ---------- G : NetworkX DiGraph source : node in G Returns ------- ancestors : set() The ancestors of source in G """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) anc = set(nx.shortest_path_length(G, target=source).keys()) - set([source]) return anc
Example #14
Source File: dag.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def descendants(G, source): """Return all nodes reachable from `source` in G. Parameters ---------- G : NetworkX DiGraph source : node in G Returns ------- des : set() The descendants of source in G """ if not G.has_node(source): raise nx.NetworkXError("The node %s is not in the graph." % source) des = set(nx.shortest_path_length(G, source=source).keys()) - set([source]) return des
Example #15
Source File: test_distance_measures.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_eccentricity(self): assert_equal(networkx.eccentricity(self.G,1),6) e=networkx.eccentricity(self.G) assert_equal(e[1],6) sp=networkx.shortest_path_length(self.G) e=networkx.eccentricity(self.G,sp=sp) assert_equal(e[1],6) e=networkx.eccentricity(self.G,v=1) assert_equal(e,6) e=networkx.eccentricity(self.G,v=[1,1]) #This behavior changed in version 1.8 (ticket #739) assert_equal(e[1],6) e=networkx.eccentricity(self.G,v=[1,2]) assert_equal(e[1],6) # test against graph with one node G=networkx.path_graph(1) e=networkx.eccentricity(G) assert_equal(e[0],0) e=networkx.eccentricity(G,v=0) assert_equal(e,0) assert_raises(networkx.NetworkXError, networkx.eccentricity, G, 1) # test against empty graph G=networkx.empty_graph() e=networkx.eccentricity(G) assert_equal(e,{})
Example #16
Source File: main.py From scTDA with GNU General Public License v3.0 | 6 votes |
def dendritic_graph(self): """ Builds skeleton of the topological representation (used internally) """ diam = networkx.diameter(self.gl) g3 = networkx.Graph() dicdend = {} for n in range(diam-1): nodedist = [] for k in self.pl: dil = networkx.shortest_path_length(self.gl, self.root, k) if dil == n: nodedist.append(str(k)) g2 = self.gl.subgraph(nodedist) dicdend[n] = sorted(networkx.connected_components(g2)) for n2, yu in enumerate(dicdend[n]): g3.add_node(str(n) + '_' + str(n2)) if n > 0: for n3, yu2 in enumerate(dicdend[n-1]): if networkx.is_connected(self.gl.subgraph(list(yu)+list(yu2))): g3.add_edge(str(n) + '_' + str(n2), str(n-1) + '_' + str(n3)) return g3, dicdend
Example #17
Source File: dmeasure.py From netrd with MIT License | 6 votes |
def node_distance(G): """ Return an NxN matrix that consists of histograms of shortest path lengths between nodes i and j. This is useful for eventually taking information theoretic distances between the nodes. Parameters ---------- G (nx.Graph): the graph in question. Returns ------- out (np.ndarray): a matrix of binned node distance values. """ N = G.number_of_nodes() a = np.zeros((N, N)) dists = nx.shortest_path_length(G) for idx, row in enumerate(dists): counts = Counter(row[1].values()) a[idx] = [counts[l] for l in range(1, N + 1)] return a / (N - 1)
Example #18
Source File: SpreadingActivation.py From Quadflor with BSD 3-Clause "New" or "Revised" License | 6 votes |
def bell_reweighting(tree, root, sublinear=False): # convert the hierarchy to a tree if make_bfs_tree is true distance_by_target = nx.shortest_path_length(tree, source=root) level_count = defaultdict(int) for val in distance_by_target.values(): level_count[val] += 1 for edge in tree.edges(): parent, child = edge if sublinear: # use smoothed logarithm tree[parent][child]['weight'] = 1.0 / log(1 + level_count[distance_by_target[child]], 10) else: tree[parent][child]['weight'] = 1.0 / level_count[distance_by_target[child]] return tree
Example #19
Source File: find_best_mapping.py From Liftoff with GNU General Public License v3.0 | 6 votes |
def find_best_mapping(alignments, query_length, parent, coords_to_exclude, children_dict, previous_gene_start, copy_tag): children = children_dict[parent.id] children_coords = liftoff_utils.merge_children_intervals(children) node_dict, aln_graph = intialize_graph() head_nodes = add_single_alignments(node_dict, aln_graph, alignments, children_coords, parent, coords_to_exclude, previous_gene_start) chain_alignments(head_nodes, node_dict, aln_graph, coords_to_exclude, parent, children_coords) add_target_node(aln_graph, node_dict, query_length, children_coords, parent) shortest_path = nx.shortest_path(aln_graph, source=0, target=len(node_dict) - 1, weight=lambda u, v, d: get_weight(u, v, d, aln_graph)) shortest_path_weight = nx.shortest_path_length(aln_graph, source=0, target=len(node_dict) - 1, weight=lambda u, v, d: get_weight(u, v, d, aln_graph)) shortest_path_nodes = [] for i in range (1,len(shortest_path)-1): node_name = shortest_path[i] shortest_path_nodes.append(node_dict[node_name]) if len(shortest_path_nodes) == 0: return {}, shortest_path_weight, 0,0 mapped_children, alignment_coverage, seq_id = convert_all_children_coords(shortest_path_nodes, children, parent, copy_tag) return mapped_children, shortest_path_weight, alignment_coverage, seq_id
Example #20
Source File: rcm.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def pseudo_peripheral_node(G): # helper for cuthill-mckee to find a node in a "pseudo peripheral pair" # to use as good starting node u = arbitrary_element(G) lp = 0 v = u while True: spl = dict(nx.shortest_path_length(G, v)) l = max(spl.values()) if l <= lp: break lp = l farthest = (n for n, dist in spl.items() if dist == l) v, deg = min(G.degree(farthest), key=itemgetter(1)) return v
Example #21
Source File: test_unweighted.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_shortest_path_length(self): assert_equal(nx.shortest_path_length(self.cycle, 0, 3), 3) assert_equal(nx.shortest_path_length(self.grid, 1, 12), 5) assert_equal(nx.shortest_path_length(self.directed_cycle, 0, 4), 4) # now with weights assert_equal(nx.shortest_path_length(self.cycle, 0, 3, weight=True), 3) assert_equal(nx.shortest_path_length(self.grid, 1, 12, weight=True), 5) assert_equal(nx.shortest_path_length(self.directed_cycle, 0, 4, weight=True), 4)
Example #22
Source File: flex_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
def get_shortest_path_for_routed_lsp(self, source_node_name, dest_node_name, lsp, needed_bw): """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available for an LSP that is already routed. Return the shortest path in dictionary form: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} :param source_node_name: name of source node :param dest_node_name: name of destination node :param lsp: LSP object :param needed_bw: reserved bandwidth for LSPs :return: dict {'path': [list of lists, each list a shortest path route], 'cost': path_cost} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph_routed_lsp(lsp, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest digraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') try: for path in digraph_shortest_paths: model_path = self._convert_nx_path_to_model_path_routed_lsp(path, needed_bw, lsp) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') except BaseException: return converted_path # Normalize the path info to get all combinations of with parallel # interfaces path_info = self._normalize_multidigraph_paths(converted_path['path']) return {'cost': converted_path['cost'], 'path': path_info}
Example #23
Source File: flex_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
def get_shortest_path(self, source_node_name, dest_node_name, needed_bw=0): # TODO - does this work? """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available. :param source_node_name: name of source node in path :param dest_node_name: name of destination node in path :param needed_bw: the amount of reservable bandwidth required on the path :return: Return the shortest path in dictionary form: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph_mdg(include_failed_circuits=False, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest multidigraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') # Get shortest path(s) from source to destination; this may include paths # that have multiple links between nodes try: for path in multidigraph_shortest_paths: model_path = self._convert_nx_path_to_model_path(path, needed_bw) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') except BaseException: return converted_path # Normalize the path info to get all combinations of with parallel # interfaces path_info = self._normalize_multidigraph_paths(converted_path['path']) return {'cost': converted_path['cost'], 'path': path_info}
Example #24
Source File: performance_model.py From network_traffic_modeler_py3 with Apache License 2.0 | 5 votes |
def get_shortest_path(self, source_node_name, dest_node_name, needed_bw=0): """ For a source and dest node name pair, find the shortest path(s) with at least needed_bw available. :param source_node_name: name of source node in path :param dest_node_name: name of destination node in path :param needed_bw: the amount of reservable bandwidth required on the path :return: Return the shortest path in dictionary form Example: shortest_path = {'path': [list of shortest path routes], 'cost': path_cost} """ # Define a networkx DiGraph to find the path G = self._make_weighted_network_graph(include_failed_circuits=False, needed_bw=needed_bw) # Define the Model-style path to be built converted_path = dict() converted_path['path'] = [] converted_path['cost'] = None # Find the shortest paths in G between source and dest digraph_shortest_paths = nx.all_shortest_paths(G, source_node_name, dest_node_name, weight='cost') try: for path in digraph_shortest_paths: model_path = self._convert_nx_path_to_model_path(path) converted_path['path'].append(model_path) converted_path['cost'] = nx.shortest_path_length(G, source_node_name, dest_node_name, weight='cost') return converted_path except BaseException: return converted_path
Example #25
Source File: rcm.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def pseudo_peripheral_node(G): # helper for cuthill-mckee to find a node in a "pseudo peripheral pair" # to use as good starting node u = arbitrary_element(G) lp = 0 v = u while True: spl = dict(nx.shortest_path_length(G, v)) l = max(spl.values()) if l <= lp: break lp = l farthest = (n for n, dist in spl.items() if dist == l) v, deg = min(G.degree(farthest), key=itemgetter(1)) return v
Example #26
Source File: mininet_test_watcher.py From faucet with Apache License 2.0 | 5 votes |
def get_connected_hosts(self, two_way=False, strictly_intervlan=False): """ Hosts are connected if the shortest path they can form in the predicted graph that is longer than 3 (itself, shared DP, dst host) Returns dictionary of host index to list of connected host index """ if self.connected_hosts: return self.connected_hosts connected_hosts = {i: [] for i in self.host_name_to_index.values()} for src_host in self.host_name_to_index: src_index = self.host_name_to_index[src_host] for dst_host in self.host_name_to_index: dst_index = self.host_name_to_index[dst_host] if src_index != dst_index and self.is_shared_router( src_index, dst_index, strictly_intervlan=strictly_intervlan): if two_way or ( src_index not in connected_hosts[dst_index] and dst_index not in connected_hosts[src_index]): try: path_length = networkx.shortest_path_length( self.predicted_network_graph, src_host, dst_host) if path_length >= 3: connected_hosts[src_index].append(dst_index) except networkx.exception.NetworkXNoPath: continue self.connected_hosts = connected_hosts return connected_hosts
Example #27
Source File: efficiency.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def efficiency(G, u, v): """Returns the efficiency of a pair of nodes in a graph. The *efficiency* of a pair of nodes is the multiplicative inverse of the shortest path distance between the nodes [1]_. Returns 0 if no path between nodes. Parameters ---------- G : :class:`networkx.Graph` An undirected graph for which to compute the average local efficiency. u, v : node Nodes in the graph ``G``. Returns ------- float Multiplicative inverse of the shortest path distance between the nodes. Notes ----- Edge weights are ignored when computing the shortest path distances. See also -------- local_efficiency global_efficiency References ---------- .. [1] Latora, Vito, and Massimo Marchiori. "Efficient behavior of small-world networks." *Physical Review Letters* 87.19 (2001): 198701. <http://dx.doi.org/10.1103/PhysRevLett.87.198701> """ try: eff = 1 / nx.shortest_path_length(G, u, v) except NetworkXNoPath: eff = 0 return eff
Example #28
Source File: SpreadingActivation.py From Quadflor with BSD 3-Clause "New" or "Revised" License | 5 votes |
def fit(self, X, y=None): # the bell methods require additional information if self.method in ["bell", "belllog"]: # precompute node count by level self.levels = defaultdict(int) for node in self.hierarchy.nodes(): l = nx.shortest_path_length(self.hierarchy, self.root, node) self.levels[l] += 1 print(self.levels) return self
Example #29
Source File: SpreadingActivation.py From Quadflor with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _score(self, freq, scores, row, col, memoization=None): mem = memoization if memoization is not None else [False] * scores.shape[1] # memoization hit if mem[col]: return scores[row, col] children = self.hierarchy.successors(self.feature_names[col] if self.feature_names else col) if len(children) == 0: # Base case for leaves scores[row, col] = freq[row, col] mem[col] = True return scores[row, col] # recursively compute children score score = float(0) for child in children: child_idx = self.vocabulary[child] if self.vocabulary else child score += self._score(freq, scores, row, child_idx, memoization=mem) # scale them with some method specific factor if self.method in ["bell", "belllog"]: k = nx.shortest_path_length(self.hierarchy, self.root, self.feature_names[col] if self.feature_names else col) print(k+1, self.levels[k+1]) print("Count of children:", len(children)) denom = self.levels[k+1] if self.method == "belllog": denom = log(denom, 10) #TODO problem when zero score *= 1.0 / denom elif self.method == "children": score *= 1.0 / len(children) elif self.method == "basic": score *= self.decay # add the freq of the concept just now since it should not be scaled score += freq[row, col] scores[row, col] = score mem[col] = True return scores[row, col]
Example #30
Source File: cycles.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _min_cycle(G, orth, weight=None): """ Computes the minimum weight cycle in G, orthogonal to the vector orth as per [p. 338, 1] """ T = nx.Graph() nodes_idx = {node: idx for idx, node in enumerate(G.nodes())} idx_nodes = {idx: node for node, idx in nodes_idx.items()} nnodes = len(nodes_idx) # Add 2 copies of each edge in G to T. If edge is in orth, add cross edge; # otherwise in-plane edge for u, v, data in G.edges(data=True): uidx, vidx = nodes_idx[u], nodes_idx[v] edge_w = data.get(weight, 1) if frozenset((u, v)) in orth: T.add_edges_from( [(uidx, nnodes + vidx), (nnodes + uidx, vidx)], weight=edge_w) else: T.add_edges_from( [(uidx, vidx), (nnodes + uidx, nnodes + vidx)], weight=edge_w) all_shortest_pathlens = dict(nx.shortest_path_length(T, weight=weight)) cross_paths_w_lens = {n: all_shortest_pathlens[n][nnodes + n] for n in range(nnodes)} # Now compute shortest paths in T, which translates to cyles in G start = min(cross_paths_w_lens, key=cross_paths_w_lens.get) end = nnodes + start min_path = nx.shortest_path(T, source=start, target=end, weight='weight') # Now we obtain the actual path, re-map nodes in T to those in G min_path_nodes = [node if node < nnodes else node - nnodes for node in min_path] # Now remove the edges that occur two times mcycle_pruned = _path_to_cycle(min_path_nodes) return {frozenset((idx_nodes[u], idx_nodes[v])) for u, v in mcycle_pruned}