Ejemplo n.º 1
0
 def scramble_cube(self, n_moves=1000):
     move_list = []
     move_string = ''
     move_formula = pc.Formula(move_string)
     while (len(move_list) < n_moves):
         move = self.random_move()
         move_string = move_string + ' ' + move
         move_formula = pc.Formula(move_string).optimise()
         move_list = move_formula.__repr__().split(" ")
     output_moves = copy.deepcopy(move_formula)
     solution = move_formula.reverse()
     return output_moves, solution
Ejemplo n.º 2
0
def cubeSolve(moves):
    count = 0
    space = " "
    cube = pc.Cube()
    cube(random_alg)

    #First solve the Bottom face
    if count == 0:
        face = 'D'
        solvedFace = solved.get_face(face)
        tempMoves = list(moves)
        for i in range(len(moves)):
            move = tempMoves.pop(0)
            count = 0
            my_formula = pc.Formula(move)
            cube(my_formula)
            cubeFace = cube.get_face(face)
            for i in range(0, 3):
                for y in range(0, 3):
                    if (cubeFace[i][y] == solvedFace[i][y]):
                        count += 1

            if count >= 9:
                print(fCount)
                count += 9 + len(tempMoves)
                break
    #If bottom face is solved solve the lower parts of the surrounding faces
    if count >= 9:
        faceLoop = ['D', 'F', 'R', 'B', 'L']

        rMoves = len(tempMoves)

        for i in range(rMoves):
            move = tempMoves.pop(0)
            fCount = 0
            my_formula = pc.Formula(move)
            cube(my_formula)
            for face in faces:
                solvedFace = solved.get_face(face)
                cubeFace = cube.get_face(face)
                for i in range(0, 3):
                    for y in range(0, 3):
                        if (cubeFace[i][y] == solvedFace[i][y]):
                            fCount += 1
            if fCount >= 33:
                count += 33
                break
    if (count == 0):
        count = howClose(moves) % 3
    return count
def generate_game(max_moves=max_moves):
    # generate a single game with max number of permutations number_moves

    mycube = pc.Cube()

    global possible_moves
    formula = []
    cube_original = cube2np(mycube)
    number_moves = max_moves  # randint(3,max_moves)
    for j in range(number_moves):
        formula.append(possible_moves[randint(0, len(possible_moves) - 1)])

    # my_formula = pc.Formula("R U R' U' D' R' F R2 U' D D R' U' R U R' D' F'")

    my_formula = pc.Formula(formula)

    # print(my_formula)

    mycube = mycube((my_formula))
    # use this instead if you want it in OG data type

    cube_scrambled = mycube.copy()

    solution = my_formula.reverse()

    # print(mycube)

    return cube_scrambled, solution
Ejemplo n.º 4
0
def generate_game(max_moves=6):

    # generate a single game with max number of permutations number_moves

    mycube = pc.Cube()

    global possible_moves
    formula = []
    cube_original = cube2np(mycube)
    number_moves = max_moves  #randint(3,max_moves)

    action = randint(0, len(possible_moves) - 1)
    for j in range(number_moves):
        formula.append(possible_moves[action])
        new_action = randint(0, len(possible_moves) - 4)
        delta = action % 3
        action_face = action - delta
        if new_action >= action_face:
            new_action += 3
        action = new_action

    #my_formula = pc.Formula("R U R' U' D' R' F R2 U' D D R' U' R U R' D' F'")

    my_formula = pc.Formula(formula)

    mycube = mycube((my_formula))
    # use this instead if you want it in OG data type

    cube_scrambled = mycube

    solution = my_formula.reverse()

    #print(mycube)

    return cube_scrambled, formula, solution
Ejemplo n.º 5
0
def gen_sequence_plus_1(n_steps=6):
    cube = pc.Cube()

    transformation = [
        choice(list(action_map_small.keys())) for _ in range(n_steps - 1)
    ]

    my_formula = pc.Formula(transformation)

    cube(my_formula)

    my_formula.reverse()

    cubes = []
    distance_to_solved = []

    for i, s in enumerate(my_formula):
        cubes.append(cube.copy())
        cube(s.name)
        distance_to_solved.append(n_steps - i - 1)

    cubes.append(pc.Cube())
    distance_to_solved.append(0)

    return cubes, distance_to_solved
Ejemplo n.º 6
0
def test_for_basic_ability_to_solve():
    c = pc.Cube()
    alg = pc.Formula()
    random_alg = alg.random()
    c(random_alg)
    solver = CFOPSolver(c)
    solver.solve()
