def test_shortest_path_should_fail_if_source_does_not_exist(self):    
     gr = testlib.new_graph()
     try:
         shortest_path(gr, 'invalid')
         assert False
     except (KeyError):
         pass
 def test_shortest_path_should_fail_if_source_does_not_exist(self):
     gr = testlib.new_graph()
     try:
         shortest_path(gr, 'invalid')
         assert False
     except (KeyError):
         pass
    def describe_route(self, origin, destination, line_code='All', via=None):
        """
        Return the shortest route between origin and destination. Returns an list describing the route from start to finish
        Each element of the list is a tuple of form (station_name, direction, line_code)
        """
        if not self.network:
            return []
        if via:
            first_half = self.describe_route(origin, via, line_code)
            second_half = self.describe_route(via, destination, line_code)
            if first_half and second_half and second_half[0] == first_half[-1]:
                del second_half[0]
            return first_half + second_half

        origin_name = origin.name + ":entrance"
        destination_name = destination.name + ":exit"

        network = self.network[line_code]
        shortest_path_values = shortest_path(network, origin_name)
        shortest_path_dictionary = shortest_path_values[0]

        if origin_name not in shortest_path_dictionary or destination_name not in shortest_path_dictionary:
            return []
        # Shortest path dictionary consists of a dictionary of node names as keys, with the values
        # being the name of the node that preceded it in the shortest path
        # Count back from our destinaton, to the origin point
        path_taken = []
        while destination_name:
            path_taken.append(tuple(destination_name.split(":")))
            destination_name = shortest_path_dictionary[destination_name]

        # Trim off the entrance & exit nodes and reverse the list to get it in the right order
        path_taken = path_taken[1:-1][::-1]
        return path_taken
示例#4
0
    def dijkstra(self, startNode, targetNode):
        print("dijkstra:pygraph from %d to %d" % (startNode, targetNode))
        start = time.time()
        if not self.gr.has_node(startNode):
            print("start node not found %d" % (startNode))
            return None, None

        if not self.gr.has_node(targetNode):
            print("target node not found %d" % (targetNode))
            return None, None

        pathEdgeList = list()
        pathCost = 0.0
        st, dist = shortest_path(self.gr, startNode)

        path = self.route(self.gr, st, startNode, targetNode)

        for source, target in path:
            pathEdgeList.append(int(self.gr.edge_label((source, target))))

        if targetNode in dist:
            pathCost = float(dist[targetNode])

        curr = time.time()
        dur = int(curr - start)
        print("dijkstra:pygraph: " + str(dur) + "s")

        return pathEdgeList, pathCost
 def test_shortest_path_on_digraph(self):
     # Test stub: not checking for correctness yet
     gr = testlib.new_digraph(wt_range=(1,10))
     st, dist = shortest_path(gr, 0)
     for each in gr:
         if (each in dist):
             assert bf_path(gr, 0, each, dist[each])    
 def test_shortest_path_on_digraph(self):
     # Test stub: not checking for correctness yet
     gr = testlib.new_digraph(wt_range=(1, 10))
     st, dist = shortest_path(gr, 0)
     for each in gr:
         if (each in dist):
             assert bf_path(gr, 0, each, dist[each])
示例#7
0
 def test_shortest_path_on_graph(self):
     gr = new_graph(wt_range=(1,10))
     st, dist = shortest_path(gr, 0)
     print(st)
     print(dist)
     for each in gr:
         if (each in dist):
             assert bf_path(gr, 0, each, dist[each])
示例#8
0
def sample_gene_interactions(c, args, idx_to_sample):
    #fetch variant gene dict for all samples
    get_variant_genes(c, args, idx_to_sample)
    #file handle for fetching the hprd graph
    file_graph = os.path.join(path_dirname, 'hprd_interaction_graph')
    #load the graph using cPickle and close file handle
    gr = graph()
    f = open(file_graph, 'rb')
    gr = cPickle.load(f)
    f.close()
    k = []
    variants = []
    #calculate nodes from the graph
    hprd_genes = gr.nodes()
    if args.gene == None or args.gene not in hprd_genes:
        sys.stderr.write("gene name not given else not represented in the p-p interaction file\n")
    elif args.gene in hprd_genes:
        x, y = \
            breadth_first_search(gr,root=args.gene,filter=radius(args.radius))
        gst = digraph()
        gst.add_spanning_tree(x)
        dot = write(gst)
        out.write(dot)
        st, sd = shortest_path(gst, args.gene)
        
        if args.var_mode:
            for sample in sam.iterkeys():
                var = sam[str(sample)]
                #for each level return interacting genes if they are 
                # variants in the sample. 
                # 0th order would be returned if the user chosen 
                # gene is a variant in the sample        
                for x in range(0, (args.radius+1)):
                    for each in var:
                        for key, value in sd.iteritems():
                            if value == x and key == each[0]:
                                print "\t".join([str(sample),str(args.gene), \
                                          str(x), \
                                          str(key), \
                                          str(each[1]), \
                                          str(each[2]), \
                                          str(each[3])])        
        elif (not args.var_mode):
            for sample in sam.iterkeys():
                for each in sam[str(sample)]:
                    variants.append(each[0])
                for x in range(0, (args.radius+1)):
                    for key, value in sd.iteritems():
                        if value == x and key in set(variants):
                            k.append(key)
                    if k:
                        print "\t".join([str(sample), str(args.gene), \
                                 str(x)+"_order:", 
                                 ",".join(k)])
                    else:
                        print "\t".join([str(sample), str(args.gene), str(x)+"_order:", "none"])
                    #initialize keys for next iteration
                    k = []
示例#9
0
def shortest_distance(graph, node1, node2):
    """
    minimum distance between two nodes in the graph
    """
    undirected = to_undirected(graph)
    _, d = shortest_path(graph=undirected, source=node1)
    if node2 not in d:
        return -1
    return d[node2]
示例#10
0
def shortest_distance(graph, node1, node2):
    """
    minimum distance between two nodes in the graph
    """
    undirected = to_undirected(graph)
    _, d = shortest_path(graph=undirected, source=node1)
    if node2 not in d:
        return -1
    return d[node2]
示例#11
0
    def getPathLength(self, ingress, egress):
        try:
            paths = pygraph.algorithms.minmax.shortest_path(self.graph,ingress)
        except AttributeError:
            paths = mm.shortest_path(self.graph,ingress)

        if(egress in paths[1]):           
            return paths[1][egress]
        else:
            return -1
