def test_sudoku(self): try: handler = DesktopHandler(ClingoDesktopService(self.getPath())) inp = ASPInputProgram() for i in range(9): for j in range(9): if (self.inputMatrix[i][j] != 0): inp.add_object_input( Cell(i, j, self.inputMatrix[i][j])) inp.add_files_path(os.path.join( "..", "..", "..", "..", "test-resources", "asp", "sudoku")) handler.add_program(inp) mc = MyCallback() handler.start_async(mc) mc.await() out = mc.get_output() # out = handler.startSync() self.assertIsNotNone(out) self.assertTrue(isinstance(out, Output), "Error, result object is not Output") self.assertIsNone( out.get_errors(), "Found error in the Plan\n" + str(out.get_errors())) if (len(out.get_answer_sets()) == 0): return ans = out.get_answer_sets()[0] for obj in ans.get_atoms(): self.inputMatrix[obj.get_row()][obj.get_column() ] = obj.get_value() tmp = "" for i in range(9): for j in range(9): tmp += str(self.inputMatrix[i][j]) + " " print(tmp) tmp = "" except Exception as e: self.fail("Exception " + str(e))
def test_sudoku(self): try: handler = DesktopHandler(DLVDesktopService(self.getPath())) inp = ASPInputProgram() for i in range(9): for j in range(9): if self.inputMatrix[i][j] != 0: inp.add_object_input(Cell(i, j, self.inputMatrix[i][j])) inp.add_files_path( os.path.join("..", "..", "..", "..", "test-resources", "asp", "sudoku")) handler.add_program(inp) mc = MyCallback() handler.start_async(mc) mc. await () out = mc.get_output() # out = handler.startSync() self.assertIsNotNone(out) self.assertTrue(isinstance(out, Output), "Error, result object is not Output") self.assertTrue(out.get_errors() == "", "Found error:\n" + str(out.get_errors())) self.assertTrue(len(out.get_answer_sets()) != 0) ans = out.get_answer_sets()[0] for obj in ans.get_atoms(): self.inputMatrix[obj.get_row()][ obj.get_column()] = obj.get_value() tmp = "" for i in range(9): for j in range(9): tmp += str(self.inputMatrix[i][j]) + " " print(tmp) tmp = "" except Exception as e: self.fail("Exception " + str(e))
def __init__(self): if os.name == 'nt': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/DLV2.exe"))) elif os.uname().sysname == 'Darwin': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2.mac_7"))) else: self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2-linux-64_6"))) self.__inputProgram = ASPInputProgram() self.__inputProgram.add_files_path(os.path.join(resource_path, "map.dlv2")) self.__handler.add_program(self.__inputProgram)
def __init__(self): self.__countLogs = 0 # count for debug self.__dir = None # log directory for debug self.__lastPositionsEnemy = {} # check all last position of enemy self.__bombs = ListBomb() # list of bomb already placed try: if os.name == 'nt': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/DLV2.exe"))) elif os.uname().sysname == 'Darwin': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2.mac_7"))) else: self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2-linux-64_6"))) self.__fixedInputProgram = ASPInputProgram() self.__variableInputProgram = None self.__fixedInputProgram.add_files_path(os.path.join(resource_path, "enemyRules.dlv2")) self.__handler.add_program(self.__fixedInputProgram) except Exception as e: print(str(e))
def core(self, results_sizes, base_path): print("Testing " + str(len(results_sizes)) + " files for " + base_path) for i in range(1, len(results_sizes) + 1): try: plan = None handler = DesktopHandler(SPDDesktopService()) input_program_domain = PDDLInputProgram(PDDLProgramType.DOMAIN) input_program_domain.add_files_path(base_path + "domain.pddl") inputProgramProblem = PDDLInputProgram(PDDLProgramType.PROBLEM) if i < 10: problem = base_path + "p" + "0" + str(i) + ".pddl" else: problem = base_path + "p" + str(i) + ".pddl" self.assertTrue(os.path.isfile(problem), "File not found: " + problem) inputProgramProblem.add_files_path(problem) handler.add_program(input_program_domain) handler.add_program(inputProgramProblem) PDDLMapper.get_instance().register_class(PickUp) self.assertIsNone(plan) mc = MyCallback() handler.start_async(mc) mc. await () plan = mc.get_output() self.assertIsNotNone(plan) tmp = "" for action in plan.get_actions(): tmp = tmp + action.get_name() + "," print(tmp) if results_sizes[i - 1] != 0: self.assertTrue( not plan.get_errors(), "Found error in the Plan " + problem + "\n" + plan.get_errors()) self.assertEqual(results_sizes[i - 1], len(plan.get_actions())) for obj in plan.get_actions_objects(): if isinstance(obj, PickUp): print(obj.get_block()) time.sleep(0.5) except Exception as e: self.fail("Exception " + str(e))
[0, 0, 9, 6, 0, 0, 5, 0, 0], [0, 0, 5, 3, 0, 0, 9, 0, 0], [0, 1, 0, 0, 8, 0, 0, 0, 2], [6, 0, 0, 0, 0, 4, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 1, 0], [0, 4, 1, 0, 0, 0, 0, 0, 7], [0, 0, 7, 0, 0, 0, 3, 0, 0]] # inputMatrix = [ [ 5, 0, 0, 0, 0, 0, 0, 8, 0 ], # [ 0, 3, 0, 7, 0, 0, 0, 9, 0 ], # [ 0, 0, 0, 4, 0, 2, 6, 0, 0 ], # [ 6, 2, 0, 8, 0, 0, 3, 0, 0 ], # [ 0, 9, 5, 0, 0, 0, 7, 1, 0 ], # [ 0, 0, 1, 0, 0, 5, 0, 2, 6 ], # [ 0, 0, 8, 5, 0, 3, 0, 0, 0 ], # [ 0, 5, 0, 0, 0, 9, 0, 4, 0 ], # [ 0, 1, 0, 0, 0, 0, 0, 0, 8 ] ] handler = DesktopHandler( DLVDesktopService("app/src/test/resources/asp/executables/dlv.mingw.exe")) inp = ASPInputProgram() for i in range(9): for j in range(9): # print(str(inputMatrix[i][j]) + " ", end="") if (inputMatrix[i][j] != 0): inp.add_object_input(Cell(i, j, inputMatrix[i][j])) # print() inp.add_files_path("app/src/test/resources/asp/sudoku") handler.add_program(inp) # opt = OptionDescriptor()
lock = CountDownLatch(1) w, h = 9, 9; inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] handler = DesktopHandler(DLVDesktopService("app/src/test/resources/asp/executables/dlv.x86-64-linux-elf-static.bin")) inp = ASPInputProgram() for i in range(9): for j in range(9): # print(str(inputMatrix[i][j]) + " ", end="") if (inputMatrix[i][j] != 0): inp.add_object_input(Cell(i,j,inputMatrix[i][j])) # print() inp.add_files_path("app/src/test/resources/asp/sudoku") handler.add_program(inp)
class AI: def __init__(self) -> None: # Instantiate the Handler. self.handler = DesktopHandler(DLV2DesktopService(os.path.join(dirname, "dlv2.exe"))) # Register input facts to provide to DLV2. ASPMapper.get_instance().register_class(MatrixCellPredicate) ASPMapper.get_instance().register_class(ShapePredicate) ASPMapper.get_instance().register_class(InCellPredicate) def instantiateProgram(self) -> None: # Instantiate the ASP program. self.inputProgram = ASPInputProgram() # Define the program's rules. logicProgram = open(os.path.join(dirname, "newShapeRules.lp"), "r") self.rules = logicProgram.read() logicProgram.close() # Add rules to the program self._addRules() def getOptimalPlace(self, matrix: list, shapes: list): self.instantiateProgram() matrixPredicates = [] for i in range(len(matrix)): for j in range(len(matrix)): if (matrix[i][j]): matrixPredicates.append(MatrixCellPredicate(i, j)) shapePredicate = ShapePredicate(0, shapes[0]) #DEBUG #self.printArray(matrixPredicates) #self.printArray(shapePredicate) # Add predicates to the program self.inputProgram.add_objects_input(matrixPredicates) self.inputProgram.add_object_input(shapePredicate) # Add program to the handler self.handler.add_program(self.inputProgram) print(self.inputProgram) # Spawn DLV synchronously and get the output output = self.handler.start_sync() optimalPlacement = [] optimalAnswerSets = output.get_optimal_answer_sets() #print(len(optimalAnswerSets)) for answerSet in output.get_optimal_answer_sets(): #print(answerSet.get_weights()) for atom in answerSet.get_atoms(): # Filter out inCellPredicates. The answer set contains facts, outCellPredicates etc. We are only interested in inCellPredicates. if isinstance(atom, InCellPredicate): optimalPlacement.append((atom.get_index(), atom.get_coordX(), atom.get_coordY())) self.inputProgram.clear_all() self.handler.remove_all() return optimalPlacement def getOptimalPlacement(self, matrix: list, shapes: list): """ Returns the optimal placement for a single `ShapeAggregate`, given the input matrix status. Returns `None` if the AS is empty (no solution). """ # Instantiate program. self.instantiateProgram() matrixPredicates = [] for i in range(len(matrix)): for j in range(len(matrix)): if (matrix[i][j]): matrixPredicates.append(MatrixCellPredicate(i, j)) shapePredicate = [] for x in range(len(shapes)): shapePredicate.append(ShapePredicate(x, shapes[x][0])) #self.printArray(matrixPredicates) #self.printArray(shapePredicate) # Add predicates to the program self.inputProgram.add_objects_input(matrixPredicates) self.inputProgram.add_objects_input(shapePredicate) # Add program to the handler self.handler.add_program(self.inputProgram) print(self.inputProgram) # Spawn DLV synchronously and get the output output = self.handler.start_sync() optimalPlacement = [] optimalAnswerSets = output.get_optimal_answer_sets() for answerSet in output.get_optimal_answer_sets(): #print(answerSet.get_weights()) for atom in answerSet.get_atoms(): # Filter out inCellPredicates. The answer set contains facts, outCellPredicates etc. We are only interested in inCellPredicates. if isinstance(atom, InCellPredicate): optimalPlacement.append((atom.get_index(), atom.get_coordX(), atom.get_coordY())) self.inputProgram.clear_all() self.handler.remove_all() return optimalPlacement def getOptimalPlacements(self, matrix, shapeAggregates): pass def _addRules(self) -> None: self.rules = re.sub(r'\s?\n\t+', '', self.rules) self.inputProgram.add_program(self.rules) def _reset(self) -> None: # Remove the program from the handler self.handler.remove_all() # Remove rules and facts from the program self.inputProgram.clear_all() # Add rules back self._addRules() def printArray(self, arr: list) -> None: for el in arr: print(el)
class DLVSolution: def __init__(self): self.__countLogs = 0 # count for debug self.__dir = None # log directory for debug self.__lastPositionsEnemy = {} # check all last position of enemy self.__bombs = ListBomb() # list of bomb already placed try: if os.name == 'nt': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/DLV2.exe"))) elif os.uname().sysname == 'Darwin': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2.mac_7"))) else: self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2-linux-64_6"))) self.__fixedInputProgram = ASPInputProgram() self.__variableInputProgram = None self.__fixedInputProgram.add_files_path(os.path.join(resource_path, "enemyRules.dlv2")) self.__handler.add_program(self.__fixedInputProgram) except Exception as e: print(str(e)) # DEBUG def __log_program(self) -> None: if not os.path.exists(logs_path): os.mkdir(f"{logs_path}") if self.__countLogs == 0: timestamp = datetime.datetime.now() self.__dir = f"{timestamp.hour}-{timestamp.minute}-{timestamp.second}" os.mkdir(f"{logs_path}/{self.__dir}") with open(f"{logs_path}/{self.__dir}/BomberFriend-{self.__countLogs}.log", "w") as f: f.write(f"Variable: \n" f"{self.__variableInputProgram.get_programs()} \n\n\n" f"Fixed:\n" f"{self.__fixedInputProgram.get_files_paths()}") self.__countLogs += 1 # END DEBUG def recallASP(self) -> None: try: print("RECALL ASP") # # print(f" ENEMY: {gameInstance.getEnemy()} \n " # f"PLAYER: {gameInstance.getPlayer()}") # self.__nMovements += 1 # increase movements size = gameInstance.getSize() self.__variableInputProgram = ASPInputProgram() # input matrix as facts for i in range(size): for j in range(size): typeNumber = gameInstance.getElement(i, j) p = InputPointType(i, j, typeNumber) self.__variableInputProgram.add_object_input(p) # point(I, J, ELEMENT_TYPE) # compute neighbors values ai e = gameInstance.getEnemy() p = gameInstance.getPlayer() listAdjacent = computeNeighbors(e.get_i(), e.get_j()) for adjacent in listAdjacent: if not gameInstance.outBorders(adjacent.get_i(), adjacent.get_j()): distance = getDistanceEP(adjacent, p) d = Distance(adjacent.get_i(), adjacent.get_j(), distance) print(f"Distance: {d} --> {distance}") self.__variableInputProgram.add_object_input(d) # adding last position if len(self.__lastPositionsEnemy) != 0: for enemy in self.__lastPositionsEnemy: self.__variableInputProgram.add_program( f"lastPositionEnemy({enemy.get_i()}, {enemy.get_j()}, {self.__lastPositionsEnemy[enemy]}).") # adding bombs ai for bomb in self.__bombs: self.__variableInputProgram.add_object_input(bomb) index = self.__handler.add_program(self.__variableInputProgram) answerSets = self.__handler.start_sync() self.__log_program() print("#######################################") print(answerSets.get_answer_sets_string()) for answerSet in answerSets.get_optimal_answer_sets(): print(answerSet) for obj in answerSet.get_atoms(): if isinstance(obj, Path): moveEnemyFromPath(obj, self.__lastPositionsEnemy) elif isinstance(obj, InputBomb): addBombEnemy(self.__bombs, obj) elif isinstance(obj, EnemyBomb): gameInstance.plantBomb(obj.get_i(), obj.get_j()) bomb = InputBomb(obj.get_i(), obj.get_j()) addBombEnemy(self.__bombs, bomb) elif isinstance(obj, BreakBomb): gameInstance.plantBomb(obj.get_i(), obj.get_j()) bomb = InputBomb(obj.get_i(), obj.get_j()) addBombEnemy(self.__bombs, bomb) elif isinstance(obj, AdjacentPlayerAndEnemy): self.__lastPositionsEnemy.clear() # clear last enemy position because enemy find player print("#######################################") self.__handler.remove_program_from_id(index) except Exception as e: print(str(e))
class MatrixBuilder: def __init__(self): if os.name == 'nt': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/DLV2.exe"))) elif os.uname().sysname == 'Darwin': self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2.mac_7"))) else: self.__handler = DesktopHandler( DLV2DesktopService(os.path.join(resource_path, "../../lib/dlv2-linux-64_6"))) self.__inputProgram = ASPInputProgram() self.__inputProgram.add_files_path(os.path.join(resource_path, "map.dlv2")) self.__handler.add_program(self.__inputProgram) def build(self) -> list[list[int]]: global MAP_SIZE worldMap = [[0 for _ in range(MAP_SIZE)] for _ in range(MAP_SIZE)] try: for i in range(MAP_SIZE): # adding size matrix self.__inputProgram.add_program(f"n({i}).") for i in range(int(MAP_SIZE / 2)): # adding numbers of wall self.__inputProgram.add_program(f"wallId({i}).") self.__inputProgram.add_program(f"minWood({MAP_SIZE}).") self.__inputProgram.add_program(f"maxWood({MAP_SIZE * 2}).") Starting().start() answerSets = self.__handler.start_sync() print("~~~~~~~~~~~~~~~~~~~~~~ MATRIX ~~~~~~~~~~~~~~~~~~~~~~") if len(answerSets.get_answer_sets()) == 0: raise Exception for answerSet in answerSets.get_answer_sets(): print(answerSet) for obj in answerSet.get_atoms(): if isinstance(obj, InputPointType): worldMap[obj.get_i()][obj.get_j()] = obj.get_t() for row in worldMap: print(row) print("~~~~~~~~~~~~~~~~~~~~~~ END MATRIX ~~~~~~~~~~~~~~~~~~~~~~") self.__handler.remove_all() except Exception as e: MAP_SIZE = 16 worldMap = [[1, 0, 0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 3, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 0, 0, 4, 4, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 4, 0, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [4, 0, 0, 0, 3, 0, 4, 0, 0, 0, 0, 0, 0, 4, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 3, 0, 0, 4, 0, 0, 3, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 4, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 4, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 4, 4, 4, 0, 0, 0, 0], [0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [2, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]] finally: global done done = True return worldMap
class PickUp(Predicate): predicate_name = "pick-up" def __init__(self, block=None): super(PickUp, self).__init__([("block")]) self.block = block def get_block(self): return self.block def set_block(self, block): self.block = block handler = DesktopHandler(SPDDesktopService()) inputProgramDomain = PDDLInputProgram(PDDLProgramType.DOMAIN) inputProgramDomain.add_files_path( "app/src/test/resources/pddl/blocksworld/domain.pddl") inputProgramProblem = PDDLInputProgram(PDDLProgramType.PROBLEM) inputProgramProblem.add_files_path( "app/src/test/resources/pddl/blocksworld/p35.pddl") handler.add_program(inputProgramDomain) handler.add_program(inputProgramProblem) PDDLMapper.get_instance().register_class(PickUp)
w, h = 9, 9; inputMatrix = [ [ 1, 0, 0, 0, 0, 7, 0, 9, 0 ], [ 0, 3, 0, 0, 2, 0, 0, 0, 8 ], [ 0, 0, 9, 6, 0, 0, 5, 0, 0 ], [ 0, 0, 5, 3, 0, 0, 9, 0, 0 ], [ 0, 1, 0, 0, 8, 0, 0, 0, 2 ], [ 6, 0, 0, 0, 0, 4, 0, 0, 0 ], [ 3, 0, 0, 0, 0, 0, 0, 1, 0 ], [ 0, 4, 1, 0, 0, 0, 0, 0, 7 ], [ 0, 0, 7, 0, 0, 0, 3, 0, 0 ] ] handler = DesktopHandler(ClingoDesktopService("app/src/test/resources/asp/executables/clingo64.exe")) inp = ASPInputProgram() for i in range(9): for j in range(9): # print(str(inputMatrix[i][j]) + " ", end="") if (inputMatrix[i][j] != 0): inp.add_object_input(Cell(i,j,inputMatrix[i][j])) # print() inp.add_files_path("app/src/test/resources/asp/sudoku") handler.add_program(inp)
def run(csv_file, solvers_dir, input_file, option_file): FileManager.write_to_file(csv_file, 'a', input_file, True, True) for solver in Solver.get_solvers(): if not FileManager.solver_present(solvers_dir, solver.value + '.solver'): continue answer_sets = [] input_program = ASPInputProgram() handler = DesktopHandler(solver.get_service(solvers_dir)) option_id = handler.add_option( OptionDescriptor(solver.get_output_option())) if option_file is not None and option_file != "" and option_file.lower( ) != "-no-option-file": for _filter in FileManager.read_filters(option_file, solver): handler.add_option(OptionDescriptor(' ' + _filter)) handler.add_program(input_program) input_program.add_files_path(input_file) sorted_output = OutputManager.process_raw_output( solver.value, handler.start_sync().get_answer_sets_string()) handler.remove_option_from_id(option_id) start_time = time.time() for answer_set in handler.start_sync().get_answer_sets(): answer_sets.append(answer_set.get_atoms()) end_time = time.time() FileManager.write_to_file( csv_file, 'a', solver.value + ':' + str(end_time - start_time), None, True) if answer_sets: for answer_set in answer_sets: tmp = ' '.join(sort_facts(answer_set)) if tmp not in sorted_output: print('ERROR! Original ' + solver.value + ' output does not contain:\n' + tmp + '\n') print('END')
def core(self, results_sizes, base_path): print("Testing " + str(len(results_sizes)) + " files for " + base_path) for i in range(1, len(results_sizes) + 1): try: plan = None handler = DesktopHandler(SPDDesktopService()) input_program_domain = PDDLInputProgram(PDDLProgramType.DOMAIN) input_program_domain.add_files_path(base_path + "domain.pddl") inputProgramProblem = PDDLInputProgram(PDDLProgramType.PROBLEM) if i < 10: problem = base_path + "p" + "0" + str(i) + ".pddl" else: problem = base_path + "p" + str(i) + ".pddl" self.assertTrue(os.path.isfile(problem), "File not found: " + problem) inputProgramProblem.add_files_path(problem) handler.add_program(input_program_domain) handler.add_program(inputProgramProblem) PDDLMapper.get_instance().register_class(PickUp) self.assertIsNone(plan) mc = MyCallback() handler.start_async(mc) mc.await() plan = mc.get_output() self.assertIsNotNone(plan) tmp = "" for action in plan.get_actions(): tmp = tmp + action.get_name() + "," print(tmp) if results_sizes[i - 1] != 0: self.assertTrue(not plan.get_errors( ), "Found error in the Plan " + problem + "\n" + plan.get_errors()) self.assertEqual(results_sizes[i - 1], len(plan.get_actions())) for obj in plan.get_actions_objects(): if isinstance(obj, PickUp): print(obj.get_block()) time.sleep(0.5) except Exception as e: self.fail("Exception " + str(e))