Python networkx.weakly_connected_components() Examples

The following are 30 code examples of networkx.weakly_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: plot_distributions.py    From AMLSim with Apache License 2.0 6 votes vote down vote up
def plot_wcc_distribution(_g, _plot_img):
    """Plot weakly connected components size distributions
    :param _g: Transaction graph
    :param _plot_img: WCC size distribution image (log-log plot)
    :return:
    """
    all_wcc = nx.weakly_connected_components(_g)
    wcc_sizes = Counter([len(wcc) for wcc in all_wcc])
    size_seq = sorted(wcc_sizes.keys())
    size_hist = [wcc_sizes[x] for x in size_seq]

    plt.figure(figsize=(16, 12))
    plt.clf()
    plt.loglog(size_seq, size_hist, 'ro-')
    plt.title("WCC Size Distribution")
    plt.xlabel("Size")
    plt.ylabel("Number of WCCs")
    plt.savefig(_plot_img) 
Example #2
Source File: operations.py    From pybel with MIT License 6 votes vote down vote up
def left_outer_join(g, h) -> None:
    """Only add components from the ``h`` that are touching ``g``.

    Algorithm:

    1. Identify all weakly connected components in ``h``
    2. Add those that have an intersection with the ``g``

    :param BELGraph g: A BEL graph
    :param BELGraph h: A BEL graph

    Example usage:

    >>> import pybel
    >>> g = pybel.from_bel_script('...')
    >>> h = pybel.from_bel_script('...')
    >>> left_outer_join(g, h)
    """
    g_nodes = set(g)
    for comp in nx.weakly_connected_components(h):
        if g_nodes.intersection(comp):
            h_subgraph = subgraph(h, comp)
            left_full_join(g, h_subgraph) 
Example #3
Source File: weakly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def number_weakly_connected_components(G):
    """Return the number of weakly connected components in G.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    Returns
    -------
    n : integer
        Number of weakly connected components

    See Also
    --------
    connected_components

    Notes
    -----
    For directed graphs only.

    """
    return len(list(weakly_connected_components(G))) 
Example #4
Source File: test_weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_weakly_connected_components(self):
        for G, C in self.gc:
            U = G.to_undirected()
            w = {frozenset(g) for g in nx.weakly_connected_components(G)}
            c = {frozenset(g) for g in nx.connected_components(U)}
            assert_equal(w, c) 
Example #5
Source File: weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def is_weakly_connected(G):
    """Test directed graph for weak connectivity.

    A directed graph is weakly connected if, and only if, the graph
    is connected when the direction of the edge between nodes is ignored.

    Parameters
    ----------
    G : NetworkX Graph
        A directed graph.

    Returns
    -------
    connected : bool
        True if the graph is weakly connected, False otherwise.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    See Also
    --------
    is_strongly_connected
    is_semiconnected
    is_connected
    is_biconnected
    weakly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    if len(G) == 0:
        raise nx.NetworkXPointlessConcept(
            """Connectivity is undefined for the null graph.""")

    return len(list(weakly_connected_components(G))[0]) == len(G) 
Example #6
Source File: weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def number_weakly_connected_components(G):
    """Return the number of weakly connected components in G.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    Returns
    -------
    n : integer
        Number of weakly connected components

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    See Also
    --------
    weakly_connected_components
    number_connected_components
    number_strongly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    return len(list(weakly_connected_components(G))) 
Example #7
Source File: test_weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_connected_raise(self):
        G = nx.Graph()
        assert_raises(NetworkXNotImplemented, nx.weakly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.number_weakly_connected_components, G)
        assert_raises(NetworkXNotImplemented, nx.is_weakly_connected, G)
        # deprecated
        assert_raises(NetworkXNotImplemented, nx.weakly_connected_component_subgraphs, G) 
Example #8
Source File: test_weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_weakly_connected_components(self):
        for G, C in self.gc:
            U = G.to_undirected()
            w = {frozenset(g) for g in nx.weakly_connected_components(G)}
            c = {frozenset(g) for g in nx.connected_components(U)}
            assert_equal(w, c) 