示例#12
0
    def getPathLength(self, source, sink):
        try:
            paths = pygraph.algorithms.minmax.shortest_path(self.graph,source)
        except AttributeError:
            paths = mm.shortest_path(self.graph,source)

        if(sink in paths[1]):           
            return paths[1][sink]
        else:
            return -1
示例#13
0
def find_top_of_component(graph, source_node):
    """
    Find the top node of the connected component in which source_node resides.
    Since this graph may contain cycles - we go "up" the graph, as long as we don't revisit nodes
    """
    _, d = shortest_path(
        reverse_graph_edges(graph),  # Reverse graph to go up
        source=source_node)
    return max(d.iteritems(),
               key=itemgetter(1))[0]  # Returns the farthest away node
示例#14
0
 def optimize(self, graph):
     """
     Build a dictionary mapping each pair of nodes to a number (the distance between them).
     
     @type  graph: graph
     @param graph: Graph. 
     """
     for center in self.centers:
         shortest_routes = shortest_path(graph, center)[1]
         for node, weight in list(shortest_routes.items()):
             self.nodes.setdefault(node, []).append(weight)
示例#15
0
文件: chow.py 项目: aliahmet/rogue
 def optimize(self, graph):
     """
     Build a dictionary mapping each pair of nodes to a number (the distance between them).
     
     @type  graph: LoopGraph
     @param graph: Graph. 
     """        
     for center in self.centers:
         shortest_routes = shortest_path(graph, center)[1]
         for node, weight in list(shortest_routes.items()):
             self.nodes.setdefault(node, []).append(weight)
示例#16
0
文件: Rogue.py 项目: aliahmet/rogue
    def toward(self,_from,_to,is_monster=False):

        def orta(lst):
            if not config.manhattan_distance:
                return lst[0]
            if is_monster:
                rg_x,rg_y = self.decode()(self.rogue_location)

                min = 9999
                sq = "00"
                for p in lst:
                    x,y = self.decode()(p)
                    val = abs(rg_x - x) + abs(rg_y - y)
                    if val < min:
                        min = val
                        sq = p
            else:
                rg_x,rg_y = self.decode()(self.monster_location)

                min = -1
                sq = "00"
                for p in lst:
                    x,y = self.decode()(p)
                    val = abs(rg_x - x) + abs(rg_y - y)
                    if val > min:
                        val = min
                        sq = p
            return sq

        edges = self.FullGraph.edges()
        if (_from, _to) in edges or (_to, _from) in edges:
            return  _to
        if _from == _to:
            return _to
        try:
            path, distances =  shortest_path(self.FullGraph, _to)
            next_step =  path[_from]
        except:
            raise InfiniteMove
        startables = []
        distant=  distances[next_step]
        for c in distances:
            if distances[c] == distant and c in self.FullGraph.neighbors(_from):
                startables += [c]

        l = str(orta(sorted([int(c) for c in startables])))
        if l in startables:
            next_step = l



        if next_step is not None:
            return next_step
        return _to
    def _calculate_order_path(self):
        start_node = self._order_spec.start[1]*(self._map_spec.max_y + 1) + self._order_spec.start[0]
        finish_node = self._order_spec.finish[1]*(self._map_spec.max_y + 1) + self._order_spec.finish[0]

        spanning_tree, shortest_paths = minmax.shortest_path(self._map_spec.graph, start_node)

        if finish_node in shortest_paths:
            self._path = minmax.path(spanning_tree, finish_node)
            self._path.reverse()
        else:
            self._path = None
示例#18
0
 def length_of_route(self, origin, destination, line_code='All'):
     """
     Return the amount of time (in minutes) it is estimated to take to get from RailStation origin to RailStation destination
     via the specified line_code (if any)
     Returns -1 if there is no route between the two
     """
     origin_name = origin.name + ":entrance"
     destination_name = destination.name + ":exit"
     network = self.network[line_code]
     shortest_path_times = shortest_path(network, origin_name)[1]
     return int(ceil(shortest_path_times.get(destination_name, -1)))
示例#19
0
 def GetShortestPathMST(self,goal):
     ''' Find the shortest path Minimum-Spanning Tree
     '''
     if self.g!= None:
         if self.UseNetworkX:
             import networkx as nx
             self.sp_mst = nx.all_pairs_dijkstra_path(self.g)
             self.dist = nx.all_pairs_dijkstra_path_length(self.g)
         else:
             from pygraph.algorithms.minmax import shortest_path
             self.sp_mst, self.dist = shortest_path(self.g,'(%d,%d)'%(goal[0],goal[1]))
         return self.sp_mst, self.dist
     else:
         print 'CreateExpRiskGraph first before calling GetShortestPathMST(goal)'
         return None, None
示例#20
0
 def GetShortestPathMST(self,goal):
     ''' Find the shortest path Minimum-Spanning Tree
     '''
     if self.g!= None:
         if self.UseNetworkX:
             import networkx as nx
             self.sp_mst = nx.all_pairs_dijkstra_path(self.g)
             self.dist = nx.all_pairs_dijkstra_path_length(self.g)
         else:
             from pygraph.algorithms.minmax import shortest_path
             self.sp_mst, self.dist = shortest_path(self.g,'(%d,%d)'%(goal[0],goal[1]))
         return self.sp_mst, self.dist
     else:
         print 'CreateExpRiskGraph first before calling GetShortestPathMST(goal)'
         return None, None
示例#21
0
def graphgen(grnodes):
    """Initialises the graph. Ensures that all nodes in the graph are connected.
    Creates an image called graph.png which represents the graph.
    """
    graph = generate(grnodes, int(1.2*grnodes),
                     directed=False, weight_range=(1, 1))
    # Makes sure graphs generated by generate() have all their nodes connected.
    while len(shortest_path(graph, 0)[1]) < grnodes:
        graph = generate(grnodes, int(1.2*grnodes),
                         directed=False, weight_range=(1, 1))
        # print len(shortest_path(graph, 0)[1])
    # Draw as PNG
    dot = write(graph)
    gvv = gv.readstring(dot)
    gv.layout(gvv, 'dot')
    gv.render(gvv, 'png', 'graph.png')
    return graph
