Quantum Computing SEArchived Jun 27, 2026✓ Full text saved
How do I generate a random quantum circuit with $n$ gates and $q$ qubits in Qiskit This is answered here ; basically, use random_circuit from qiskit.circuit.random . shuffle the order of the gates
Full text archived locally
✦ AI Summary· Claude Sonnet
Shuffle Qiskit gate order?
Ask Question
Asked 7 days ago
Modified 5 days ago
Viewed 122 times
1
How do I
generate a random quantum circuit with
n
𝑛
gates and
q
𝑞
qubits in Qiskit
This is answered here; basically, use random_circuit from qiskit.circuit.random.
shuffle the order of the gates
qiskitcircuit-constructionrandom-quantum-circuit
Share
Improve this question
Follow
edited Jun 21 at 6:05
Martin Vesely
15.6k4
4 gold badges
34
34 silver badges
77
77 bronze badges
asked Jun 19 at 20:25
Geremia
1879
9 bronze badges
Add a comment
2 Answers
Sorted by:
Highest score (default)
Date modified (newest first)
Date created (oldest first)
1
If you want to do it correct, not a naive approach, using exclusively Qiskit, you can mess a bit with the Qiskit transpiler. Basically, a circuit in Qiskit is represented as a DAG (Direct Acyclic Graph), where each gate is a node and the edges encode data dependencies between gates on the same qubit.
So this is the correct way to shuffle it. If you just do random.shuffle(qc.data), you can generate invalid orderings (as placing a gate before another it depends on). The DAG prevents that, as it only lets you place a gate after all its dependencies are satisfied, so the shuffle is as random as physically possible while still producing a valid circuit.
import random
from qiskit import QuantumCircuit
from qiskit.transpiler import PassManager
from qiskit.transpiler.basepasses import TransformationPass
class ShuffleGates(TransformationPass):
def run(self, dag):
nodes = list(dag.topological_op_nodes())
random.shuffle(nodes)
new_dag = dag.copy_empty_like()
for node in nodes:
new_dag.apply_operation_back(node.op, node.qargs, node.cargs)
return new_dag
def shuffle_circuit(qc : QuantumCircuit) -> QuantumCircuit:
pm = PassManager(ShuffleGates())
shuffled_qc = pm.run(qc)
return shuffled_qc
topological_op_nodes() gives you the gates in dependency order. Shuffling them and replaying onto a fresh DAG with apply_operation_back randomizes the order while respecting qubit dependencies.
This was REALLY fun to solve. I work a lot these days with these things, but I had never thought of solving this problem. Hope this solution is valid to you. 🙂
Share
Improve this answer
Follow
edited Jun 21 at 22:42
Geremia
1879
9 bronze badges
answered Jun 21 at 13:35
Enrique Anguiano Vara
1265
5 bronze badges
Your answer is interesting, but did the OP say that they wanted all dependencies maintained? You can take a circuit, shuffle the gates, and you'll still have a circuit, though most likely it won't do anything useful. Given the original question was about random circuits, it's unclear which question they were actually asking. –
Frank Yellin
Commented
Jun 21 at 17:23
1
@FrankYellin You're right but it can generate orderings that are invalid as measurement before a gate on the same qubit (i like weak-measurments but this is not the case) The DAG approach avoids that by only shuffling gates that are free to move. Whether the resulting circuit is meaningful is something idk, but at least it's legal. –
Enrique Anguiano Vara
Commented
Jun 21 at 17:36
What about simply reversing the order of the gates? Is the DAG method still necessary in that case? Or would ops.reverse() in my solution work? –
Geremia
Commented
Jun 21 at 19:51
1
@Geremia Yes, for reversing should work what you said (the method here, not the code below). Idk your goal with this but note qc.inverse() is a bit more general than qc.reverse_ops() if you want to make any complex gate become the identity. (as an example, a T gate, in reverse, you'll have
TT≠I
𝑇
𝑇
≠
𝐼
but at inverse it will be for any gate). Nevertheless, note shuffling does not mean reversing by any meaning. Your solution below is doing a shuffling which can have illegal results as we discussed above –
Enrique Anguiano Vara
Commented
Jun 22 at 19:34
@EnriqueAnguianoVara Interesting. I didn't know about QuantumCircuit's reverse_ops() or inverse(). Gracias. 🙏 –
Geremia
Commented
Jun 22 at 20:00
Add a comment
1
This should work:
import random
def shuffle_gate_order(circ: QuantumCircuit, seed=None) -> QuantumCircuit:
rng = random.Random(seed)
new = QuantumCircuit(circ.num_qubits, circ.num_clbits)
ops = list(circ.data)
rng.shuffle(ops)
for item in ops:
inst = item.operation
qargs = item.qubits
cargs = item.clbits
new.append(inst, qargs, cargs)
return new
Note: Reversibility of quantum circuits does not mean gate-order doesn't matter. See this example.
Share
Improve this answer
Follow
edited Jun 20 at 4:57
answered Jun 19 at 21:40
Geremia
1879
9 bronze badges
Add a comment
Your Answer
Sign up or log in
Sign up using Google
Sign up using Email and Password
Post as a guest
Name
Email
Required, but never shown
Post Your Answer
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Ask question
Explore related questions
qiskitcircuit-constructionrandom-quantum-circuit
See similar questions with these tags.
The Overflow Blog
Code isn’t the only thing causing your production...
Paging Charity! How can engineering leaders avoid becoming Bond...
Featured on Meta
Partnering with Communities to Modernize Policies & Norms
Linked
2
How to make circuit for randomly selected gate?
Related
20
Do multi-qubit measurements make a difference in quantum circuits?
1
Multiple random coin flips without measurements
12
Understanding Google's “Quantum supremacy using a programmable superconducting processor” (Part 1): choice of gate set
3
Can I 'shuffle' the qubits in my circuit?
4
How can I generate a quaternion using Qiskit?
0
Generating random circuits with only CNOT gates using qiskit.circuit.random.random_circuit
0
What is the gate order in QuantumCircuit.data?
1
How to make sense of `Pauli observables` in the gate cutting code here?
3
Sampling a Haar Random State Conditioned on Having Low Entanglement Entropy
7
Complexity of a superposition of two random circuits
Hot Network Questions
How to notate non-word vocalizations?
DP83825I: Why would TI specify an ESR value for the crystal?
Is air density or air pressure the important quantity for breathing?
Use GDAL to download from remote 7zip
What is "1:1 time", and where does it come from?
In this piece, can I pluck the first string using fingers i and m?
Taxes are exorbitant and spending is being slashed to the bone, why is there still rising inflation?
Theoretically, could the heat from volcanic geothermal vents be used to smelt underwater?
Where to get Ubuntu Yaru theme assets?
Interaction between drawing something in the background and a page of floats
How can I easily find all the possible intermediate cities for a stopover where both legs are strictly non-stop flights?
What happens when a choice doesn't matter (until it does)?
Practical maximum clique search on 300–900 vertex graphs with only a few seconds available
Ghost story, cemetery under man-made lake
Is anyone able to translate and comprehend this Chinese calligraphy please
How to show text data in TCP packets in Wireshark?
Documented instances of speciation on human time-scale
How can I stop relying on AI when writing code?
How can I position text characters side by side based on their bounding boxes in Geometry Nodes?
I have a recipe that is calling for 12 basil leaves but I have ground basil instead
"I said to stay back." "I said stay back." What's the difference?
How do researchers stay organized when working on multiple papers at once?
Water softener drain line discharge height
How/could one figure out any method of variolation for an unknown water born virus without killing too many in the process?
Question feed
By continuing to use this website, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy. By exiting this window, default cookies will be accepted. To reject cookies, select an option from below.
Customize settings
Cookie consent preference center
When you visit any of our websites, it may store or retrieve information on your browser, mostly in the form of cookies. This information might be about you, your preferences, or your device and is mostly used to make the site work as you expect it to. The information does not usually directly identify you, but it can give you a more personalized experience. Because we respect your right to privacy, you can choose not to allow some types of cookies. Click on the different category headings to find out more and manage your preferences. Please note, blocking some types of cookies may impact your experience of the site and the services we are able to offer.
Cookie policy
Accept all cookies
Manage consent preferences
Strictly Necessary Cookies
Always Active
These cookies are necessary for the website to function and cannot be switched off in our systems. They are usually only set in response to actions made by you which amount to a request for services, such as setting your privacy preferences, logging in or filling in forms. You can set your browser to block or alert you about these cookies, but some parts of the site will not then work. These cookies do not store any personally identifiable information.
Targeting Cookies
Targeting Cookies
These cookies are used to make advertising messages more relevant to you and may be set through our site by us or by our advertising partners. They may be used to build a profile of your interests and show you relevant advertising on our site or on other sites. They do not store directly personal information, but are based on uniquely identifying your browser and internet device.
Performance Cookies
Performance Cookies
These cookies allow us to count visits and traffic sources so we can measure and improve the performance of our site. They help us to know which pages are the most and least popular and see how visitors move around the site. All information these cookies collect is aggregated and therefore anonymous. If you do not allow these cookies we will not know when you have visited our site, and will not be able to monitor its performance.
Functional Cookies
Functional Cookies
These cookies enable the website to provide enhanced functionality and personalisation. They may be set by us or by third party providers whose services we have added to our pages. If you do not allow these cookies then some or all of these services may not function properly.
Cookie List
Clear
checkbox label label
Apply Cancel
Consent Leg.Interest
checkbox label label
checkbox label label
checkbox label label
Necessary cookies only Confirm my choices