Exemplo n.º 1
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))
Exemplo n.º 2
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)