Пример #1
0
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')
Пример #2
0
    def test_shortest_path(self):
        try:
            handler = DesktopHandler(DLV2DesktopService(self.getPath()))

            ASPMapper.get_instance().register_class(Edge)
            ASPMapper.get_instance().register_class(Path)

            inputProgram = ASPInputProgram()

            self.source = 0  # source node
            self.destination = 7  # destination node

            rules = "source(" + str(self.source) + "). destination(" + str(
                self.destination) + ")."
            rules += "path(X,Y,W) | notPath(X,Y,W) :- source(X), edge(X,Y,W)."
            rules += "path(X,Y,W) | notPath(X,Y,W) :- path(_,X,_), edge(X,Y,W), not to(X)."
            rules += "visited(X) :- path(_,X,_)."
            rules += ":- destination(X), not visited(X)."
            rules += ":~ path(X,Y,W). [W@1 ,X,Y]"

            inputProgram.add_program(rules)
            inputProgram.add_objects_input(self.getEdges())

            handler.add_program(inputProgram)

            answerSets = handler.start_sync()

            self.assertIsNotNone(answerSets)
            self.assertTrue(isinstance(answerSets, Output),
                            "Error, result object is not Output")
            self.assertTrue(answerSets.get_errors() == "",
                            "Found error:\n" + str(answerSets.get_errors()))
            self.assertTrue(len(answerSets.get_optimal_answer_sets()) != 0)

            answerSet = answerSets.get_optimal_answer_sets()[0]

            path = []  # edges in the shortest path (unsorted)
            sum_ = 0  # total weight of the path

            for obj in answerSet.get_atoms():
                if isinstance(obj, Path):
                    path.append(obj)
                    sum_ += int(obj.get_weight())

            sortedPath = []  # edges in the shortest path (sorted)
            sortedPath.append(self.source)

            self.join(self.source, path, sortedPath)  # sorts the edges
            self.show(sortedPath, sum_)  # shows the path

        except Exception as e:
            print(str(e))
Пример #3
0
    def test_find_reachable_nodes(self):
        try:
            o1 = Edge(1, 2)
            o2 = Edge(2, 3)
            o3 = Edge(2, 4)
            o4 = Edge(3, 5)
            o5 = Edge(5, 6)

            handler = DesktopHandler(IDLVDesktopService(getPath()))
            testInputProgram = DatalogInputProgram()
            testInputProgram.add_program("path(X,Y) :- edge(X,Y).")
            testInputProgram.add_program("path(X,Y) :- path(X,Z), path(Z,Y). ")

            testInputProgram.add_object_input(o1)
            testInputProgram.add_object_input(o2)
            testInputProgram.add_object_input(o3)
            testInputProgram.add_object_input(o4)
            testInputProgram.add_object_input(o5)

            handler.add_program(testInputProgram)
            # handler.add_option(OptionDescriptor("--no-projection=0 "))
            # handler.add_option(OptionDescriptor("--no-decomp "))
            # handler.add_option(OptionDescriptor("--t"))

            DatalogMapper.get_instance().register_class(Path)

            minimalModels = handler.start_sync()
            self.assertIsNotNone(minimalModels)
            self.assertTrue(minimalModels.get_errors() == "", "Found error:\n" + str(minimalModels.get_errors()))
            self.assertTrue(len(minimalModels.get_minimal_models()) == 1)

            for o in minimalModels.get_minimal_models().pop().get_atoms_as_objectset():
                if isinstance(o, Path):
                    print(o.__str__())

        except Exception as e:
            print(str(e))
Пример #4
0
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)
Пример #5
0
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))
Пример #6
0
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