Python networkx.simple_cycles() Examples

The following are 30 code examples of networkx.simple_cycles(). 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: graph.py    From CausalDiscoveryToolbox with MIT License 6 votes vote down vote up
def dagify_min_edge(g):
    """Input a graph and output a DAG.

    The heuristic is to reverse the edge with the lowest score of the cycle
    if possible, else remove it.

    Args:
        g (networkx.DiGraph): Graph to modify to output a DAG

    Returns:
        networkx.DiGraph: DAG made out of the input graph.

    Example:
        >>> from cdt.utils.graph import dagify_min_edge
        >>> import networkx as nx
        >>> import numpy as np
        >>> # Generate sample data
        >>> graph = nx.DiGraph((np.ones(4) - np.eye(4)) *
                               np.random.uniform(size=(4,4)))
        >>> output = dagify_min_edge(graph)
    """
    ncycles = len(list(nx.simple_cycles(g)))
    while not nx.is_directed_acyclic_graph(g):
        cycle = next(nx.simple_cycles(g))
        edges = [(cycle[-1], cycle[0])]
        scores = [(g[cycle[-1]][cycle[0]]['weight'])]
        for i, j in zip(cycle[:-1], cycle[1:]):
            edges.append((i, j))
            scores.append(g[i][j]['weight'])

        i, j = edges[scores.index(min(scores))]
        gc = deepcopy(g)
        gc.remove_edge(i, j)
        gc.add_edge(j, i)
        ngc = len(list(nx.simple_cycles(gc)))
        if ngc < ncycles:
            g.add_edge(j, i, weight=min(scores))
        g.remove_edge(i, j)
        ncycles = ngc
    return g 
Example #2
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_simple_graph_with_reported_bug(self):
        G = nx.DiGraph()
        edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4),
                 (3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0),
                 (5, 1), (5, 2), (5, 3)]
        G.add_edges_from(edges)
        cc = sorted(nx.simple_cycles(G))
        assert_equal(len(cc), 26)
        rcc = sorted(nx.recursive_simple_cycles(G))
        assert_equal(len(cc), len(rcc))
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in rcc))
        for rc in rcc:
            assert_true(any(self.is_cyclic_permutation(rc, c) for c in cc))

# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
#    networkx/algorithms/traversal/tests/test_edgedfs.py 
Example #3
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_simple_graph_with_reported_bug(self):
        G = nx.DiGraph()
        edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4),
                 (3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0),
                 (5, 1), (5, 2), (5, 3)]
        G.add_edges_from(edges)
        cc = sorted(nx.simple_cycles(G))
        assert_equal(len(cc), 26)
        rcc = sorted(nx.recursive_simple_cycles(G))
        assert_equal(len(cc), len(rcc))
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in rcc))
        for rc in rcc:
            assert_true(any(self.is_cyclic_permutation(rc, c) for c in cc))

# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
#    networkx/algorithms/traversal/tests/test_edgedfs.py 
Example #4
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_simple_graph_with_reported_bug(self):
        G=nx.DiGraph()
        edges = [(0, 2), (0, 3), (1, 0), (1, 3), (2, 1), (2, 4), \
                (3, 2), (3, 4), (4, 0), (4, 1), (4, 5), (5, 0), \
                (5, 1), (5, 2), (5, 3)]
        G.add_edges_from(edges)
        cc=sorted(nx.simple_cycles(G))
        assert_equal(len(cc),26)
        rcc=sorted(nx.recursive_simple_cycles(G))
        assert_equal(len(cc),len(rcc))
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc))
        for rc in rcc:
            assert_true(any(self.is_cyclic_permutation(rc,c) for c in cc))

# These tests might fail with hash randomization since they depend on
# edge_dfs. For more information, see the comments in:
#    networkx/algorithms/traversal/tests/test_edgedfs.py 
Example #5
Source File: param.py    From st2 with Apache License 2.0 6 votes vote down vote up
def _validate(G):
    '''
    Validates dependency graph to ensure it has no missing or cyclic dependencies
    '''
    for name in G.nodes():
        if 'value' not in G.node[name] and 'template' not in G.node[name]:
            msg = 'Dependency unsatisfied in variable "%s"' % name
            raise ParamException(msg)

    if not nx.is_directed_acyclic_graph(G):
        graph_cycles = nx.simple_cycles(G)

        variable_names = []
        for cycle in graph_cycles:
            try:
                variable_name = cycle[0]
            except IndexError:
                continue

            variable_names.append(variable_name)

        variable_names = ', '.join(sorted(variable_names))
        msg = ('Cyclic dependency found in the following variables: %s. Likely the variable is '
               'referencing itself' % (variable_names))
        raise ParamException(msg) 
