Python networkx.has_path() Examples

The following are 30 code examples of networkx.has_path(). 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: path_check.py    From bap-tutorial with MIT License 6 votes vote down vote up
def verify(prog, src_name, dst_name):
    src = prog.subs.find(src_name)
    dst = prog.subs.find(dst_name)
    if src is None or dst is None:
        return None

    graphs = GraphsBuilder()
    graphs.run(prog)
    cg = graphs.callgraph

    if nx.has_path(cg, src.id.number, dst.id.number):
        return ('calls', nx.shortest_path(cg, src.id.number, dst.id.number))

    calls = CallsitesCollector(graphs.callgraph, src.id.number, dst.id.number)

    for sub in prog.subs:
        calls.run(sub)
        cfg = graphs.callgraph.nodes[sub.id.number]['cfg']
        for src in calls.srcs:
            for dst in calls.dsts:
                if src != dst and nx.has_path(cfg, src, dst):
                    return ('sites', nx.shortest_path(cfg, src, dst))
        calls.clear()

    return None 
Example #2
Source File: test_dag.py    From aws-kube-codesuite with Apache License 2.0 6 votes vote down vote up
def test_topological_sort3(self):
        DG = nx.DiGraph()
        DG.add_edges_from([(1, i) for i in range(2, 5)])
        DG.add_edges_from([(2, i) for i in range(5, 9)])
        DG.add_edges_from([(6, i) for i in range(9, 12)])
        DG.add_edges_from([(4, i) for i in range(12, 15)])

        def validate(order):
            ok_(isinstance(order, list))
            assert_equal(set(order), set(DG))
            for u, v in combinations(order, 2):
                assert_false(nx.has_path(DG, v, u))
        validate(list(nx.topological_sort(DG)))

        DG.add_edge(14, 1)
        assert_raises(nx.NetworkXUnfeasible, consume, nx.topological_sort(DG)) 
Example #3
Source File: test_dag.py    From Carnets with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_topological_sort3(self):
        DG = nx.DiGraph()
        DG.add_edges_from([(1, i) for i in range(2, 5)])
        DG.add_edges_from([(2, i) for i in range(5, 9)])
        DG.add_edges_from([(6, i) for i in range(9, 12)])
        DG.add_edges_from([(4, i) for i in range(12, 15)])

        def validate(order):
            ok_(isinstance(order, list))
            assert_equal(set(order), set(DG))
            for u, v in combinations(order, 2):
                assert_false(nx.has_path(DG, v, u))
        validate(list(nx.topological_sort(DG)))

        DG.add_edge(14, 1)
        assert_raises(nx.NetworkXUnfeasible, consume, nx.topological_sort(DG)) 
Example #4
Source File: test_dag.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 6 votes vote down vote up
def test_topological_sort3(self):
        DG = nx.DiGraph()
        DG.add_edges_from([(1, i) for i in range(2, 5)])
        DG.add_edges_from([(2, i) for i in range(5, 9)])
        DG.add_edges_from([(6, i) for i in range(9, 12)])
        DG.add_edges_from([(4, i) for i in range(12, 15)])

        def validate(order):
            ok_(isinstance(order, list))
            assert_equal(set(order), set(DG))
            for u, v in combinations(order, 2):
                assert_false(nx.has_path(DG, v, u))
        validate(nx.topological_sort_recursive(DG))
        validate(nx.topological_sort(DG))

        DG.add_edge(14, 1)
        assert_raises(nx.NetworkXUnfeasible, nx.topological_sort, DG)
        assert_raises(nx.NetworkXUnfeasible, nx.topological_sort_recursive, DG) 
Example #5
Source File: graph.py    From mayo with MIT License 6 votes vote down vote up
def _optimize_propagation(self):
        changed = False
        # remove redundant tensor nodes from graph
        for node in list(self.nodes()):
            if not isinstance(node, TensorNode):
                continue
            preds = node.predecessors
            succs = node.successors
            if not (len(preds) == len(succs) == 1):
                continue
            changed = True
            # remove current node as it is redundant
            self.remove_node(node)
            self.add_edge(preds[0], succs[0])
        # remove nodes not connected to output
        output_nodes = self.output_nodes()
        for node in list(self.nodes()):
            if not any(self.has_path(node, o) for o in output_nodes):
                self.remove_node(node)
        return changed 
