Esempio n. 1
0
def NQueenDriver():
    attempted = 0
    hc_solved = 0
    sa_solved = 0
    saf_solved = 0

    for i in range(1000):
        attempted += 1

        hc = hill_climbing(MyNQueen(8))
        if -1 not in hc:
            hc_solved += 1
            print(f"hill_climbing solution: {hc}")

        sa = simulated_annealing(MyNQueen(8))
        if -1 not in sa:
            sa_solved += 1
            print(f"simulated annealing solution: {sa}")

        saf = simulated_annealing_full(MyNQueen(8))
        if -1 not in saf:
            saf_solved += 1
            print(f"Simulated annealing full solved: {saf}")
    print(
        f"N-Queen: Hill climbing (solved/attempted)                {hc_solved} / {attempted}"
    )
    print(
        f"N-Queen: Simulated annealing (solved/attempted)          {sa_solved} / {attempted}"
    )
    print(
        f"N-Queen: Simluated annealing full (solved/attempted)     {saf_solved} / {attempted}"
    )
Esempio n. 2
0
def test_maxsat_hillclimbing_restarts(fn, restarts):

    if VERBOSE_TESTING:
        print 'Hillclimbing with random restarts...(' + str(HILL_CLIMBING_RESTARTS) + ')'

    ms = MAXSAT(fn)
    # print "Initial: ", ms.true_clauses(ms.initial)

    t0 = time.time()

    best = None
    highest = 0

    for x in range(HILL_CLIMBING_RESTARTS):

        ms.initial = ms.init_variables(True)                  # randomize

        sol = search.hill_climbing(ms)

        if ms.true_clauses(sol) > highest:
            highest = ms.true_clauses(sol)
            best = sol[:]

    td = time.time() - t0
    
    if VERBOSE_TESTING:
        print ms.true_clauses(ms.initial), '->', ms.true_clauses(best)
        print "Time: %.2f" % td

    return ms.true_clauses(best), round(td, DEC_PRECISION)
Esempio n. 3
0
def test_rr_searches(restarts, initial_max):

    hill_restart_solution = 0
    hill_avg = []
    annealing_restart_solution = 0
    annealing_avg = []
    for i in range(restarts):
        # Get new starting point
        internal_p = SineVariant(randrange(0, initial_max),
                                 initial_max,
                                 delta=1)

        # Solve using hill-climbing + random restarts
        current_hill_solution = hill_climbing(internal_p)
        hill_avg.append(current_hill_solution)
        if current_hill_solution > hill_restart_solution:
            hill_restart_solution = current_hill_solution

        # Solve the problem using simulated annealing + random restarts
        current_annealing_solution = simulated_annealing(
            internal_p, exp_schedule(k=30, lam=0.005, limit=1000))
        annealing_avg.append(current_annealing_solution)
        if current_annealing_solution > annealing_restart_solution:
            annealing_restart_solution = current_annealing_solution

    # Print results of each test
    print('Hill-climbing (RR) solution       x: ' +
          str(hill_restart_solution) + '\t\tvalue: ' +
          str(internal_p.value(hill_restart_solution)) +
          '\taverage of runs: ' + str(sum(hill_avg) / len(hill_avg)))

    print('Simulated annealing (RR) solution x: ' +
          str(annealing_restart_solution) + '\t\tvalue: ' +
          str(internal_p.value(annealing_restart_solution)) +
          '\taverage of runs: ' + str(sum(annealing_avg) / len(annealing_avg)))
