<?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 Pablo E Cingolani on Medium]]></title>
        <description><![CDATA[Stories by Pablo E Cingolani on Medium]]></description>
        <link>https://medium.com/@pablo.e.cingolani?source=rss-d60e7152751------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*EHPd2KwfTrYfP7PKHf8Piw.jpeg</url>
            <title>Stories by Pablo E Cingolani on Medium</title>
            <link>https://medium.com/@pablo.e.cingolani?source=rss-d60e7152751------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 21:35:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@pablo.e.cingolani/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[Quantum Computer simulator from scratch]]></title>
            <link>https://medium.com/@pablo.e.cingolani/quantum-computer-simulator-from-scratch-9e5e5e1e973d?source=rss-d60e7152751------2</link>
            <guid isPermaLink="false">https://medium.com/p/9e5e5e1e973d</guid>
            <category><![CDATA[simulator]]></category>
            <category><![CDATA[quantum-computer]]></category>
            <category><![CDATA[qubit]]></category>
            <category><![CDATA[simulation]]></category>
            <category><![CDATA[quantum-computing]]></category>
            <dc:creator><![CDATA[Pablo E Cingolani]]></dc:creator>
            <pubDate>Thu, 06 Jan 2022 18:04:23 GMT</pubDate>
            <atom:updated>2022-01-07T11:03:54.090Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yUiXq7u_9JOhii5c" /><figcaption>Photo by <a href="https://unsplash.com/@dancristianp?utm_source=medium&amp;utm_medium=referral">Dan-Cristian Pădureț</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In less than one hour.</p><p>The basic <a href="https://andisama.medium.com/embarking-on-a-journey-to-quantum-computing-without-physics-degree-4f22a1fb6a2b">principles of Quantum Computing</a> are quite simple, and coding a naive “Quantum Computer simulator” is a great way to have a good grasp of the fundamentals.</p><p>Obviously, you can use great quantum computing software packages such as <a href="https://qiskit.org/">Qiskit</a>, <a href="https://quantumai.google/cirq">Cirq</a>, or <a href="https://quantum-computing.ibm.com/">IBM Quantum</a>. All of them are highly optimized and extremely flexible, but here we are coding this simulator for educational purposes, so we focus on simplicity. The project is roughly 200 lines of code and it is available on <a href="https://github.com/pcingola/quantum_computer_simulator/blob/main/quantum_simulator.ipynb">GitHub</a>.</p><h3>The setup</h3><p>I’m using a Python, Jupyter notebook, and Numpy in a Conda environment, so my setup process looks like this:</p><pre># Create a Conda environment and add packages<br>conda create -y --name quantum_computer_simulator<br>conda activate quantum_computer_simulator<br>conda install -y pip ipykernel numpy</pre><pre># Add environment to conda<br>ipython kernel install --user --name=quantum_computer_simulator</pre><pre># Start jupyter<br>jupyter-lab</pre><p>Now, once you are in a Jupyter notebook, let’s add some imports:</p><pre>import numpy as np<br>import string</pre><p>Then we’ll create a class for our simulator</p><pre>class QuantumComputer:<br>    &quot;&quot;&quot;<br>    Implement a naive quantum computer simulator<br>    &quot;&quot;&quot;</pre><p>From now on, we’ll be adding all the methods to this class, so the rest of the code in this article is inside this QuantumComputerclass.</p><h3>From Quantum Postulates to code</h3><p>There are four <em>Quantum Computing postulates</em>, which we can translate very easily into the code for our QuantumComputerclass.</p><blockquote><strong>Postulate 1:</strong> The state of a quantum system is a unit vector in a Hilbert space</blockquote><p>Simply put, the state of a quantum computer is a vector of complex numbers (in a <a href="https://en.wikipedia.org/wiki/Hilbert_space">Hilbert space</a>) that has norm one (unit vector). The smallest state vector is a two-dimensional complex vector, which is called a <a href="https://en.wikipedia.org/wiki/Qubit">Qubit</a> (short for <em>“Quantum bit”</em>).</p><p>So, now that we know a qubit is a vector of two complex numbers, how do we combine multiple qubits? That’s the next postulate</p><blockquote><strong>Postulate 2:</strong> The system’s state is a tensor product of individual states</blockquote><p>To create a state for an <em>n-qubit</em> quantum computer, we need to combine multiple qubits in a tensor, adding one dimension per qubit. This means that the state’s shape for a one-qubit system is [2], for a two-qubit system is [2, 2], for a three-qubit system is [2, 2, 2], and for n-qubit would be [2] * n (using a pythonic notation). In our QuantumComputer class, we call the state tensor psi (i.e. the greek letter ψ), and the code for initializing it is:</p><pre><strong>def</strong> __init__(self, num_qubits):<br>    self<strong>.</strong>num_qubits <strong>=</strong> num_qubits<br>    self<strong>.</strong>psi <strong>=</strong> np<strong>.</strong>zeros([2] <strong>*</strong> num_qubits, dtype<strong>=</strong>complex)<br>    self<strong>.</strong>psi<strong>.</strong>flat[0] <strong>=</strong> 1<br></pre><p>We have a QuantumComputer in an initialized state, how do we change the state to make “quantum programs”? The next postulate tells us how the system evolves.</p><blockquote><strong>Postulate 3</strong>: State evolution is unitary</blockquote><p>The evolution of a quantum system is simply a <a href="https://en.wikipedia.org/wiki/Unitary_matrix">Unitary matrix</a> operating on the state tensor. Some of these unitary matrices are well-known “<a href="https://en.wikipedia.org/wiki/Quantum_logic_gate">quantum logic gates</a>” that operate on one, two, or more qubits. For simplicity, here we will only focus on one and two-qubit gates.</p><h4>One-Qubit gates</h4><p>To implement a one-qubit gate, we need to multiply a unitary 2x2 complex matrix (the quantum gate) by the state tensor. Fortunately, NumPy has the <a href="https://numpy.org/doc/stable/reference/generated/numpy.einsum.html">Einstein summation</a> function np.einsumwhich allows us to do this.</p><p>The slightly confusing part of np.einsum is to keep track of the tensor indices. As an example, let’s say we have a 5-qubit system, the state will be a tensor in five dimensions psi[a, b, c, d, e]. Imagine that we want to apply a one-qubit gate U[y, z] to qubit number 3 (i.e. the one indexed by c in psi). So the np.einsum command to update the state tensor psiwould be:</p><pre>psi = np.eisum(&quot;yz, ab<strong>z</strong>de -&gt; ab<strong>y</strong>de&quot;, U, psi)</pre><p>This performs a <a href="https://en.wikipedia.org/wiki/Kronecker_product">Kronecker product</a> that acts only on the third qubit, i.e. the one indexed by c. To understand how this is done, let’s take a look at the “subscript” parameter yz, ab<strong>z</strong>de -&gt; ab<strong>y</strong>de. On the left-hand side (before the arrow -&gt;), we have indices for U and psi respectively, and on the right-hand side, we have the output indices. On the left-hand side, we replaced psi&#39;s index for the third qubit from c by z, so instead of abcde it reads ab<strong>z</strong>de. Similarly, for the right-hand side, we replaced psi&#39;s index c by the matrix index y, so it reads ab<strong>y</strong>de (instead of abcde).</p><p>Once we understand the notation for Einstein summations in NumPy, all we have to do is write a simple method to generalize how we apply one-qubit gates. First, we have a method for creating np.einsumsubscripts for qubit number n, and then apply an Einstein summation to the unitary matrix U and the state tensor psi:</p><pre><strong>def</strong> eins_vars(self, n, char1):<br>  eins <strong>=</strong> list(string<strong>.</strong>ascii_lowercase[:self<strong>.</strong>num_qubits])<br>  eins[n] <strong>=</strong> char1<br>  <strong>return</strong> &#39;&#39;<strong>.</strong>join(eins)</pre><pre><strong>def</strong> apply_one_qubit_gate(self, U, n):<br>  subs <strong>=</strong> f&quot;yz , {self<strong>.</strong>eins_vars(n, &#39;z&#39;)} -&gt; {self<strong>.</strong>eins_vars(n, &#39;y&#39;)}&quot;<br>  self<strong>.</strong>psi <strong>=</strong> np<strong>.</strong>einsum(subs, U, self<strong>.</strong>psi)</pre><p>Now we have this code to apply any unitary matrix to a single qubit. We can easily implement some of the well-known one-qubit gates, such as <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli_gates_(X,Y,Z)">Pauli-X (</a><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli_gates_(X,Y,Z)">x), Pauli-Y (</a><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli_gates_(X,Y,Z)">y), Pauli-Z (</a><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Pauli_gates_(X,Y,Z)">z)</a>, <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_gate">Hadamard (</a><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_gate">h)</a>, Phase (s), π/8 gate (t), and the <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Square_root_of_NOT_gate_(%E2%88%9ANOT)">“Square root of X” gate (</a><a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Square_root_of_NOT_gate_(%E2%88%9ANOT)">sx)</a>. First, let’s define the unitary matrices for each one:</p><pre>IDENTITY = np.array([[1, 0],[0, 1]])<br>SIGMA_X = np.array([[0, 1],[1, 0]])<br>SIGMA_Y = np.array([[0, -1j],[1j, 0]])<br>SIGMA_Z = np.array([[1, 0],[0, -1]])<br>HADAMARD = 1/np.sqrt(2) * np.array([[1, 1],[1, -1]])<br>S_GATE = np.array([[1, 0], [0, 1j]])<br>T_GATE = np.array([[1, 0], [0, EIPIO4]])<br>SX_GATE = 1/2 * np.array([[1 + 1j, 1 - 1j], [1 - 1j, 1 + 1j]])</pre><p>Add a method for each gate to our QuantumComputerclass is trivial. The code just calls apply_one_qubit_gate with the appropriate matrix:</p><pre>def s(self, n):<br>        self.apply_one_qubit_gate(S_GATE, n)</pre><pre>def sx(self, n):<br>        self.apply_one_qubit_gate(SX_GATE, n)</pre><pre>def t(self, n):<br>        self.apply_one_qubit_gate(T_GATE, n)<br>    <br>def x(self, n):<br>        self.apply_one_qubit_gate(SIGMA_X, n)</pre><pre>def y(self, n):<br>        self.apply_one_qubit_gate(SIGMA_Y, n)</pre><pre>def z(self, n):<br>        self.apply_one_qubit_gate(SIGMA_Z, n)</pre><h4>Two-Qubit gates</h4><p>Implementing two-qubit gates is an extension of the previous method used for one-qubit gates. We also perform an Einstein summation with the appropriate subscripts. Using our previous example of a 5-qubit system with a state psi[a, b, c, d, e], and a two-qubit gate descrived by the unitary tensor U[w, x, y, z], if we want to apply the two-qubit gate to qubits 2 and 3, the Einstein sum would be:</p><pre>np.eisum(&quot;wxyz, a<strong>yz</strong>de -&gt; a<strong>wx</strong>de&quot;, U, self.psi)</pre><p>Note that, similarly to what we did in the one-qubit gate case, we replace the indexes for qubits 2 and 3 (indexed by b and c) by the indices from the unitary gate y and z on the left-hand side, and indices w and x for the right-hand side.</p><p>The code to generate these indices and apply the Einstein sums looks quite similar to the previous one. Note that we extended eins_vars to handle two qubits and added a method apply_two_qubit_gate:</p><pre>def eins_vars(self, n0, char1, n1=None, char2=&#39;&#39;):<br>  eins = list(string.ascii_lowercase[:self.num_qubits])<br>  eins[n0] = char1<br>  if n1 is not None:<br>    eins[n1] = char2<br>  return &#39;&#39;.join(eins)</pre><pre>def apply_two_qubit_gate(self, U, n0, n1):<br>  subscripts = f&quot;wxyz , {self.eins_vars(n0, &#39;y&#39;, n1, &#39;z&#39;)} -&gt; {self.eins_vars(n0, &#39;w&#39;, n1, &#39;x&#39;)}&quot;<br>  self.psi = np.einsum(subscripts, U, self.psi)</pre><p>We can define the unitary tensors for some well known two-qubit gates, such as <a href="https://en.wikipedia.org/wiki/Quantum_logic_gate#Controlled_gates">“controlled not” (CNOT), and “controlled Z” (CZ)</a>:</p><pre>CNOT = np.array([<br>                [[[1, 0], [0, 0]], <br>                 [[0, 1], [0, 0]]], <br>                [[[0, 0], [0, 1]],<br>                 [[0, 0], [1, 0]]]<br>                ])</pre><pre>CZ = np.array([<br>                [[[1, 0], [0,  0]], <br>                 [[0, 1], [0,  0]]],<br>                [[[0, 0], [1,  0]],<br>                 [[0, 0], [0, -1]]]<br>                ])</pre><p>And now we can define the methods for two-qubit gates, which just apply the correct unitary tensor to two qubits (n0and n1):</p><pre>def cx(self, n0, n1):<br>  self.apply_two_qubit_gate(CNOT, n0, n1)</pre><pre>def cz(self, n0, n1):<br>  self.apply_two_qubit_gate(CZ, n0, n1)</pre><h4>Measurement</h4><p>We have a QuantumComputer class that can apply one and two-qubit gates. Now we can add methods to simulate quantum measurement of qubits. This brings us to the next postulate:</p><blockquote><strong>Postulate 4:</strong> Measurement is a projection operator into probabilities, changing the state</blockquote><p>This means that the complex amplitudes of the state tensor determine the probabilities of whether measuring a qubit would result in state “0” or state “1”. So our simulator has to calculate the probabilities for each qubit’s state 0 and state 1, and then “flip a coin” using those probabilities.</p><p><strong>From state to probabilities:</strong> In order to calculate the probabilities for qubit n, we need to sum over all the absolute tensor values squared for qubit n. How do we do it? Well, you probably guessed it, np.einsum can do the trick. Going back to our previous 5-qubit example system, let’s say we want to measure qubit number 3, then we can calculate the sum over the square of the absolute values of the state tensor, which is equivalent to applying the identity matrix to a vector of absolute values squared:</p><pre>psi_p = np.square(np.abs(psi))<br>p = np.einsum(&quot;yz, ab<strong>z</strong>de -&gt; y&quot;, IDENTITY, psi_p)</pre><p>The sum over all tensor indices results in a vector of two real numbers [P₀, P₁] representing the probabilities of measuring states “0” and “1” of the qubit. The general code would be:</p><pre>def probabilities(self, n):<br>  subscripts = f&quot;yz , {self.eins_vars(n, &#39;z&#39;)} -&gt; y&quot;<br>  psi_p = np.square(np.abs(self.psi))<br>  p = np.einsum(subscripts, IDENTITY, psi_p)<br>  return p</pre><p><strong>From probabilities to measurement:</strong> Now that we have the probabilities, we can simulate a measurement by a random number with probabilities [P₀, P₁].</p><p><strong>State update after measurement:</strong> After the qubit measurement is performed, we must update the state tensor. There are two parts in this process:</p><ul><li>All states not compatible with our measurement must be set to zero. In our 5-qubit example system, if the outcome of our measurement for qubit number 3 was 1, then we need to reset all psi’s entries where qubit number 3 is different than 1(i.e. equal to 0). We can do it like this:</li></ul><pre>psi[:, :, 0, :, :] = 0</pre><ul><li>The state tensor has to be re-normalized so that the vector is still unitary, in NumPy this is simply:</li></ul><pre>psi = psi / np.linalg.norm(psi)</pre><p>OK, let’s put all this together in the measurement methods:</p><pre>def measure(self, n):<br>  p = self.probabilities(n)<br>  r = np.random.rand()<br>  bit = 0 if r &lt;= p[0] else 1<br>  self._update_psi(n, bit, p)<br>  return bit</pre><pre>def probabilities(self, n):<br>  subscripts = f&quot;yz , {self.eins_vars(n, &#39;z&#39;)} -&gt; y&quot;<br>  psi_p = np.square(np.abs(self.psi))<br>  p = np.einsum(subscripts, IDENTITY, psi_p)<br>  return p</pre><pre>def _update_psi(self, n, bit, p):<br>  idx =  [slice(0, 2)] * self.num_qubits <br>  idx[n] = 1 - bit # Set index &#39;n&#39; as the negation of &#39;bit&#39;<br>  self.psi[ tuple(idx) ] = 0 # Reset amplitudes<br>  self.psi = self.psi / np.linalg.norm(self.psi) # Re-normalize psi</pre><h3>Using the Quantum Simulator</h3><p>Our QuantumComputer class is finished and we can try some simple quantum circuits. Let’s try two entangled qubits</p><pre># Circuit for two entangled qubits (Bell state)<br>qc = QuantumComputer(2)<br>qc.h(0)<br>qc.cnot(0, 1)</pre><p>The final state of this entanglement circuit is:</p><pre>Number of Qubits: 2<br>psi:<br>	|00&gt; : (0.7071067811865475+0j)<br>	|01&gt; : 0j<br>	|10&gt; : 0j<br>	|11&gt; : (0.7071067811865475+0j)</pre><p>which corresponds to the well-known Φ⁺ <a href="https://en.wikipedia.org/wiki/Bell_state">Bell state</a>.</p><p>In the <a href="https://github.com/pcingola/quantum_computer_simulator/blob/main/quantum_simulator.ipynb">GitHub</a> repository, you can find the full code as well as many test cases including a “random quantum circuit generator” that can be used to test and compare results to other platforms.</p><p>Enjoy!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9e5e5e1e973d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>