Skip to content

Commit

Permalink
Add check_generator to assert_valid
Browse files Browse the repository at this point in the history
  • Loading branch information
astralcai committed Sep 19, 2024
1 parent cbc5a9d commit 52e430b
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion pennylane/operation.py
Original file line number Diff line number Diff line change
Expand Up @@ -1449,7 +1449,7 @@ def generator(self): # pylint: disable=no-self-use
0.5 * Y(0) + Z(0) @ X(1)
The generator may also be provided in the form of a dense or sparse Hamiltonian
(using :class:`.Hermitian` and :class:`.SparseHamiltonian` respectively).
(using :class:`.Hamiltonian` and :class:`.SparseHamiltonian` respectively).
The default value to return is ``None``, indicating that the operation has
no defined generator.
Expand Down
20 changes: 20 additions & 0 deletions pennylane/ops/functions/assert_valid.py
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,25 @@ def _check_eigendecomposition(op):
assert qml.math.allclose(decomp_mat, original_mat), failure_comment


def _check_generator(op):
"""Checks that if an operator has a generator, it does."""

if op.has_generator:
gen = op.generator()
assert isinstance(gen, qml.Hamiltonian) or isinstance(gen, qml.ops.SparseHamiltonian)

Check notice on line 177 in pennylane/ops/functions/assert_valid.py

View check run for this annotation

codefactor.io / CodeFactor

pennylane/ops/functions/assert_valid.py#L177

Consider merging these isinstance calls to isinstance(gen, (qml.Hamiltonian, qml.ops.SparseHamiltonian)) (consider-merging-isinstance)
new_op = qml.exp(gen, 1j * op.data[0])
assert qml.math.allclose(
qml.matrix(op, wire_order=op.wires), qml.matrix(new_op, wire_order=op.wires)
)
else:
failure_comment = (
"If has_generator is False, the matrix method must raise a ``GeneratorUndefinedError``."
)
_assert_error_raised(
op.matrix, qml.operation.GeneratorUndefinedError, failure_comment=failure_comment
)()


def _check_copy(op):
"""Check that copies and deep copies give identical objects."""
copied_op = copy.copy(op)
Expand Down Expand Up @@ -333,4 +352,5 @@ def __init__(self, wires):
_check_matrix(op)
_check_matrix_matches_decomp(op)
_check_eigendecomposition(op)
_check_generator(op)
_check_capture(op)

0 comments on commit 52e430b

Please sign in to comment.