Esempio n. 4
0
def compare_algorithms_for_this_world(world,
                                      dist_dict,
                                      attempts=30,
                                      print_solution=False):

    # using the initial as our baseline
    best_hill_climber = world
    best_annealing = world

    # initializing averages
    avg_hill_climber = 0
    avg_annealing = 0

    # our small world problem representation
    tsp = TSP(world, dist_dict)

    # try both algorithms over and over
    for i in range(0, attempts):

        hill_climber = hill_climbing(tsp)
        annealing = simulated_annealing(
            tsp, exp_schedule(k=20, lam=0.005, limit=1000))

        # keep track of the best solutions
        if tsp.value(hill_climber) > tsp.value(best_hill_climber):
            best_hill_climber = hill_climber
        if tsp.value(annealing) > tsp.value(best_annealing):
            best_annealing = annealing

        # maintain average values
        avg_hill_climber += tsp.value(hill_climber)
        avg_annealing += tsp.value(annealing)

    # Calculate the average
    avg_hill_climber /= attempts
    avg_annealing /= attempts

    # Ouptut: world statistics
    print("World of size " + str(len(world)) + " with " + str(attempts) +
          " per algorithm")

    hill_path = str(best_hill_climber)
    annealing_path = str(best_annealing)

    if not print_solution:
        hill_path = ""
        annealing_path = ""

    # Output: hill climbing results
    print("Hill Climbing:\t" + hill_path + "\tbest: " +
          str(tsp.value(best_hill_climber)) + "\tavg: " +
          str(round(avg_hill_climber, 2)))

    # Output: simulated annealing results
    print("Annealing:\t" + annealing_path + "\tbest: " +
          str(tsp.value(best_annealing)) + "\tavg: " +
          str(round(avg_annealing, 2)))
Esempio n. 5
0
def test_searches(searchspace):
    # Solve the problem using hill-climbing.
    hill_solution = hill_climbing(searchspace)
    print('Hill-climbing solution            x: ' + str(hill_solution) +
          '\t\tvalue: ' + str(p.value(hill_solution)))
    # Solve the problem using simulated annealing.
    annealing_solution = simulated_annealing(
        searchspace, exp_schedule(k=30, lam=0.005, limit=1000))
    print('Simulated annealing solution      x: ' + str(annealing_solution) +
          '\t\tvalue: ' + str(p.value(annealing_solution)))
Esempio n. 6
0
def test_knapsack_hill_climbing_large_scale_3():
    params = open_file("../dataset/large_scale/knapPI_1_500_1000_1")
    problem = KnapsackProblem(params[0], params[1])
    ins_problem = InstrumentedProblem(problem)
    result = hill_climbing(ins_problem)
    optimum = int((
        open("../dataset/large_scale-optimum/knapPI_1_500_1000_1").readline()))
    assert optimum == 28857
    assert result.value <= 10000
    assert result.value >= 9800
def run_local_search(runType, inFile, outFile=OUTFILE):
  print >> outFile, '--------------------------------'
  fi = FORBIDDEN_ISLAND(inFile)
  if runType == 'SA':
    print >> outFile, 'Simulated Annealing'
    sTime = time.time()
    rtn = search.simulated_annealing(fi, annealing_schedule())
    print >> outFile, '  Time: {} secs'.format(time.time()-sTime)
    print >> outFile, '  Value: {}'.format(fi.value(rtn.state))
    print >> outFile, '  baseValues: {}'.format(rtn.state)
  elif runType == 'GA':
    print >> outFile, 'Genetic Algorithm'
    sTime = time.time()
    rtn = genetic_search(fi, fi.value)
    print >> outFile, '  Time: {} secs'.format(time.time()-sTime)
    print >> outFile, '  Value: {} / {}'.format(fi.value(rtn),  fi.numClause)
  elif runType == 'StA':
    print >> outFile, 'Steepest ascent'
    sTime = time.time()
    rtn = search.hill_climbing(fi)
    print >> outFile, '  Time: {} secs'.format(time.time()-sTime)
    print >> outFile, '  Value: {} / {}'.format(fi.value(rtn),  fi.numClause)
  elif runType == 'StAR':
    print >> outFile, 'Steepest ascent random restarts'
    valueL = []
    timeL = []
    for r in range(20):
      sTime = time.time()
      fi.random_start()
      rtn = search.hill_climbing(fi)
      timeL.append(time.time()-sTime)
      valueL.append(fi.value(rtn))
    print >> outFile, '  Time: {} secs'.format(sum(timeL)/float(len(timeL)))
    print >> outFile, '  Mean: {} / {}'.format(sum(valueL)/float(len(valueL)),  fi.numClause)
    print >> outFile, '  Min: {} / {}'.format(min(valueL),  fi.numClause)
    print >> outFile, '  Max: {} / {}'.format(max(valueL),  fi.numClause)
Esempio n. 8
0
def test_maxsat_hillclimbing(fn):
    
    if VERBOSE_TESTING:
        print 'Hillclimbing...'

    ms = MAXSAT(fn)
    # print "Initial: ", ms.true_clauses(ms.initial)  

    t0 = time.time()
    solution = search.hill_climbing(ms)
    td = time.time() - t0

    if VERBOSE_TESTING:
        print ms.true_clauses(ms.initial), '->', ms.true_clauses(solution)
        print "Time: %.2f" % td

    return ms.true_clauses(solution), round(td, DEC_PRECISION)
