rigetti / pyquil

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

Expressions are parsed incorrectly by Defgate #1734

Closed bramathon closed 3 months ago

bramathon commented 5 months ago

Code Snippet

import numpy as np
from pyquil.quilbase import DefGate
from pyquil.quilatom import quil_exp, Parameter

phi = Parameter("phi")

rz = np.array(
    [
        [quil_exp(-1j*phi/2), 0],
        [0, quil_exp(+1j*phi/2)],
    ]
)

print(DefGate(name="blarg", matrix=rz, parameters=[phi]))

rz2 = np.array(
    [
        [quil_exp(-1j*phi/2)*np.exp(1j*np.pi/4), 0],
        [0, quil_exp(+1j*phi/2)*np.exp(1j*np.pi/4)],
    ]
)

print(rz2[0,0])
print(DefGate(name="blarg", matrix=rz2, parameters=[phi]))

Error Output

The first defgate outputs as expected.

The second output is the expression, EXP(-i*%phi/2)*0.7071067811865476+0.7071067811865475i While the expression is ambiguous, a closer look reveals that it is structured correctly: Mul(Function('EXP',Div(Mul((-0-1j),Parameter('phi')),2),<ufunc 'exp'>),(0.7071067811865476+0.7071067811865475j)) The exponential is multiplied by the complex number.

In the defgate, it's clear this is not the case. The expression is the exponential multiplied by the real part of the complex number, while the imaginary part is then added after the fact. Ie:

(a+bi)*exp(theta)

vs

a*exp(theta) + bi

A closer look at the matrix reveals this to be the case:

Add(Mul(Function('EXP',Div(Mul((-0-1j),Parameter('phi')),(2+0j)),<ufunc 'exp'>),(0.7071067811865476+0j)),0.7071067811865475j)

DEFGATE blarg(%phi) AS MATRIX:
    exp((-1.0i*%phi)/2), 0
    0, exp((1.0i*%phi)/2)

EXP(-i*%phi/2)*0.7071067811865476+0.7071067811865475i
DEFGATE blarg(%phi) AS MATRIX:
    (exp((-1.0i*%phi)/2)*0.7071067811865476)+0.7071067811865475i, 0
    0, (exp((1.0i*%phi)/2)*0.7071067811865476)+0.7071067811865475i
bramathon commented 4 months ago

Possibly related to https://github.com/rigetti/pyquil/issues/1682