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

feat: add str, repr and getitem to BasisState #808

Merged
merged 6 commits into from
Dec 6, 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
12 changes: 12 additions & 0 deletions src/braket/circuits/basis_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,18 @@ def __iter__(self):
def __eq__(self, other):
return self.state == other.state

def __bool__(self):
return any(self.state)

def __str__(self):
return self.as_string

def __repr__(self):
return f'BasisState("{self.as_string}")'

def __getitem__(self, item):
return BasisState(self.state[item])
jcjaskula-aws marked this conversation as resolved.
Show resolved Hide resolved

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We could define __bool__ to use BasisStates in conditions.

Suggested change
def __bool__(self):
return any(self.state)


BasisStateInput = Union[int, list[int], str, BasisState]

Expand Down
58 changes: 55 additions & 3 deletions test/unit_tests/braket/circuits/test_basis_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,58 @@
),
)
def test_as_props(basis_state_input, size, as_tuple, as_int, as_string):
assert BasisState(basis_state_input, size).as_tuple == as_tuple
assert BasisState(basis_state_input, size).as_int == as_int
assert BasisState(basis_state_input, size).as_string == as_string
basis_state = BasisState(basis_state_input, size)
assert basis_state.as_tuple == as_tuple
assert basis_state.as_int == as_int
assert basis_state.as_string == as_string == str(basis_state)
assert repr(basis_state) == f'BasisState("{as_string}")'


@pytest.mark.parametrize(
"basis_state_input, index, substate_input",
(
(
"1001",
slice(None),
"1001",
),
(
"1001",
3,
"1",
),
(
"1010",
slice(None, None, 2),
"11",
),
(
"1010",
slice(1, None, 2),
"00",
),
(
"1010",
slice(None, -2),
"10",
),
(
"1010",
-1,
"0",
),
),
)
def test_indexing(basis_state_input, index, substate_input):
assert BasisState(basis_state_input)[index] == BasisState(substate_input)


def test_bool():
assert all(
[
BasisState("100"),
BasisState("111"),
BasisState("1"),
]
)
assert not BasisState("0")