Python networkx.complement() Examples

The following are 12 code examples of networkx.complement(). 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: mixin_matching.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def find_pos_augment_edges(infr, pcc, k=None):
        """
        # [[1, 0], [0, 2], [1, 2], [3, 1]]
        pos_sub = nx.Graph([[0, 1], [1, 2], [0, 2], [1, 3]])
        """
        if k is None:
            pos_k = infr.params['redun.pos']
        else:
            pos_k = k
        pos_sub = infr.pos_graph.subgraph(pcc)

        # TODO:
        # weight by pairs most likely to be comparable

        # First try to augment only with unreviewed existing edges
        unrev_avail = list(nxu.edges_inside(infr.unreviewed_graph, pcc))
        try:
            check_edges = list(nxu.k_edge_augmentation(
                pos_sub, k=pos_k, avail=unrev_avail, partial=False))
        except nx.NetworkXUnfeasible:
            check_edges = None
        if not check_edges:
            # Allow new edges to be introduced
            full_sub = infr.graph.subgraph(pcc).copy()
            new_avail = ut.estarmap(infr.e_, nx.complement(full_sub).edges())
            full_avail = unrev_avail + new_avail
            n_max = (len(pos_sub) * (len(pos_sub) - 1)) // 2
            n_complement = n_max - pos_sub.number_of_edges()
            if len(full_avail) == n_complement:
                # can use the faster algorithm
                check_edges = list(nxu.k_edge_augmentation(
                    pos_sub, k=pos_k, partial=True))
            else:
                # have to use the slow approximate algo
                check_edges = list(nxu.k_edge_augmentation(
                    pos_sub, k=pos_k, avail=full_avail, partial=True))
        check_edges = set(it.starmap(e_, check_edges))
        return check_edges 
Example #2
Source File: mixin_helpers.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def ensure_full(infr):
        """
        Explicitly places all edges, but does not make any feedback items
        """
        infr.print('ensure_full with %d nodes' % (len(infr.graph)), 2)
        new_edges = list(nx.complement(infr.graph).edges())
        infr.ensure_edges_from(new_edges) 
Example #3
Source File: mixin_helpers.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def find_connecting_edges(infr):
        """
        Searches for a small set of edges, which if reviewed as positive would
        ensure that each PCC is k-connected.  Note that in somes cases this is
        not possible
        """
        label = 'name_label'
        node_to_label = infr.get_node_attrs(label)
        label_to_nodes = ut.group_items(node_to_label.keys(),
                                        node_to_label.values())

        # k = infr.params['redun.pos']
        k = 1
        new_edges = []
        prog = ut.ProgIter(list(label_to_nodes.keys()),
                           label='finding connecting edges',
                           enabled=infr.verbose > 0)
        for nid in prog:
            nodes = set(label_to_nodes[nid])
            G = infr.pos_graph.subgraph(nodes, dynamic=False)
            impossible = nxu.edges_inside(infr.neg_graph, nodes)
            impossible |= nxu.edges_inside(infr.incomp_graph, nodes)

            candidates = set(nx.complement(G).edges())
            candidates.difference_update(impossible)

            aug_edges = nxu.k_edge_augmentation(G, k=k, avail=candidates)
            new_edges += aug_edges
        prog.ensure_newline()
        return new_edges 
Example #4
Source File: test_kcomponents.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def setUp(self):
        self.Gnp = nx.gnp_random_graph(20,0.8)
        self.Anp = _AntiGraph(nx.complement(self.Gnp))
        self.Gd = nx.davis_southern_women_graph()
        self.Ad = _AntiGraph(nx.complement(self.Gd))
        self.Gk = nx.karate_club_graph()
        self.Ak = _AntiGraph(nx.complement(self.Gk))
        self.GA = [(self.Gnp, self.Anp),
                    (self.Gd,self.Ad),
                    (self.Gk, self.Ak)] 
Example #5
Source File: quality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def inter_community_non_edges(G, partition):
    """Returns the number of inter-community non-edges according to the
    given partition of the nodes of `G`.

    `G` must be a NetworkX graph.

    `partition` must be a partition of the nodes of `G`.

    A *non-edge* is a pair of nodes (undirected if `G` is undirected)
    that are not adjacent in `G`. The *inter-community non-edges* are
    those non-edges on a pair of nodes in different blocks of the
    partition.

    Implementation note: this function creates two intermediate graphs,
    which may require up to twice the amount of memory as required to
    store `G`.

    """
    # Alternate implementation that does not require constructing two
    # new graph objects (but does require constructing an affiliation
    # dictionary):
    #
    #     aff = dict(chain.from_iterable(((v, block) for v in block)
    #                                    for block in partition))
    #     return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v])
    #
    return inter_community_edges(nx.complement(G), partition) 
