Esempio n. 1
0
    def __construction(self):
        # la lista RLC contiene los k mejores candidatos
        # la otra lista contiene el resto de las arista que no pertenecen al camino ni a la RLC

        RCL = []
        visited = initialize_array(self.cities_count())
        other_edges = PriorityQueue()
        for i in range(0, len(self.coordinates) - 1):
            for j in range(i + 1, len(self.coordinates)):
                x, y = self.coordinates[i], self.coordinates[j]
                distance = euclidean_distance(x, y)
                other_edges.push((x, y), distance)

        for i in range(0, self.RCL_lenght):
            if other_edges.isEmpty():
                break
            RCL.append(other_edges.pop())

        tour = {}
        edges = 0
        while edges != self.cities_count() - 1:
            r = int(round(random.uniform(0, len(RCL) - 1)))
            (city1, city2) = RCL[r]

            if visited[self.mapped_cities[city1]] < 2 and visited[
                    self.mapped_cities[city2]] < 2:
                if not city1 in tour:
                    tour[city1] = []
                if not city2 in tour:
                    tour[city2] = []

                tour[city1].append(city2)
                tour[city2].append(city1)
                if not self.__DFS(tour):
                    edges += 1
                    visited[self.mapped_cities[city1]] += 1
                    visited[self.mapped_cities[city2]] += 1
                else:
                    tour[city1].remove(city2)
                    tour[city2].remove(city1)

            # ya sea porque la arista se agrego al tour o porque la ciudad ya estaba visitada, removerla de la lista de candidatos y agregar otro elemento
            RCL.remove((city1, city2))
            if not other_edges.isEmpty():
                RCL.append(other_edges.pop())

        result = []
        for i in range(0, len(visited)):
            if visited[i] == 1:
                result = self.sort_tour(tour, current=self.mapped_cities[i])
                break

        return result
    def breadth_first(self, xy1, xy2):
        """Execute a breadth first search"""
        tile_col1, tile_row1 = self.the_map.xy_to_cr(xy1[0], xy1[1])
        tile_col2, tile_row2 = self.the_map.xy_to_cr(xy2[0], xy2[1])

        successor_to_parent_map = {}
        start_state = (tile_col1, tile_row1)
        successor_to_parent_map[(
            start_state,
            None)] = None  # (Successor, Action) -> (Parent, Action)

        open_list = PriorityQueue()
        open_list.update((start_state, None), 0)
        closed = []

        while not open_list.isEmpty():
            current_state, action_to_current_state = open_list.pop()

            if current_state == (tile_col2, tile_row2):
                return self.__get_action_path(
                    (current_state, action_to_current_state),
                    successor_to_parent_map)

            if current_state not in closed:
                for successor_state, action, step_cost in self.__get_successors(
                        current_state):
                    open_list.update((successor_state, action), 0)

                    if successor_state not in closed:
                        successor_to_parent_map[(successor_state, action)] = (
                            current_state, action_to_current_state)

            closed.append(current_state)

        return []
Esempio n. 3
0
def least_constraining_value(var, assignment, csp):
    """
    Implements Least Constraining Value Heuristic (LCV), which order the domain
    values in the order in which they rule out the fewest values in the remaining
    variables
    """
    variables = csp.unassigned_variables()
    variables.remove(var)
    for X in assignment:
        if X in variables:
            variables.remove(X)

    minpq = PriorityQueue()
    for val in csp.domain(var):
        csp.assign_variable(var, val)
        values_ruled_out = 0
        for X in variables:
            for v in csp.domain(X):
                csp.assign_variable(X, v)
                if not csp.check_consistency():
                    values_ruled_out += 1
                csp.assign_variable(X, None)
        csp.assign_variable(var, None)
        minpq.push(val, values_ruled_out)

    domain_ordered = []
    while not minpq.isEmpty():
        domain_ordered.append(minpq.pop())
    return domain_ordered
