def test_shuffle_bayesian(): cube = Cube() game = Game(cube) game.shuffle(min_step=3, max_step=100) for step in game.shuffle_steps: bayesian.add_feature_and_decision(step.feature_string, DIRECTIONS[-step.direction + DIRECTION_OFFSET]) cube = Cube() game = Game(cube) game.shuffle(min_step=3, max_step=100) for step in game.shuffle_steps: bayesian.add_feature_and_decision(step.feature_string, DIRECTIONS[-step.direction + DIRECTION_OFFSET]) cube = Cube() game = Game(cube) game.shuffle(min_step=3, max_step=100) for step in game.shuffle_steps: bayesian.add_feature_and_decision(step.feature_string, DIRECTIONS[-step.direction + DIRECTION_OFFSET]) print_possibility() bayesian.export('bayesiantest.yaml') bayesian.load('bayesiantest.yaml') print_possibility()
def test_hash_cube(self): hash_map = dict() hash_map[ImmutableCube().change_by(Move.DOWN)] = 1 hash_map[Cube().change_by(Move.DOWN)] = 2 hash_map[ImmutableCube().change_by(Move.DOWN)] = 5 hash_map[Cube().change_by(Move.LEFT)] = 3 self.assertEqual(2, len(hash_map)) self.assertEqual(5, hash_map[Cube().change_by(Move.DOWN)])
def generate_samples(depth: int, iterations: int) -> Iterable[Sample]: def get_next_move(last_move): while True: next_move = np.random.choice(list(Move)) if next_move != last_move: return next_move for _ in range(iterations): c, last_move = Cube(), None for d in range(depth): last_move = move = get_next_move(last_move) yield Sample(Cube(c.change_by(move)), d + 1)
def _extract_path(self): current = Cube() path = [current] while self._parent[current] is not None: current = self._parent[current] path.append(current) return list(reversed(path))
def main(): # test_shuffle() # test_shuffle_elimination(directions=[F, L, L, L, L, F]) # test_shuffle_elimination(directions=[F, L, L, L, L]) # test_shuffle_elimination(directions=[L, L, L, L]) # test_shuffle_elimination(directions=[L, L, L, L, F]) # test_shuffle_elimination(directions=[F, B, L, L, L, L, L, R]) # test_shuffle_elimination(directions=[F, B, L, L_, B_]) # for i in range(0, 100000): # print i # validate_shuffle_elimination() cube = Cube() game = Game(cube) game.shuffle(min_step=3, max_step=3) game.export_to_file(file_path='./sample_file.dat') print 'Full step' game.print_shuffle_full_steps() print 'Step' game.print_shuffle_steps() with open('./sample_file.dat', 'r') as fp: is_eof = False while True: step_sample = [] for i in range(0, CUBE_DATA_LEN): data = fp.read(4) if '' == data: is_eof = True else: step_sample.append(data) if is_eof: break print create_Sample_from_buffer(step_sample)
def test_shuffle_elimination(directions): cube = Cube() game = Game(cube) game.shuffle(directions=directions) print '============= FULL STEPS ==============' game.print_shuffle_full_steps() print '============= ELIMINATED STEPS ==============' game.print_shuffle_steps()
def generate_file(file_path, data_num, min_step, max_step): with open(file_path, 'w') as fp: for i in range(0, data_num): c = Cube() game = Game(c) game.shuffle(min_step=min_step, max_step=max_step) game.export_to_file_point(fp) print '%s generate %i' % (file_path, i)
def test_shuffle(): cube = Cube() game = Game(cube) game.shuffle() step = len(game.shuffle_full_steps) print '=========== initialized with %s-step shuffle ============' % step cube.show() print '' print 'Feature string is ', cube.calculate_feature_string() print 'Is standard? ', cube.check() command = raw_input("Command: ").upper() while command != 'Q': if command not in command_map: print("Invalid input. Input again.") continue cube.transform(command_map[command]) print '=========== %s ============' % command print '' cube.show() print '' command = raw_input("Command: ").upper()
def generate_shuffle_bayesian(): for i in range(0, 10000): c = Cube() game = Game(c) game.shuffle(min_step=10, max_step=1024) for step in game.shuffle_steps: bayesian.add_feature_and_decision(step.feature_string, DIRECTIONS[-step.direction + DIRECTION_OFFSET]) if i % 100 == 0: print i bayesian.export('bayesiantest.yaml')
def validate_shuffle_elimination(): cube = Cube() game = Game(cube) game.shuffle() # print '============= FULL STEPS ==============' # game.print_shuffle_full_steps() # print '============= ELIMINATED STEPS ==============' # game.print_shuffle_steps() print 'Full steps: ', len(game.shuffle_full_steps) print 'Steps: ', len(game.shuffle_steps) directions = [-step.direction for step in game.shuffle_steps] directions.reverse() # print [DIRECTIONS[direction + DIRECTION_OFFSET] for direction in directions] game.play(directions) assert game.cube.check() print 'Validation PASS!' return True
def test_transform(): result_file = 'tmp_result.txt' benchmark_file = 'ut_result.txt' cube = Cube() with open(result_file, 'w') as result_fp: cube.show(result_fp) for command in command_list: for i in range(0, 4): result_fp.write('=========== %s ============\n' % command) cube.transform(command_list[command]) cube.show(result_fp) benchmark = open(result_file, 'U').readlines() result = open(benchmark_file, 'U').readlines() diff = unified_diff(benchmark, result, benchmark_file, result_file) print 'Diff between benchmark and result.\n' stdout.writelines(diff) print '\nTest transform done.'
def solve(self, root: Cube, timeout: Union[int, None] = None) -> Union[List[Move], None]: self._stop = threading.Event() if root.is_solved(): return [] self._initialize_tree(root) self._backup_stack = [] root = ImmutableCube(root) if timeout is not None: timer = threading.Timer(timeout, lambda: self._stop.set()) timer.daemon = True timer.start() while not self._stop.is_set(): if self._traverse_for_solved(root): return self._extract_final_sequence(root) self._backup() return None
def test_train_and_solve(): cube = Cube() game = Game(cube) game.shuffle() step = len(game.shuffle_full_steps) print '=========== initialized with %s-step shuffle ============' % step cube.show() print 'Solving . . . . . . ' game.solve() cube.show() if game.is_solved: print 'Congratulations!!!! Solved after %s steps!' % len( game.solve_steps) print( 'Steps: %s' % ''.join([ DIRECTIONS[step.direction + DIRECTION_OFFSET] for step in game.solve_steps ])) else: print 'Stupid!!!! Cannot solve a cube in %s steps!' % len( game.solve_steps)
def __init__(self, root: Cube, nodes: Set[Cube]): assert Cube() in nodes self._nodes, self._root = nodes, root
def generate_random_cube(iterations: int = 100) -> Cube: c = Cube() for _ in range(iterations): c.change_by(np.random.choice(list(Move))) return c
def test_is_initially_solved(self): self.assertTrue(Cube().is_solved())
def test_mutability(self): mut = Cube() changed = mut.change_by(Move.DOWN) self.assertFalse(mut.is_solved()) self.assertListEqual(mut.front, changed.front)
def test_get_children_of(self): cube = Cube() children = list(get_children_of(cube)) self.assertEqual(6, len(children))
def test_back_move_and_return(self): c = Cube() c.change_by(Move.BACK) self.assertFalse(c.is_solved()) c.change_by(Move.BACK_CTR) self.assertTrue(c.is_solved())
def test_scatter_and_return(self): c = Cube() c.change_by(Move.BACK) c.change_by(Move.LEFT_CTR) c.change_by(Move.DOWN) self.assertFalse(c.is_solved()) c.change_by(Move.DOWN_CTR) c.change_by(Move.LEFT) c.change_by(Move.BACK_CTR) self.assertTrue(c.is_solved())
def test_left_move_and_return(self): c = Cube() c.change_by(Move.LEFT) self.assertFalse(c.is_solved()) c.change_by(Move.LEFT_CTR) self.assertTrue(c.is_solved())
def test_down_move_and_return(self): c = Cube() c.change_by(Move.DOWN) c.change_by(Move.DOWN_CTR) self.assertTrue(c.is_solved())
def test_not_solved_after_move(self): c = Cube() c.change_by(Move.DOWN) self.assertFalse(c.is_solved())
def main(): cube = Cube() print '=========== initial ============' cube.show() print cube.calculate_feature_string() print cube.check() print '' command = raw_input("Command: ").upper() while command != 'Q': if command not in command_map: print("Invalid input. Input again.") continue cube.transform(command_map[command]) print '=========== %s ============' % command print '' cube.show() print '' command = raw_input("Command: ").upper()
def test_bayesian(): cube = Cube() cube.transform(F) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[-F + DIRECTION_OFFSET]) cube.transform(B) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[-B + DIRECTION_OFFSET]) cube.transform(-B) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[B + DIRECTION_OFFSET]) cube.transform(R) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[-R + DIRECTION_OFFSET]) cube.transform(L) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[-L + DIRECTION_OFFSET]) cube.transform(B) bayesian.add_feature_and_decision(cube.feature_string, DIRECTIONS[-B + DIRECTION_OFFSET]) print_possibility() bayesian.export('bayesiantest.yaml') bayesian.load('bayesiantest.yaml') print_possibility()
import pickle from cube.model import Cube from mcts.solver import Solver from performance.effectiveness import generate_random_cube from plotting.plotter import Plotter if __name__ == '__main__': with open('./nets/trained_net500.pkl', 'rb') as input: net = pickle.load(input) solver = Solver(net) cube = generate_random_cube(iterations=6) moves = solver.solve(cube) sequence = [Cube(cube)] + [Cube(cube.change_by(move)) for move in moves] # Plotter().save_sequence(sequence, 'demo.gif') Plotter().plot_sequence(sequence)
def _initialize_tree(self, root: Cube): self._tree = dict() policy = self._net.evaluate(root.one_hot_encode().T)[0].policy self._tree[root] = NodeInfo.create_new(policy)