Example #6
Source File: surface_codes.py    From QTop with GNU General Public License v3.0 6 votes vote down vote up
def hasLogicalError(self):
        for type in self.types:
            for charge_type in ['X','Z']:
                LogicalLattice = self.Primal.copy()
                for node in self.Primal.nodes():
                    if self.Primal.node[node]['charge'][charge_type] == 0:
                        LogicalLattice.remove_node(node)
                for node1 in LogicalLattice.nodes():
                    for node2 in LogicalLattice.nodes():
                        if node1 in self.Boundary[type] and node2 in self.Boundary[type]:
                            if self.Boundary[type][node1] != self.Boundary[type][node2]:
                                start, end = node1, node2
                                if start in LogicalLattice.nodes() and end in LogicalLattice.nodes():
                                    if nx.has_path(LogicalLattice, start, end):
                                        return True

        return False 
Example #7
Source File: introduce_cycles_to_DAG.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_extra_edges(g,number_of_edges):
	number = 0
	num_nodes = g.number_of_nodes()
	nodes = g.nodes()
	extra_edges = set()
	while len(extra_edges) < number_of_edges:
		u,v = np.random.randint(0,num_nodes,2)
		u = nodes[u]
		v = nodes[v]
		if nx.has_path(g,u,v):
			if (v,u) not in extra_edges:
				extra_edges.add((v,u))	
		if nx.has_path(g,v,u):
			if (u,v) not in extra_edges:
				extra_edges.add((u,v))
	extra_edges = list(extra_edges)
	print("# extra edges added (path lenght unconstrainted): %d" % (len(extra_edges)))
	return extra_edges 
Example #8
Source File: introduce_cycles_to_DAG.py    From breaking_cycles_in_noisy_hierarchies with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def add_cycle_edges_by_path(g,number_of_edges,path_length = 5):
	number = 0
	num_nodes = g.number_of_nodes()
	nodes = g.nodes()
	extra_edges = []
	while number < number_of_edges:
		u,v = np.random.randint(0,num_nodes,2)
		u = nodes[u]
		v = nodes[v]
		if nx.has_path(g,u,v):
			length = nx.shortest_path_length(g,source = u,target = v)
			if length <= path_length:
				extra_edges.append((v,u))
				number += 1
		if nx.has_path(g,v,u):
			length = nx.shortest_path_length(g,source = v,target = u)
			if length <= path_length:
				extra_edges.append((u,v))
				number += 1
	print("# extra edges added with path length <= %d: %d" % (path_length,len(extra_edges)))
	return extra_edges 
Example #9
Source File: test_networkx.py    From beagle with MIT License 6 votes vote down vote up
def test_one_edge(nx):
    proc = Process(process_id=10, process_image="test.exe", command_line="test.exe /c foobar")
    other_proc = Process(process_id=12, process_image="best.exe", command_line="best.exe /c 123456")

    proc.launched[other_proc].append(timestamp=1)

    G = nx(nodes=[proc, other_proc])

    assert len(G.nodes()) == 2
    assert len(G.edges()) == 1

    u = hash(proc)
    v = hash(other_proc)

    assert networkx.has_path(G, u, v)
    assert "Launched" in G[u][v]
    assert {"timestamp": 1} == G[u][v]["Launched"]["data"][0] 
Example #10
Source File: test_mazes.py    From pixelworld with MIT License 6 votes vote down vote up
def check_solvable(self):
        # create the grid graph
        gf = nx.Graph()
        for r in xrange(self.world.height):
            for c in xrange(self.world.width):
                if c < self.world.width - 1:
                    gf.add_edge((r, c), (r, c + 1))
                if r < self.world.height - 1:
                    gf.add_edge((r, c), (r + 1, c))

        # remove nodes that are wall pixels
        for wall in self.world.objects['wall']:
            gf.remove_node(tuple(wall.state_index.tolist()))

        # find player and goal
        player = self.world.objects['self']
        goal = self.world.objects['goal']
        player_node = tuple(player.state_index.tolist())
        goal_node = tuple(goal.state_index.tolist())

        # check for existence of path
        self.assertTrue(nx.has_path(gf, player_node, goal_node)) 
Example #11
Source File: scipy2015_cbnx_demo_code.py    From Causal-Bayesian-NetworkX with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def create_path_complete_condition(transmit_node_pairs):
    """
    This factory allows us to specify that there are valid directed paths between pairs of nodes.
    This returns a function that takes an graph argument (G) 
    and verifies that for the list of node pairs the graph meets those dependency conditions. 
    
    NB: This is useful for making known indirect dependencies explicit.
    
    Variables:
    node_list is a list of 2-tuples of nodes that will have valid direct paths 
    from the first of the nodes to the second.
    """

    def path_complete_condition(G):
        return all([nx.has_path(G,x,y) for x,y in transmit_node_pairs])
    return path_complete_condition 
