Skip to content

Commit 8750312

Browse files
convert ExpressionConvertible to duration as well (#86)
Co-authored-by: Phil Reinhold <[email protected]>
1 parent bc9382c commit 8750312

File tree

2 files changed

+16
-6
lines changed

2 files changed

+16
-6
lines changed

oqpy/timing.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -72,19 +72,19 @@ def convert_float_to_duration(time: AstConvertible, require_nonnegative: bool =
7272
if require_nonnegative and time < 0:
7373
raise ValueError(f"Expected a non-negative duration, but got {time}")
7474
return OQDurationLiteral(time)
75+
if hasattr(time, "_to_oqpy_expression"):
76+
time = cast(ExpressionConvertible, time)
77+
time = time._to_oqpy_expression()
78+
if hasattr(time, "_to_cached_oqpy_expression"):
79+
time = cast(CachedExpressionConvertible, time)
80+
time = time._to_cached_oqpy_expression()
7581
if isinstance(time, OQPyExpression):
7682
if isinstance(time.type, (ast.UintType, ast.IntType, ast.FloatType)):
7783
time = time * OQDurationLiteral(1)
7884
elif not isinstance(time.type, ast.DurationType):
7985
raise TypeError(f"Cannot convert expression with type {time.type} to duration")
8086
if hasattr(time, "to_ast"):
8187
return time # type: ignore[return-value]
82-
if hasattr(time, "_to_oqpy_expression"):
83-
time = cast(ExpressionConvertible, time)
84-
return time._to_oqpy_expression()
85-
if hasattr(time, "_to_cached_oqpy_expression"):
86-
time = cast(CachedExpressionConvertible, time)
87-
return time._to_cached_oqpy_expression()
8888
raise TypeError(
8989
f"Expected either float, int, HasToAst or ExpressionConverible: Got {type(time)}"
9090
)

tests/test_directives.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1572,19 +1572,29 @@ class A:
15721572

15731573
def _to_oqpy_expression(self):
15741574
return DurationVar(1e-7, self.name)
1575+
1576+
@dataclass
1577+
class B:
1578+
name: str
1579+
1580+
def _to_oqpy_expression(self):
1581+
return FloatVar(1e-7, self.name)
15751582

15761583
frame = FrameVar(name="f1")
15771584
prog = Program()
15781585
prog.set(A("a1"), 2)
15791586
prog.delay(A("a2"), frame)
1587+
prog.delay(B("b1"), frame)
15801588
expected = textwrap.dedent(
15811589
"""
15821590
OPENQASM 3.0;
15831591
duration a1 = 100.0ns;
15841592
duration a2 = 100.0ns;
15851593
frame f1;
1594+
float[64] b1 = 1e-07;
15861595
a1 = 2;
15871596
delay[a2] f1;
1597+
delay[b1 * 1s] f1;
15881598
"""
15891599
).strip()
15901600
assert prog.to_qasm() == expected

0 commit comments

Comments
 (0)