def recursive_backtrack_algorithm(assignment, sudoku):

    # if assignment is complete then return assignment
    if len(assignment) == len(sudoku.cells):
        return assignment

    # var = select-unassigned-variables(csp)
    cell = select_unassigned_variable(assignment, sudoku)

    # for each value in order-domain-values(csp, var)
    for value in order_domain_values(sudoku, cell):

        # if value is consistent with assignment
        if is_consistent(sudoku, assignment, cell, value):

            # add {cell = value} to assignment
            assign(sudoku, cell, value, assignment)

            # result = backtrack(assignment, csp)
            result = recursive_backtrack_algorithm(assignment, sudoku)

            # if result is not a failure return result
            if result:
                return result

            # remove {cell = value} from assignment
            unassign(sudoku, cell, assignment)

    # return failure
    return False
Ejemplo n.º 2
0
    def hmc(self, xs, ys, hparams):
        """ Perform one iteration of HMC. 

        Iterate through leapfrog iterations, THEN through weights. Don't do it
        in reverse, because one weight change affects the subsequent gradients.

        Parameters
        ----------
        xs, ys: [np.array, np.array]
            A minibatch of data and labels, respectively.
        
        Returns
        -------
        A dictionary containing statistics about this HMC iteration.
        """
        L = self.args.num_leapfrog
        eps = self.args.leapfrog_step
        hparams = np.array(hparams)
        feed_l = {self.x_BO: xs, self.y_targ_B: ys, self.hparams: hparams}

        # For now q_old, p_old, q_new, p_new, weights, grads are synchronized lists.
        weights = self.sess.run(self.weights)
        pos_old = []  # Old Position
        mom_old = []  # Old Momentum
        for w in weights:
            pos_old.append(np.copy(w))
            mom_old.append(np.random.normal(size=w.shape))
        pos_new = copy.deepcopy(pos_old)
        mom_new = copy.deepcopy(mom_old)
        assert len(weights) == len(pos_old) == len(mom_old) == len(pos_new) \
                == len(mom_new) == len(hparams)

        # Run leapfrog. Half momentum, full position, half momentum.
        grads_wrt_U = self.sess.run(self.U_grads, feed_l)

        for ll in range(L):
            for (idx, grad) in enumerate(grads_wrt_U):
                mom_new[idx] += -(0.5 * eps) * grad
                pos_new[idx] += eps * mom_new[idx]

            # Get new gradients.
            U.assign(self.sess, self.update_wts_op, self.new_weights_v,
                     pos_new)
            grads_wrt_U = self.sess.run(self.U_grads, feed_l)

            for (idx, grad) in enumerate(grads_wrt_U):
                mom_new[idx] += -(0.5 * eps) * grad

        # Negate momentum. Not actually necessary w/our kinetic energy, I think.
        mom_new = [-m for m in mom_new]

        # Run the Metropolis test using whatever method.
        return self.mhtest.test(hparams, mom_old, mom_new, pos_old, pos_new)
Ejemplo n.º 3
0
    def test(self, hparams, mom_old, mom_new, pos_old, pos_new):
        """
        As this is the normal MH test, we must iterate through the entire
        dataset when computing the potential energy U(theta_old) and
        U(theta_new).
        """
        K_old, K_new = self._kinetic_energy(mom_old, mom_new)

        U_new = self.sess.run(self.neg_logprior, {self.hparams: hparams})
        for ii in range(self.num_train_mbs):
            xs = self.data_mb_list['X_train'][ii]
            ys = self.data_mb_list['y_train'][ii]
            feed = {self.x_BO: xs, self.y_targ_B: ys, self.hparams: hparams}
            U_new -= self.sess.run(self.logprob_sum, feed)

        # Now do U(theta_old). Assign theta_old weights.
        U.assign(self.sess, self.update_wts_op, self.new_weights_v, pos_old)

        U_old = self.sess.run(self.neg_logprior, {self.hparams: hparams})
        for ii in range(self.num_train_mbs):
            xs = self.data_mb_list['X_train'][ii]
            ys = self.data_mb_list['y_train'][ii]
            feed = {self.x_BO: xs, self.y_targ_B: ys, self.hparams: hparams}
            U_old -= self.sess.run(self.logprob_sum, feed)

        # Collect information.
        H_old = U_old + K_old
        H_new = U_new + K_new
        test_stat = -H_new + H_old

        if (np.log(np.random.random()) < test_stat):
            U.assign(self.sess, self.update_wts_op, self.new_weights_v,
                     pos_new)
            accept = 1
        else:
            accept = 0
        # print(H_old,H_new,accept)

        info = {
            'accept': accept,
            'K_old': K_old,
            'K_new': K_new,
            'U_old': U_old,
            'U_new': U_new,
            'H_old': H_old,
            'H_new': H_new
        }
        return info
