Skip to content

Detect and convert constants #44

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 1 commit into from
May 30, 2023
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
35 changes: 34 additions & 1 deletion oqpy/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,13 +21,16 @@

from __future__ import annotations

import math
import sys
from abc import ABC, abstractmethod
from typing import TYPE_CHECKING, Any, Iterable, Sequence, Union

import numpy as np
from openpulse import ast

from oqpy import classical_types

if sys.version_info >= (3, 8):
from typing import Protocol, runtime_checkable
else:
Expand Down Expand Up @@ -314,7 +317,13 @@ def to_ast(program: Program, item: AstConvertible) -> ast.Expression:
return ast.IntegerLiteral(item)
if isinstance(item, (float, np.floating)):
if item < 0:
return ast.UnaryExpression(ast.UnaryOperator["-"], ast.FloatLiteral(-item))
if program.simplify_constants:
neg_ast_term = detect_and_convert_constants(-item, program)
else:
neg_ast_term = ast.FloatLiteral(-item)
return ast.UnaryExpression(ast.UnaryOperator["-"], neg_ast_term)
if program.simplify_constants:
return detect_and_convert_constants(item, program)
return ast.FloatLiteral(item)
if isinstance(item, Iterable):
return ast.ArrayLiteral([to_ast(program, i) for i in item])
Expand Down Expand Up @@ -347,3 +356,27 @@ def make_annotations(vals: Sequence[str | tuple[str, str]]) -> list[ast.Annotati
keyword, command = val
anns.append(ast.Annotation(keyword, command))
return anns


def detect_and_convert_constants(val: float | np.floating[Any], program: Program) -> ast.Expression:
"""Construct a float ast expression which is either a literal or an expression using constants."""
if val == 0:
return ast.FloatLiteral(val)
x = val / (math.pi / 4.0)
rx = round(x)
if rx > 100 or not math.isclose(x, rx, rel_tol=1e-12):
return ast.FloatLiteral(val)
term: OQPyExpression
if rx == 4:
term = classical_types.pi
elif rx == 2:
term = classical_types.pi / 2
elif rx == 1:
term = classical_types.pi / 4
elif rx % 4 == 0:
term = (rx // 4) * classical_types.pi
elif rx % 2 == 0:
term = (rx // 2) * classical_types.pi / 2
else:
term = rx * classical_types.pi / 4
return term.to_ast(program)
3 changes: 2 additions & 1 deletion oqpy/program.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ def add_statement(self, stmt: ast.Statement | ast.Pragma) -> None:
class Program:
"""A builder class for OpenQASM/OpenPulse programs."""

def __init__(self, version: Optional[str] = "3.0") -> None:
def __init__(self, version: Optional[str] = "3.0", simplify_constants: bool = True) -> None:
self.stack: list[ProgramState] = [ProgramState()]
self.defcals: dict[
tuple[tuple[str, ...], str, tuple[str, ...]], ast.CalibrationDefinition
Expand All @@ -100,6 +100,7 @@ def __init__(self, version: Optional[str] = "3.0") -> None:
self.externs: dict[str, ast.ExternDeclaration] = {}
self.declared_vars: dict[str, Var] = {}
self.undeclared_vars: dict[str, Var] = {}
self.simplify_constants = simplify_constants

if version is None or (
len(version.split(".")) in [1, 2]
Expand Down
33 changes: 33 additions & 0 deletions tests/test_directives.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
############################################################################

import copy
import math
import textwrap
from dataclasses import dataclass

Expand Down Expand Up @@ -1747,3 +1748,35 @@ def test_ramsey_example_blog():
).strip()

assert full_prog.to_qasm(encal_declarations=True) == expected


def test_constant_conversion():
w = oqpy.FloatVar(math.pi, name="w")
x = oqpy.FloatVar(3 * math.pi / 4, name="x")
y = oqpy.FloatVar(math.pi / 2, name="y")
z = oqpy.FloatVar(7 * math.pi, name="z")
prog = Program()
prog.declare([w, x, y, z])
expected = textwrap.dedent(
"""
OPENQASM 3.0;
float[64] w = pi;
float[64] x = 3 * pi / 4;
float[64] y = pi / 2;
float[64] z = 7 * pi;
"""
).strip()
assert prog.to_qasm() == expected

prog = Program(simplify_constants=False)
prog.declare([w, x, y, z])
expected = textwrap.dedent(
"""
OPENQASM 3.0;
float[64] w = 3.141592653589793;
float[64] x = 2.356194490192345;
float[64] y = 1.5707963267948966;
float[64] z = 21.991148575128552;
"""
).strip()
assert prog.to_qasm() == expected