Quantum Basis and Quantum State (19)

In order to use QuantumBasis, one gives dimension information as arguments, which will be interpreted as the computational basis. Alternatively, an association can be given with the basis name as the key and the corresponding basis elements as the values.

Define a 2D quantum basis (computational):

QuantumBasis[2]

Given a basis of dimension n, the basis elements will be indexed by the key (Ket) with :

Normal/@%["ElementAssociation"]

Use QuantumBasis[n,m] to define a basis for m qudits of dimension n (for which the overall dimension will be ). For example, define a 2×2×2-dimensional quantum basis (with three qubits):

QuantumBasis[2,3]

%["Dimensions"]

Use QuantumBasis[{(Subscript[n, 1]),(Subscript[n, 2]),…,(Subscript[n, m])}] to define an (Subscript[n, 1])×(Subscript[n, 2])×(Subscript[n, 3])×…×(Subscript[n, m])-dimensional Hilbert space of  qudits as a list. For example, define a 3×5-dimensional quantum basis (with two qudits):

QuantumBasis[{3,5}]

A basis can also be defined as an association with the basis element names as keys and the corresponding vectors as values:

QuantumBasis[<|a-> {1,I}, b-> {2,-I}|>]

Normal/@%["ElementAssociation"]

There are many 'named' bases built into the quantum framework, including "Computational", "PauliX", "PauliY", "PauliZ", "Fourier", "Identity", "Schwinger", "Pauli", "Dirac" and "Wigner":

{QuantumBasis["Computational"],QuantumBasis["PauliX"],QuantumBasis["Schwinger"],QuantumBasis["Bell"],QuantumBasis["Dirac"]}

After a basis object has been defined, it is straightforward to construct quantum states and operators. A quantum state is represented by a QuantumState object and a quantum operator is represented by QuantumOperator.

A pure quantum state is represented as a vector for which the elements are amplitudes. The corresponding basis should be given in this format: QuantumState[(Subscript[arg, 1]),(Subscript[arg, 2])], where (Subscript[arg, 1]) specifies amplitudes or the density matrix, and (Subscript[arg, 2]) specifies the basis. With no basis specified, the default basis will be the computational basis, the dimension of which depends on the amplitude vector given in arg1.

Note that the big endian convention is in use, such that qubits are labeled left-to-right, starting with 1. For example, the decimal representation of (Ket) (which means (Ket)⊗(Ket)⊗(Subscript[(Ket), 3])) is . Additionally, for the eigenvalues of Pauli-Z, there is:

Eigensystem[PauliMatrix[3]]

Denote the eigenstate {1,0} by (Ket[0]) (which corresponds to +1 eigenvalue), and {0,1} by (Ket[1]) (which corresponds to the eigenvalue -1).

Define a pure 2-dimensional quantum state (qubit) in the Pauli-X basis:

QuantumState[{1,-1+I}, QuantumBasis["PauliX"]]

%["Formula"]

If the basis is not specified, the default is the computational basis of  dimensions ( qubits):

state=QuantumState[{3,2I,1,-5}]

state["Amplitudes"]

If the vector has more than 2 elements, it is interpreted as an -qubit state, unless the dimension is specified. If fewer than (2^n) amplitudes are specified, right-padding is applied to reach the (2^n) "ceiling":

state= QuantumState[{2,0,I}]

state["Amplitudes"]

Here is the same amplitude vector, but this time with the dimension specified:

state= QuantumState[{2,0,I},3];
state["Amplitudes"]

Binary strings can also be used as inputs:

QuantumState["001"]

Many "named" states are available through the framework:

{QuantumState[{"UniformSuperposition",4}], QuantumState["PsiPlus"], QuantumState["GHZ"]}

Using associations, one can create a superposition of states, where the keys are lists of corresponding indexes and the values are amplitudes.

Create a superposition of 3 qubits (i.e. QuantumBasis[2,3] as (1/(Sqrt[2]))((Ket[000])+(Ket[111]))):

ψ=QuantumState[<|{0,0,0}->(1/(Sqrt[2])),{1,1,1}->(1/(Sqrt[2]))|>,2,3]

ψ["Formula"]