示例#22
0
    def shortest_path(self, tupA, tupB):
        tupA_id = self.tuple2node_id[tupA]
        tupB_id = self.tuple2node_id[tupB]

        # Get shortest path from pygraph
        paths = shortest_path(self.word_graph, tupA_id)

        # Follow the spanning tree to create the shortest path
        spanning_trees = paths[0]
        path = [tupB_id]
        cur_node = spanning_trees[tupB_id]
        while cur_node != tupA_id:
            path.append(cur_node)
            cur_node = spanning_trees[cur_node]
        path.append(tupA_id)
        path.reverse()
        tup_path = [self.node_id2tuple[p] for p in path]
        return tup_path
示例#23
0
    def getJumpsBetweenSS(self, ss1, ss2):
        if ss1 in self.jumpsCache:
            return self.jumpsCache[ss1][ss2]
        if ss2 in self.jumpsCache:
            return self.jumpsCache[ss2][ss1]

        gr = 0
        if self.ssgraph:
            gr = self.ssgraph
        else:
            gr = graph()
            nodes = self.getAllSS()
            gr.add_nodes(nodes)
            for edge in self.getAllSSEdges():
                gr.add_edge(edge)

        paths = shortest_path(gr, ss1)[1]
        self.jumpsCache[ss1] = paths
        return paths[ss2]
示例#24
0
def shortest_distance(graph, node1, node2):
    """
    minimum distance between two nodes in the graph
    """
    
#     t = minimal_spanning_tree(graph,node1)
#     if node2 not in t:
#         return -1
#     
    undirected = to_undirected(graph)
    t, d = shortest_path(graph=undirected, source=node1)
    if node2 not in d:
        return -1
    ret = [node2]
    v = node2
    while v!= node1:
        u = t[v]
        ret.extend([undirected.edge_label((u,v)),graph.has_edge((u,v)),u])
        v=u
#     return ret

    return ret
示例#25
0
def shortest_distance(graph, node1, node2):
    """
    minimum distance between two nodes in the graph
    """
    
#     t = minimal_spanning_tree(graph,node1)
#     if node2 not in t:
#         return -1
#     
    undirected = to_undirected(graph)
    t, d = shortest_path(graph=undirected, source=node1)
    if node2 not in d:
        return -1
    ret = [node2]
    v = node2
    while v!= node1:
        u = t[v]
        ret.extend([undirected.edge_label((u,v)),graph.has_edge((u,v)),u])
        v=u
#     return ret

    return ret
示例#26
0
	def feedback_score(self, segment_collection, correct_labels):

		# HIGH VALUES FOR GOOD
		# 0 to 1

		try:
			self.build_graph(segment_collection)
			min_dist_all = {}
			for label in correct_labels:

				min_dist =  shortest_path(self.graph, label)[1]

				if len(min_dist_all.keys()) >0:

					for x in min_dist.keys():
						min_dist_all[x] = max ((min_dist_all[x], np.exp(-min_dist[x])))
				else:
					
					for x in min_dist.keys():
						min_dist_all[x] = np.exp( -min_dist[x])

			self.feedback_correct_score = [0] * len(segment_collection.list_of_segments)

	#		hist, bins = np.histogram(self.avg_neighbor_dissimilarity)
	#		max_loc = np.argmax(hist)
	#		sigma = 10 # (bins[max_loc] + bins[max_loc+1]) / 2. 


			if len(correct_labels)>0:
				max_val = max (min_dist_all.values())
				for label in min_dist_all.keys():
					seg_idx = segment_collection.segment_label_to_list_index_dict[label]

					#new_val = np.exp(-min_dist_all[label]**2./(2.*sigma**2.))
					self.feedback_correct_score[seg_idx] = min_dist_all[label]
		
		except Exception as err:
			pdb.set_trace()
示例#27
0
    def __init__(self,nodes,edges,specialNodes):
        self.edges = edges
        self.nodes = nodes
        self.graph = graph()
        self.graph.add_nodes(nodes)
        for (v1,v2,c) in edges:
            self.graph.add_edge((v1,v2), c)

        self.paths = {}
        self.pathsLength = {}
        for v in self.graph.nodes():
            self.paths[v] = {}
            self.pathsLength[v] = {}
            for w in self.graph.nodes():
                self.paths[v][w] = []
                self.pathsLength[v][w] = 0 if v == w else float('inf')

        for v in self.graph.nodes():
            (tree,lengths) = shortest_path(self.graph,v)
            for w in self.graph.nodes():
                self.pathsLength[v][w] = lengths[w]
                self._extractPath(v,w,tree)

        self.specialNodes = specialNodes
gr.add_nodes(["a", "b", "c", "d", "e", "f"])

# notar que los vertices o edge, ahora tienen definido un peso
gr.add_edge(("a", "b"), 3)
gr.add_edge(("a", "f"), 5)
gr.add_edge(("a", "d"), 4)
gr.add_edge(("b", "f"), 1)
gr.add_edge(("b", "c"), 1)
gr.add_edge(("f", "d"), 2)
gr.add_edge(("c", "d"), 2)
gr.add_edge(("d", "b"), 3)
gr.add_edge(("e", "f"), 2)
gr.add_edge(("e", "d"), 3)

#mostrar el grafo
print "\nEl grafo: \n"
print gr

#### ruta mas corta, iniciando en Anchorage
st, dist = shortest_path(gr, "a")
# mostrar la ruta, indicada en el spanning tree
print "\nRuta:\n"
print st
# mostrar los valores de las rutas:
print "\nValores de la ruta mas corta, a cada vertice:\n"
print dist

