microsoft/qdk

Public

mirrored fromhttps://github.com/microsoft/qdkAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
copilot/fix-wasm-logging-issue

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

samples/testing/states/test_states.py

42lines · modecode

1import pytest
2import qsharp
3
4@pytest.fixture(autouse=True)
5def setup():
6 """Fixture to execute before a test is run"""
7 # Setting the project root to current folder.
8 qsharp.init(project_root=".")
9 yield # this is where the testing happens
10
11# 1/2 (|00⟩ + i|01⟩ - |10⟩ - i|11⟩)
12# The basis states are converted to indices of amplitudes in the array using big endian notation.
13expected_state = [0.5, 0.5j, -0.5, -0.5j]
14
15def test_state_exact() -> None:
16 """Test that Q# code prepares the expected state exactly using Python test code."""
17 # Run Q# code that allocates the qubits and prepares the state but doesn't deallocate the qubits.
18 qsharp.eval(f"use qs = Qubit[2]; StatePrep.PrepareStateWithComplexPhases(qs);")
19 # Get the state of the allocated qubits and convert it to a dense vector.
20 state = qsharp.dump_machine().as_dense_state()
21 # Compare two vectors.
22 assert state == pytest.approx(expected_state)
23
24
25def test_state_exact_rejects_global_phase() -> None:
26 """Test that shows that the exact check from the previous test fails if the state is different by a global phase."""
27 # Run Q# code that allocates the qubits and prepares the state but doesn't deallocate the qubits.
28 qsharp.eval(f"use qs = Qubit[2]; StatePrep.PrepareStateWithGlobalPhase(qs);")
29 # Get the state of the allocated qubits and convert it to a dense vector.
30 state = qsharp.dump_machine().as_dense_state()
31 # Compare two vectors. Here we expect them to be _not equal_ due to the global phase -1.
32 assert state != pytest.approx(expected_state)
33
34
35def test_state_global_phase() -> None:
36 """Test that Q# code prepares the expected state up to a global phase using Python test code."""
37 # Run Q# code that allocates the qubits and prepares the state but doesn't deallocate the qubits.
38 qsharp.eval(f"use qs = Qubit[2]; StatePrep.PrepareStateWithGlobalPhase(qs);")
39 # Get the state of the allocated qubits.
40 state = qsharp.dump_machine()
41 # Compare the state to the expected one, taking into account the possible global phase difference.
42 assert state.check_eq(expected_state)
43