pyquil icon indicating copy to clipboard operation
pyquil copied to clipboard

There are too many ways to construct a Program

Open karalekas opened this issue 5 years ago • 3 comments

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!

karalekas avatar Apr 18 '19 18:04 karalekas

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.

perak avatar May 15 '19 20:05 perak

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

notmgsk avatar May 15 '19 21:05 notmgsk

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

joshcombes avatar May 27 '19 04:05 joshcombes