Python networkx.number_connected_components() Examples

The following are 29 code examples of networkx.number_connected_components(). 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: utility.py    From ohmnet with MIT License 6 votes vote down vote up
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 
Example #2
Source File: split_train_test.py    From EvalNE with MIT License 6 votes vote down vote up
def _sanity_check(G):
    r"""
    Helper function that checks if the input graphs contains a single connected component. Raises an error if not.

    Parameters
    ----------
    G : graph
       A NetworkX graph

    Raises
    ------
    ValueError
        If the graph has more than one (weakly) connected component.
    """
    # Compute the number of connected components
    if G.is_directed():
        num_ccs = nx.number_weakly_connected_components(G)
    else:
        num_ccs = nx.number_connected_components(G)

    # Rise an error if more than one CC exists
    if num_ccs != 1:
        raise ValueError("Input graph should contain one (weakly) connected component. "
                         "This graph contains: " + str(num_ccs)) 
Example #3
Source File: centrality.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def _without_most_central_edges(G, most_valuable_edge):
    """Returns the connected components of the graph that results from
    repeatedly removing the most "valuable" edge in the graph.

    `G` must be a non-empty graph. This function modifies the graph `G`
    in-place; that is, it removes edges on the graph `G`.

    `most_valuable_edge` is a function that takes the graph `G` as input
    (or a subgraph with one or more edges of `G` removed) and returns an
    edge. That edge will be removed and this process will be repeated
    until the number of connected components in the graph increases.

    """
    original_num_components = nx.number_connected_components(G)
    num_new_components = original_num_components
    while num_new_components <= original_num_components:
        edge = most_valuable_edge(G)
        G.remove_edge(*edge)
        new_components = tuple(nx.connected_components(G))
        num_new_components = len(new_components)
    return new_components 
Example #4
Source File: genetic_algorithm.py    From graph_adversarial_attack with MIT License 6 votes vote down vote up
def get_fitness(self):
        g_list = []
        g = self.s2v_g.to_networkx()
        for edges in self.population:
            g2 = g.copy()
            g2.add_edge(edges[0][0], edges[0][1])
    #        g2.add_edges_from(edges)
            assert nx.number_connected_components(g2) == self.s2v_g.label
            g_list.append(S2VGraph(g2, self.s2v_g.label))

        log_ll, _, acc = self.classifier(g_list)
        acc = acc.cpu().double().numpy()
        if self.solution is None:
            for i in range(len(self.population)):
                if acc[i] < 1.0:
                    self.solution = self.population[i]
                    break
        nll = -log_ll[:, self.classifier.label_map[self.s2v_g.label]]
        return nll 
Example #5
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 6 votes vote down vote up
def test_plot_three_connected(self):
        self.a.plot(['a','c','qqqq'])
        self.check_subgraph()

        # No islands
        ni = nx.number_connected_components(self.a.dispG)
        self.assertEqual(ni, 1)

        # Make sure the path that conects the a,c group to qqqq
        #  is displayed (ie, node 11 and TTTT are in the graph
        node_11 = self.a._find_disp_node(11)
        TTTTT = self.a._find_disp_node('TTTTT')
        self.assertIsNot(node_11, None)
        self.assertIsNot(TTTTT, None)

        self.check_num_nodes_edges(9, 11) 
Example #6
Source File: centrality.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _without_most_central_edges(G, most_valuable_edge):
    """Returns the connected components of the graph that results from
    repeatedly removing the most "valuable" edge in the graph.

    `G` must be a non-empty graph. This function modifies the graph `G`
    in-place; that is, it removes edges on the graph `G`.

    `most_valuable_edge` is a function that takes the graph `G` as input
    (or a subgraph with one or more edges of `G` removed) and returns an
    edge. That edge will be removed and this process will be repeated
    until the number of connected components in the graph increases.

    """
    original_num_components = nx.number_connected_components(G)
    num_new_components = original_num_components
    while num_new_components <= original_num_components:
        edge = most_valuable_edge(G)
        G.remove_edge(*edge)
        new_components = tuple(nx.connected_components(G))
        num_new_components = len(new_components)
    return new_components 