ψ["Dimensions"]

A superposition can also be created by simply adding two quantum state objects. For example, the previous state can also be constructed as follows:

ψ2=(QuantumState["000"]+QuantumState["111"])/(Sqrt[2]);
ψ==ψ2

With a built-in basis specified, amplitudes correspond to the basis elements. For example, use the Bell basis:

Normal/@QuantumBasis["Bell"]["ElementAssociation"]

ψ=QuantumState[{2,-I,1,3},QuantumBasis["Bell"]]

ψ["Amplitudes"]

A state can also be defined by inputting a density matrix:

QuantumState[1/2(IdentityMatrix[2]+PauliMatrix[2])]

For pure states, one can get the corresponding normalized state vector:

%["Formula"]

Define a generic Bloch vector:

mat[r_]/;VectorQ[r]:=1/2(IdentityMatrix[2]+r.Table[PauliMatrix[i],{i,3}])

r={.1,.1,0};
state=QuantumState[mat[r]]

Test to see if it is a mixed state:

state["MixedStateQ"]

Calculate its von Neumann entropy:

state["VonNeumannEntropy"]

Compute its purity:

state["Purity"]

Note that one can directly use a Bloch vector as an input:

QuantumState[{"BlochVector",r}]

%==state

Test to see if a matrix is positive semidefinite:

mat[{1,2,0}]//PositiveSemidefiniteMatrixQ

A matrix that is not positive semidefinite cannot be a density matrix in standard quantum mechanics (with some exceptional cases, such as ZX formalism). Here is the result when it is attempted to define a state using such a matrix:

QuantumState[mat[{1,2,0}]]

When a matrix is given as input but no basis is given, the default basis will be computational:

m=RandomComplex[{-1-I,1+I},{8,8}];
ρ=ConjugateTranspose[m].m;
state=QuantumState[ρ]

state["Dimensions"]

Using , define a quantum state in a 2×4-dimensional basis (and note the number of qudits):

state=QuantumState[ρ,{2,4}]

state["Dimensions"]

Define a quantum state in 8D Hilbert space (with one 8-dimensional qudit only):

state=QuantumState[ρ,8]

state["Dimensions"]

One can also define a state in a given basis and then transform it into a new basis. For example, transform (Ket[0]), the computational basis, into the Pauli-X basis {(Ket[+]),(Ket[-])}:

ψ1=QuantumState[{1,0}];
ψ2=QuantumState[ψ1,"PauliX"]

Return the amplitudes:

ψ1["Formula"]

ψ2["Formula"]

Note that the states are the same, but defined in different bases:

ψ1==ψ2

One can use QuantumTensorProduct to construct different states or operators. Create a tensor product of a + state with three qubits (Ket[+++]):

ψ1=QuantumTensorProduct[QuantumState["Plus"],QuantumState["Plus"],QuantumState["Plus"]];
ψ1["Formula"]

Another way of defining (Ket[+++]) is to first define a basis and then assign amplitudes:

plusbasis=QuantumTensorProduct[QuantumBasis["PauliX"],QuantumBasis["PauliX"],QuantumBasis["PauliX"]];

ψ2=QuantumState[{0,0,0,0,0,0,0,1},plusbasis];
ψ2["Formula"]

ψ2==ψ1

Quantum Operators (10)

Quantum operators can be defined by a matrix or by specifying eigenvalues with respect to a QuantumBasis. Additionally, there are many built-in named operators that can be used.

Define a Pauli-X operator:

QuantumOperator["PauliX"]

Apply a Pauli-X operator to a symbolic state ((Ket[0])+(Ket[1])):

QuantumOperator["PauliX"][QuantumState[{α,β}]]

Test to see if the application of the Pauli-X operator yields the correct state:

%==QuantumState[{β,α}]

Apply the Hadamard operator H(Ket[0])(Ket[+]):

QuantumOperator["Hadamard"]@QuantumState[{1,0}]

Test to see if the application of the Hadamard operator yields the correct state:

%==QuantumState["Plus"]

One can also compose operators. Here is a composition of two Hadamard operators and one Pauli-Z operator:

QuantumOperator["Hadamard"]@QuantumOperator["PauliZ"]@QuantumOperator["Hadamard"]