def others_can_corner_me(data, myhead, thishead):
    #moves[a]
    if thishead != myhead:
        moves = assign(thishead)
        for a in range(4):
            if tryCorner([myhead], thishead, moves[a], data):
                #print(f"THISHEAD {thishead}\nMYHEAD {myhead}")
                #if onlyOneWayToGo(data, myhead, False):
                return True
    return False
def other_can_trap(data, myhead, thisHead):
    moves = assign(thisHead)
    worst_scenario = 999999999
    for a in range(4):
        bodies = getBodies(data)
        bodies.append(moves[a])
        #first_time = getPossibleMoves(bodies, dict_moves[a], data, mybody)
        thismove = getPossibleMoves(bodies, myhead, data, data['you']['body'])
        if thismove < worst_scenario and thismove > 0:
            #print('THIS MOVE', thismove)
            worst_scenario = thismove
    if worst_scenario < len(data['you']['body']) / 2:
        return -40
    else:
        return 10
Ejemplo n.º 6
0
from coloc.cafeh import CAFEH
import pickle
from utils import assign

# load model
cafeh = CAFEH(**pickle.load(open(snakemake.input.model, 'rb')), K=20)
# load data
assign(cafeh, pickle.load(open(snakemake.input.data, 'rb')))

# generate credible sets
cs, p = cafeh.get_credible_sets()