Example #7
Source File: test_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_number_connected_components2(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.grid), 1) 
Example #8
Source File: mst.py    From PyRate with Apache License 2.0 5 votes vote down vote up
def mst_from_ifgs(ifgs):
    """
    Returns a Minimum Spanning Tree (MST) network from the given interferograms
    using Kruskal's algorithm. The MST is calculated using a weighting based
    on the number of NaN cells in the phase band.

    :param list ifgs: List of interferogram objects (Ifg class)

    :return: edges: The number of network connections
    :rtype: int
    :return: is_tree: A boolean that is True if network is a tree
    :rtype: bool
    :return: ntrees: The number of disconnected trees
    :rtype: int
    :return: mst_ifgs: Minimum Spanning Tree network of interferograms
    :rtype: list
    """

    edges_with_weights_for_networkx = [(i.master, i.slave, i.nan_fraction)
                                       for i in ifgs]
    g_nx = _build_graph_networkx(edges_with_weights_for_networkx)
    mst = nx.minimum_spanning_tree(g_nx)
    # mst_edges, is tree?, number of trees
    edges = mst.edges()
    ifg_sub = [ifg_date_index_lookup(ifgs, d) for d in edges]
    mst_ifgs = [i for k, i in enumerate(ifgs) if k in ifg_sub]
    return mst.edges(), nx.is_tree(mst), \
        nx.number_connected_components(mst), mst_ifgs 
Example #9
Source File: test_weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_number_weakly_connected_components(self):
        for G, C in self.gc:
            U = G.to_undirected()
            w = nx.number_weakly_connected_components(G)
            c = nx.number_connected_components(U)
            assert_equal(w, c) 
Example #10
Source File: test_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_connected_raise(self):
        assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG)
        assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG,1)
        assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph()) 
Example #11
Source File: test_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_number_connected_components2(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.grid), 1) 
Example #12
Source File: test_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_number_connected_components(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.G), 3) 
Example #13
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_connected_raise(self):
        assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG, 1)
        assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph())
        # deprecated
        assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG) 
Example #14
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_number_connected_components2(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.grid), 1) 
Example #15
Source File: test_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_number_connected_components(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.G), 3) 
Example #16
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dimensionality(self):
        # checks |MCB|=|E|-|V|+|NC|
        ntrial = 10
        for _ in range(ntrial):
            rg = nx.erdos_renyi_graph(10, 0.3)
            nnodes = rg.number_of_nodes()
            nedges = rg.number_of_edges()
            ncomp = nx.number_connected_components(rg)

            dim_mcb = len(minimum_cycle_basis(rg))
            assert_equal(dim_mcb, nedges - nnodes + ncomp) 
Example #17
Source File: test_weakly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_number_weakly_connected_components(self):
        for G, C in self.gc:
            U = G.to_undirected()
            w = nx.number_weakly_connected_components(G)
            c = nx.number_connected_components(U)
            assert_equal(w, c) 
Example #18
Source File: test_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_connected_raise(self):
        assert_raises(NetworkXNotImplemented, nx.connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.number_connected_components, self.DG)
        assert_raises(NetworkXNotImplemented, nx.connected_component_subgraphs, self.DG)
        assert_raises(NetworkXNotImplemented, nx.node_connected_component, self.DG,1)
        assert_raises(NetworkXNotImplemented, nx.is_connected, self.DG)
        assert_raises(nx.NetworkXPointlessConcept, nx.is_connected, nx.Graph()) 
Example #19
Source File: test_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_number_connected_components(self):
        ncc = nx.number_connected_components
        assert_equal(ncc(self.G), 3) 
Example #20
Source File: rl_common.py    From graph_adversarial_attack with MIT License 5 votes vote down vote up
def attackable(classifier, s2v_g, x = None, y = None):
    g = s2v_g.to_networkx()
    comps = [c for c in nx.connected_component_subgraphs(g)]
    set_id = {}

    for i in range(len(comps)):
        for j in comps[i].nodes():
            set_id[j] = i
    
    if x is not None:
        r_i = [x]
    else:
        r_i = range(len(g) - 1)

    g_list = []    
    for i in r_i:
        if y is not None:
            assert x is not None
            r_j = [y]
        else:
            if x is not None:
                r_j = range(len(g) - 1)
            else:
                r_j = range(i + 1, len(g))
        for j in r_j:
            if set_id[i] != set_id[j]:
                continue
            g2 = g.copy()
            g2.add_edge(i, j)
            assert nx.number_connected_components(g2) == s2v_g.label
            g_list.append(S2VGraph(g2, s2v_g.label))
    if len(g_list) == 0:
        print(x, y)
        print(g.edges(), s2v_g.label)
        print(set_id)
    assert len(g_list)
    _, _, acc = classifier(g_list)

    return np.sum(acc.view(-1).numpy()) < len(g_list) 