Ejemplo n.º 7
0
def gen_sample(max_steps=6):
    n_steps = randrange(max_steps + 1)
    cube = pc.Cube()

    transformation = [choice(list(action_map.keys())) for _ in range(n_steps)]
    my_formula = pc.Formula(transformation)
    cube(my_formula)
    return cube
Ejemplo n.º 8
0
    def robot_turn(self, cube, formula):
        y_next = {"L": "F", "F": "R", "R": "B", "B": "L", "U": "U", "D": "D"}

        new_formula = pc.Formula()
        for i in formula:
            new_formula += i.set_face(y_next[i.face])

        return cube("y'"), new_formula
Ejemplo n.º 9
0
def scramble():
    cube = pc.Cube()
    actions = []
    for i in range(3):
        actions.append(r.choice(list(action_map.keys())))
    formula = pc.Formula(actions)
    cube(formula)
    return cube, formula
Ejemplo n.º 10
0
    def calculate_solve(self, part='ALL'):
        if type(part != str):
            return 1
        part = part.upper()

        if part == 'ALL': # Solve the entire cube
            formula = pycuber.Formula(self.all_moves)
            formula.reverse()
            return str(formula)
Ejemplo n.º 11
0
    def kociemba(self, cube):
        base = os.path.dirname(os.path.realpath(__file__))
        executable = os.path.join(base, "kociemba")
        cachepath = os.path.join(base, "cache")

        # execute arm binary on arm
        if platform.machine() == "armv7l":
            executable += "-armv7l"

        # get color map of current cube as kociemba expects the center
        # pieces to be in the right position
        cmap = {}
        for i in list("UDLRBF"):
            cmap[cube.get_face(i)[1][1].colour] = i

        # check if the executable really is executable
        # as the file came from a zip during installation it
        # may not have the executable flag set
        st = os.stat(executable)
        if not (st.st_mode & stat.S_IEXEC):
            os.chmod(executable, st.st_mode | stat.S_IEXEC)

        # get cube string
        cube_str = self.dump_cube(cube, cmap)

        # run external kociemba program
        try:
            proc = subprocess.Popen([executable, cachepath, cube_str],
                                    stdout=subprocess.PIPE,
                                    stderr=subprocess.PIPE)
            response = proc.communicate()
            response_stdout = response[0].decode('UTF-8')

            if proc.returncode != 0:
                print("Program returned an error code", proc.returncode)
                print("Response: ", response_stdout)
                return None

        except OSError as e:
            if e.errno == errno.ENOENT:
                print(("Unable to locate program %s" % executable))
            else:
                print(("Error occured \"%s\"" % str(e)))
            return None

        except ValueError as e:
            print("Value error occured. Check your parameters.")
            return None

        if response_stdout != "Unsolvable cube!\n":
            return pc.Formula(response_stdout)

        return None
Ejemplo n.º 12
0
 def test_solver(self):
     cube = pycuber.Cube()
     initial_cube = str(cube)
     alg = pycuber.Formula()
     random_alg = alg.random()
     cube(random_alg)
     assert initial_cube != str(cube), "Randomization haven't worked."
     solution = solve_fast(cube)
     print(solution)
     for step in solution.split(" "):
         cube.perform_step(step)
     assert initial_cube == str(cube), "Fast solution doesn't work"
Ejemplo n.º 13
0
def generate_game(max_moves=10):
    # generate a single game with max number of permutations number_moves
    mycube = pc.Cube()
    global possible_moves
    formula = []
    number_moves = max_moves  #randint(3,max_moves)
    for j in range(number_moves):
        formula.append(possible_moves[randint(0, len(possible_moves) - 1)])
    my_formula = pc.Formula(formula)
    mycube = mycube((my_formula))
    cube_scrambled = mycube.copy()
    return cube_scrambled
Ejemplo n.º 14
0
    def step(self, action):
        lookup = [
            "R", "L", "D", "U", "B", "F", "R'", "L'", "D'", "U'", "B'", "F'"
        ]  #We are not accounting for half turns

        tcube = self.cube.copy()

        step_taken = pc.Formula(lookup[action])

        self.cube(step_taken)

        rwd, over = self.reward(tcube)

        return utils.flatten_1d_b(self.cube), rwd, over
