Python networkx.is_directed_acyclic_graph() Examples

The following are 30 code examples of networkx.is_directed_acyclic_graph(). 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: test_strongly_connected.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_contract_scc1(self):
        G = nx.DiGraph()
        G.add_edges_from([
            (1, 2), (2, 3), (2, 11), (2, 12), (3, 4), (4, 3), (4, 5), (5, 6),
            (6, 5), (6, 7), (7, 8), (7, 9), (7, 10), (8, 9), (9, 7), (10, 6),
            (11, 2), (11, 4), (11, 6), (12, 6), (12, 11),
        ])
        scc = list(nx.strongly_connected_components(G))
        cG = nx.condensation(G, scc)
        # DAG
        assert_true(nx.is_directed_acyclic_graph(cG))
        # nodes
        assert_equal(sorted(cG.nodes()), [0, 1, 2, 3])
        # edges
        mapping={}
        for i, component in enumerate(scc):
            for n in component:
                mapping[n] = i
        edge = (mapping[2], mapping[3])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[2], mapping[5])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[3], mapping[5])
        assert_true(cG.has_edge(*edge)) 
Example #2
Source File: test_utils.py    From numpy-ml with GNU General Public License v3.0 6 votes vote down vote up
def test_topological_ordering(N=1):
    np.random.seed(12345)
    i = 0
    while i < N:
        p = np.random.uniform(0.25, 1)
        n_v = np.random.randint(5, 10)

        G = random_DAG(n_v, p)
        G_nx = to_networkx(G)

        if nx.is_directed_acyclic_graph(G_nx):
            topo_order = G.topological_ordering()

            #  test topological order
            seen_it = set()
            for n_i in topo_order:
                seen_it.add(n_i)
                assert any([c_i in seen_it for c_i in G.get_neighbors(n_i)]) == False

            print("PASSED")
            i += 1 
Example #3
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 #4
Source File: readers.py    From partridge with MIT License 6 votes vote down vote up
def load_feed(
    path: str, view: Optional[View] = None, config: Optional[nx.DiGraph] = None
) -> Feed:
    config = default_config() if config is None else config
    view = {} if view is None else view

    if not nx.is_directed_acyclic_graph(config):
        raise ValueError("Config must be a DAG")

    if os.path.isdir(path):
        feed = _load_feed(path, view, config)
    elif os.path.isfile(path):
        feed = _unpack_feed(path, view, config)
    else:
        raise ValueError("File or path not found: {}".format(path))

    return feed 
Example #5
Source File: test_strongly_connected.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_contract_scc1(self):
        G = nx.DiGraph()
        G.add_edges_from([
            (1, 2), (2, 3), (2, 11), (2, 12), (3, 4), (4, 3), (4, 5), (5, 6),
            (6, 5), (6, 7), (7, 8), (7, 9), (7, 10), (8, 9), (9, 7), (10, 6),
            (11, 2), (11, 4), (11, 6), (12, 6), (12, 11),
        ])
        scc = list(nx.strongly_connected_components(G))
        cG = nx.condensation(G, scc)
        # DAG
        assert_true(nx.is_directed_acyclic_graph(cG))
        # nodes
        assert_equal(sorted(cG.nodes()), [0, 1, 2, 3])
        # edges
        mapping = {}
        for i, component in enumerate(scc):
            for n in component:
                mapping[n] = i
        edge = (mapping[2], mapping[3])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[2], mapping[5])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[3], mapping[5])
        assert_true(cG.has_edge(*edge)) 
Example #6
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 #7
Source File: remove_cycle_edges_by_minimum_feedback_arc_set_greedy.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def remove_cycle_edges_by_mfas(graph_file):
	g = nx.read_edgelist(graph_file,create_using = nx.DiGraph(),nodetype = int)
	from remove_self_loops import remove_self_loops_from_graph
	self_loops = remove_self_loops_from_graph(g)

	scc_nodes,_,_,_ = scc_nodes_edges(g)
	degree_dict = get_nodes_degree_dict(g,scc_nodes)
	sccs = get_big_sccs(g)
	if len(sccs) == 0:
		print("After removal of self loop edgs: %s" % nx.is_directed_acyclic_graph(g))
		return self_loops
	edges_to_be_removed = []
	import timeit
	t1 = timeit.default_timer()
	greedy_local_heuristic(sccs,degree_dict,edges_to_be_removed)
	t2 = timeit.default_timer()
	print("mfas time usage: %0.4f s" % (t2 - t1))
	edges_to_be_removed = list(set(edges_to_be_removed))
	g.remove_edges_from(edges_to_be_removed)
	edges_to_be_removed += self_loops
	edges_to_be_removed_file = graph_file[:len(graph_file)-6] + "_removed_by_mfas.edges"
	write_pairs_to_file(edges_to_be_removed,edges_to_be_removed_file)
	return edges_to_be_removed 
