Ejemplo n.º 1
0
 def risk(self, paths, snakes):
     # for each point in a path, calculate distance to other snakes
     # for each path, the score is the sum of all distances. greater is better
     # return {path1: score, path2: score, ...}
     board_with_heads = self.make_board_with_heads(snakes)
     _heuristic = chow(*paths.keys())
     _heuristic.optimize(board_with_heads)
     return dict([(food, self._risk(_heuristic, board_with_heads, paths[food], snakes)) for food in paths.keys()])
Ejemplo n.º 2
0
    def search_A_star(self, sentence):
        tokens = nltk.word_tokenize(sentence)

        #if a node does not exist, it shall be added to the graph and connected to the previous node
        for i, token in enumerate(tokens):
            if not self.net.has_node(token):
                self.net.add_node(str(token))

                #print "adding node", token

            #if the edge does not exist between the current node and the previous one, an edge shall be added
            if i != 0:
                edge = (tokens[i - 1], token)
                if not self.net.has_edge(edge):
                    self.net.add_edge(edge,
                                      wt=self.EDGE_START_WEIGHT,
                                      label=self.START_OCCURRENCES_NUM)

        h = chow(
            tokens[0]
        )  #this optimization shall be performed chooosing a term which is connected: the choice of this term shall be performed accoding to some rule
        h.optimize(self.net)
        path = ''

        for k, token in enumerate(tokens):
            if k != 0:
                try:
                    intermediate_node_path = heuristic_search(
                        self.net, tokens[k - 1], token,
                        h)  #the path between each couple

                except NodeUnreachable, e:
                    print str(e)
                    print "NODE UREACHABLE"

                for j, node in enumerate(
                        intermediate_node_path
                ):  #increase the weight of the edges in the path
                    if j != 0:
                        edge = (intermediate_node_path[j - 1], node)
                        if not self.net.has_edge(edge):
                            raise Exception('edge not found')
                        else:  #if the edge exists, its weight is divided by the number of occurrences stored in the label
                            number_of_occurrences = self.net.edge_label(edge)
                            new_number_of_occurrences = number_of_occurrences + 1
                            self.net.set_edge_label(edge,
                                                    new_number_of_occurrences)
                            self.net.set_edge_weight(edge,
                                                     wt=1.0 /
                                                     new_number_of_occurrences)

                if k < len(tokens) - 1:
                    #we remove the last element to prevent repetitions of head and tail in the subsequences of the final path
                    path = path + ' ' + ' '.join(intermediate_node_path[0:-1])
                else:
                    path = path + ' ' + ' '.join(intermediate_node_path)
Ejemplo n.º 3
0
def pathgen(graph):
    """Calculates the shortest path from each node to each other node."""
    # grnodes = len(graph.nodes())
    h = chow(1)         # Needed for heuristic_search()
    h.optimize(graph)
    paths = [[] for x in range(len(graph.nodes()))]
    for j in graph.nodes():
        for i in graph.nodes():
            paths[j].append(heuristic_search(graph, j, i, h))
    return paths
 def test_chow_unreachable(self):
     heuristic = chow( "Wales", "North Korea", "Russia" )
     self.G.add_node("Sealand")
     self.G.add_edge("England", "Sealand")
     heuristic.optimize(self.G)
     self.G.del_edge("England", "Sealand")
     
     try:
         result = pygraph.algorithms.minmax.heuristic_search( self.G, "England", "Sealand" , heuristic )
     except exceptions.NodeUnreachable, _:
         return
Ejemplo n.º 5
0
 def test_chow_unreachable(self):
     heuristic = chow( "Wales", "North Korea", "Russia" )
     self.G.add_node("Sealand")
     self.G.add_edge(("England", "Sealand"))
     heuristic.optimize(self.G)
     self.G.del_edge(("England", "Sealand"))
     
     try:
         result = pygraph.algorithms.minmax.heuristic_search( self.G, "England", "Sealand" , heuristic )
     except exceptions.NodeUnreachable as _:
         return
     
     assert False, "This test should raise an unreachable error."
Ejemplo n.º 6
0
 def run_benchmark(self):
     G = self.fn_create()
     self.generate(G, self.GRAPH_ORDER, self.GRAPH_EDGES)
     
     reference_nodes = sample( G.nodes(), self.CHOW_REFERENCE_POINTS )
     heuristic = chow( *reference_nodes )
     heuristic.optimize(G)
     
     source_nodes = sample( G.nodes(), self.NUMBER_OF_SEARCHES )
     dest_nodes = sample( G.nodes(), self.NUMBER_OF_SEARCHES )
     
     for s,d in zip( source_nodes, dest_nodes ):
         log.debug("Searching from %s to %s" % (s,d) )
         result = heuristic_search( G, s, d, heuristic )