Esempio n. 4
0
def aStarSearch(pos, goal):
    fringe, visited, best = PriorityQueue(), set(), {}
    fringe.push((pos, [], 0), manhattanDistance(pos, goal))

    while not fringe.isEmpty():

        current_point, actions, total_cost = fringe.pop()

        if current_point in visited or \
        (current_point in best and best[current_point] <= total_cost):
            continue

        visited.add(current_point)
        best[current_point] = total_cost

        # current vertex is a solution
        if current_point == goal:
            return actions

        for (point, action) in getSuccessors(current_point):
            # if node not visited add it to the fringe
            if point not in visited:
                actions_copy = list(actions)
                actions_copy.append(action)
                cost = total_cost + 1
                fringe.push((point, actions_copy, cost), \
                    cost + manhattanDistance(point, goal))

    raise Exception('Problem Not Solved')
Esempio n. 5
0
    def uc_search(self, initial_state):
        """ Uniform-Cost Search.

		It returns the path as a list of directions among
		{ Direction.left, Direction.right, Direction.up, Direction.down }
		"""

        # use a priority queue with the minimum queue.
        from utils import PriorityQueue
        open_list = PriorityQueue()
        open_list.push([(initial_state, None)], 0)
        closed_list = set([initial_state])  # keep already explored positions

        while not open_list.isEmpty():
            # Get the path at the top of the queue
            current_path, cost = open_list.pop()
            # Get the last place of that path
            current_state, current_direction = current_path[-1]
            #print("current_state -> ", current_state._position, " direction -> ", current_state._direction, " cost -> ", cost)

            # Check if we have reached the goal
            if current_state.is_goal_state():
                return (list(map(lambda x: x[1], current_path[1:])))
            else:
                # Check were we can go from here
                next_steps = current_state.get_successor_states()
                # Add the new paths (one step longer) to the queue
                for state, direction, weight in next_steps:
                    # Avoid loop!
                    if state not in closed_list:
                        closed_list.add(state)
                        open_list.push((current_path + [(state, direction)]),
                                       cost + weight)
        return []
def optimum_policy2D(grid, init, goal, cost):
    Nr = len(grid)
    Nc = len(grid[0])
    inf = 999

    policy2D = [[' ' for j in range(Nc)] for i in range(Nr)]
    value2D = [[inf for j in range(Nc)] for i in range(Nr)]

    value3D = [[[inf for j in range(Nc)] for i in range(Nr)] for o in range(4)]
    policy3D = [[[' ' for j in range(Nc)] for i in range(Nr)]
                for o in range(4)]

    visited = []
    frontier = PriorityQueue()
    cumcost = 0
    frontier.push([init, ' ', cumcost],
                  cumcost + heuristic_fun(init[0:2], goal))

    while not frontier.isEmpty():
        loc, move_name, cumcost = frontier.pop()
        if not loc in visited:
            visited.append(loc)

            value3D[loc[2]][loc[0]][loc[1]] = cumcost
            policy3D[loc[2]][loc[0]][loc[1]] = move_name

            if loc[0:2] == goal:
                # print 'Value:'
                # for row in value:
                #     print '---'
                #     for i in row:
                #         print i
                # print 'Policy:'
                # for row in policy3D:
                #     print '---'
                #     for i in row:
                #         print i
                # return policy2D
                policy2D[goal[0]][goal[1]] = '*'
                value2D[goal[0]][goal[1]] = value3D[loc[2]][goal[0]][goal[1]]
                while loc[0:2] != init[0:2]:
                    loc, loc_move = reverse_move(
                        loc, policy3D[loc[2]][loc[0]][loc[1]])
                    policy2D[loc[0]][loc[1]] = loc_move
                    value2D[loc[0]][loc[1]] = value3D[loc[2]][loc[0]][loc[1]]
                print('Value')
                for i in value2D:
                    print(i)
                return policy2D

            for nextloc, move_name, move_cost in childNode(
                    grid, loc, forward, forward_name):
                if not nextloc in visited:
                    nextcumcost = cumcost + move_cost
                    frontier.push([nextloc, move_name, nextcumcost],
                                  nextcumcost +
                                  heuristic_fun(nextloc[0:2], goal))

    return 'fail'