Example #8
Source File: test_strongly_connected.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_contract_scc1(self):
        G = nx.DiGraph()
        G.add_edges_from([
            (1, 2), (2, 3), (2, 11), (2, 12), (3, 4), (4, 3), (4, 5), (5, 6),
            (6, 5), (6, 7), (7, 8), (7, 9), (7, 10), (8, 9), (9, 7), (10, 6),
            (11, 2), (11, 4), (11, 6), (12, 6), (12, 11),
        ])
        scc = list(nx.strongly_connected_components(G))
        cG = nx.condensation(G, scc)
        # DAG
        assert_true(nx.is_directed_acyclic_graph(cG))
        # nodes
        assert_equal(sorted(cG.nodes()), [0, 1, 2, 3])
        # edges
        mapping={}
        for i, component in enumerate(scc):
            for n in component:
                mapping[n] = i
        edge = (mapping[2], mapping[3])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[2], mapping[5])
        assert_true(cG.has_edge(*edge))
        edge = (mapping[3], mapping[5])
        assert_true(cG.has_edge(*edge)) 
Example #9
Source File: test_recognition.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_multicycle():
    G = nx.MultiDiGraph()
    G.add_edges_from([(0, 1), (0, 1)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #10
Source File: test_generators.py    From CausalDiscoveryToolbox with MIT License 5 votes vote down vote up
def test_noises():
        for noise in ['gaussian', 'uniform']:
            data, agg = AcyclicGraphGenerator("linear", npoints=200, nodes=10, parents_max=3, noise=noise).generate()
            assert type(agg) == nx.DiGraph
            assert nx.is_directed_acyclic_graph(agg) 
Example #11
Source File: dag.py    From lightflow with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate(self, graph):
        """ Validate the graph by checking whether it is a directed acyclic graph.

        Args:
            graph (DiGraph): Reference to a DiGraph object from NetworkX.

        Raises:
            DirectedAcyclicGraphInvalid: If the graph is not a valid dag.
        """
        if not nx.is_directed_acyclic_graph(graph):
            raise DirectedAcyclicGraphInvalid(graph_name=self._name) 
Example #12
Source File: test_recognition.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_dag_nontree():
    G = nx.DiGraph()
    G.add_edges_from([(0,1), (0,2), (1,2)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #13
Source File: test_recognition.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_multicycle():
    G = nx.MultiDiGraph()
    G.add_edges_from([(0,1), (0,1)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #14
Source File: test_dag.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_is_directed_acyclic_graph(self):
        G = nx.generators.complete_graph(2)
        assert_false(nx.is_directed_acyclic_graph(G))
        assert_false(nx.is_directed_acyclic_graph(G.to_directed()))
        assert_false(nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)])))
        assert_true(nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))) 
Example #15
Source File: test_dag.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_topological_sort2(self):
        DG = nx.DiGraph({1: [2], 2: [3], 3: [4],
                         4: [5], 5: [1], 11: [12],
                         12: [13], 13: [14], 14: [15]})
        assert_raises(nx.NetworkXUnfeasible, nx.topological_sort, DG)
        assert_raises(nx.NetworkXUnfeasible, nx.topological_sort_recursive, DG)

        assert_false(nx.is_directed_acyclic_graph(DG))

        DG.remove_edge(1, 2)
        assert_equal(nx.topological_sort_recursive(DG),
                     [11, 12, 13, 14, 15, 2, 3, 4, 5, 1])
        assert_equal(nx.topological_sort(DG),
                     [11, 12, 13, 14, 15, 2, 3, 4, 5, 1])
        assert_true(nx.is_directed_acyclic_graph(DG)) 