Example #12
Source File: graph.py    From mayo with MIT License 5 votes vote down vote up
def has_path(self, from_node, to_node):
        return nx.has_path(self.nx_graph, from_node, to_node) 
Example #13
Source File: ontology_definitions.py    From geosolver with Apache License 2.0 5 votes vote down vote up
def issubtype(child_type, parent_type):
    if child_type == "ground":
        return True
    if parent_type == "ground":
        return False
    if parent_type.startswith("*"):
        parent_type = parent_type[1:]
    if is_plural(child_type):
        child_type = child_type[:-1]
    if is_plural(parent_type):
        parent_type = parent_type[:-1]
    if child_type not in type_graph.nodes() or parent_type not in type_graph.nodes():
        return False
    return nx.has_path(type_graph, parent_type, child_type) 
Example #14
Source File: complete_formulas.py    From geosolver with Apache License 2.0 5 votes vote down vote up
def _apply_is(is_formulas, core_formulas):
    """
    Given a list of formulas, resolve transitivity by Is relation

    :param formula_nodes:
    :return:
    """
    graph = nx.Graph()
    explicit_sigs = set()
    equal_formulas = []
    for formula_node in is_formulas:
        assert isinstance(formula_node, FormulaNode)
        a_node, b_node = formula_node.children
        a_sig, b_sig = a_node.signature, b_node.signature

        if a_sig.return_type == 'number' or b_sig.return_type == 'number':
            equal_formula = FormulaNode(signatures['Equals'], [a_node, b_node])
            equal_formulas.append(equal_formula)

        if not isinstance(a_sig, VariableSignature) or not isinstance(b_sig, VariableSignature):
            continue

        graph.add_edge(a_sig, b_sig)
        p = re.compile("^([A-Z]+|[a-z])$")
        if p.match(a_sig.name):
            explicit_sigs.add(a_sig)
        if p.match(b_sig.name):
            explicit_sigs.add(b_sig)

    tester = lambda sig: sig in graph and any(nx.has_path(graph, sig, explicit_sig) for explicit_sig in explicit_sigs)
    getter = lambda sig: [explicit_sig for explicit_sig in explicit_sigs if nx.has_path(graph, sig, explicit_sig)][0]
    new_formula_nodes = [formula_node.replace_signature(tester, getter) for formula_node in core_formulas]
    new_formula_nodes = new_formula_nodes + equal_formulas
    return new_formula_nodes 
Example #15
Source File: utils.py    From Recycler with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_contigs_of_mates(node, bamfile, G):
    """ retrieves set of nodes mapped to by read pairs
        having one mate on node; discards isolated nodes
        because they tend to reflect irrelevant alignments
    """
    mate_tigs = set([])
    if node[-1] == "'": node=node[:-1]
    try:    
        for hit in bamfile.fetch(node):
            nref = bamfile.getrname(hit.next_reference_id)
            if nref != node:
                mate_tigs.add(nref)

    except ValueError:
        pass
    source_name = node #re.sub('NODE_','EDGE_', node)

    # print "before removal", mate_tigs
    to_remove = set([])
    for nd in mate_tigs:
        # flip name from "NODE_" prefix back to "EDGE_"
        # differs between contigs set and graph node names
        nd_name = nd #re.sub('NODE_','EDGE_', nd)
        if (G.in_degree(nd_name)==0 and G.out_degree(nd_name)==0) or \
        (not G.has_node(nd_name)):
            to_remove.add(nd)
        # see if nd reachable by node or vice-versa
        # try both flipping to rc and switching source and target    
        elif G.has_node(rc_node(source_name)) and not any([nx.has_path(G, source_name, nd_name), nx.has_path(G, rc_node(source_name),nd_name), \
          nx.has_path(G, nd_name, source_name), nx.has_path(G, nd_name, rc_node(source_name))]):
            to_remove.add(nd)
        elif not any([nx.has_path(G, source_name, nd_name), nx.has_path(G, nd_name, source_name)]):
            to_remove.add(nd)            
    mate_tigs -= to_remove
    # print "after removal", mate_tigs

    return mate_tigs 
Example #16
Source File: test_generic.py    From aws-kube-codesuite with Apache License 2.0 5 votes vote down vote up
def test_has_path(self):
        G = nx.Graph()
        nx.add_path(G, range(3))
        nx.add_path(G, range(3, 5))
        assert_true(nx.has_path(G,0,2))
        assert_false(nx.has_path(G,0,4)) 
Example #17
Source File: path_check.py    From bap-tutorial with MIT License 5 votes vote down vote up
def enter_Call(self,jmp):
        callee = direct(jmp.target[0])
        if callee:
            if nx.has_path(self.callgraph, callee.number, self.src):
                self.srcs.append(self.caller)
            if nx.has_path(self.callgraph, callee.number, self.dst):
                self.dsts.append(self.caller) 