Esempio n. 9
0
def EightPuzzleDriver():
    hill_solved_count = 0
    hill_attempted_count = 0
    sa_attempted_count = 0
    sa_solved_count = 0
    saf_attempted_count = 0
    saf_solved_count = 0
    solution = (1, 2, 3, 4, 5, 6, 7, 8, 0)
    for i in itertools.permutations(list("012345678")):
        initial = tuple([int(j) for j in list(i)])
        my_8_pz = MyEightPuzzle(initial)

        hc = hill_climbing(my_8_pz)
        hill_attempted_count += 1
        if (solution == hc):
            print(f"Hill climbing solved {initial} -> {state}")
            hill_solved_count += 1

        my_8_pz = MyEightPuzzle(initial)
        sa = simulated_annealing(my_8_pz)
        sa_attempted_count += 1
        if (solution == sa):
            print(f"Simulated annealing solved {initial} -> {state}")
            sa_solved_count += 1

        my_8_pz = MyEightPuzzle(initial)
        saf = simulated_annealing_full(my_8_pz)
        saf_attempted_count += 1
        if (solution == saf):
            print(f"Simulated annealing full solved {initial} -> {state}")
            saf_solved_count += 1

        if hill_attempted_count > 1000:
            break

    print(
        f"8-puzzle: Hill climbing (solved / attempted):                     {hill_solved_count} / {hill_attempted_count}"
    )
    print(
        f"8-puzzle: Simulated annealing (solved / attempted):               {sa_solved_count} / {sa_attempted_count}"
    )
    print(
        f"8-puzzle: Simulated annealing full (solved / attempted):          {saf_solved_count} / {saf_attempted_count}"
    )
import tours
import search
from itertools import permutations
from random import choice

reg_tours = tours.generate_instances(100)
reg_tours = [list(permutations(cities)) for cities in reg_tours]

optimal = search.brute_force(reg_tours)

# random tour
selected_tours = [list(choice(permus)) for permus in reg_tours]
search.random_tour(selected_tours)

# hill climbing with randomly selected starting points
min_costs = search.hill_climbing(selected_tours)

# count optimal tours and print out
num_optimal = sum(x == y for x, y in zip(min_costs, optimal))

print("OPTIMAL PATHS FOUND: " + str(num_optimal))
print()
'''
  for tours with lots of cities
 100 cities proved to take incredibly long, 
 50 gets the job done in a reasonable amount of time
'''
big_tours = tours.generate_instances(100, 50)
search.hill_climbing(big_tours)
Esempio n. 11
0
    def value(self, state):
        mcovered = state.num_covered()  # /(state.N*state.M)
        over_covered = state.num_over_covered() / state.num_covered(
        ) if state.num_covered() > 0 else 0
        antennas_used = len(state.antennas) / state.A
        power_used = state.total_power() / state.P
        return mcovered - over_covered - antennas_used - power_used


initial = state(2, 8, 120, 120)
problem = city_antenna(initial)

print("Initial sate")
print(initial.forbidden)
problem.initial.print_state()
sol = search.hill_climbing(problem)

