簡體   English   中英

關於用.networkx畫圖的問題

[英]Question about Drawing a graph with networkx

我正在使用 NetworkX 繪制圖形,當我在 NetworkX 文檔中搜索時,我看到 Antigraph class 中的一段代碼令人困惑,我無法理解這段代碼的某些行。 請幫助我理解這段代碼。

我附上了這段代碼:

import networkx as nx
from networkx.exception import NetworkXError
import matplotlib.pyplot as plt


class AntiGraph(nx.Graph):
    """
    Class for complement graphs.

    The main goal is to be able to work with big and dense graphs with
    a low memory footprint.

    In this class you add the edges that *do not exist* in the dense graph,
    the report methods of the class return the neighbors, the edges and
    the degree as if it was the dense graph. Thus it's possible to use
    an instance of this class with some of NetworkX functions.
    """

    all_edge_dict = {"weight": 1}

    def single_edge_dict(self):
        return self.all_edge_dict

    edge_attr_dict_factory = single_edge_dict

    def __getitem__(self, n):
        """Return a dict of neighbors of node n in the dense graph.

        Parameters
        ----------
        n : node
           A node in the graph.

        Returns
        -------
        adj_dict : dictionary
           The adjacency dictionary for nodes connected to n.

        """
        return {
            node: self.all_edge_dict for node in set(self.adj) - set(self.adj[n]) - {n}
        }

    def neighbors(self, n):
        """Return an iterator over all neighbors of node n in the
           dense graph.

        """
        try:
            return iter(set(self.adj) - set(self.adj[n]) - {n})
        except KeyError as e:
            raise NetworkXError(f"The node {n} is not in the graph.") from e

    def degree(self, nbunch=None, weight=None):
        """Return an iterator for (node, degree) in the dense graph.

        The node degree is the number of edges adjacent to the node.

        Parameters
        ----------
        nbunch : iterable container, optional (default=all nodes)
            A container of nodes.  The container will be iterated
            through once.

        weight : string or None, optional (default=None)
           The edge attribute that holds the numerical value used
           as a weight.  If None, then each edge has weight 1.
           The degree is the sum of the edge weights adjacent to the node.

        Returns
        -------
        nd_iter : iterator
            The iterator returns two-tuples of (node, degree).

        See Also
        --------
        degree

        Examples
        --------
        >>> G = nx.path_graph(4)  # or DiGraph, MultiGraph, MultiDiGraph, etc
        >>> list(G.degree(0))  # node 0 with degree 1
        [(0, 1)]
        >>> list(G.degree([0, 1]))
        [(0, 1), (1, 2)]

        """
        if nbunch is None:
            nodes_nbrs = (
                (
                    n,
                    {
                        v: self.all_edge_dict
                        for v in set(self.adj) - set(self.adj[n]) - {n}
                    },
                )
                for n in self.nodes()
            )
        elif nbunch in self:
            nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}
            return len(nbrs)
        else:
            nodes_nbrs = (
                (
                    n,
                    {
                        v: self.all_edge_dict
                        for v in set(self.nodes()) - set(self.adj[n]) - {n}
                    },
                )
                for n in self.nbunch_iter(nbunch)
            )

        if weight is None:
            return ((n, len(nbrs)) for n, nbrs in nodes_nbrs)
        else:
            # AntiGraph is a ThinGraph so all edges have weight 1
            return (
                (n, sum((nbrs[nbr].get(weight, 1)) for nbr in nbrs))
                for n, nbrs in nodes_nbrs
            )

    def adjacency_iter(self):
        """Return an iterator of (node, adjacency set) tuples for all nodes
           in the dense graph.

        This is the fastest way to look at every edge.
        For directed graphs, only outgoing adjacencies are included.

        Returns
        -------
        adj_iter : iterator
           An iterator of (node, adjacency set) for all nodes in
           the graph.

        """
        for n in self.adj:
            yield (n, set(self.adj) - set(self.adj[n]) - {n})


# Build several pairs of graphs, a regular graph
# and the AntiGraph of it's complement, which behaves
# as if it were the original graph.
Gnp = nx.gnp_random_graph(20, 0.8, seed=42)
Anp = AntiGraph(nx.complement(Gnp))
Gd = nx.davis_southern_women_graph()
Ad = AntiGraph(nx.complement(Gd))
Gk = nx.karate_club_graph()
Ak = AntiGraph(nx.complement(Gk))
pairs = [(Gnp, Anp), (Gd, Ad), (Gk, Ak)]
# test connected components
for G, A in pairs:
    gc = [set(c) for c in nx.connected_components(G)]
    ac = [set(c) for c in nx.connected_components(A)]
    for comp in ac:
        assert comp in gc
