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

Add API to convert StateDump to a dense array of amplitudes #1836

Merged
merged 1 commit into from
Aug 14, 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
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
Loading