예제 #1
0
def resolver(metodo_busqueda, iteraciones, haz, reinicios):

    visor = ConsoleViewer()

    if (metodo_busqueda == 'hill_climbing'):
        resultado = hill_climbing(problem=HnefataflProblema(INITIAL),
                                  iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'hill_climbing_stochastic'):
        resultado = hill_climbing_stochastic(
            problem=HnefataflProblema(INITIAL), iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'beam'):
        resultado = beam(problem=HnefataflProblema(None),
                         beam_size=haz,
                         iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'hill_climbing_random_restarts'):
        resultado = hill_climbing_random_restarts(
            problem=HnefataflProblema(None),
            restarts_limit=reinicios,
            iterations_limit=iteraciones)
        return resultado

    if (metodo_busqueda == 'simulated_annealing'):
        resultado = simulated_annealing(problem=HnefataflProblema(INITIAL),
                                        iterations_limit=iteraciones)
        return resultado
def resolver(metodo_busqueda):
    vwr = BaseViewer()
    if metodo_busqueda == "hill_climbing":
        result = hill_climbing(DotaArmamento(INITIAL), viewer=vwr, iterations_limit=1000)
    elif metodo_busqueda == "beam":
        result = beam(DotaArmamento(), beam_size=100, viewer=vwr, iterations_limit=1000)
    elif metodo_busqueda == "hill_climbing_random_restarts":
        result = hill_climbing_random_restarts(DotaArmamento(), restarts_limit=100, viewer=vwr, iterations_limit=1000)
    return result
예제 #3
0
    def pixelize_image(self, method, points=None):

        best_state = None
        triangle_mask = None

        if points is None:
            best_state = cacher.best_state(self.image_name, self.max_points)

        if best_state is not None:
            triangle_mask = best_state

        if triangle_mask is None:
            triangle_mask = TriangleMask(self.width, self.height)

        my_problem = SplitProblem( triangle_mask, split_image=self )

        if method == "astar":
            result = astar(my_problem, graph_search = True)
        elif method == "beam":
            result = beam(my_problem)
        elif method == "hill_random":
            result = hill_climbing_random_restarts(my_problem, 1)
        elif method == "hill":
            result = hill_climbing(my_problem)
        else:
            print("Invalid method: {}".format(method))
            return

        print("FINAL RESULT REACHED")
        print("RESULT: {}".format( result.state.triangles))

        # TODO: Make caching work with triangle masks
        cacher.persist_log( self.image_name )

        triangle_mask = result.state
        triangles = triangle_mask.triangles

        self.display(triangles)

        if self.wait:
            a = input("Would you like to improve on this?\n")
            a = a.upper().strip()
            if a not in {"Y","YES","YUP","YEAH"}:
                return

            method_temp = input("Which method? [{}]\n".format(method)).strip().lower()
            if method_temp:
                method = method_temp
            max_points = input("How many points? [{}]\n".format(self.max_points)).strip()
            if max_points:
                self.max_points = int(max_points)

            return self.pixelize_image(method, points)
        return triangles
예제 #4
0
def resolver(metodo_busqueda, iteraciones, haz, reinicios):
    #problema = Hnefatafl(INICIAL)
    if metodo_busqueda == "hill_climbing":
        resultado = hill_climbing(Hnefatafl(INICIAL), iteraciones)
    if metodo_busqueda == "hill_climbing_stochastic":
        resultado = hill_climbing_stochastic(Hnefatafl(INICIAL), iteraciones)
    if metodo_busqueda == "hill_climbing_random_restarts":
        resultado = hill_climbing_random_restarts(Hnefatafl(None), reinicios, iteraciones)
    if metodo_busqueda == "beam":
        resultado = beam(Hnefatafl(INICIAL), beam_size = haz, iterations_limit = iteraciones)
    if metodo_busqueda == "simulated_annealing":
        resultado = simulated_annealing(Hnefatafl(INICIAL), iterations_limit = iteraciones)
    return resultado
def resolver(metodo_busqueda, iteraciones, haz, reinicios):
    problema = HnefataflProblem(inicial())
    if metodo_busqueda == "hill_climbing":
        resultado = hill_climbing(problema, iteraciones)
        return resultado
    if metodo_busqueda == "hill_climbing_stochastic":
        return hill_climbing_stochastic(problema, iteraciones)
    if metodo_busqueda == "beam":
        return beam(problema, haz, iteraciones)
    if metodo_busqueda == "hill_climbing_random_restarts":
        return hill_climbing_random_restarts(problema, reinicios, iteraciones)
    if metodo_busqueda == "simulated_annealing":
        return simulated_annealing(problema, iterations_limit=iteraciones)