Check the relation (Subscript[σ, x])=(Subscript[Hσ, x])H:

%==QuantumOperator["PauliX"]

Multi-qubit operators can take specific orders.

For instance, first define the state α(Ket[10])+β(Ket[11]):

state=QuantumState[<|{1,0}->α,{1,1}->β|>,QuantumBasis[2,2]];
state["Amplitudes"]

Then, apply a Pauli-X operator on the second qubit only (by defining an order for the operator):

QuantumOperator["PauliX",{2}][state]

Test the result:

%==QuantumState[<|{1,0}->β,{1,1}->α|>,QuantumBasis[2,2]]

For multi-qudit cases, one can define an order or construct the operator using QuantumTensorProduct. For example:

QuantumOperator["Hadamard",{1}]@QuantumOperator["PauliX",{2}]==QuantumTensorProduct[QuantumOperator["Hadamard"],QuantumOperator["PauliX"]]

Generalize Pauli matrices to higher dimensions:

QuantumOperator[{"PauliX",3}]

Convert to matrix form:

%["Matrix"]//MatrixForm

Generalize the Hadamard operator to more qubits:

QuantumOperator[{"Hadamard",3}]

Test that the Hadamard operator can be constructed as a tensor product:

QuantumOperator[{"Hadamard",3}]==QuantumTensorProduct[QuantumOperator["H"],QuantumOperator["H"],QuantumOperator["H"]]

One can define a "Controlled" operator with specific target and control qudits:

ct=QuantumOperator[{"C","T",{1}}];

Return the control and target qudits:

AssociationMap[ct,{"ControlOrder","TargetOrder"}]

Get the action of the operator (T-controlled (1, 2)) on (Ket[1+]):

ct@QuantumTensorProduct[QuantumState[{0,1}],QuantumState["Plus"]]

%["Formula"]

Note that "CT" is also a "named" controlled operator in this framework:

QuantumOperator["CT"]==ct

One can create a new operator by performing some mathematical operations (e.g., exponential, fraction power, etc.) on a quantum operator:

Exp[-I ϕ/2 QuantumOperator["X"]]

Show that the result is the same as a rotation operator around x:

%==QuantumOperator[{"RX",ϕ}]

Get the fractional power of the NOT operator:

Sqrt[QuantumOperator["NOT"]]

%["Matrix"]//MatrixForm

Time Evolution Operators (4)

Time evolution can be implemented by adding a parametric specification to any operator. Then, using the EvolutionOperator property of a quantum operator, one can generate the corresponding time evolution operator.

Unitary operator and analytic solution of time-dependent Schrödinger equation (2)

Setting a Pauli-X operator as the Hamiltonian and evolving (Ket[0]), we get:

u=QuantumOperator["PauliX","ParameterSpec"->t]["EvolutionOperator"];
ψf=u@QuantumState["0"]

Return the amplitudes at time :

ψf["StateVector"]//Normal

Evolution in a time-dependent field: Nuclear magnetic resonance (NMR) (2)

Set up the Hamiltonian (as a time-dependent operator) in a magnetic field ((Subscript[ω, 1])/2){,,}:

hamiltonian=QuantumOperator[((Subscript[ω, 1])/2) Cos[α] QuantumOperator["Z"]+((Subscript[ω, 1])/2) Sin[α] (Cos[ω t] QuantumOperator["X"]+Sin[ω t] QuantumOperator["Y"]),"ParameterSpec"->t];

u=hamiltonian["EvolutionOperator"];
ψf=u@QuantumState[{Cos[α/2],Sin[α/2]}]

Get the state vector for the pure state:

ψf["StateVector"]//Normal//FullSimplify

Quantum Measurement (12)

In the Wolfram Quantum Framework, one can study projective measurements or, generally, any positive operator-valued measurement (POVM) using QuantumMeasurementOperator.

PVMs (projective measurements) (5)

A measurement can be defined by specifying the corresponding measurement basis.

Measure a 3D system in its state basis:

ψ0=QuantumState["RandomPure",3];
m=QuantumMeasurementOperator[QuantumBasis[ψ0["Dimensions"]]][ψ0]