Example #9
Source File: weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def weakly_connected_component_subgraphs(G, copy=True):
    """DEPRECATED: Use ``(G.subgraph(c) for c in weakly_connected_components(G))``

           Or ``(G.subgraph(c).copy() for c in weakly_connected_components(G))``
    """
    msg = "weakly_connected_component_subgraphs is deprecated and will be removed in 2.2" \
        "use (G.subgraph(c).copy() for c in weakly_connected_components(G))"
    _warnings.warn(msg, DeprecationWarning)
    for c in weakly_connected_components(G):
        if copy:
            yield G.subgraph(c).copy()
        else:
            yield G.subgraph(c) 
Example #10
Source File: weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def number_weakly_connected_components(G):
    """Returns the number of weakly connected components in G.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    Returns
    -------
    n : integer
        Number of weakly connected components

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    See Also
    --------
    weakly_connected_components
    number_connected_components
    number_strongly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    return sum(1 for wcc in weakly_connected_components(G)) 
Example #11
Source File: graph.py    From gunpowder with MIT License 5 votes vote down vote up
def connected_components(self):
        if not self.directed:
            return nx.connected_components(self.__graph)
        else:
            return nx.weakly_connected_components(self.__graph) 
Example #12
Source File: test_weakly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_weakly_connected_components(self):
        for G, C in self.gc:
            U = G.to_undirected()
            w = {frozenset(g) for g in nx.weakly_connected_components(G)}
            c = {frozenset(g) for g in nx.connected_components(U)}
            assert_equal(w, c) 
Example #13
Source File: weakly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def is_weakly_connected(G):
    """Test directed graph for weak connectivity.

    A directed graph is weakly connected if, and only if, the graph
    is connected when the direction of the edge between nodes is ignored.

    Parameters
    ----------
    G : NetworkX Graph
        A directed graph.

    Returns
    -------
    connected : bool
        True if the graph is weakly connected, False otherwise.

    See Also
    --------
    is_strongly_connected
    is_semiconnected
    is_connected

    Notes
    -----
    For directed graphs only.

    """
    if len(G) == 0:
        raise nx.NetworkXPointlessConcept(
            """Connectivity is undefined for the null graph.""")

    return len(list(weakly_connected_components(G))[0]) == len(G) 
Example #14
Source File: utils.py    From pybel with MIT License 5 votes vote down vote up
def get_largest_component(graph: BELGraph) -> BELGraph:
    """Get the giant component of a graph.

    :param graph: A BEL graph
    """
    biggest_component_nodes = max(nx.weakly_connected_components(graph), key=len)
    return subgraph(graph, biggest_component_nodes) 
Example #15
Source File: computePathStats.py    From Beeline with GNU General Public License v3.0 5 votes vote down vote up
def getNetProp(inGraph):
    '''
    Function to compute properties
    of a given network.
    '''

    # number of weakly connected components in 
    # reference network
    numCC = len(list(nx.weakly_connected_components(inGraph)))
    
    # number of feedback loop 
    # in reference network
    allCyc = nx.simple_cycles(inGraph)
    cycSet = set()
    for cyc in allCyc:
        if len(cyc) == 3:
            cycSet.add(frozenset(cyc))
    
    numFB = len(cycSet)
    
    # number of feedfwd loops
    # in reference network
    allPaths = []
    allPathsSet = set()   
    for u,v in inGraph.edges():
        allPaths = nx.all_simple_paths(inGraph, u, v, cutoff=2)
        for p in allPaths:
            if len(p) >  2:
                allPathsSet.add(frozenset(p))
                
    numFF= len(allPathsSet)
    
    
    # number of mutual interactions
    numMI = 0.0
    for u,v in inGraph.edges():
        if (v,u) in inGraph.edges():
            numMI += 0.5

    return numCC, numFB, numFF, numMI 
Example #16
Source File: intra_citation.py    From arxiv-public-datasets with MIT License 5 votes vote down vote up
def biggest_connected_subgraph(G):
    if G.is_directed():
        comps = nx.weakly_connected_components(G)
    else:
        comps = nx.connected_components(G)
    biggest = max(comps, key=len)
    return G.subgraph(biggest) 
Example #17
Source File: graph.py    From ScaffoldGraph with MIT License 5 votes vote down vote up
def separate_disconnected_components(self, sort=False):
        """Separate disconnected components into distinct ScaffoldGraph objects.

        Parameters
        ----------
        sort : (bool, optional (default=False)) If True sort components in descending order according
            to the number of nodes in the subgraph.
        """
        components = []
        for c in nx.weakly_connected_components(self):
            components.append(self.subgraph(c).copy())
        if sort:
            return sorted(components, key=len, reverse=True)
        return components 
Example #18
Source File: graphs.py    From ReGraph with MIT License 5 votes vote down vote up
def nodes_disconnected_from(self, node_id):
        """Find nodes disconnected from the input node."""
        components = nx.weakly_connected_components(
            self._graph)

        disconnected_components = []
        for comp in components:
            if node_id not in comp:
                disconnected_components.append(comp)
        return set([
            n
            for comp in disconnected_components
            for n in comp
        ]) 
Example #19
Source File: cfg_emulated.py    From angr with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _remove_non_return_edges(self):
        """
        Remove those return_from_call edges that actually do not return due to
        calling some not-returning functions.
        :return: None
        """
        for func in self.kb.functions.values():
            graph = func.transition_graph
            all_return_edges = [(u, v) for (u, v, data) in graph.edges(data=True) if data['type'] == 'return_from_call']
            for return_from_call_edge in all_return_edges:
                callsite_block_addr, return_to_addr = return_from_call_edge
                call_func_addr = func.get_call_target(callsite_block_addr)
                if call_func_addr is None:
                    continue

                call_func = self.kb.functions.function(call_func_addr)
                if call_func is None:
                    # Weird...
                    continue

                if call_func.returning is False:
                    # Remove that edge!
                    graph.remove_edge(call_func_addr, return_to_addr)
                    # Remove the edge in CFG
                    nodes = self.get_all_nodes(callsite_block_addr)
                    for n in nodes:
                        successors = self.get_successors_and_jumpkind(n, excluding_fakeret=False)
                        for successor, jumpkind in successors:
                            if jumpkind == 'Ijk_FakeRet' and successor.addr == return_to_addr:
                                self.remove_edge(n, successor)

                                # Remove all dangling nodes
                                # wcc = list(networkx.weakly_connected_components(graph))
                                # for nodes in wcc:
                                #    if func.startpoint not in nodes:
                                #        graph.remove_nodes_from(nodes)

    # Private methods - resolving indirect jumps 
Example #20
Source File: osmnx_funcs.py    From apls with Apache License 2.0 4 votes vote down vote up
def get_largest_component(G, strongly=False):
    """
    https://github.com/gboeing/osmnx/blob/master/osmnx/utils.py
    Return a subgraph of the largest weakly or strongly connected component
    from a directed graph.
    Parameters
    ----------
    G : networkx multidigraph
    strongly : bool
        if True, return the largest strongly instead of weakly connected
        component
    Returns
    -------
    G : networkx multidigraph
        the largest connected component subgraph from the original graph
    """

    start_time = time.time()
    original_len = len(list(G.nodes()))

    if strongly:
        # if the graph is not connected retain only the largest strongly connected component
        if not nx.is_strongly_connected(G):

            # get all the strongly connected components in graph then identify the largest
            sccs = nx.strongly_connected_components(G)
            largest_scc = max(sccs, key=len)
            G = induce_subgraph(G, largest_scc)

            msg = ('Graph was not connected, retained only the largest strongly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))
    else:
        # if the graph is not connected retain only the largest weakly connected component
        if not nx.is_weakly_connected(G):

            # get all the weakly connected components in graph then identify the largest
            wccs = nx.weakly_connected_components(G)
            largest_wcc = max(wccs, key=len)
            G = induce_subgraph(G, largest_wcc)

            msg = ('Graph was not connected, retained only the largest weakly '
                   'connected component ({:,} of {:,} total nodes) in {:.2f} seconds')
            print(msg.format(len(list(G.nodes())), original_len, time.time()-start_time))

    return G 
Example #21
Source File: urdf.py    From urdfpy with MIT License 4 votes vote down vote up
def _validate_graph(self):
        """Raise an exception if the link-joint structure is invalid.

        Checks for the following:

        - The graph is connected in the undirected sense.
        - The graph is acyclic in the directed sense.
        - The graph has only one base link.

        Returns
        -------
        base_link : :class:`.Link`
            The base link of the URDF.
        end_links : list of :class:`.Link`
            The end links of the URDF.
        """

        # Check that the link graph is weakly connected
        if not nx.is_weakly_connected(self._G):
            link_clusters = []
            for cc in nx.weakly_connected_components(self._G):
                cluster = []
                for n in cc:
                    cluster.append(n.name)
                link_clusters.append(cluster)
            message = ('Links are not all connected. '
                       'Connected components are:')
            for lc in link_clusters:
                message += '\n\t'
                for n in lc:
                    message += ' {}'.format(n)
            raise ValueError(message)

        # Check that link graph is acyclic
        if not nx.is_directed_acyclic_graph(self._G):
            raise ValueError('There are cycles in the link graph')

        # Ensure that there is exactly one base link, which has no parent
        base_link = None
        end_links = []
        for n in self._G:
            if len(nx.descendants(self._G, n)) == 0:
                if base_link is None:
                    base_link = n
                else:
                    raise ValueError('Links {} and {} are both base links!'
                                     .format(n.name, base_link.name))
            if len(nx.ancestors(self._G, n)) == 0:
                end_links.append(n)
        return base_link, end_links 
Example #22
Source File: weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def weakly_connected_component_subgraphs(G, copy=True):
    """Generate weakly connected components as subgraphs.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    copy: bool (default=True)
        If True make a copy of the graph attributes

    Returns
    -------
    comp : generator
        A generator of graphs, one for each weakly connected component of G.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    Examples
    --------
    Generate a sorted list of weakly connected components, largest first.

    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
    >>> nx.add_path(G, [10, 11, 12])
    >>> [len(c) for c in sorted(nx.weakly_connected_component_subgraphs(G),
    ...                         key=len, reverse=True)]
    [4, 3]

    If you only want the largest component, it's more efficient to
    use max instead of sort:

    >>> Gc = max(nx.weakly_connected_component_subgraphs(G), key=len)

    See Also
    --------
    weakly_connected_components
    strongly_connected_component_subgraphs
    connected_component_subgraphs

    Notes
    -----
    For directed graphs only.
    Graph, node, and edge attributes are copied to the subgraphs by default.

    """
    for comp in weakly_connected_components(G):
        if copy:
            yield G.subgraph(comp).copy()
        else:
            yield G.subgraph(comp) 
Example #23
Source File: weakly_connected.py    From aws-kube-codesuite with Apache License 2.0 4 votes vote down vote up
def weakly_connected_components(G):
    """Generate weakly connected components of G.

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

    Returns
    -------
    comp : generator of sets
        A generator of sets of nodes, one for each weakly connected
        component of G.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    Examples
    --------
    Generate a sorted list of weakly connected components, largest first.

    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
    >>> nx.add_path(G, [10, 11, 12])
    >>> [len(c) for c in sorted(nx.weakly_connected_components(G),
    ...                         key=len, reverse=True)]
    [4, 3]

    If you only want the largest component, it's more efficient to
    use max instead of sort:

    >>> largest_cc = max(nx.weakly_connected_components(G), key=len)

    See Also
    --------
    connected_components
    strongly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    seen = set()
    for v in G:
        if v not in seen:
            c = set(_plain_bfs(G, v))
            yield c
            seen.update(c) 