예제 #6
0
def resolver(metodo_busqueda, iteraciones, haz, reinicios):
    problema_inicial = Hnefatafl2(INICIAL)
    if metodo_busqueda == "hill_climbing":
        return hill_climbing(problema_inicial, iteraciones)
    if metodo_busqueda == "hill_climbing_stochastic":
        return hill_climbing_stochastic(problema_inicial, iteraciones)
    if metodo_busqueda == "beam":
        return beam(problema_inicial, haz, iteraciones)
    if metodo_busqueda == "hill_climbing_random_restarts":
        return hill_climbing_random_restarts(problema_inicial, reinicios,
                                             iteraciones)
    if metodo_busqueda == "simulated_annealing":
        return simulated_annealing(problema_inicial,
                                   iterations_limit=iteraciones)
예제 #7
0
파일: reinas.py 프로젝트: ucse-ia/ucse_ia
        columna, fila = action
        state[columna] = fila

        return tuple(state)

    def value(self, state):
        atacando = 0

        for columna1, fila1 in enumerate(state):
            for columna2, fila2 in enumerate(state):
                if columna2 > columna1:
                    if fila1 == fila2:
                        atacando += 1
                    else:
                        dif_col = abs(columna1 - columna2)
                        dif_fil = abs(fila1 - fila2)
                        if dif_col == dif_fil:
                            atacando += 1

        return -atacando

    def generate_random_state(self):
        return tuple([random.randint(0, 8)
                      for _ in range(8)])


result = hill_climbing_random_restarts(EightQueensProblem(), 1000)

print result.state
print EightQueensProblem().value(result.state)
예제 #8
0
        for queen, current_row in enumerate(state):
            for queen2, current_row2 in enumerate(state):
                if queen < queen2:
                    # same row
                    if current_row == current_row2:
                        attacks += 1
                    else:
                        # diagonal
                        diff_col = abs(queen - queen2)
                        diff_row = abs(current_row - current_row2)
                        if diff_col == diff_row:
                            attacks += 1

        return -attacks

    def generate_random_state(self):
        state = []
        for queen in range(N):
            row = random.randint(0, N - 1)
            state.append(row)

        return tuple(state)


if __name__ == '__main__':
    problem = QueensProblem(INITIAL)
    result = hill_climbing_random_restarts(problem, restarts_limit=10)

    print(result.state)
    print('Attacks:', -problem.value(result.state))
예제 #9
0
        attacks = 0
        for queen, current_row in enumerate(state):
            for queen2, current_row_2 in enumerate(state):
                if queen < queen2:
                    #same row
                    if current_row == current_row_2:
                        attacks += 1
                    else:
                        #diagonal
                        diff_col = abs(queen - queen2)
                        diff_row = abs(current_row_2 - current_row_2)
                        if diff_col == diff_row:
                            attacks += 1
        return -attacks

    def generate_random_state(self):
        state = []
        for queens in range(N):
            row = random.randint(0, N - 1)
            state.append(row)
        return tuple(state)


if __name__ == '__main__':
    problem = QueensProblem(INITIAL)
    result = hill_climbing_random_restarts(problem,
                                           restarts_limit=10000,
                                           viewer=None)

    print(result.state)
    print('Attacks:', -problem.value())
예제 #10
0
파일: queens.py 프로젝트: ucse-ia/ucse_ia
        ataques = ataques / 2

        return -ataques

    def generate_random_state(self):
        estado = []
        for reina in range(8):
            estado.append(random.randint(0, 7))

        return tuple(estado)


if __name__ == '__main__':
    result = globals()[metodo_busqueda](Problema...)
    result = hill_climbing_random_restarts(QueensProblem(None), restarts_limit=100)

    for fila in range(8):
        for columna in range(8):
            if result.state[columna] == fila:
                print '|*',
            else:
                print '| ',
        print
        print '-' * 40

    print result.value



예제 #11
0
	def _tour_length(self, s):
		length = 0
		for i in xrange(len(s)-1):
			length += self.distances[s[i]][s[i+1]]
		return length


