def _check_is_diagonal(operator: OperatorBase) -> bool: """Check whether ``operator`` is diagonal. Args: operator: The operator to check for diagonality. Returns: True, if the operator is diagonal, False otherwise. Raises: OpflowError: If the operator is not diagonal. """ if isinstance(operator, PauliOp): # every X component must be False return not np.any(operator.primitive.x) # For sums (PauliSumOp and SummedOp), we cover the case of sums of diagonal paulis, but don't # raise since there might be summand canceling the non-diagonal parts. That case is checked # in the inefficient matrix check at the bottom. if isinstance(operator, PauliSumOp): if not np.any(operator.primitive.paulis.x): return True elif isinstance(operator, SummedOp): if all( isinstance(op, PauliOp) and not np.any(op.primitive.x) for op in operator.oplist): return True elif isinstance(operator, ListOp): return all(operator.traverse(_check_is_diagonal)) # cannot efficiently check if a operator is diagonal, converting to matrix matrix = operator.to_matrix() return np.all(matrix == np.diag(np.diagonal(matrix)))
def convert(self, operator: OperatorBase) -> OperatorBase: """Convert the Operator to ``CircuitStateFns``, recursively if ``traverse`` is True. Args: operator: The Operator to convert Returns: The converted Operator. """ if isinstance(operator, DictStateFn) and self._convert_dicts: return CircuitStateFn.from_dict(operator.primitive) if isinstance(operator, VectorStateFn) and self._convert_vectors: return CircuitStateFn.from_vector(operator.to_matrix(massive=True)) elif isinstance(operator, ListOp) and "Dict" in operator.primitive_strings(): return operator.traverse(self.convert) else: return operator
def _check_is_diagonal(operator: OperatorBase) -> bool: """Check whether ``operator`` is diagonal. Args: operator: The operator to check for diagonality. Returns: True, if the operator is diagonal, False otherwise. Raises: OpflowError: If the operator is not diagonal. """ if isinstance(operator, PauliOp): # every X component must be False if not np.any(operator.primitive.x): return True return False if isinstance(operator, SummedOp): # cover the case of sums of diagonal paulis, but don't raise since there might be summands # canceling the non-diagonal parts # ignoring mypy since we know that all operators are PauliOps if all( isinstance(op, PauliOp) and not np.any(op.primitive.x) for op in operator.oplist): return True if isinstance(operator, ListOp): return all(operator.traverse(_check_is_diagonal)) # cannot efficiently check if a operator is diagonal, converting to matrix matrix = operator.to_matrix() if np.all(matrix == np.diag(np.diagonal(matrix))): return True return False