m["ProbabilityPlot"]

Test to confirm that the measured states are the same as the basis states:

Thread[m["States"]=={QuantumState[{1,0,0},3],QuantumState[{0,1,0},3],QuantumState[{0,0,1},3]}]

Measure a 2-qubit system in the computational basis:

ψ0=QuantumState[{"RandomPure",2}];
m=QuantumMeasurementOperator[{1,2}][ψ0]

m["ProbabilityPlot"]

Note the labels for the corresponding eigenvalues, from 0 to n-1 as follows:

QuantumMeasurement[m,"Label"->Automatic]["ProbabilityPlot"]

For composite systems, one can measure one or more qudits. This can be done by specifying an order for QuantumMeasurementOperator.

2D×3D composite system:

ψ0=QuantumState["RandomPure",{2,3}];

Measure only the first qudit:

QuantumMeasurementOperator[ψ0["Dimensions"],{1}][ψ0]["ProbabilityPlot"]

Measure only the second qudit:

QuantumMeasurementOperator[ψ0["Dimensions"],{2}][ψ0]["ProbabilityPlot"]

Measure both qudits:

QuantumMeasurementOperator[ψ0["Dimensions"],{1,2}][ψ0]["ProbabilityPlot"]

One can use the following format for "named" bases and their corresponding eigenvalues: QuantumMeasurementOperator[name->eigenvalues].

For example, define a measurement operator with a "named" QuantumBasis (as an eigenbasis) and a list of eigenvalues:

QuantumMeasurementOperator["Bell"->{-3,-1,2,4.}]

POVMs (7)

One can also give a list of POVM elements by which to define the measurement operator:

