Python networkx 模块,number_connected_components() 实例源码

我们从Python开源项目中,提取了以下8个代码示例,用于说明如何使用networkx.number_connected_components()

项目:ohmnet    作者:marinkaz    | 项目源码 | 文件源码
def read_net(fname, weighted, directed, log):
    if weighted:
        G = nx.read_edgelist(inodetype=int, data=(('weight', float),),
                             create_using=nx.DiGraph())
    else:
        G = nx.read_edgelist(fname, nodetype=int, create_using=nx.DiGraph())
        for edge in G.edges():
            G[edge[0]][edge[1]]['weight'] = 1

    if not directed:
        G = G.to_undirected()

    log.info('N: %d E: %d' % (G.number_of_nodes(), G.number_of_edges()))
    log.info('CC: %d' % nx.number_connected_components(G))
    giant = max(nx.connected_component_subgraphs(G), key=len)
    log.info('N: %d E: %d' % (giant.number_of_nodes(), giant.number_of_edges()))
    return giant
项目:WNTR    作者:USEPA    | 项目源码 | 文件源码
def bridges(self):
        """
        Get bridge links. Uses an undirected graph.

        Parameters
        ----------
        G : graph
            A networkx graph

        Returns
        -------
        bridges : list
            list of link indexes
        """
        n = nx.number_connected_components(self.to_undirected())
        bridges = []
        for (node1, node2, link_name) in list(self.edges(keys=True)):
            # if node1 and node2 have a neighbor in common, no bridge
            if len(set(self.neighbors(node1)) & set(self.neighbors(node2))) == 0:
                self.remove_edge(node1, node2, key=link_name)
                if nx.number_connected_components(self.to_undirected()) > n:
                    bridges.append(link_name)
                self.add_edge(node1, node2, key=link_name)

        return bridges
项目:graphpca    作者:brandones    | 项目源码 | 文件源码
def reduce_graph(nx_graph, output_dim):
    """
    Run PCA on the ETCD of the input NetworkX graph

    The best algorithm and parameters for doing so are selected dynamically,
    based on the size of the graph. A graph G with number of nodes n < 50 will
    use the naive algorithm, reduce_graph_naively, which has more stable
    behaviour at low node counts. Above that will use reduce_graph_efficiently.
    For such graphs the connectivity is checked, and if the graph has
    20 or more connected components we use the add_supernode trick.

    Parameters
    ----------
    nx_graph : :class:`nx.Graph` or :class:`nx.DiGraph`
        The graph to be reduced
    output_dim : int
        The number of dimensions to reduce to
    """
    if len(nx_graph) < 50:
        return reduce_graph_naively(nx_graph, output_dim)
    else:
        nullity = nx.number_connected_components(nx_graph)
        if nullity < 20:
            return reduce_graph_efficiently(nx_graph, output_dim, add_supernode=False)
        else:
            return reduce_graph_efficiently(nx_graph, output_dim, add_supernode=True)
项目:BrainModulyzer    作者:sugeerth    | 项目源码 | 文件源码
def ModularityBehaviour(self):
        Number_of_Connected_Components = dict()
        Number_of_Communities = dict()
        modularity = dict()
        start= int(self.correlationTable().data.min()*1000)
        end = int(self.correlationTable().data.max()*1000)
        g1 = self.Graphwidget.Graph_data().DrawHighlightedGraph(self.Graphwidget.EdgeSliderValue)
        # counter = 0.225
        partition=cm.best_partition(g1)
        Number_of_Communitie = len(set(partition.values()))

        for i in range(0,end):
            counter = float(i)/1000
            g1 =  self.Graphwidget.Graph_data().DrawHighlightedGraph(counter)
            try: 
                partition=cm.best_partition(g1)
                modularity[i] = cm.modularity(partition, g1)
                Number_of_Connected_Components[i] = nx.number_connected_components(g1)
                Number_of_Communities[i] = len(set(partition.values()))
            except AttributeError:
                continue

        f=open("modularity.txt", "wb")
        w = csv.writer(f)
        for key, val in modularity.items():
            w.writerow([key, val])
        f.close()

        f=open("number_connected_components.txt", "wb")
        w = csv.writer(f)
        for key, val in Number_of_Connected_Components.items():
            w.writerow([key, val])
        f.close()

        f=open("Number_of_Communities.txt", "wb")
        w = csv.writer(f)
        for key, val in Number_of_Communities.items():
            w.writerow([key, val])
        f.close()
项目:visa_free    作者:BBischof    | 项目源码 | 文件源码
def communitySplits(self, graph, weight=None):
        """
        Compute the splits for the formation of communities. 

        Parameters
        ----------
        graph -  A networkx graph of digraph.
        weight (string) - If None, all edge weights are considered equal. 
            Otherwise holds the name of the edge attribute used as weight


        Returns
        -------
        The graph with weak edges removed. 


        Usage
        -----
        >>> G = nx.path_graph(10)
        >>> out = GirvanNewman(G)
        >>> comm = out.communities(G, weight=None)
        >>> for x in comm:
                print x
        """

        nConnComp = nx.number_connected_components(graph)
        nComm = nConnComp

        while (nComm <= nConnComp):
            betweenness = nx.edge_betweenness_centrality(graph, weight=weight)
            if (len(betweenness.values()) != 0 ):
                max_betweenness = max(betweenness.values())
            else:
                break   
            for u,v in betweenness.iteritems():
                if float(v) == max_betweenness:
                    # print u,v
                    graph.remove_edge(u[0], u[1])
            nComm = nx.number_connected_components(graph)           
        return graph
