5
$\begingroup$

I'm just wondering how one should go about using parametrised values and the Symbol object that gets resolved at runtime?

For example, if I would like to implement the gate $R_x(\theta) = e^{-i\theta/2}$, but would like to leave $\theta$ as a Symbol to be resolved at the end of the simulation, what would be the best way to do this?

Thanks in advance for any answers :)

$\endgroup$

1 Answer 1

3
$\begingroup$

In the current release of Cirq (0.4.0) there is a strong limitation on symbols: you can't scale them or add them (Why? We were worried about being pulled down the rabbit hole of implementing a whole symbolic algebra system.). Making matters worse, Cirq internally works in radians divided by pi to avoid some minor sources of floating point error. So when you write cirq.Rx(cirq.Symbol("θ")) it internally attempts to scale the argument, and you get an error about multiplication/division not being supported for symbols.

There is an active pull request to fix this by delegating all symbolic work to sympy. Once that's merged, the next release will allow you to write cirq.Rx(sympy.Symbol("θ")) whereas currently you can only use symbols in exponents e.g. cirq.X**cirq.Symbol("t").

So, currently in 0.4.0, you can do this:

import cirq
import matplotlib.pyplot as plt

q = cirq.LineQubit(0)
circuit = cirq.Circuit.from_ops(
    cirq.X(q)**cirq.Symbol('angle_over_pi'),
    cirq.measure(q),
)
results = cirq.Simulator().run_sweep(
    circuit,
    params=cirq.Linspace(key='angle_over_pi', start=0, stop=2, length=20),
    repetitions=1000)

plt.plot([r.histogram(key=str(q))[1] for r in results])
plt.show()

rabi oscillation

But you'll need to wait until 0.5.0 to be able to do this extremely similar thing using Rx instead of X** and sympy.Symbol instead of cirq.Symbol (which will be gone):

import cirq
import matplotlib.pyplot as plt
import numpy as np

q = cirq.LineQubit(0)
circuit = cirq.Circuit.from_ops(
    cirq.Rx(sympy.Symbol('rads')).on(q),
    cirq.measure(q),
)
results = cirq.Simulator().run_sweep(
    circuit,
    params=cirq.Linspace(key='rads', start=0, stop=2*np.pi, length=20),
    repetitions=1000)

plt.plot([r.histogram(key=q)[1] for r in results])
plt.show()
$\endgroup$
1
  • $\begingroup$ Thank you, that clears everything up for me! $\endgroup$
    – QC90
    Feb 16, 2019 at 13:21

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.