pdhoolia / qiskit

Qiskit is an open-source SDK for working with quantum computers at the level of extended quantum circuits, operators, and primitives.
https://www.ibm.com/quantum/qiskit
Apache License 2.0
0 stars 0 forks source link

Unable to Create Multi-Controlled Gates with More Than 3 Controls in Qiskit #5

Open pdhoolia opened 1 month ago

pdhoolia commented 1 month ago

What is happening?

I am encountering an issue where I cannot create multi-controlled gates with more than 3 controls in Qiskit.

How can we reproduce the issue?

Code Example:

from qiskit import QuantumCircuit
from qiskit.circuit import Parameter

theta1 = Parameter('θ1')

qc = QuantumCircuit(5)
qc.ry(theta1,4)
qc.control(4,ctrl_state=0)

qc.draw("mpl")

What should happen?

I got the error: TypeError: ParameterExpression with unbound parameters (dict_keys([Parameter(θ1)])) cannot be cast to a float.

se-agent commented 1 month ago

The error you're encountering is due to the fact that the control method is being applied directly to a QuantumCircuit object, which does not have a control method. The control method is available on Gate objects, and it is used to create a controlled version of a gate. In your example, you're trying to create a multi-controlled gate from a parameterized ry gate, which should be converted to a gate first before calling control.

Here's a step-by-step guide to resolve the issue and create a multi-controlled gate with more than 3 controls:

  1. Convert the ry gate to a Gate object: Use the to_gate() method to convert the ry instruction into a gate.

  2. Create a multi-controlled gate: Use the control method on the gate object to create a controlled version of the gate.

  3. Append the controlled gate to the circuit: Append the controlled gate to the quantum circuit using the append method.

Here's the corrected code:

from qiskit import QuantumCircuit
from qiskit.circuit import Parameter

# Define a parameter
theta1 = Parameter('θ1')

# Create a quantum circuit with 5 qubits
qc = QuantumCircuit(5)

# Add a parameterized ry gate to the 5th qubit
ry_gate = qc.ry(theta1, 4).to_gate()

# Create a multi-controlled version of the ry gate with 4 control qubits
controlled_ry_gate = ry_gate.control(4, ctrl_state='1111')

# Append the controlled gate to the circuit
# Note: The qubit order is control qubits followed by the target qubit
qc.append(controlled_ry_gate, [0, 1, 2, 3, 4])

# Draw the circuit
qc.draw("mpl")

Explanation:

This approach should resolve the issue and allow you to create multi-controlled gates with more than 3 controls in Qiskit.