Example #16
Source File: mcmc_sampler.py    From dowhy with MIT License 5 votes vote down vote up
def fit_causal_model(self, g, df, data_types, initialization_trace=None):
        if nx.is_directed_acyclic_graph(g):
            with pm.Model() as model:
                g = self.apply_data_types(g, data_types)
                g = self.apply_parents(g)
                g = self.apply_parameters(g, df, initialization_trace=initialization_trace)
                g = self.build_bayesian_network(g, df)
                trace = pm.sample(1000, tune=1000)
        else:
            raise Exception("Graph is not a DAG!")
        return g, trace 
Example #17
Source File: mcmc_sampler.py    From dowhy with MIT License 5 votes vote down vote up
def sample_prior_causal_model(self, g, df, data_types, initialization_trace):
        if nx.is_directed_acyclic_graph(g):
            with pm.Model() as model:
                g = self.apply_data_types(g, data_types)
                g = self.apply_parents(g)
                g = self.apply_parameters(g, df, initialization_trace=initialization_trace)
                g = self.build_bayesian_network(g, df)
                trace = pm.sample_prior_predictive(1)
        else:
            raise Exception("Graph is not a DAG!")
        return g, trace 
Example #18
Source File: test_recognition.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_dag_nontree():
    G = nx.DiGraph()
    G.add_edges_from([(0, 1), (0, 2), (1, 2)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #19
Source File: test_generators.py    From CausalDiscoveryToolbox with MIT License 5 votes vote down vote up
def test_acyclic_generators():
    for mechanism in mechanisms:
        g = AcyclicGraphGenerator(mechanism, npoints=200, nodes=10, parents_max=3)
        data, agg = g.generate()
        g.to_csv('test')
        # cleanup
        os.remove('test_data.csv')
        os.remove('test_target.csv')
        assert type(agg) == nx.DiGraph
        assert nx.is_directed_acyclic_graph(agg) 
Example #20
Source File: test_dag.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_is_directed_acyclic_graph(self):
        G = nx.generators.complete_graph(2)
        assert_false(nx.is_directed_acyclic_graph(G))
        assert_false(nx.is_directed_acyclic_graph(G.to_directed()))
        assert_false(nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)])))
        assert_true(nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))) 
Example #21
Source File: test_dag.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_topological_sort2(self):
        DG = nx.DiGraph({1: [2], 2: [3], 3: [4],
                         4: [5], 5: [1], 11: [12],
                         12: [13], 13: [14], 14: [15]})
        assert_raises(nx.NetworkXUnfeasible, consume, nx.topological_sort(DG))

        assert_false(nx.is_directed_acyclic_graph(DG))

        DG.remove_edge(1, 2)
        consume(nx.topological_sort(DG))
        assert_true(nx.is_directed_acyclic_graph(DG)) 
