Search code examples
unit-testingquantum-computingq#

Q# unit testing to check phase


I want to test a phase oracle by testing if the phase of qubit flipped. I tried to do it by

AssertQubitIsInStateWithinTolerance((Complex(0., 0.), Complex(-1., 0.)), qubit, 1e-5);

But it doesn't really check the phase because the same input also worked for the test without phase

AssertQubitIsInStateWithinTolerance((Complex(0., 0.), Complex(1., 0.)), qubit, 1e-5);

Is there a way to use unit tests to check the phase of qubit (or of the entire register)?

Thanks for the help.


Solution

  • There is no physical way to observe a global phase of a quantum state, so you won't be able to distinguish |1⟩ state from -|1⟩ state. You'll need to find a way to convert this global phase to a relative phase, so that you can observe it.

    • If you want to check whether a phase of a specific basis state |ψ⟩ is flipped by your oracle, you can use a modification of phase kickback trick: prepare a state (|0⟩ + |1⟩) ⊗ |ψ⟩, apply a controlled version of your oracle (with the first qubit as the control), and check which state you got on the first qubit: if it is still |0⟩ + |1⟩, the oracle doesn't flip the phase of the state, and if it changed to |0⟩ - |1⟩, the phase of the state is flipped. (You can do this measurement using Measure([PauliX], [q]) operation).
    • If you want to check the phases of all, you can prepare a superposition of all basis states, apply your oracle and compare the state with the state you'd expect to obtain. You can do this by applying explicit Control Z gates to flip the phases of states you know need to be flipped - this should give you a superposition of all basis states again. You can check that it did by applying H gate to each qubit of the register and using AssertAllZero operation to check that the result is an all-zero state.

    You can check the testing harnesses in the Quantum Katas for examples of these approaches; they test a lot of different quantum conditions, so they are a good source for testing approaches.