pennylane
pennylane copied to clipboard
Add matrix and sparse matrix to `Permute` template
PennyLane has a Permute
template that decomposes into SWAP operations to reorder wires.
qml.Permute([4, 2, 0, 1, 3], wires=[0, 1, 2, 3, 4])
We should be able to directly construct the matrix for this template. Since the matrix is so sparse, we should add a sparse matrix as well, though that can added separately in a later PR.
A successful PR completely this task would:
- Add a
matrix
orcompute_matrix
method toqml.Permute
(and/orsparse_matrix
) - Add tests to
tests/templates/test_subroutines/test_permute.py
- Add a changelog entry
@albi3ro I would like to work on this issue. If possible assign it to me.
Question: What should be the arguments for this function? Also, the docs state that qml.Permute
has a compute_matrix
function (I think it is of the super class i.e. Operation
). Do you want to override it?
Thanks @Gopal-Dahale !
For some added information, Operator
defines the default behaviour for compute_matrix
and matrix
. This default behaviour is raising a MatrixNotImplementedError
. We want to override that behavior.
We have two options for defining the matrix:
-
Permute.compute_matrix(*parameters, **hyperparameters)
. This static method acceptsop.parameters
andop.hyperparameters
. Since the existing hyperparameters does not provide enough information to calculate the matrix, we would need to addwires
to the hyperparameters dictionary. -
Permute.matrix(self, wire_order=None)
. If we override this instead, we need to manually set the propertyPermute.has_matrix=True
. We would also need to useqml.math.expand_matrix
to convert from the default wire order to any arbitrary wire order.
See the source code for the GroverOperator
and the QFT
template for examples of templates that define compute_matrix
.
@albi3ro I have created a draft pr. I have some questions:
- The
compute_matrix
method's signature is*params, **hyperparams
. I need the number of wires (n_wires
) and thepermutation
for computing the matrix. So the call to the function will look like this (for 3 wires)
P_matrix = qml.templates.Permute([1,2,0], wires=wires).compute_matrix(3, [1,2,0])
Passing the permutation
in the compute_matrix
seems redundant as it is given in Permute
but I do not see any other alternative to this. As compute_matrix
is a static method, I cannot access self.hyperparameters
dict.
2. Passing permutation
as the second argument to compute_matrix
method as a 'dict' gives an error
TypeError: unhashable type: 'dict'
I am not sure what exactly the signature of the compute_matrix
method should be.
@albi3ro Need some help here.
@Gopal-Dahale , I left some clarifications on the PR itself here: https://github.com/PennyLaneAI/pennylane/pull/3173#issuecomment-1281300771 .
Hope that helps clear things up a little.