Esempio n. 7
0
def aStarSearch(task, heuristic, useHelpfulAction=False, noDel=False):
    extendedPathsCount = 0

    root = SearchNode(task.initial_state, None, None, 0)
    open_set = PriorityQueue()
    open_set.push(root, 0)

    state_cost = {task.initial_state: 0}

    while not open_set.isEmpty():
        pop_node = open_set.pop()
        pop_state = pop_node.state

        # Extend only if the cost of the node is the cheapest found so far.
        # Otherwise ignore, since we've found a better one.
        if state_cost[pop_state] == pop_node.cost:
            extendedPathsCount += 1

            if task.goal_reached(pop_state):
                print "Finished searching. Found a solution. "
                return (extendedPathsCount, pop_node.cost, pop_node.path(),
                        pop_state)

            relaxedPlan = None
            if useHelpfulAction:
                relaxedPlan = heuristic.getRelaxedPlan(
                    SearchNode(pop_state, None, None, 0))

            for op, succ_state in task.get_successor_states(pop_state, noDel):
                # If we're using helpful actions, ignore op that is not in the helpful actions
                if useHelpfulAction:
                    if relaxedPlan and not op.name in relaxedPlan:
                        #print str(op.name) + " not in " +  str(relaxedPlan)
                        continue

                # Assume each action (operation) has cost of one
                succ_node = SearchNode(succ_state, pop_node, op, 1)
                h = heuristic(succ_node)
                #print "\nHeuristic values for " + ', '.join(map(format_string, succ_node.state)) + " is " + str(h)

                if h == float('inf'):
                    # Don't bother with states that can't reach the goal anyway
                    continue

                old_succ_cost = state_cost.get(succ_state, float("inf"))
                if succ_node.cost < old_succ_cost:
                    # Found a cheaper state or never saw this state before
                    open_set.push(succ_node, succ_node.cost + h)
                    state_cost[succ_state] = succ_node.cost

    print "No more operations left. Cannot solve the task"
    # (extendedPathsCount, cost, path, final_state)
    return (extendedPathsCount, None, None, None)
