0

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.

Abdullah Khalid
  • 1,783
  • 6
  • 17

1 Answers1

2

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

```

rhundt
  • 988
  • 4
  • 12