How to get a gate from circuit

I want to implement the function of converting a circuit into an operator, and add to a new circuit.
Qiskit code

qc = QuantumCircuit(2)
qc.h(0)
qc.cx(0,1)
gate1 = qc.to_gate(label="U1")
gate2 = qc.to_gate(label="U2").control(1) #controlled

new = QuantumCircuit(3)
new.append(gate1, [1,2])
new.append(gate2, [0,1,2])

How can I achieve the same functionality in pennylane?

I have tried his code but it doesn’t run.(pennylane version == 0.26.0)

import pennylane as qml
from pennylane.operation import Operation
from pennylane import numpy as np

class RXX(Operation):
    num_params = 1
    num_wires = 2
    par_domain = "R"

    @staticmethod
    def decomposition(theta, wires):
        return [qml.PauliRot(theta, 'XX', wires=wires)]
dev = qml.device('default.qubit', wires=2, shots=100)

@qml.qnode(dev)
def circuit(theta):
    RXX(theta, wires=[0, 1])
    qml.Hadamard(1)
    return qml.expval(qml.PauliZ(0) @ qml.PauliY(1))
print(circuit(0.3))

Thank you very much for your help.

Hello @SHAN !

Thank you for sending your code!

This version works for me:

import pennylane as qml
from pennylane.operation import Operation
from pennylane import numpy as np

class RXX(Operation):
    num_params = 1
    num_wires = 2
    par_domain = "R"

    @staticmethod
    def compute_decomposition(theta, wires):
        return [qml.PauliRot(theta, 'XX', wires=wires)]
    

Instead of decomposition just use compute_decomposition and it should work. :slight_smile:

3 Likes

Hello @ludmilaaasb
Thanks :heart_eyes:

1 Like