Skip to content

Commit

Permalink
Add API to convert StateDump to a dense array of amplitudes (#1836)
Browse files Browse the repository at this point in the history
Fixes #1722
  • Loading branch information
swernli authored Aug 14, 2024
1 parent ef98e36 commit 9ae1d2a
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 0 deletions.
6 changes: 6 additions & 0 deletions pip/qsharp/_qsharp.py
Original file line number Diff line number Diff line change
Expand Up @@ -426,6 +426,12 @@ def check_eq(
return False
return True

def as_dense_state(self) -> List[complex]:
"""
Returns the state dump as a dense list of complex amplitudes. This will include zero amplitudes.
"""
return [self.__inner.get(i, complex(0)) for i in range(2**self.qubit_count)]


def dump_machine() -> StateDump:
"""
Expand Down
8 changes: 8 additions & 0 deletions pip/tests/test_qsharp.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,13 @@ def test_dump_machine() -> None:
assert state_dump.qubit_count == 2
assert len(state_dump) == 1
assert state_dump[2] == complex(1.0, 0.0)
assert state_dump.as_dense_state() == [0, 0, 1, 0]
qsharp.eval("X(q2);")
state_dump = qsharp.dump_machine()
assert state_dump.qubit_count == 2
assert len(state_dump) == 1
assert state_dump[3] == complex(1.0, 0.0)
assert state_dump.as_dense_state() == [0, 0, 0, 1]
qsharp.eval("H(q1);")
state_dump = qsharp.dump_machine()
assert state_dump.qubit_count == 2
Expand All @@ -102,6 +104,12 @@ def test_dump_machine() -> None:
# in of different, potentially unnormalized states. The state should be
# |01⟩: 0.7071+0.0000𝑖, |11⟩: −0.7071+0.0000𝑖
assert state_dump.check_eq({1: complex(0.7071, 0.0), 3: complex(-0.7071, 0.0)})
assert state_dump.as_dense_state() == [
0,
0.7071067811865476,
0,
-0.7071067811865476,
]
assert state_dump.check_eq({1: complex(0.0, 0.7071), 3: complex(0.0, -0.7071)})
assert state_dump.check_eq({1: complex(0.5, 0.0), 3: complex(-0.5, 0.0)})
assert state_dump.check_eq(
Expand Down

0 comments on commit 9ae1d2a

Please sign in to comment.