Example #24
Source File: computeNetMotifs.py    From Beeline with GNU General Public License v3.0 4 votes vote down vote up
def getNetProp(inGraph):
    '''
    A helper function to compute
    counts of various network motifs.
    

    :param inGraph: An graph object of class :class:`networkx.DiGraph`.
    :type inGraph: :obj:networkx.DiGraph

    :returns:
        - A value corresponding to the number of three-node feedback loops
        - A value corresponding to the number of three-node feedforward loops
        - A value corresponding to the number of two-node mutual interaction


    '''

    # number of weakly connected components in 
    # reference network
    # numCC = len(list(nx.weakly_connected_components(inGraph)))
    
    # number of feedback loop 
    # in reference network
    allCyc = nx.simple_cycles(inGraph)
    cycSet = set()
    for cyc in allCyc:
        if len(cyc) == 3:
            cycSet.add(frozenset(cyc))
    
    numFB = len(cycSet)
    
    # number of feedfwd loops
    # in reference network
    allPaths = []
    allPathsSet = set()   
    for u,v in inGraph.edges():
        allPaths = nx.all_simple_paths(inGraph, u, v, cutoff=2)
        for p in allPaths:
            if len(p) > 2:
                allPathsSet.add(frozenset(p))
                
    numFF= len(allPathsSet)
    
    
    # number of mutual interactions
    numMI = 0.0
    for u,v in inGraph.edges():
        if (v,u) in inGraph.edges():
            numMI += 0.5

    return numFB, numFF, numMI 