Example #22
Source File: test_recognition.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_dag_nontree():
    G = nx.DiGraph()
    G.add_edges_from([(0,1), (0,2), (1,2)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #23
Source File: test_recognition.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_multicycle():
    G = nx.MultiDiGraph()
    G.add_edges_from([(0,1), (0,1)])
    assert_false(nx.is_tree(G))
    assert_true(nx.is_directed_acyclic_graph(G)) 
Example #24
Source File: test_dag.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_is_directed_acyclic_graph(self):
        G = nx.generators.complete_graph(2)
        assert_false(nx.is_directed_acyclic_graph(G))
        assert_false(nx.is_directed_acyclic_graph(G.to_directed()))
        assert_false(nx.is_directed_acyclic_graph(nx.Graph([(3, 4), (4, 5)])))
        assert_true(nx.is_directed_acyclic_graph(nx.DiGraph([(3, 4), (4, 5)]))) 
Example #25
Source File: test_dag.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_topological_sort2(self):
        DG = nx.DiGraph({1: [2], 2: [3], 3: [4],
                         4: [5], 5: [1], 11: [12],
                         12: [13], 13: [14], 14: [15]})
        assert_raises(nx.NetworkXUnfeasible, consume, nx.topological_sort(DG))

        assert_false(nx.is_directed_acyclic_graph(DG))

        DG.remove_edge(1, 2)
        consume(nx.topological_sort(DG))
        assert_true(nx.is_directed_acyclic_graph(DG)) 
Example #26
Source File: data_generator.py    From feagen with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def draw_dag(cls, path, data_keys):
        # pylint: disable=protected-access
        dag = cls._dag.draw(path, data_keys, root_node_key='generate',
                            reverse=True)
        if not nx.is_directed_acyclic_graph(dag):
            print("Warning! The graph is not acyclic!") 
Example #27
Source File: CGNN.py    From CausalDiscoveryToolbox with MIT License 5 votes vote down vote up
def hill_climbing(data, graph, **kwargs):
    """Hill Climbing optimization: a greedy exploration algorithm."""
    if isinstance(data, th.utils.data.Dataset):
        nodelist = data.get_names()
    elif isinstance(data, pd.DataFrame):
        nodelist = list(data.columns)
    else:
        raise TypeError('Data type not understood')
    tested_candidates = [nx.adj_matrix(graph, nodelist=nodelist, weight=None)]
    best_score = parallel_graph_evaluation(data,
                                           tested_candidates[0].todense(),
                                           ** kwargs)
    best_candidate = graph
    can_improve = True
    while can_improve:
        can_improve = False
        for (i, j) in best_candidate.edges():
            test_graph = deepcopy(best_candidate)
            test_graph.add_edge(j, i, weight=test_graph[i][j]['weight'])
            test_graph.remove_edge(i, j)
            tadjmat = nx.adj_matrix(test_graph, nodelist=nodelist, weight=None)
            if (nx.is_directed_acyclic_graph(test_graph) and not any([(tadjmat != cand).nnz ==
                                                                      0 for cand in tested_candidates])):
                tested_candidates.append(tadjmat)
                score = parallel_graph_evaluation(data, tadjmat.todense(),
                                                  **kwargs)
                if score < best_score:
                    can_improve = True
                    best_candidate = test_graph
                    best_score = score
                    break
    return best_candidate 
Example #28
Source File: remove_cycle_edges_by_hierarchy_greedy.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def scc_based_to_remove_cycle_edges_iterately(g,nodes_score):
	from remove_self_loops import remove_self_loops_from_graph
	self_loops = remove_self_loops_from_graph(g)
	big_sccs = get_big_sccs(g)
	scc_nodes_score_dict = scores_of_nodes_in_scc(big_sccs,nodes_score)
	edges_to_be_removed = []
	if len(big_sccs) == 0:
		print("After removal of self loop edgs: %s" % nx.is_directed_acyclic_graph(g))
		return self_loops
	
	remove_cycle_edges_by_agony_iterately(big_sccs,scc_nodes_score_dict,edges_to_be_removed)
	#print(" # edges to be removed: %d" % len(edges_to_be_removed))
	return edges_to_be_removed+self_loops 
Example #29
Source File: remove_cycle_edges_by_hierarchy_voting.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def scc_based_to_remove_cycle_edges_iterately(g,edges_score):
	big_sccs = get_big_sccs(g)
	if len(big_sccs) == 0:
		print("After removal of self loop edgs: %s" % nx.is_directed_acyclic_graph(g))
		return []
	edges_to_be_removed = []
	remove_cycle_edges_by_agony_iterately(big_sccs,edges_score,edges_to_be_removed)
	#print(" # edges to be removed: %d" % len(edges_to_be_removed))
	return edges_to_be_removed 
Example #30
Source File: remove_cycle_edges_by_hierarchy_BF.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def scc_based_to_remove_cycle_edges_iterately(g,nodes_score,is_Forward):
	big_sccs = get_big_sccs(g)
	if len(big_sccs) == 0:
		print("After removal of self loop edgs: %s" % nx.is_directed_acyclic_graph(g))
		return []
	scc_nodes_score_dict = scores_of_nodes_in_scc(big_sccs,nodes_score)
	edges_to_be_removed = []
	remove_cycle_edges_by_ranking_score_iterately(big_sccs,scc_nodes_score_dict,edges_to_be_removed,is_Forward)
	#print(" # edges to be removed: %d" % len(edges_to_be_removed))
	return edges_to_be_removed