Example #18
Source File: test_generic.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_has_path(self):
        G = nx.Graph()
        nx.add_path(G, range(3))
        nx.add_path(G, range(3, 5))
        assert_true(nx.has_path(G, 0, 2))
        assert_false(nx.has_path(G, 0, 4)) 
Example #19
Source File: test_generic.py    From qgisSpaceSyntaxToolkit with GNU General Public License v3.0 5 votes vote down vote up
def test_has_path(self):
        G = nx.Graph()
        G.add_path(range(3))
        G.add_path(range(3,5))
        assert_true(nx.has_path(G,0,2))
        assert_false(nx.has_path(G,0,4)) 
Example #20
Source File: UserTrigger.py    From dr_droid with Apache License 2.0 5 votes vote down vote up
def user_CFG_API(fcgnx, source_node_list, j):
    
    flag=False 
    for i in source_node_list:  
       if nx.has_path(fcgnx, i, j): 
          print (" {} ->  {}".format(i,j)) 
          #print (nx.dijkstra_path(fcgnx,i,j))               
          flag = True
          break
    return flag    
    
###
#  user trigger feature
### 
Example #21
Source File: graph_enumerator.py    From Causal-Bayesian-NetworkX with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_path_complete_condition(transmit_node_pairs):
    """
    This creates a closure that takes a graph as its input and returns a boolean value indicating whether the pairs of nodes in transmit_node_pairs are able to communicate from each tuple in transmit_node_pairs such that there is a path from transmit_node_pairs[i][0] to transmit_node_pairs[i][1]
    """

    def path_complete_condition(G):
        return all([nx.has_path(G,x,y) for x,y in transmit_node_pairs])
    return path_complete_condition 
Example #22
Source File: mazes.py    From pixelworld with MIT License 5 votes vote down vote up
def ensure_solvable(self, screen):
        """Delete wall pixels until there is a path from start to finish.
        """
        height, width = len(screen), len(screen[0])
        gf = nx.Graph()
        gf.add_node((1, 1))
        gf.add_node((height - 2, width - 2))
        for r, row in enumerate(screen):
            for c, x in enumerate(row):
                if c < width - 1 and screen[r][c] == ' ' and screen[r][c + 1] == ' ':
                    gf.add_edge((r, c), (r, c + 1))
                if r < height - 1 and screen[r][c] == ' ' and screen[r + 1][c] == ' ':
                    gf.add_edge((r, c), (r + 1, c))

        while not nx.has_path(gf, (1, 1), (height - 2, width - 2)):
            r, c = self.rng.randint(1, height - 1), self.rng.randint(1, width - 1)
            while screen[r][c] != 'W':
                r, c = self.rng.randint(1, height - 1), self.rng.randint(1, width - 1)

            screen[r][c] = ' '
            if c > 0 and screen[r][c - 1] == ' ':
                gf.add_edge((r, c), (r, c - 1))
            if r > 0 and screen[r - 1][c] == ' ':
                gf.add_edge((r, c), (r - 1, c))
            if c < width - 1 and screen[r][c + 1] == ' ':
                gf.add_edge((r, c), (r, c + 1))
            if r < height - 1 and screen[r + 1][c] == ' ':
                gf.add_edge((r, c), (r + 1, c)) 
Example #23
Source File: simple.py    From dqa-net with Apache License 2.0 5 votes vote down vote up
def guess(graph, question, choices):
    MAX = 9999
    SUBMAX = 999
    ques_node = find_node(graph, question)
    dists = []
    for choice in choices:
        choice_node = find_node(graph, choice)
        if ques_node is None and choice_node is None:
            dist = MAX
        elif ques_node is None and choice_node is not None:
            dist = SUBMAX
        elif ques_node is not None and choice_node is None:
            dist = MAX
        else:
            if nx.has_path(graph, ques_node, choice_node):
                pl = len(nx.shortest_path(graph, ques_node, choice_node))
                dist = pl
            else:
                dist = MAX
        dists.append(dist)
    answer, dist = min(enumerate(dists), key=lambda x: x[1])
    max_dist = max(dists)
    if dist == MAX:
        return None
    if dist == max_dist:
        return None
    return answer 
Example #24
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def connectedBoundaries(loops_graph, Exts):
    for ext1 in loops_graph.nodes():
        for ext2 in loops_graph.nodes():
            if ext1 in Exts and ext2 in Exts and ext1 != ext2:
                if nx.has_path(loops_graph,ext1,ext2):
                    path = nx.shortest_path(loops_graph, ext1, ext2)
                    for node in path:
                        if node not in Exts:
                            return ext1, ext2 