项目:visa_free    作者:BBischof    | 项目源码 | 文件源码
def communities(self, nCommunities, weight=None):
        """
        Compute communities.

        Parameters
        ----------
        nCommunities - number of communities to be returned.
            This is added to simplify the process, the original GN algorithm doesn't 
            need predecided number of communities. 
            Other measures like a threshold on betweenness centrality can be used instead.

        weight (string) - If None, all edge weights are considered equal. 
            Otherwise holds the name of the edge attribute used as weight. 


        Returns
        --------
        A list of communities where each community is a list of the nodes in the community.  
        """
        gr = self.g
        n = nx.number_connected_components(gr)
        components = nx.connected_components(gr)

        while (n < nCommunities):
            gr = self.communitySplits(gr, weight=weight)
            components = nx.connected_components(gr)
            n = nx.number_connected_components(gr)
            if gr.number_of_edges() == 0:
                break
        return components
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def connectGraphComponents(graph, level=2, highway='path', connectNearest=False):
    if nx.is_connected(graph):
        return graph

    combinations = itertools.permutations(range(nx.number_connected_components(graph)),2)

    subgraphs = list(nx.connected_component_subgraphs(graph, copy=True))
    rtrees = [getGraphRtree(subgraph,'nodes') for subgraph in subgraphs]

    nearestComponents={}
    for i, j in combinations:
        if i not in nearestComponents:
            nearestComponents[i] = []
        smallest = i if len(subgraphs[i]) < len(subgraphs[j]) else j
        biggest = j if smallest is i else i
        candidates = {}
        nearestNeighbors = {}

        for node1, data in subgraphs[smallest].nodes(data=True):
            x, y = data['longitude'], data['latitude']
            hits = list(rtrees[biggest].nearest((x, y, x, y), 2, objects="raw"))
            for candidate in hits:
                data = json.loads(candidate)
                candidates[data['id']] = Point(data['geometry']['coordinates'])
            source = Point([x,y])
            distance, node2 = nearestNode(source, candidates)
            nearestNeighbors[distance] = node1, node2
            u,v = nearestNeighbors[min(nearestNeighbors.keys())]

        if connectNearest:
            nearestComponents[i].append((j, min(nearestNeighbors.keys()), (u,v)))
        else:
            newAttributes = {'level':level, 'highway': highway,'osmid':'-1','policosm':True, 'lanes':1,'oneway': False}
            graph.add_edge(u, v, newAttributes)

    if connectNearest:
        for i in nearestComponents.keys():
            data = nearestComponents[i]
            j, distance, (u,v) = sorted(data, key=lambda tup: tup[1])[0]

            if not graph.has_edge(u, v):
                newAttributes = {'level':level, 'highway': highway,'osmid':'-1','policosm':True, 'lanes':1,'oneway': False}
                graph.add_edge(u, v, newAttributes)
    return connectGraphComponents(graph, level, highway, connectNearest=connectNearest)
项目:policosm    作者:ComplexCity    | 项目源码 | 文件源码
def connectGraphComponents(graph, level=2, highway='path', connectNearest=False):
    if nx.is_connected(graph):
        return graph

    combinations = itertools.permutations(range(nx.number_connected_components(graph)),2)

    subgraphs = list(nx.connected_component_subgraphs(graph, copy=True))
    rtrees = [getGraphRtree(subgraph,'nodes') for subgraph in subgraphs]

    nearestComponents={}
    for i, j in combinations:
        if i not in nearestComponents:
            nearestComponents[i] = []
        smallest = i if len(subgraphs[i]) < len(subgraphs[j]) else j
        biggest = j if smallest is i else i
        candidates = {}
        nearestNeighbors = {}

        for node1, data in subgraphs[smallest].nodes(data=True):
            x, y = data['longitude'], data['latitude']
            hits = list(rtrees[biggest].nearest((x, y, x, y), 2, objects="raw"))
            for candidate in hits:
                data = json.loads(candidate)
                candidates[data['id']] = Point(data['geometry']['coordinates'])
            source = Point([x,y])
            distance, node2 = nearestNode(source, candidates)
            nearestNeighbors[distance] = node1, node2
            u,v = nearestNeighbors[min(nearestNeighbors.keys())]

        if connectNearest:
            nearestComponents[i].append((j, min(nearestNeighbors.keys()), (u,v)))
        else:
            newAttributes = {'level':level, 'highway': highway,'osmid':'-1','policosm':True, 'lanes':1,'oneway': False}
            graph.add_edge(u, v, newAttributes)

    if connectNearest:
        for i in nearestComponents.keys():
            data = nearestComponents[i]
            j, distance, (u,v) = sorted(data, key=lambda tup: tup[1])[0]

            if not graph.has_edge(u, v):
                newAttributes = {'level':level, 'highway': highway,'osmid':'-1','policosm':True, 'lanes':1,'oneway': False}
                graph.add_edge(u, v, newAttributes)
    return connectGraphComponents(graph, level, highway, connectNearest=connectNearest)