Example #21
Source File: evaluate.py    From GrowingNeuralGas with MIT License 5 votes vote down vote up
def evaluate_on_digits():
    digits = datasets.load_digits()
    data = digits.data
    target = digits.target
    gng = GrowingNeuralGas(data)
    gng.fit_network(e_b=0.05, e_n=0.006, a_max=8, l=100, a=0.5, d=0.995, passes=5, plot_evolution=False)
    clustered_data = gng.cluster_data()
    print('Found %d clusters.' % nx.number_connected_components(gng.network))
    target_infered = []
    for observation, cluster in clustered_data:
        target_infered.append(cluster)
    homogeneity = metrics.homogeneity_score(target, target_infered)
    print(homogeneity)
    gng.plot_clusters(gng.reduce_dimension(gng.cluster_data())) 
Example #22
Source File: gng.py    From GrowingNeuralGas with MIT License 5 votes vote down vote up
def plot_clusters(self, clustered_data):
        number_of_clusters = nx.number_connected_components(self.network)
        plt.clf()
        plt.title('Cluster affectation')
        color = ['r', 'b', 'g', 'k', 'm', 'r', 'b', 'g', 'k', 'm']
        for i in range(number_of_clusters):
            observations = [observation for observation, s in clustered_data if s == i]
            if len(observations) > 0:
                observations = np.array(observations)
                plt.scatter(observations[:, 0], observations[:, 1], color=color[i], label='cluster #'+str(i))
        plt.legend()
        plt.savefig('visualization/clusters.png') 
Example #23
Source File: gng.py    From GrowingNeuralGas with MIT License 5 votes vote down vote up
def number_of_clusters(self):
        return nx.number_connected_components(self.network) 
Example #24
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def test_add_to_plot_without_path2(self):
        # Test adding nodes around qqqq but because our levels is so big, we
        #  should just connect to the existing graph (no prompt)
        self.display_a()

        with patch(ASKYESNO_FUNC) as prompt:
            self.a.plot_additional(set(['qqqq']), levels=2)

        self.assertFalse(prompt.called) # We should not prompt
        self.check_subgraph()
        self.check_num_nodes_edges(9, 11)
        # All connected together
        self.assertEqual(nx.number_connected_components(self.a.dispG), 1) 
Example #25
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def test_add_to_plot_without_path(self):
        # Test adding nodes around qqqq to a display but as an island
        self.display_a()

        with patch(ASKYESNO_FUNC) as prompt:
            prompt.return_value = False      # No, we don't want to include path
            self.a.plot_additional(set(['qqqq']), levels=1)

        self.assertTrue(prompt.called)
        self.check_subgraph()
        self.check_num_nodes_edges(8, 9)
        # There are two islands
        self.assertEqual(nx.number_connected_components(self.a.dispG), 2) 
Example #26
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def test_add_to_plot_with_path(self):
        # Test adding nodes around qqqq to a display showing nodes around a
        self.display_a()

        with patch(ASKYESNO_FUNC) as prompt:
            prompt.return_value = True      # Yes, we want to include path
            self.a.plot_additional(set(['qqqq']), levels=1)

        self.assertTrue(prompt.called)
        self.check_subgraph()
        self.check_num_nodes_edges(9, 11)
        # All connected together
        self.assertEqual(nx.number_connected_components(self.a.dispG), 1) 
Example #27
Source File: tests.py    From networkx_viewer with GNU General Public License v3.0 5 votes vote down vote up
def test_plot_three_no_connection(self):
        self.a.plot(['a','qqqq','alone'])

        # There should be two islands (a-11-TTTTT-qqqq and alone)
        ni = nx.number_connected_components(self.a.dispG)
        self.assertEqual(ni, 2)

        # a and qqqq should be connected via 11 and TTTTT
        self.check_num_nodes_edges(9, 9)
        node_11 = self.a._find_disp_node(11)
        TTTTT = self.a._find_disp_node('TTTTT')
        self.assertIsNot(node_11, None)
        self.assertIsNot(TTTTT, None) 
