dwavesystems / dwave-gate

dwave-gate is a software package for constructing, modifying and running quantum circuits on the provided state-vector simulator.
Apache License 2.0
12 stars 7 forks source link

Bikeshedding: accept named parameters in ParametricCircuit #27

Open boothby opened 1 year ago

boothby commented 1 year ago

From 3_parametric_circuits.py

rot_circuit = ParametricCircuit(1)
with rot_circuit.context as (p, q, c):
    ops.RZ(p[0], q[0])
    ops.RY(p[1], q[0])
    ops.RZ(p[2], q[0])

...

MyRotOperation([3 * np.pi / 2, np.pi / 2, np.pi], q[2])

As Andrew Berkeley pointed out in a meeting yesterday, it might be nice to allow named parameters. I'm not sure of the best interface for this, but here's some slightly rambly thoughts.

Defining the parametric circuit already uses syntactic sugar; that can be extended through __getattr__:

#maximum sweetness
circuit = ParametricCircuit(1)
with rot_circuit.context as (p, q, c):
    ops.RZ(p.dz0, q[0])
    ops.RY(p.dy, q[0])
    ops.RZ(p.dz1, q[0])

#less sugar
circuit = ParametricCircuit(1)
with rot_circuit.context as (p, q, c):
    ops.RZ(p['dz0'], q[0])
    ops.RY(p['dy'], q[0])
    ops.RZ(p['dz1'], q[0])

Applying the operator then suffers a bit -- named parameters must follow positional arguments. We can work around this by providing a dict:

MyRotOperation(dict(dz0=3 * np.pi / 2, dy=np.pi / 2, dz1=np.pi), q[2])

But the circuit definition does not forbid a mix of positional and named operations! If support named parameters is a popular idea, I might suggest not supporting the notation above, nor the extant

MyRotOperation([3 * np.pi / 2, np.pi / 2, np.pi], q[2])

Rather than expect an array of parameters and allow the application of the operator in the same call, we could force the user to curry the parameters separately:

#positional only
MyRotOperation(3 * np.pi / 2, np.pi / 2, np.pi)(q[2])

#named only
MyRotOperation(dz0=3 * np.pi / 2, dy=np.pi / 2, dz1=np.pi)(q[2])

#mixed named and positional
MyRotOperation(3 * np.pi / 2, np.pi / 2, dz1=np.pi)(q[2])

Now, if we do want to forbid the mix of named and positional arguments, we could take an optional parameter:

# list of params
rot_circuit = ParametricCircuit(1) #default: params=list
rot_circuit = ParametricCircuit(1, params=list)  #explicit
with rot_circuit.context as (p, q, c):
    ops.RZ(p[0], q[0])
    ops.RY(p[1], q[0])
    ops.RZ(p[2], q[0])
...
MyRotOperation([3 * np.pi / 2, np.pi / 2, np.pi], q[2])

#dict of params
circuit = ParametricCircuit(1, params=dict)
with rot_circuit.context as (p, q, c):
    ops.RZ(p.dz0, q[0])
    ops.RY(p.dy, q[0])
    ops.RZ(p.dz1, q[0])
...
MyRotOperation({'dz0': 3 * np.pi / 2, 'dy': np.pi / 2, 'dz1': np.pi}, q[2])