Example #25
Source File: dsp.py    From QTop with GNU General Public License v3.0 5 votes vote down vote up
def hasConnectedBoundaries(code, loops_graph, Exts):
    if len(loops_graph.edges()) <= 1:
        return False
    for ext1 in loops_graph.nodes():
        for ext2 in loops_graph.nodes():
            if ext1 in Exts and ext2 in Exts and ext1 != ext2:
                if nx.has_path(loops_graph,ext1,ext2):
                    path = nx.shortest_path(loops_graph, ext1, ext2)
                    for node in path:
                        if node not in Exts:
                            return True
    return False 
Example #26
Source File: paths.py    From pybel with MIT License 5 votes vote down vote up
def get_random_path(graph: BELGraph) -> List[BaseEntity]:
    """Get a random path from the graph as a list of nodes.

    :param graph: A BEL graph
    """
    wg = graph.to_undirected()

    nodes = wg.nodes()

    def pick_random_pair() -> Tuple[BaseEntity, BaseEntity]:
        """Get a pair of random nodes."""
        return random.sample(nodes, k=2)

    source, target = pick_random_pair()

    tries = 0
    sentinel_tries = 5

    while not nx.has_path(wg, source, target) and tries < sentinel_tries:
        tries += 1
        source, target = pick_random_pair()

    if tries == sentinel_tries:
        return [source]

    return nx.shortest_path(wg, source=source, target=target) 
Example #27
Source File: functional.py    From clevr-graph with The Unlicense 5 votes vote down vote up
def op(self, graph, a:List, b:NodeSpec):
		return [i for i in a if nx.has_path(graph.gnx, i["id"], b["id"])]


# --------------------------------------------------------------------------
# List operators
# -------------------------------------------------------------------------- 
Example #28
Source File: nx_edge_augmentation.py    From ibeis with Apache License 2.0 5 votes vote down vote up
def is_locally_k_edge_connected(G, s, t, k):
    """
    Tests to see if an edge in a graph is locally k-edge-connected

    See Also
    --------
    is_k_edge_connected

    Example
    -------
    >>> G = nx.barbell_graph(10, 0)
    >>> is_locally_k_edge_connected(G, 5, 15, k=1)
    True
    >>> is_locally_k_edge_connected(G, 5, 15, k=2)
    False
    >>> is_locally_k_edge_connected(G, 1, 5, k=2)
    True
    """
    if k < 1:
        raise ValueError('k must be positive, not {}'.format(k))

    # First try to quickly determine s, t is not k-locally-edge-connected in G
    if G.degree(s) < k or G.degree(t) < k:
        return False
    else:
        # Otherwise perform the full check
        if k == 1:
            return nx.has_path(G, s, t)
        else:
            localk = nx.connectivity.local_edge_connectivity(G, s, t, cutoff=k)
            return localk >= k 
Example #29
Source File: fwd.py    From Ryu-SDN-IP with MIT License 5 votes vote down vote up
def get_shortest_path(self, nx_graph, src_dpid, dst_dpid):

        if nx.has_path(nx_graph, src_dpid, dst_dpid):
            return nx.shortest_path(nx_graph, src_dpid, dst_dpid)

        return None 
Example #30
Source File: test_networkx.py    From beagle with MIT License 5 votes vote down vote up
def test_add_node_overlaps_existing(nx):
    proc = Process(process_id=10, process_image="test.exe", command_line="test.exe /c foobar")
    other_proc = Process(process_id=12, process_image="best.exe", command_line="best.exe /c 123456")

    proc.launched[other_proc].append(timestamp=1)

    backend = NetworkX(consolidate_edges=True, nodes=[proc, other_proc])
    G = backend.graph()

    assert len(G.nodes()) == 2
    assert len(G.edges()) == 1

    # Add a new node that *overlaps* an existing node (note - not the same node object.)
    proc2 = Process(process_id=10, process_image="test.exe", command_line="test.exe /c foobar")
    f = File(file_name="foo", file_path="bar")
    proc2.wrote[f]

    G = backend.add_nodes([proc2, f])

    # Graph grew, but only 3 nodes.
    assert len(G.nodes()) == 3
    assert len(G.edges()) == 2

    # Process should have both write and launched edges.

    u = hash(proc2)
    v = hash(other_proc)
    v2 = hash(f)

    assert networkx.has_path(G, u, v)
    assert networkx.has_path(G, u, v2)
    assert "Launched" in G[u][v]
    assert "Wrote" in G[u][v2]