Example #28
Source File: test_spantree.py    From EvalNE with MIT License 4 votes vote down vote up
def test_split():
    # Variables
    dataset_path = "./data/"
    test_name = "network.edgelist"

    # Load a graph
    SG = pp.load_graph(dataset_path + test_name, delimiter=",", comments='#', directed=False)

    # Preprocess the graph
    SG, ids = pp.prep_graph(SG, relabel=True, del_self_loops=True)
    print("Number of CCs input: {}".format(nx.number_connected_components(SG)))

    # Store the edges in the graphs as a set E
    E = set(SG.edges())

    # Use LERW approach to get the ST
    start = time.time()
    train_lerw = stt.wilson_alg(SG, E)
    end1 = time.time() - start

    # Use BRO approach to get the ST
    start = time.time()
    train_bro = stt.broder_alg(SG, E)
    end2 = time.time() - start

    print("LERW time: {}".format(end1))
    print("Bro time: {}".format(end2))

    print("Num tr_e lerw: {}".format(len(train_lerw)))
    print("Num tr_e bro: {}".format(len(train_bro)))

    print("All tr_e in E for lerw?: {}".format(train_lerw - E))
    print("All tr_e in E for bro?: {}".format(train_bro - E))

    # Check that the graph generated with lerw has indeed one single cc
    TG_lerw = nx.Graph()
    TG_lerw.add_edges_from(train_lerw)
    print("Number of CCs with lerw: {}".format(nx.number_connected_components(TG_lerw)))

    # Check that the graph generated with broder algorithm has indeed one single cc
    TG_bro = nx.Graph()
    TG_bro.add_edges_from(train_bro)
    print("Number of CCs with lerw: {}".format(nx.number_connected_components(TG_bro))) 
Example #29
Source File: graph_canvas.py    From networkx_viewer with GNU General Public License v3.0 4 votes vote down vote up
def plot_additional(self, home_nodes, levels=0):
        """Add nodes to existing plot.  Prompt to include link to existing
        if possible.  home_nodes are the nodes to add to the graph"""

        new_nodes = self._neighbors(home_nodes, levels=levels)
        new_nodes = home_nodes.union(new_nodes)

        displayed_data_nodes = set([ v['dataG_id']
                            for k,v in self.dispG.node.items() ])

        # It is possible the new nodes create a connection with the existing
        #  nodes; in such a case, we don't need to try to find the shortest
        #  path between the two blocks
        current_num_islands = nx.number_connected_components(self.dispG)
        new_num_islands = nx.number_connected_components(
            self.dataG.subgraph(displayed_data_nodes.union(new_nodes)))
        if new_num_islands > current_num_islands:
            # Find shortest path between two blocks graph and, if it exists,
            #  ask the user if they'd like to include those nodes in the
            #  display as well.
            # First, create a block model of our data graph where what is
            #  current displayed is a block, the new nodes are a a block
            all_nodes = set(self.dataG.nodes())
            singleton_nodes = all_nodes - displayed_data_nodes - new_nodes
            singleton_nodes = map(lambda x: [x], singleton_nodes)
            partitions = [displayed_data_nodes, new_nodes] + \
                         list(singleton_nodes)
            B = nx.blockmodel(self.dataG, partitions, multigraph=True)

            # Find shortest path between existing display (node 0) and
            #  new display island (node 1)
            try:
                path = nx.shortest_path(B, 0, 1)
            except nx.NetworkXNoPath:
                pass
            else:
                ans = tkm.askyesno("Plot path?", "A path exists between the "
                  "currently graph and the nodes you've asked to be added "
                  "to the display.  Would you like to plot that path?")
                if ans: # Yes to prompt
                    # Add the nodes from the source graph which are part of
                    #  the path to the new_nodes set
                    # Don't include end points because they are the two islands
                    for u in path[1:-1]:
                        Gu = B.node[u]['graph'].nodes()
                        assert len(Gu) == 1; Gu = Gu[0]
                        new_nodes.add(Gu)

        # Plot the new nodes
        self._plot_additional(new_nodes)