The way to append gate instances to a QuantumCircuit
is with the append
method.
circuit.append(controlled_gate, circuit.qubits)
Here is a full example with explanations:
You mentioned:
I would like to encode state only if qubit a and b are 1
As such, you can create two single-qubit registers $a$ and $b$; and a register for the state to encode:
from qiskit import QuantumCircuit, QuantumRegister
circuit = QuantumCircuit(QuantumRegister(1, "a"),
QuantumRegister(1, "b"),
QuantumRegister(2, "state"))
Then, in order to control on two qubits ($a$ and $b$), you need to set control(2)
.
from qiskit.circuit.library import StatePreparation
import numpy as np
state = [0, 1/np.sqrt(2), -1.j/np.sqrt(2), 0]
controlled_gate = StatePreparation(state).control(2)
Finally, the append
. The second parameter describe how to wire the gate, in this case circuit.qubits
$= [a, b, state_0, state_1]$:
circuit.append(controlled_gate, circuit.qubits)
circuit.draw()
a: ──────────────────────■──────────────────────
│
b: ──────────────────────■──────────────────────
┌─────────────────────┴─────────────────────┐
state_0: ┤0 ├
│ State Preparation(0,0.70711,-0.70711j,0) │
state_1: ┤1 ├
└───────────────────────────────────────────┘