Skip to content
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

fix: Expression arithmetic does not error when a numpy type is on the left hand side. #1769

Merged
merged 2 commits into from
Apr 16, 2024
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
8 changes: 5 additions & 3 deletions pyquil/quilatom.py
Original file line number Diff line number Diff line change
Expand Up @@ -578,9 +578,11 @@ def __array__(self, dtype: Optional[np.dtype] = None) -> np.ndarray:
return np.asarray(self._evaluate(), dtype=dtype)
raise ValueError
except ValueError:
# Note: The `None` here is a placeholder for the expression in the numpy array.
# The expression instance will still be accessible in the array.
return np.array(None, dtype=object)
# np.asarray(self, ...) would cause an infinite recursion error, so we build the array with a
# placeholder value, then replace it with self after.
array = np.asarray(None, dtype=object)
array.flat[0] = self
return array


ParameterSubstitutionsMapDesignator = Mapping[Union["Parameter", "MemoryReference"], ExpressionValueDesignator]
Expand Down
10 changes: 9 additions & 1 deletion test/unit/test_quilatom.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
from typing import Sequence, Union

import pytest
from syrupy.assertion import SnapshotAssertion
import numpy as np

from pyquil.quilatom import FormalArgument, Frame, Qubit, Label, LabelPlaceholder, QubitPlaceholder
from pyquil.quilatom import Add, FormalArgument, Frame, Qubit, Label, LabelPlaceholder, QubitPlaceholder, Parameter


@pytest.mark.parametrize(
Expand Down Expand Up @@ -69,3 +71,9 @@ def test_qubit_placeholder():
register[0].out()

assert register[0] != register[1]


def test_arithmetic_with_numpy():
x = Parameter("x")
expression = np.float_(1.0) + x
assert expression == Add(np.float_(1.0), x)
Loading