Beispiel #1
0
def anytime_gbfs(initial_state, heur_fn, timebound=10):
    # IMPLEMENT
    """Provides an implementation of anytime greedy best-first search, as described in the HW1 handout"""
    """INPUT: a rush hour state that represents the start state and a timebound (number of seconds)"""
    """OUTPUT: A goal state (if a goal is found), else False"""
    """implementation of anytime greedybfs algorithm"""
    search_engine = SearchEngine("best_first", "full")
    search_engine.init_search(initial_state, rushhour_goal_fn, heur_fn)

    gval_cost_bound = float("inf")
    time_left = timebound

    init_time = os.times()[0]
    solution = search_engine.search(
        timebound=time_left, costbound=(gval_cost_bound, float("inf"), float("inf"))
    )
    finish_time = os.times()[0]

    time_left -= finish_time - init_time

    if solution:
        gval_cost_bound = solution.gval
    else:
        return False

    while time_left > 0:
        init_time = os.times()[0]
        improved_solution = search_engine.search(
            timebound=time_left, costbound=(gval_cost_bound, float("inf"), float("inf"))
        )
        time_left -= os.times()[0] - init_time
        if improved_solution:
            gval_cost_bound = improved_solution.gval
            solution = improved_solution
        else:
            break

    return solution
Beispiel #2
0
def anytime_weighted_astar(initial_state, heur_fn, weight=1.0, timebound=10):
    # IMPLEMENT
    """Provides an implementation of anytime weighted a-star, as described in the HW1 handout"""
    """INPUT: a rush hour state that represents the start state and a timebound (number of seconds)"""
    """OUTPUT: A goal state (if a goal is found), else False"""
    """implementation of weighted astar algorithm"""
    time_left = timebound
    wrapped_fval_function = lambda sN: fval_function(sN, weight)
    se = SearchEngine("custom", "full")
    se.init_search(initial_state, rushhour_goal_fn, heur_fn, wrapped_fval_function)
    cost_bound = float("inf")
    init_time = os.times()[0]
    solution = se.search(
        timebound=time_left, costbound=(float("inf"), float("inf"), cost_bound)
    )
    finish_time = os.times()[0]
    time_left -= finish_time - init_time

    if solution:
        cost_bound = solution.gval + heur_fn(solution)
    else:
        return False

    while time_left > 0:
        init_time = os.times()[0]
        improved_solution = se.search(
            timebound=time_left, costbound=(float("inf"), float("inf"), cost_bound)
        )
        finish_time = os.times()[0]
        time_left -= finish_time - init_time
        if improved_solution:
            cost_bound = improved_solution.gval + heur_fn(improved_solution)
            solution = improved_solution
        else:
            break

    return solution