if __name__ == "__main__":
	distances = [ \
	[0, 6, 5, 7, 8, 2, 2, 6, 6, 5, 7, 5], \
	[6, 0, 3, 5, 2, 4, 4, 5, 2, 2, 1, 5], \
	[5, 3, 0, 6, 1, 1, 8, 7, 7, 6, 4, 3], \
	[7, 5, 6, 0, 3, 5, 1, 1, 7, 3, 8, 4], \
	[8, 2, 1, 3, 0, 7, 7, 8, 7, 3, 2, 5], \
	[2, 4, 1, 5, 7, 0, 8, 2, 5, 5, 2, 6], \
	[2, 4, 8, 1, 7, 8, 0, 1, 7, 8, 1, 8], \
	[6, 5, 7, 1, 8, 2, 1, 0, 1, 5, 1, 4], \
	[6, 2, 7, 7, 7, 5, 7, 1, 0, 7, 5, 4], \
	[5, 2, 6, 3, 3, 5, 8, 5, 7, 0, 4, 2], \
	[7, 1, 4, 8, 2, 2, 1, 1, 5, 4, 0, 2], \
	[5, 5, 3, 4, 5, 6, 8, 4, 4, 2, 2, 0]]
	problem = TspProblem(len(distances),distances);
	result = hill_climbing_random_restarts(problem, restarts_limit=200, viewer=ConsoleViewer())
	#result = hill_climbing_random_restarts(problem, restarts_limit=200)
	print result.state
	#print result.path()




        state[aenum][aen] = val
        state[enum][en] = 0
        return tuple(state)

    def value(self, state):
        cant = 0
        for enum, item in enumerate(state):
            for en, it in enumerate(item):
                if it != GOAL[enum][en]:
                    cant += it
        return -cant

    def generate_random_state(self):
        initial = list((list(INITIAL[0]), list(INITIAL[1]), list(INITIAL[2])))
        enum, en = find(initial, 0)
        aenum, aen = find(initial, randint(1, 8))
        initial[enum][en] = initial[aenum][aen]
        initial[aenum][aen] = 0
        return tuple((tuple(initial[0]), tuple(initial[1]), tuple(initial[2])))


visor = BaseViewer()
reinicios = 1000
resultado = hill_climbing_random_restarts(
    Puzzle(INITIAL), iterations_limit=1000, restarts_limit=reinicios, viewer=visor
)
# resultado = hill_climbing_random_restars(Puzzle(INITIAL), viewer=visor)
print "path", resultado.path()
print "resultado", resultado
print "visor", visor.stats
            next_city = s[0][i + 1]
            current_dist = self.cityDistances[current_city][next_city]
            total_dist += current_dist
        
        # Add in distance for returning trip to origin of tour
        total_dist += self.cityDistances[s[0][self.numCities - 1]][s[0][0]]
        
        return total_dist



problem = TspProblem(12, [[0, 5, 7, 6, 8, 1, 3, 9, 14, 3, 2, 9], \
                          [5, 0, 6, 10, 4, 3, 12,14, 9, 1, 2, 7], \
                          [7, 6, 0, 2, 3, 4, 11, 13, 4, 8, 10, 5], \
                          [6, 10, 2, 0, 5, 7, 9, 11, 13, 5, 3, 1], \
                          [8, 4, 3, 5, 0, 9, 11, 14, 5, 8, 3, 8], \
                          [1, 3, 4, 7, 9, 0, 5, 6, 14, 18, 4, 7], \
                          [3, 12, 11, 9, 11, 5, 0, 19, 4, 3, 5, 6], \
                          [9, 14, 13, 11, 14, 6, 19, 0, 1, 4, 5, 7], \
                          [14, 9, 4, 13, 5, 14, 4, 1, 0, 8, 3, 1], \
                          [3, 1, 8, 5, 8, 18, 3, 4, 8, 0, 4, 5], \
                          [2, 2, 10, 3, 3, 4, 5, 5, 3, 4, 0, 1], \
                          [9, 7, 5, 1, 8, 7, 6, 7, 1, 5, 1, 0]])

#vw = ConsoleViewer()

#result = hill_climbing_random_restarts(problem, restarts_limit=200, viewer=vw)
result = hill_climbing_random_restarts(problem, restarts_limit=200)

