Python networkx.density() Examples
The following are 30
code examples of networkx.density().
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: test_ramsey.py From aws-kube-codesuite with Apache License 2.0 | 6 votes |
def test_ramsey(): # this should only find the complete graph graph = nx.complete_graph(10) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") # this trival graph has no cliques. should just find i-sets graph = nx.trivial_graph(nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 0.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") graph = nx.barbell_graph(10, 5, nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!")
Example #2
Source File: subgraph.py From strawberryfields with Apache License 2.0 | 6 votes |
def _update_dict(d: dict, d_new: dict, max_count: int) -> None: """Updates dictionary ``d`` with subgraph tuples contained in ``d_new``. Subgraph tuples are a pair of values: a float specifying the subgraph density and a list of integers specifying the subgraph nodes. Both ``d`` and ``d_new`` are dictionaries over different subgraph sizes. The values of ``d`` are lists of subgraph tuples containing the top densest subgraphs for a given size, with maximum length ``max_count``. The values of ``d_new`` are candidate subgraph tuples that can be the result of resizing an input subgraph over a range using :func:`resize`. We want to add these candidates to the list of subgraph tuples in ``d`` to build up our collection of dense subgraphs. Args: d (dict[int, list[tuple[float, list[int]]]]): dictionary of subgraph sizes and corresponding list of subgraph tuples d_new (dict[int, tuple[float, list[int]]]): dictionary of subgraph sizes and corresponding subgraph tuples that are candidates to be added to the list max_count (int): the maximum length of every subgraph tuple list Returns: None: this function modifies the dictionary ``d`` in place """ for size, t in d_new.items(): l = d.setdefault(size, [t]) _update_subgraphs_list(l, t, max_count)
Example #3
Source File: test_clique.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_clique_removal(): graph = nx.complete_graph(10) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by clique_removal!") for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 1.0, "clique not found by clique_removal!") graph = nx.trivial_graph(nx.Graph()) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") # we should only have 1-cliques. Just singleton nodes. for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 0.0, "clique not found by clique_removal!") graph = nx.barbell_graph(10, 5, nx.Graph()) i, cs = apxa.clique_removal(graph) idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") for clique in cs: cdens = nx.density(graph.subgraph(clique)) eq_(cdens, 1.0, "clique not found by clique_removal!")
Example #4
Source File: test_ramsey.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 6 votes |
def test_ramsey(): # this should only find the complete graph graph = nx.complete_graph(10) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") # this trival graph has no cliques. should just find i-sets graph = nx.trivial_graph(nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 0.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!") graph = nx.barbell_graph(10, 5, nx.Graph()) c, i = apxa.ramsey_R2(graph) cdens = nx.density(graph.subgraph(c)) eq_(cdens, 1.0, "clique not found by ramsey!") idens = nx.density(graph.subgraph(i)) eq_(idens, 0.0, "i-set not found by ramsey!")
Example #5
Source File: graph.py From pybel with MIT License | 6 votes |
def list(self) -> List[Tuple[str, float]]: """Return a list of tuples that summarize the graph.""" number_nodes = self.graph.number_of_nodes() return [ ('Name', self.graph.name), ('Version', self.graph.version), ('Number of Nodes', number_nodes), ('Number of Namespaces', len(self.graph.count.namespaces())), ('Number of Edges', self.graph.number_of_edges()), ('Number of Annotations', len(self.graph.count.annotations())), ('Number of Citations', self.graph.number_of_citations()), ('Number of Authors', self.graph.number_of_authors()), ('Network Density', '{:.2E}'.format(nx.density(self.graph))), ('Number of Components', nx.number_weakly_connected_components(self.graph)), ('Number of Warnings', self.graph.number_of_warnings()), ]
Example #6
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 6 votes |
def scaled_density(graph, communities, **kwargs): """Scaled density. The scaled density of a community is defined as the ratio of the community density w.r.t. the complete graph density. :param graph: a networkx/igraph object :param communities: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> scd = evaluation.scaled_density(g,communities) """ return __quality_indexes(graph, communities, lambda graph, coms: nx.density(nx.subgraph(graph, coms)) / nx.density(graph), **kwargs)
Example #7
Source File: graph.py From taskflow with Apache License 2.0 | 6 votes |
def pformat(self): """Pretty formats your graph into a string. This pretty formatted string representation includes many useful details about your graph, including; name, type, frozeness, node count, nodes, edge count, edges, graph density and graph cycles (if any). """ lines = _common_format(self, "->") cycles = list(nx.cycles.recursive_simple_cycles(self)) lines.append("Cycles: %s" % len(cycles)) for cycle in cycles: buf = six.StringIO() buf.write("%s" % (cycle[0])) for i in range(1, len(cycle)): buf.write(" --> %s" % (cycle[i])) buf.write(" --> %s" % (cycle[0])) lines.append(" %s" % buf.getvalue()) return os.linesep.join(lines)
Example #8
Source File: graph.py From taskflow with Apache License 2.0 | 6 votes |
def _common_format(g, edge_notation): lines = [] lines.append("Name: %s" % g.name) lines.append("Type: %s" % type(g).__name__) lines.append("Frozen: %s" % nx.is_frozen(g)) lines.append("Density: %0.3f" % nx.density(g)) lines.append("Nodes: %s" % g.number_of_nodes()) for n, n_data in g.nodes(data=True): if n_data: lines.append(" - %s (%s)" % (n, n_data)) else: lines.append(" - %s" % n) lines.append("Edges: %s" % g.number_of_edges()) for (u, v, e_data) in g.edges(data=True): if e_data: lines.append(" %s %s %s (%s)" % (u, edge_notation, v, e_data)) else: lines.append(" %s %s %s" % (u, edge_notation, v)) return lines
Example #9
Source File: kcomponents.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def _cliques_heuristic(G, H, k, min_density): h_cnumber = nx.core_number(H) for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)): cands = set(n for n, c in h_cnumber.items() if c == c_value) # Skip checking for overlap for the highest core value if i == 0: overlap = False else: overlap = set.intersection(*[ set(x for x in H[n] if x not in cands) for n in cands]) if overlap and len(overlap) < k: SH = H.subgraph(cands | overlap) else: SH = H.subgraph(cands) sh_cnumber = nx.core_number(SH) SG = nx.k_core(G.subgraph(SH), k) while not (_same(sh_cnumber) and nx.density(SH) >= min_density): SH = H.subgraph(SG) if len(SH) <= k: break sh_cnumber = nx.core_number(SH) sh_deg = SH.degree() min_deg = min(sh_deg.values()) SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg) SG = nx.k_core(G.subgraph(SH), k) else: yield SG
Example #10
Source File: generate.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 5 votes |
def correct_density(filename: str, real_density: float): path_elts = filename.split("/") for i in range(len(path_elts)): if path_elts[i].split("=")[0] == "density": path_elts[i] = "density={}".format(round(real_density, 1)) return "/".join(path_elts)
Example #11
Source File: test_function.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_density(self): assert_equal(nx.density(self.G), 0.5) assert_equal(nx.density(self.DG), 0.3) G = nx.Graph() G.add_node(1) assert_equal(nx.density(G), 0.0)
Example #12
Source File: test_function.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_density_selfloop(self): G = nx.Graph() G.add_edge(1, 1) assert_equal(nx.density(G), 0.0) G.add_edge(1, 2) assert_equal(nx.density(G), 2.0)
Example #13
Source File: test_threshold.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_fast_versions_properties_threshold_graphs(self): cs = 'ddiiddid' G = nxt.threshold_graph(cs) assert_equal(nxt.density('ddiiddid'), nx.density(G)) assert_equal(sorted(nxt.degree_sequence(cs)), sorted(d for n, d in G.degree())) ts = nxt.triangle_sequence(cs) assert_equal(ts, list(nx.triangles(G).values())) assert_equal(sum(ts) // 3, nxt.triangles(cs)) c1 = nxt.cluster_sequence(cs) c2 = list(nx.clustering(G).values()) assert_almost_equal(sum([abs(c - d) for c, d in zip(c1, c2)]), 0) b1 = nx.betweenness_centrality(G).values() b2 = nxt.betweenness_sequence(cs) assert_true(sum([abs(c - d) for c, d in zip(b1, b2)]) < 1e-14) assert_equal(nxt.eigenvalues(cs), [0, 1, 3, 3, 5, 7, 7, 8]) # Degree Correlation assert_true(abs(nxt.degree_correlation(cs) + 0.593038821954) < 1e-12) assert_equal(nxt.degree_correlation('diiiddi'), -0.8) assert_equal(nxt.degree_correlation('did'), -1.0) assert_equal(nxt.degree_correlation('ddd'), 1.0) assert_equal(nxt.eigenvalues('dddiii'), [0, 0, 0, 0, 3, 3]) assert_equal(nxt.eigenvalues('dddiiid'), [0, 1, 1, 1, 4, 4, 7])
Example #14
Source File: kcomponents.py From Carnets with BSD 3-Clause "New" or "Revised" License | 5 votes |
def _cliques_heuristic(G, H, k, min_density): h_cnumber = nx.core_number(H) for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)): cands = set(n for n, c in h_cnumber.items() if c == c_value) # Skip checking for overlap for the highest core value if i == 0: overlap = False else: overlap = set.intersection(*[ set(x for x in H[n] if x not in cands) for n in cands]) if overlap and len(overlap) < k: SH = H.subgraph(cands | overlap) else: SH = H.subgraph(cands) sh_cnumber = nx.core_number(SH) SG = nx.k_core(G.subgraph(SH), k) while not (_same(sh_cnumber) and nx.density(SH) >= min_density): #!! This subgraph must be writable => .copy() SH = H.subgraph(SG).copy() if len(SH) <= k: break sh_cnumber = nx.core_number(SH) sh_deg = dict(SH.degree()) min_deg = min(sh_deg.values()) SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg) SG = nx.k_core(G.subgraph(SH), k) else: yield SG
Example #15
Source File: test_function.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_density(self): assert_equal(nx.density(self.G), 0.5) assert_equal(nx.density(self.DG), 0.3) G = nx.Graph() G.add_node(1) assert_equal(nx.density(G), 0.0)
Example #16
Source File: test_function.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_density_selfloop(self): G = nx.Graph() G.add_edge(1, 1) assert_equal(nx.density(G), 0.0) G.add_edge(1, 2) assert_equal(nx.density(G), 2.0)
Example #17
Source File: test_threshold.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def test_fast_versions_properties_threshold_graphs(self): cs = 'ddiiddid' G = nxt.threshold_graph(cs) assert_equal(nxt.density('ddiiddid'), nx.density(G)) assert_equal(sorted(nxt.degree_sequence(cs)), sorted(d for n, d in G.degree())) ts = nxt.triangle_sequence(cs) assert_equal(ts, list(nx.triangles(G).values())) assert_equal(sum(ts) // 3, nxt.triangles(cs)) c1 = nxt.cluster_sequence(cs) c2 = list(nx.clustering(G).values()) assert_almost_equal(sum([abs(c - d) for c, d in zip(c1, c2)]), 0) b1 = nx.betweenness_centrality(G).values() b2 = nxt.betweenness_sequence(cs) assert_true(sum([abs(c - d) for c, d in zip(b1, b2)]) < 1e-14) assert_equal(nxt.eigenvalues(cs), [0, 1, 3, 3, 5, 7, 7, 8]) # Degree Correlation assert_true(abs(nxt.degree_correlation(cs) + 0.593038821954) < 1e-12) assert_equal(nxt.degree_correlation('diiiddi'), -0.8) assert_equal(nxt.degree_correlation('did'), -1.0) assert_equal(nxt.degree_correlation('ddd'), 1.0) assert_equal(nxt.eigenvalues('dddiii'), [0, 0, 0, 0, 3, 3]) assert_equal(nxt.eigenvalues('dddiiid'), [0, 1, 1, 1, 4, 4, 7])
Example #18
Source File: kcomponents.py From aws-kube-codesuite with Apache License 2.0 | 5 votes |
def _cliques_heuristic(G, H, k, min_density): h_cnumber = nx.core_number(H) for i, c_value in enumerate(sorted(set(h_cnumber.values()), reverse=True)): cands = set(n for n, c in h_cnumber.items() if c == c_value) # Skip checking for overlap for the highest core value if i == 0: overlap = False else: overlap = set.intersection(*[ set(x for x in H[n] if x not in cands) for n in cands]) if overlap and len(overlap) < k: SH = H.subgraph(cands | overlap) else: SH = H.subgraph(cands) sh_cnumber = nx.core_number(SH) SG = nx.k_core(G.subgraph(SH), k) while not (_same(sh_cnumber) and nx.density(SH) >= min_density): #!! This subgraph must be writable => .copy() SH = H.subgraph(SG).copy() if len(SH) <= k: break sh_cnumber = nx.core_number(SH) sh_deg = dict(SH.degree()) min_deg = min(sh_deg.values()) SH.remove_nodes_from(n for n, d in sh_deg.items() if d == min_deg) SG = nx.k_core(G.subgraph(SH), k) else: yield SG
Example #19
Source File: test_function.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_density_selfloop(self): G = nx.Graph() G.add_edge(1,1) assert_equal(nx.density(G), 0.0) G.add_edge(1,2) assert_equal(nx.density(G), 2.0)
Example #20
Source File: test_function.py From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 | 5 votes |
def test_density(self): assert_equal(nx.density(self.G), 0.5) assert_equal(nx.density(self.DG), 0.3) G=nx.Graph() G.add_node(1) assert_equal(nx.density(G), 0.0)
Example #21
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 5 votes |
def internal_edge_density(graph, community, **kwargs): """The internal density of the community set. .. math:: f(S) = \\frac{m_S}{n_S(n_Sā1)/2} where :math:`m_S` is the number of community internal edges and :math:`n_S` is the number of community nodes. :param graph: a networkx/igraph object :param community: NodeClustering object :param summary: boolean. If **True** it is returned an aggregated score for the partition is returned, otherwise individual-community ones. Default **True**. :return: If **summary==True** a FitnessResult object, otherwise a list of floats. Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = evaluation.internal_edge_density(g,communities) :References: 1. Radicchi, F., Castellano, C., Cecconi, F., Loreto, V., & Parisi, D. (2004). Defining and identifying communities in networks. Proceedings of the National Academy of Sciences, 101(9), 2658-2663. """ return __quality_indexes(graph, community, pq.PartitionQuality.internal_edge_density, **kwargs)
Example #22
Source File: scd.py From karateclub with GNU General Public License v3.0 | 5 votes |
def _calculate_community_statistics(self, inverse_community_index): """ Calculating the community level statistics used for refinement. """ community_statistics = {} for comm, members in inverse_community_index.items(): induced_graph = self._graph.subgraph(members) size = induced_graph.number_of_nodes() density = nx.density(induced_graph) edge_out = sum([0 if neighbor in induced_graph else 1 for node in members for neighbor in self._graph.neighbors(node)]) community_statistics[comm] = {"r":size, "d": density, "b": edge_out} return community_statistics
Example #23
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_add_above_max_count_low_density(self): """Test if function does not add in a subgraph tuple of density lower than the minimum value of ``l`` when the length of ``l`` is at its maximum""" max_count = 10 l = self.l.copy() subgraph._update_subgraphs_list(l, self.t_below_min_density, max_count=max_count) assert l == self.l
Example #24
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_add_above_max_count_equal_density(self, monkeypatch): """Test if function randomly adds in a subgraph tuple with density equal to the minimum value of ``l``, even though the length of ``l`` is at its maximum. This test monkeypatches the ``np.random.choice`` call used in the function to decide whether to keep the original subgraph or add in the new one. In one case, ``np.random.choice`` is monkeypatched to leave ``l`` unchanged, and in another case ``np.random.choice`` is monkeypatched to swap the minimum value of ``l`` with ``t_min_density``.""" max_count = 10 with monkeypatch.context() as m: m.setattr(np.random, "choice", lambda x: 0) l = self.l.copy() subgraph._update_subgraphs_list(l, self.t_min_density, max_count=max_count) assert len(l) == max_count assert l == self.l with monkeypatch.context() as m: m.setattr(np.random, "choice", lambda x: 1) l = self.l.copy() subgraph._update_subgraphs_list(l, self.t_min_density, max_count=max_count) l_ideal = self.l.copy() del l_ideal[-1] l_ideal.append(self.t_min_density) assert len(l) == max_count assert l == l_ideal
Example #25
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_add_above_max_count_high_density(self): """Test if function adds subgraph tuples with density exceeding the minimum value of ``l`` even though the length of ``l`` is at its maximum""" max_count = 10 for t in self.t_above_min_density: l = self.l.copy() l_ideal = sorted(l + [t], reverse=True) subgraph._update_subgraphs_list(l, t, max_count=max_count) del l_ideal[-1] assert len(l) == max_count assert l == l_ideal
Example #26
Source File: test_subgraph.py From strawberryfields with Apache License 2.0 | 5 votes |
def test_density(self, process_planted): """Test if function returns dictionary values that are lists of tuples where the first element is the density of the subgraph specified by the second element""" assert all( [ t[0] == nx.density(g_planted.subgraph(t[1])) for l in process_planted.values() for t in l ] )
Example #27
Source File: generate.py From pyDcop with BSD 3-Clause "New" or "Revised" License | 5 votes |
def set_parser(main_subparsers): parser = main_subparsers.add_parser("generate", help="Generate Random problems") parser.set_defaults(func=run_cmd) parser.add_argument( "-c", "--correct_density", action="store_true", default=False, help='In case you use the pattern "/density=d/" (' "where d " "is a float) in the path of the output file, " "this argument helps you to correct the density " "if the generated graph has a different density." "However this rounds density to 1 decimal.", ) # parser.add_argument('-o', '--output', nargs=1, default=None, # help='Determines if the output is printed in console ' # 'or returned in the code. If not used, ' # 'the result is printed, else it is stored in the' # 'file given as argument.') subparsers = parser.add_subparsers( title="Problems", dest="problem", description="The type of problem you " "want to generate", ) # parser.set_defaults(func=run_cmd) graphcoloring.init_cli_parser(subparsers) meetingscheduling.init_cli_parser(subparsers) ising.init_cli_parser(subparsers) agents.init_cli_parser(subparsers) scenario.init_cli_parser(subparsers) parser_mixed_problem(subparsers) parser_ising_soft(subparsers) parser_iot_problem(subparsers) parser_secp(subparsers)
Example #28
Source File: fitness.py From cdlib with BSD 2-Clause "Simplified" License | 4 votes |
def modularity_density(graph, communities, **kwargs): """The modularity density is one of several propositions that envisioned to palliate the resolution limit issue of modularity based measures. The idea of this metric is to include the information about community size into the expected density of community to avoid the negligence of small and dense communities. For each community :math:`C` in partition :math:`S`, it uses the average modularity degree calculated by :math:`d(C) = d^{int(C)} ā d^{ext(C)}` where :math:`d^{int(C)}` and :math:`d^{ext(C)}` are the average internal and external degrees of :math:`C` respectively to evaluate the fitness of :math:`C` in its network. Finally, the modularity density can be calculated as follows: .. math:: Q(S) = \\sum_{C \\in S} \\frac{1}{n_C} ( \\sum_{i \\in C} k^{int}_{iC} - \\sum_{i \\in C} k^{out}_{iC}) where :math:`n_C` is the number of nodes in C, :math:`k^{int}_{iC}` is the degree of node i within :math:`C` and :math:`k^{out}_{iC}` is the deree of node i outside :math:`C`. :param graph: a networkx/igraph object :param communities: NodeClustering object :return: FitnessResult object Example: >>> from cdlib.algorithms import louvain >>> from cdlib import evaluation >>> g = nx.karate_club_graph() >>> communities = louvain(g) >>> mod = evaluation.modularity_density(g,communities) :References: 1. Li, Z., Zhang, S., Wang, R. S., Zhang, X. S., & Chen, L. (2008). `Quantitative function for community detection. <https://www.sciencedirect.com/science/article/pii/S0020025516305059/>`_ Physical review E, 77(3), 036109. """ q = 0 for community in communities.communities: c = nx.subgraph(graph, community) nc = c.number_of_nodes() dint = [] dext = [] for node in c: dint.append(c.degree(node)) dext.append(graph.degree(node) - c.degree(node)) try: q += (1 / nc) * (np.mean(dint) - np.mean(dext)) except ZeroDivisionError: pass return FitnessResult(score=q)
Example #29
Source File: engine.py From taskflow with Apache License 2.0 | 4 votes |
def validate(self): # At this point we can check to ensure all dependencies are either # flow/task provided or storage provided, if there are still missing # dependencies then this flow will fail at runtime (which we can avoid # by failing at validation time). if LOG.isEnabledFor(logging.TRACE): execution_graph = self._compilation.execution_graph LOG.trace("Validating scoping and argument visibility for" " execution graph with %s nodes and %s edges with" " density %0.3f", execution_graph.number_of_nodes(), execution_graph.number_of_edges(), nx.density(execution_graph)) missing = set() # Attempt to retain a chain of what was missing (so that the final # raised exception for the flow has the nodes that had missing # dependencies). last_cause = None last_node = None missing_nodes = 0 for atom in self._runtime.iterate_nodes(compiler.ATOMS): exec_missing = self.storage.fetch_unsatisfied_args( atom.name, atom.rebind, optional_args=atom.optional) revert_missing = self.storage.fetch_unsatisfied_args( atom.name, atom.revert_rebind, optional_args=atom.revert_optional) atom_missing = (('execute', exec_missing), ('revert', revert_missing)) for method, method_missing in atom_missing: if method_missing: cause = exc.MissingDependencies(atom, sorted(method_missing), cause=last_cause, method=method) last_cause = cause last_node = atom missing_nodes += 1 missing.update(method_missing) if missing: # For when a task is provided (instead of a flow) and that # task is the only item in the graph and its missing deps, avoid # re-wrapping it in yet another exception... if missing_nodes == 1 and last_node is self._flow: raise last_cause else: raise exc.MissingDependencies(self._flow, sorted(missing), cause=last_cause) self._validated = True
Example #30
Source File: minors.py From Carnets with BSD 3-Clause "New" or "Revised" License | 4 votes |
def _quotient_graph(G, partition, edge_relation=None, node_data=None, edge_data=None, relabel=False, create_using=None): # Each node in the graph must be in exactly one block. if any(sum(1 for b in partition if v in b) != 1 for v in G): raise NetworkXException('each node must be in exactly one block') if create_using is None: H = G.__class__() else: H = nx.empty_graph(0, create_using) # By default set some basic information about the subgraph that each block # represents on the nodes in the quotient graph. if node_data is None: def node_data(b): S = G.subgraph(b) return dict(graph=S, nnodes=len(S), nedges=S.number_of_edges(), density=density(S)) # Each block of the partition becomes a node in the quotient graph. partition = [frozenset(b) for b in partition] H.add_nodes_from((b, node_data(b)) for b in partition) # By default, the edge relation is the relation defined as follows. B is # adjacent to C if a node in B is adjacent to a node in C, according to the # edge set of G. # # This is not a particularly efficient implementation of this relation: # there are O(n^2) pairs to check and each check may require O(log n) time # (to check set membership). This can certainly be parallelized. if edge_relation is None: def edge_relation(b, c): return any(v in G[u] for u, v in product(b, c)) # By default, sum the weights of the edges joining pairs of nodes across # blocks to get the weight of the edge joining those two blocks. if edge_data is None: def edge_data(b, c): edgedata = (d for u, v, d in G.edges(b | c, data=True) if (u in b and v in c) or (u in c and v in b)) return {'weight': sum(d.get('weight', 1) for d in edgedata)} block_pairs = permutations(H, 2) if H.is_directed() else combinations(H, 2) # In a multigraph, add one edge in the quotient graph for each edge # in the original graph. if H.is_multigraph(): edges = chaini(((b, c, G.get_edge_data(u, v, default={})) for u, v in product(b, c) if v in G[u]) for b, c in block_pairs if edge_relation(b, c)) # In a simple graph, apply the edge data function to each pair of # blocks to determine the edge data attributes to apply to each edge # in the quotient graph. else: edges = ((b, c, edge_data(b, c)) for (b, c) in block_pairs if edge_relation(b, c)) H.add_edges_from(edges) # If requested by the user, relabel the nodes to be integers, # numbered in increasing order from zero in the same order as the # iteration order of `partition`. if relabel: # Can't use nx.convert_node_labels_to_integers() here since we # want the order of iteration to be the same for backward # compatibility with the nx.blockmodel() function. labels = {b: i for i, b in enumerate(partition)} H = nx.relabel_nodes(H, labels) return H