Ejemplo n.º 15
0
    def reset(self, max_scrambles):
        self.cube = pc.Cube()
        alg = pc.Formula()
        #Random arrangement
        random_alg = alg.random()

        if max_scrambles == None:
            pass
        else:
            max_scrambles = np.random.choice(list(range(max_scrambles)))
            random_alg = random_alg[:max_scrambles]
        self.cube(random_alg)
        # print(utils.perc_solved_cube(self.cube)*100)
        return utils.flatten_1d_b(self.cube)  #return states
Ejemplo n.º 16
0
        def turn_2s_into_2_moves(formula):
            out_list = []
            for move in formula:
                str_move = str(move)
                if (("2" in str_move) & (len(str_move) == 2)):
                    out_move = str_move[0]
                    out_list.append(out_move)
                elif (("2" in str_move) & (len(str_move) == 3)):
                    out_move = str_move[0] + str_move[-1]
                    out_list.append(out_move)
                else:
                    out_move = str_move
                out_list.append(out_move)

            return pc.Formula(out_list)
Ejemplo n.º 17
0
def howClose(moves):
    count = 0
    space = " "
    string = space.join(moves)
    my_formula = pc.Formula(string)
    cube = pc.Cube()
    cube(random_alg)
    cube(my_formula)
    for face in faces:
        solvedFace = solved.get_face(face)
        cubeFace = cube.get_face(face)
        for i in range(0, 3):
            for y in range(0, 3):
                if (cubeFace[i][y] == solvedFace[i][y]):
                    count = count + 1
    return count
Ejemplo n.º 18
0
def generate_sequence(prob=100, reward={}):
    # prob is the probability that we will solve the cube by reversing the actions which scrambled it
    # prob is 100 by default
    scrambled_cube = pc.Cube()
    actions = []
    states_cube_list = []
    value_list = []
    # The following lines scrambles the cubes using 3 actions
    for i in range(3):
        actions.append(r.choice(list(action_map.keys())))
    formula = pc.Formula(actions)
    scrambled_cube(formula)
    # The following loop tries to solve the scrambled cube 10 times
    for i in range(10):
        # cube is a copy of the scrambled_cube
        # the scrambled state is being kept in scrambled_cube while cube is being solved
        cube = scrambled_cube.copy()
        total_steps = 0
        random_number = r.randint(0, 100)
        if random_number <= prob:
            # The following code solves the cube by reversing the actions that it was scrambled with
            formula.reverse()
            for k, move in enumerate(formula):
                states_cube_list.append(cube.copy())
                cube(move)
                total_steps += 1
        else:
            while total_steps < 6 and cube_completeness(cube) < 1:
                best_move = list(action_map.keys())
                max_value = 0
                for move in action_map.keys():
                    init_cube = cube.copy()
                    init_cube(move)
                    if flatten_string(init_cube) in reward:
                        if reward[flatten_string(init_cube)] > max_value:
                            best_move = [move]
                            max_value = reward[flatten_string(init_cube)]
                        elif reward[flatten_string(init_cube)] > max_value:
                            best_move.append(move)
                states_cube_list.append(cube.copy())
                cube(r.choice(best_move))
                total_steps += 1
        final_reward = 100 * (cube_completeness(cube) == 1) - 5 * total_steps
        for step, state in enumerate(states_cube_list):
            value = final_reward * math.pow(0.9, step + 1)
            value_list.append(value)
    return states_cube_list, value_list
Ejemplo n.º 19
0
    def get_best_move(self,
                      model,
                      last_move,
                      noise=None,
                      return_cubes=False,
                      return_moves=False):
        moves = [
            'F', 'U', 'R', 'D', 'L', 'B', 'F\'', 'U\'', 'R\'', 'D\'', 'L\'',
            'B\''
        ]

        if (last_move is not None):
            reverse_last_move = pc.Formula(last_move).reverse().__str__()
            moves.remove(reverse_last_move)

        predictions = []
        cubes = []
        for move in moves:
            new_cube = self.copy()
            new_cube(move)
            cubes.append(new_cube)
            predictions.append(model.predict_score(new_cube))

        if (noise):
            avg_prediction = int(np.floor(np.mean(predictions)))
            if (avg_prediction >= len(noise)):
                sum_noise = noise[-1]
            else:
                sum_noise = noise[avg_prediction]
            predictions = [
                p + np.random.normal(0, sum_noise) for p in predictions
            ]

        predictions_dict = dict(zip(moves, predictions))

        out_array = [moves[np.argmin(predictions)], predictions_dict]
        if (return_cubes): out_array.append(cubes)
        if (return_moves): out_array.append(moves)
        return out_array
