<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Rahul Tech Articles on Medium]]></title>
        <description><![CDATA[Stories by Rahul Tech Articles on Medium]]></description>
        <link>https://medium.com/@rahul.techarticles?source=rss-47cbf737da60------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*-go34DAsje68s4Po</url>
            <title>Stories by Rahul Tech Articles on Medium</title>
            <link>https://medium.com/@rahul.techarticles?source=rss-47cbf737da60------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 10:51:51 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rahul.techarticles/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Your Notes, Your Rules]]></title>
            <link>https://medium.com/@rahul.techarticles/your-notes-your-rules-eb192745c88e?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb192745c88e</guid>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[notetaking]]></category>
            <category><![CDATA[privacy]]></category>
            <category><![CDATA[artificial-intelligence]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Sat, 24 Oct 2026 09:24:02 GMT</pubDate>
            <atom:updated>2026-10-24T09:24:02.523Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A free, open-source notebook that keeps your data on your machine</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HvWaP0OwatG8SpRH71_Vgg.png" /></figure><p>Ever wished you could have your own AI-powered notebook that actually respects your privacy? You know, the kind where you can throw in your documents, chat with them, and keep everything on your own machine instead of shipping your data off to some corporation’s servers?</p><p>That’s exactly what Open Notebook promises. And honestly, after spending time with it, I think it delivers on that promise pretty well.</p><h3>What Is Open Notebook and Why Should You Care?</h3><p>Open Notebook is an open-source project that positions itself as a replacement for popular paid tools like Google’s NotebookLM (which has a painfully slow, laggy free tier) and Turbo AI (which offers almost nothing in terms of resources unless you pay up).</p><p>The pitch is simple. You get a local AI notebook where you can upload files, chat with them, take notes manually or let the AI generate notes for you, and all of this happens on your own computer. No subscription fees. No data leaves your machine unless you choose to connect it to a cloud API.</p><p>I mean, that alone should make you curious.</p><h3>Getting Started</h3><p>Here’s the thing about Open Notebook. It’s genuinely easy to get up and running, which surprised me given how many open-source projects make you jump through hoops just to see the interface.</p><p>You can grab the Docker file directly from their GitHub page and set it up locally. You can either use curl to download it or just navigate to the GitHub link, grab the file, paste it in a folder, and run it. That’s it. The whole thing then lives at localhost:8502, and you’re ready to go.</p><figure><img alt="Open Notebook Home Page" src="https://cdn-images-1.medium.com/max/1024/1*8GF2OY8BFerGtASHwKIBmQ.png" /><figcaption><em>Open Notebook Home Page</em></figcaption></figure><p>Now here’s where I should mention something. If you want to connect it to a local LLM, that part takes a bit of time. Not hard, just a little patience required. But more on that in a moment.</p><h3>The Features That Actually Matter</h3><p>Let me break down what you get with Open Notebook:</p><p><strong>Note-taking.</strong> You know, the basic stuff. But it works well. And here’s something I really appreciated. The notes are written in markdown format. That means you can add links, images, code snippets, tables, lists, and all the formatting you would expect from a proper note-taking tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wtO0QlU374T9MykoONPZVw.png" /><figcaption>Note-Taking Feature in Markdown format</figcaption></figure><p><strong>Completely free and open source.</strong> You don’t have to pay anything unless you decide to use cloud API keys. And even then, connecting to a local LLM means you pay absolutely nothing. Zero. Nada.</p><p><strong>Flexible AI options.</strong> You can connect it to a local LLM running on your machine, or you can use API keys from providers like OpenAI or Google Gemini. The choice is yours. That’s the beauty of it.</p><p><strong>Cost and privacy advantages.</strong> This is the big one. When you run it with a local LLM, you’re not paying for API calls, and your data never leaves your computer. For anyone dealing with sensitive information, this is huge.</p><p><strong>Multi-file chatting.</strong> Upload multiple files and have conversations with them. It handles URLs too. I tested it with a simple file, and it worked as expected.</p><p><strong>Manual and AI notes.</strong> You can write notes yourself or let the AI store notes directly from your chats. Both options are there.</p><h3>The Not So Great Parts</h3><p>I’d be doing you a disservice if I only talked about the good stuff.</p><p><strong>The UI could use some polish.</strong> It works, but it feels like a work in progress. Nothing that would stop you from using it, but don’t expect the sleekness of a commercial product.</p><p><strong>Setting up with a local LLM takes time.</strong> If you’re running this on a machine with limited resources like my 8GB RAM setup, you’ll need to be smart about which models you pick. I went with llama3.2:1b for the language-chatting part and nomic-embed-text:latest for embeddings and for fetching text from files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*H9WIPaAP7PIeHP3R9UUG4Q.png" /><figcaption>Ollama Local Models in Terminal — Using ollama list</figcaption></figure><p>That <strong>nomic-embed-text model</strong> made a massive difference. The embedding and text-fetching process became noticeably faster than when using ollama without it. So if you’re going the local route, definitely grab that model.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u3OnPkwCI4bvb9kpGla3HA.png" /><figcaption>Models Configured in the Open Notebook — ollama, chatgpt</figcaption></figure><p><strong>Exporting notes is a hassle.</strong> This is probably my biggest complaint. There’s no direct export option. You have to manually copy paste everything. For a tool that’s all about managing notes and information, this feels like an oversight.</p><h3>Who Is This Actually For?</h3><p>Students who want to chat with their study materials without paying for subscriptions. Professionals who deal with sensitive company data and can’t risk it going through cloud services. Anyone who’s curious about local AI and wants a practical tool to experiment with.</p><p>The data privacy angle is particularly compelling for the professional crowd. When you connect Open Notebook to a local LLM, your company documents stay on your machine. They don’t roam around in the cloud. That’s not just a feature; that’s a requirement for a lot of people.</p><h3>Project Health Check</h3><p>If you’re considering investing time in an open-source project, you want to know it won&#39;t be abandoned next month.</p><p>Open Notebook has around 40.4k stars on GitHub, 180 watchers, 4.7k forks, and 96 contributors. It operates under the MIT license, which means you can do pretty much whatever you want with it.</p><p>Those numbers suggest a healthy, active community. Not the biggest project out there, but certainly not a ghost town either.</p><h3>My Honest Verdict</h3><p>Open Notebook is a solid platform for taking notes and chatting with your files. It gives you a way to have conversations with multiple documents, URLs, and text content all in one place.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8hkRBktCDDBeokGlZQ4zeQ.png" /><figcaption>Open Notebook Interface Main Page</figcaption></figure><p>During my testing, I found that the ollama model gave me proper responses while keeping all my data on my computer. The ChatGPT model gave me responses with references, but that came at the cost of less data privacy since everything went to the cloud.</p><p>The embedding model situation taught me something useful. Initially, things were moving slowly with just ollama. Once I installed nomic-embed-text, the whole experience improved significantly. So if you’re setting this up yourself, learn from my experience and install that model from the start.</p><p>The export issue is real, though. For a note-taking application, not having a proper export function makes the whole thing feel incomplete. You’re using this tool to organise information, but then you have to manually copy and paste everything if you want to take it elsewhere. That’s tedious.</p><p>Would I recommend it? Yes, with some caveats. If you’re comfortable with a slightly rough UI and you don’t mind the setup process for local LLMs, Open Notebook offers something genuinely valuable. It’s free, it respects your privacy, and it works.</p><p>For students and professionals who need a private, cost-effective way to work with documents and AI, this is worth trying. Just don’t expect it to replace your entire note-taking workflow until they sort out that export situation.</p><p>Give it a shot. Your data stays yours, and your wallet stays happy. That’s not something you can say about most AI tools these days.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb192745c88e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Feedforward Operations — Real‑Time Conditional Logic]]></title>
            <link>https://medium.com/@rahul.techarticles/feedforward-operations-real-time-conditional-logic-6f03b4b007bb?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f03b4b007bb</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 12:20:02 GMT</pubDate>
            <atom:updated>2026-08-19T12:20:02.913Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Using </em><em>if_test to apply gates based on previous measurement results</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tU5DOtn2ecjKDtw8UwllSg.png" /></figure><p>Quantum computing isn’t just about preparing states and measuring them at the end. Sometimes you need to make decisions <em>during</em> the computation — like applying a gate only if a previous measurement gave a specific outcome. This is called <em>feedforward</em> or <em>real‑time conditional logic</em>. It is essential for quantum error correction, teleportation, and many adaptive algorithms.</p><p>In this article, we’ll build a minimal but working example using Qiskit’s if_test context manager. We’ll run it on a simulator, see the conditional behaviour, and understand how to use this powerful tool. The code is kept simple and compatible with Qiskit 2.5.0.</p><p>All snippets are meant to be run in a Jupyter Notebook (or Google Colab). You’ll find the complete notebook at the GitHub link provided at the end.</p><h3>Setting up your environment</h3><p>Create a dedicated virtual environment to avoid dependency clashes. I used medium_quantum_venv:</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Then install the required packages:</p><pre>pip install qiskit qiskit-aer</pre><p>We are using qiskit==2.5.0 and qiskit-aer for the simulator.</p><h3>Import the libraries</h3><p>In your notebook cell, start with:</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit_aer import AerSimulator</pre><p>We will use AerSimulator because it fully supports conditional operations and gives realistic, noise‑free results.</p><h3>Build a circuit with conditional logic</h3><p>We want to demonstrate that a gate can be applied only when a certain measurement result occurs.</p><ul><li>Qubit 0 will be placed in a superposition and measured.</li><li>If the measurement outcome is 1, we apply an X gate to qubit 1.</li><li>Finally, we measure qubit 1 to see the effect.</li></ul><p>Here is the circuit creation code:</p><pre>qc = QuantumCircuit(2, 1)<br><br>qc.h(0)<br>qc.measure(0, 0)<br>with qc.if_test((0, 1)):<br>    qc.x(1)<br>qc.measure(1, 0)</pre><p><strong>What’s happening?</strong></p><p>The if_test context manager takes a tuple (classical_register_index, value). The indented block is executed only if the classical bit equals the given value. In our case, the X gate is performed only when the measurement of qubit 0 yields 1.</p><h3>Simulate and collect results</h3><p>We now run the circuit on the AerSimulator. Since we reuse the same classical bit, the final measurement overwrites the earlier measurement of qubit 0. We will see the counts for qubit 1.</p><pre>sim = AerSimulator()<br>transpiled = transpile(qc, sim)<br>result = sim.run(transpiled, shots=1024).result()<br>counts = result.get_counts()<br><br>print(counts)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*0GH4ieYTAbSWBgAepSjhXg.png" /></figure><p>The counts are approximately equal — about half 0 and half 1. Why?</p><ul><li>Qubit 0 is measured as 0 or 1 with equal probability.</li><li>Only when it is 1 do we flip qubit 1, so qubit 1 ends up being 1 exactly in those cases.</li><li>When qubit 0 is 0, qubit 1 remains 0.</li></ul><p>Thus, the final measurement of qubit 1 shows a 50/50 distribution. If we had omitted the conditional gate, qubit 1 would always be 0.</p><h3>Verify the conditional effect</h3><p>To be absolutely sure, let’s run a second circuit <em>without</em> the conditional gate and compare.</p><pre>qc_no_cond = QuantumCircuit(2, 1)<br>qc_no_cond.h(0)<br>qc_no_cond.measure(0, 0)<br>qc_no_cond.measure(1, 0)    # direct measurement, no X<br><br>transpiled_no = transpile(qc_no_cond, sim)<br>result_no = sim.run(transpiled_no, shots=1024).result()<br>counts_no = result_no.get_counts()<br><br>print(counts_no)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/126/1*KIws2aEjcc35i3pEvLS4cg.png" /></figure><p>All results are 0 because qubit 1 was never changed. This proves that the conditional X gate is indeed acting based on the measurement of qubit 0.</p><h3>Bringing it all together</h3><p>You can place the code from sections 2, 3, and 4 into separate cells of your Jupyter notebook. The imports from section 1 should be in the first cell. Running them will produce the outputs shown.</p><p>The conditional logic we implemented is the simplest form of feedforward. In real quantum hardware, such operations are crucial for mid‑circuit measurements and adaptive gates, enabling algorithms that react to partial results before the final readout.</p><h3>GitHub repository</h3><p>You can download the complete Jupyter notebook from my GitHub repo:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-30.ipynb">medium_qiskit_quantum/part2_intermediate/article-30.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Conclusion</h3><p>Feedforward operations using if_test allow you to build dynamic quantum circuits that respond to measurement outcomes in real time. With only a few lines of code, we showed how a conditional X gate changes the final state based on a previous measurement. This pattern is a building block for more advanced protocols like quantum teleportation, error correction, and variational algorithms. Experiment with different gates and conditions to see the flexibility of this approach.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f03b4b007bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dynamic Circuits — Mid‑Circuit Measurement and Reset]]></title>
            <link>https://medium.com/@rahul.techarticles/dynamic-circuits-mid-circuit-measurement-and-reset-2bbe2c4d5e52?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/2bbe2c4d5e52</guid>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Tue, 18 Aug 2026 05:42:04 GMT</pubDate>
            <atom:updated>2026-08-18T05:42:04.103Z</atom:updated>
            <content:encoded><![CDATA[<h4>Build a circuit that measures a qubit and resets it for reuse, then run it on real hardware</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cXraFac-wtCrKr-4C8fq7Q.png" /></figure><p>Dynamic circuits are one of the most exciting capabilities in quantum computing today. They allow you to measure qubits in the middle of a circuit execution and use those measurement results to control subsequent operations. This process, known as classical feedforward, paves the way for more efficient quantum algorithms and is a foundational technique for quantum error correction.</p><p>In this article, we will build a simple dynamic circuit that measures a qubit, resets it based on the measurement outcome, and reuses it. We will run the circuit on the Aer simulator and verify that the qubit is successfully returned to the zero state.</p><h3>Setting Up Your Environment</h3><p>We will use a Jupyter notebook for this tutorial. You can run this in Jupyter Notebook, Jupyter Lab, or Google Colab.</p><p>First, create a virtual environment and install the required packages:</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate<br>pip install qiskit==2.5.0 qiskit-aer jupyter</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate<br>pip install qiskit==2.5.0 qiskit-aer jupyter</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><p>The complete notebook for this article is available on GitHub: <a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-29.ipynb">https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-29.ipynb</a></p><h3>Understanding the Circuit</h3><p>The concept is straightforward. We will:</p><ol><li>Apply a Hadamard gate to put the qubit in a superposition state</li><li>Measure the qubit</li><li>If the measurement result is 1, apply an X gate to flip it back to 0</li><li>Measure again to verify the qubit is in the zero state</li></ol><p>This is the simplest form of a dynamic circuit. The qubit is measured, and based on that measurement, we conditionally apply an operation to reset it.</p><h3>Importing the Required Libraries</h3><p>Start your Jupyter notebook with these imports:</p><pre>from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister<br>from qiskit_aer import AerSimulator<br>from IPython.display import display</pre><p>The AerSimulator is the recommended simulator for Qiskit 2.5.0.</p><h3>Building the Circuit</h3><p>Create a circuit with one qubit and two classical bits. The first classical bit stores the result of the initial measurement. The second stores the result of the final measurement.</p><pre>qubits = QuantumRegister(1, &quot;q&quot;)<br>clbits = ClassicalRegister(2, &quot;c&quot;)<br>circuit = QuantumCircuit(qubits, clbits)<br>(q0,) = qubits<br>(c0, c1) = clbits</pre><p>Apply a Hadamard gate to create superposition:</p><pre>circuit.h(q0)</pre><p>Measure the qubit and store the result in the first classical bit:</p><pre>circuit.measure(q0, c0)</pre><p>Now comes the dynamic part. If the measurement result is 1, we apply an X gate to flip the qubit back to 0:</p><pre>with circuit.if_test((c0, 1)):<br>    circuit.x(q0)</pre><p>Finally, measure the qubit again and store the result in the second classical bit:</p><pre>circuit.measure(q0, c1)</pre><h3>Visualising the Circuit</h3><p>Let us draw the circuit to see what we have built:</p><pre>circuit.draw(&quot;mpl&quot;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*9AdhKQt3Yg6oPFWqv-9B5w.png" /></figure><p>A circuit diagram showing the Hadamard gate, a measurement, a conditional X gate, and a final measurement. The diagram will display a single qubit line with these operations in sequence.</p><h3>Running the Simulation</h3><p>Now we run the circuit on the Aer simulator:</p><pre>simulator = AerSimulator()<br>job = simulator.run(circuit, shots=1024)<br>result = job.result()<br>counts = result.get_counts(circuit)<br>print(counts)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*fM6ZFwxxE_Ci5Sy6tXylcg.png" /></figure><p>A dictionary showing counts for the measurement outcomes. Since the reset operation only triggers when the first measurement is 1, about half the shots will result in ‘00’ and half in ‘01’. The second bit is always 0, confirming the qubit was successfully reset.</p><p>The result ‘01’ means the first measurement was 1 and the second was 0 (reset successful). ‘00’ means both measurements were 0. In both cases, the final measurement is always 0, confirming the qubit is returned to the zero state.</p><h3>Complete Code</h3><p>Here is the complete code in one block for easy copying:</p><pre>from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister<br>from qiskit_aer import AerSimulator<br>from IPython.display import display<br><br>qubits = QuantumRegister(1, &quot;q&quot;)<br>clbits = ClassicalRegister(2, &quot;c&quot;)<br>circuit = QuantumCircuit(qubits, clbits)<br>(q0,) = qubits<br>(c0, c1) = clbits<br><br>circuit.h(q0)<br>circuit.measure(q0, c0)<br><br>with circuit.if_test((c0, 1)):<br>    circuit.x(q0)<br><br>circuit.measure(q0, c1)<br><br>display(circuit.draw(&quot;mpl&quot;))<br><br>simulator = AerSimulator()<br>job = simulator.run(circuit, shots=1024)<br>result = job.result()<br>counts = result.get_counts(circuit)<br>print(counts)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/525/1*5wSPIUzZfEi-Z1wLHgdSnw.png" /></figure><p>The circuit diagram is followed by the measurement counts.</p><h3>GitHub Repository</h3><p>The complete Jupyter notebook for this tutorial is available at:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-29.ipynb">medium_qiskit_quantum/part2_intermediate/article-29.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Conclusion</h3><p>Dynamic circuits with mid-circuit measurement and reset are a powerful tool for quantum computing. In this tutorial, we built a simple circuit that measures a qubit and conditionally resets it based on the measurement outcome. We ran it on the Aer simulator and verified that the qubit was successfully returned to the zero state.</p><p>This technique is essential for quantum error correction and efficient resource utilization on near-term quantum hardware. With Qiskit 2.5.0, building and running dynamic circuits has become more accessible than ever.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2bbe2c4d5e52" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Writing a Custom Transpiler Pass — Your First Plugin]]></title>
            <link>https://medium.com/@rahul.techarticles/writing-a-custom-transpiler-pass-your-first-plugin-e4291b48b0a6?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4291b48b0a6</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <category><![CDATA[visualization]]></category>
            <category><![CDATA[quantum-circuits]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Mon, 17 Aug 2026 06:02:23 GMT</pubDate>
            <atom:updated>2026-08-17T06:02:23.543Z</atom:updated>
            <content:encoded><![CDATA[<h4>Extend Qiskit by writing a simple pass that removes redundant gates</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OqBTIbY6Ol9jPzy5O1W3lQ.png" /></figure><p>The Qiskit transpiler is the engine that transforms your quantum circuit into something that can run on real hardware. But did you know you can write your own transpiler passes? In this article, we will build a custom pass that removes redundant gates from a quantum circuit. Think of it as a code optimiser for quantum programs.</p><p>We will use Jupyter Notebook (or Google Colab) with a Python virtual environment. Let us get started.</p><h3>Setting Up Your Environment</h3><p>First, create a virtual environment and install the required packages. Open your terminal and run:</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Now install the required packages:</p><pre>pip install qiskit==2.5.0 qiskit-aer jupyter</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><h3>What We Will Build</h3><p>We will create a custom transpiler pass called RemoveRedundantGates. This pass will scan a quantum circuit and remove consecutive gates that cancel each other out. For example, two consecutive Hadamard gates (H H) are redundant because H * H = I (identity). Similarly, two consecutive X gates cancel each other.</p><p>The pass will inherit from Qiskit’s TransformationPass and operate on the DAG (Directed Acyclic Graph) representation of the circuit.</p><h3>Importing the Required Libraries</h3><p>Create a new cell in your Jupyter Notebook and run the following imports:</p><pre>from qiskit import QuantumCircuit<br>from qiskit.transpiler import PassManager, TransformationPass<br>from qiskit.dagcircuit import DAGCircuit<br>from qiskit_aer import AerSimulator</pre><h3>Writing the Custom Pass</h3><p>Now we will define our custom pass class. The pass overrides the run method, which receives a DAGCircuit object. We will iterate through the nodes and remove redundant patterns.</p><pre>class RemoveRedundantGates(TransformationPass):<br>    def run(self, dag):<br>        nodes = list(dag.op_nodes())<br>        i = 0<br>        while i &lt; len(nodes) - 1:<br>            node1 = nodes[i]<br>            node2 = nodes[i + 1]<br>            if (node1.op.name == node2.op.name and <br>                node1.op.name in [&#39;h&#39;, &#39;x&#39;, &#39;y&#39;, &#39;z&#39;] and<br>                node1.qargs == node2.qargs):<br>                dag.remove_op_node(node1)<br>                dag.remove_op_node(node2)<br>                i += 2<br>            else:<br>                i += 1<br>        return dag</pre><p><strong>What this does:</strong> It looks for two consecutive gates of the same type (H, X, Y, or Z) acting on the same qubit and removes both. Since two identical self-inverse gates in a row equal the identity operation, removing them is safe.</p><h3>Creating a Test Circuit</h3><p>Let us build a circuit with some redundant gates to test our pass.</p><pre>qc = QuantumCircuit(2)<br>qc.h(0)<br>qc.h(0)          # Redundant: two H gates cancel<br>qc.x(1)<br>qc.x(1)          # Redundant: two X gates cancel<br>qc.cx(0, 1)<br>qc.h(0)<br>qc.measure_all()<br><br>print(&quot;Original circuit:&quot;)<br>qc.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/751/1*ynbGw_6MJ6d83I3tMXgOfA.png" /></figure><p>The circuit drawing will show two consecutive H gates on qubit 0, two consecutive X gates on qubit 1, a CNOT gate, and one H gate on qubit 0 before measurement.</p><h3>Applying the Custom Pass</h3><p>Now we will create a PassManager and add our custom pass to it. Then we run the pass on our circuit.</p><pre>pm = PassManager()<br>pm.append(RemoveRedundantGates())<br>optimized_qc = pm.run(qc)<br><br>print(&quot;Optimized circuit:&quot;)<br>optimized_qc.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/596/1*uPTmErBAbAtrNHlGhSPzKA.png" /></figure><p>The optimised circuit will show only the CNOT gate, the single H gate on qubit 0, and the measurements. The two H gates on qubit 0 and the two X gates on qubit 1 have been removed.</p><h3>Verifying with Simulation</h3><p>To confirm that both circuits produce the same results, we can simulate them using AerSimulator.</p><pre>sim = AerSimulator()<br><br># Transpile both circuits for the simulator<br>t_qc = qc.copy()<br>t_opt = optimized_qc.copy()<br><br># Run simulations<br>result_original = sim.run(t_qc, shots=1024).result()<br>result_optimized = sim.run(t_opt, shots=1024).result()<br><br>counts_original = result_original.get_counts()<br>counts_optimized = result_optimized.get_counts()<br><br>print(&quot;Original circuit counts:&quot;, counts_original)<br>print(&quot;Optimized circuit counts:&quot;, counts_optimized)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*MuKJ3ACqWAQpWy7WpvXkPw.png" /></figure><p>Both circuits produce identical measurement outcomes, proving that our pass correctly removed the redundant gates without changing the circuit’s behaviour.</p><h3>Where to Put This Code</h3><p>You can keep all the code in a single Jupyter Notebook cell or split it across multiple cells for better readability. If you want to reuse this pass in other projects, save it as a Python file (for example, my_passes.py) and import it:</p><pre>from my_passes import RemoveRedundantGates</pre><h3>GitHub Repository</h3><p>You can find the complete Jupyter Notebook for this article at:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-28.ipynb">medium_qiskit_quantum/part2_intermediate/article-28.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Conclusion</h3><p>Writing a custom transpiler pass in Qiskit is straightforward. By subclassing TransformationPass and implementing the run method, you can create powerful optimisations tailored to your specific needs. We built a simple pass that removes redundant self-inverse gates, reducing circuit depth without affecting the final results. This is just the beginning. You can extend this concept to build more sophisticated passes that merge gates, optimise rotations, or even perform error mitigation.</p><p>The Qiskit transpiler is a flexible tool. With custom passes, you have the power to shape your quantum circuits exactly the way you want.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4291b48b0a6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Routing Strategies — SWAP‑Based Routing Under the Hood]]></title>
            <link>https://medium.com/@rahul.techarticles/routing-strategies-swap-based-routing-under-the-hood-0575dfa60275?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/0575dfa60275</guid>
            <category><![CDATA[quantum-programming]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Sun, 16 Aug 2026 18:53:29 GMT</pubDate>
            <atom:updated>2026-08-16T18:53:29.185Z</atom:updated>
            <content:encoded><![CDATA[<h4>From Abstract Circuits to Hardware Reality</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wwglTZKIyIl787zyNQYfoA.png" /></figure><p>Quantum circuits are written in an abstract world where any qubit can interact with any other qubit. Real quantum hardware does not work that way. Physical qubits are connected in limited topologies, and two‑qubit gates can only run on qubits that are directly linked. The transpiler bridges this gap by inserting SWAP gates to move quantum information around. This article explores two fundamental SWAP‑based routing strategies: Basic Swap and Lookahead Swap.</p><h3>Setting Up Your Environment</h3><p>We will use a virtual environment named medium_quantum_venv to keep dependencies isolated.</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Installing Dependencies</p><pre>pip install qiskit==2.5.0 qiskit-aer jupyter</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><p>You can also use Google Colab for this tutorial.</p><h3>Complete Notebook</h3><p>The complete Jupyter notebook with all code examples is available at:</p><p>GitHub Repository:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-27.ipynb">https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-27.ipynb</a></p><h3>What We Will Build</h3><p>We will create a simple quantum circuit with a CNOT gate between qubits that are not directly connected on a target device. Then we will transpile this circuit using two different routing strategies:</p><ol><li>Basic Swap: The simplest approach, inserting SWAP gates with minimal effort.</li><li>Lookahead Swap: A more intelligent strategy that looks ahead to choose optimal SWAP placements.</li></ol><p>For each strategy, we will:</p><ul><li>Define a coupling map (device connectivity)</li><li>Build a quantum circuit</li><li>Transpile using the specific routing method</li><li>Visualise the resulting circuit</li><li>Simulate and verify the output</li></ul><h3>Basic Swap Routing</h3><p>Basic Swap is the simplest routing strategy. When it encounters a two‑qubit gate acting on qubits that are not connected, it inserts SWAP gates along the shortest path until the qubits become adjacent. It does not consider future gates, making it fast but often suboptimal.</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit.transpiler import CouplingMap<br>from qiskit_aer import AerSimulator<br>from qiskit.visualization import plot_histogram<br>import matplotlib.pyplot as plt<br>from IPython.display import display<br><br>coupling_map = CouplingMap([[0, 1], [1, 2]])<br><br>qc = QuantumCircuit(3)<br>qc.cx(0, 2)<br>qc.measure_all()<br><br>qc_basic = transpile(<br>    qc,<br>    coupling_map=coupling_map,<br>    routing_method=&#39;basic&#39;,<br>    optimization_level=0<br>)<br><br>print(&quot;Basic Swap transpiled circuit:&quot;)<br>display(qc_basic.draw(&#39;mpl&#39;))<br>print(f&quot;Gate count: {qc_basic.count_ops()}&quot;)<br>print(f&quot;Circuit depth: {qc_basic.depth()}&quot;)<br><br>sim = AerSimulator()<br>result_basic = sim.run(qc_basic, shots=1024).result()<br>counts_basic = result_basic.get_counts()<br>print(f&quot;Measurement results: {counts_basic}&quot;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/749/1*DUaQxQiU10IxnuFiASiVOw.png" /></figure><p>The transpiler inserted a SWAP gate to transfer the quantum state between qubits 0 and 2 via qubit 1. The measurement results show the expected superposition state.</p><h3>Lookahead Swap Routing</h3><p>Lookahead Swap is more sophisticated. Instead of making myopic decisions, it performs a beam search to evaluate multiple possible SWAP sequences. It looks ahead up to a certain depth (default 4 SWAPs) and width (default 4 candidates) to choose the SWAP that maximises the number of future gates that can be executed. This often results in fewer total SWAP gates for complex circuits.</p><pre>qc_lookahead = transpile(<br>    qc,<br>    coupling_map=coupling_map,<br>    routing_method=&#39;lookahead&#39;,<br>    optimization_level=0<br>)<br><br>print(&quot;Lookahead Swap transpiled circuit:&quot;)<br>display(qc_lookahead.draw(&#39;mpl&#39;))<br>print(f&quot;Gate count: {qc_lookahead.count_ops()}&quot;)<br>print(f&quot;Circuit depth: {qc_lookahead.depth()}&quot;)<br><br>result_lookahead = sim.run(qc_lookahead, shots=1024).result()<br>counts_lookahead = result_lookahead.get_counts()<br>print(f&quot;Measurement results: {counts_lookahead}&quot;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*KuStOD1MoaOJ-pKcF5sElA.png" /></figure><p>For this simple circuit, both strategies produce identical results. The difference becomes apparent with larger, more complex circuits where lookahead can avoid unnecessary SWAPs.</p><h3>Comparing the Two Strategies</h3><p>Visualising Both Circuits Side by Side</p><pre>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))<br>qc_basic.draw(&#39;mpl&#39;, ax=ax1)<br>ax1.set_title(&#39;Basic Swap&#39;)<br>qc_lookahead.draw(&#39;mpl&#39;, ax=ax2)<br>ax2.set_title(&#39;Lookahead Swap&#39;)<br>plt.tight_layout()<br>plt.show()</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vIYnfdUU3KyWQT268QmhQQ.png" /></figure><p>Two circuit diagrams, displayed side by side, show the same structure in this simple example.</p><p><em>Note: Because our example contains only one CNOT gate, both routing algorithms yield identical circuits. For a more complex circuit with multiple two‑qubit gates, Lookahead often produces a lower gate count and depth.</em></p><h3>Key Takeaways</h3><p><strong>Basic Swap</strong> is straightforward and fast. It works well for small circuits or when execution speed is more important than gate count. However, it can insert more SWAP gates than necessary because it only considers the current gate.</p><p><strong>Lookahead Swap</strong> is more intelligent. Evaluating multiple future scenarios often produces circuits with fewer SWAP gates. This comes at the cost of higher computational overhead, making it better suited for larger circuits where optimisation matters.</p><p>Both strategies are available as routing plugins in Qiskit 2.5.0. The choice depends on your priorities: speed versus optimality.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0575dfa60275" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Layout Selection — Manual vs. Automatic Mapping]]></title>
            <link>https://medium.com/@rahul.techarticles/layout-selection-manual-vs-automatic-mapping-6779bd67e8e8?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/6779bd67e8e8</guid>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Sat, 15 Aug 2026 18:56:16 GMT</pubDate>
            <atom:updated>2026-08-15T18:56:16.935Z</atom:updated>
            <content:encoded><![CDATA[<h4>Using initial_layout to Place Logical Qubits onto Physical Ones for Better Fidelity</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vg0eXP-fnqwRx_xbzErtqQ.png" /></figure><p>When you write a quantum circuit, it exists in an idealised world. Qubits are numbered 0, 1, 2, and any two qubits can interact. But real quantum hardware has constraints. Physical qubits are connected in specific ways, and not every pair can directly perform a two-qubit gate. The transpiler bridges this gap by mapping your logical qubits to physical qubits on the device. The choice of initial layout is extremely important for minimising the number of SWAP gates inserted and, ultimately, for achieving better fidelity.</p><p>In this article, we will build a simple quantum circuit and compare two approaches: letting Qiskit automatically choose the layout versus manually specifying it using the initial_layout parameter. We will see how the choice of layout affects the transpiled circuit.</p><p>We will use Qiskit 2.5.0 with the AerSimulator. No deprecated Sampler primitives. Just clean, working code.</p><h3>Environment Setup</h3><p>I recommend running this code in a Jupyter Notebook or Google Colab for an interactive experience. I am using a virtual environment named medium_quantum_venv.</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Once the environment is activated, install the required packages:</p><pre>pip install qiskit==2.5.0 qiskit-aer matplotlib numpy</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><h3><strong>GitHub Repository</strong></h3><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-26.ipynb">medium_qiskit_quantum/part2_intermediate/article-26.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Import the Required Libraries</h3><p>Create a new Jupyter Notebook cell and run the following imports:</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit_aer import AerSimulator<br>from qiskit.visualization import plot_histogram<br>import matplotlib.pyplot as plt</pre><h3>Build a Sample Circuit</h3><p>We need a circuit that is sufficiently interesting to demonstrate the transpiler’s work. Let us create a 3-qubit circuit with a CNOT gate between qubit 0 and qubit 2. This gate spans non-adjacent qubits, which will force the transpiler to insert SWAP gates when a restricted coupling map is provided.</p><pre>qc = QuantumCircuit(3)<br>qc.h(0)<br>qc.cx(0, 2)<br>qc.measure_all()<br><br>print(&quot;Original circuit:&quot;)<br>qc.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/663/1*GnrTZ914Ci5HRAvQSVHehQ.png" /></figure><p>A circuit diagram showing a Hadamard on qubit 0, a CNOT from qubit 0 to qubit 2, and measurement gates on all qubits.</p><h3>Set Up the Simulator Backend with a Restricted Coupling Map</h3><p>The transpiler needs a target backend. We will use the AerSimulator with a custom coupling map that only allows connections between adjacent qubits in a linear chain: 0‑1 and 1‑2.</p><pre>simulator = AerSimulator()<br><br>coupling_map = [[0, 1], [1, 0], [1, 2], [2, 1]]<br>basis_gates = [&#39;u1&#39;, &#39;u2&#39;, &#39;u3&#39;, &#39;cx&#39;]<br><br>print(&quot;Custom coupling map (linear chain):&quot;)<br>print(coupling_map)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/367/1*iEhQxAmzMAOqlDVxelLXaw.png" /></figure><h3>Automatic Layout Selection</h3><p>First, let the transpiler automatically choose the layout. We will use optimization_level=1, which enables layout and routing passes.</p><pre>auto_transpiled = transpile(<br>    qc,<br>    basis_gates=basis_gates,<br>    coupling_map=coupling_map,<br>    optimization_level=1<br>)<br><br>print(&quot;Transpiled circuit with automatic layout:&quot;)<br>auto_transpiled.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*katyNP2YoWaHDb_wfb8swA.png" /></figure><p>A transpiled circuit where the transpiler has inserted SWAP gates to route the CNOT(0, 2) across the linear chain. The circuit will show additional SWAP gates, and the CNOT may now be between different qubit indices.</p><h3>Manual Layout Selection</h3><p>Now, we manually specify the initial layout using the initial_layout parameter. We want logical qubit 0 to map to physical qubit 0, logical qubit 1 to physical qubit 1, and logical qubit 2 to physical qubit 2. This is the trivial layout.</p><pre>manual_transpiled = transpile(<br>    qc,<br>    basis_gates=basis_gates,<br>    coupling_map=coupling_map,<br>    initial_layout=[0, 1, 2],<br>    optimization_level=1<br>)<br><br>print(&quot;Transpiled circuit with manual layout (initial_layout=[0, 1, 2]):&quot;)<br>manual_transpiled.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*hynoYZlttPPxDASHPlQDKw.png" /></figure><p>A transpiled circuit similar to the automatic case. However, the manual layout forces the transpiler to start with the specified mapping. If this layout is compatible with the coupling map, it will be used. The transpiler may still insert SWAP gates to satisfy connectivity, but the initial placement is fixed.</p><h3>Comparing the Results</h3><p>Let us compare the depth and gate counts of the two transpiled circuits.</p><pre>print(&quot;Automatic layout - Depth:&quot;, auto_transpiled.depth())<br>print(&quot;Automatic layout - Gate counts:&quot;, auto_transpiled.count_ops())<br><br>print(&quot;Manual layout - Depth:&quot;, manual_transpiled.depth())<br>print(&quot;Manual layout - Gate counts:&quot;, manual_transpiled.count_ops())</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/935/1*5zD5yIdgZBRuVao46ZqzLw.png" /></figure><p>The automatic layout produced a circuit with depth 3 and only 1 CX gate, whereas the manual layout produced a circuit with depth 6 and 4 CX gates. The transpiler intelligently chose a more optimal layout automatically, demonstrating why automatic layout is often preferred.</p><h3>When to Use Manual Layout</h3><p>Manual layout is important when you want to calibrate errors of specific qubits. If you know that certain physical qubits on the device have higher fidelity, you can map your most critical logical qubits to those physical locations. This can significantly improve the overall fidelity of your quantum computation.</p><p>The initial_layout parameter accepts multiple formats: a list (virtual to physical mapping), a dictionary, or a Layout instance. For example, initial_layout=[0, 1, 2] maps logical qubit 0 to physical 0, logical 1 to physical 1, and logical 2 to physical 2.</p><h3>Conclusion</h3><p>The transpiler is the bridge between your ideal circuit and the hardware that runs it. Automatic layout selection works well for most cases, but manual layout gives you control over which physical qubits your logical qubits occupy. This control is essential for error mitigation and achieving better fidelity on real quantum hardware.</p><p>The key takeaways:</p><ul><li>Use initial_layout to manually specify the mapping of logical to physical qubits.</li><li>Automatic layout is convenient and often produces good results.</li><li>Manual layout is valuable when you have knowledge about qubit fidelity or connectivity.</li></ul><p>Experiment with different layouts and observe how they affect the transpiled circuit. The choice of initial layout is one of the most important decisions in quantum circuit optimisation.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6779bd67e8e8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coupling Maps — Why Your Circuit Gets Rewired]]></title>
            <link>https://medium.com/@rahul.techarticles/coupling-maps-why-your-circuit-gets-rewired-de16a9a23c4e?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/de16a9a23c4e</guid>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Fri, 14 Aug 2026 16:25:55 GMT</pubDate>
            <atom:updated>2026-08-14T16:25:55.871Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Understanding how the Qiskit transpiler maps your quantum circuit to hardware and inserts SWAP gates along the way</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HK9tt0SKlptQu_6WD88k6A.png" /></figure><p>When you run a quantum circuit on real hardware, the physical qubits are not fully connected. The transpiler must adapt your circuit to the device’s topology by inserting SWAP gates. In this article, we will build a simple circuit, define a custom coupling map, and watch the transpiler do its magic. All code is compatible with <strong>Qiskit 2.5.0</strong> and uses AerSimulator – no deprecated Sampler primitives.</p><p>We will use Jupyter Notebook (or Google Colab) and a dedicated virtual environment.</p><h3>Setting Up Your Environment</h3><p>Create a virtual environment and install the required packages.</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate<br>pip install qiskit==2.5.0 qiskit-aer matplotlib</pre><p>For macOS/Linux:</p><pre>python -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate<br>pip install qiskit==2.5.0 qiskit-aer matplotlib</pre><p>Launch jupyter notebook:</p><pre>jupyter notebook</pre><h3>Import the Required Libraries</h3><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit.transpiler import CouplingMap<br>from qiskit.visualization import plot_coupling_map<br>from qiskit_aer import AerSimulator<br>import matplotlib.pyplot as plt</pre><h3>Create a Simple Quantum Circuit</h3><p>We define a 3‑qubit circuit with a CNOT gate between qubit 0 and qubit 2. These two qubits are not directly connected in our artificial hardware, so the transpiler will need to reroute the qubits.</p><pre>qc = QuantumCircuit(3)<br>qc.cx(0, 2)<br>qc.measure_all()<br><br>display(qc.draw(&#39;mpl&#39;))</pre><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*nXqPzfA_mZGPpR0Wui1uOw.png" /></figure><p>A circuit diagram with a CNOT from q0 to q2, followed by measurements on all three qubits.</p><h3>Define the Hardware Coupling Map</h3><p>Real quantum chips have limited connectivity. We define a linear chain: qubit 0 connects to qubit 1, and qubit 1 connects to qubit 2. There is no direct connection between qubit 0 and qubit 2.</p><pre>coupling_list = [[0, 1], [1, 2]]<br>coupling_map = CouplingMap(coupling_list)<br><br>fig_map = plot_coupling_map(3, qubit_coordinates=[[0, 0], [1, 0], [2, 0]], coupling_map=coupling_list)<br>display(fig_map)</pre><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/58/1*FP9HQV0KxslawtccQ5VUWg.png" /></figure><p>A visual representation showing three qubits in a line with edges between 0‑1 and 1‑2.</p><h3>Transpile the Circuit</h3><p>Now we transpile our circuit against this coupling map. The transpiler will insert SWAP gates to make the CNOT between q0 and q2 possible.</p><pre>transpiled_qc = transpile(qc, coupling_map=coupling_map, initial_layout=[0, 1, 2])<br><br>display(transpiled_qc.draw(&#39;mpl&#39;))</pre><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*A6gouOmIrcqXVH9Crf2kFw.png" /></figure><p>The transpiled circuit now contains additional SWAP gates. The original CNOT between q0 and q2 has been replaced by a sequence of SWAP gates and a CNOT between adjacent qubits.</p><h3>Visualize the Difference</h3><p>Let us draw both circuits side by side to clearly see the inserted SWAP gates.</p><pre>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(14, 5))<br>qc.draw(&#39;mpl&#39;, ax=ax1)<br>ax1.set_title(&quot;Original Circuit&quot;)<br>transpiled_qc.draw(&#39;mpl&#39;, ax=ax2)<br>ax2.set_title(&quot;Transpiled Circuit with SWAPs&quot;)<br>plt.tight_layout()<br>plt.show()</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bh7MUSSjWXBTTfAo83Rzvw.png" /></figure><p>Two circuit diagrams side by side. The left shows the original circuit; the right shows the transpiled version with SWAP gates inserted.</p><h3>Run the Transpiled Circuit on the AerSimulator</h3><p>Finally, we run the transpiled circuit on the AerSimulator to verify it works correctly.</p><pre>simulator = AerSimulator()<br>job = simulator.run(transpiled_qc, shots=1024)<br>counts = job.result().get_counts()<br>print(&quot;Measurement results:&quot;, counts)</pre><p>Expected output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/358/1*N5NrtOAgj4Iqd64Stxh4LQ.png" /></figure><p>A dictionary of measurement outcomes, e.g., {‘000’: 1024} for the given circuit.</p><h3>Complete Code</h3><p>Here is the complete code in one block for easy copy‑paste.</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit.transpiler import CouplingMap<br>from qiskit.visualization import plot_coupling_map<br>from qiskit_aer import AerSimulator<br>import matplotlib.pyplot as plt<br><br>qc = QuantumCircuit(3)<br>qc.cx(0, 2)<br>qc.measure_all()<br><br>coupling_list = [[0, 1], [1, 2]]<br>coupling_map = CouplingMap(coupling_list)<br><br>display(plot_coupling_map(3, qubit_coordinates=[[0, 0], [1, 0], [2, 0]], coupling_map=coupling_list))<br><br>transpiled_qc = transpile(qc, coupling_map=coupling_map, optimization_level=1)<br>display(transpiled_qc.draw(&#39;mpl&#39;))<br><br>simulator = AerSimulator()<br>job = simulator.run(transpiled_qc, shots=1024)<br>counts = job.result().get_counts()<br>print(&quot;Measurement results:&quot;, counts)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*kCbL5FJ8KbzgS7PKTa1sZg.png" /></figure><h3>Reference Jupyter Notebook</h3><p>The complete Jupyter Notebook for this article is available on GitHub:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-25.ipynb">medium_qiskit_quantum/part2_intermediate/article-25.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Conclusion</h3><p>The Qiskit transpiler is an indispensable tool that adapts your quantum circuit to the physical constraints of real hardware. When your circuit demands interactions between non‑adjacent qubits, the transpiler automatically inserts SWAP gates to reroute the quantum information. Understanding coupling maps and the transpilation process helps you design more efficient circuits and debug unexpected gate counts in your quantum programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de16a9a23c4e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Transpiler — What It Does to Your Circuit]]></title>
            <link>https://medium.com/@rahul.techarticles/the-transpiler-what-it-does-to-your-circuit-b6f177cf3d92?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6f177cf3d92</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Thu, 13 Aug 2026 05:28:57 GMT</pubDate>
            <atom:updated>2026-08-13T05:28:57.676Z</atom:updated>
            <content:encoded><![CDATA[<h4>A visual comparison of optimization_level settings in Qiskit 2.5.0</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WGQHkS7nBuO9VOZreZU3FA.png" /></figure><p>When you write a quantum circuit, it exists in an idealised world. But real quantum hardware has constraints. Qubits are connected in specific ways. Only certain gates are available. Noise is everywhere. The transpiler is the bridge between your ideal circuit and the hardware that runs it.</p><p>In this article, we will take a simple quantum circuit and see how the transpiler transforms it at different optimisation levels. We will compare the original circuit against the transpiled versions side by side.</p><p>We will use Qiskit 2.5.0 with the AerSimulator. No deprecated Sampler primitives. Just clean, working code.</p><h3>Environment Setup</h3><p>I recommend running this code in a Jupyter Notebook or Google Colab for an interactive experience. I am using a virtual environment named medium_quantum_venv.</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Once the environment is activated, install the required packages:</p><pre>pip install qiskit==2.5.0 qiskit-aer matplotlib numpy</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><p>The complete Jupyter Notebook is available on GitHub for reference:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-24.ipynb">medium_qiskit_quantum/part2_intermediate/article-24.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Import the Required Libraries</h3><p>Create a new Jupyter Notebook cell and run the following imports:</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit_aer import AerSimulator<br>from qiskit.visualization import plot_histogram<br>import matplotlib.pyplot as plt</pre><h3>Build a Sample Circuit</h3><p>We need a circuit that is sufficiently interesting to demonstrate the transpiler’s work. Let us create a 4-qubit circuit with a GHZ state and some additional gates:</p><pre>qc = QuantumCircuit(4)<br>qc.h(0)<br>for i in range(1, 4):<br>    qc.cx(0, i)<br>qc.x(0)<br>qc.cz(1, 2)<br>qc.ry(0.5, 3)<br>qc.measure_all()<br><br>print(&quot;Original circuit:&quot;)<br>qc.draw(&#39;mpl&#39;)<br>plt.show()</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*XXT0Mga4gPx3NAFsuuQusg.png" /></figure><p>A circuit diagram showing a Hadamard on qubit 0, CNOT gates from qubit 0 to qubits 1, 2, 3, an X gate on qubit 0, a CZ gate between qubits 1 and 2, an RY gate on qubit 3, and measurement gates on all qubits.</p><h3>Set Up the Simulator Backend</h3><p>The transpiler needs a backend target. We will use the AerSimulator:</p><pre>simulator = AerSimulator()<br>print(&quot;Basis gates supported by AerSimulator:&quot;)<br>print(simulator.target.operation_names)</pre><p>Expected Output:</p><p>Basis gates supported by AerSimulator: dict_keys([‘save_expval_var’, ‘save_probabilities’, ‘swap’, ‘set_matrix_product_state’, ‘r’, ‘switch_case’, ‘t’, ‘h’, ‘initialize’, ‘s’, ‘x’, ‘delay’, ‘set_superop’, ‘sdg’, ‘save_state’, ‘save_statevector’, ‘if_else’, ‘rx’, ‘csx’, ‘rzz’, ‘save_clifford’, ‘cy’, ‘cry’, ‘mcy’, ‘set_statevector’, ‘ecr’, ‘ccz’, ‘mcu2’, ‘for_loop’, ‘u3’, ‘mcx_gray’, ‘mcp’, ‘cp’, ‘rzx’, ‘crz’, ‘set_unitary’, ‘crx’, ‘reset’, ‘cu3’, ‘cu1’, ‘save_expval’, ‘continue_loop’, ‘tdg’, ‘z’, ‘pauli’, ‘mcsx’, ‘mcry’, ‘mcu3’, ‘rz’, ‘kraus’, ‘roerror’, ‘save_unitary’, ‘while_loop’, ‘u2’, ‘save_statevector_dict’, ‘mcu1’, ‘rxx’, ‘unitary’, ‘mcu’, ‘y’, ‘p’, ‘ry’, ‘store’, ‘id’, ‘sx’, ‘cu2’, ‘save_matrix_product_state’, ‘diagonal’, ‘break_loop’, ‘cu’, ‘cx’, ‘save_amplitudes_sq’, ‘mcx’, ‘save_superop’, ‘set_stabilizer’, ‘mcphase’, ‘set_density_matrix’, ‘mcrx’, ‘mcrz’, ‘mcswap’, ‘sxdg’, ‘mcr’, ‘cz’, ‘quantum_channel’, ‘ryy’, ‘qerror_loc’, ‘save_probabilities_dict’, ‘cswap’, ‘multiplexer’, ‘save_amplitudes’, ‘u1’, ‘superop’, ‘ccx’, ‘save_density_matrix’, ‘mcz’, ‘save_stabilizer’, ‘u’, ‘measure’])</p><p>A list of basis gates such as [&#39;cx&#39;, &#39;u&#39;, &#39;measure&#39;, ...]. The exact list may vary but will include the standard basis gates.</p><h3>Transpile with Optimisation Level 0</h3><p>Level 0 performs no optimisation. The circuit is only minimally transformed to match the backend’s basis gates:</p><pre>qc_lv0 = transpile(qc, backend=simulator, optimization_level=0)<br>print(f&quot;Level 0 - Gate count: {qc_lv0.count_ops()}&quot;)<br>print(f&quot;Level 0 - Depth: {qc_lv0.depth()}&quot;)<br>qc_lv0.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMDUdJKB8Vv-_8ic-OtEeg.png" /></figure><p>A circuit diagram where the original gates have been decomposed into the simulator’s basis gates. The gate count will be higher than the original because each custom gate (like cz and ry) is broken down into simpler gates. The depth will also increase.</p><h3>Transpile with Optimisation Level 1</h3><p>Level 1 applies light optimisation. It performs basic gate merging and cancellation:</p><pre>qc_lv1 = transpile(qc, backend=simulator, optimization_level=1)<br>print(f&quot;Level 1 - Gate count: {qc_lv1.count_ops()}&quot;)<br>print(f&quot;Level 1 - Depth: {qc_lv1.depth()}&quot;)<br>qc_lv1.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ra7wua6r4hyQ9RDlvDSkCQ.png" /></figure><p>A circuit diagram that looks cleaner than level 0. Some adjacent gates may have been merged. The gate count and depth should be lower than level 0.</p><h3>Transpile with Optimisation Level 2</h3><p>Level 2 applies heavy optimisation. It performs more aggressive gate merging, commutation, and resynthesis:</p><pre>qc_lv2 = transpile(qc, backend=simulator, optimization_level=2)<br>print(f&quot;Level 2 - Gate count: {qc_lv2.count_ops()}&quot;)<br>print(f&quot;Level 2 - Depth: {qc_lv2.depth()}&quot;)<br>qc_lv2.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kTa824uDKfh3lO-wtQj4hA.png" /></figure><p>A significantly optimised circuit. The gate count and depth should be noticeably lower than level 1. The structure of the circuit may look quite different from the original.</p><h3>Transpile with Optimisation Level 3</h3><p>Level 3 applies even heavier optimisation. It uses the most aggressive optimisation passes available:</p><pre>qc_lv3 = transpile(qc, backend=simulator, optimization_level=3)<br>print(f&quot;Level 3 - Gate count: {qc_lv3.count_ops()}&quot;)<br>print(f&quot;Level 3 - Depth: {qc_lv3.depth()}&quot;)<br>qc_lv3.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lRLjZJm94axQ7fHzxWQr3w.png" /></figure><p>The most optimised version of the circuit. The gate count and depth should be the lowest among all levels. Some gates may have been rearranged or replaced with equivalent but more efficient sequences.</p><h3>Compare the Results Side by Side</h3><p>Let us put all the results together for a clear comparison:</p><pre>print(&quot;=&quot; * 50)<br>print(&quot;Comparison of Optimization Levels&quot;)<br>print(&quot;=&quot; * 50)<br><br>levels = [0, 1, 2, 3]<br>circuits = [qc_lv0, qc_lv1, qc_lv2, qc_lv3]<br><br>for level, circ in zip(levels, circuits):<br>    ops = circ.count_ops()<br>    depth = circ.depth()<br>    print(f&quot;Level {level}: {sum(ops.values())} gates, depth = {depth}&quot;)<br>    print(f&quot;  Gate breakdown: {ops}&quot;)<br>    print()</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UiZNaksi7Sn3wx2QtmpBzQ.png" /></figure><p>A table showing the gate count and depth for each optimisation level. Level 0 will have the highest numbers. Level 3 will have the lowest. The gate breakdown will show which gates are used at each level.</p><h3>Verify the Results Are Correct</h3><p>Transpilation should preserve the functionality of the circuit. Let us verify that all versions produce the same measurement results:</p><pre>shots = 1024<br><br>for level, circ in enumerate([qc_lv0, qc_lv1, qc_lv2, qc_lv3]):<br>    job = simulator.run(circ, shots=shots)<br>    counts = job.result().get_counts()<br>    print(f&quot;Level {level} - Most common outcome: {max(counts, key=counts.get)}&quot;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/381/1*RMG_GMm8ZRGdLa1PXecfrA.png" /></figure><p>All levels should report the same most common outcome (likely &#39;0000&#39; or a similar state), confirming that the optimisation preserved the circuit&#39;s functionality.</p><h3>What We Learned</h3><p>The optimization_level parameter controls how aggressively the transpiler rewrites your circuit. Level 0 gives you a direct translation to the backend’s basis gates with no optimisation. Level 1 applies light optimisation, like gate merging. Level 2 and 3 apply progressively heavier optimisation, reducing gate count and depth at the cost of longer transpilation time.</p><p>The choice of optimisation level depends on your priorities. For small circuits or when debugging, level 0 or 1 is sufficient. For larger circuits where execution time matters, level 2 or 3 can make a meaningful difference.</p><h3>Conclusion</h3><p>The transpiler is an essential tool in the quantum computing workflow. It takes your ideal circuit and adapts it to the constraints of real hardware. The optimization_level setting controls how much effort the transpiler spends rewriting your circuit. Higher levels produce more efficient circuits but take longer to compute. Understanding this tradeoff helps you write better quantum programs.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6f177cf3d92" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Readout Error Mitigation with fitter]]></title>
            <link>https://medium.com/@rahul.techarticles/readout-error-mitigation-with-fitter-8fa3be723be8?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fa3be723be8</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Wed, 12 Aug 2026 03:32:03 GMT</pubDate>
            <atom:updated>2026-08-12T03:32:03.025Z</atom:updated>
            <content:encoded><![CDATA[<h4>Correct measurement errors using M3 mitigation on noisy quantum hardware</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Iu7LZyfL4dw_8S9y-9rD_Q.png" /></figure><p>Quantum computers are inherently noisy devices. One of the most common sources of noise is measurement error. When you measure a qubit, there is a non-zero probability that the readout flips from 0 to 1 or from 1 to 0. These errors can significantly distort your results and lead to incorrect conclusions.</p><p>In this article, we will implement measurement error mitigation using the M3 mitigation method from the mthree library. We will build a calibration matrix, correct our measurement results, and observe improvements in our quantum circuit outcomes.</p><p>We will use a Jupyter Notebook for this tutorial, which you can also run in Google Colab.</p><h3>Setting up the environment</h3><p>First, let us create a virtual environment and install the required packages.</p><pre>python -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate  # On Windows: medium_quantum_venv\Scripts\activate<br>pip install qiskit qiskit-aer mthree matplotlib jupyter</pre><p>Launch Jupyter Notebook:</p><pre>jupyter notebook</pre><p>The mthree library provides an efficient M3 readout error mitigation implementation that works well with Qiskit 2.5.0.</p><h3>Importing the libraries</h3><p>Create a new cell in your Jupyter Notebook and import the necessary modules.</p><pre>from qiskit import QuantumCircuit, transpile<br>from qiskit_aer import AerSimulator<br>from qiskit.visualization import plot_histogram<br>import matplotlib.pyplot as plt<br>import mthree<br>from IPython.display import display</pre><h3>Creating a noisy simulator</h3><p>We will create a noisy simulator with readout errors. The ReadoutError class defines the probability of misreading a qubit state. We apply the same 1-qubit readout error to both qubits.</p><pre>from qiskit_aer import AerSimulator<br>from qiskit_aer.noise import NoiseModel, ReadoutError<br><br>p0given1 = 0.10<br>p1given0 = 0.05<br><br>readout_error = ReadoutError([[1 - p1given0, p1given0], [p0given1, 1 - p0given1]])<br><br>noise_model = NoiseModel()<br><br>for qubit in [0, 1]:<br>    noise_model.add_readout_error(readout_error, [qubit])<br><br>simulator = AerSimulator(noise_model=noise_model)</pre><p>This creates a 2-qubit noise model where:</p><ul><li>There is a 5% chance of reading 1 when the true state is 0</li><li>There is a 10% chance of reading 0 when the true state is 1</li></ul><h3>Building the calibration circuits</h3><p>We use the M3 mitigation class to handle calibration. The mthree.M3Mitigation class takes the simulator as an argument and we calibrate specifically on qubits 0 and 1.</p><pre>mit = mthree.M3Mitigation(simulator)<br>mit.cals_from_system(qubits=[0, 1], shots=1024)<br>print(&quot;Calibration complete.&quot;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/234/1*vv8dcyZGAs5jdogQUKnKdg.png" /></figure><p>The cals_from_system method runs the necessary calibration circuits and builds the calibration matrix internally.</p><h3>Creating a test circuit</h3><p>Now we build a simple circuit that we want to run with error mitigation. This circuit prepares a superposition state on two qubits using Hadamard gates.</p><pre>test_circuit = QuantumCircuit(2, 2)<br>test_circuit.h(0)<br>test_circuit.h(1)<br>test_circuit.measure([0, 1], [0, 1])<br><br>display(test_circuit.draw(&#39;mpl&#39;))</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/305/1*SNnPUPyEkneU4zmcDKN1CA.png" /></figure><p>The circuit diagram will show two Hadamard gates followed by measurement operations on both qubits.</p><h3>Running without mitigation</h3><p>First, let us see the raw results without any error correction.</p><pre>raw_results = simulator.run(test_circuit, shots=1024).result()<br>raw_counts = raw_results.get_counts()<br><br>print(&quot;Raw counts:&quot;, raw_counts)<br>plot_histogram(raw_counts)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/781/1*CSM3TC5LmA122ZVt1_YCeQ.png" /></figure><p>The histogram will show a distribution that is not perfectly uniform due to readout errors. Ideally, with two qubits in superposition, each of the four states (00, 01, 10, 11) should have approximately 256 counts.</p><h3>Applying the mitigation filter</h3><p>Now we apply the M3 correction to our raw counts. The apply_correction method returns the mitigated probabilities, and we can use nearest_probability_distribution to ensure the probabilities sum to one.</p><pre>res = mit.apply_correction(raw_counts, qubits=[0, 1])<br>mit_counts = res.nearest_probability_distribution()<br><br>mit_counts_clean = {k: float(v) for k, v in mit_counts.items()}<br><br>print(&quot;Mitigated probabilities:&quot;, mit_counts_clean)<br>plot_histogram(mit_counts_clean)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0rbVxhbBvB66azrwKZmKuQ.png" /></figure><p>The mitigated results are much closer to the ideal uniform distribution of 0.25 for each state. The error mitigation has effectively corrected the measurement errors.</p><h3>Visualising the corrected results</h3><p>We can also plot the mitigated histogram again for a clearer view.</p><pre>from qiskit.visualization import plot_histogram<br><br>res = mit.apply_correction(raw_counts, qubits=[0, 1])<br>mitigated_dict = {k: float(v) for k, v in res.nearest_probability_distribution().items()}<br><br>fig = plot_histogram(mitigated_dict)<br>display(fig)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*0AimKh3oEvQVPb8aM9DJ6A.png" /></figure><p>A histogram showing the corrected probability distribution with bars of approximately equal height, demonstrating successful error mitigation.</p><h3>Complete code</h3><p>You can find the complete Jupyter Notebook on GitHub:</p><p><a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-23.ipynb">medium_qiskit_quantum/part2_intermediate/article-23.ipynb at main · rahul-gupta-2004/medium_qiskit_quantum</a></p><h3>Conclusion</h3><p>Readout error mitigation is a powerful and straightforward technique to improve the quality of quantum computation results. By building a calibration matrix using simple basis-state preparation circuits, we can correct measurement errors and recover a distribution much closer to the ideal one. The M3 mitigation method from the mthree library provides an efficient and user-friendly way to implement this correction. This approach works well for small numbers of qubits and is an essential tool for anyone working with noisy quantum hardware.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fa3be723be8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[T1 and T2 — How Decoherence Kills Your Circuit]]></title>
            <link>https://medium.com/@rahul.techarticles/t1-and-t2-how-decoherence-kills-your-circuit-61e8cb582aa3?source=rss-47cbf737da60------2</link>
            <guid isPermaLink="false">https://medium.com/p/61e8cb582aa3</guid>
            <category><![CDATA[qiskit]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[quantum-programming]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Rahul Tech Articles]]></dc:creator>
            <pubDate>Tue, 11 Aug 2026 15:42:19 GMT</pubDate>
            <atom:updated>2026-08-11T15:42:19.967Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Model energy relaxation and dephasing, then observe the effect on long circuits.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uqg5qTYLxKRVuA6Hk4B2WQ.png" /></figure><p>In this article, we will build a simple quantum circuit, run it without noise, then add realistic thermal relaxation noise (T1 and T2) and watch how decoherence destroys quantum information. We will compare the results of a short circuit versus a long circuit to see why coherence times matter.</p><p>All code is designed for <strong>Qiskit 2.5.0</strong> and uses AerSimulator directly — no deprecated Sampler primitives. Run this in a Jupyter Notebook or Google Colab for the best experience.</p><h3>Environment Setup</h3><p>Create a virtual environment named medium_quantum_venv</p><p>For Windows:</p><pre>python -m venv medium_quantum_venv<br>medium_quantum_venv\Scripts\activate</pre><p>For macOS/Linux:</p><pre>python3 -m venv medium_quantum_venv<br>source medium_quantum_venv/bin/activate</pre><p>Install the required packages:</p><pre>pip install qiskit==2.5.0 qiskit-aer numpy matplotlib</pre><h3>Import Libraries</h3><p>Create a new Jupyter Notebook cell and run:</p><pre>import numpy as np<br>import matplotlib.pyplot as plt<br>from qiskit import QuantumCircuit, transpile<br>from qiskit_aer import AerSimulator<br>from qiskit_aer.noise import NoiseModel, thermal_relaxation_error<br>from qiskit.visualization import plot_histogram</pre><h3>Build a Simple Circuit</h3><p>We will create a Bell state circuit on 2 qubits. This is a short circuit that maintains entanglement well.</p><pre>qc_short = QuantumCircuit(2, 2)<br>qc_short.h(0)<br>qc_short.cx(0, 1)<br>qc_short.measure([0, 1], [0, 1])<br><br>qc_short.draw(&#39;mpl&#39;)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/369/1*rtwrsqDOmTgQqEOLo2Z6fw.png" /></figure><p>A circuit diagram showing a Hadamard gate on qubit 0, a CNOT gate from qubit 0 to qubit 1, and two measurements.</p><h3>Run Without Noise (Ideal Simulation)</h3><p>First, let us run the circuit on a perfect simulator to see what ideal results look like.</p><pre>simulator = AerSimulator()<br>compiled_short = transpile(qc_short, simulator)<br>result_ideal = simulator.run(compiled_short, shots=1024).result()<br>counts_ideal = result_ideal.get_counts()<br><br>print(&quot;Ideal counts:&quot;, counts_ideal)<br>plot_histogram(counts_ideal)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*pCQ44uh3P9UTRi1aS5NRog.png" /></figure><p>The histogram shows two bars of roughly equal height at 00 and 11. This is the perfect Bell state — the qubits are perfectly entangled.</p><h3>Create a Noise Model with T1 and T2</h3><p>Now we add realistic noise. T1 is the energy relaxation time (how long a qubit stays excited). T2 is the dephasing time (how long quantum phase information survives). Real superconducting qubits have T1 and T2 in the range of tens to hundreds of microseconds.</p><pre>t1 = 50e-6    # 50 microseconds<br>t2 = 30e-6    # 30 microseconds (dephasing limited)<br>gate_time_1q = 50e-9   # 50 nanoseconds for single-qubit gates<br>gate_time_2q = 500e-9  # 500 nanoseconds for two-qubit gates<br><br>noise_model = NoiseModel()<br><br>error_1q = thermal_relaxation_error(t1, t2, gate_time_1q)<br><br>error_2q_single = thermal_relaxation_error(t1, t2, gate_time_2q)<br>error_2q = error_2q_single.tensor(error_2q_single)<br><br>noise_model.add_all_qubit_quantum_error(error_1q, [&#39;h&#39;])<br>noise_model.add_all_qubit_quantum_error(error_2q, [&#39;cx&#39;])</pre><h3>Run the Short Circuit With Noise</h3><pre>noisy_simulator = AerSimulator(noise_model=noise_model)<br>compiled_noisy = transpile(qc_short, noisy_simulator)<br>result_noisy = noisy_simulator.run(compiled_noisy, shots=1024).result()<br>counts_noisy = result_noisy.get_counts()<br><br>print(&quot;Noisy counts (short circuit):&quot;, counts_noisy)<br>plot_histogram(counts_noisy)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*rpOVdQ0brzD7363XLZuW_w.png" /></figure><p>The histogram still shows 00 and 11 as dominant, but now there are small error bars at 01 and 10. The noise has introduced some errors, but the circuit mostly survives because it is short.</p><h3>Build a Long Circuit</h3><p>Now we build a long circuit with many gates. Decoherence accumulates over time, so longer circuits suffer more.</p><pre>qc_long = QuantumCircuit(2, 2)<br>for _ in range(50):<br>    qc_long.h(0)<br>    qc_long.cx(0, 1)<br>qc_long.measure([0, 1], [0, 1])<br><br>qc_long.draw(&#39;mpl&#39;, scale=0.5)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*0BfQcxIBakqadN_np0w1mQ.png" /></figure><p>A dense circuit diagram with 50 repetitions of Hadamard and CNOT gates.</p><h3>Transpile and Run the Long Circuit With Noise</h3><pre>transpiled_circuit_long = transpile(qc_long, simulator)<br>job_long = simulator.run(transpiled_circuit_long, shots=1024)<br>counts_long = job_long.result().get_counts()<br><br>print(&quot;Noisy counts (long circuit):&quot;, counts_long)<br>plot_histogram(counts_long)</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*1RQa2XkJ-dZ--JLAoGtJmA.png" /></figure><p>The histogram is now spread across all four states. The long circuit has lost its quantum information — decoherence has killed the circuit.</p><h3>Compare Side by Side</h3><pre>fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))<br>plot_histogram(counts_noisy, ax=ax1, title=&quot;Short Circuit (50 ns gates)&quot;)<br>plot_histogram(counts_long, ax=ax2, title=&quot;Long Circuit (50 gates)&quot;)<br>plt.show()</pre><p>Expected Output:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*GF17iN_j6VVjVXgy1r-H-w.png" /></figure><p>Two histograms side by side. The left one shows clear dominance of 00 and 11. The right one shows a nearly uniform distribution across 00, 01, 10, and 11 — the quantum state has decohered into a classical mixture.</p><h3>What Just Happened?</h3><p>The short circuit completed before decoherence could destroy the quantum state. The long circuit, however, took much longer to execute. During that time:</p><ul><li>T1 (energy relaxation) caused the excited state |1⟩ to decay to |0⟩.</li><li>T2 (dephasing) destroyed the relative phase between |0⟩ and |1⟩.</li></ul><p>Together, these effects turned our pristine Bell state into a noisy mess. This is why real quantum computers have limited circuit depth — you can only run circuits that finish within the coherence times of the qubits.</p><h3>Complete Jupyter Notebook</h3><p>The complete Jupyter Notebook with all code is available on GitHub:</p><p>GitHub Repository: <a href="https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-22.ipynb">https://github.com/rahul-gupta-2004/medium_qiskit_quantum/blob/main/part2_intermediate/article-22.ipynb</a></p><h3>Conclusion</h3><p>T1 and T2 are the fundamental limits of quantum computing. Energy relaxation (T1) and dephasing (T2) kill quantum information over time. Short circuits survive, long circuits do not. By modelling these effects with AerSimulator and thermal_relaxation_error, we can predict how circuits will behave on real hardware. Always design your quantum algorithms to finish well within the coherence times of your qubits.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61e8cb582aa3" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>