rigetti / pyquil

A Python library for quantum programming using Quil.
http://docs.rigetti.com
Apache License 2.0
1.4k stars 341 forks source link

Bit indices reversed from bit_string_probabilities to measured #8

Closed vontell closed 7 years ago

vontell commented 7 years ago

When running the following code, there are some conflicting results:

def test():

  qvm = forest.Connection()
  p = Program()

  p.inst(X(0))
  p.inst(X(1))
  p.inst(I(2))

  print qvm.bit_string_probabilities(p)
  print qvm.wavefunction(p)[0]
  p.measure(0, 0).measure(1, 1).measure(2, 2)

  print p
  return qvm.run(p, range(3))

print test()

I would expect this piece of code to transform my initial | 000 > state into | 110 >. The final result of running and measuring this code does return this result, but qvm.bit_string_probabilities(p) and print qvm.wavefunction(p)[0] do not have what I expect:

{'010': 0.0, '011': 1.0, '001': 0.0, '000': 0.0, '111': 0.0, '110': 0.0, '100': 0.0, '101': 0.0}
[ 0.+0.j  0.+0.j  0.+0.j  1.+0.j  0.+0.j  0.+0.j  0.+0.j  0.+0.j]

The ordering of the bits seems to be off; instead of 110 having an amplitude/probability of 1, 011 has an amplitude/probability of 1. After trying this out on a few other qubit variations, it seems that the results are reversed.

stylewarning commented 7 years ago

Hello! Thanks for the report.

The qubit indexes in Quil correspond to the exponents in the binary expansion of the basis index. Or, in other words, you should read the binary numbers right-to-left. So

X 0
X 1

would be the |011> state, because

011 (binary) = 3 (decimal) = 0*2^2 + 1*2^1 + 1*2^0

The exponents of the radix 2 are precisely the qubit indexes.

It is important to note that some sciences do use other conventions here, which is important to be mindful of when writing Quil.

vontell commented 7 years ago

Ah of course; thanks for the clarification!

stylewarning commented 7 years ago

No problem. I might add that this is a good convention to follow because, were we to do it left-to-right, the basis elements would change if you add a qubit to the system. The index of the |1> state in a 1-qubit system is the same as the index of the |0001> state in a 4-qubit system. In the left-to-right scheme, we would have |1> be indexed by 1, but |1000> be indexed by 8, which seems silly. :)