Example #6
Source File: K3000_gfa_post_treatment.py    From DiscoSnp with GNU Affero General Public License v3.0 6 votes vote down vote up
def remove_cc_with_cycles(DG):
    # remove pairend links and unitig links (unoriented)
    edges_to_remove = []
    for edge in DG.edges.data():
        if edge[2]['type'] == '-1M':
            edges_to_remove.append(edge)
            
    for edge in edges_to_remove:
        DG.remove_edge(edge[0],edge[1])
    cycles = list(nx.simple_cycles(DG))
    # sys.stderr.write(f" removed {len(cycles)} cycles\n")    #DEB
    
    # tmpnb=0                                         #DEB
    G=nx.Graph(DG)
    for nodes in cycles:
        first_node_in_cycle = nodes[0]              # get the first node, the other ones in the cycle are in the same CC
        # remove the whole CC:
        CC_with_cycle = nx.node_connected_component(G, first_node_in_cycle)
        for node_id in CC_with_cycle:
            if node_id in DG.nodes():
                # tmpnb+=1                            #DEB
                DG.remove_node(node_id)
    # sys.stderr.write(f" removed {tmpnb} nodes\n")   #DEB 
Example #7
Source File: build.py    From bioconda-utils with MIT License 6 votes vote down vote up
def remove_cycles(dag, name2recipes, failed, skip_dependent):
    nodes_in_cycles = set()
    for cycle in list(nx.simple_cycles(dag)):
        logger.error('BUILD ERROR: dependency cycle found: %s', cycle)
        nodes_in_cycles.update(cycle)

    for name in sorted(nodes_in_cycles):
        cycle_fail_recipes = sorted(name2recipes[name])
        logger.error('BUILD ERROR: cannot build recipes for %s since '
                     'it cyclically depends on other packages in the '
                     'current build job. Failed recipes: %s',
                     name, cycle_fail_recipes)
        failed.extend(cycle_fail_recipes)
        for node in nx.algorithms.descendants(dag, name):
            if node not in nodes_in_cycles:
                skip_dependent[node].extend(cycle_fail_recipes)
    return dag.subgraph(name for name in dag if name not in nodes_in_cycles) 
Example #8
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_simple_cycles_graph(self):
        G = nx.Graph()
        c = sorted(nx.simple_cycles(G)) 
Example #9
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_unsortable(self):
        #  TODO What does this test do?  das 6/2013
        G=nx.DiGraph()
        G.add_cycle(['a',1])
        c=list(nx.simple_cycles(G)) 
Example #10
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_simple_cycles_small(self):
        G = nx.DiGraph()
        G.add_cycle([1,2,3])
        c=sorted(nx.simple_cycles(G))
        assert_equal(len(c),1)
        assert_true(self.is_cyclic_permutation(c[0],[1,2,3]))
        G.add_cycle([10,20,30])
        cc=sorted(nx.simple_cycles(G))
        ca=[[1,2,3],[10,20,30]]
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c,rc) for rc in ca)) 
Example #11
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_simple_cycles_empty(self):
        G = nx.DiGraph()
        assert_equal(list(nx.simple_cycles(G)),[]) 
Example #12
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_worst_case_graph(self):
        # see figure 1 in Johnson's paper
        for k in range(3,10):
            G=self.worst_case_graph(k)
            l=len(list(nx.simple_cycles(G)))
            assert_equal(l,3*k) 
Example #13
Source File: test_cycles.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_recursive_simple_and_not(self):
        for k in range(2,10):
            G=self.worst_case_graph(k)
            cc=sorted(nx.simple_cycles(G))
            rcc=sorted(nx.recursive_simple_cycles(G))
            assert_equal(len(cc),len(rcc))
            for c in cc:
                assert_true(any(self.is_cyclic_permutation(c,rc) for rc in rcc))
            for rc in rcc:
                assert_true(any(self.is_cyclic_permutation(rc,c) for c in cc)) 
Example #14
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_simple_cycles(self):
        edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
        G = nx.DiGraph(edges)
        cc = sorted(nx.simple_cycles(G))
        ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
        assert_equal(len(cc), len(ca))
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in ca)) 
Example #15
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_simple_cycles_graph(self):
        G = nx.Graph()
        c = sorted(nx.simple_cycles(G)) 
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_unsortable(self):
        #  TODO What does this test do?  das 6/2013
        G = nx.DiGraph()
        nx.add_cycle(G, ['a', 1])
        c = list(nx.simple_cycles(G)) 
Example #17
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_simple_cycles_small(self):
        G = nx.DiGraph()
        nx.add_cycle(G, [1, 2, 3])
        c = sorted(nx.simple_cycles(G))
        assert_equal(len(c), 1)
        assert_true(self.is_cyclic_permutation(c[0], [1, 2, 3]))
        nx.add_cycle(G, [10, 20, 30])
        cc = sorted(nx.simple_cycles(G))
        assert_equal(len(cc), 2)
        ca = [[1, 2, 3], [10, 20, 30]]
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in ca)) 
Example #18
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_simple_cycles_empty(self):
        G = nx.DiGraph()
        assert_equal(list(nx.simple_cycles(G)), []) 