print "\nPAGE RANK:\n"
r = pagerank(gr, damping_factor=0.85, max_iterations=100, min_delta=1e-05)
print r
示例#29
0
def sample_lof_interactions(c, args, idx_to_sample, samples):
    lof = get_lof_genes(c, args, idx_to_sample)
    #file handle for fetching the hprd graph
    config = read_gemini_config(args=args)
    path_dirname = config["annotation_dir"]
    file_graph = os.path.join(path_dirname, 'hprd_interaction_graph')
    #load the graph using cPickle and close file handle
    gr = graph()
    f = open(file_graph, 'rb')
    gr = cPickle.load(f)
    f.close()
    #calculate nodes from the graph
    hprd_genes = gr.nodes()
    #initialize keys
    k = []
    variants = []

    if (not args.var_mode):
        for sample in lof.iterkeys():
            lofvariants = list(set(lof[str(sample)]))
            for each in samples[str(sample)]:
                variants.append(each[0])
            for gene in lofvariants:
                if gene in hprd_genes:
                    x, y = \
                        breadth_first_search(gr,root=gene,\
                        filter=radius(args.radius))

                    gst = digraph()
                    gst.add_spanning_tree(x)
                    st, sd = shortest_path(gst, gene)
                    # for each level return interacting genes
                    # if they are variants in the sample.
                    for rad in range(1, (args.radius + 1)):
                        for key, value in sd.iteritems():
                            if (value == rad) and key in set(variants):
                                k.append(key)
                        if k:
                            print "\t".join([str(sample), \
                                       str(gene), \
                                       str(rad)+"_order:",
                                       ",".join(k)])
                        else:
                            print "\t".join([str(sample), \
                                       str(gene), \
                                       str(rad)+"_order:", \
                                       "none"])
                        #initialize k
                        k = []
            #initialize variants list for next iteration
            variants = []
    elif args.var_mode:
        for sample in lof.iterkeys():
            lofvariants = list(set(lof[str(sample)]))
            var = samples[str(sample)]
            for gene in lofvariants:
                if gene in hprd_genes:
                    x, y = \
                         breadth_first_search(gr,root=gene, \
                         filter=radius(args.radius))
                    gst = digraph()
                    gst.add_spanning_tree(x)
                    st, sd = shortest_path(gst, gene)
                    for rad in range(1, (args.radius + 1)):
                        for each in var:
                            for key, value in sd.iteritems():
                                if value == rad and key == each[0]:
                                    print "\t".join([str(sample), \
                                               str(gene), \
                                               str(rad), \
                                               str(key), \
                                               str(each[1]), \
                                               str(each[2]), \
                                               str(each[3]), \
                                               str(each[4]), \
                                               str(each[5]), \
                                               str(each[6]), \
                                               str(each[7]), \
                                               str(each[8]), \
                                               str(each[9]), \
                                               str(each[10]), \
                                               str(each[11])])
示例#30
0
def sample_gene_interactions(c, args, idx_to_sample):
    out = open("file.dot", 'w')
    #fetch variant gene dict for all samples
    samples = get_variant_genes(c, args, idx_to_sample)
    #file handle for fetching the hprd graph
    config = read_gemini_config(args=args)
    path_dirname = config["annotation_dir"]
    file_graph = os.path.join(path_dirname, 'hprd_interaction_graph')
    #load the graph using cPickle and close file handle
    gr = graph()
    f = open(file_graph, 'rb')
    gr = cPickle.load(f)
    f.close()
    k = []
    variants = []
    #calculate nodes from the graph
    hprd_genes = gr.nodes()
    if args.gene == None or args.gene not in hprd_genes:
        sys.stderr.write("Gene name not found or")
        sys.stderr.write(" gene not in p-p interaction file\n")

    elif args.gene in hprd_genes:
        x, y = \
            breadth_first_search(gr,root=args.gene,filter=radius(args.radius))
        gst = digraph()
        gst.add_spanning_tree(x)
        dot = write(gst)
        out.write(dot)
        st, sd = shortest_path(gst, args.gene)

        if args.var_mode:
            for sample in samples.iterkeys():
                var = samples[str(sample)]
                #for each level return interacting genes if they are
                # variants in the sample.
                # 0th order would be returned if the user chosen
                # gene is a variant in the sample
                for x in range(0, (args.radius + 1)):
                    for each in var:
                        for key, value in sd.iteritems():
                            if value == x and key == each[0]:
                                print "\t".join([str(sample),str(args.gene), \
                                          str(x), \
                                          str(key), \
                                          str(each[1]), \
                                          str(each[2]), \
                                          str(each[3]), \
                                          str(each[4]), \
                                          str(each[5]), \
                                          str(each[6]), \
                                          str(each[7]), \
                                          str(each[8]), \
                                          str(each[9]), \
                                          str(each[10]), \
                                          str(each[11])])
        elif (not args.var_mode):
            for sample in samples.iterkeys():
                for each in samples[str(sample)]:
                    variants.append(each[0])
                for x in range(0, (args.radius + 1)):
                    for key, value in sd.iteritems():
                        if value == x and key in set(variants):
                            k.append(key)
                    if k:
                        print "\t".join([str(sample), str(args.gene), \
                                 str(x)+"_order:",
                                 ",".join(k)])
                    else:
                        print "\t".join([str(sample), str(args.gene), \
                                         str(x)+"_order:", "none"])
                    #initialize keys for next iteration
                    k = []
                #initialize variants list for next iteration
                variants = []
 def test_shortest_path_on_graph(self):
     gr = testlib.new_graph(wt_range=(1,10))
     st, dist = shortest_path(gr, 0)
     for each in gr:
         if (each in dist):
             assert bf_path(gr, 0, each, dist[each])
