当前位置: 首页>>代码示例>>Python>>正文


Python networkx.bidirectional_dijkstra函数代码示例

本文整理汇总了Python中networkx.bidirectional_dijkstra函数的典型用法代码示例。如果您正苦于以下问题:Python bidirectional_dijkstra函数的具体用法?Python bidirectional_dijkstra怎么用?Python bidirectional_dijkstra使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了bidirectional_dijkstra函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: LabelFeature

    def LabelFeature(self, graph):
        # for each graph
        # pick a random source and a random target
        # run each of the networkx src tgt shortest path algorithms one by one
        # time how long they each take
        # repeat for N different srcs/tgts
        # find the average time for each algorithm
        # make the label for that graph the one with the shortest time
        # feature key: 0 = dijkstra, 1 = bidijkstra 2 = astar
        numIters = 10
        n = networkx.number_of_nodes(graph)
        dijkstraTimes = np.zeros(numIters)
        biDijkstraTimes = np.zeros(numIters)
        aStarTimes = np.zeros(numIters)
        for i in xrange(numIters):
            # pick a random source and target
            src = np.random.randint(0, n) + 1
            tgt = np.random.randint(0, n) + 1
            while tgt == src:
                tgt = np.random.randint(0, n) + 1

            dijkstraTime = time.time()
            try:
                networkx.dijkstra_path(graph, src, tgt)
            except:
                # no path found
                i -= 1
                continue

            dijkstraTime = time.time() - dijkstraTime
            dijkstraTimes[i] = dijkstraTime

            biDijkstraTime = time.time()
            networkx.bidirectional_dijkstra(graph, src, tgt)
            biDijkstraTime = time.time() - biDijkstraTime
            biDijkstraTimes[i] = biDijkstraTime

            aStarTime = time.time()
            networkx.astar_path(graph, src, tgt)
            aStarTime = time.time() - aStarTime
            aStarTimes[i] = aStarTime

        meanDijkstra = np.mean(dijkstraTimes)
        meanBiDijkstra = np.mean(biDijkstraTimes)
        meanAStar = np.mean(aStarTimes)

        minTime = min(meanDijkstra, meanBiDijkstra, meanAStar)
        if meanDijkstra == minTime:
            label = 0
        elif meanBiDijkstra == minTime:
            label = 1
        else:
            label = 2

        return label
开发者ID:jhurwitzupenn,项目名称:CIS419Project,代码行数:55,代码来源:IncrementalGraphAnalyzer.py

示例2: traceEndpoints

 def traceEndpoints(self, key=0):
     """Uses the bidirectional dijkstra to traceback the paths from the endpoints"""
     og = nx.DiGraph(spacing=None, origin=None, orientation=None)
     self._populateImageFeaturesToGraph(og)
     currentRoot = self.roots[(self.currentGraphKey,key)]
     og.graph["root"] = currentRoot
     endpoints = self.endpoints[self.currentGraphKey]
     bifurcations = self.bifurcations[self.currentGraphKey]
     cg = self.graphs[self.currentGraphKey]
     if( self.VERBOSE ):
         print("current root is",currentRoot)
     for e in endpoints:
         plen, path = nx.bidirectional_dijkstra(cg, currentRoot, e)
         i = 0
         start = currentRoot
         path = path[1:]
         while( path ):               
             try:
                 if( path[i] in bifurcations ):
                     og.add_edge(start,path[i],path=path[:i])
                     start = path[i]
                     path = path[i+1:]
                     i = 0
                 else:
                     i += 1
             except IndexError:
                 og.add_edge(start,e,{'path':path[:-1]})
                 path = None
     self.orderedGraphs[(self.currentGraphKey,key)] = og
开发者ID:chapmanbe,项目名称:vasctree,代码行数:29,代码来源:SkeletonGraph.py

示例3: set_random_loads

    def set_random_loads(max_for_each_route):
        scheme_len = len(SystemBuilder.scheme.node)
        for route in SystemBuilder.routes:
            for k in range(int(random() * max_for_each_route)):

                dispatch_st_num = route.route_list[int(random() * route.length())]

                destination_is_founded = False
                counter = 0
                while not destination_is_founded:
                    counter += 1
                    assert counter < 999
                    destination_st_num = int(random() * scheme_len) + 1
                    try:
                        way_length, way_list = nx.bidirectional_dijkstra(
                            SystemBuilder.routes_scheme, dispatch_st_num, destination_st_num)
                        new_growth_coeff = GrowthCoeff(RandomFunctions.growth_coef_func(), way_list)
                        destination_is_founded = True
                        SystemBuilder.growth_coeffs.append(new_growth_coeff)
                        attr_name = SystemBuilder.ATTRIBUTE_GROWTH_LIST
                        SystemBuilder.scheme.node[dispatch_st_num][attr_name].append(new_growth_coeff)
                    except nx.exception.NetworkXError:
                        pass
                    except nx.exception.NetworkXNoPath:
                        pass
