Python networkx.edge_dfs() Examples

The following are 6 code examples of networkx.edge_dfs(). 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: learning.py    From science_rcn with MIT License 6 votes vote down vote up
def adjust_edge_perturb_radii(frcs,
                              graph,
                              perturb_factor=2):
    """Returns a new graph where the 'perturb_radius' has been adjusted to account for 
    rounding errors. See train_image for parameters and returns.
    """
    graph = graph.copy()

    total_rounding_error = 0
    for n1, n2 in nx.edge_dfs(graph):
        desired_radius = distance.euclidean(frcs[n1, 1:], frcs[n2, 1:]) / perturb_factor

        upper = int(np.ceil(desired_radius))
        lower = int(np.floor(desired_radius))
        round_up_error = total_rounding_error + upper - desired_radius
        round_down_error = total_rounding_error + lower - desired_radius
        if abs(round_up_error) < abs(round_down_error):
            graph.edge[n1][n2]['perturb_radius'] = upper
            total_rounding_error = round_up_error
        else:
            graph.edge[n1][n2]['perturb_radius'] = lower
            total_rounding_error = round_down_error
    return graph 
Example #2
Source File: test_highlevel.py    From tskit with MIT License 5 votes vote down vote up
def verify_nx_for_tutorial_algorithms(self, tree, g):
        # traversing upwards
        for u in tree.leaves():
            path = []
            v = u
            while v != tskit.NULL:
                path.append(v)
                v = tree.parent(v)

            self.assertSetEqual(set(path), {u} | nx.ancestors(g, u))
            self.assertEqual(
                path,
                [u] + [n1 for n1, n2, _ in nx.edge_dfs(g, u, orientation="reverse")],
            )

        # traversals with information
        def preorder_dist(tree, root):
            stack = [(root, 0)]
            while len(stack) > 0:
                u, distance = stack.pop()
                yield u, distance
                for v in tree.children(u):
                    stack.append((v, distance + 1))

        for root in tree.roots:
            self.assertDictEqual(
                {k: v for k, v in preorder_dist(tree, root)},
                nx.shortest_path_length(g, source=root),
            )

        for root in tree.roots:
            # new traversal: measuring time between root and MRCA
            for u, v in itertools.combinations(nx.descendants(g, root), 2):
                mrca = tree.mrca(u, v)
                tmrca = tree.time(mrca)
                self.assertAlmostEqual(
                    tree.time(root) - tmrca,
                    nx.shortest_path_length(
                        g, source=root, target=mrca, weight="branch_length"
                    ),
                ) 
Example #3
Source File: osm_to_vissim.py    From vissim with MIT License 5 votes vote down vote up
def getStartNodes(self):
        """ Get a list of nodes that do not overlap when traversed.
        """
        edgeNodes = self.getExteriorNodes()
        for node in edgeNodes:
            for prev, n in nx.edge_dfs(self.G, source=node):
                if n in edgeNodes:
                    edgeNodes.remove(n)
        return edgeNodes

    # Intersection dict 
Example #4
Source File: osm_to_vissim.py    From vissim with MIT License 5 votes vote down vote up
def createIntersectionDict(self):
        """ Use depth-first search to map intersection nodes and lane widths.
            Input: graph, startNode
            Output: dictionary mapping of intersection nodes
        """
        intersections = {}
        for fromN, toN in nx.edge_dfs(self.G):
            if self.isIntersection(toN):
		print 'Processing intersection %d' %(int(toN))
                intersections[toN] = self.getIntersection(toN)
        return intersections

    # Ways dict 
Example #5
Source File: osm_to_vissim.py    From vissim with MIT License 5 votes vote down vote up
def createWaysDict(self):
        """ Begin with startNode and traverse the graph, collecting the nodes
            of each way. When a new way is encountered, start a new list of
            nodes. When a new intersection is encountered, pass the list of
            ways to the getWay function for processing.
            Input: graph, startNode
            Output: dictionary used for creating VISSIM links
        """
        waysDict = {}
        ways = []
        nodes = []
        prevAttr = None
        currAttr = None
        
        for fromN, toN in nx.edge_dfs(self.G):
            currAttr = self.G.edge[fromN][toN]
            print 'createWaysDict : fromN %s toN %s ' %(fromN,toN)
            #print currAttr['highway']
            if currAttr['highway'] not in self.roadTypes:
                continue
            if self.isIntersection(fromN):
                ways.append(nodes)
#                print ways
                waysDict.update(self.getWay(ways))
                ways = []
                nodes = []
            elif self.isNewWay(fromN, toN, prevAttr):
                ways.append(nodes)
                nodes = []
            nodes.append(fromN)
            nodes.append(toN)
            prevAttr = currAttr
            if self.isExterior(toN):
                ways.append(nodes)
                self.getWay(ways)
        ways.append(nodes)
        waysDict.update(self.getWay(ways))
        return waysDict

    # XY dict - translate nodes from ways dict to X,Y points including lane
    # offsets 
Example #6
Source File: bakefile.py    From bake with ISC License 4 votes vote down vote up
def depends_on(self, *, include_filters=True, recursive=False, include_fakes=True):
        def gen_actions(include_filters=include_filters, include_fakes=include_fakes):
            task_strings = self.declaration_line.split(":", 1)[1].split()

            task_name_index_tuples = [
                (self.bf.find_chunk(task_name=s), s) for s in task_strings
            ]

            for i, task_string in task_name_index_tuples:

                if task_string.startswith("@"):
                    if include_filters:
                        yield TaskFilter(task_string, bf=self.bf)
                elif i is None:
                    if include_fakes:
                        yield FakeTaskScript(task_string, bf=self.bf)
                else:
                    # Otherwise, create the task.
                    yield TaskScript(chunk_index=i, bf=self.bf)

        actions = [t for t in gen_actions()]

        if recursive:
            graph = {}
            actions = []

            edge_view = networkx.edge_dfs(self.bf.graph, self, orientation="original")

            for parent, child, _ in edge_view:
                if parent not in graph:
                    graph[parent] = [child]
                else:
                    if child not in graph[parent]:
                        graph[parent].append(child)

            for task in graph:
                for action in graph[task]:
                    for dep_action in graph.get(action, []):
                        actions.append(dep_action)
                    actions.append(action)

        # Remove filters, if requested to do so.
        if not include_filters:
            _actions = []
            for action in actions:
                if not isinstance(action, TaskFilter):
                    _actions.append(action)

            actions = _actions

        # Remove duplicates from the list.
        _actions = []
        for action in actions:
            if action not in _actions:
                _actions.append(action)
        actions = _actions

        return actions