# test biconnected components
for G, A in pairs:
    gc = [set(c) for c in nx.biconnected_components(G)]
    ac = [set(c) for c in nx.biconnected_components(A)]
    for comp in ac:
        assert comp in gc
# test degree
for G, A in pairs:
    node = list(G.nodes())[0]
    nodes = list(G.nodes())[1:4]
    assert G.degree(node) == A.degree(node)
    assert sum(d for n, d in G.degree()) == sum(d for n, d in A.degree())
    # AntiGraph is a ThinGraph, so all the weights are 1
    assert sum(d for n, d in A.degree()) == sum(d for n, d in A.degree(weight="weight"))
    assert sum(d for n, d in G.degree(nodes)) == sum(d for n, d in A.degree(nodes))

nx.draw(Gnp)
plt.show()

我無法理解這兩行:

(1) for v in set(self.adj) - set(self.adj[n]) - {n}

(2) nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}

要理解這些行,讓我們仔細分解每個術語。 出於解釋的目的,我將創建以下圖表:

import networkx as nx

source = [1, 2, 3, 4, 2, 3]
dest = [2, 3, 4, 6, 5, 5]
edge_list = [(u, v) for u, v in zip(source, dest)]

G = nx.Graph()

G.add_edges_from(ed_ls)

該圖具有以下邊:

print(G.edges())
# EdgeView([(1, 2), (2, 3), (2, 5), (3, 4), (3, 5), (4, 6)])

現在讓我們理解上面代碼中的術語:

設置(self.adj)
如果我們打印出來,我們可以看到它是圖中的節點集:

print(set(self.adj))
# {1, 2, 3, 4, 5, 6}

設置(self.adj[n])
這是與節點n相鄰的節點集:

print(set(G.adj[2]))
# {1, 3, 5}

現在讓我們看看您在問題中提出的第一行

for v in set(self.adj) - set(self.adj[n]) - {n}

這可以翻譯如下:

for v in set of all nodes - set of nodes adjacent to node N - node N

因此,這set of all nodes - set of nodes adjacent to node N N相鄰的節點集(這包括節點N本身)。 (本質上這將創建圖形的補充)。

讓我們看一個例子:

nodes_nbrs = (
                (
                    n,
                    {
                        v: {'weight': 1}
                        for v in set(G.adj) - set(G.adj[n]) - {n}
                    },
                )
                for n in G.nodes()
            )

這將具有以下值:

Node 1: {3: {'weight': 1}, 4: {'weight': 1}, 5: {'weight': 1}, 6: {'weight': 1}}
Node 2: {4: {'weight': 1}, 6: {'weight': 1}}
Node 3: {1: {'weight': 1}, 6: {'weight': 1}}
Node 4: {1: {'weight': 1}, 2: {'weight': 1}, 5: {'weight': 1}}
Node 6: {1: {'weight': 1}, 2: {'weight': 1}, 3: {'weight': 1}, 5: {'weight': 1}}
Node 5: {1: {'weight': 1}, 4: {'weight': 1}, 6: {'weight': 1}}

因此,如果您仔細觀察,對於每個節點,我們都會得到一個不與該節點相鄰的節點列表。

例如,節點 2,計算看起來像這樣:

{1, 2, 3, 4, 5, 6} - {1, 3, 5} - {2} = {4, 6}

現在讓我們來到第二行:

nbrs = set(self.nodes()) - set(self.adj[nbunch]) - {nbunch}

這里set(self.adj[nbunch])基本上是與nbunch中的節點相鄰的節點集。 nbunch只不過是節點的迭代器,所以我們獲取單個節點的鄰居的地方不是 set(self.adj[n]),而是多個節點的鄰居。

所以表達式可以翻譯為: Set of all nodes - Set of all nodes adjacent to each node in nbunch - Set of nodes in nbunch

這與您詢問的第一個表達式相同,只是這個表達式用於多個節點,即這還將返回與 nbunch 中的節點不相鄰的節點列表

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM