Skip to content

Commit 4e65c20

Browse files
authored
Add cirq.symbol function to create a sympy.Symbol. (#7853)
It is very common in "hello world" examples of sweeps to use symbols to parameterize a circuit, for example I often do something like a rabi circuit: cirq.Circuit(cirq.X(q)**sympy.Symbol("x"), cirq.M(q)) With this change, such a circuit can be constructed after importing cirq only, without also needing to import sympy: cirq.Circuit(cirq.X(q)**cirq.symbol("x"), cirq.M(q)) Note that for this particular case, we could also change gate and op exponentiation to accept a str and convert to symbol, but having a `symbol` helper function covers any symbol use, not just this particular case.
1 parent ef5e2f7 commit 4e65c20

4 files changed

Lines changed: 17 additions & 0 deletions

File tree

cirq-core/cirq/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -520,6 +520,7 @@
520520
Product as Product,
521521
Sweep as Sweep,
522522
Sweepable as Sweepable,
523+
symbol as symbol,
523524
to_resolvers as to_resolvers,
524525
to_sweep as to_sweep,
525526
to_sweeps as to_sweeps,

cirq-core/cirq/study/__init__.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
ParamMappingType as ParamMappingType,
2727
ParamResolver as ParamResolver,
2828
ParamResolverOrSimilarType as ParamResolverOrSimilarType,
29+
symbol as symbol,
2930
)
3031

3132
from cirq.study.sweepable import (

cirq-core/cirq/study/resolver.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,15 @@
4848
_RECURSION_FLAG = object()
4949

5050

51+
def symbol(name: str) -> sympy.Symbol:
52+
"""Creates a sympy Symbol for use in sweeps.
53+
54+
We export this from cirq to allow constructing basic parametrizable objects
55+
without additional imports beyond cirq itself.
56+
"""
57+
return sympy.Symbol(name)
58+
59+
5160
class ParamResolver:
5261
"""Resolves parameters to actual values.
5362

cirq-core/cirq/study/resolver_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,12 @@
2525
import cirq
2626

2727

28+
def test_symbol() -> None:
29+
x = cirq.symbol("x")
30+
assert isinstance(x, sympy.Symbol)
31+
assert str(x) == "x"
32+
33+
2834
@pytest.mark.parametrize(
2935
'val',
3036
[

0 commit comments

Comments
 (0)