def plot_pathlen(options):
    '''
    Plot the distances from each node to each other node
    '''
    cursor = options['db_conn'].cursor()
    options['prefix'] = 'all'

    steps = 1.0 / options['bins']
    quantiles = numpy.arange(0, 1.0 + steps * 0.9, steps)

    fig_avr_len = MyFig(options,
                        grid=True,
                        legend=True,
                        xlabel='Hops',
                        ylabel='CDF of Average Distances',
                        aspect='auto')
    fig_max_len = MyFig(options,
                        grid=True,
                        legend=True,
                        xlabel='Hops',
                        ylabel='CDF of Maximum Distances',
                        aspect='auto')
    fig_max_avr_len_meds = MyFig(options,
                                 grid=True,
                                 xlabel='Maximum Distance',
                                 ylabel='Median of Average Distance')

    cursor.execute('''SELECT host FROM addr''')
    hosts = cursor.fetchall()
    vertices = digraph()
    for host, in hosts:
        vertices.add_node(host)

    tag_ids = cursor.execute(
        'SELECT DISTINCT(id), helloSize FROM tag ORDER BY helloSize').fetchall(
        )
    colors = cm.hsv(pylab.linspace(0, 0.8, len(tag_ids)))
    for i, (tag_id, hello_size) in enumerate(tag_ids):
        logging.info('tag_id=\"%s\" (%d/%d)', tag_id, i + 1, len(tag_ids))

        fig_max_avr_len = MyFig(options,
                                grid=True,
                                xlabel='Maximum Distance',
                                ylabel='Average Distance')

        links = cursor.execute(
            'SELECT src,host,pdr FROM eval_helloPDR WHERE tag_id=?'
            '', (tag_id, )).fetchall()
        lens = []
        maxl = []
        max_avr_len = []
        graph = deepcopy(vertices)
        for src, host, pdr in links:
            graph.add_edge((src, host), wt=1)
        for host, in hosts:
            stp, distances = minmax.shortest_path(graph, host)
            if len(distances) > 1:
                vals = [t for t in distances.values() if t > 0]
                lens.append(scipy.average(vals))
                maxl.append(max(vals))
                max_avr_len.append((maxl[-1], lens[-1]))
        avr_values = stats.mstats.mquantiles(lens, prob=quantiles)
        max_values = stats.mstats.mquantiles(maxl, prob=quantiles)
        fig_avr_len.ax.plot(avr_values,
                            quantiles,
                            '-',
                            color=colors[i],
                            label=str(hello_size) + ' bytes')
        fig_max_len.ax.plot(max_values,
                            quantiles,
                            '-',
                            color=colors[i],
                            label=str(hello_size) + ' bytes')

        points = []
        for max_avr_dist in sorted(set([x[0] for x in max_avr_len])):
            median = scipy.median(
                [y[1] for y in max_avr_len if y[0] == max_avr_dist])
            fig_max_avr_len.ax.plot(max_avr_dist,
                                    median,
                                    'o',
                                    color='black',
                                    label='')
            points.append((max_avr_dist, median))
        fig_max_avr_len_meds.ax.plot([x[0] for x in points],
                                     [y[1] for y in points],
                                     color=colors[i],
                                     label=str(hello_size) + ' bytes')

        fig_max_avr_len.ax.scatter([x[0] for x in max_avr_len],
                                   [y[1] for y in max_avr_len],
                                   color=colors[i],
                                   label='')
        fig_max_avr_len.ax.axis((0, max([x[0] for x in max_avr_len]) + 1, 0,
                                 max([y[1] for y in max_avr_len]) + 1))
        fig_max_avr_len.save('dist-average_over_max_%d' % (hello_size))

    for _ax in [fig_avr_len.ax, fig_max_len.ax]:
        _ax.set_yticks(numpy.arange(0.1, 1.1, 0.1))

    fig_avr_len.save('dist-cdf_avr')
    fig_max_len.save('dist-cdf_max')
    fig_max_avr_len_meds.save('dist-median_of_averages_over_max')
示例#33
0
 def calculate_shortest_paths(self, origin_node):
     return shortest_path(self._graph, origin_node)[0]
示例#34
0
print(dist)

# Following will only work if you have installed
# pygraph [https://github.com/pmatiello/python-graph.git]
# once downloaded install, viz. "python3.4 setup.py install"
#
try:
    from pygraph.classes.digraph import digraph
    from pygraph.algorithms.minmax import shortest_path

    g = digraph()
    g.add_nodes([0, 1, 2, 3, 4, 5])

    g.add_edge((0, 1), wt=6)
    g.add_edge((0, 3), wt=18)

    g.add_edge((0, 2), wt=8)
    g.add_edge((1, 4), wt=11)
    g.add_edge((4, 5), wt=3)
    g.add_edge((2, 3), wt=9)
    g.add_edge((5, 2), wt=7)
    g.add_edge((5, 3), wt=4)

    x = shortest_path(g, 0)
    print(x[1])

except Exception:
    print()
    print("To complete this example, you need to install pygraph.")
    print("   https://github.com/pmatiello/python-graph.git")
示例#35
0
def sample_lof_interactions(c, args, idx_to_sample, samples):
    lof = get_lof_genes(c, args, idx_to_sample)
    #file handle for fetching the hprd graph
    file_graph = os.path.join(path_dirname, 'hprd_interaction_graph')
    #load the graph using cPickle and close file handle
    gr = graph()
    f = open(file_graph, 'rb')
    gr = cPickle.load(f)
    f.close()
    #calculate nodes from the graph
    hprd_genes = gr.nodes()
    #initialize keys
    k = []
    variants = []
    
    if (not args.var_mode):
        for sample in lof.iterkeys():
            lofvariants = list(set(lof[str(sample)]))
            for each in samples[str(sample)]:
                variants.append(each[0])
                
            for gene in lofvariants:
                if gene in hprd_genes:
                    x, y = \
                        breadth_first_search(gr,root=gene,\
                        filter=radius(args.radius))

                    gst = digraph()
                    gst.add_spanning_tree(x)
                    st, sd = shortest_path(gst, gene)
                    # for each level return interacting genes 
                    # if they are variants in the sample.
                    for rad in range(1, (args.radius+1)):
                        for key, value in sd.iteritems():
                            if (value == rad) and key in set(variants):
                                k.append(key)
                        if k:
                            print "\t".join([str(sample), \
                                       str(gene), \
                                       str(rad)+"_order:", 
                                       ",".join(k)])
                        else:
                            print "\t".join([str(sample), \
                                       str(gene), \
                                       str(rad)+"_order:", \
                                       "none"])
                        #initialize k
                        k = []
    elif args.var_mode:
        for sample in lof.iterkeys():
            lofvariants = list(set(lof[str(sample)]))
            var = samples[str(sample)]    
            for gene in lofvariants:
                if gene in hprd_genes:
                    x, y = \
                         breadth_first_search(gr,root=gene, \
                         filter=radius(args.radius))
                    gst = digraph()
                    gst.add_spanning_tree(x)
                    st, sd = shortest_path(gst, gene)
                    for rad in range(1, (args.radius+1)):
                        for each in var:
                            for key, value in sd.iteritems():
                                if value == rad and key == each[0]:
                                    print "\t".join([str(sample), \
                                               str(gene), \
                                               str(rad), \
                                               str(key), \
                                               str(each[1]), \
                                               str(each[2]), \
                                               str(each[3]), \
                                               str(each[4]), \
                                               str(each[5]), \
                                               str(each[6]), \
                                               str(each[7]), \
                                               str(each[8]), \
                                               str(each[9]), \
                                               str(each[10])])
示例#36
0
 def shortestpath(self, node):
     return shortest_path(self.graph, node)