def best_move(data, scores):
    moves = ['up', 'down', 'left', 'right']
    dict_moves = assign(data['you']['head'])
    points_moves = [150, 150, 150, 150]
    #print('DICT MOVES:', dict_moves)
    bodies = getBodies(data)
    heads = getHeads(data)
    myhead = data['you']['head']
    mybody = data['you']['body']
    #mytail = data['you']['body'][len(data['you']['body']) - 1]
    food = data['board']['food']
    health = data['you']['health']
    height = data['board']['height']
    width = data['board']['width']
    snakes = data['board']['snakes']
    center = {'x': round(width / 2), 'y': round(height / 2)}
    small_heads = smaller_snakes_get_heads(data)
    indv_bodies = indvBodies(data)
    head_areas = areas_near_heads(small_heads, indv_bodies, mybody, myhead)
    danger_heads = get_dangerous_heads(data)
    me_smallest = 0
    for snake in snakes:
        if len(snake['body']) >= len(mybody):
            me_smallest += 1
    if me_smallest == len(snakes):
        me_smallest = 2
    else:
        me_smallest = 1 / 3
    #print('AM I THE SMALLEST?', me_smallest)
    best_move_for_space = None
    num_best_move_space = 0
    for trymoves in dict_moves:
        thismoves = getPossibleMoves(bodies, trymoves, data, mybody)
        if thismoves > num_best_move_space:
            num_best_move_space = thismoves
            best_move_for_space = trymoves
    #print(num_best_move_space)
    for a in range(4):
        if dict_moves[a] in bodies or not -1 < dict_moves[a][
                'x'] < width or not -1 < dict_moves[a]['y'] < height:
            points_moves[a] -= scores[0]  #350
        print('MOVESCORE FOR ' + moves[a] + ' SO FAR: ' + str(points_moves[a]))
        if safe(dict_moves[a], heads, indv_bodies, myhead, mybody) == []:

            first_time = getPossibleMoves(bodies, dict_moves[a], data, mybody,
                                          num_best_move_space <= len(mybody))

            popthese = []
            body_copy = []
            bodies_copy = []
            for minibody in mybody:
                body_copy.append(minibody)
            for hh in bodies:
                bodies_copy.append(hh)
            for h in range(first_time):
                try:
                    popthese.append(body_copy[len(body_copy) - 1])
                    body_copy.pop(len(body_copy) - 1)
                except:
                    pass
            for elem in popthese:
                if elem in bodies_copy:
                    bodies_copy.pop(bodies_copy.index(elem))
            #move_count = getPossibleMoves(bodies_copy, dict_moves[a], data, body_copy, num_best_move_space <= len(mybody), True)
            points_moves[a] += (first_time - len(mybody) * scores[1])  #1.5
            print("MOVES AVAILABLE FOR MOVE", moves[a], ': ' + str(first_time))
            #print('MOVES INTERPRETTED AS:', (move_count - len(mybody)*scores[1]))

            points_moves[a] -= scores[2]
        else:
            points_moves[a] -= 200  #70
            #print(moves[a], "IS NOT SAFE!!!!!")
        print('MOVESCORE FOR', moves[a], 'SO FAR:', points_moves[a])
        food_runtime = 0
        if me_smallest == 2 or health < 46:
            for foodcoord in food:
                if i_am_closest(heads, dict_moves[a], foodcoord):

                    if foodcoord == dict_moves[a]:
                        print('  RIGHT ON TOP OF FOOD!')
                        points_moves[a] += 50
                    elif distance_between(foodcoord, dict_moves[a]) == 1:
                        points_moves[a] += 40
                    else:
                        points_moves[a] += 5
                    food_runtime += 1
            if food_runtime == 0:
                points_moves[a] -= len(food) * 3
            print('FOODSCORE!!! FOR', moves[a], 'SO FAR:', points_moves[a])
        #print('TRYING TO CLONK A HEAD...')
        #points_moves[a] += scores[4] + 30 #60
        #print("SMALL HEADS LENGTH:", len(head_areas))
        if me_smallest != 2:
            for smallhead in heads:
                avg = (width + height) / 2
                points_moves[a] += (
                    (2 * avg) -
                    (distance_between(dict_moves[a], smallhead))) * 2.5
                #print('FOR MOVE:', moves[a] + ", THE DISTANCE TO THIS HEAD IS", distance_between(dict_moves[a], myhead))
        else:
            for smallhead in small_heads:
                avg = (width + height) / 2
                points_moves[a] += (2 * avg) - (distance_between(
                    dict_moves[a], smallhead)) * 2.5
                #print('FOR MOVE:', moves[a] + ", THE DISTANCE TO THIS HEAD IS", distance_between(dict_moves[a], myhead))
        i_can_corner = False
        if tryCorner(heads, myhead, dict_moves[a], data):
            points_moves[a] += scores[5] + 25  #60
            print('MOVE:', moves[a], '........GET CORNERED HA YOU THOUGHT')
            i_can_corner = True
        if dict_moves[a] in head_areas:
            print('ON MOVE', moves[a], "I CAN (probably) HIT A HEAD!")
            #60
            points_moves[a] += scores[6] + (
                10 - distance_between(myhead, center)) * 1.2
        for snakehead in snakes:
            if not i_can_corner:
                if others_can_corner_me(
                        data, dict_moves[a],
                        snakehead['head']) and not snakehead['head'] == myhead:
                    print('ON MOVE', moves[a], 'I MIGHT GET CORNERED')
                    points_moves[a] -= scores[7]  #70
            if can_trap(data, heads, dict_moves[a]):
                points_moves[a] += scores[8]  #55
            if other_can_trap(data, dict_moves[a],
                              snakehead['head']) <= len(mybody):
                points_moves[a] -= 70

        for danger in danger_heads:
            if distance_between(danger, myhead) * 2 <= 4.5:
                #swcores[9] = 2.5
                points_moves[a] += distance_between(danger, myhead) * scores[9]
            else:
                points_moves[a] += scores[9] + 3

        if num_best_move_space <= len(mybody) / 2:
            print('STATUS: TRAPPED\nTRYING TO CONSERVE SPACE...')
            if dict_moves[a] == best_move_for_space:
                points_moves[a] += scores[10]  #60

    print('MOVESCORES:', points_moves)
    print('MOVES:', moves)
    print(
        f"Best move is {moves[points_moves.index(max(points_moves))]} with a score of {max(points_moves)}"
    )
    return moves[points_moves.index(max(points_moves))]