开发者ID:shawinmihail,项目名称:TrainsManagment,代码行数:25,代码来源:SystemBuilder.py

示例4: getPath

    def getPath(self, nd0, nd1, weight_name):
        
        try:
            _, nodes = networkx.bidirectional_dijkstra(
                self.digraph,
                nd0, nd1,
                weight_name
            )
        except networkx.NetworkXNoPath:
            raise NoPath('no path found between the points')


        def getKey(u, v):
            keys = []
            for k in self.digraph[u][v]:
                weight = self.digraph[u][v][k][weight_name]
                keys.append((weight, k))
            keys.sort()
            return keys[0][1]

        keys = []
        for a, b in zip(nodes[:-1], nodes[1:]):
            k = getKey(a,b)
            keys.append(k)

        return nodes, keys
开发者ID:ericstalbot,项目名称:django-routefinder,代码行数:26,代码来源:routefinder.py

示例5: find_path

def find_path(n1, n2, skip = []):
    start = time.time()
    path = None
    status = 'ok'

    a1 = find_artist(n1)
    a2 = find_artist(n2)

    if not a1:
        status = "Can't find " + n1
    if not a2:
        status = "Can't find " + n2

    if a1 and a2:
        if skip and len(skip) > 0:
            # graph = G.copy()
            graph = G
        else:
            graph = G

        remove_nodes(graph, skip)
        try:
            l, path = nx.bidirectional_dijkstra(graph, a1['id'], a2['id'], 'weight')

        except nx.NetworkXNoPath:
            status = 'No path found between ' + n1 + " and " + n2;
            
        restore_nodes(graph, skip)

    print 'find_path took %s seconds' % (time.time() - start,)
    return status, path
开发者ID:ibenka,项目名称:BoilTheFrog,代码行数:31,代码来源:graph.py

示例6: _areConnected

 def _areConnected(self, minkey1, minkey2):
     try:
         ret = nx.bidirectional_dijkstra(self.graph, minkey1, minkey2)
         if ret != None:
             return True
         else: return False
     except nx.NetworkXNoPath:
         return False
开发者ID:js850,项目名称:pele,代码行数:8,代码来源:min_ts_graph.py

示例7: findNeighbours

    def findNeighbours(src, dest):
        
        G = nx.Graph()
        db = MySQLdb.connect(host = "localhost", user = "root", passwd = "", db = "project")
        cursor = db.cursor()
        cursor.execute("SELECT * FROM nodes")
        for row in cursor.fetchall():
            G.add_node(int(row[0]))
         
        cursor.execute("SELECT * FROM lanes")
        for row in cursor.fetchall():
            G.add_edge(int(row[1]), int(row[2]))
            G[row[1]][row[2]]['weight'] = row[3]
         
        print G.edges()
        print G.nodes()
        
        query = "SELECT node_id FROM locations WHERE name like '" + src + "'"
        cursor.execute(query)
        try:
            fetch = cursor.fetchall()
            source = fetch[0][0]

            query = "SELECT node_id FROM locations WHERE type = '" + dest + "'"
            print query
            cursor.execute(query)
            results = cursor.fetchall()
            print results
            
            F = []
            for x in results:
                temp = nx.bidirectional_dijkstra(G, source, int(x[0]), weight = 'weight')
                F.append(temp)
            
            maxval = min(F[0:])
            index = []
            for ctr in range(len(F)):
                if F[ctr][0] == maxval[0]:
                    index.append(ctr)

            cursor.execute("SELECT nodes.node_id, nodes.x, nodes.y, name from nodes left join locations on nodes.node_id = locations.node_id")
            results = cursor.fetchall()
            Pathlist = []
            for y in index:
                A = []
                for x in F[y][1]:
                    for row in results:
                        if x == row[0]:
                            A.append((row[1],row[2],row[3]))
                Pathlist.append(A)
                
            return Pathlist
            
        except:
            print "Invalid Query"
            return []
开发者ID:pknelakuditi,项目名称:campus-route,代码行数:56,代码来源:finder.py

示例8: areConnected

 def areConnected(self, min1, min2):
     return self.connected_components.areConnected(min1, min2)
     try:
         ret = nx.bidirectional_dijkstra(self.graph, min1, min2)
         if ret != None:
             return True
         else: 
             return False
     except nx.NetworkXNoPath:
         return False
开发者ID:wwwtyro,项目名称:PyGMIN,代码行数:10,代码来源:_graph.py

示例9: get_distance

    def get_distance(self,source,sink):
        """
        find shortest path length
        """

        minDistance = 1e8
        if self.G.has_node(source) and self.G.has_node(sink):
            (dijkDist, dijkPath) = nx.bidirectional_dijkstra(self.G,source,sink)
            return dijkDist
        return None
