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
def __init__( self, mujoco_simulation, face_geom_names: typing.List[str], num_scramble_steps: int, ): """ Create new FaceCubeSolverGoalGenerator object :param mujoco_simulation: A SimulationInterface object for a mujoco simulation considered :param success_threshold: Dictionary of threshold levels for cube orientation and face rotation, for which we consider the cube "aligned" with the goal """ super().__init__() assert len(face_geom_names) == 6, "Only full cube can be solved" self.mujoco_simulation = mujoco_simulation self.face_geom_names = face_geom_names self.num_scramble_steps = num_scramble_steps self.goal_quat_for_face = cube_utils.face_up_quats( mujoco_simulation.sim, "cube:cube:rot", self.face_geom_names) self._reset_goal_state(pycuber.Cube())
def __init__(self): self.actions = ["R", "R'", "R2", "U", "U'", "U2", "F", "F'", "F2"] self.action_space = spaces.Discrete(len(self.actions)) self.observation_space = spaces.Box(0, 5, (6, 2, 2)) self.cube = pc.Cube() self.state = cubeto2x2(cube2np(self.cube)) self.edgereward = []
def _solve_cube_NN(self, *args): global model cube_solved = pc.Cube() cube = self._pycuber_rep moves = [] for j in range(10): cube_np = cube2np(cube) cube_np = np.reshape(cube_np, (1, 54)) p = model.predict(cube_np)[0] # move = possible_moves[np.argmax(p)] move = possible_moves[np.random.choice(len(p), size=1, p=p)[0]] moves.append(move) cube(move) if cube == cube_solved: print(j) break for j in moves: if (len(str(j)) == 1): self.rotate_face(str(j)[0]) else: if (str(j)[1] == "'"): self.rotate_face(str(j)[0], -1) #c.rotate_face(j) elif (str(j)[1] == "2"): self.rotate_face(str(j)[0]) self.rotate_face(str(j)[0])
def _reset_cube(self, *args): move_list = self.cube._move_list[:] for (face, n, layer) in move_list[::-1]: self.rotate_face(face, -n, layer, steps=3) self.cube._move_list = [] self._pycuber_rep = pc.Cube()
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
def reset(self, step=25): print('resetting') self.cube = pycuber.Cube() for i in range(step): self.step(self.action_space.sample()) self.current_step = 0 return self.get_obs()
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()
def custom(channel_id, letters, database_connection): """ Verifies and configures a cube with a sequence of characters.""" if len(letters) != SQUARES_ON_A_CUBE: return ( "You must provide " + str(SQUARES_ON_A_CUBE) + " colour characters but you have given " + str(len(letters)) + "." ) for x in range(0, SQUARES_ON_A_CUBE): if not letters[x] in COLOUR_CODES: return embolden( letters[x] ) + " is not a valid colour code. " "Please only use codes from this list: " + str( COLOUR_CODES ) colours = list(map((lambda x: COLOUR_DECODE[x]), letters)) mycube = pc.Cube(pc.array_to_cubies(colours)) solver = CFOPSolver(mycube) try: solution = solver.solve() except ValueError: return "You have input an impossible cube configuration." state = str(solution.reverse()) delete_cube(channel_id, database_connection) modify_and_draw_cube(channel_id, state, database_connection)
def turn(content): new_cubies = set() #print(content) #Create cubies for copy cude for faces in content: #print(faces) #print(content[faces]) new_dict = {} for i in range(len(faces)): #print(faces[i]) new_dict[faces[i]] = pc.Square(content[faces][faces[i]]) print(new_dict) if len(new_dict) == 1: new_cubies.add(pc.cube.Centre(**new_dict)) elif len(new_dict) == 2: new_cubies.add(pc.cube.Edge(**new_dict)) elif len(new_dict) == 3: new_cubies.add(pc.cube.Corner(**new_dict)) else: return "invalid input" new_cube = pc.Cube(new_cubies) print([new_cube]) return new_cube
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
def _solve_cube_NN(self, *args): global model print("Solve") cube_solved = pc.Cube() cube = self._pycuber_rep moves = [] for j in range(10): cube_np = cube2np(cube) #cube_np = np.reshape(cube_np,(1,18,3,1)) cube_np = np.reshape(cube_np, (1, 6, 3, 3, 6)) move = possible_moves[np.argmax(model.predict(cube_np))] moves.append(move) cube(move) if cube == cube_solved: # break for j in moves: if (len(str(j)) == 1): self.rotate_face(str(j)[0]) #clock-wise else: if (str(j)[1] == "'"): self.rotate_face(str(j)[0], -1) #anticlock-wise #c.rotate_face(j) elif (str(j)[1] == "2"): self.rotate_face(str(j)[0]) self.rotate_face(str(j)[0]) print("Solve Finish")
def test_solver(steps, solver, n_iter, time_limit, iter_limit): if IS_SEED: np.random.seed(SEED) result = { 'success': [], 'actions': [], 'time': [], 'depths': [], 'values': [], 'real actions': [] } for _ in tqdm.tqdm(range(n_iter)): solving_cube = pycuber.Cube() random_actions = np.random.choice(cube.ACTIONS, size=steps) solving_cube.perform_algo(random_actions) start_time = time.time() is_done, actions, depth, value = solver.solve(solving_cube, time_limit=time_limit, iter_limit=iter_limit) solve_time = time.time() - start_time result['success'].append(is_done) result['actions'].append(actions) result['time'].append(solve_time) result['depths'].append(depth) result['values'].append(value) result['real actions'].append(revert_actions(random_actions)) return result
def getcolors(cmd): mycube = pc.Cube() mycube(cmd) s_cube = str(mycube) s_dic = ''' [U1][U2][U3] [U4][U5][U6] [U7][U8][U9] [L1][L2][L3][F1][F2][F3][R1][R2][R3][B1][B2][B3] [L4][L5][L6][F4][F5][F6][R4][R5][R6][B4][B5][B6] [L7][L8][L9][F7][F8][F9][R7][R8][R9][B7][B8][B9] [D1][D2][D3] [D4][D5][D6] [D7][D8][D9] ''' dic = [] cube = [] def f_dic(matched): value = matched.group('value') value = value[1:-1] dic.append(value) re.sub('(?P<value>\[[A-Z]\d])', f_dic, s_dic) def f_cube(matched): value = matched.group('value') value = value[1:-1] cube.append(value) re.sub('(?P<value>\[[a-z]\])', f_cube, s_cube) final_dic = {} for i in range(54): final_dic[dic[i]] = cube[i] print(final_dic)
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
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
def train(n_moves, iterations): for _ in range(floor(iterations / 100)): print(_, flush=True, end="\r") for __ in range(100): cube = pc.Cube() cube_shuffle(cube, n_moves) for ___ in range(1): q_action(cube)
def _scramble_cube(self): """ Scramble a cube randomly at the beginning of an episode """ cube = pycuber.Cube() for i in range(self.constants.num_scramble_steps): action = self._random_state.choice(self.PYCUBER_ACTIONS) cube.perform_step(action) self.mujoco_simulation.cube_model.from_pycuber(cube)
def generate_cube(self, move_depth): # get cube and define as cube cube = pc.Cube() for action_num in cube_shuffle(move_depth): # Gen cube cube(ACTIONS[action_num]) return cube
def __init__(self, number_of_turns=0, seed=None, cube=None): assert number_of_turns == 0 or cube is None # can't provide both at the same time if cube is None: self.cube = pc.Cube() else: self.cube = cube self.__solved = self.cube.copy() if cube is None else pc.Cube() self.action_space = ["F", "B", "L", "R", "U", "D", "F'", "B'", "L'", "R'", "U'", "D'"] self.current_step = 0 if seed is not None: self.__set_seed(seed) if cube is None: self.reset(number_of_turns)
def __init__(self): self.solvedCube = pc.Cube() self.scramblingCube = pc.Cube() self.color_mapper = { "L": 0, "r": 0, "U": 0.2, "y": 0.2, "F": 0.4, "g": 0.4, "D": 0.6, "w": 0.6, "R": 0.8, "o": 0.8, "B": 1, "b": 1 } self.N = 54
def to_pycuber(self): """ Returns a list of PyCuber Cubes """ import pycuber as pc # will raise error if pycuber not installed # convert to number representation return [pc.Cube(pc.helpers.array_to_cubies([str(int(c)) for c in color_list])) for color_list in self._cube_array]
def __init__(self): self.mycube = pycuber.Cube() self.action_space = spaces.Discrete(6) # No. of face x No. of possible color self.observation_space = spaces.Tuple((spaces.Discrete(3*3*6), spaces.Discrete(6))) # LabelBinarizer to transform cube to array self.color_binarizer = LabelBinarizer() self.color_binarizer.fit(['[r]','[o]','[y]','[w]','[b]','[g]'])
def _reset(self): done = True self.edgereward = [] while done: shuffle = ' '.join(np.random.choice(self.actions, 20)) self.cube = pc.Cube() self.cube(shuffle) self.state = keep_yellow_edge(cube2np(self.cube)) done, _ = checkCross(self.state) return np.reshape(self.state, (1, 6, 3, 3))
def _reset(self): done = True self.edgereward = [] while done: shuffle = ' '.join(np.random.choice(self.actions, 6)) self.cube = pc.Cube() self.cube(shuffle) self.state = cubeto2x2(cube2np(self.cube)) done = check_finished(self.state) return self.state
def n_move_test(n_moves, test_size): correct = 0 for _ in range(test_size): test_cube = pc.Cube() cube_shuffle(test_cube, n_moves) for __ in range(n_moves): a = np.argmax(q_table[str(test_cube)]) test_cube(actions[a]) if test_cube.__ne__(SOLVED_CUBE) == False: correct += 1 return correct
def text(channel_id, database_connection): """Returns the configuration of a cube in text form.""" progress = append_movements_to_cube(channel_id, "", database_connection) mycube = pc.Cube() mycube(progress) txt = "" for i in range(0, SIDES_ON_A_CUBE): for j in range(0, SQUARES_IN_A_ROW): for k in range(0, SQUARES_IN_A_COLUMN): txt += str(mycube.get_face(SIDES[i])[j][k].colour[0]) return txt
def _solve_cube_NN(max_move, model): cube_solved = pc.Cube() cube_shuffled = generate_game(max_move) for j in range(10): cube_np = cube2np(cube_shuffled) cube_np = np.reshape(cube_np, (1, 6, 3, 3, 6)) move = possible_moves[np.argmax(model.predict(cube_np))] cube_shuffled(move) if cube_shuffled == cube_solved: return 1 return 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
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"