Ejemplo n.º 20
0
    def __init__(self, n_moves=100):
        def get_game_states(move_formula, solve_formula):
            cube = Cube()
            cube(move_formula)

            game_states = []
            for move in solve_formula:
                cube(move)
                game_state = cube.copy()
                game_states.append(game_state)

            return game_states

        def turn_2s_into_2_moves(formula):
            out_list = []
            for move in formula:
                str_move = str(move)
                if (("2" in str_move) & (len(str_move) == 2)):
                    out_move = str_move[0]
                    out_list.append(out_move)
                elif (("2" in str_move) & (len(str_move) == 3)):
                    out_move = str_move[0] + str_move[-1]
                    out_list.append(out_move)
                else:
                    out_move = str_move
                out_list.append(out_move)

            return pc.Formula(out_list)

        moves = [
            'F', 'U', 'R', 'D', 'L', 'B', 'F\'', 'U\'', 'R\'', 'D\'', 'L\'',
            'B\''
        ]
        move_list = np.random.choice(moves, n_moves)
        move_formula = pc.Formula(" ".join(move_list)).optimise()
        move_formula = turn_2s_into_2_moves(move_formula)
        self.solve_formula = copy.copy(move_formula)
        self.solve_formula.reverse()
        self.game_states = get_game_states(move_formula, self.solve_formula)
Ejemplo n.º 21
0
        def get_new_sets(self, model, last_set):
            base_formula = last_set['Formula']

            if (base_formula.__str__() == '[]'):
                last_move = last_set['Formula'][-1].__str__()
                base_formula = base_formula[0]
                last_move = None
            else:
                last_move = base_formula[-1]

            _, prediction_dict, cubes, moves = self.get_best_move(
                model, last_move, return_cubes=True, return_moves=True)

            formulas = [
                pc.Formula(base_formula.__str__() + ' ' + move)
                for move in moves
            ]
            predictions = [prediction_dict[move] for move in moves]

            out_sets = np.array(zip(formulas, cubes, predictions),
                                dtype=last_set.dtype)
            return out_sets
Ejemplo n.º 22
0
def gen_sample(n_steps=6):
    cube = pc.Cube()

    transformation = [choice(list(action_map.keys())) for _ in range(n_steps)]

    my_formula = pc.Formula(transformation)

    cube(my_formula)

    my_formula.reverse()

    sample_X = []
    sample_Y = []
    cubes = []

    for s in my_formula:
        sample_X.append(flatted_1d(cube))
        sample_Y.append(action_map[s.name])
        cubes.append(cube.copy())
        cube(s.name)

    return sample_X, sample_Y, cubes
Ejemplo n.º 23
0
def generate_sample(steps=3):
    # this method generates samples of a cube that is randomly scrambled for a number of steps, default 3 steps
    # returns a list of the state, flattened state, action, and distance from solved for the cube at each step
    cube = pc.Cube()
    actions = []
    for i in range(steps):
        actions.append(choice(list(action_map.keys())))
    formula = pc.Formula(actions)
    cube(formula)
    formula.reverse()

    actions_list = []
    states_cube_list = []
    states_1d_list = []
    distance_list = []
    i = 0
    for s in formula:
        actions_list.append(s)
        states_cube_list.append(cube.copy())
        distance_list.append(steps - i)
        cube(s)
        i += 1
    return actions_list, states_cube_list, distance_list
Ejemplo n.º 24
0
def gen_sample_2(move_list, n_steps=6):
    cube = pc.Cube()
    transformation = []
    for act in move_list:
        transformation.append(new_action__per_number[act])
    # transformation = [choice(list(action_map.keys())) for _ in range(n_steps)]
    print(transformation)
    my_formula = pc.Formula(transformation)

    cube(my_formula)

    my_formula.reverse()

    sample_X = []
    sample_Y = []
    cubes = []

    for s in my_formula:
        sample_X.append(flatten_1d_b(cube))
        sample_Y.append(action_map[s.name])
        cubes.append(cube.copy())
        cube(s.name)

    return sample_X, sample_Y, cubes
