Skip to content

Commit

Permalink
fix: Support angle declarations (#199)
Browse files Browse the repository at this point in the history
  • Loading branch information
speller26 authored Aug 3, 2023
1 parent b8150fa commit 0474f22
Show file tree
Hide file tree
Showing 6 changed files with 95 additions and 7 deletions.
13 changes: 13 additions & 0 deletions src/braket/default_simulator/openqasm/_helpers/arrays.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

from functools import singledispatch
from typing import List, Optional, Type, Union

Expand Down
31 changes: 26 additions & 5 deletions src/braket/default_simulator/openqasm/_helpers/casting.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

import warnings
from copy import deepcopy
from functools import singledispatch
Expand All @@ -7,6 +20,7 @@
from sympy import Symbol

from ..parser.openqasm_ast import (
AngleType,
ArrayLiteral,
ArrayType,
BitstringLiteral,
Expand Down Expand Up @@ -103,14 +117,21 @@ def _(into: UintType, variable: LiteralType) -> IntegerLiteral:
def _(into: FloatType, variable: LiteralType) -> FloatLiteral:
"""Cast to float"""
if into.size is None:
value = float(variable.value)
else:
if into.size.value not in (16, 32, 64):
raise ValueError("Float size must be one of {16, 32, 64}.")
value = float(np.array(variable.value, dtype=np.dtype(f"float{into.size.value}")))
return FloatLiteral(float(variable.value))
if into.size.value not in (16, 32, 64):
raise ValueError("Float size must be one of {16, 32, 64}.")
value = float(np.array(variable.value, dtype=np.dtype(f"float{into.size.value}")))
return FloatLiteral(value)


@cast_to.register
def _(into: AngleType, variable: LiteralType) -> FloatLiteral:
"""Cast angle to float"""
if into.size is None:
return FloatLiteral(float(variable.value) % (2 * np.pi))
raise ValueError("Fixed-bit angles are not supported.")


@cast_to.register
def _(into: ArrayType, variable: Union[ArrayLiteral, DiscreteSet]) -> ArrayLiteral:
"""Cast to Array and enforce dimensions"""
Expand Down
13 changes: 13 additions & 0 deletions src/braket/default_simulator/openqasm/_helpers/functions.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

"""
Evaluating expressions
"""
Expand Down
13 changes: 13 additions & 0 deletions src/braket/default_simulator/openqasm/_helpers/quantum.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,16 @@
# Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License"). You
# may not use this file except in compliance with the License. A copy of
# the License is located at
#
# http://aws.amazon.com/apache2.0/
#
# or in the "license" file accompanying this file. This file is
# distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF
# ANY KIND, either express or implied. See the License for the specific
# language governing permissions and limitations under the License.

from typing import List, Union

from ..parser.openqasm_ast import (
Expand Down
6 changes: 4 additions & 2 deletions src/braket/default_simulator/openqasm/interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@
WhileLoop,
)
from .parser.openqasm_parser import parse
from .program_context import ProgramContext
from .program_context import AbstractProgramContext, ProgramContext


class Interpreter:
Expand All @@ -114,7 +114,9 @@ class Interpreter:
the ProgramContext object, which can be used for debugging or other customizability.
"""

def __init__(self, context: Optional[ProgramContext] = None, logger: Optional[Logger] = None):
def __init__(
self, context: Optional[AbstractProgramContext] = None, logger: Optional[Logger] = None
):
# context keeps track of all state
self.context = context or ProgramContext()
self.logger = logger or getLogger(__name__)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
from braket.default_simulator.openqasm.circuit import Circuit
from braket.default_simulator.openqasm.interpreter import Interpreter
from braket.default_simulator.openqasm.parser.openqasm_ast import (
AngleType,
ArrayLiteral,
ArrayType,
BitstringLiteral,
Expand Down Expand Up @@ -193,6 +194,31 @@ def test_float_declaration():
assert context.get_value("unsized") == FloatLiteral(np.pi)


def test_angle_declaration():
qasm = """
angle uninitialized;
angle pos = 3.5 * π;
angle neg = -4.5 * π;
"""
context = Interpreter().run(qasm)

assert context.get_type("uninitialized") == AngleType(None)
assert context.get_type("pos") == AngleType(None)
assert context.get_type("neg") == AngleType(None)

assert context.get_value("uninitialized") is None
assert context.get_value("pos") == FloatLiteral(1.5 * np.pi)
assert context.get_value("neg") == FloatLiteral(1.5 * np.pi)


def test_fixed_bit_angle_declaration():
qasm = """
angle[16] pos = 10;
"""
with pytest.raises(ValueError):
Interpreter().run(qasm)


def test_constant_declaration():
qasm = """
const float[16] const_tau = 2 * π;
Expand Down

0 comments on commit 0474f22

Please sign in to comment.