Ejemplo n.º 7
0
    def test_chow_unreachable(self):
        heuristic = chow("Wales", "North Korea", "Russia")
        self.G.add_node("Sealand")
        self.G.add_edge(("England", "Sealand"))
        heuristic.optimize(self.G)
        self.G.del_edge(("England", "Sealand"))

        try:
            result = pygraph.algorithms.minmax.heuristic_search(
                self.G, "England", "Sealand", heuristic)
        except exceptions.NodeUnreachable as _:
            return

        assert False, "This test should raise an unreachable error."
Ejemplo n.º 8
0
 def a_star(self, targets):
     paths = {}
     distances = {}
     heuristic = chow(*targets)
     heuristic.optimize(self.board)
     for target in targets:
         try:
             paths[target] = heuristic_search(self.board, tuple(self.snake["coords"][0]), target, heuristic)
             paths[target] = paths[target][1:]  # remove first (current position)
             distances[target] = len(paths[target])
         except Exception as e:
             distances[target] = sys.maxint
             print("ERROR %s" % e)
             pass
     return paths, distances
    def search_A_star(self, sentence):
        tokens = nltk.word_tokenize(sentence)
        
        #if a node does not exist, it shall be added to the graph and connected to the previous node
        for i, token in enumerate(tokens):
            if not self.net.has_node(token):
                self.net.add_node(str(token))

                #print "adding node", token
                
            #if the edge does not exist between the current node and the previous one, an edge shall be added
            if i!=0:
                edge = (tokens[i-1], token)
                if not self.net.has_edge(edge):             
                    self.net.add_edge(edge, wt=self.EDGE_START_WEIGHT, label = self.START_OCCURRENCES_NUM)


                    
        h = chow(tokens[0]) #this optimization shall be performed chooosing a term which is connected: the choice of this term shall be performed accoding to some rule
        h.optimize(self.net)
        path = ''
        
        for k, token in enumerate(tokens):
            if k!=0:
                try:                     
                    intermediate_node_path = heuristic_search(self.net, tokens[k-1], token, h) #the path between each couple
                    
                except NodeUnreachable, e:
                    print str(e)
                    print "NODE UREACHABLE"
                        
                for j, node in enumerate(intermediate_node_path): #increase the weight of the edges in the path
                    if j != 0:
                        edge = (intermediate_node_path[j-1], node)
                        if not self.net.has_edge(edge):
                            raise Exception('edge not found')
                        else: #if the edge exists, its weight is divided by the number of occurrences stored in the label
                            number_of_occurrences = self.net.edge_label(edge)
                            new_number_of_occurrences = number_of_occurrences + 1
                            self.net.set_edge_label(edge, new_number_of_occurrences)
                            self.net.set_edge_weight(edge, wt = 1.0/new_number_of_occurrences)
                
                if k < len(tokens)-1: 
                    #we remove the last element to prevent repetitions of head and tail in the subsequences of the final path
                    path = path + ' ' + ' '.join(intermediate_node_path[0:-1])
                else:
                    path = path + ' ' + ' '.join(intermediate_node_path)
Ejemplo n.º 10
0
 def test_chow(self):
     heuristic = chow( "Wales", "North Korea", "Russia" )
     heuristic.optimize(self.G)
     result = pygraph.algorithms.minmax.heuristic_search( self.G, "England", "India", heuristic )
Ejemplo n.º 11
0
Archivo: rrt.py Proyecto: boonflies/RRT
 def build_path(self, g):
     h = chow(self.qinit, self.nearest_qgoal_node)
     h.optimize(g)
     h_search = heuristic_search
     self.path = h_search(g, self.qinit, self.nearest_qgoal_node, h)
Ejemplo n.º 12
0
 def test_chow(self):
     heuristic = chow("Wales", "North Korea", "Russia")
     heuristic.optimize(self.G)
     result = pygraph.algorithms.minmax.heuristic_search(
         self.G, "England", "India", heuristic)
Ejemplo n.º 13
0
 def build_path(self, g):
     h = chow(self.qinit, self.nearest_qgoal_node)
     h.optimize(g)
     h_search = heuristic_search
     self.path = h_search(g, self.qinit, self.nearest_qgoal_node, h)