Example #25
Source File: weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def is_weakly_connected(G):
    """Test directed graph for weak connectivity.

    A directed graph is weakly connected if and only if the graph
    is connected when the direction of the edge between nodes is ignored.

    Note that if a graph is strongly connected (i.e. the graph is connected
    even when we account for directionality), it is by definition weakly
    connected as well.

    Parameters
    ----------
    G : NetworkX Graph
        A directed graph.

    Returns
    -------
    connected : bool
        True if the graph is weakly connected, False otherwise.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    See Also
    --------
    is_strongly_connected
    is_semiconnected
    is_connected
    is_biconnected
    weakly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    if len(G) == 0:
        raise nx.NetworkXPointlessConcept(
            """Connectivity is undefined for the null graph.""")

    return len(list(weakly_connected_components(G))[0]) == len(G) 
Example #26
Source File: weakly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def weakly_connected_components(G):
    """Generate weakly connected components of G.

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

    Returns
    -------
    comp : generator of sets
        A generator of sets of nodes, one for each weakly connected
        component of G.

    Raises
    ------
    NetworkXNotImplemented:
        If G is undirected.

    Examples
    --------
    Generate a sorted list of weakly connected components, largest first.

    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
    >>> nx.add_path(G, [10, 11, 12])
    >>> [len(c) for c in sorted(nx.weakly_connected_components(G),
    ...                         key=len, reverse=True)]
    [4, 3]

    If you only want the largest component, it's more efficient to
    use max instead of sort:

    >>> largest_cc = max(nx.weakly_connected_components(G), key=len)

    See Also
    --------
    connected_components
    strongly_connected_components

    Notes
    -----
    For directed graphs only.

    """
    seen = set()
    for v in G:
        if v not in seen:
            c = set(_plain_bfs(G, v))
            yield c
            seen.update(c) 
Example #27
Source File: utils_graph.py    From osmnx with MIT License 4 votes vote down vote up
def get_largest_component(G, strongly=False):
    """
    Get subgraph of MultiDiGraph's largest weakly/strongly connected component.

    Parameters
    ----------
    G : networkx.MultiDiGraph
        input graph
    strongly : bool
        if True, return the largest strongly instead of weakly connected
        component

    Returns
    -------
    G : networkx.MultiDiGraph
        the largest connected component subgraph from the original graph
    """
    original_len = len(list(G.nodes()))

    if strongly:
        # if the graph is not connected retain only the largest strongly connected component
        if not nx.is_strongly_connected(G):

            # get all the strongly connected components in graph then identify the largest
            sccs = nx.strongly_connected_components(G)
            largest_scc = max(sccs, key=len)
            G = induce_subgraph(G, largest_scc)

            msg = (
                f"Graph was not connected, retained only the largest strongly "
                f"connected component ({len(G)} of {original_len} total nodes)"
            )
            utils.log(msg)
    else:
        # if the graph is not connected retain only the largest weakly connected component
        if not nx.is_weakly_connected(G):

            # get all the weakly connected components in graph then identify the largest
            wccs = nx.weakly_connected_components(G)
            largest_wcc = max(wccs, key=len)
            G = induce_subgraph(G, largest_wcc)

            msg = (
                f"Graph was not connected, retained only the largest weakly "
                f"connected component ({len(G)} of {original_len} total nodes)"
            )
            utils.log(msg)

    return G 
Example #28
Source File: utils.py    From graspy with Apache License 2.0 4 votes vote down vote up
def get_lcc(graph, return_inds=False):
    r"""
    Finds the largest connected component for the input graph.

    The largest connected component is the fully connected subgraph
    which has the most nodes.

    Parameters
    ----------
    graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray
        Input graph in any of the above specified formats. If np.ndarray,
        interpreted as an :math:`n \times n` adjacency matrix

    return_inds: boolean, default: False
        Whether to return a np.ndarray containing the indices in the original
        adjacency matrix that were kept and are now in the returned graph.
        Ignored when input is networkx object

    Returns
    -------
    graph: nx.Graph, nx.DiGraph, nx.MultiDiGraph, nx.MultiGraph, np.ndarray
        New graph of the largest connected component of the input parameter.

    inds: (optional)
        Indices from the original adjacency matrix that were kept after taking
        the largest connected component.
    """
    input_ndarray = False
    if type(graph) is np.ndarray:
        input_ndarray = True
        if is_symmetric(graph):
            g_object = nx.Graph()
        else:
            g_object = nx.DiGraph()
        graph = nx.from_numpy_array(graph, create_using=g_object)
    if type(graph) in [nx.Graph, nx.MultiGraph]:
        lcc_nodes = max(nx.connected_components(graph), key=len)
    elif type(graph) in [nx.DiGraph, nx.MultiDiGraph]:
        lcc_nodes = max(nx.weakly_connected_components(graph), key=len)
    lcc = graph.subgraph(lcc_nodes).copy()
    lcc.remove_nodes_from([n for n in lcc if n not in lcc_nodes])
    if return_inds:
        nodelist = np.array(list(lcc_nodes))
    if input_ndarray:
        lcc = nx.to_numpy_array(lcc)
    if return_inds:
        return lcc, nodelist
    return lcc 
Example #29
Source File: weakly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 4 votes vote down vote up
def weakly_connected_component_subgraphs(G, copy=True):
    """Generate weakly connected components as subgraphs.

    Parameters
    ----------
    G : NetworkX graph
        A directed graph.

    copy: bool (default=True)
        If True make a copy of the graph attributes

    Returns
    -------
    comp : generator
        A generator of graphs, one for each weakly connected component of G.

    Examples
    --------
    Generate a sorted list of weakly connected components, largest first.

    >>> G = nx.path_graph(4, create_using=nx.DiGraph())
    >>> G.add_path([10, 11, 12])
    >>> [len(c) for c in sorted(nx.weakly_connected_component_subgraphs(G),
    ...                         key=len, reverse=True)]
    [4, 3]

    If you only want the largest component, it's more efficient to
    use max instead of sort.

    >>> Gc = max(nx.weakly_connected_component_subgraphs(G), key=len)

    See Also
    --------
    strongly_connected_components
    connected_components

    Notes
    -----
    For directed graphs only.
    Graph, node, and edge attributes are copied to the subgraphs by default.

    """
    for comp in weakly_connected_components(G):
        if copy:
            yield G.subgraph(comp).copy()
        else:
            yield G.subgraph(comp) 
Example #30
Source File: urdf.py    From scikit-robot with MIT License 4 votes vote down vote up
def _validate_graph(self):
        """Raise an exception if the link-joint structure is invalid.

        Checks for the following:

        - The graph is connected in the undirected sense.
        - The graph is acyclic in the directed sense.
        - The graph has only one base link.

        Returns
        -------
        base_link : :class:`.Link`
            The base link of the URDF.
        end_links : list of :class:`.Link`
            The end links of the URDF.
        """

        # Check that the link graph is weakly connected
        if not nx.is_weakly_connected(self._G):
            link_clusters = []
            for cc in nx.weakly_connected_components(self._G):
                cluster = []
                for n in cc:
                    cluster.append(n.name)
                link_clusters.append(cluster)
            message = ('Links are not all connected. '
                       'Connected components are:')
            for lc in link_clusters:
                message += '\n\t'
                for n in lc:
                    message += ' {}'.format(n)
            raise ValueError(message)

        # Check that link graph is acyclic
        if not nx.is_directed_acyclic_graph(self._G):
            raise ValueError('There are cycles in the link graph')

        # Ensure that there is exactly one base link, which has no parent
        base_link = None
        end_links = []
        for n in self._G:
            if len(nx.descendants(self._G, n)) == 0:
                if base_link is None:
                    base_link = n
                else:
                    raise ValueError('Links {} and {} are both base links!'
                                     .format(n.name, base_link.name))
            if len(nx.ancestors(self._G, n)) == 0:
                end_links.append(n)
        return base_link, end_links