Skip to content

convert ExpressionConvertible to duration #86

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 6 additions & 6 deletions oqpy/timing.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,19 +72,19 @@ def convert_float_to_duration(time: AstConvertible, require_nonnegative: bool =
if require_nonnegative and time < 0:
raise ValueError(f"Expected a non-negative duration, but got {time}")
return OQDurationLiteral(time)
if hasattr(time, "_to_oqpy_expression"):
time = cast(ExpressionConvertible, time)
time = time._to_oqpy_expression()
if hasattr(time, "_to_cached_oqpy_expression"):
time = cast(CachedExpressionConvertible, time)
time = time._to_cached_oqpy_expression()
if isinstance(time, OQPyExpression):
if isinstance(time.type, (ast.UintType, ast.IntType, ast.FloatType)):
time = time * OQDurationLiteral(1)
elif not isinstance(time.type, ast.DurationType):
raise TypeError(f"Cannot convert expression with type {time.type} to duration")
if hasattr(time, "to_ast"):
return time # type: ignore[return-value]
if hasattr(time, "_to_oqpy_expression"):
time = cast(ExpressionConvertible, time)
return time._to_oqpy_expression()
if hasattr(time, "_to_cached_oqpy_expression"):
time = cast(CachedExpressionConvertible, time)
return time._to_cached_oqpy_expression()
raise TypeError(
f"Expected either float, int, HasToAst or ExpressionConverible: Got {type(time)}"
)
Expand Down
10 changes: 10 additions & 0 deletions tests/test_directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -1572,19 +1572,29 @@ class A:

def _to_oqpy_expression(self):
return DurationVar(1e-7, self.name)

@dataclass
class B:
name: str

def _to_oqpy_expression(self):
return FloatVar(1e-7, self.name)

frame = FrameVar(name="f1")
prog = Program()
prog.set(A("a1"), 2)
prog.delay(A("a2"), frame)
prog.delay(B("b1"), frame)
expected = textwrap.dedent(
"""
OPENQASM 3.0;
duration a1 = 100.0ns;
duration a2 = 100.0ns;
frame f1;
float[64] b1 = 1e-07;
a1 = 2;
delay[a2] f1;
delay[b1 * 1s] f1;
"""
).strip()
assert prog.to_qasm() == expected
Expand Down