rigetti / pyquil

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

There are too many ways to construct a Program #884

Open karalekas opened 5 years ago

karalekas commented 5 years ago

In the pyQuil documentation for "Programs and Gates", we see snippets like this:

import numpy as np

from pyquil import Program
from pyquil.gates import RX, RZ, MEASURE

qubit = 0

p = Program()
ro = p.declare("ro", "BIT", 1)
theta_ref = p.declare("theta", "REAL")

p += RX(np.pi / 2, qubit)
p += RZ(theta_ref, qubit)
p += RX(-np.pi / 2, qubit)

p += MEASURE(qubit, ro[0])

Which seem to imply that we are pushing the += <PYQUIL_OBJECT> method of building out Program objects as the recommended way. However, there are other spots in the source, docs, and examples, where other forms of program construction are used. These include:

  1. p.inst(X(0))
  2. p.inst("X 0")
  3. p = Program(X(0))
  4. p = Program("X 0")
  5. p += "X 0"
  6. p += Program(X(0)) etc.

We as pyQuil developers / maintainers feel that this is simply too many ways to do the same thing, and is a source of confusion. We would like to funnel all program construction toward one canonical/supported way of doing so.

My vote would be for the += <PYQUIL_OBJECT> method, but there are some caveats to this. There are specialized methods on the Program object, and some can easily be replaced by the += approach. Others, like the declare method or ones that add control flow, are not as easily swapped out.

For example, the declare method returns a MemoryReference that we use when adding MEASURE instructions:

p = Program()
ro = p.declare("ro", "BIT")
p += MEASURE(0, ro[0])

# replaced by

p = Program()
p += Declare("ro", "BIT")
ro = MemoryReference("ro")
p += MEASURE(0, ro[0])

In addition, the control flow methods like if_then are convenient, as they handle the different jump statements for you. However, there is probably a way unify everything into the += approach, so we are looking for input / suggestions based off of what people prefer to use, before we settle on one!

perak commented 5 years ago

I vote for .inst() or anything else but not +=. I am also not super-happy with p.inst("X 0").

I had difficulties with this while writing pyquil parser.

notmgsk commented 5 years ago

IMO += feels natural because a Program object is like a list in others ways (e.g. can be subscripted).

joshcombes commented 5 years ago

I have a preference for += as it is a lot less typing and (IMHO) easier to read.