开发者ID:ajrichards,项目名称:htsint,代码行数:10,代码来源:TermDistances.py

示例10: _search_grammer_path

 def _search_grammer_path(self, pos_via_point):
     pos_via_and_end = (self.START_NODE,) + pos_via_point + (self.END_NODE,)
     paths = []
     cost = 0
     for network_start_end in sliding_window(2, pos_via_and_end):
         path = networkx.bidirectional_dijkstra(self._grammer_graph, network_start_end[0], network_start_end[1])
         cost += path[0]
         node_path = path[1][1:]
         paths += node_path
     paths.pop()
     return cost, paths
开发者ID:yukota,项目名称:elpod,代码行数:11,代码来源:sentence.py

示例11: qfind

def qfind(a1, a2):
    start = time.time()
    path = None

    if a1 and a2:
        graph = G
        try:
            l, path = nx.bidirectional_dijkstra(graph, a1['id'], a2['id'], 'weight')
        except nx.NetworkXNoPath:
            pass
    return path
开发者ID:ibenka,项目名称:BoilTheFrog,代码行数:11,代码来源:graph.py

示例12: path

    def path(self, source_name, target_name, skipset=set()):
        def get_weight(src, dest, attrs):
            if src in skipset or dest in skipset:
                # print "gw", srx, dest, attrs, 10000
                return 10000
            # print "gw", src, dest, attrs, 1
            return attrs['weight']

        results = { 
            'status': 'ok'
        }

        if len(source_name) == 0:
            results['status'] = 'error'
            results['reason'] = "No artist given"
        else:
            source_aid = self.search(source_name)
            if source_aid == None:
                results['status'] = 'error'
                results['reason'] = "Can't find " + source_name

            target_aid = self.search(target_name)
            if target_aid == None:
                results['status'] = 'error'
                results['reason'] = "Can't find " + target_name

            print "s=t", source_aid, target_aid
            if source_aid not in self.G:
                results['status'] = 'error'
                results['reason'] = "Can't find " + source_name + " in the artist graph"

            if target_aid not in self.G:
                results['status'] = 'error'
                results['reason'] = "Can't find " + target_name + " in the artist graph"

        if source_aid and target_aid and results['status'] == 'ok':
            start = time.time()
            if len(skipset) > 0:
                rpath = nx.dijkstra_path(self.G, source_aid, target_aid, get_weight)
                score = len(rpath)
            else:
                score, rpath = nx.bidirectional_dijkstra(self.G, source_aid, target_aid)
            pdelta = time.time() - start
            results['score'] = score
            populated_path = [self.get_artist(aid) for aid in rpath]
            fdelta = time.time() - start
                
            results['status'] = 'ok'
            results['raw_path'] = rpath
            results['path'] = populated_path
            results['pdelta'] = pdelta * 1000
            results['fdelta'] = fdelta * 1000
        return results
开发者ID:plamere,项目名称:BoilTheFrog,代码行数:53,代码来源:artist_graph.py

示例13: _dijkstra

    def _dijkstra(self, verbose, debug):
        try:
            if verbose:
                print('Dijkstra algorithm', flush=True)

            length,triPath=nx.bidirectional_dijkstra(self._tGraph, self._startTriplet, self._endTriplet)


        except (nx.NetworkXNoPath, nx.NetworkXError):
            print('ERROR: Impossible to find a path')
            triPath = []

        return triPath
开发者ID:trianam,项目名称:voropath,代码行数:13,代码来源:voronizator.py

示例14: get_best_path

def get_best_path (init_dest, final_dest):
    DG = makeDiGraph()
    x= findCommonRoutes(init_dest, final_dest, DG)
    # check if any common bus is active
    activeRoutes = isActive(x)
    if(len(activeRoutes) == 0):
        print "You are fucked, buddy. No active routes"
    else:
        print activeRoutes
        # TOTAL TIME incomplete !!
        total_time(x,init_dest, activeRoutes)
        best = (nx.bidirectional_dijkstra(DG, init_dest, final_dest , weight = 'edge_weight') )
        print (best)
开发者ID:avdaredevil,项目名称:RUJarvis,代码行数:13,代码来源:Graph.py

示例15: mp_worker

def mp_worker((source,sink,graphPath)):
    """
    find shortest path length
    """
    G = nx.read_gpickle(graphPath)
    minDistance = 1e8
    if G.has_node(source) and G.has_node(sink):
        (dijkDist, dijkPath) = nx.bidirectional_dijkstra(G,source,sink)
    else:
        dijkDist = None
    
    if dijkDist:
        return [source,sink,dijkDist]
开发者ID:xflicsu,项目名称:htsint,代码行数:13,代码来源:TermDistances.py


注:本文中的networkx.bidirectional_dijkstra函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。