def counter_double_menace(): print( '|----------------------------------------------------------------------------|' ) print(' TEST OBJECTIVE: counter the double menace\n') start_time = time() shape = (4, 5) sequence = [18, 13, 17] game = DynamicGame(grid_shape=shape) for action in sequence: game.step(action) print('Initial state: \n', game) solver = Solver(game.gameState) game.step(solver.get_action()) print('\n', game) end_time = time() assert (game.gameState.board[16] == -1) print('\n TEST SUCCESSFUL:', solver.nodes_explored, 'nodes explored in ', round(end_time - start_time, 2), 'seconds.') print( '|----------------------------------------------------------------------------|' )
def first_move(): print( '|----------------------------------------------------------------------------|' ) print(' TEST OBJECTIVE: choose the optimal first move\n') start_time = time() shape = (4, 5) game = DynamicGame(grid_shape=shape) print('\n', game) solver = Solver(game.gameState) game.step(solver.get_action()) end_time = time() assert (game.gameState.board[17] == 1) print('\n TEST SUCCESSFUL:', solver.nodes_explored, 'nodes explored in ', round(end_time - start_time, 2), 'seconds.') print( '|----------------------------------------------------------------------------|' )
def testNakedPair(self): sudoku = PuzzleFactory.createEmptySudoku() #initialize a grid that contains a naked pair sudoku.grid.setConstraintGridValue(3,1,7) sudoku.grid.setConstraintGridValue(4,1,4) sudoku.grid.setConstraintGridValue(6,2,7) sudoku.grid.setConstraintGridValue(7,2,4) sudoku.grid.setConstraintGridValue(0,3,7) sudoku.grid.setConstraintGridValue(0,4,4) # now the second and third cell must contain the possibleValues ([4,7]) as these are the only # two cells that can contain these values, they are also the only possibleValues c1_0 = sudoku.grid.getCellFromSquareGrid(1,0) c2_0 = sudoku.grid.getCellFromSquareGrid(2,0) solver = Solver(sudoku) solver.solve() print sudoku.grid self.assertEqual(c1_0.getPossibleValues(), set([4,7]), "Did not correctly identify naked pair") self.assertEqual(c2_0.getPossibleValues(), set([4,7]), "Did not correctly identify naked pair")
def update_AI(self): solver = Solver(self.env.gameState) action = solver.get_action() self.env.step(action) self.render(self.main_window) pg.display.update()
def testNakedPair(self): sudoku = PuzzleFactory.createEmptySudoku() #initialize a grid that contains a naked pair sudoku.grid.setConstraintGridValue(3, 1, 7) sudoku.grid.setConstraintGridValue(4, 1, 4) sudoku.grid.setConstraintGridValue(6, 2, 7) sudoku.grid.setConstraintGridValue(7, 2, 4) sudoku.grid.setConstraintGridValue(0, 3, 7) sudoku.grid.setConstraintGridValue(0, 4, 4) # now the second and third cell must contain the possibleValues ([4,7]) as these are the only # two cells that can contain these values, they are also the only possibleValues c1_0 = sudoku.grid.getCellFromSquareGrid(1, 0) c2_0 = sudoku.grid.getCellFromSquareGrid(2, 0) solver = Solver(sudoku) solver.solve() print sudoku.grid self.assertEqual(c1_0.getPossibleValues(), set([4, 7]), "Did not correctly identify naked pair") self.assertEqual(c2_0.getPossibleValues(), set([4, 7]), "Did not correctly identify naked pair")
def main(): parser = argparse.ArgumentParser(description='Picross solver.') parser.add_argument('picross', type=str, nargs='+', help='input file in PICROSS format') parser.add_argument('-m', dest='model', type=str, nargs='*', help='modelization method: ' + ' '.join(Model.all_models().keys()), default=['ikj']) parser.add_argument('-s', dest='solver', type=str, nargs='*', help='sat solver: ' + ' '.join(Solver.all_solvers().keys()), default=['pycosat']) parser.add_argument('-o', dest='output', type=str, help='destination GRID file', default=None) parser.add_argument('--dimacs', dest='dimacs', action='store_true', help='generate DIMACS file', default=False) parser.add_argument('--silent', dest='silent', action='store_true', help='silent mode', default=False) args = parser.parse_args() models = Model.all_models() solvers = Solver.all_solvers() utils.set_silent(args.silent) for path in args.picross: picross = Picross(path) for model in args.model: if args.dimacs: picross.save_dimacs(model=models[model]) for solver in args.solver: picross.print_solution(model=models[model], solver=solvers[solver]) picross.save_grid(model=models[model], solver=solvers[solver], output=args.output)
def positive_alignments(shape=(6, 7)): print( '|----------------------------------------------------------------------------|' ) print(' TEST OBJECTIVE: test all possible alignments in grid of', shape, 'shape') # Start with an empty board and node game = DynamicGame(shape) solver = Solver(game.gameState) node = solver.root_node # Binary values leading to the victory of the first player or second winners = [] index = np.flip(np.arange(0, node.WIDTH * (node.HEIGHT + 1), dtype=np.int64).reshape( (node.WIDTH, (node.HEIGHT + 1))), axis=1).transpose() # Vertical alignments are possible if shape[0] >= 4: for col in range(node.WIDTH): for row in range(1, node.HEIGHT - 2): winners.append( sum(map(lambda x: 2**x, index[row:row + 4, col]))) # Horizontal alignments are possible if shape[1] >= 4: for row in range(node.HEIGHT): for col in range(node.WIDTH - 3): winners.append( sum(map(lambda x: 2**x, index[row, col:col + 4]))) # Diagonal alignments are possible if shape[0] >= 4 and shape[1] >= 4: for col in range(node.WIDTH - 3): for row in range(1, node.HEIGHT - 2): indexes = [] for c in range(4): indexes.append(index[row + c, col + c]) winners.append(sum(map(lambda x: 2**x, indexes))) for col in range(node.WIDTH - 1, 2, -1): for row in range(node.HEIGHT - 3, 0, -1): indexes = [] for c in range(4): indexes.append(index[row + c, col - c]) winners.append(sum(map(lambda x: 2**x, indexes))) for winner in winners: assert (node.alignment(winner)) print('\n TEST SUCCESSFUL') print( '|----------------------------------------------------------------------------|' )
def parsePuzzle(filename): start = time() puzzle = PuzzleFactory.createEmptySudoku() # Set the initial data to work with myFile = open(filename) values = range(1, 10) stringArray = myFile.readlines() y = 0 for line in stringArray: x = 0 for el in line.split(' '): try: if (int(el) in values): puzzle.grid.setConstraintGridValue(x, y, int(el)) except ValueError: pass x += 1 y += 1 # And solve solver = Solver(puzzle) #print solver #grid.printAsSudoku() #print "Done in", int((time() - start) *1000), "ms" return puzzle, solver
def setup(args): utils.init_seeds(20) cfg = config.clone() if len(args.model_config) > 0: cfg.merge_from_file(args.model_config) opt = CfgNode(args.__dict__) cfg.merge_from_other_cfg(opt) device = torch.device(cfg.DEVICE) if torch.cuda.is_available() else torch.device('cpu') cfg.update({'DEVICE': device}) model = model_factory.create_model(cfg) dataloader = create_dataloader(cfg.DATASET.PATH, cfg, TrainAugmentation(cfg.INPUT_SIZE[0], mean=cfg.DATASET.MEAN), is_training=True)[0] test_dataloader = create_dataloader(cfg.DATASET.PATH, cfg, TestTransform(cfg.INPUT_SIZE[0], mean=cfg.DATASET.MEAN), is_training=True, split='test')[0] model.train() model.to(cfg.DEVICE) nb = len(dataloader) max_step_burn_in = max(3 * nb, 1e3) # burn-in iterations, max(3 epochs, 1k iterations) # solver = Solver(model, cfg, max_steps_burn_in=max_step_burn_in, apex=amp) solver = Solver(model, cfg) rtm3d_loss = RTM3DLoss(cfg) return model, (dataloader, test_dataloader), solver, rtm3d_loss, cfg
def parsePuzzle(self, filename): start = time() puzzle = PuzzleFactory.createFutoshikiPuzzle(7) # Set the initial data to work with myFile = open("./futoshiki.txt") values = range(1,10) stringArray = myFile.readlines() y = 0 addingValues = True for line in stringArray: if line.startswith("relativity"): addingValues = False if addingValues: x = 0 for el in line.split(' '): try: if(int(el) in values): puzzle.grid.setConstraintGridValue(x,y,int(el)) except ValueError: pass x += 1 y += 1 else: cellStrings = line.split(">") if len(cellStrings) == 2: c1, c2 = cellStrings x,y = c1.split(",") x = int(x) y = int(y) cell1 = puzzle.grid.getCellFromSquareGrid(x-1,y-1) x,y = c2.split(",") x = int(x) y = int(y) cell2 = puzzle.grid.getCellFromSquareGrid(x-1,y-1) cg = puzzle.addConstraintGroup("Relativity") constraint = cg.addConstraint(CellGreaterThanCellConstraint) cg.addCell(cell1) cg.addCell(cell2) constraint.setLesserCell(cell1) constraint.setGreaterCell(cell2) # And solve solver = Solver(puzzle) #print solver #grid.printAsSudoku() #print "Done in", int((time() - start) *1000), "ms" return puzzle, solver
def parsePuzzle(filename): start = time() #puzzle = PuzzleFactory.createExampleKakuro() # Set the initial data to work with myFile = open(filename) values = range(1, 10) stringArray = myFile.readlines() y = 0 for line in stringArray: if (line.startswith("range")): min, max = [ int(x) for x in line[line.find("=") + 1:].split(",") ] puzzle = Puzzle("Test-kakuro", range(min, max + 1)) if (line.startswith("cell")): x, y = [ int(x) for x in line[line.find("(") + 1:line.find(')')].split(",") ] puzzle.getGrid().addCell(QtCore.QPoint(x, y)) if (line.startswith("total")): value = int(line.split("=")[-1]) cells = [ cell[1:-1].split(",") for cell in line[line.find("(") + 1:line.rfind(")")].split(";") ] cg = puzzle.addConstraintGroup("Line") for cell in cells: try: c = puzzle.getGrid().searchCellWithPosition( QtCore.QPoint(int(cell[0]), int(cell[1]))) except ValueError: print line cg.addCell(c) uvc = cg.addConstraint(UniqueValueConstraint) tsvc = cg.addConstraint(TotalSumValueConstraint) tsvc.setTotalValue(value) solver = Solver(puzzle) return puzzle, solver
def double_menace(): print( '|----------------------------------------------------------------------------|' ) print(' TEST OBJECTIVE: complete the double menace\n') start_time = time() shape = (4, 5) sequence = [18, 13, 17, 12] game = DynamicGame(grid_shape=shape) for action in sequence: game.step(action) print('Initial state: \n', game) total_nodes = 0 for x in range(3): solver = Solver(game.gameState) game.step(solver.get_action()) total_nodes += solver.nodes_explored print('\n', game) end_time = time() assert (game.gameState.board[15] == 1 and game.gameState.board[16] == 1 or game.gameState.board[16] == 1 and game.gameState.board[19] == 1) print('\n TEST SUCCESSFUL:', total_nodes, ' nodes explored in ', round(end_time - start_time, 2), 'seconds.') print( '|----------------------------------------------------------------------------|' )
def save_grid(self, model=Model.MODEL_IKJ, solver=Solver.PYCOSAT_SOLVER, output=None): grid = self.solve(model, solver) if grid is None: return output = output or (self.file_path.split('.')[0] + '-' + Model.get(model).name() + '-' + Solver.get(solver).name() + '.GRID') f = open(output, 'w') for c in self.comments: f.write('{}\n'.format(c)) f.write('sol {} \n'.format(self.n)) for row in grid: f.write('{} 0\n'.format(' '.join(['#' if c else ' ' for c in row]))) f.close()
def parsePuzzle(filename): # Set the initial data to work with myFile = open("./simpleSumbrero.txt") values = range(1, 10) stringArray = myFile.readlines() y = 0 for line in stringArray: line = line.strip() # strip off whitespace if (line.startswith("range")): min, max = [ int(x) for x in line[line.find("=") + 1:].split(",") ] puzzle = Puzzle("Test-sumbrero", range(min, max + 1)) if (line.startswith("cell")): x, y = [ float(x) for x in line[line.find("(") + 1:line.find(')')].split(",") ] puzzle.getGrid().addCell(QtCore.QPoint(x, y)) if (line.startswith("column")): column, value = line.split('=') column = int(column.split('(')[1].split(')')[0]) # create a sum constraint cg = puzzle.addConstraintGroup("Column sum " + str(column)) tsvc = cg.addConstraint(TotalSumValueConstraint) uvc = cg.addConstraint(UniqueValueConstraint) for cell in puzzle.grid.cells: if (cell.position.x() == column): cg.addCell(cell) tsvc.setTotalValue(int(value)) # TODO: deal with the two different kinds of row sums solver = Solver(puzzle) return puzzle, solver
# # Create containers # recordCont = RecordContainer.Instance() # recordCont.set_db_access(dbQuery) # readCont = ReadContainer.Instance() # cdsAlnCont = CdsAlnContainer.Instance() # readCont.populate_from_aln_file(aln_file) # print "passed container initialization!" # ---------------------- Initialize Solver --------------------- # greedySolver = GreedySolver() taxonomySolver = SimpleJoinTaxonomySolver() solver = Solver(determine_host, greedySolver, taxonomySolver) # ---------------------- Run Solver --------------------- # solver.generateSolutionXML(aln_file) print "Successfully initialized solver!" # fill_containers (aln_file) # -------------------- Test stats methods ----------------------- # ''' read_container = ReadContainer.Instance() cds_aln_container = CdsAlnContainer.Instance()
def setup(gpu_idx, configs): configs.gpu_idx = gpu_idx device = torch.device('cpu' if configs.gpu_idx == -1 else 'cuda:{}'.format(configs.gpu_idx)) configs.update({'DEVICE': device}) save_dir = os.path.join(configs.TRAINING.WEIGHTS, configs.MODEL.BACKBONE) logs_dir = os.path.join(configs.TRAINING.LOGDIR, configs.MODEL.BACKBONE) if not os.path.exists(save_dir): os.mkdir(save_dir) if not os.path.exists(logs_dir): os.mkdir(logs_dir) if configs.distributed: if configs.dist_url == "env://" and configs.rank == -1: configs.rank = int(os.environ["RANK"]) if configs.multiprocessing_distributed: # For multiprocessing distributed training, rank needs to be the # global rank among all the processes configs.rank = configs.rank * configs.ngpus_per_node + gpu_idx dist.init_process_group(backend=configs.dist_backend, init_method=configs.dist_url, world_size=configs.world_size, rank=configs.rank) configs.subdivisions = int(64 / configs.BATCH_SIZE / configs.ngpus_per_node) else: configs.subdivisions = int(64 / configs.BATCH_SIZE) configs.is_master_node = (not configs.distributed) or ( configs.distributed and (configs.rank % configs.ngpus_per_node == 0)) if configs.is_master_node: logger = logging.Logger('RTM3D') logger.info('>>> Created a new logger') logger.info('>>> configs: {}'.format(configs)) tb_writer = SummaryWriter(log_dir=os.path.join(logs_dir, 'tensorboard')) else: logger = None tb_writer = None model = model_factory.create_model(configs) model.to(configs.DEVICE) checkpointer = check_point.CheckPointer(model, save_dir=save_dir, save_to_disk=True, mode='state-dict', device=configs.DEVICE) configs.start_epoch = 0 configs.min_loss = 10000 ckpt = {} if len(configs.TRAINING.CHECKPOINT_FILE) > 0: ckpt = checkpointer.load(configs.TRAINING.CHECKPOINT_FILE, use_latest=(configs.TRAINING.CHECKPOINT_MODE != 'pretrained'), load_solver=configs.SOLVER.LOAD_SOLVER) if 'epoch' in ckpt and configs.TRAINING.CHECKPOINT_MODE == 'resume': configs.start_epoch = ckpt['epoch'] + 1 if 'min_loss' in ckpt and configs.TRAINING.CHECKPOINT_MODE == 'resume': configs.min_loss = ckpt['min_loss'] # Data Parallel model = model_factory.make_data_parallel(model, configs) solver = Solver(model, configs) checkpointer.set_solver(solver) checkpointer.load_solver(ckpt) del ckpt rtm3d_loss = RTM3DLoss(configs) if configs.is_master_node: num_parameters = model_factory.get_num_parameters(model) logger.info('number of trained parameters of the model: {}'.format(num_parameters)) if logger is not None: logger.info(">>> Loading dataset & getting dataloader...") # Create dataloader train_dataloader = create_dataloader(configs.DATASET.PATH, configs, TrainAugmentation(configs.INPUT_SIZE[0], mean=configs.DATASET.MEAN), is_training=True)[:2] test_dataloader = create_dataloader(configs.DATASET.PATH, configs, TestTransform(configs.INPUT_SIZE[0], mean=configs.DATASET.MEAN), is_training=True, split='test')[0] if logger is not None: logger.info('number of batches in training set: {}'.format(len(train_dataloader))) return model, checkpointer, (train_dataloader, test_dataloader), solver, rtm3d_loss, configs, tb_writer
if (len(sys.argv) < 5): print "Solver usage: python populate_containers.py <INPUT_ALN_FILE> <DATASET_DESC_XML_FILE> <SOLUTION_XML_OUTPUT_FILE> <STATS_OUTPUT_DIRECTORY>" sys.exit(-1) aln_file = sys.argv[1] dataset_xml_file = sys.argv[2] solution_xml_output_file = sys.argv[3] stats_dir = sys.argv[4] log.info("I got the input file!") # ---------------------- Initialize Solver --------------------- # greedySolver = GreedySolver() taxonomySolver = SimpleTaxonomySolver() solver = Solver(determine_host, greedySolver, taxonomySolver) # ---------------------- Run Solver --------------------- # start_total = time.time() solver.generateSolutionXML(aln_file, dataset_xml_file, solution_xml_output_file, stats_dir) log.info("Successfully initialized solver!") end_total = time.time() elapsed_time_total = end_total - start_total print("TOTAL - \t\telapsed time: %.2f" % elapsed_time_total) # fill_containers (aln_file)
log.info("taxonomy solver: %s" % args.tax_solver) if args.tax_solver == 'simple': tax_solver = SimpleTaxonomySolver() elif args.tax_solver == 'simple_join': tax_solver = SimpleJoinTaxonomySolver() # Create database access db_access = DbQuery() tax_tree = TaxTree(args.tax_tree) host_determinator = HostDeterminator(dbquery=db_access, tax_tree=tax_tree) log.info("Started.") processing_start = timing.start() solver = Solver(host_determinator, read2cds_solver, tax_solver) # Populate read container # The read container type can now be determined from the input parameters # and injected into the Solver start = timing.start() read_container = ReadContainer() read_container.populate_from_aln_file(read_alignment_file=args.input) elapsed_time = timing.end(start) log.info("Populate read container - elapsed time: %s", timing.humanize(elapsed_time)) # Populate record container # The record container type can now be determine from the input parameters # and injected into the Solver start = timing.start()
def solve(self, solver=Solver.PYCOSAT_SOLVER): self.solved[solver] = Solver.get(solver).solve(self.n, self.clauses) return self.solved[solver]
def fill_position_mask(shape=(6, 7)): print( '|----------------------------------------------------------------------------|' ) print(' TEST OBJECTIVE: test binary representation of grid of', shape, 'shape') # Start with an empty board and node game = DynamicGame(grid_shape=shape) solver = Solver(game.gameState) node = solver.root_node # Node should be empty assert (node.position == 0 and node.mask == 0) # Every column should be playable for col in range(node.WIDTH): assert (node.can_play(col)) # Move sequence (row, col) move_order_h = [] move_order_v = [] # Fill the board left to right, bottom to top for row in range(node.HEIGHT): for col in range(node.WIDTH): move_order_h.append((row, col)) # Fill the board bottom to top, lef to right for col in range(node.WIDTH): for row in range(node.HEIGHT): move_order_v.append((row, col)) for i in range(0, 2): solver = Solver(game.gameState) node = solver.root_node played_cells = [] if i == 0: moves = move_order_h else: moves = move_order_v for row, col in moves: # Current player plays a move played_cells.append(col * (node.HEIGHT + 1) + row) node.play(col) # Compute what should be position of the current player expected_position = 0 for idx, cell in enumerate(played_cells): # It is the starting players turn if node.total_moves % 2 == 0: if idx % 2 == 0: expected_position += 2**cell # It is the second players turn else: if idx % 2 == 1: expected_position += 2**cell # The value of the position is the sum of 2**cell for all cell played by the current player. assert (node.position == expected_position) # The value of the mask is the sum of 2**cell for all cell played. assert (node.mask == sum(map(lambda x: 2**x, played_cells))) # Node should be full at this point and have no legal moves left for col in range(node.WIDTH): assert (not node.can_play(col)) print('\n TEST SUCCESSFUL') print( '|----------------------------------------------------------------------------|' )
if (len(sys.argv) < 5): print "Solver usage: python populate_containers.py <INPUT_ALN_FILE> <DATASET_DESC_XML_FILE> <SOLUTION_XML_OUTPUT_FILE> <STATS_OUTPUT_DIRECTORY>" sys.exit(-1) aln_file = sys.argv[1] dataset_xml_file = sys.argv[2] solution_xml_output_file = sys.argv[3] stats_dir = sys.argv[4] log.info("I got the input file!") # ---------------------- Initialize Solver --------------------- # greedySolver = GreedySolver() taxonomySolver = SimpleTaxonomySolver() solver = Solver(determine_host, greedySolver, taxonomySolver) # ---------------------- Run Solver --------------------- # start_total = time.time() solver.generateSolutionXML(aln_file, dataset_xml_file, solution_xml_output_file, stats_dir) log.info("Successfully initialized solver!") end_total = time.time() elapsed_time_total = end_total - start_total print ("TOTAL - \t\telapsed time: %.2f" % elapsed_time_total) # fill_containers (aln_file)
tax_solver = None log.info("taxonomy solver: %s" % args.tax_solver) if args.tax_solver == 'simple': tax_solver = SimpleTaxonomySolver() elif args.tax_solver == 'simple_join': tax_solver = SimpleJoinTaxonomySolver() # Create database access db_access = DbQuery() tax_tree = TaxTree(args.tax_tree) host_determinator = HostDeterminator(dbquery=db_access, tax_tree=tax_tree) log.info("Started.") processing_start = timing.start() solver = Solver(host_determinator, read2cds_solver, tax_solver) # Populate read container # The read container type can now be determined from the input parameters # and injected into the Solver start = timing.start() read_container = ReadContainer() read_container.populate_from_aln_file(read_alignment_file=args.input) elapsed_time = timing.end(start) log.info("Populate read container - elapsed time: %s", timing.humanize(elapsed_time)) # Populate record container # The record container type can now be determine from the input parameters # and injected into the Solver start = timing.start()