print("")
print("Final sate")
sol.state.print_state()
print(sol.state.antennas)
print(sol.solution())
"""
a = state(9, 9, 12, 12, ())
print(a.add_antenna((2, (8,8))))
print(a.add_antenna((2, (0,0))))
print('Num antennas: ', len(a.antennas))
print('Antennas: ', a.antennas)
print('Covered squares: ', a.num_covered())
print('Total power: ', a.total_power())
print(a.forbidden)
Esempio n. 12
0
            idx += 1
        assert (len(pos) == 2 or not pos)
        return pos

    def __str__(self):
        return 'driver: {} Route: {}'.format(self.user['id'], self.travel)


"""
This is going to call the Hill Climbing algorithm
"""

state = State(n=100, m=50)
state.generate_random_problem()

print('Initial global distance: {}'.format(state.global_distance()))

hc = CO2(state)

print('Initial value: {}'.format(hc.value(state)))
print()

final = search.hill_climbing(hc)

print()
print('Final global distance: {}'.format(final.global_distance()))
print('Final value: {}'.format(hc.value(final)))

print()
print("Final state:")
print(final)
Esempio n. 13
0
class TSP(Problem):
    def __init__(self, instance):
        self.city_count, self.matrix = read_txt_file(instance + ".txt")
        self.initial = get_initial_route(self.matrix, self.city_count)

    def actions(self, state):
        return get_possible_pairs(self.city_count)

    def result(self, state, action):
        return two_opt_swap_route(state, *action)

    def cost(self, state):
        cost = 0
        start = state[0]

        for end in state[1:]:
            num = self.matrix[start][end]
            cost += num
            start = end

        last_to_home = self.matrix[state[-1]][state[0]]
        return cost + last_to_home

    def value(self, state):
        return 1 / (self.cost(state) + 1)

p = search.InstrumentedProblem(TSP("gr48"))
g = search.hill_climbing(p)
print(g)
print(p.cost(g))
Esempio n. 14
0
File: sine.py Progetto: Jonri2/cs344
    def value(self, x):
        return math.fabs(x * math.sin(x))


if __name__ == '__main__':

    # Formulate a problem with a 2D hill function and a single maximum value.
    maximum = 30
    initial = randrange(0, maximum)
    p = SineVariant(initial, maximum, delta=1.0)
    print('Initial                      x: ' + str(p.initial) + '\t\tvalue: ' +
          str(p.value(initial)))

    # Solve the problem using hill-climbing.
    hill_solution = hill_climbing(p)
    print('Hill-climbing solution       x: ' + str(hill_solution) +
          '\tvalue: ' + str(p.value(hill_solution)))

    # Solve the problem using simulated annealing.
    annealing_solution = simulated_annealing(
        p, exp_schedule(k=20, lam=0.005, limit=1000))
    print('Simulated annealing solution x: ' + str(annealing_solution) +
          '\tvalue: ' + str(p.value(annealing_solution)))

    # Implements 100 random restarts, finding the average and best solutions for each algorithm
    best_hill_solution = 0
    best_annealing_solution = 0
    sum_hill_solutions = 0
    sum_annealing_solutions = 0
    for i in range(100):
        for i in range(2, len(state) - 1):
            l[1] = l[i]
            l[i] = second
            action = list_to_string(l)
            l[i] = l[1]
            l[1] = second
            actions.append(action)
        return actions

    def result(self, state, action):
        state = action
        return state

    def path_cost(self, c, state1, action, state2):
        return c + 1

    def value(self, state):
        l = list(state)
        cost = 0
        for i in range(0, len(l) - 1):
            index_1 = self.nodes.index(l[i])
            index_2 = self.nodes.index(l[i + 1])
            cost += -1 * self.costs[index_1][index_2]
        return cost


#result = astar_search(TSPProblem(nodes, costs))
#result = recursive_best_first_search(TSPProblem(nodes, costs))
result = hill_climbing(TSPProblem(nodes, costs, initial))
print(['-'.join(list(result))])
Esempio n. 16
0
    towns = 10
    world = World(towns)
    path = []
    for i in range(towns):
        path.append(i)
    
    random.shuffle(path)
    print(path)
    tsp = TSP(world, path)
    print('Initial                      x: ' + str(tsp.initial)
          + '\t\tvalue: ' + str(-tsp.value(path))
          )

    startHill = time.time()
    # Solve the problem using hill-climbing.
    hill_solution = hill_climbing(tsp)
    endHill = time.time()
    print('Hill-climbing solution       x: ' + str(hill_solution)
          + '\tvalue: ' + str(-tsp.value(hill_solution))
          )
    print("Time taken was", round(endHill - startHill, 7))

    startAnneal = time.time()
    annealing_solution = simulated_annealing(
        tsp,
        exp_schedule(k=20, lam=0.005, limit=1000)
    )
    endAnneal = time.time()
    print('Simulated annealing solution x: ' + str(annealing_solution)
          + '\tvalue: ' + str(-tsp.value(annealing_solution))
          )
Esempio n. 17
0
            possibilities = list(node.state.possible_values(i, j))
            return len(possibilities) - 1
        return 0

    choices = {
        'depth_first': depth_first_tree_search,
        # 'best_first_uniform': uniform_cost_tree_search,
        'best_first_h1': lambda x: best_first_tree_search(x, h1),
        'best_first_h2': lambda x: best_first_tree_search(x, h2),
        'best_first_greedy_h1': lambda x: best_first_greedy_tree_search(x, h1),
        'best_first_greedy_h2': lambda x: best_first_greedy_tree_search(x, h2),
        'best_first_h3': lambda x: best_first_tree_search(x, h3),
        'best_first_greedy_h3': lambda x: best_first_greedy_tree_search(x, h3),
        'best_first_graph_h1': lambda x: best_first_graph_search(x, h1),
        'best_first_graph_h2': lambda x: best_first_graph_search(x, h2),
        'hill_climbing': lambda x: hill_climbing(x),
        'annealing': lambda x: simulated_annealing(x, schedule=sim)
    }

    #    print(sys.argv)
    searchers = sys.argv[1:]
    lewisProblems = map(LewisSudokuProblem, sudokus)
    naiveProblems = map(SudokuProblem, sudokus)
    #csv header
    print("problem,searcher,explored,states,tests,solution,value")
    for (i, (p1, p2)) in enumerate(zip(lewisProblems, naiveProblems)):
        #print("Initial state:")

        for s in searchers:
            if s in ['hill_climbing', 'annealing']:
                ip = InstrumentedProblem(p1)
Esempio n. 18
0
                     eforie=(562, 293),
                     fagaras=(305, 449),
                     giurgiu=(375, 270),
                     hirsova=(534, 350),
                     iasi=(473, 506),
                     lugoj=(165, 379),
                     mehadia=(168, 339),
                     neamt=(406, 537),
                     oradea=(131, 571),
                     pitesti=(320, 368),
                     rimnicuvilcea=(233, 410),
                     sibiu=(207, 457),
                     timisoara=(94, 410),
                     urziceni=(456, 350),
                     vaslui=(509, 444),
                     zerind=(108, 531))

initial1 = random.choice(list(locations.keys()))
problem1 = TSP(locations, initial1)
initial2 = random.choice(list(locations.keys()))
problem2 = TSP(locations, initial2)

hill_solution = hill_climbing(problem1)
print('\nHill-climbing solution       x: ' + '\tvalue: ' +
      str(math.fabs(problem1.value(hill_solution))) + "\n\n")

annealing_solution = simulated_annealing(
    problem2, exp_schedule(k=20, lam=0.005, limit=15000))
print('\nAnnealing solution       x: ' + '\tvalue: ' +
      str(math.fabs(problem2.value(annealing_solution))) + "\n\n")
Esempio n. 19
0
File: tsp.py Progetto: bff3/cs344
        for k in vertexstring[i + 1:]:
            vertex_dict[k] = rnd.randint(1, maxdist)
        graph_dict[vertexstring[i]] = vertex_dict
    return graph_dict

if __name__ == '__main__':

    # invalid_it = ['C','D','B','A']
    # valid_it = ['C','A','B','D']
    # simpleTSP = TSP(invalid_it, simple_map)
    # print(hill_climbing(simpleTSP))
    graph_dict = gen_graph(vertexstring='ABCDEFGHIJKLMNOPQRSTUVWXYZ')
    print(graph_dict)
    myGraph = UndirectedGraph(graph_dict)
    myTSP = TSP(get_city_list(myGraph), myGraph)
    values = []
    for _ in range(1000):
        hill_climbing_solution = hill_climbing(myTSP)
        values.append(myTSP.value(hill_climbing_solution))
        # print(hill_climbing_solution)
        # print(myTSP.value(hill_climbing_solution))
    print(max(values))

    annealing_solution = simulated_annealing(myTSP, exp_schedule(k=20, lam=0.005, limit=100000))
    print(annealing_solution)
    print(myTSP.value(annealing_solution))




Esempio n. 20
0
def value_function(b, n, d):
    return math.pow(b, d + 1) - (n + 1) * b + n


city_num = 20
start = generate_random_init(city_num)
print(start)

tsp = TSPHillClimbingProblem(start,
                             cities=generate_random_cities(city_num, 100))
#print(tsp.actions(start))

# compare the execution time
start_time = time.time()
path = hill_climbing(tsp)
print(path)
print("Execution time for hill-climbing: {}".format(time.time() - start_time))

xs = []
ys = []
for i in range(len(path)):
    xs.append(tsp.cities[path[i]][0])
    ys.append(tsp.cities[path[i]][1])
xs.append(tsp.cities[path[0]][0])
ys.append(tsp.cities[path[0]][1])

plt.plot(xs, ys)
plt.axis([-1, 100. + 1, -1, 100 + 1])
plt.show()
Esempio n. 21
0
import search
from utils import (is_in, argmin, argmax, argmax_random_tie, probability,
                   weighted_sampler, memoize, print_table, open_data, Stack,
                   FIFOQueue, PriorityQueue, name, distance, vector_add)

eight_puzzle = search.EightPuzzle((1, 2, 3, 4, 5, 7, 8, 6, 0))
nqueens = search.NQueensProblem(8)
romania_problem = search.GraphProblem('Arad', 'Craiova', search.romania_map)

prob = search.PeakFindingProblem(
    (0, 0), [[0, 5, 30, 20], [10, 5, 45, 20], [6, 9, 18, 22]
             ])  #N,W,S,E considered to find peak
print(search.hill_climbing(prob))
Esempio n. 22
0
    if debug:
        # Debug statement.
        print("\nDistances between pairs of cities: A --> B and B --> A")
        for key, value in cityDistancesUnique.items():
            print("Key is: " + str(key))
            print("Value is: " + str(value))

    ################################################################################################

    # Initialize the Traveling Salesman Problem.
    travel = Salesman(cityDistancesUnique, cities)

    # Solve the problem using hill climbing.
    hillStartTime = time.time()
    hill_solution = hill_climbing(travel)
    hillEndTime = time.time()
    print('Hill-climbing:')
    print('\tSolution: ' + str(hill_solution))
    print('\tValue:    ' + str(travel.value(hill_solution)))
    print('\tTime to find solution using hill-climbing: ' +
          str(hillEndTime - hillStartTime))

    # Solve the problem using simulated annealing.
    annealStartTime = time.time()
    annealing_solution = simulated_annealing(
        travel, exp_schedule(k=20, lam=0.005, limit=10000))
    annealEndTime = time.time()
    print('Simulated annealing:')
    print('\tSolution: ' + str(annealing_solution))
    print('\tValue:    ' + str(travel.value(annealing_solution)))
Esempio n. 23
0
def main():
    args = parser.parse_args()

    bounds, ghosts, pacman, goal = mapPositions(args.layout)

    print('Barreiras:', bounds)
    print('Fantasmas:', ghosts)
    print('Pacman:', pacman)
    print('Gol:', goal)
    print()

    #Problema e algoritmos
    problem = PacmanProblem(obstacles=bounds | ghosts,
                            initial=pacman,
                            goal=goal)
    gfsProblem = greedy_best_first_search(problem)
    astarProblem = astar_search(problem)
    bfsProblem = breadth_first_graph_search(problem)
    dfsProblem = depth_first_graph_search(problem)
    hcProblem = hill_climbing(problem)
    print('Greedy Best First Search:')
    print('Caminho:', gfsProblem.path())
    print('Gol:', gfsProblem)
    print('A* Search:')
    print('Caminho:', astarProblem.path())
    print('Solução:', astarProblem.solution())
    print('Estados:', path_states(astarProblem))
    print('Gol:', astarProblem)
    print('Breadth-First Search:')
    print('Caminho:', bfsProblem.path())
    print('Solução:', bfsProblem.solution())
    print('Estados:', path_states(bfsProblem))
    print('Gol:', dfsProblem)
    print('Depth-First Search:')
    print('Caminho:', dfsProblem.path())
    print('Solução:', dfsProblem.solution())
    print('Estados:', path_states(dfsProblem))
    print('Gol:', dfsProblem)
    print('Hill Climbing:')
    print('Caminho:', hcProblem.path())
    print('Solução:', hcProblem.solution())
    print('Estados:', path_states(hcProblem))
    print('Gol:', dfsProblem)
    print()
    print('Gerando saídas...')
    generateOutput(
        set(gfsProblem.solution()) - {pacman, goal},
        gfsProblem.explored - {pacman, goal}, args.layout, 'gfs')
    generateOutput(
        set(astarProblem.solution()) - {pacman, goal},
        astarProblem.explored - {pacman, goal}, args.layout, 'astar')
    generateOutput(
        set(bfsProblem.solution()) - {pacman, goal},
        bfsProblem.explored - {pacman, goal}, args.layout, 'bfs')
    generateOutput(
        set(dfsProblem.solution()) - {pacman, goal},
        dfsProblem.explored - {pacman, goal}, args.layout, 'dfs')
    generateOutput(
        set(hcProblem.solution()) - {pacman, goal},
        hcProblem.explored - {pacman, goal}, args.layout, 'hc')

    print()
    print('Desempenho:')
    report([
        greedy_best_first_search, astar_search, breadth_first_graph_search,
        depth_first_graph_search, hill_climbing
    ], [problem])
Esempio n. 24
0
    def value(self, x):
        return math.fabs(x * math.sin(x))


if __name__ == '__main__':

    # Formulate a problem with a 2D hill function and a single maximum value.
    maximum = 30
    initial = randrange(0, maximum)
    p = SineVariant(initial, maximum, delta=1.1)
    print('Initial                      x: ' + str(p.initial) + '\t\tvalue: ' +
          str(p.value(initial)))

    # Solve the problem using hill-climbing.
    hill_solution = hill_climbing(p)
    annealing_solution = simulated_annealing(
        p, exp_schedule(k=20, lam=0.005, limit=1000))

    hill_restarts = hill_solution
    hill_value_accumulator = 0
    hill_x_accumulator = 0

    annealing_restarts = annealing_solution
    annealing_value_accumulator = 0
    annealing_x_accumulator = 0

    restarts = 100
    for i in range(restarts):
        initial = randrange(0, maximum)
        p = SineVariant(initial, maximum, delta=1.1)
Esempio n. 25
0
class TSP2(Problem):

    def __init__(self, n, initial):
        self.n = n
        self.initial = initial

    def actions(self, state):
        actions = []
        for column in range(self.n):
            for row in [x for x in range(self.n) if x != state[column]]:
                actions.append([column, row])
        for i in range(1,10):
        return actions

    def result(self, state, move):
        """Makes the given move on a copy of the given state."""
        new_state = state[:]
        new_state[move[0]] = move[1]
        return new_state

    def goal_test(self, state):
        """Check to see if there are no conflicts."""
        return not any(self.conflicted(state, state[col], col)
                       for col in range(len(state)))

    def conflicted(self, state, row, col):
        """Check to see if placing a queen at (row, col) would conflict with
        anything.
        """
        return any(self.conflict(row, col, state[c], c)
                   for c in range(col))

    def conflict(self, row1, col1, row2, col2):
        """Check to see if two queens placed in (row1, col1) and (row2, col2)
        respectively would conflict with each other.
        """
        return (row1 == row2  # # same row
                or col1 == col2  # # same column
                or row1 - col1 == row2 - col2  # # same \ diagonal
                or row1 + col1 == row2 + col2)  # # same / diagonal

    def value(self, state):
        """This method computes a value of given state based on the number of
        conflicting pairs of queens. It doesn't follow AIMA-Python's NQueens
        gradient-descent formulation; instead, it counts the number of
        non-conflicting pairs (e.g., top score: 28 for a 8-queen problem;
        worst score: 0).
        """

        # Start with the highest possible score (n combined 2).
        value = math.factorial(self.n) / (2 * math.factorial(self.n - 2))

        # Loop through all pairs, subtracting one for every conflicted pair.
        for pair in itertools.combinations(range(self.n), 2):
            if self.conflict(state[pair[0]], pair[0], state[pair[1]], pair[1]):
                value -= 1
                
        return value


if __name__ == '__main__':

    # Set the board size.
    n = 8

    # Initialize the board with all queens in the first row.
    board = [0] * n
    print('Start:    ' + str(board))

    # Initialize the NQueens problem
    p = TSP2(n, board)
    print('Value:    ' + str(p.value(board)))

    # Solve the problem using hill climbing.
    hill_solution = hill_climbing(p)
    print('Hill-climbing:')
    print('\tSolution: ' + str(hill_solution))
    print('\tValue:    ' + str(p.value(hill_solution)))
    print('\tGoal?     ' + str(p.goal_test(hill_solution)))

    # Solve the problem using simulated annealing.
    annealing_solution = simulated_annealing(
        p,
        exp_schedule(k=20, lam=0.005, limit=10000)
    )
    print('Simulated annealing:')
    print('\tSolution: ' + str(annealing_solution))
    print('\tValue:    ' + str(p.value(annealing_solution)))
    print('\tGoal?     ' + str(p.goal_test(annealing_solution)))