Ejemplo n.º 25
0
    def solve_search(self, model, max_iter=100, show=False):
        def get_new_sets(self, model, last_set):
            base_formula = last_set['Formula']

            if (base_formula.__str__() == '[]'):
                last_move = last_set['Formula'][-1].__str__()
                base_formula = base_formula[0]
                last_move = None
            else:
                last_move = base_formula[-1]

            _, prediction_dict, cubes, moves = self.get_best_move(
                model, last_move, return_cubes=True, return_moves=True)

            formulas = [
                pc.Formula(base_formula.__str__() + ' ' + move)
                for move in moves
            ]
            predictions = [prediction_dict[move] for move in moves]

            out_sets = np.array(zip(formulas, cubes, predictions),
                                dtype=last_set.dtype)
            return out_sets

        def prune_set(self, model, new_sets, alpha=4):
            cube_prediction = model.predict_score(self)
            out_sets = new_sets[new_sets['Prediction'] < (cube_prediction +
                                                          alpha)]
            return out_sets

        def get_minimum_state(saved_states):
            index = np.argmin(saved_states['Prediction'])
            out_state = saved_states[index]
            return out_state, index

        def stuck_in_loop(current_state):
            f = current_state['Formula']
            if (len(f) < 3): return False
            elif (f[-1] == f[-2] == f[-3]): return True
            else: return False

        original_cube = self.copy()
        saved_states = np.empty(0,
                                dtype=[('Formula', object), ('Cube', object),
                                       ('Prediction', 'f8')])
        last_set = np.array([(pc.Formula(), self.copy(), 100)],
                            dtype=saved_states.dtype)
        current_state = last_set

        for _ in range(max_iter + 1):
            if (self.is_completed()): break
            if ((_ > 0) & (saved_states.size == 0)): break
            new_sets = get_new_sets(self, model, last_set)
            pruned_set = prune_set(self, model, new_sets)
            if (pruned_set.size > 0):
                saved_states = np.append(saved_states, pruned_set)
            current_state, current_state_index = get_minimum_state(
                saved_states)
            saved_states = np.delete(saved_states, current_state_index)
            if (stuck_in_loop(current_state)):
                current_state, current_state_index = get_minimum_state(
                    saved_states)
                saved_states = np.delete(saved_states, current_state_index)
            self = current_state['Cube'].copy()
            last_set = current_state
            current_state

        return original_cube, self, _, current_state['Formula']
Ejemplo n.º 26
0
    
    cube = pc.Cube()
    
    totalScore = 0
    
    # Load the model
    saver.restore(sess, "./models/model.ckpt")
    # saver.restore(sess, "./best_model/model.ckpt")

    # while(1):
    print("New Episode")
    saa = int(input("Shuffle : ") )

    cube = pc.Cube()
    transformation = [choice(list(action_map_small.keys())) for z in range(saa)]
    my_formula = pc.Formula(transformation)
    cube(my_formula)

    run = True
    print("********************************************************")
    print("START : ")
    

    print([cube])
    print("********************************************************")
    time.sleep(3)

    while run:            

        if perc_solved_cube(cube) == 1:
            run = False
Ejemplo n.º 27
0
def test_inverse():
    # test to make sure they invert correctly based off of hand inverted algs

    for i, alg in enumerate(orig_algs):
        plausible = pc.Formula(alg).reverse()
        assert str(plausible) == inverted_algs[i]
Ejemplo n.º 28
0
    global line3
    line1, = ax.plot([0, .18], [0, 54], 'r.')
    line2, = ax.plot([0, .18], [0, 54], 'go')
    line3, = ax.plot([0, .18], [0, 54], 'b.')

    if len(sys.argv) < 4:
        print("Must include 'numGens popSize numberOfMoves'")
        exit()
    elif int(sys.argv[2]) < 2 or int(sys.argv[2]) % 2 != 0:
        print("Pop size must be 2 or greater and even")
        exit()
    elif int(sys.argv[3]) < 1:
        print("numAllowedMoves must be 1 or more")
        exit()

    alg = pc.Formula()
    random_alg = alg.random()


#Converts moves to a decimal fraction, used for plotting and sharing
def moves2dec(movesCube):
    fraction = "0."
    for move in movesCube:
        index = moves.index(move)
        if (index < 10):
            fraction += "0" + str(index)
        else:
            fraction += str(index)
    return float(fraction)

Ejemplo n.º 29
0
def test_double_inverting():
    # two inverts successive should revert back to the original algorithm
    for alg in orig_algs:
        assert alg == str(pc.Formula(alg).reverse().reverse())
Ejemplo n.º 30
0
def scramble_cube(mycube):
    algo = pc.Formula()
    random_alg = algo.random()
    return mycube(random_alg), random_alg