0
$\begingroup$

For educational purposes, I am looking for a simulator written in pure python.

It may use scientific-python libraries such as numpy to exploit the data structures they provide, but the core algorithms should be written on top of these libraries.

$\endgroup$

1 Answer 1

2
$\begingroup$

There is code to apply single-qubit gates and controlled gates here:

Depending on endianess, you may have to adjust index. The type of self in this code is just a wrapper around numpy's ndarray class with added properies to compute the number of qubits (nbits)

  def apply1(self, gate, index) -> None:
    """Apply single-qubit gate to this state."""

    # To maintain qubit ordering in this infrastructure,
    # index needs to be reversed.
    #
    index = self.nbits - index - 1
    two_q = 1 << index
    g00 = gate[0, 0]
    g01 = gate[0, 1]
    g10 = gate[1, 0]
    g11 = gate[1, 1]
    for g in range(0, 1 << self.nbits, 1 << (index+1)):
      for i in range(g, g + two_q):
        t1 = g00 * self[i] + g01 * self[i + two_q]
        t2 = g10 * self[i] + g11 * self[i + two_q]
        self[i] = t1
        self[i + two_q] = t2

  def applyc(self, gate, control, target) -> None:
    """Apply a controlled 2-qubit gate via explicit indexing."""

    # To maintain qubit ordering in this infrastructure,
    # index needs to be reversed.
    qbit = self.nbits - target - 1
    two_q = 2**qbit
    control = self.nbits - control - 1
    g00 = gate[0, 0]
    g01 = gate[0, 1]
    g10 = gate[1, 0]
    g11 = gate[1, 1]
    for g in range(0, 1 << self.nbits, 1 << (qbit+1)):
      idx_base = g * (1 << self.nbits)
      for i in range(g, g + two_q):
        idx = idx_base + i
        if idx & (1 << control):
          t1 = g00 * self[i] + g01 * self[i + two_q]
          t2 = g10 * self[i] + g11 * self[i + two_q]
          self[i] = t1
          self[i + two_q] = t2
```
$\endgroup$
1
  • $\begingroup$ Great repo. Thanks. $\endgroup$
    – MonteNero
    Jan 24, 2023 at 6:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.