Ejemplo n.º 1
0
def djikstra(start, neighbor_func, distance_func, goal_pred):
    visited = set()

    parents = {start: None}

    distances = {start: 0}
    queue = PQ()
    queue.add_task(start, distances[start])

    while not queue.empty():
        current = queue.pop_task()
        for neighbor in neighbor_func(current):
            if neighbor in visited:
                continue
            tentative_distance = distances[current] + distance_func(
                current, neighbor)
            if neighbor not in distances:
                queue.add_task(neighbor, tentative_distance)
                distances[neighbor] = tentative_distance
                parents[neighbor] = current
            elif tentative_distance < distances[neighbor]:
                queue.update_task(neighbor, tentative_distance)
                distances[neighbor] = tentative_distance
                parents[neighbor] = current
        visited.add(current)
        if goal_pred(current):
            return {
                "distance": distances[current],
                "path": reconstruct_path(current, parents),
                "parents": parents
            }

    return {"distance": float("inf"), "path": None, "parents": parents}
Ejemplo n.º 2
0
class InformedSearch(Search):
    """
    Implement this.
    """
    def __init__(self, initial_state, goal_state, verbose=False):
        self.node_expansions = 0
        self.unique_states = {}
        self.unique_states[initial_state.dictkey()] = True
        self.q = PriorityQueue()
        self.goal_state = goal_state
        self.q.enqueue(InformedNode(initial_state, None, 0, self.goal_state))
        self.verbose = verbose
        solution = self.execute()
        if solution is None:
            print("Search failed")
        else:
            self.showPath(solution)

    def execute(self):
        while not self.q.empty():
            current = self.q.dequeue()
            self.node_expansions += 1
            if self.goal_state.equals(current.state):
                return current
            else:
                successors = current.state.applyOperators()
                for next_state in successors:
                    if next_state.dictkey() not in self.unique_states.keys():
                        n = InformedNode(next_state, current,
                                         current.depth + 1, self.goal_state)
                        self.q.enqueue(n)
                        self.unique_states[next_state.dictkey()] = True
                    if self.verbose:
                        print("Expanded:", current)
                        print("Number of successors:", len(successors))
                        print("Queue length: ", self.q.size())
                        print("-------------------------------")
        return None

    def get_expansions(self):
        return self.node_expansions
Ejemplo n.º 3
0
def run_astar(start_dict, h, start_name):

  hname = h.__name__
  print("running astar with " + hname)

  def get_f(state):
    return h(state) + state.get_g()

  start_state = State(start_dict)
  q = PriorityQueue(get_f)
  q.put(start_state)

  popped = 0
  while not q.empty():
    state = q.get()
    popped += 1
    if state.is_solved():
      log_result("astar_" + hname + "_results.txt", start_state, start_name, state, popped, heuristic=h)
      return popped
    moves = state.get_moves()
    for move in moves:
      q.put(state.make_move(move))
  print("failed to solve!")