Example #19
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_worst_case_graph(self):
        # see figure 1 in Johnson's paper
        for k in range(3, 10):
            G = self.worst_case_graph(k)
            l = len(list(nx.simple_cycles(G)))
            assert_equal(l, 3 * k) 
Example #20
Source File: test_cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_recursive_simple_and_not(self):
        for k in range(2, 10):
            G = self.worst_case_graph(k)
            cc = sorted(nx.simple_cycles(G))
            rcc = sorted(nx.recursive_simple_cycles(G))
            assert_equal(len(cc), len(rcc))
            for c in cc:
                assert_true(any(self.is_cyclic_permutation(c, r) for r in rcc))
            for rc in rcc:
                assert_true(any(self.is_cyclic_permutation(rc, c) for c in cc)) 
Example #21
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 #22
Source File: cycles.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def minimum_cycle_basis(G, weight=None):
    """ Returns a minimum weight cycle basis for G

    Minimum weight means a cycle basis for which the total weight
    (length for unweighted graphs) of all the cycles is minimum.

    Parameters
    ----------
    G : NetworkX Graph
    weight: string
        name of the edge attribute to use for edge weights

    Returns
    -------
    A list of cycle lists.  Each cycle list is a list of nodes
    which forms a cycle (loop) in G. Note that the nodes are not
    necessarily returned in a order by which they appear in the cycle

    Examples
    --------
    >>> G=nx.Graph()
    >>> G.add_cycle([0,1,2,3])
    >>> G.add_cycle([0,3,4,5])
    >>> print(nx.minimum_cycle_basis(G))
    [[0, 1, 2, 3], [0, 3, 4, 5]]

    References:
        [1] Kavitha, Telikepalli, et al. "An O(m^2n) Algorithm for
        Minimum Cycle Basis of Graphs."
        http://link.springer.com/article/10.1007/s00453-007-9064-z
        [2] de Pina, J. 1995. Applications of shortest path methods.
        Ph.D. thesis, University of Amsterdam, Netherlands

    See Also
    --------
    simple_cycles, cycle_basis
    """
    # We first split the graph in commected subgraphs
    return sum((_min_cycle_basis(c, weight) for c in
                nx.connected_component_subgraphs(G)), []) 
Example #23
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_simple_cycles(self):
        edges = [(0, 0), (0, 1), (0, 2), (1, 2), (2, 0), (2, 1), (2, 2)]
        G = nx.DiGraph(edges)
        cc = sorted(nx.simple_cycles(G))
        ca = [[0], [0, 1, 2], [0, 2], [1, 2], [2]]
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in ca)) 
Example #24
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_simple_cycles_graph(self):
        G = nx.Graph()
        c = sorted(nx.simple_cycles(G)) 
Example #25
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_unsortable(self):
        #  TODO What does this test do?  das 6/2013
        G = nx.DiGraph()
        nx.add_cycle(G, ['a', 1])
        c = list(nx.simple_cycles(G)) 
Example #26
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_simple_cycles_small(self):
        G = nx.DiGraph()
        nx.add_cycle(G, [1, 2, 3])
        c = sorted(nx.simple_cycles(G))
        assert_equal(len(c), 1)
        assert_true(self.is_cyclic_permutation(c[0], [1, 2, 3]))
        nx.add_cycle(G, [10, 20, 30])
        cc = sorted(nx.simple_cycles(G))
        ca = [[1, 2, 3], [10, 20, 30]]
        for c in cc:
            assert_true(any(self.is_cyclic_permutation(c, rc) for rc in ca)) 
Example #27
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_simple_cycles_empty(self):
        G = nx.DiGraph()
        assert_equal(list(nx.simple_cycles(G)), []) 
Example #28
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_worst_case_graph(self):
        # see figure 1 in Johnson's paper
        for k in range(3, 10):
            G = self.worst_case_graph(k)
            l = len(list(nx.simple_cycles(G)))
            assert_equal(l, 3*k) 
Example #29
Source File: test_cycles.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_recursive_simple_and_not(self):
        for k in range(2, 10):
            G = self.worst_case_graph(k)
            cc = sorted(nx.simple_cycles(G))
            rcc = sorted(nx.recursive_simple_cycles(G))
            assert_equal(len(cc), len(rcc))
            for c in cc:
                assert_true(any(self.is_cyclic_permutation(c, r) for r in rcc))
            for rc in rcc:
                assert_true(any(self.is_cyclic_permutation(rc, c) for c in cc)) 
Example #30
Source File: include.py    From catcher with Apache License 2.0 5 votes vote down vote up
def check_circular(parent: str,
                       all_includes: nx.DiGraph,
                       current_include: dict) -> 'Include':
        path = current_include['file']
        all_includes.add_edge(parent, path)
        if list(nx.simple_cycles(all_includes)):
            debug(str(all_includes.edges))
            raise Exception('Circular dependencies for ' + path)
        return Include(**current_include)