示例#37
0
 def calculateWalkDistances(self, stops):
     self._clearDistances()
     fillerNodes = 0
     
     gr = graph()
     gr.add_nodes(self.nodes.keys())
     
     # build the graph from our map
     for way in self.ways.values():
         lastNode = None
         for node in way.refs:
             if (lastNode and lastNode in self.nodes and
                     node in self.nodes and not gr.has_edge((lastNode, node))):
                 gr.add_edge((lastNode, node), self.nodes[lastNode].distanceTo(self.nodes[node]))
             lastNode = node
     
     def frange(x, y, jump):
         while x < y:
           yield x
           x += jump
     
     #Add nodes from stops
     for stop in stops:
         #add stop to graph
         gr.add_node(stop)
         
         #find nearest node to stop
         nearest = -1
         nearestDist = float('inf')
         for key, node in self.nodes.iteritems():
             if node.walkable:
                 dist = node.distanceTo(stop)
                 if dist <= 10: # here we add all nodes within 10 m (approx road width)
                     gr.add_edge((stop, key), dist)
                 if dist < nearestDist:
                     nearestDist = node.distanceTo(stop)
                     nearest = key
         # ensure the nearest node is not missed
         if nearestDist > 10:
             #gr.add_edge((stop, nearest), nearestDist)
             nearestNode = self.nodes[nearest]
             for mrR in gr.neighbors(nearest):
                 if mrR not in self.nodes:
                     continue
                 mrRogers = self.nodes[mrR]
                 ndist = nearestNode.distanceTo(mrRogers)
                 lastNode = nearest
                 for factor in frange(5.0/ndist, 1, 5.0/ndist):
                     fillerNodes -= 1
                     newNode = Node(nearestNode.lon + factor *
                                                    (mrRogers.lon - nearestNode.lon),
                                                    nearestNode.lat + factor *
                                                    (mrRogers.lat - nearestNode.lat))
                     gr.add_node(fillerNodes)
                     self.nodes[fillerNodes] = newNode
                     if stop.distanceTo(newNode) <= 10:
                         gr.add_edge((stop, fillerNodes), stop.distanceTo(newNode))
                     gr.add_edge((lastNode, fillerNodes), 5)
                     lastNode = fillerNodes
                 if not gr.has_edge((lastNode, mrR)):
                     gr.add_edge((lastNode, mrR), ndist % 5)
             
         
         # this graph libary may be overkill (i.e. we should probably stop Djikstra's algorithm
         # after some distance) but it beats reinventing the wheel
         st, distances = shortest_path(gr, stop)
         
         # Set the walking distance to be whatever is the nearest stop
         for key, dist in distances.iteritems():
             if key in self.nodes and dist < self.nodes[key].walkDistance:
                 self.nodes[key].walkDistance = dist
示例#38
0
#   [630, 803, 746, 422, 111],
#    [537, 699, 497, 121, 956],
#     [805, 732, 524, 37, 331]]

gr = digraph()
leny = len(data)
lenx = len(data[0])

for y in range(leny):
    for x in range(lenx):
        gr.add_node((y, x))

gr.add_node("start")
gr.add_node("end")

gr.add_edge(("start", (0, 0)), wt=data[0][0])
gr.add_edge(((leny - 1, lenx - 1), "end"), wt=0)

for y in range(leny):
    for x in range(lenx):
        if y != leny - 1:
            gr.add_edge(((y, x), (y + 1, x)), wt=data[y + 1][x])
        if x != lenx - 1:
            gr.add_edge(((y, x), (y, x + 1)), wt=data[y][x + 1])
        if y != 0:
            gr.add_edge(((y, x), (y - 1, x)), wt=data[y - 1][x])
        if x != 0:
            gr.add_edge(((y, x), (y, x - 1)), wt=data[y][x - 1])

print minmax.shortest_path(gr, "start")[1]["end"]
示例#39
0
f = open('matrix.txt')

matrix = [map(int, line.rstrip('\n').split(',')) for line in f.xreadlines()]

x_length = len(matrix[0])
y_length = len(matrix)

#- Creating gr -#
gr = digraph()

start_node = "start"
gr.add_node(start_node)
for x in xrange(x_length):
	for y in xrange(y_length):
		current_node = "%d,%d" % (x, y)
		current_node_weight = matrix[x][y]
		gr.add_node(current_node)
		if x > 0:
			left_node = "%d,%d" % (x-1, y)
			gr.add_edge((left_node, current_node), wt=current_node_weight)
		if y > 0:
			top_node = "%d,%d" % (x, y-1)
			gr.add_edge((top_node, current_node), wt=current_node_weight)

first_node_weight = matrix[0][0]
gr.add_edge((start_node, "0,0"), wt=first_node_weight)
last_node = "%d,%d" % (x_length-1, y_length-1)

tree, distances = shortest_path(gr, start_node)
print distances[last_node]
示例#40
0
 def _computeExitDistances(self):
     self.exitDistances = {node:INFINITY for node in self.graph.nodes()} 
     for exit in self.exits:
         _, myDistances = shortest_path(self.graph, exit)
         self.exitDistances = {node: min(self.exitDistances[node], myDistance) 
                               for node, myDistance in myDistances.items()}    