print result
def resolver(metodo_busqueda, iteraciones, haz, reinicios):
    print '··· Se van a ejecutar las 10 iteraciones para la busqueda {} ···'.format(
        metodo_busqueda)
    #print 'Haz:', haz
    #print 'Reinicios:', reinicios
    prob = HnefataflProblem(INITIAL)
    visor = BaseViewer()
    if (metodo_busqueda == 'hill_climbing'):  # Ascenso de colina
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing(problem=prob,
                                      iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('1', max(apuntos))
    elif (metodo_busqueda == 'hill_climbing_stochastic'
          ):  # Ascenso de colina, variante estocástica
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing_stochastic(problem=prob,
                                                 iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('2', max(apuntos))
    elif (metodo_busqueda == 'beam'):  # Haz local
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = beam(problem=HnefataflProblem(None),
                             iterations_limit=iteraciones,
                             beam_size=haz)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('3', max(apuntos))
    elif (metodo_busqueda == 'hill_climbing_random_restarts'
          ):  # Ascenso de colina con reinicios aleatorios
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = hill_climbing_random_restarts(
                problem=HnefataflProblem(None),
                iterations_limit=iteraciones,
                restarts_limit=reinicios)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('4', max(apuntos))
    elif (metodo_busqueda == 'simulated_annealing'):  # Temple simulado
        for x in range(10):
            print 'Ejecutando Iteracion {} ...'.format(x)
            inicio = datetime.now()
            resultado = simulated_annealing(problem=prob,
                                            iterations_limit=iteraciones)
            fin = datetime.now()
            print 'Tiempo de iteracion {} : {} segundos.'.format(
                x, (fin - inicio).total_seconds())
        grabar('5', max(apuntos))
    return resultado
예제 #15
0
            totales.append(sum(fila))

        # totales por columna
        for indice_col in range(3):
            numeros_col = [fila[indice_col] for fila in state]
            totales.append(sum(numeros_col))

        # cuantos hay igual a 15??
        correctas = totales.count(15)

        return correctas

    def generate_random_state(self):
        numeros = list(range(1, 10))
        shuffle(numeros)

        state = tuple(numeros[:3]), tuple(numeros[3:6]), tuple(numeros[6:])

        return state


if __name__ == '__main__':
    problema = CuadradosProblem(INITIAL_STATE)
    # resultado = hill_climbing(problema)
    # resultado = simulated_annealing(problema)
    resultado = hill_climbing_random_restarts(problema, 1000)

    print(resultado.state)
    print('Cuantas dan 15?:', problema.value(resultado.state))

예제 #16
0
        # pero despues restamos los precios de las cosas "rotas" por conflicto
        for item_a, item_b in CONFLICTOS:
            if item_a in state and item_b in state:
                suma -= PRECIOS[item_a]
                suma -= PRECIOS[item_b]

        return suma

    def generate_random_state(self):
        items_disponibles = list(ITEMS)  # creamos una copia para nosotros
        random.shuffle(items_disponibles)

        items_equipados = []
        for i in range(4):
            items_equipados.append(items_disponibles.pop())

        return tuple(items_equipados)

print 'Hill climbing:'
v = BaseViewer()
result = hill_climbing(ItemsDota(('A', 'B', 'C', 'D')), viewer=v)
print result.state
print result.value
print v.stats


print 'Hill climbing random restarts'
result = hill_climbing_random_restarts(ItemsDota(), restarts_limit=100)
print result.state
print result.value
예제 #17
0
        return (None, state)

    def _tour_length(self, s):
        length = 0
        for i in xrange(len(s) - 1):
            length += self.distances[s[i]][s[i + 1]]
        return length


if __name__ == "__main__":
    distances = [ \
    [0, 6, 5, 7, 8, 2, 2, 6, 6, 5, 7, 5], \
    [6, 0, 3, 5, 2, 4, 4, 5, 2, 2, 1, 5], \
    [5, 3, 0, 6, 1, 1, 8, 7, 7, 6, 4, 3], \
    [7, 5, 6, 0, 3, 5, 1, 1, 7, 3, 8, 4], \
    [8, 2, 1, 3, 0, 7, 7, 8, 7, 3, 2, 5], \
    [2, 4, 1, 5, 7, 0, 8, 2, 5, 5, 2, 6], \
    [2, 4, 8, 1, 7, 8, 0, 1, 7, 8, 1, 8], \
    [6, 5, 7, 1, 8, 2, 1, 0, 1, 5, 1, 4], \
    [6, 2, 7, 7, 7, 5, 7, 1, 0, 7, 5, 4], \
    [5, 2, 6, 3, 3, 5, 8, 5, 7, 0, 4, 2], \
    [7, 1, 4, 8, 2, 2, 1, 1, 5, 4, 0, 2], \
    [5, 5, 3, 4, 5, 6, 8, 4, 4, 2, 2, 0]]
    problem = TspProblem(len(distances), distances)
    result = hill_climbing_random_restarts(problem,
                                           restarts_limit=200,
                                           viewer=ConsoleViewer())
    #result = hill_climbing_random_restarts(problem, restarts_limit=200)
    print result.state
    #print result.path()