Example #6
Source File: test_kcomponents.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setUp(self):
        self.Gnp = nx.gnp_random_graph(20, 0.8)
        self.Anp = _AntiGraph(nx.complement(self.Gnp))
        self.Gd = nx.davis_southern_women_graph()
        self.Ad = _AntiGraph(nx.complement(self.Gd))
        self.Gk = nx.karate_club_graph()
        self.Ak = _AntiGraph(nx.complement(self.Gk))
        self.GA = [(self.Gnp, self.Anp),
                   (self.Gd, self.Ad),
                   (self.Gk, self.Ak)] 
Example #7
Source File: quality.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def inter_community_non_edges(G, partition):
    """Returns the number of inter-community non-edges according to the
    given partition of the nodes of `G`.

    `G` must be a NetworkX graph.

    `partition` must be a partition of the nodes of `G`.

    A *non-edge* is a pair of nodes (undirected if `G` is undirected)
    that are not adjacent in `G`. The *inter-community non-edges* are
    those non-edges on a pair of nodes in different blocks of the
    partition.

    Implementation note: this function creates two intermediate graphs,
    which may require up to twice the amount of memory as required to
    store `G`.

    """
    # Alternate implementation that does not require constructing two
    # new graph objects (but does require constructing an affiliation
    # dictionary):
    #
    #     aff = dict(chain.from_iterable(((v, block) for v in block)
    #                                    for block in partition))
    #     return sum(1 for u, v in nx.non_edges(G) if aff[u] != aff[v])
    #
    return inter_community_edges(nx.complement(G), partition) 
Example #8
Source File: test_kcomponents.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def setUp(self):
        self.Gnp = nx.gnp_random_graph(20,0.8)
        self.Anp = _AntiGraph(nx.complement(self.Gnp))
        self.Gd = nx.davis_southern_women_graph()
        self.Ad = _AntiGraph(nx.complement(self.Gd))
        self.Gk = nx.karate_club_graph()
        self.Ak = _AntiGraph(nx.complement(self.Gk))
        self.GA = [(self.Gnp, self.Anp),
                    (self.Gd,self.Ad),
                    (self.Gk, self.Ak)] 
Example #9
Source File: specialdraw.py    From ibeis with Apache License 2.0 4 votes vote down vote up
def redun_demo3():
    r"""
    python -m ibeis.scripts.specialdraw redun_demo3 --show
    python -m ibeis.scripts.specialdraw redun_demo3 --saveparts=~/slides/incon_redun.jpg --dpi=300
    """
    from ibeis.algo.graph.state import POSTV, NEGTV, INCMP  # NOQA
    from ibeis.algo.graph import demo
    from ibeis.algo.graph import nx_utils as nxu
    import plottool_ibeis as pt

    # import networkx as nx
    pt.ensureqt()
    import matplotlib as mpl
    from ibeis.scripts.thesis import TMP_RC
    mpl.rcParams.update(TMP_RC)

    fnum = 1
    showkw = dict(show_inconsistency=False, show_labels=True,
                  simple_labels=True,
                  show_recent_review=False, wavy=False,
                  groupby='name_label',
                  splines='spline',
                  show_all=True,
                  pickable=True, fnum=fnum)

    graphkw = dict(hpad=50, vpad=50, group_grid=True)
    pnum_ = pt.make_pnum_nextgen(2, 1)

    infr = demo.make_demo_infr(ccs=[(1, 2, 3, 5, 4), (6,)])
    infr.add_feedback((5, 6), evidence_decision=POSTV)
    for e in nxu.complement_edges(infr.graph):
        infr.add_feedback(e, evidence_decision=INCMP)

    infr.graph.graph.update(graphkw)
    infr.show(pnum=pnum_(), **showkw)
    ax = pt.gca()
    ax.set_aspect('equal')

    ccs = [(1, 2, 3, 4), (11, 12, 13, 14, 15)]
    infr = demo.make_demo_infr(ccs=ccs)
    infr.add_feedback((4, 14), evidence_decision=NEGTV)
    import networkx as nx
    for e in nxu.edges_between(nx.complement(infr.graph), ccs[0], ccs[1]):
        print('e = %r' % (e,))
        infr.add_feedback(e, evidence_decision=INCMP)
    infr.graph.graph.update(graphkw)
    infr.show(pnum=pnum_(), **showkw)
    ax = pt.gca()
    ax.set_aspect('equal')

    fig = pt.gcf()
    fig.set_size_inches(10 / 3, 5)

    ut.show_if_requested() 