Esempio n. 8
0
def aStarSearch(problem, heuristic=manhattanHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""

    priority_q = PriorityQueue()
    visited = []
    node = {}

    root = problem.getStartState()

    node["parent"] = None
    node["action"] = None
    node["goal"] = 0
    node["heuristic"] = heuristic(root, problem)
    node["state"] = root

    priority_q.push(node, node["goal"] + node["heuristic"])  #push root

    while (not priority_q.isEmpty()):

        node = priority_q.pop()
        state = node["state"]

        if (problem.isGoalState(state)):
            break

        if (state in visited):
            continue

        visited.append(state)
        children = problem.getSuccessors(state)

        if (children):
            for i in range(len(children)):

                if (children[i][0] not in visited):
                    sub_node = {}
                    sub_node["parent"] = node
                    sub_node["action"] = children[i][1]
                    sub_node["state"] = children[i][0]
                    sub_node["goal"] = children[i][2] + node["goal"]
                    sub_node["heuristic"] = heuristic(sub_node["state"],
                                                      problem)
                    priority_q.push(sub_node,
                                    sub_node["goal"] + sub_node["heuristic"])

    path = []
    while (node["action"] != None):
        path.insert(0, node["action"])
        node = node["parent"]

    return path
Esempio n. 9
0
    def astarSearch(problem, heuristic = 'eqn'):
        
        print bcolors.HEADER + "\n>> Running A* Search" + bcolors.ENDC
        
        startState              = problem.getStartState()
        goalState               = problem.getGoalState()
        [T, r, Z]               = problem.getTransform()
        listOfPredicates        = problem.listOfPredicates
        goalCompliantConditions = problem.goalCompliantConditions

        fval                    = float(heuristic(startState, problem))
        print bcolors.OKGREEN + "--> Initial heuristic estimate = " + bcolors.OKBLUE + str(fval) + bcolors.ENDC

        fringe                  = PriorityQueue()
        closed                  = []
        numberOfStatesExpanded  = 0
        printloop               = 0
        fringe.push([startState, [], 0.0], fval)

        while not fringe.isEmpty():

            printloop += 1
            if printloop == 300:
                printloop = 0
                print bcolors.OKGREEN + "--> Number of states expanded > " + str(numberOfStatesExpanded) + bcolors.ENDC
            
            node = fringe.pop()
            if problem.isGoalState(node[0]):
                print bcolors.OKGREEN + "--> Goal Found. Final number of states expanded = " + bcolors.OKBLUE + str(numberOfStatesExpanded) + bcolors.ENDC
                return node

            numberOfStatesExpanded += 1
            successor_list          = []

            if node[0] not in closed:
                closed.append(node[0])
                successor_list = problem.getSuccessors(node)
                while len(successor_list) > 0:
                    put = successor_list.pop()
                    if put[0] not in closed:

                        hval = heuristic(put[0], problem)
                        if hval != -1:
                            newnode = copy.deepcopy(node)
                            newnode[0] = put[0]
                            newnode[1] = newnode[1] + [put[1]]
                            newnode[2] = put[2] + hval
                            fringe.push(newnode,newnode[2])

        print bcolors.OKGREEN + "--> Search Terminated. Final number of states expanded = " + bcolors.OKBLUE + str(numberOfStatesExpanded) + bcolors.ENDC
        return None
Esempio n. 10
0
 def UCS(self, s):
     pq = PriorityQueue()
     visited = []
     visited.append(s)
     for v, w in self.graph[s]:
         pq.update(item=v, priority=w)
         
     while not pq.isEmpty():
         (pri,it) = pq.pop()
         visited.append(it)
         for v,w in self.graph[it]:
             if  v not in visited:
                 pq.update(item=v, priority=w+pri)
     print(visited)
    def a_star(self, xy1, xy2):
        """Search the node that has the lowest combined cost and heuristic first."""
        tile_col1, tile_row1 = self.the_map.xy_to_cr(xy1[0], xy1[1])
        tile_col2, tile_row2 = self.the_map.xy_to_cr(xy2[0], xy2[1])

        successor_to_parent_map = {}
        start_state = (tile_col1, tile_row1)
        #print('x=%d, y=%d to col=%d, row=%d (map row=%d, col= %d)' % (xy1[0], xy1[1], tile_col1, tile_row1,
        #                               self.the_map.tile_speeds.shape[0], self.the_map.tile_speeds.shape[1]))
        successor_to_parent_map[(
            start_state,
            None)] = None  # (Successor, Action) -> (Parent, Action)

        open_list = PriorityQueue()
        open_list.update((start_state, None), 0)
        closed = []

        while not open_list.isEmpty():
            current_state, action_to_current_state = open_list.pop()

            if current_state == (tile_col2, tile_row2):
                return self.__get_action_path(
                    (current_state, action_to_current_state),
                    successor_to_parent_map)

            if current_state not in closed:
                if current_state == start_state:
                    current_cost = 0
                else:
                    current_cost = len(
                        self.__get_action_path(
                            (current_state, action_to_current_state),
                            successor_to_parent_map))

                for successor_state, action, step_cost in self.__get_successors(
                        current_state):
                    cost = current_cost + step_cost + self.__cartesian_distance(
                        current_state, successor_state)

                    open_list.update((successor_state, action), cost)

                    if successor_state not in closed:
                        successor_to_parent_map[(successor_state, action)] = (
                            current_state, action_to_current_state)

            closed.append(current_state)
        return []
Esempio n. 12
0
    def aStarSearch(self, heuristicName = 'equality'):

        method = getattr(self, 'heuristic_' + heuristicName)
        print bcolors.HEADER + "\n>> Running A* Search" + bcolors.ENDC
        
        startState              = self.getStartState()
        goalState               = self.getGoalState()
        [T, r, Z]               = self.getTransform()
        listOfPredicates        = self.listOfPredicates
        goalCompliantConditions = self.goalCompliantConditions

        fval                    = float(method(startState))
        print bcolors.OKGREEN + "--> Initial heuristic estimate = " + bcolors.OKBLUE + str(fval) + bcolors.ENDC

        fringe                  = PriorityQueue()
        closed                  = []
        numberOfStatesExpanded  = 0
        printloop               = 0
        fringe.push([startState, [], 0.0], fval)

        while not fringe.isEmpty():

            if numberOfStatesExpanded%100 == 0: print bcolors.OKGREEN + "--> Number of states expanded > " + str(numberOfStatesExpanded) + bcolors.ENDC
                
            node = fringe.pop()
            if self.isGoalState(node[0]):
                print bcolors.OKGREEN + "--> Goal Found. Final number of states expanded = " + bcolors.OKBLUE + str(numberOfStatesExpanded) + bcolors.ENDC
                return [node[1], node[2]]

            numberOfStatesExpanded += 1
            successor_list          = []

            if node[0] not in closed:
                closed.append(node[0])
                successor_list = self.getSuccessors(node)
                while len(successor_list) > 0:
                    put = successor_list.pop()
                    if put[0] not in closed:

                        hval = float(method(put[0]))
                        if hval != -1:
                            newnode = [put[0], node[1] + [put[1]], put[2] + hval]
                            fringe.push(newnode, newnode[2])

        print bcolors.OKGREEN + "--> Search Terminated. Final number of states expanded = " + bcolors.OKBLUE + str(numberOfStatesExpanded) + bcolors.ENDC
        return None
Esempio n. 13
0
def aStarSearch(problem, heuristic=nullHeuristic):
    """Search the node that has the lowest combined cost and heuristic first."""
    def frontier_last_states(frontier):
        states = [path[2][-1][0] for path in frontier.heap]
        return states

    def path_cost(path):
        last_state = path[-1][0]
        cost = sum([cost for _, _, cost in path])
        hcost = heuristic(last_state, problem)
        return cost + hcost

    frontier = PriorityQueue()
    start_path = [(problem.initial_state(), 'START', 0.0)]
    frontier.push(start_path, path_cost(start_path))
    explored = set()
    limit = 50000
    while limit > 0:
        if frontier.isEmpty():
            return []
        path = frontier.pop()
        end_step = path[-1]
        end_state = end_step[0]
        explored.add(end_state.immutable())
        if problem.goal_test(end_state):
            return [action for _, action, _ in path[1:]], True, (len(explored),
                                                                 len(frontier))
        successors = problem.successors(end_state)
        for successor in successors:
            last_state = successor[0]
            if (last_state not in frontier_last_states(frontier)
                    and last_state.immutable()
                    not in explored) or problem.goal_test(last_state):
                extended_path = path.copy()
                extended_path.append(successor)
                frontier.push(extended_path, path_cost(extended_path))
            else:
                pass
        limit -= 1
    return [action for _, action, _ in frontier.pop()[1:]
            ], False, (len(explored), len(frontier))
Esempio n. 14
0
def search(grid, init, goal, cost):
    # ----------------------------------------
    # insert code here
    # ----------------------------------------
    Nr = len(grid)
    Nc = len(grid[0])
    expand = [[-1 for j in range(Nc)] for i in range(Nr)]
    count = 0

    def childNode(grid, loc, delta, delta_name):
        child = []
        for i in range(len(delta)):
            move = delta[i]
            newloc = [loc[0] + move[0], loc[1] + move[1]]
            if loc[0]+move[0]>=0 and loc[0]+move[0]<Nr \
            and loc[1]+move[1]>=0 and loc[1]+move[1]<Nc \
            and grid[newloc[0]][newloc[1]] ==0:
                child.append([newloc, delta_name[i]])
        return child

    visited = []
    frontier = PriorityQueue()
    gv = 0 + heuristic_fun(init, goal)
    frontier.push([init, 0], gv)

    while not frontier.isEmpty():
        loc, rlen = frontier.pop()
        if not loc in visited:
            visited.append(loc)
            expand[loc[0]][loc[1]] = count
            count += 1

            if loc == goal:
                return expand

            for nextloc, move_name in childNode(grid, loc, delta, delta_name):
                if not nextloc in visited:
                    gv = rlen + heuristic_fun(nextloc, goal)
                    frontier.push([nextloc, rlen + cost], gv)
    return 'fail'
Esempio n. 15
0
def branch_n_price(n, demands, capacity, distances, MasterProb):

    queue = PriorityQueue()
    MasterProb.RelaxOptimize()
    obj_val = MasterProb.relax_modelo.ObjVal

    queue.insert(obj_val, MasterProb)
    best_int_obj = 1e3
    best_relax_obj = 1e3

    nodes_explored = 0
    best_model = None

    while not queue.isEmpty():
        obj_val, MP_branch = queue.delete()
        nodes_explored += 1
        MP_branch.RelaxOptimize()
        solution = MP_branch.getSolution()
        duals = MP_branch.getDuals()

        branch_cost = MP_branch.getCosts()
        branch_routes = MP_branch.modelo.getA().toarray()
        sol_is_int = all([float(round(s, 4)).is_integer() for s in solution])
        # sol_is_int = all([False if i > 0.3 and np.abs(i - 1.0) > 0.3 else True for i in solution ])

        if obj_val < best_int_obj and sol_is_int:
            print(f"Best Integer Obj: {obj_val}")
            print(f"Nodes explored: {nodes_explored}")
            best_int_obj = obj_val

            # print(f"best sol: {solution}")
            best_model = copy_model(branch_cost, branch_routes, MP_branch)

        if obj_val < best_relax_obj:
            print(f"Best Relaxed Obj: {obj_val}")
            print(f"Nodes explored: {nodes_explored}")
            best_relax_obj = obj_val

        # --- # --- # Column generation # --- # --- #
        new_MP = column_generation(n, demands, capacity, distances, duals,
                                   MP_branch)

        if new_MP != None:
            new_MP.RelaxOptimize()
            branch_cost = new_MP.getCosts()
            branch_routes = new_MP.modelo.getA().toarray()
            if new_MP.relax_modelo.ObjVal <= best_relax_obj:
                queue.insert(new_MP.relax_modelo.ObjVal,
                             copy_model(branch_cost, branch_routes, new_MP))

        else:
            # --- # If stopped col generation then branch if solution is not integer # --- #

            if not sol_is_int:

                # print("#--#--#--# Not integer solution  ........Branching")
                queue = branch(branch_cost, branch_routes, n, demands,
                               capacity, distances, duals, solution, MP_branch,
                               queue, best_relax_obj)
            else:
                # print(f"best sol: {solution}")
                best_model = MP_branch

    return best_model
def dijkstra_transect(data, s, t):
    """ Calculate the optimal transect using Dijkstra's algorithm

    Parameters
    ----------
    data: array_like
        data image to run Dijkstra on
    s: tuple
        start coordinate (row, col) corresponding to glacier head
    t: tuple
        terminal coordinate (row, col) corresponding to glacier terminus

    Returns
    -------
    transect: array_like
        Recovered array with list of row and column for each point in transect
    vis: array_like
        Image where each pixel stores the order that it was visited at when the
        algorithm was run
    """
    nrow, ncol = data.shape

    x = np.arange(0, ncol)
    y = np.arange(0, nrow)
    coords = np.reshape(list(itertools.product(y, x)), (nrow, ncol, 2))

    # min cumulative velocity from s to given pixel
    dist = np.full((nrow, ncol), np.inf)
    # backtracking info at each pixel back to s
    back = np.full((nrow, ncol, 2), np.nan)
    # priority queue for storing discovered paths
    pq = PriorityQueue()
    # order of nodes visited
    vis = np.full((nrow, ncol), np.nan)

    # Add source to pq
    dist[s[0], s[1]] = data[s[0], s[1]]
    pq.push(s, data[s[0], s[1]])

    i = 0
    # Keep going until terminus found
    while np.isinf(dist[t[0], t[1]]) and not pq.isEmpty():
        # Expand next shortest path
        ui, uj = pq.pop()
        for v in get_neighbors(ui, uj, coords):
            # Found shorter path to v
            vi, vj = v

            vis[vi, vj] = int(i / 1e5)
            i += 1

            if vi == ui and vj == uj:
                continue

            if dist[vi, vj] > dist[ui, uj] + data[vi, vj]:
                # Update distance of v
                dist[vi, vj] = dist[ui, uj] + data[vi, vj]
                # Update backtrack pointer from v to u
                back[vi, vj] = [ui, uj]
                # Insert v into pq
                pq.push(coords[vi, vj], dist[vi, vj])

    # backtrack path
    return recover_transect(back, s, t), vis
Esempio n. 17
0

def path_list(it):  # this function is used to change -1 to _ again
    String = ""
    for i in it:
        for j in i:
            j = int(j)
            if j == -1:
                j = "_"
            j = str(j)
            String += j + " "
        String += "\n"
    print(String)


while not pq.isEmpty():
    pri, it = pq.pop()
    path_list(it)
    if pri == 0:
        print("Cost path:", cost)
        break
    closed_lst.append(it)
    successors = generateSuccessors(it)
    for successor in successors:
        if puzzleExistence(
                successor,
                closed_lst) or pq.checkExistence(successor) == False:
            successor_h = heuristic(successor, result)
            pq.update(successor, successor_h)
    cost += 1