Ejemplo n.º 8
0
    def reduce(self):

        sop = []
        combined = {}  # used for redundant group removal
        combos = self.combos
        m = self.kmap  # copying the expression to a smaller variable name for readibility

        ####################################
        ###### 2 Variable Karnaugh Map #####
        ####################################

        if self.kmap_type == '1':

            ###### QUAD CHECK #####
            combo = combos['two']['quads']['***']
            if compare(combo, 1, m):
                sop.append('***')
                m = assign(combo, m)

            ###### PAIR CHECK ######
            for flag in [1, -1]:
                for i in range(0, 4):
                    if m[i] == 1:
                        for pair in combos['two']['pairs']:
                            if i in combos['two']['pairs'][pair]:
                                combo = combos['two']['pairs'][pair]
                                if compare(combo, flag, m):
                                    sop.append(pair)
                                    m = assign(combo, m)

            ###### LONER CHECK ######
            for flag in [1]:
                for i in range(0, 4):
                    if m[i] == 1:
                        for loner in combos['two']['loners']:
                            if i in combos['two']['loners'][loner]:
                                combo = combos['two']['loners'][loner]
                                if compare(combo, 1, m):
                                    sop.append(loner)
                                    m = assign(combo, m)

        ####################################
        ###### 3 Variable Karnaugh Map #####
        ####################################

        if self.kmap_type == '2':

            ###### OCTET CHECK #####
            combo = combos['three']['octets']['***']
            if compare(combo, 1, m):
                sop.append('***')
                m = assign(combo, m)

            ###### QUAD CHECK ######
            for flag in [1, -1]:
                for i in range(0, 8):
                    if m[i] == 1:
                        for quad in combos['three']['quads']:
                            if i in combos['three']['quads'][quad]:
                                combo = combos['three']['quads'][quad]
                                if compare(combo, flag, m):
                                    sop.append(quad)
                                    combined.update({"{}".format(quad): combo})
                                    m = assign(combo, m)

            ###### PAIR CHECK ######
            for flag in [1, -1]:
                for i in range(0, 8):
                    if m[i] == 1:
                        for pair in combos['three']['pairs']:
                            if i in combos['three']['pairs'][pair]:
                                combo = combos['three']['pairs'][pair]
                                if compare(combo, flag, m):
                                    sop.append(pair)
                                    combined.update({"{}".format(pair): combo})
                                    m = assign(combo, m)

            ###### LONER CHECK ######
            for flag in [1]:
                for i in range(0, 8):
                    if m[i] == 1:
                        for loner in combos['three']['loners']:
                            if i in combos['three']['loners'][loner]:
                                combo = combos['three']['loners'][loner]
                                if compare(combo, 1, m):
                                    sop.append(loner)
                                    combined.update(
                                        {"{}".format(loner): combo})
                                    m = assign(combo, m)

        ####################################
        ###### 4 Variable Karnaugh Map #####
        ####################################

        if self.kmap_type == '3':

            ###### OCTET CHECK ######
            for flag in [1, -1]:
                for i in range(0, 16):
                    if m[i] == 1:
                        for octet in combos['four']['octets']:
                            if i in combos['four']['octets'][octet]:
                                combo = combos['four']['octets'][octet]
                                if compare(combo, flag, m):
                                    sop.append(octet)
                                    combined.update(
                                        {"{}".format(octet): combo})
                                    m = assign(combo, m)

            ###### QUAD CHECK ######
            for flag in [1, -1]:
                for i in range(0, 16):
                    if m[i] == 1:
                        for quad in combos['four']['quads']:
                            if i in combos['four']['quads'][quad]:
                                combo = combos['four']['quads'][quad]
                                if compare(combo, flag, m):
                                    sop.append(quad)
                                    combined.update({"{}".format(quad): combo})
                                    m = assign(combo, m)

            ###### PAIR CHECK ######
            for flag in [1, -1]:
                for i in range(0, 16):
                    if m[i] == 1:
                        for pair in combos['four']['pairs']:
                            if i in combos['four']['pairs'][pair]:
                                combo = combos['four']['pairs'][pair]
                                if compare(combo, flag, m):
                                    sop.append(pair)
                                    combined.update({"{}".format(pair): combo})
                                    m = assign(combo, m)

            ###### LONER CHECK ######
            for flag in [1]:
                for i in range(0, 16):
                    if m[i] == 1:
                        for loner in combos['four']['loners']:
                            if i in combos['four']['loners'][loner]:
                                combo = combos['four']['loners'][loner]
                                if compare(combo, 1, m):
                                    sop.append(loner)
                                    combined.update(
                                        {"{}".format(loner): combo})
                                    m = assign(combo, m)

        return remove_redundant(sop, combined)