示例#41
0
def handle_client(conn, addr):
    numpy.random.seed()
    NUM_LEVELS = 10
    COMMAND_LIST = [
        'north', 'south', 'east', 'west', 'up', 'down', 'pickup', 'escape'
    ]

    conn.send('Please wait while the map loads...\n')

    levels = {}
    gr = graph()
    key_level = rand(NUM_LEVELS - 3, NUM_LEVELS - 1)
    door_level = 0
    for i in range(NUM_LEVELS):
        levels[i] = maze(25, 25, 1, 1)
        add_graph(gr, levels[i], i)
        if i > 0:
            (x_d, y_d) = setnode(levels[i], M_DOWN)
            down = get_id(x_d, y_d, i)
            gr.add_edge((up, down))
        if i < NUM_LEVELS - 1:
            (x_u, y_u) = setnode(levels[i], M_UP)
            up = get_id(x_u, y_u, i)
        if i == key_level:
            (x, y) = setnode(levels[i], M_KEY)
            key = get_id(x, y, i)
        if i == door_level:
            (x, y) = setnode(levels[i], M_DOOR)
            door = get_id(x, y, i)

    st, weights = shortest_path(gr, key)
    distance = weights[door]
    collapse = distance + 5

    start_z = NUM_LEVELS / 2
    (start_x, start_y) = emptynode(levels[start_z])

    c_x = start_x
    c_y = start_y
    c_z = start_z

    player_key = False

    conn.send('Map loaded.\n')

    while True:
        node = levels[c_z][c_y, c_x]
        if node == M_UP:
            conn.send('There are stairs heading upward.\n')
        if node == M_DOWN:
            conn.send('There are stairs heading downward.\n')
        if node == M_KEY:
            conn.send('There is a key here.\n')
        if node == M_DOOR:
            conn.send('There is a locked door here.\n')

        data = conn.recv(1024).strip()
        commands = data.split('\n')

        for command in commands:
            if not command in COMMAND_LIST:
                conn.send(
                    'Invalid command: %s. Possible commands include are: %s\n'
                    % (command, COMMAND_LIST))
                continue
            if command == 'pickup':
                if player_key:
                    conn.send('You already have the key.\n')
                else:
                    if checknode(levels[c_z], c_x, c_y, M_KEY):
                        conn.send('You picked up the key.\n')
                        conn.send('The ceiling starts to collapse.\n')
                        player_key = True
                    else:
                        conn.send('No key here.\n')
            elif command == 'escape':
                if checknode(levels[c_z], c_x, c_y, M_DOOR):
                    if player_key:
                        conn.send('YOU ESCAPED!\n')
                        conn.send('Key: %s' % helpers.load_flag())
                    else:
                        conn.send('You need the key to unlock the door.\n')
                else:
                    conn.send('No door here.\n')
            elif command == 'north':
                if checknode(levels[c_z], c_x, c_y - 1, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved north.\n')
                    c_y = c_y - 1
            elif command == 'south':
                if checknode(levels[c_z], c_x, c_y + 1, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved south.\n')
                    c_y = c_y + 1
            elif command == 'west':
                if checknode(levels[c_z], c_x - 1, c_y, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved west.\n')
                    c_x = c_x - 1
            elif command == 'east':
                if checknode(levels[c_z], c_x + 1, c_y, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved east.\n')
                    c_x = c_x + 1
            elif command == 'up':
                if checknode(levels[c_z], c_x, c_y, M_UP):
                    conn.send('You moved upstairs.\n')
                    c_z = c_z + 1
                    c_x, c_y = findnode(levels[c_z], M_DOWN)
                else:
                    conn.send('No stairs upward here.\n')
            elif command == 'down':
                if checknode(levels[c_z], c_x, c_y, M_DOWN):
                    conn.send('You moved downstairs.\n')
                    c_z = c_z - 1
                    c_x, c_y = findnode(levels[c_z], M_UP)
                else:
                    conn.send('No stairs downward here.\n')

            if player_key:
                collapse -= 1
                conn.send('Get out of here!\n')

            if collapse == 10:
                conn.send('The ceiling is about to collapse!\n')

            if collapse == 50:
                conn.send('Large pieces of debris fall from the ceiling.\n')

            if collapse == 100:
                conn.send('Hurry!\n')

            if collapse == 0:
                conn.send(
                    'The ceiling collapses and crushes you. You are dead.\n')
                conn.send('You are dead.\n')
                return
示例#42
0
 def calculate_shortest_paths(self, origin_node):
     return shortest_path(self._graph, origin_node)[0]
示例#43
0
文件: war.py 项目: Mrs-Hudson/codejam
    
from pygraph.classes.graph import graph    
from pygraph.algorithms.minmax import shortest_path  
from collections import defaultdict
T = int(f.readline())
for i in range(1,T+1):
    P,W = [int(x) for x in f.readline().split()]
    G = graph()
    for x in range(P):
        G.add_node(x)
    wormholes = [tuple(int(x) for x in s.split(",")) for s in f.readline().split()]
    for (x,y) in wormholes:
        G.add_edge((x,y))
    # our home planet is 0
    # AI's home planet is 1
    tree, distance = shortest_path(G,0) # distance of each vertex from 0
    D = distance[1]
    vertices_by_distance = defaultdict(list)
    for v,d in distance.items():
        vertices_by_distance[d].append(v)
    
    def H(a,b,c):
        """Number of neighbors of c that are not neighbors of either a or b."""
        return len( set(G.neighbors(c)) - set(G.neighbors(a)) - set(G.neighbors(b)) )
        
    F = dict()  # Let F(a, b) := the maximum number of planets threatened or conquered by a shortest path 0-...-a-b , defined for adjacent vertices a and b such that distance[b]==distance[a]+1
    
    Pre = dict()
    for a in vertices_by_distance[1]:
        F[(0,a)] = len(set([0,a]+G.neighbors(0)+G.neighbors(a)))
    
示例#44
0
            g.add_edge((rctonode(r - 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r, c + 1), rctonode(r, c)), matrix[r][c])

        # first column
        elif c == 0:
            g.add_edge((rctonode(r - 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r + 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r, c + 1), rctonode(r, c)), matrix[r][c])

        # last column
        elif c == (N - 1):
            g.add_edge((rctonode(r, c - 1), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r - 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r + 1, c), rctonode(r, c)), matrix[r][c])

        # everywhere else in the middle
        else:
            g.add_edge((rctonode(r, c - 1), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r - 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r + 1, c), rctonode(r, c)), matrix[r][c])
            g.add_edge((rctonode(r, c + 1), rctonode(r, c)), matrix[r][c])


st, dist = shortest_path(g, START)

if DEBUG:
    print(st)
    print(dist)

print(dist[END])
示例#45
0
文件: nav.py 项目: bluepnume/pyp
 def shortestpath(self, node):
   return shortest_path(self.graph, node)
示例#46
0
def val(co: Coordinate):
    global risks
    return co.row * risks.width + co.column


g = digraph()
for c in risks.get_all_coords():
    g.add_node(val(c))

for c in risks.get_all_coords():
    for n in risks.get_neighbor_cells(c, include_diagonal=False):
        # if n.coord.x >= c.x and n.coord.y >= c.y:
        g.add_edge((val(c), val(n.coord)), wt=n.value)

g.add_node(-1)
g.add_edge((-1, 0), wt=risks.get_value_by_index(0, 0))

g.add_node(9999999999)
g.add_edge((val(risks.rows[-1][-1].coord), 9999999999), wt=0)

shortest = list(reversed(shortest_path(shortest_paths(g, -1)[0], 9999999999)))
print(shortest)

cost = 0
for n in shortest[2:-1]:
    c = Coordinate(int(n / risks.width), n % risks.width)
    cost += risks.get_value_by_coord(c)

print(cost)
示例#47
0
def path(start, end):

	WEIGHT_FUNCTION = pesewa_weight_function
	
	trograph = get_trograph(WEIGHT_FUNCTION)

	if isinstance(start, Station):
		root = start.id		

	elif isinstance(start, Stop):
		root = "stop:%i" % start.id
		trograph.add_node(root)
		
		start_included_routes = Route.objects.filter(stops__id=start.id)
		for route in start_included_routes:
			trograph.add_edge(
				(root, route.arrival.id),
				wt = route_departing_stop_weight_function(start, route),
				label = route,
			)
		

	if isinstance(end, Station):
		end_node = end.id

	elif isinstance(end, Stop):
		end_node = "stop:%i" % end.id
		trograph.add_node(end_node)
		
		stop_included_routes = Route.objects.filter(stops__id=end.id)
		for route in stop_included_routes:
			trograph.add_edge(
				(route.departure.id, end_node),
				wt = route_arriving_stop_weight_function(end, route),
				label = route,			
			)

        #checking for same route start and stop
        routes = {}
        start_included_routes = Route.objects.filter(stops__stop=start)
        for route in start_included_routes:
            routes[route] = 1

        stop_included_routes = Route.objects.filter(stops__stop=end)
        for route in stop_included_routes:
            if route in routes:
                routes[route] += 1

        duplicated_routes = [route for route, count in routes.items() if count == 2]

        if duplicated_routes:

            out_routes = []
            for route in duplicated_routes:

                start_route_stop = route.stops.get(stop=start)
                stop_route_stop = route.stops.get(stop=end)

                distance = stop_route_stop.accumulated_distance - start_route_stop.accumulated_distance

                if distance >= 0:
                    out_routes.append(route)

            return PathResult(out_routes, is_same_route=True)
        
	#ok i have now fully transformed the graph

	#djisktra!
	spanning_tree, shortest_distance = shortest_path(trograph, root)

	#lets make sure that we found it
	if end_node not in spanning_tree:
		raise ValueError("Unable to find a path from %s to %s" % 
			(str(start), str(end)))
	
	routes = []
	
	current = end_node
	

	while spanning_tree[current] is not None:
		previous = spanning_tree[current]
		if not ":mock:" in str(previous):
        		routes.append(trograph.edge_label((previous,current)))
		current = previous

	return PathResult(routes[::-1])
示例#48
0
文件: server.py 项目: CySCA/CySCA2014
def handle_client(conn,addr):
    numpy.random.seed()
    NUM_LEVELS = 10
    COMMAND_LIST = ['north', 'south', 'east', 'west', 'up', 'down', 'pickup', 'escape']

    conn.send('Please wait while the map loads...\n')

    levels = {}
    gr = graph()
    key_level = rand(NUM_LEVELS-3,NUM_LEVELS-1)
    door_level = 0
    for i in range(NUM_LEVELS):
        levels[i] = maze(25, 25, 1, 1)
        add_graph(gr, levels[i], i)
        if i > 0:
            (x_d,y_d) = setnode(levels[i], M_DOWN)
            down = get_id(x_d, y_d, i)
            gr.add_edge((up, down))
        if i < NUM_LEVELS-1:
            (x_u,y_u) = setnode(levels[i], M_UP)
            up = get_id(x_u, y_u, i)
        if i == key_level:
            (x, y) = setnode(levels[i], M_KEY)
            key = get_id(x, y, i)
        if i == door_level:
            (x, y) = setnode(levels[i], M_DOOR)
            door = get_id(x, y, i)
            
    st,weights = shortest_path(gr, key)
    distance = weights[door]
    collapse = distance + 5

    start_z = NUM_LEVELS/2
    (start_x, start_y) = emptynode(levels[start_z])
    
    c_x = start_x
    c_y = start_y
    c_z = start_z
    
    player_key = False

    conn.send('Map loaded.\n')
    
    while True:
        node = levels[c_z][c_y,c_x]
        if node == M_UP:
            conn.send('There are stairs heading upward.\n')
        if node == M_DOWN:
            conn.send('There are stairs heading downward.\n')
        if node == M_KEY:
            conn.send('There is a key here.\n')
        if node == M_DOOR:
            conn.send('There is a locked door here.\n')        
        
        data = conn.recv(1024).strip()
        commands = data.split('\n')

        for command in commands:
            if not command in COMMAND_LIST:
                conn.send('Invalid command: %s. Possible commands include are: %s\n' % (command, COMMAND_LIST))
                continue
            if command == 'pickup':
                if player_key:
                    conn.send('You already have the key.\n')
                else:
                    if checknode(levels[c_z], c_x, c_y, M_KEY):
                        conn.send('You picked up the key.\n')
                        conn.send('The ceiling starts to collapse.\n')
                        player_key = True
                    else:
                        conn.send('No key here.\n')
            elif command == 'escape':
                if checknode(levels[c_z], c_x, c_y, M_DOOR):
                    if player_key:
                        conn.send('YOU ESCAPED!\n')
			conn.send('Key: %s' % helpers.load_flag())
                    else:
                        conn.send('You need the key to unlock the door.\n')
                else:
                    conn.send('No door here.\n')
            elif command == 'north':
                if checknode(levels[c_z], c_x, c_y-1, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved north.\n')
                    c_y = c_y-1
            elif command == 'south':
                if checknode(levels[c_z], c_x, c_y+1, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved south.\n')
                    c_y = c_y+1
            elif command == 'west':
                if checknode(levels[c_z], c_x-1, c_y, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved west.\n')
                    c_x = c_x-1
            elif command == 'east':
                if checknode(levels[c_z], c_x+1, c_y, M_WALL):
                    conn.send('There is a wall there.\n')
                else:
                    conn.send('You moved east.\n')
                    c_x = c_x+1
            elif command == 'up':
                if checknode(levels[c_z], c_x, c_y, M_UP):
                    conn.send('You moved upstairs.\n')
                    c_z = c_z + 1
                    c_x, c_y = findnode(levels[c_z], M_DOWN)
                else:
                    conn.send('No stairs upward here.\n')
            elif command == 'down':
                if checknode(levels[c_z], c_x, c_y, M_DOWN):
                    conn.send('You moved downstairs.\n')
                    c_z = c_z - 1
                    c_x, c_y = findnode(levels[c_z], M_UP)
                else:
                    conn.send('No stairs downward here.\n')
                        
            if player_key:
                collapse -= 1
                conn.send('Get out of here!\n')

            if collapse == 10:
                conn.send('The ceiling is about to collapse!\n')
            
            if collapse == 50:
                conn.send('Large pieces of debris fall from the ceiling.\n')
                
            if collapse == 100:
                conn.send('Hurry!\n')
            
            if collapse == 0:
                conn.send('The ceiling collapses and crushes you. You are dead.\n')
                conn.send('You are dead.\n')
                return        
示例#49
0
 def _runDijkstra(self, tailName, headName):
     if((tailName not in self.vertices) or (headName not in self.vertices)):
         return({},{})
     return(shortest_path(self.gr,tailName))