Example #10
Source File: clique.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def max_clique(G):
    r"""Find the Maximum Clique

    Finds the `O(|V|/(log|V|)^2)` apx of maximum clique/independent set
    in the worst case.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    clique : set
        The apx-maximum clique of the graph

    Notes
    ------
    A clique in an undirected graph G = (V, E) is a subset of the vertex set
    `C \subseteq V`, such that for every two vertices in C, there exists an edge
    connecting the two. This is equivalent to saying that the subgraph
    induced by C is complete (in some cases, the term clique may also refer
    to the subgraph).

    A maximum clique is a clique of the largest possible size in a given graph.
    The clique number `\omega(G)` of a graph G is the number of
    vertices in a maximum clique in G. The intersection number of
    G is the smallest number of cliques that together cover all edges of G.

    http://en.wikipedia.org/wiki/Maximum_clique

    References
    ----------
    .. [1] Boppana, R., & Halldórsson, M. M. (1992).
        Approximating maximum independent sets by excluding subgraphs.
        BIT Numerical Mathematics, 32(2), 180–196. Springer.
        doi:10.1007/BF01994876
    """
    if G is None:
        raise ValueError("Expected NetworkX graph!")

    # finding the maximum clique in a graph is equivalent to finding
    # the independent set in the complementary graph
    cgraph = nx.complement(G)
    iset, _ = clique_removal(cgraph)
    return iset 
Example #11
Source File: clique.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def max_clique(G):
    r"""Find the Maximum Clique

    Finds the $O(|V|/(log|V|)^2)$ apx of maximum clique/independent set
    in the worst case.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    clique : set
        The apx-maximum clique of the graph

    Notes
    ------
    A clique in an undirected graph G = (V, E) is a subset of the vertex set
    `C \subseteq V` such that for every two vertices in C there exists an edge
    connecting the two. This is equivalent to saying that the subgraph
    induced by C is complete (in some cases, the term clique may also refer
    to the subgraph).

    A maximum clique is a clique of the largest possible size in a given graph.
    The clique number `\omega(G)` of a graph G is the number of
    vertices in a maximum clique in G. The intersection number of
    G is the smallest number of cliques that together cover all edges of G.

    https://en.wikipedia.org/wiki/Maximum_clique

    References
    ----------
    .. [1] Boppana, R., & Halldórsson, M. M. (1992).
        Approximating maximum independent sets by excluding subgraphs.
        BIT Numerical Mathematics, 32(2), 180–196. Springer.
        doi:10.1007/BF01994876
    """
    if G is None:
        raise ValueError("Expected NetworkX graph!")

    # finding the maximum clique in a graph is equivalent to finding
    # the independent set in the complementary graph
    cgraph = nx.complement(G)
    iset, _ = clique_removal(cgraph)
    return iset 
Example #12
Source File: clique.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def max_clique(G):
    r"""Find the Maximum Clique

    Finds the $O(|V|/(log|V|)^2)$ apx of maximum clique/independent set
    in the worst case.

    Parameters
    ----------
    G : NetworkX graph
        Undirected graph

    Returns
    -------
    clique : set
        The apx-maximum clique of the graph

    Notes
    ------
    A clique in an undirected graph G = (V, E) is a subset of the vertex set
    `C \subseteq V`, such that for every two vertices in C, there exists an edge
    connecting the two. This is equivalent to saying that the subgraph
    induced by C is complete (in some cases, the term clique may also refer
    to the subgraph).

    A maximum clique is a clique of the largest possible size in a given graph.
    The clique number `\omega(G)` of a graph G is the number of
    vertices in a maximum clique in G. The intersection number of
    G is the smallest number of cliques that together cover all edges of G.

    https://en.wikipedia.org/wiki/Maximum_clique

    References
    ----------
    .. [1] Boppana, R., & Halldórsson, M. M. (1992).
        Approximating maximum independent sets by excluding subgraphs.
        BIT Numerical Mathematics, 32(2), 180–196. Springer.
        doi:10.1007/BF01994876
    """
    if G is None:
        raise ValueError("Expected NetworkX graph!")

    # finding the maximum clique in a graph is equivalent to finding
    # the independent set in the complementary graph
    cgraph = nx.complement(G)
    iset, _ = clique_removal(cgraph)
    return iset