states={QuantumState[-(1/2){1,(Sqrt[3])}],QuantumState[-(1/2){1,-(Sqrt[3])}],QuantumState["0"]};
{e1,e2,e3}=(2/3)QuantumOperator[#[#["Dagger"]]]&/@states;
povm={e1,e2,e3};

Check that all POVM elements are explicitly positive semidefinite:

PositiveSemidefiniteMatrixQ[#["Matrix"]]&/@povm

Check the completeness relations:

Total[povm]==QuantumOperator["Identity"]

Measure POVMs on a quantum state:

qm=QuantumMeasurementOperator[povm][QuantumState[{1,1}]];

Get the post-measurement states:

qm["StatesAssociation"]

Get the corresponding probabilities:

N@qm["Probabilities"]

Show that post-measurement states are the same as states initially defined as POVMs:

Thread[qm["States"]==states]

Quantum Partial Tracing, Distance and Entanglement (4)

In the framework, there are some functionalities to explore the quantum distance, entanglement monotones and partial tracing, as well as other useful features.

Trace out the second subsystem in a 2-qubit state:

QuantumPartialTrace[QuantumState["PsiPlus"],{2}]

A partial trace can also be applied to QuantumBasis:

QuantumPartialTrace[QuantumBasis[{3,2}],{2}]

There are several metrics by which one can measure entanglement between two qudits, such as concurrence, entanglement entropy, negativity, etc. The calculation of entanglement measure is represented by the QuantumEntanglementMonotone function.

Plot various entanglement measures for the state α(Ket[00])+ (Sqrt[1-(α^2)])(Ket[11]):

Plot[{QuantumEntanglementMonotone[QuantumState[{α,0,0,Sqrt[1-(α^2)]}],{{1},{2}},"Concurrence"],QuantumEntanglementMonotone[QuantumState[{α,0,0,Sqrt[1-(α^2)]}],{{1},{2}},"LogNegativity"],QuantumEntanglementMonotone[QuantumState[{α,0,0,Sqrt[1-(α^2)]}],{{1},{2}},"EntanglementEntropy"]},{α,0,1}, PlotLegends->{"Concurrence", "LogNegativity", "EntanglementEntropy"}]

To know whether a state is entangled or separable without computing its measure, use QuantumEntangledQ.

Check whether subsystems 1 and 3 are entangled in the "W" state:

state=QuantumState["W"];
state["Formula"]

QuantumEntangledQ[state,{{1},{3}}]

In quantum information, there exist notions of distance between quantum states, such as fidelity, trace distance, Bures angle, etc. One can use QuantumDistance to compute the distance between two quantum states with various metrics.

Measure the trace distance between a pure state and a mixed state:

ψ1=QuantumState[{{1/4,0},{0,3/4}}];
ψ2=QuantumState[{1,0}];

AssociationMap[QuantumDistance[ψ1, ψ2,#]&,{"Fidelity","Trace","BuresAngle","HilbertSchmidt"}]

Quantum Circuits (4)

One may create a list of QuantumOperator and/or QuantumMeasurementOperator objects to build a quantum circuit, which can be represented as a QuantumCircuitOperator object.

Construct a quantum circuit that includes a controlled Hadamard gate:

qc=QuantumCircuitOperator[{"NOT","CH","NOT",{1}}];
qc["Diagram"]

The wire labels can be customized:

qc["Diagram","WireLabels"->{{Placed["(Subscript[a, i])",Left],Placed["(Subscript[a, f])",Right]},{Placed["(Subscript[b, i])",Left],Placed["(Subscript[b, f])",Right]}},"MeasurementWireLabel"->"M"]

Construct a Toffoli gate as a circuit:

qc=QuantumCircuitOperator[{{"C",Sqrt["X"]}->{2,3},"CX",{"C",Sqrt[QuantumOperator["X"]]["Dagger"]}->{2,3},"CX"->{1,2},{"C",Sqrt["X"]}->{1,3}}];qc["Diagram"]

Show that the circuit is the same as the Toffoli gate:

QuantumOperator["Toffoli"]==qc["CircuitOperator"]

Define a combination of control-0 and control-1 qubits:

cu=QuantumOperator[{"C","X",{1,4},{2}},{3}];
QuantumCircuitOperator[{cu}]["Diagram"]

Measurement operators can also be added to a quantum circuit. For a single-qubit unitary operator  with eigenvalues ±1, a measurement of  can be implemented in the following circuit (note that here, Pauli-Y is considered a  operator):

qc=QuantumCircuitOperator[{"H","CY","H",{1}}];
qc["Diagram"]

Applying the circuit operators to a quantum state results in a quantum measurement:

m=qc[]

Calculate the state of the second qubit after the measurement by tracing over the first qubit:

statesQ2=QuantumPartialTrace[#,{1}]&/@m["States"]

Thread[statesQ2==Reverse[QuantumState/@QuantumOperator["Y"]["Eigenvectors"]]]

The post-measurement states of the second qubit should be the same as the Pauli-Y eigenstates.

Superdense coding (5)

Alice wants to send Bob two classical bits: 00, 01, 10 or 11. She can do so by using a single qubit if her qubit and Bob's are initially prepared as Bell states:

ϕ=QuantumState["PhiPlus"];
ϕ["Formula"]

Depending on Alice's intended message, she will perform the following operations on her qubit:

1. To send 00, she does nothing.

2. To send 01, she applies the X-gate.

3. To send 10, she applies the Z-gate.

4. To send 11, she applies the X-gate and then the Z-gate.

Such operations can be represented as circuits, each with a final state resulting from application of its respective gate(s) to the initial Bell state:

TableForm[{#1,QuantumCircuitOperator[#2]["Diagram","WireLabels"->None],QuantumCircuitOperator[{#2,QuantumOperator["Identity",{2}]}][QuantumState["PhiPlus"]]["Formula"]}&@@@{{"00",QuantumOperator["Identity"]},{"01",QuantumOperator["X"]},{"10",QuantumOperator["Z"]},{"11",{QuantumOperator["X"],QuantumOperator["Z"]}}},TableHeadings->{None,{"Message","Gate","Final state"}}]

Next, Alice sends her qubit to Bob through a quantum channel. If Bob performs a Bell measurement on his qubits, he receives Alice's message.

Alice's "messaging" with Bob can be fully implemented in a quantum circuit using two ancillary qubits. In the circuit, the first qubit is Alice's, the second one is Bob's and the third and the fourth are the ancillary qubits. Note that Alice sends her qubit to Bob and Bob performs a measurement on qubits 1 and 2:

superdense=QuantumCircuitOperator[{"H","CNOT","CX"->{4,1},"CZ"->{3,1},"CNOT","H",{1},{2}}];
superdense["Diagram"]

Define an initial state as (Ket[00]), where  is the code that Alice wants to send Bob, which is encoded in two ancillary qubits (qubits 3 and 4).

Run the state through the circuit and return the outcome probabilities:

superdense[QuantumState["00"<>#1<>#2]]["ProbabilityPlot"]&@@@Tuples[{"0","1"},2]//GraphicsRow

For each case, Bob finds Alice's code with probability 1.

Quantum teleportation (4)

Quantum teleportation is the reverse of superdense coding. Here, one wants to teleport a generic unknown quantum bit. Suppose that Alice wants to send a qubit (qubit 1) to Bob. To implement a quantum circuit for teleporting a qubit, Alice and Bob share an entangled state (qubits 2 and 3). Qubits 1 and 2 represent Alice's system, while qubit 3 is Bob's. The goal is to transfer the state of Alice's first qubit to Bob's qubit.

Set up a circuit:

qc=QuantumCircuitOperator[{"H"->2,"CX"->{2,3},"CX","H","CX"->{2,3},"CZ"->{1,3},{1},{2}}];

qc["Diagram"]

The state to be teleported is (Ket[ψ])=α(Ket[0])+β(Ket[1]), where α and β are unknown amplitudes. The input state of the circuit is as follows:

ψ0=QuantumTensorProduct[QuantumState[{α,β}],QuantumState["00"]];

Given the result of Alice's measurement on the first and second qubits, get the post-measurement states:

postMeasurementStates=qc[ψ0]["States"];
#["Formula"]&/@postMeasurementStates

Regardless of measurement results, the state of the third qubit is the same state as the original first qubit (Ket[ψ])=α(Ket[0])+β(Ket[1]) (with only a normalization difference). Trace out the first and second qubits and compare the reduced state of qubit 3 only:

Thread[QuantumState[{α,β}/2]==QuantumPartialTrace[#,{1,2}]&/@postMeasurementStates]

Bernstein–Vazirani algorithm (3)

The goal of the Bernstein–Vazirani algorithm is to find a secret string bit as s using the action of a Bernstein–Vazirani oracle (i.e. which should be treated as a black box), which is defined by this transformation: (Ket[x])(Ket[q])->(Ket[x])(Ket[q⊕(x.s)]) with (Ket[x]) the index register state of n-qubits, and (Ket[q]) the state of an ancillary qubit carrying the result.

A Bernstein–Vazirani oracle for the secret bit of 101:

bv=QuantumCircuitOperator[{"BernsteinVaziraniOracle","101"}];
bv["Diagram"]

A Bernstein–Vazirani circuit for the secret bit of 101:

QuantumCircuitOperator[{"BernsteinVazirani","101"}]["Diagram"]

As expected, the only measurement outcome corresponds to the secret bit string:

QuantumCircuitOperator[{"BernsteinVazirani","101"}][]["ProbabilityPlot"]

Grover's search algorithm (14)

The goal of Grover's search algorithm is to find the solutions of a Boolean function . This can be done using the named circuits or oracles in the quantum framework.

The action of a Boolean oracle is defined by this transformation: (Ket[x])(Ket[q])->(Ket[x])(Ket[q⊕f(x)]) with (Ket[x]) the index register state of n-qubits, and (Ket[q]) the state of an ancillary qubit carrying the result of the Boolean function f(x); meaning if (Ket[q])=(Ket[0]), then it will be (Ket[1]) if x is a solution of f(x), and unchanged if it is not.

Define a Boolean function of 3-SAT with five clauses:

f=And[!v1||!v2||!v3,v1||!v2||v3,v1||v2||!v3,v1||!v2||!v3,!v1||v2||v3];

Here is the truth table for this Boolean function:

ResourceFunction["TruthTable"][f,{v1,v2,v3}]

The corresponding oracle's quantum circuit:

oracle=QuantumCircuitOperator[{"BooleanOracle",f}];

The diagram of the oracle:

oracle["Diagram"]

Prepare the 4-qubit in the previous circuit (i.e. the ancillary qubit) as a 0-state, and then other qubits (1–3) in the index register states. To compare with the truth table, create the index register states |x> in the order |(2^n)-1> down to |0:

states=QuantumTensorProduct[#,QuantumState["0"]]&/@Table[QuantumState[{"Register",3,i}],{i,2^3-1,0,-1}];

Create a list with elements {|x>,|q⊕f(x)}:

TableForm[Transpose[{Table[QuantumState[{"Register",3,i}]["Formula"],{i,2^3-1,0,-1}],QuantumPartialTrace[oracle[#],{1,2,3}]["Formula"]&/@states}],TableHeadings->{None, {"|x>","|q⊕f(x)>"}}]

The action of a phase oracle can be defined as the following transformation:  with  the index register state of n-qubits:

phaseOracle=QuantumCircuitOperator[{"PhaseOracle",f}];

The diagram of the oracle:

phaseOracle["Diagram"]

Create a list with elements {|x>,(((-1))^(f(x)))|x>}:

Module[{index=Table[QuantumState[{"Register",3,i}],{i,2^3-1,0,-1}]},
TableForm[Transpose[{#["Formula"]&/@index,phaseOracle[#]["Formula"]&/@index}],TableHeadings->{None, {"|x>","(-1)^(f (x))|x>"}}]]

Generate the corresponding Grover circuit using a Boolean oracle:

QuantumCircuitOperator[{"Grover",q1&&q2&&q3}]["Diagram"]

Generate a Grover circuit using the phase oracle for a Boolean function:

QuantumCircuitOperator[{"GroverPhase",q1&&q2&&q3}]["Diagram"]

Given a Grover phase circuit for a Boolean function, calculate the probability of success of the algorithm:

g=QuantumCircuitOperator[{"GroverPhase",q1&&q2&&q3}];

steps=NestList[g,QuantumState[{"UniformSuperposition",3}],20];

Calculate the success probability after each iteration (note 111 is the solution of the Boolean function):

success=Abs[Normal[QuantumState["111"]["Dagger"][#][[1,1]]]]^2&/@steps;

Plot the success probability:

ListLinePlot[success,GridLines->Automatic,AxesLabel->{"# of Grover iteration","Probability of success" },PlotStyle->{Orange,Thick}]

As expected, this follows the formula for the probability of success , where M is the number of correct solutions out of a total N after k steps

Quantum phase estimation (5)

The quantum phase estimation algorithm solves the problem of finding  in the eigenvalue equation (Ket[ψ]) = (Ket[ψ]), where  is a unitary operator. The inputs of the algorithm are  qubits at the initial state (Ket[ψ])(Ket[0]). The output is (Ket[ψ])(Ket).
Consider a phase shift as the unitary operator in which the aim is to find the phase θ:

QuantumOperator[{"Phase",2π θ}]["Eigenvalues"]

To specify the corresponding quantum circuit, one can use the built-in circuit "PhaseEstimation" that takes two input arguments: a unitary operator U and an integer n. The integer n specifies the number of qubits and controlled-(U^j) operators in the circuit, with j=0,1,…,n-1. The accuracy of phase estimation and the success probability depends on n:

phase=1/5;n=3;

circuit=QuantumCircuitOperator[{"PhaseEstimation",QuantumOperator[{"Phase",2Pi phase}],n}];
circuit["Diagram",FontSize->11]

Return the corresponding measurement, with all qubits prepared in (Ket[0]) state:

m=N[circuit][];

m["ProbabilityPlot"]

Given the outcome with the largest probability, estimate the phase:

FromDigits[Keys[TakeLargest[m["Probabilities"],1]][[1]]["Name"],2]/(2^n)//N

As expected, it is a rough estimate, since a small value was chosen for n. If one increases n, with a higher probability, one can get a better estimate of the phase.

Estimate the phase (the expected value is 1/5=0.2) for n=6:

With[{m=QuantumCircuitOperator[{"PhaseEstimation",N@QuantumOperator[{"Phase",2Pi phase}],6}][]},FromDigits[Keys[TakeLargest[m["Probabilities"],1]][[1]]["Name"],2]/(2^6)//N]