diff --git a/Dockerfile b/Dockerfile index 1cef67f5e8c..fb50dc08476 100644 --- a/Dockerfile +++ b/Dockerfile @@ -57,6 +57,7 @@ RUN cd ${HOME} && \ ./scripts/prebuild-kata.sh tutorials/LinearAlgebra LinearAlgebra.ipynb && \ ./scripts/prebuild-kata.sh tutorials/MultiQubitGates MultiQubitGates.ipynb && \ ./scripts/prebuild-kata.sh tutorials/MultiQubitSystems MultiQubitSystems.ipynb && \ + ./scripts/prebuild-kata.sh tutorials/MultiQubitSystemMeasurements MultiQubitSystemMeasurements.ipynb && \ #./scripts/prebuild-kata.sh tutorials/Oracles Oracles.ipynb && \ ./scripts/prebuild-kata.sh tutorials/Qubit Qubit.ipynb && \ ./scripts/prebuild-kata.sh tutorials/RandomNumberGeneration RandomNumberGenerationTutorial.ipynb && \ diff --git a/index.ipynb b/index.ipynb index 3259e4bfa36..169147aeb17 100644 --- a/index.ipynb +++ b/index.ipynb @@ -44,6 +44,8 @@ "\n", "* **[Single-qubit measurements (tutorial)](./tutorials/SingleQubitSystemMeasurements/SingleQubitSystemMeasurements.ipynb)**.\n", " Learn what quantum measurement is and how to use it for single-qubit systems.\n", + "* **[Multi-qubit measurements (tutorial)](./tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb)**.\n", + " Learn to use measurements for multi-qubit systems.\n", "* **[Measurements](./Measurements/Measurements.ipynb)**.\n", " Learn to distinguish quantum states using measurements.\n", "* **[Distinguish unitaries](./DistinguishUnitaries/DistinguishUnitaries.ipynb)**\\*.\n", diff --git a/tutorials/MultiQubitSystemMeasurements/.iqsharp-config.json b/tutorials/MultiQubitSystemMeasurements/.iqsharp-config.json new file mode 100644 index 00000000000..ec71e329ec5 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/.iqsharp-config.json @@ -0,0 +1 @@ +{"dump.basisStateLabelingConvention":"Bitstring"} \ No newline at end of file diff --git a/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.csproj b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.csproj new file mode 100644 index 00000000000..52d15e4c079 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.csproj @@ -0,0 +1,20 @@ + + + + netcoreapp3.1 + x64 + Quantum.Kata.MultiQubitSystemMeasurements + true + + + + + + + + + + + + + diff --git a/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb new file mode 100644 index 00000000000..fa3bfd466b5 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb @@ -0,0 +1,789 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Measurements in systems with multiple qubits\n", + "\n", + "In the previous tutorial, we discussed the concept of measurements done on single-qubit systems. \n", + "Building upon those ideas, this tutorial will introduce you to measurements done on multi-qubit systems, and how to implement such measurements in Q#. \n", + "This will include measuring a single qubit in a multi-qubit system, as well as measuring multiple qubits simultaneously. \n", + "\n", + "We recommend to go through the [tutorial that introduces single qubit system measurements](../SingleQubitSystemMeasurements/SingleQubitSystemMeasurements.ipynb) before starting this one.\n", + "$\\newcommand{\\ket}[1]{\\left|#1\\right>}$\n", + "$\\newcommand{\\bra}[1]{\\left<#1\\right|}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Types of measurements on multi-qubit systems\n", + "There are several types of measurements you can perform on an $n$-qubit system ($n>1$):\n", + "- Measuring all the qubits simultaneously in an orthogonal basis ($2^n$ possible outcomes). As we shall see below, this is a direct generalization of orthogonal basis measurements done in single-qubit systems introduced in the previous tutorial.\n", + "- Partial measurement: measuring $m$ qubits out of $n$, for $m\n", + " \n", + " \n", + " \n", + " \n", + " Measurement outcome\n", + " Probability of outcome\n", + " State after measurement\n", + " \n", + " \n", + " $b_i$\n", + " $|c_i|^2$\n", + " $\\ket{b_i}$\n", + " \n", + "\n", + " \n", + " \n", + "> Similar to measurements in single qubit systems, the assumption of normalization of the original wave function is required in order to ensure that the sum of all the outcome probabilities is 1." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 1: Multi-qubit measurement outcome probabilities I \n", + "Suppose that a two-qubit system is known to be in the following state:\n", + "$$\\ket \\psi = \\frac{1}{3}\\ket {00} + \\frac{2}{3} \\ket {01} + \\frac{2}{3}\\ket {11}$$\n", + "\n", + "If all the qubits are measured simultaneously in the computational basis, what are the outcome probabilities?\n", + "\n", + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-1:-Multi-qubit-measurement-outcome-probabilities-I).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 2: Multi-qubit measurement outcome probabilities II \n", + "Suppose that a two-qubit system is known to be in the following state:\n", + "$$\\ket \\psi = \\frac{2}{3}\\ket {00} + \\frac{1}{3} \\ket {01} + \\frac{2}{3}\\ket {11}$$\n", + "\n", + "If all the qubits are measured simultaneously in the Pauli X basis, i.e., in the $\\{ \\ket{++}, \\ket{+-}, \\ket{-+}, \\ket{--}\\}$ basis, what are the outcome probabilities?\n", + "\n", + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-2:-Multi-qubit-measurement-outcome-probabilities-II).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Measuring each qubit in a system one after another\n", + "As described in the previous sections, in theory it is possible to measure all the qubits in an $n$-qubit system simultaneously in an orthogonal basis. The post-measurement state of the qubits is then exactly one of the $2^n$ possible basis states.\n", + "\n", + "In practice, this is implemented by measuring all the qubits one after another. For example, if one wants to measure a two-qubit system in the computational basis, one can implement this by first measuring the first qubit in the computational basis to obtain $0$ or $1$, and then measuring the second qubit in the computational basis. This can result in one of the four possible outcomes: $00, 01, 10, 11$.\n", + "\n", + "This can be generalized to measurements in other bases, such as the 2-qubit Pauli X basis $\\ket{++}, \\ket{+-}, \\ket{-+}, \\ket{--}$, and the bases for larger numbers of qubits.\n", + "\n", + "> Note that measuring all qubits one after another can only be used to measure in orthogonal bases $\\{ \\ket{b_i}\\}$ such that each $\\ket{b_i}$ is a 'tensor product state'. That is, each $\\ket{b_i}$ must be of the form $\\ket{v_0} \\otimes \\ket{v_1} \\dotsc \\otimes \\ket{v_{n-1}}$, with each $\\ket{v_j}$ being a single-qubit basis state. \n", + "For example, for the 2-qubit Pauli X basis $\\ket{++}, \\ket{+-}, \\ket{-+}, \\ket{--}$ each basis state is a tensor product of states $\\ket{+}$ and $\\ket{-}$, which form a single-qubit basis state.\n", + "> \n", + "> Measuring in orthogonal bases which contain states which are not tensor product states, such as the Bell basis, are trickier to implement, and require appropriate unitary rotations in addition to measuring all qubits one after another. \n", + "> We will not discuss such measurements in this tutorial.\n", + "> You can find examples of such measurements and their implementations in the [Measurements kata](../../Measurements/Measurements.ipynb).\n", + ">\n", + "> If we restrict ourselves to measurements in tensor product states, the distinction between measuring all the qubits simultaneously versus one after another is not important for an ideal quantum computer: in terms of the outcomes and measurement probabilities, both are identical. Furthermore, as long as all the qubits are measured, the sequence in which they are measured is also inconsequential. These factors can be important in the case of real quantum computers with imperfect qubits, but we restrict the discussion to ideal systems in this tutorial.\n", + "\n", + "\n", + "### Demo: Measurement statistics for qubit-by-qubit full measurement\n", + "This demo illustrates the equivalence of the measurement probabilities for simultaneous measurement on all qubits, and measurements on each of the qubits executed one after another. Using the wave function from exercise 1 above as an example, we show that the measurement probabilities obtained using the `M` operation in Q# are the same as those expected theoretically for exercise 1. " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "// Run this cell using Ctrl+Enter (⌘+Enter on Mac)\n", + "// Run the next cell to see the output\n", + "\n", + "open Microsoft.Quantum.Diagnostics;\n", + "open Microsoft.Quantum.Preparation;\n", + "open Microsoft.Quantum.Arithmetic;\n", + "open Microsoft.Quantum.Convert;\n", + "\n", + "operation DemoBasisMeasurement(numRuns : Int) : Unit {\n", + " \n", + " // Define coefficients and obtain measurement probabilities\n", + " // for the state corresponding to Exercise 1\n", + " // |𝜓❭ = 0.33 |00❭ + 0.67 |01❭ + 0.67 |11❭ \n", + " // Use little endian format to encode basis states as integer indices.\n", + " let coefficients = [0.333, 0.0, 0.667, 0.667]; \n", + " let expected_probabilities = [0.111, 0.0, 0.445, 0.445];\n", + " \n", + " // Set up counter array for measurements.\n", + " mutable countArray = [0, 0, 0, 0]; \n", + " \n", + " use qs = Qubit[2];\n", + " for i in 1 .. numRuns {\n", + " let register = LittleEndian(qs);\n", + " // Prepare the state using PrepareArbitraryStateD library operation:\n", + " PrepareArbitraryStateD(coefficients, register);\n", + " if (i == 1) {\n", + " Message(\"The state |𝜓❭ of the system before measurement is:\");\n", + " DumpMachine();\n", + " } \n", + "\n", + " // Measure the first qubit, followed by the second qubit, and convert the result to little endian integer\n", + " let result = MeasureInteger(register);\n", + "\n", + " // Update countArray\n", + " set countArray w/= result <- countArray[result] + 1; \n", + " }\n", + " \n", + " // Obtain simulated probability of measurement for each outcome\n", + " mutable simulated_probabilities = [];\n", + " for i in 0 .. 3 {\n", + " set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)];\n", + " }\n", + " \n", + " Message($\"Theoretical measurement probabilities are {expected_probabilities}\");\n", + " Message($\"Simulated measurement probabilities are {simulated_probabilities}\");\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%simulate DemoBasisMeasurement numRuns=100" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The simulated probabilities will be different for each run of `DemoBasisMeasurement`. The simulated and theoretical probabilities are not expected to be identical, since measurements are probabilistic. However, we expect the values to be similar, and the simulated probabilities to approach the theoretical probabilities as the parameter `numRuns` is increased." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using full measurements to identify the state of the system\n", + "\n", + "Full measurements can also be used to identify the state of the system, if it is guaranteed to be in one of several possible orthogonal states.\n", + "\n", + "### Exercise 3: Distinguish four basis states\n", + "\n", + "**Input:** Two qubits (stored in an array of length 2) which are guaranteed to be in one of the four basis states ($|00\\rangle$, $|01\\rangle$, $|10\\rangle$, or $|11\\rangle$).\n", + "\n", + "**Output:**\n", + "\n", + "* 0 if the qubits were in the $|00\\rangle$ state,\n", + "* 1 if they were in the $|01\\rangle$ state, \n", + "* 2 if they were in the $|10\\rangle$ state, \n", + "* 3 if they were in the $|11\\rangle$ state.\n", + "\n", + "In this task and the subsequent ones the order of qubit states in task description matches the order of qubits in the array (i.e., $|10\\rangle$ state corresponds to `qs[0]` in state $|1\\rangle$ and `qs[1]` in state $|0\\rangle$).\n", + "\n", + "The state of the qubits at the end of the operation does not matter." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T1_BasisStateMeasurement\n", + "\n", + "operation BasisStateMeasurement(qs : Qubit[]) : Int {\n", + " // Type your answer below\n", + " // Then run the cell using Ctrl+Enter (⌘+Enter on macOS).\n", + " // ...\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb##Exercise-3:-Distinguish-four-basis-states).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Partial Measurements\n", + "\n", + "For a system with $n>1$ qubits, it is possible to measure $m The symbol $\\otimes$ represents the tensor product or the Kronecker product of two matrices. It is different from the usual matrix multiplication (see the [Linear Algebra tutorial](../LinearAlgebra/LinearAlgebra.ipynb#Tensor-Product) for a refresher). In the current context, $|b_i\\rangle \\langle b_i| \\otimes \\mathbb{1}_{n-m}$ simply means that the operator $|b_i\\rangle \\langle b_i|$ acts only on the $m$ qubits being measured, while the effect of $P_i$ on the remaining qubits is $\\mathbb{1}_{n-m}$, i.e., the identity operator. \n", + "\n", + "Analogous to the case for measurements for single qubit systems, the rules for partial measurement probabilities and outcomes can be summarized as follows:\n", + "- When a measurement is done, one of these projectors is chosen randomly. The probability of choosing projector $P_i$ is $\\big|P_i|\\psi\\rangle\\big|^2$.\n", + "- If the projector $P_i$ is chosen, the measurement outcome is $b_i$, and the state of the system after the measurement is given by\n", + "$$\n", + "\\frac{P_i |\\psi\\rangle}{\\big|P_i |\\psi\\rangle\\big|}.\n", + "$$\n", + "\n", + "For example, consider a two-qubit system in the state $\\ket \\psi = \\frac{1}{\\sqrt{2}}\\ket{01} - \\frac{1}{\\sqrt 2}\\ket{10}$. Consider a measurement of the first qubit in the computational basis, i.e., in the $\\{\\ket 0 , \\ket 1 \\}$ basis. Then, we have two projectors that represent this measurement:\n", + "\\begin{align*}\n", + "P_0 &= \\ket 0\\bra 0 \\otimes \\mathbb{1},\\\\\n", + "P_1 &= \\ket 1 \\bra 1 \\otimes \\mathbb{1}.\n", + "\\end{align*}\n", + "\n", + "The action of $P_0$ on $\\ket \\psi$ is \n", + "\\begin{align*}\n", + "P_0 \\ket \\psi &= \\left(\\ket 0\\bra 0 \\otimes \\mathbb{1}\\right) \\frac{1}{\\sqrt 2}\\big(\\ket{01} - \\ket{10}\\big) = \\\\\n", + " &= \\frac{1}{\\sqrt 2} \\big( \\ket 0\\bra 0 0\\rangle \\otimes \\mathbb{1} \\ket{1} - \\ket 0 \\bra 0 1\\rangle \\otimes \\mathbb{1} \\ket 0 \\big) = \\\\\n", + " &= \\frac{1}{\\sqrt 2} \\ket{01}.\n", + "\\end{align*}\n", + "\n", + "Similarly, we obtain \n", + "$$\n", + "P_1 \\ket\\psi = -\\frac{1}{\\sqrt 2} \\ket{10}.\n", + "$$\n", + "\n", + "Clearly, we have $\\big|P_0 \\ket \\psi\\big| = \\big|P_1 \\ket \\psi\\big| = \\frac{1}{2}$ in this case. Thus, the probabilities of measuring $0$ and $1$ are both $0.5$, with the post-measurement states of system being $\\ket{01}$ and $\\ket{10}$, respectively.\n", + "\n", + "> Similar to the case of single-qubit system measurements, the applicability of the formalism above requires the state of the multi-qubit system, $\\ket \\psi$, to be normalized. This is required to ensure that all the probabilities of individual outcomes add up to 1." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 4: Partial measurement probabilities for the Hardy state\n", + "\n", + "Consider a 2-qubit system in the state $\\ket \\psi = \\frac{1}{\\sqrt{12}} \\big(3|00\\rangle + |01\\rangle + |10\\rangle + |11\\rangle\\big)$.\n", + "\n", + "If only the first qubit is measured in the computational basis, what are the probabilities of the outcomes, and the post-measurement states of the system?\n", + "\n", + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-4:-Partial-measurement-probabilities-for-the-Hardy-state).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Demo: Measurement statistics for partial measurement\n", + "Using the `M` operation in Q#, we demonstrate that the simulated outcome probabilities and post-measurement outcomes match the theoretical values obtained using the projection operators as described above. We use the Hardy state from Exercise 4 with a computational basis measurement on the first qubit for this purpose." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "open Microsoft.Quantum.Diagnostics;\n", + "open Microsoft.Quantum.Preparation;\n", + "open Microsoft.Quantum.Arithmetic;\n", + "open Microsoft.Quantum.Convert;\n", + "open Microsoft.Quantum.Math;\n", + "\n", + "operation DemoPartialMeasurement(numRuns : Int) : Unit {\n", + " let divider = \"--------------------------------------------------------------------------------------------------\";\n", + " // \n", + " // We can use coefficients without normalization in PrepareArbitraryStateD, \n", + " // the operation will normalize them automatically.\n", + " let coefficients = [3., 1., 1., 1.]; \n", + " let expected_probabilities = [0.833, 0.167];\n", + " \n", + " // Set up the counter array for measurements.\n", + " mutable countArray = [0, 0];\n", + " \n", + " use qs = Qubit[2];\n", + " for i in 1 .. numRuns {\n", + " // Prepare the state from Exercise 4:\n", + " // |𝜓❭ = (1/√12)(3|00⟩+|01⟩+|10⟩+|11⟩) \n", + " PrepareArbitraryStateD(coefficients, LittleEndian(qs));\n", + " \n", + " // Display the state of the qubits.\n", + " if (i == 1) {\n", + " Message(\"The state |𝜓❭ of the system before measurement is:\");\n", + " DumpMachine();\n", + " Message(divider);\n", + " }\n", + "\n", + " // Measure the first qubit.\n", + " let outcome = M(qs[0]) == Zero ? 0 | 1;\n", + " set countArray w/= outcome <- countArray[outcome] + 1;\n", + " \n", + " if (countArray[outcome] == 1) { \n", + " // The first time the outcome is 0/1, print the system state afterwards.\n", + " Message(\"For outcome {outcome}, the post-measurement state of the system is:\");\n", + " DumpMachine();\n", + " }\n", + " ResetAll(qs);\n", + " }\n", + " \n", + " // Obtain simulated probability of measurement for each outcome\n", + " mutable simulated_probabilities = [];\n", + " for i in 0 .. 1 {\n", + " set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)];\n", + " }\n", + " \n", + " Message($\"Theoretical measurement probabilities are {expected_probabilities}\");\n", + " Message($\"Simulated measurement probabilities are {simulated_probabilities}\");\n", + "}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%simulate DemoPartialMeasurement numRuns=100" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The simulated and theoretical measurement probabilities are not expected to match exactly, but should be close to each other, since measurement is probabilistic. However, the post-measurement states from the simulation should match the expected states for Exercise 4 precisely, since partial state collapse is not a probabilistic process." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using partial measurements to identify the state of the system\n", + "\n", + "In certain situations, it is possible to distinguish between orthogonal states of multi-qubit systems using partial measurements, as illustrated in the next exercise.\n", + "\n", + "### Exercise 5: Distinguish orthogonal states using partial measurements\n", + "\n", + "**Input**: A 3-qubit system which is guaranteed to be in either the $\\ket{++-}$ state, or the $\\ket{---}$ state.\n", + "\n", + "**Output**: \n", + "- 0 if the qubit is in the $\\ket{++-}$ state,\n", + "- 1 if the qubit is in the $\\ket{---}$ state.\n", + "\n", + "The state of the qubits at the end of the operation should be the same as the initial state." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T2_IsPlusPlusMinus\n", + "\n", + "operation IsPlusPlusMinus (qs : Qubit[]) : Int {\n", + " // ...\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-5:-Distinguish-orthogonal-states-using-partial-measurements).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Measurements and entanglement\n", + "\n", + "Qubits entanglement has an effect on the measurement statistics of the system. If two qubits are entangled, then their measurement outcomes will be correlated, while separable states (which are by definition not entangled) have uncorrelated measurement outcomes.\n", + "\n", + "> It is useful to revisit the concepts of entanglement and separable states, which were introduced in the [tutorial on multi-qubit systems](../MultiQubitSystems/MultiQubitSystems.ipynb#Entanglement). Consider a system of $n>1$ number of qubits, which we divide into two parts: A, consisting of $m$ qubits, and B, consisting of the remaining $n-m$ qubits. We say that the state $\\ket \\psi$ of the entire system is separable if it can be expressed as a tensor product of the states of parts A and B: \n", + "$$\n", + "\\ket \\psi = \\ket {\\phi_A} \\otimes \\ket{\\phi_B}\n", + "$$\n", + "where $\\ket{\\phi_A}$ and $\\ket{\\phi_B}$ are wave functions that describe parts $A$ and $B$, respectively. If it is not possible to express $\\ket \\psi$ in such a form, then we say that system A is entangled with system B.\n", + "\n", + "Consider a measurement on the subsystem $A$ of a separable state. Let the measurement be done in a basis $\\{ \\ket{b_0},\\dotsc,\\ket{b_{2^m-1}}\\}$. According to the projection formalism, a projection operator $P_i = \\ket{b_i}\\bra{b_i} \\otimes \\mathbb{1}$ is chosen randomly. The corresponding post-measurement state of the system is then given by\n", + "\\begin{align*}\n", + "\\ket{\\psi}_{i} &\\equiv \\frac{P_i \\ket{\\psi}}{\\big|P_i \\ket{\\psi}\\big|} = \\\\\n", + " &= \\frac{\\ket{b_i}\\bra{b_i}\\phi_A\\rangle \\otimes \\ket {\\phi_B}}{\\big|\\ket{b_i}\\bra{b_i}\\phi_A\\rangle \\otimes \\ket {\\phi_B}\\big|} = \\\\\n", + " &= \\frac{\\bra{b_i}\\phi_A\\rangle \\cdot \\ket{b_i} \\otimes \\ket {\\phi_B}}{\\big|\\ket{b_i}\\big| \\cdot \\bra{b_i}\\phi_A\\rangle \\cdot \\big| \\ket {\\phi_B}\\big|} = \\\\\n", + " &= \\ket{b_i} \\otimes \\ket{\\phi_B}.\n", + "\\end{align*}\n", + "\n", + "Thus, the state of subsystem $B$ after the measurement is $\\ket{\\phi_B}$ independently of the outcome $i$ of the measurement on the first qubit. The results of a subsequent measurement on subsystem $B$, including outcome probabilities, will be independent of the result of the first measurement. In other words, the outcomes of the two measurements will be uncorrelated.\n", + "\n", + "On the other hand, if the system is entangled, then the measurement outcomes will be correlated, in a manner dictated by the bases chosen for the measurements on the two subsystems. The following exercise illustrates this phenomenon." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 6: Sequential measurements on an entangled state and a separable state\n", + "Consider two two-qubit states:\n", + "- The Bell state $|\\Phi^{+}\\rangle = \\frac{1}{\\sqrt{2}} \\big (|00\\rangle + |11\\rangle\\big)$.\n", + "- A state $\\ket \\Theta = \\frac{1}{2} \\big( \\ket{00} + \\ket{01} + \\ket{10} + \\ket{11} \\big)$.\n", + "\n", + "For both states, consider a measurement on the first qubit, followed by a measurement on the second qubit, both done in the computational basis. For which state can we expect the measurement outcomes to be correlated? Verify by calculating the sequential measurement probabilities explicitly for both states. \n", + "\n", + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-6:-Sequential-measurements-on-an-entangled-state-and-a-separable-state).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "> Congratulations! You have learned enough about the measurements to start solving problems from the [Measurements kata](../../Measurements/Measurements.ipynb)!\n", + "You can give them a try and return to the rest of this tutorial later, or keep reading." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## State modification using partial measurements\n", + "\n", + "For certain multi-qubit systems prepared in a superposition state, it is possible to use partial measurements to collapse a part of the system to some desired state. \n", + "\n", + "### Exercise 7: State selection using partial measurements \n", + "\n", + "**Input**: \n", + "1. A 2-qubit system in the state\n", + "$$\n", + "|\\psi\\rangle = \\frac{1}{\\sqrt{2}} |0\\rangle \\otimes ( a |0\\rangle + b|1\\rangle) + \\frac{1}{\\sqrt{2}} |1\\rangle \\otimes (b|0\\rangle + a |1\\rangle),\n", + "$$\n", + "where the constants $a$ and $b$ satisfying $|a|^2 + |b|^2 = 1$ are unknown.\n", + "2. An integer $ind$ which is either $0$ or $1$.\n", + "\n", + "**Goal**: \n", + "- If $ind$ equals 0, the state of the state of the second qubit should be $a|0\\rangle + b|1\\rangle$\n", + "- If $ind$ equals 1, the state of the second qubit should be $b|0\\rangle + a |1\\rangle$. \n", + "\n", + "The state of the first qubit at the end does not matter." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T3_StateSelction\n", + "\n", + "operation StateSelction (qs : Qubit[], ind : Int) : Unit {\n", + " // ...\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-7:-State-selection-using-partial-measurements).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Any multi-qubit state can be prepared from the $|0...0\\rangle$ state using an appropriate combination of quantum gates. \n", + "However, sometimes it is easier and more efficient to prepare a state using partial measurements. \n", + "You could prepare a simpler state involving additional qubits, which, when measured, result in a collapse of the remaining qubits to the desired state with a high probability. This is called **post-selection**, and is particularly useful if it is easier to prepare the pre-measurement state with the extra qubits than to prepare the desired state directly using unitary gates alone. This is demonstrated by the following exercise.\n", + "\n", + "### Exercise 8: State preparation using partial measurements\n", + "\n", + "**Input:** Two qubits (in an array) which are in the state $\\ket{00}$.\n", + "\n", + "**Goal:** Modify the qubits to the state $\\frac{1}{\\sqrt{3}} \\big(|00\\rangle + |01\\rangle + |10\\rangle\\big)$ using post-selection.\n", + "\n", + "
\n", + "
\n", + " Need a hint? Click here\n", + " Consider a 3-qubit state $\\frac{1}{2}(|00\\rangle + |01\\rangle + |11\\rangle) \\otimes |0\\rangle + \\frac{1}{2} |11\\rangle \\otimes |1\\rangle$.\n", + " What happens when one measures the third qubit?\n", + "
" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T4_PostSelection\n", + "\n", + "operation PostSelection (qs : Qubit[]) : Unit {\n", + " // ...\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-8:-State-preparation-using-partial-measurements).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Joint measurements\n", + "\n", + "Joint measurements, also known as Pauli measurements, are a generalization of 2-outcome measurements to multiple qubits and other bases. In Q#, joint measurements in Pauli bases are implemented using the [Measure](https://docs.microsoft.com/en-us/qsharp/api/qsharp/microsoft.quantum.intrinsic.measure) operation. Let's review single-qubit measurements in a different light before discussing joint measurements. \n", + "\n", + "### Single-qubit Pauli measurement\n", + "For single-qubit systems, any measurement corresponding to an orthogonal basis can be associated with a Hermitian matrix with eigenvalues $\\pm 1$. The possible measurement outcomes (represented as `Result` in Q#) are the eigenvalues of the Hermitian matrix, and the corresponding projection matrices for the measurement are the projection operators onto the *eigenspaces* corresponding to the eigenvalues. \n", + "\n", + "For example, consider the computational basis measurement, which can result in outcomes `Zero` or `One` corresponding to states $\\ket 0$ and $\\ket 1$. This measurement is associated with the Pauli Z operator, which is given by \n", + "$$\n", + "Z = \\begin{pmatrix} 1 & 0 \\\\ 0 & -1\\end{pmatrix} = \\ket{0}\\bra{0} - \\ket{1}\\bra{1}.\n", + "$$\n", + "The $Z$ operator has two eigenvalues, $1$ and $-1$, with corresponding eigenvectors $\\ket{0}$ and $\\ket{1}$. A $Z$-measurement is then a measurement in the $\\{\\ket{0},\\ket{1}\\}$ basis, with the measurement outcomes being $1$ and $-1$ respectively. In Q#, by convention, an eigenvalue of $1$ corresponds to a `Result` of `Zero`, while an eigenvalue of $-1$ corresponds to a `Result` of `One`.\n", + "\n", + "Similarly, one can implement measurements corresponding to the Pauli X and Y operators. We summarize the various properties below:\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Pauli OperatorMatrixEigenvalueEigenvector/post-measurement stateMeasurement Result in Q#
$X$$\\begin{bmatrix} 0 & 1 \\\\ 1 & 0 \\end{bmatrix}$+1$\\ket{+}$Zero
-1$\\ket{-}$One
$Y$$\\begin{bmatrix} 0 & -i \\\\ i & 0 \\end{bmatrix}$+1$\\ket{i}$Zero
-1$\\ket{-i}$One
$Z$$\\begin{bmatrix} 1 & 0 \\\\ 0 & -1 \\end{bmatrix}$+1$\\ket{0}$Zero
-1$\\ket{1}$One
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In general, any measurement on a single qubit which results in two outcomes corresponds to the Hermitian operator $U Z U^\\dagger$, for some $2\\times 2$ unitary matrix $U$.\n", + "\n", + "Joint measurements are a generalization of this principle for multi-qubit matrices.\n", + "\n", + "\n", + "### Parity measurements\n", + "The simplest joint measurement is a parity measurement. A parity measurement treats computational basis vectors differently depending on whether the number of 1's in the basis vector is even or odd. \n", + "\n", + "For example, the operator $Z\\otimes Z$, or $ZZ$ in short, is the parity measurement operator for a two-qubit system. The eigenvalues $1$ and $-1$ correspond to the subspaces spanned by basis vectors $\\{ |00\\rangle, |11\\rangle \\}$ and $\\{ |01\\rangle, |10\\rangle \\}$, respectively. That is, when a $ZZ$ measurement results in a `Zero` (i.e. the eigenvalue $+1$), the post-measurement state is a superposition of only those computational basis vectors which have an even number of $1$'s. On the other hand, a result of `One` corresponds to a post-measurement state with only odd parity computational basis vectors.\n", + "\n", + "> Let's see what happens to various two-qubit states after the parity measurement. The $Z \\otimes Z$ matrix for two qubits is: \n", + ">\n", + ">$$Z \\otimes Z = \\begin{bmatrix}\n", + " 1 & 0 & 0 & 0 \\\\\n", + " 0 & -1 & 0 & 0 \\\\\n", + " 0 & 0 & -1 & 0 \\\\\n", + " 0 & 0 & 0 & 1 \\\\\n", + "\\end{bmatrix}$$\n", + ">\n", + ">When this transformation is applied to a basis state $|00\\rangle$, we get\n", + ">\n", + "> $$\\begin{bmatrix}\n", + " 1 & 0 & 0 & 0 \\\\\n", + " 0 & -1 & 0 & 0 \\\\\n", + " 0 & 0 & -1 & 0 \\\\\n", + " 0 & 0 & 0 & 1 \\\\\n", + "\\end{bmatrix} \n", + "\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\\\ \\end{bmatrix} = \n", + "\\begin{bmatrix} 1 \\\\ 0 \\\\ 0 \\\\ 0 \\\\ \\end{bmatrix}$$\n", + ">\n", + "> Comparing this to the characteristic equation for eigenvectors of $Z \\otimes Z$ given by\n", + "$ Z \\otimes Z |\\psi\\rangle = \\lambda |\\psi\\rangle$,\n", + "it is easy to see that $|00\\rangle$ belongs to the $+1$ eigenspace, hence the $Z \\otimes Z$ measurement will return `Zero` and leave the state unchanged.\n", + ">\n", + "> Similarly, it can easily be verified that $|11\\rangle$ also belongs to $+1$ eigenspace, while $|01\\rangle$ and $|10\\rangle$ belong to the $-1$ eigenspace.\n", + "> \n", + "> Now, what happens if we apply a $Z \\otimes Z$ measurement to a superposition state $\\alpha |00\\rangle + \\beta |11\\rangle$? We can see that \n", + ">\n", + "> $$\\begin{bmatrix}\n", + " 1 & 0 & 0 & 0 \\\\\n", + " 0 & -1 & 0 & 0 \\\\\n", + " 0 & 0 & -1 & 0 \\\\\n", + " 0 & 0 & 0 & 1 \\\\\n", + "\\end{bmatrix} \n", + "\\begin{bmatrix} \\alpha \\\\ 0 \\\\ 0 \\\\ \\beta \\\\ \\end{bmatrix} = \n", + "\\begin{bmatrix} \\alpha \\\\ 0 \\\\ 0 \\\\ \\beta \\\\ \\end{bmatrix}$$\n", + ">\n", + ">So this state also belongs to the $+1$ eigenspace, and measuring it will return `Zero` and leave the state unchanged. Similarly, we can verify that an $\\alpha |01\\rangle + \\beta |10\\rangle$ state belongs to the $-1$ eigenspace, and measuring it will return `One` without changing the state.\n", + "\n", + "Similarly, a parity measurement on a higher number of qubits can be implemented using a $Z \\otimes \\dotsc \\otimes Z$ measurement." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 9: Two-qubit parity measurement\n", + "\n", + "**Inputs**: Two qubits stored in an array which are guaranteed to be either in a superposition of the states $|00\\rangle$ and $|11\\rangle$ or in a superposition of states $|01\\rangle$ and $|10\\rangle$.\n", + "\n", + "**Output**: 0 if qubits were in the first superposition, 1 if they were in the second superposition. \n", + "*The state of the qubits at the end of the operation should be the same as the starting state.*" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T5_ParityMeasurement\n", + "\n", + "operation ParityMeasurement (qs : Qubit[]) : Int {\n", + " // ...\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-9:-Two-qubit-parity-measurement).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multi-qubit Pauli measurements\n", + "Joint measurement is a generalization of the measurement in the computational basis. \n", + "Pauli measurements can also be generalized to a larger number of qubits. A multi-qubit Pauli measurement corresponds to an operator $M_1 \\otimes \\dotsc \\otimes M_n$, with each $M_i$ being from the set of gates $\\{X,Y,Z,I\\}$. If at least one of the operators is not the identity matrix, then the measurement can result in two outcomes: a `Result` of `Zero` corresponding to eigenvalue $+1$ and a `Result` of `One` corresponding to the eigenvalue $-1$. The corresponding projection operators are the projections onto the corresponding eigenspaces.\n", + "\n", + "For example, a Pauli/joint measurement corresponding to the $X\\otimes Z$ operator can be characterized as follows:\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
EigenvalueMeasurement Result in Q#EigenbasisMeasurement Projector
$+1$Zero$\\{ \\ket{0,+}, \\ket{1,-} \\}$$P_{+1} = \\ket{0,+}\\bra{0,+} + \\ket{1,-} \\bra{1,-}$
$-1$One$\\{ \\ket{0,-}, \\ket{1,+} \\}$$P_{-1} = \\ket{0,-}\\bra{0,-} + \\ket{1,+} \\bra{1,+}$
\n", + " \n", + " The rules for measurements are then the same as those outlined in the [partial measurements section](#Partial-Measurements), with the projection operators in the table." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 10: Parity measurement in different basis\n", + "\n", + "Consider a system which is in a state $\\alpha |00\\rangle + \\beta |01\\rangle + \\beta |10\\rangle + \\alpha |11\\rangle$.\n", + "\n", + "What are the possible outcomes and their associated probabilities, if a measurement in an $XX$ Pauli measurement is done?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "*Can't come up with a solution? See the explained solution in the [Multi-Qubit System Measurement Workbook](./Workbook_MultiQubitSystemMeasurements.ipynb#Exercise-10:-Parity-measurement-in-different-basis).*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conclusion\n", + "\n", + "Congratulations! You have learned enough to solve problems from the [Measurements kata](../../Measurements/Measurements.ipynb) and the [Joint Measurements kata](../../JointMeasurements/JointMeasurements.ipynb)." + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Q#", + "language": "qsharp", + "name": "iqsharp" + }, + "language_info": { + "file_extension": ".qs", + "mimetype": "text/x-qsharp", + "name": "qsharp", + "version": "0.14" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +} diff --git a/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.sln b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.sln new file mode 100644 index 00000000000..cb667c65bb0 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.32002.261 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "MultiQubitSystemMeasurements", "MultiQubitSystemMeasurements.csproj", "{4B6FFEA0-E257-4567-8FD8-26C79E7B7B55}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {4B6FFEA0-E257-4567-8FD8-26C79E7B7B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {4B6FFEA0-E257-4567-8FD8-26C79E7B7B55}.Debug|Any CPU.Build.0 = Debug|Any CPU + {4B6FFEA0-E257-4567-8FD8-26C79E7B7B55}.Release|Any CPU.ActiveCfg = Release|Any CPU + {4B6FFEA0-E257-4567-8FD8-26C79E7B7B55}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {5B7089BA-08A6-44AB-BA1A-CA00B0185CB4} + EndGlobalSection +EndGlobal diff --git a/tutorials/MultiQubitSystemMeasurements/README.md b/tutorials/MultiQubitSystemMeasurements/README.md new file mode 100644 index 00000000000..c688abf28a0 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/README.md @@ -0,0 +1,8 @@ +# Welcome! + +This tutorial introduces the basics of quantum measurements for multi-qubit systems. + +You can run the tutorial online [here](https://mybinder.org/v2/gh/Microsoft/QuantumKatas/main?filepath=tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb). +Alternatively, you can install Jupyter and Q# on your machine, as described [here](https://docs.microsoft.com/quantum/install-guide#develop-with-jupyter-notebooks), and run the tutorial locally by navigating to this folder and starting the notebook from the command line using the following command: + + jupyter notebook MultiQubitSystemMeasurements.ipynb diff --git a/tutorials/MultiQubitSystemMeasurements/ReferenceImplementation.qs b/tutorials/MultiQubitSystemMeasurements/ReferenceImplementation.qs new file mode 100644 index 00000000000..015352bdb53 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/ReferenceImplementation.qs @@ -0,0 +1,64 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +////////////////////////////////////////////////////////////////////// +// This file contains reference solutions to all tasks. +// You should not modify anything in this file. +// We recommend that you try to solve the tasks yourself first, +// but feel free to look up the solution if you get stuck. +////////////////////////////////////////////////////////////////////// + +namespace Quantum.Kata.MultiQubitSystemMeasurements { + open Microsoft.Quantum.Intrinsic; + open Microsoft.Quantum.Math; + open Microsoft.Quantum.Canon; + open Microsoft.Quantum.Measurement; + + // Exercise 3. Identify computational basis states + operation BasisStateMeasurement_Reference(qs : Qubit[]) : Int { + // Measurement on the first qubit gives the higher bit of the answer, on the second - the lower + let m1 = M(qs[0]) == Zero ? 0 | 1; + let m2 = M(qs[1]) == Zero ? 0 | 1; + return m1 * 2 + m2; + } + // Exercise 5. Distinguish orthogonal states + operation IsPlusPlusMinus_Reference (qs : Qubit[]) : Int { + return Measure([PauliX], [qs[0]]) == Zero ? 0 | 1; + } + + // Exercise 7. State selection using partial measurements + operation StateSelction_Reference(qs : Qubit[], i : Int) : Unit { + if (i == 0) { + if (M(qs[0]) == One){ + // apply the X gate to the second qubit + X(qs[1]); + } + } else { + if (M(qs[0]) == Zero){ + // apply the X gate to the second qubit only + X(qs[1]); + } + } + } + + // Exercise 8. State preparation using partial measurements + operation PostSelection_Reference ( qs : Qubit[] ): Unit { + // Initialize the extra qubit + use anc = Qubit(); + // Using the repeat-until-success pattern to prepare the right state + repeat { + ApplyToEach(H, qs); + Controlled X(qs, anc); + let res = MResetZ(anc); + } + until (res == Zero) + fixup { + ResetAll(qs); + } + } + + // Exercise 9. Two qubit parity Measurement + operation ParityMeasurement_Reference(qs : Qubit[]) : Int { + return Measure([PauliZ, PauliZ], qs) == Zero ? 0 | 1; + } +} \ No newline at end of file diff --git a/tutorials/MultiQubitSystemMeasurements/Tasks.qs b/tutorials/MultiQubitSystemMeasurements/Tasks.qs new file mode 100644 index 00000000000..4f961a8dc82 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/Tasks.qs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +////////////////////////////////////////////////////////////////// +// This file is a back end for the tasks in the tutorial. +// We strongly recommend to use the Notebook version of the tutorial +// to enjoy the full experience. +////////////////////////////////////////////////////////////////// + +namespace Quantum.Kata.MultiQubitSystemMeasurements { + open Microsoft.Quantum.Intrinsic; + open Microsoft.Quantum.Math; + + // Exercise 3. Identify computational basis states + operation BasisStateMeasurement(qs : Qubit[]) : Int { + // ... + return 0; + } + + // Exercise 5. Distinguish orthogonal states + operation IsPlusPlusMinus(qs : Qubit[]) : Int { + // ... + return 0; + } + + // Exercise 7. State selection using partial measurements + operation StateSelction(qs : Qubit[], i : Int) : Unit { + // ... + } + + // Exercise 8. State preparation using partial measurements + operation PostSelection( qs : Qubit[] ): Unit { + // ... + } + + // Exercise 9. Two qubit parity Measurement + operation ParityMeasurement(qs : Qubit[]) : Int{ + // ... + return 1; + } +} + diff --git a/tutorials/MultiQubitSystemMeasurements/Tests.qs b/tutorials/MultiQubitSystemMeasurements/Tests.qs new file mode 100644 index 00000000000..ed89d5ef521 --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/Tests.qs @@ -0,0 +1,244 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. + +////////////////////////////////////////////////////////////////////// +// This file contains testing harness for all tasks. +// You should not modify anything in this file. +////////////////////////////////////////////////////////////////////// + +namespace Quantum.Kata.MultiQubitSystemMeasurements { + open Microsoft.Quantum.Intrinsic; + open Microsoft.Quantum.Canon; + open Microsoft.Quantum.Diagnostics; + open Microsoft.Quantum.Convert; + open Microsoft.Quantum.Math; + open Microsoft.Quantum.Arrays; + open Microsoft.Quantum.Measurement; + open Microsoft.Quantum.Random; + + open Quantum.Kata.Utils; + // ------------------------------------------------------ + // "Framework" operation for testing multi-qubit tasks for distinguishing states of an array of qubits + // with Int return + operation DistinguishStates_MultiQubit (nQubits : Int, + nStates : Int, + statePrep : ((Qubit[], Int, Double) => Unit is Adj), + testImpl : (Qubit[] => Int), + preserveState : Bool, + stateNames : String[]) : Unit { + let nTotal = 100; + // misclassifications will store the number of times state i has been classified as state j (dimension nStates^2) + mutable misclassifications = [0, size = nStates * nStates]; + // unknownClassifications will store the number of times state i has been classified as some invalid state (index < 0 or >= nStates) + mutable unknownClassifications = [0, size = nStates]; + + use qs = Qubit[nQubits]; + for i in 1 .. nTotal { + // get a random integer to define the state of the qubits + let state = DrawRandomInt(0, nStates - 1); + // get a random rotation angle to define the exact state of the qubits + // for some exercises, this value might be a dummy variable which does not matter + let alpha = DrawRandomDouble(0.0, 1.0) * PI(); + + // do state prep: convert |0...0⟩ to outcome with return equal to state + statePrep(qs, state, alpha); + + // get the solution's answer and verify that it's a match, if not, increase the exact mismatch count + let ans = testImpl(qs); + if ((ans >= 0) and (ans < nStates)) { + // classification result is a valid state index - check if is it correct + if (ans != state) { + set misclassifications w/= ((state * nStates) + ans) <- (misclassifications[(state * nStates) + ans] + 1); + } + } + else { + // classification result is an invalid state index - file it separately + set unknownClassifications w/= state <- (unknownClassifications[state] + 1); + } + + if (preserveState) { + // check that the state of the qubit after the operation is unchanged + Adjoint statePrep(qs, state, alpha); + AssertAllZero(qs); + } else { + // we're not checking the state of the qubit after the operation + ResetAll(qs); + } + } + + mutable totalMisclassifications = 0; + for i in 0 .. nStates - 1 { + for j in 0 .. nStates - 1 { + if (misclassifications[(i * nStates) + j] != 0) { + set totalMisclassifications += misclassifications[i * nStates + j]; + Message($"Misclassified {stateNames[i]} as {stateNames[j]} in {misclassifications[(i * nStates) + j]} test runs."); + } + } + if (unknownClassifications[i] != 0) { + set totalMisclassifications += unknownClassifications[i]; + Message($"Misclassified {stateNames[i]} as Unknown State in {unknownClassifications[i]} test runs."); + } + } + // This check will tell the total number of failed classifications + Fact(totalMisclassifications == 0, $"{totalMisclassifications} test runs out of {nTotal} returned incorrect state (see output for details)."); + } + + // ------------------------------------------------------ + // Exercise 3: Distinguish four basis states + // ------------------------------------------------------ + operation StatePrep_BasisStateMeasurement(qs : Qubit[], state : Int, dummyVar : Double) : Unit is Adj { + if (state / 2 == 1) { + // |10⟩ or |11⟩ + X(qs[0]); + } + if (state % 2 == 1) { + // |01⟩ or |11⟩ + X(qs[1]); + } + } + + @Test("Microsoft.Quantum.Katas.CounterSimulator") + operation T1_BasisStateMeasurement () : Unit { + DistinguishStates_MultiQubit(2, 4, StatePrep_BasisStateMeasurement, BasisStateMeasurement, false, ["|00⟩", "|01⟩", "|10⟩", "|11⟩"]); + } + + + // ------------------------------------------------------ + // Exercise 5: Distinguish orthogonal states using partial measurements + // ------------------------------------------------------ + operation StatePrep_IsPlusPlusMinus (qs : Qubit[], state : Int, dummyVar : Double) : Unit is Adj{ + if (state == 0){ + // prepare the state |++-⟩ + H(qs[0]); + H(qs[1]); + X(qs[2]); + H(qs[2]); + } else { + // prepare the state |---⟩ + X(qs[0]); + H(qs[0]); + X(qs[1]); + H(qs[1]); + X(qs[2]); + H(qs[2]); + } + } + + @Test("Microsoft.Quantum.Katas.CounterSimulator") + operation T2_IsPlusPlusMinus () : Unit { + DistinguishStates_MultiQubit(3, 2, StatePrep_IsPlusPlusMinus, IsPlusPlusMinus, false, ["|++-⟩", "|---⟩"]); + } + + + + + // ------------------------------------------------------ + // Exercise 7: State selection using partial measurements + // ------------------------------------------------------ + operation stateInitialize_StateSelction(alpha: Double, qs : Qubit[]) : Unit { + // Prepare the state to be input to the testImplementation + // set the second qubit in a superposition a |0⟩ + b|1⟩ + // with a = cos alpha, b = sin alpha + Ry(2.0 * alpha, qs[1]); + + H(qs[0]); + // Apply CX gate + CX(qs[0], qs[1]); + } + + operation statePrepare_StateSelction(alpha : Double, Choice : Int, qs : Qubit[]) : Unit is Adj { + // The expected state of the second qubit for the exercise. + + // set the second qubit in a superposition a |0⟩ + b|1⟩ + // with a = cos alpha, b = sin alpha + Ry(2.0 * alpha, qs[1]); + if (Choice == 1) { + // if the Choice is 1, change the state to b|0⟩ + a|1⟩ + X(qs[1]); + } + } + + + @Test("QuantumSimulator") + operation T3_StateSelction() : Unit { + use qs = Qubit[2]; + for i in 0 .. 5 { + let alpha = (PI() * IntAsDouble(i)) / 5.0; + + //for Choice = 0 and 1, + for Choice in 0 .. 1 { + // Prepare the state to be input to the testImplementation + stateInitialize_StateSelction(alpha, qs); + + // operate testImplementation + StateSelction(qs, Choice); + // reset the first qubit, since its state does not matter + Reset(qs[0]); + + // apply adjoint reference operation and check that the result is correct + Adjoint statePrepare_StateSelction(alpha, Choice, qs); + + AssertAllZero(qs); + ResetAll(qs); + + } + } + } + + + // ------------------------------------------------------ + // Exercise 8: State preparation using partial measurements + // ------------------------------------------------------ + + operation RefImpl_T4 (qs : Qubit[]) : Unit is Adj { + // Rotate first qubit to (sqrt(2) |0⟩ + |1⟩) / sqrt(3) (task 1.4 from BasicGates kata) + let theta = ArcSin(1.0 / Sqrt(3.0)); + Ry(2.0 * theta, qs[0]); + + // Split the state sqrt(2) |0⟩ ⊗ |0⟩ into |00⟩ + |01⟩ + (ControlledOnInt(0, H))([qs[0]], qs[1]); + } + + + @Test("QuantumSimulator") + operation T4_PostSelection() : Unit { + use qs = Qubit[2]; + + // operate the test implementation + PostSelection(qs); + + // apply adjoint reference operation and check that the result is |0⟩ + Adjoint RefImpl_T4(qs); + AssertAllZero(qs); + } + + + // ------------------------------------------------------ + // Exercise 9: Two qubit parity Measurement + // ------------------------------------------------------ + + + // ------------------------------------------------------ + operation StatePrep_ParityMeasurement (qs : Qubit[], state : Int, alpha : Double) : Unit is Adj { + + // prep cos(alpha) * |0..0⟩ + sin(alpha) * |1..1⟩ + Ry(2.0 * alpha, qs[0]); + for i in 1 .. Length(qs) - 1 { + CNOT(qs[0], qs[i]); + } + + if (state == 1) { + // flip the state of the first half of the qubits + for i in 0 .. Length(qs) / 2 - 1 { + X(qs[i]); + } + } + } + + // ------------------------------------------------------ + @Test("QuantumSimulator") + operation T5_ParityMeasurement () : Unit { + DistinguishStates_MultiQubit(2, 2, StatePrep_ParityMeasurement, ParityMeasurement, true, ["α|00⟩ + β|11⟩", "α|01⟩ + β|10⟩"]); + } + +} \ No newline at end of file diff --git a/tutorials/MultiQubitSystemMeasurements/Workbook_MultiQubitSystemMeasurements.ipynb b/tutorials/MultiQubitSystemMeasurements/Workbook_MultiQubitSystemMeasurements.ipynb new file mode 100644 index 00000000000..78ffc93c7ba --- /dev/null +++ b/tutorials/MultiQubitSystemMeasurements/Workbook_MultiQubitSystemMeasurements.ipynb @@ -0,0 +1,601 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Multi-Qubit System Measurements Tutorial Workbook\n", + "\n", + "**What is this workbook?**\n", + "A workbook is a collection of problems, accompanied by solutions to them. \n", + "The explanations focus on the logical steps required to solve a problem; they illustrate the concepts that need to be applied to come up with a solution to the problem, explaining the mathematical steps required. \n", + "\n", + "Note that a workbook should not be the primary source of knowledge on the subject matter; it assumes that you've already read a tutorial or a textbook and that you are now seeking to improve your problem-solving skills. You should attempt solving the tasks of the respective kata first, and turn to the workbook only if stuck. While a textbook emphasizes knowledge acquisition, a workbook emphasizes skill acquisition.\n", + "\n", + "This workbook describes the solutions to the problems offered in the [Multi-Qubit System Measurements tutorial](./MultiQubitSystemMeasurements.ipynb). \n", + "Since the tasks are offered as programming problems, the explanations also cover some elements of Q# that might be non-obvious for a first-time user.\n", + "\n", + "**What you should know for this workbook**\n", + "\n", + "You should be familiar with the following concepts before tackling the Single-Qubit System Measurements tutorial (and this workbook):\n", + "1. Basic linear algebra\n", + "2. Single and multi-qubit systems\n", + "3. Single and multi-qubit gates\n", + "$\\newcommand{\\ket}[1]{\\left|#1\\right>}$\n", + "$\\newcommand{\\bra}[1]{\\left<#1\\right|}$" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 1: Multi-qubit measurement outcome probabilities I \n", + "Suppose that a two-qubit system is known to be in the following state:\n", + "$$\\ket \\psi = \\frac{1}{3}\\ket {00} + \\frac{2}{3} \\ket {01} + \\frac{2}{3}\\ket {11}$$\n", + "\n", + "If all the qubits are measured simultaneously in the computational basis, what are the outcome probabilities?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "The wave function $|\\psi\\rangle$ is normalized, since $\\left(\\frac{1}{3}\\right)^2 + \\left(\\frac{2}{3}\\right)^2 + \\left(\\frac{2}{3}\\right)^2 = 1$. Hence, the probabilities of measuring each of the computational basis states is simply the square of the absolute value of the corresponding coefficients. That is, the probabilities of measuring $00$, $01$ and $11$ are $\\frac{1}{9}$, $\\frac{4}{9}$ and $\\frac{4}{9}$, respectively, and the probability of measuring the basis state $10$ that is not part of the superposition is $0$:\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Measurement outcomeProbability of outcome
$00$$\\left( \\frac{1}{3}\\right)^2 = \\frac{1}{9}$
$01$$\\left( \\frac{2}{3}\\right)^2 = \\frac{4}{9}$
$10$$\\left( 0\\right)^2 = 0$
$11$$\\left( \\frac{2}{3}\\right)^2 = \\frac{4}{9}$
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 1 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-1:-Multi-qubit-measurement-outcome-probabilities-I)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 2: Multi-qubit measurement outcome probabilities II \n", + "Suppose that a two-qubit system is known to be in the following state:\n", + "$$\\ket \\psi = \\frac{2}{3}\\ket {00} + \\frac{1}{3} \\ket {01} + \\frac{2}{3}\\ket {11}$$.\n", + "\n", + "If all the qubits are measured simultaneously in the Pauli X basis, i.e., in the $\\{ \\ket{++}, \\ket{+-}, \\ket{-+}, \\ket{--}\\}$ basis, what are the outcome probabilities?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "Using the expressions $|0\\rangle = \\frac{1}{\\sqrt{2}} \\big( |+\\rangle + |-\\rangle \\big)$ and $|1\\rangle = \\frac{1}{\\sqrt{2}} \\big( |+\\rangle - |-\\rangle \\big)$, we first express $|\\psi\\rangle$ in the Pauli X basis. This gives us\n", + "$$\n", + "|\\psi \\rangle = \n", + "\\frac{2}{3} \\cdot \\frac{1}{\\sqrt{2}} \\big( |+\\rangle + |-\\rangle \\big) \\otimes \\frac{1}{\\sqrt{2}}\\big( |+\\rangle + |-\\rangle \\big) + \n", + "\\frac{1}{3} \\cdot \\frac{1}{\\sqrt{2}} \\big( |+\\rangle + |-\\rangle \\big) \\otimes \\frac{1}{\\sqrt{2}} \\big( |+\\rangle - |-\\rangle \\big) + \n", + "\\frac{2}{3} \\cdot \\frac{1}{\\sqrt{2}} \\big( |+\\rangle - |-\\rangle \\big) \\otimes \\frac{1}{\\sqrt{2}} \\big( |+\\rangle - |-\\rangle \\big) =\n", + "\\\\ = \\frac{5}{6} |++\\rangle - \\frac{1}{6} |+-\\rangle + \\frac{1}{2} |-+\\rangle + \\frac{1}{6} |--\\rangle\n", + "$$\n", + "After this, the probabilities of measuring each of the four basis vectors is given by the square of the absolute value of its amplitude in the superposition:\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Measurement outcomeProbability of outcome
$++$$\\left( \\frac{5}{6}\\right)^2 = \\frac{25}{36}$
$+-$$\\left( -\\frac{1}{6}\\right)^2 = \\frac{1}{36}$
$-+$$\\left( \\frac{1}{2}\\right)^2 = \\frac{1}{4}$
$++$$\\left( \\frac{1}{6}\\right)^2 = \\frac{1}{36}$
\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 2 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-2:-Multi-qubit-measurement-outcome-probabilities-II)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 3: Distinguish four basis states\n", + "\n", + "**Input:** Two qubits (stored in an array of length 2) which are guaranteed to be in one of the four basis states ($|00\\rangle$, $|01\\rangle$, $|10\\rangle$, or $|11\\rangle$).\n", + "\n", + "**Output:**\n", + "\n", + "* 0 if the qubits were in the $|00\\rangle$ state,\n", + "* 1 if they were in the $|01\\rangle$ state, \n", + "* 2 if they were in the $|10\\rangle$ state, \n", + "* 3 if they were in the $|11\\rangle$ state.\n", + "\n", + "In this task and the subsequent ones the order of qubit states in task description matches the order of qubits in the array (i.e., $|10\\rangle$ state corresponds to `qs[0]` in state $|1\\rangle$ and `qs[1]` in state $|0\\rangle$).\n", + "\n", + "The state of the qubits at the end of the operation does not matter." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "\n", + "First, we measure both qubits in the input array and store the result in `m1` and `m2`. We can decode these results like this: \n", + "- `m1` is $|0\\rangle$ and `m2` is $|0\\rangle$: we return $0\\cdot2+0 = 0$\n", + "- `m1` is $|0\\rangle$ and `m2` is $|1\\rangle$: we return $0\\cdot2+1 = 1$\n", + "- `m1` is $|1\\rangle$ and `m2` is $|0\\rangle$: we return $1\\cdot2+0 = 2$\n", + "- `m1` is $|1\\rangle$ and `m2` is $|1\\rangle$: we return $1\\cdot2+1 = 3$\n", + "\n", + "In other words, we treat the measurement results as the binary notation of the return value in [big endian notation](../MultiQubitSystems/MultiQubitSystems.ipynb#Endianness)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T1_BasisStateMeasurement\n", + "\n", + "operation BasisStateMeasurement (qs : Qubit[]) : Int {\n", + " // Measurement on the first qubit gives the higher bit of the answer, on the second - the lower\n", + " let m1 = M(qs[0]) == Zero ? 0 | 1;\n", + " let m2 = M(qs[1]) == Zero ? 0 | 1;\n", + " return m1 * 2 + m2;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can generalize this code to read out an integer in big endian notation from a qubit array of arbitrary length using several library operations and functions:\n", + "\n", + "* `MultiM` measures each of the qubits in the array in the computational basis and returns an array of `Result` data type.\n", + "* `Reversed` reverses the given array.\n", + "* `ResultArrayAsInt` converts an array of bits given as `Result` to an integer, assuming little-endian notation (that's why we have to reverse the array before converting it)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T1_BasisStateMeasurement\n", + "\n", + "open Microsoft.Quantum.Arrays;\n", + "open Microsoft.Quantum.Convert;\n", + "open Microsoft.Quantum.Measurement;\n", + "\n", + "operation BasisStateMeasurement (qs : Qubit[]) : Int {\n", + " return ResultArrayAsInt(Reversed(MultiM(qs)));\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 3 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb##Exercise-3:-Distinguish-four-basis-states)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 4: Partial measurement probabilities for the Hardy state\n", + "\n", + "Consider a 2-qubit system in the state $\\ket \\psi = \\frac{1}{\\sqrt{12}} \\big(3|00\\rangle + |01\\rangle + |10\\rangle + |11\\rangle\\big)$.\n", + "\n", + "If only the first qubit is measured in the computational basis, what are the probabilities of the outcomes, and the post-measurement states of the system?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "\n", + "A measurement outcome of $0$ on the first qubit corresponds to the projection operator $P_0|0\\rangle\\langle 0| \\otimes \\mathbb{1}$. Applying it to the state $\\ket \\psi$ gives us \n", + "$$\\big|P_0 \\ket{\\psi}\\big|^2 = \\big|\\frac{1}{\\sqrt{10}} \\left(3\\ket {00} + \\ket{01}\\right) \\big|^2 = \\frac{5}{6}$$\n", + "and \n", + "$$\\frac{P_0 \\ket{\\psi}}{\\big|P_0 \\ket{\\psi}\\big|} = \\frac{1}{\\sqrt{10}} \\left( 3\\ket{00} + \\ket{01}\\right)$$\n", + "\n", + "Similarly, $P_1 = |1\\rangle \\langle 1 | \\otimes \\mathbb{1}$ is the projector corresponding to a measurement outcome of $1$ on the first qubit. Applying $P_1$ on $\\ket{\\psi}$ gives us $\\big|P_1 \\ket{\\psi}\\big|^2 = \\frac{1}{6}$ and \n", + "\n", + "$$\\frac{P_1 \\ket{\\psi}}{\\big|P_1 \\ket{\\psi}\\big|} = \\frac{1}{\\sqrt{2}} \\left(\\ket{10} + \\ket{11}\\right)$$\n", + "\n", + "\n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + " \n", + "
Measurement outcomeProbability of outcomePost-measurement state
$0$$\\frac{5}{6}$$\\frac{1}{\\sqrt{10}} \\left( 3\\ket{00} + \\ket{01}\\right)$
$1$$\\frac{1}{6}$$\\frac{1}{\\sqrt{2}} \\left(\\ket{10} + \\ket{11}\\right)$
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 4 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-4:-Partial-measurement-probabilities-for-the-Hardy-state)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 5: Distinguish orthogonal states using partial measurements\n", + "\n", + "\n", + "**Input**: A 3-qubit system which is guaranteed to be in either the $\\ket{++-}$ state, or the $\\ket{---}$ state.\n", + "\n", + "**Output**: \n", + "- 0 if the qubit is in the $\\ket{++-}$ state,\n", + "- 1 if the qubit is in the $\\ket{---}$ state.\n", + "\n", + "The state of the qubits at the end of the operation should be the same as the initial state." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "Since the state of the first qubit is different in these states ($\\ket +$ and $\\ket -$, respectively), it is sufficient to measure only the first qubit in the Pauli X basis in order to distinguish the two states. Furthermore, this measurement will not change the state of the system, since the post-projection state is identical to the original state regardless of the input state." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T2_IsPlusPlusMinus\n", + "\n", + "operation IsPlusPlusMinus (qs : Qubit[]) : Int {\n", + " return Measure([PauliX], [qs[0]]) == Zero ? 0 | 1;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 5 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-5:-Distinguish-orthogonal-states-using-partial-measurements)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 6: Sequential measurements on an entangled state and a separable state\n", + "Consider two two-qubit states:\n", + "- The Bell state $|\\Phi^{+}\\rangle = \\frac{1}{\\sqrt{2}} \\big (|00\\rangle + |11\\rangle\\big)$.\n", + "- A state $\\ket \\Theta = \\frac{1}{2} \\big( \\ket{00} + \\ket{01} + \\ket{10} + \\ket{11} \\big)$.\n", + "\n", + "For both states, consider a measurement on the first qubit, followed by a measurement on the second qubit, both done in the computational basis. For which state can we expect the measurement outcomes to be correlated? Verify by calculating the sequential measurement probabilities explicitly for both states. " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "- *The Bell state*: If the measurement outcome on the first qubit is $0$, a subsequent measurement on the second qubit *always* results in an outcome of $0$, with probability $1$. Similarly, if the measurement outcome on the first qubit is $1$, then the second qubit measurement always results in $1$. Thus, sequential measurements are perfectly *correlated*.\n", + "- *Separable state* $\\ket \\Theta$: Irrespective of whether the first qubit measurement outcome is $0$ of $1$ (each of which occurs with a probability of $0.5$), a subsequent measurement on the second qubit results in an outcome of $0$ or $1$ (both with a probability of $0.5$). Thus, sequential measurements are perfectly *uncorrelated*. \n", + "\n", + "This aligns with the fact that the Bell state is entangled, while the $\\ket{\\Theta}$ is separable and can be expressed as $\\ket \\Theta = \\ket + \\otimes \\ket +$." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 6 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-6:-Sequential-measurements-on-an-entangled-state-and-a-separable-state)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 7: State selection using partial measurements \n", + "\n", + "**Input**: \n", + "1. A 2-qubit system in the state\n", + "$$\n", + "|\\psi\\rangle = \\frac{1}{\\sqrt{2}} |0\\rangle \\otimes ( a |0\\rangle + b|1\\rangle) + \\frac{1}{\\sqrt{2}} |1\\rangle \\otimes (b|0\\rangle + a |1\\rangle),\n", + "$$\n", + "where the constants $a$ and $b$ satisfying $|a|^2 + |b|^2 = 1$ are unknown.\n", + "2. An integer $ind$ which is either $0$ or $1$.\n", + "\n", + "**Goal**: \n", + "- If $ind$ equals 0, the state of the state of the second qubit should be $a|0\\rangle + b|1\\rangle$\n", + "- If $ind$ equals 1, the state of the second qubit should be $b|0\\rangle + a |1\\rangle$. \n", + "\n", + "The state of the first qubit at the end does not matter." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "We note that if we measure the first qubit in the computational basis, then an outcome of $0$ collapses the second qubit to the state $a\\ket 0 + b \\ket 1$, while an outcome of $1$ collapses the second qubit to the state $b\\ket 0 + a \\ket 1$.\n", + "\n", + "Thus, if $ind=0$ and we measure $0$ or if $ind=1$ and we measure $1$, then after the measurement the second qubit will be in the desired state. On the other hand, if $ind=1$ and we measure $0$, or if $ind=0$ and we measure $1$, then the state of the second qubit after the measurement is not what we're looking for, but we can adjust it using the Pauli X gate." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T3_StateSelction\n", + "\n", + "operation StateSelction(qs : Qubit[], ind : Int) : Unit {\n", + " // It is convenient to convert measurement outcome to an integer\n", + " let outcome = M(qs[0]) == Zero ? 0 | 1;\n", + " if outcome != ind {\n", + " X(qs[1]);\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 7 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-7:-State-selection-using-partial-measurements)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 8: State preparation using partial measurements\n", + "\n", + "**Input:** Two qubits (in an array) which are in the state $\\ket{00}$.\n", + "\n", + "**Goal:** Modify the qubits to the state $\\frac{1}{\\sqrt{3}} \\big(|00\\rangle + |01\\rangle + |10\\rangle\\big)$ using post-selection." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "While it is possible to prepare the state $\\ket \\psi$ directly using unitary rotations, it is simpler to use post-selection for preparing it. Here, we describe the procedure in more detail below.\n", + "\n", + "Initially we will prepare an equal superposition of all basis states corresponding to the first two qubits by applying the **H** gate to each of them: \n", + "$$\\frac{1}{2} \\big(|00\\rangle + |01\\rangle + |10\\rangle + |11\\rangle\\big) \\otimes \\ket 0$$\n", + "\n", + "This state is a superposition of the state we want to prepare, and the $|11\\rangle$ state that we would like to discard.\n", + "\n", + "Now, we want to separate the first three basis states from the last one and to store this separation in the extra qubit. \n", + "For example, we can keep the state of the extra qubit $|0\\rangle$ for the basis states that we want to keep, and switch it to $|1\\rangle$ for the basis states that we would like to discard. \n", + "A **CCNOT** gate can be used to accomplish this, with the first two qubits used as control qubits and the extra qubit as target. \n", + "When the gate is applied, the state of the extra qubit will only change to $|1\\rangle$ if both control qubits are in the $|11\\rangle$ state, which marks exactly the state that we want to discard:\n", + "\n", + "$$\\text{CCNOT}\\frac{1}{2} \\big(|00\\textbf{0}\\rangle + |01\\textbf{0}\\rangle + |10\\textbf{0}\\rangle + |11\\textbf{0}\\rangle\\big) = \n", + "\\frac{1}{2}\\big(|00\\rangle + |01\\rangle + |10\\rangle \\big) \\otimes |\\textbf{0}\\rangle + \\frac{1}{2}|11\\rangle \\otimes |\\textbf{1}\\rangle $$\n", + "\n", + "Finally we measure just the extra qubit; this causes a partial collapse of the system to the state defined by the measurement result:\n", + "* If the result is $|0\\rangle$, the system collapses to a state that is a linear combination of basis states which had the extra qubit in state $|0\\rangle$, i.e., the two qubits end up in the target state $\\frac{1}{\\sqrt3}\\big(|00\\rangle + |01\\rangle + |10\\rangle\\big)$. \n", + "* If the result is $|1\\rangle$, the system collapses to a state $|11\\rangle$, so our goal is not achieved. The good thing is, this only happens in 25% of the cases, and we can just reset our qubits to the $|00\\rangle$ state and try again.\n", + "\n", + "\n", + "> Q# has a built-in [repeat-until-success (RUS) loop](https://docs.microsoft.com/en-us/quantum/user-guide/using-qsharp/control-flow#repeat-until-success-loop), which comes in handy in this case. \n", + "> * We will describe the main operations (applying **H** and **CCNOT** gates and the measurement) in the `repeat` part of the loop, which specifies its body. \n", + "> * `until` section specifies the condition which will break the loop. In this case the result of the measurement needs to be `Zero` to indicate our success. \n", + "> * Finally, the `fixup` section allows us to clean up the results of the loop body execution before trying again if the success criteria is not met. In this case we reset the first two qubits back to the $|00\\rangle$ state.\n", + "\n", + "This technique is sometimes called post-selection." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T4_PostSelection\n", + "\n", + "open Microsoft.Quantum.Measurement;\n", + "\n", + "operation PostSelection (qs : Qubit[]) : Unit {\n", + " // Initialize the extra qubit\n", + " use anc = Qubit();\n", + " // Using the repeat-until-success pattern to prepare the right state\n", + " repeat {\n", + " ApplyToEach(H, qs);\n", + " Controlled X(qs, anc);\n", + " let res = MResetZ(anc);\n", + " } \n", + " until (res == Zero)\n", + " fixup {\n", + " ResetAll(qs);\n", + " }\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 8 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-8:-State-preparation-using-partial-measurements)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 9: Two qubit parity measurement\n", + "\n", + "**Inputs**: Two qubits stored in an array which are guaranteed to be either in a superposition of the states $|00\\rangle$ and $|11\\rangle$ or in a superposition of states $|01\\rangle$ and $|10\\rangle$.\n", + "\n", + "**Output**: 0 if qubits were in the first superposition, 1 if they were in the second superposition. \n", + "*The state of the qubits at the end of the operation should be the same as the starting state.*" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Solution\n", + "\n", + "If we were not asked to maintain the state of the qubits, one approach would be to measure both the qubits separately in the computational basis, and check if the result is the same for both the measurements. If the measurement results are equal, the input state must have been a superposition of $\\ket{00}$ and $\\ket{11}$, while different measurement outcomes will imply that the input state must have been a superposition of $\\ket{01}$ and $\\ket{10}$. However, in these measurements we will lose the information about the original superposition states: a state $\\alpha |00\\rangle + \\beta |11\\rangle$ will collapse to either $|00\\rangle$ or $|11\\rangle$, and we won't be able to recover the information about the coefficients $\\alpha$ and $\\beta$.\n", + "\n", + "We need to measure the *parity* of the state without collapsing it all the way to the basis states. [Pauli measurements](https://docs.microsoft.com/en-us/quantum/concepts/pauli-measurements) can be used for joint measurements involving multiple qubits. For this task we apply the $Z \\otimes Z$ measurement on both qubits.\n", + "\n", + "A joint measurement using $Z \\otimes Z$ operator can be thought as projecting the measured state to one of the two eigenspaces of $Z \\otimes Z$ with $+1$ and $-1$ as the corresponding eigenvalues. The measurement returns `Zero` if the measured state is projected to the space with an eigenvalue of $+1$, and a result of `One` if projected to the space with an eigenvalue of $-1$.\n", + "\n", + "As we've seen in the tutorial, the state $\\alpha |00\\rangle + \\beta |11\\rangle$ is an eigenstate of the $Z \\otimes Z$ operator with the eigenvalue $+1$, and the state $\\alpha |01\\rangle + \\beta |10\\rangle$ is an eigenstate with the eigenvalue $-1$.\n", + "Hence, we can use this joint measurement to recognize which of the superposition states we were given while preserving the initial superposition state.\n", + "\n", + "In Q#, the operation [`Measure`](https://docs.microsoft.com/en-us/qsharp/api/qsharp/microsoft.quantum.intrinsic.measure) can be used to measure multiple qubits using an array of [Pauli](https://docs.microsoft.com/en-us/quantum/user-guide/language/types?#primitive-types) constants that define the basis for measurement." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "%kata T5_ParityMeasurement\n", + "\n", + "operation ParityMeasurement (qs : Qubit[]) : Int {\n", + " return Measure([PauliZ, PauliZ], qs) == Zero ? 0 | 1;\n", + "}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 9 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-9:-Two-qubit-parity-Measurement)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 10: Parity measurement in different basis\n", + "\n", + "Consider a system which is in a state $\\alpha |00\\rangle + \\beta |01\\rangle + \\beta |10\\rangle + \\alpha |11\\rangle$.\n", + "\n", + "What are the possible outcomes and their associated probabilities, if a measurement in an $XX$ Pauli measurement is done?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Solution\n", + "\n", + "The first step towards identifying the outcomes and their probabilities for joint measurements is to identify the eigenvectors corresponding to eigenvalues $\\pm1$ of the Pauli operator. We note that since $X\\ket{\\pm}= \\pm\\ket{\\pm}$, we have \n", + "\\begin{align}\n", + "XX \\ket{++} &= \\ket{++}, &XX \\ket{--} &= \\ket{--};\\\\\n", + "XX \\ket{+-} &= -\\ket{+-}, &XX \\ket{-+} &= -\\ket{-+}.\n", + "\\end{align}\n", + "Thus, the $XX$ operator measures the parity in the Hadamard, or the $\\ket{\\pm}$ basis. That is, it distinguishes basis states with an even number of $+$'s from basis states which have an odd number of $+$'s.\n", + "\n", + "The projector corresponding to a result of `Zero` is given by $P_{+1} = \\ket{++}\\bra{++} + \\ket{--}\\bra{--}$, while the projector corresponding to a result of `One` is given by $P_{-1} = \\ket{+-}\\bra{+-} + \\ket{-+}\\bra{-+}$. Then, we note that $P_{+1}$ annihilates states with odd parity, while leaving states with even parity unaffected. That is, for any values of the constants \n", + "\\begin{align}\n", + "P_{+1} ( \\gamma \\ket{++} + \\delta \\ket{--} ) &= ( \\gamma \\ket{++} + \\delta \\ket{--} )\\\\\n", + "P_{+1} ( \\mu \\ket{-+} + \\nu \\ket{+-} ) &= 0.\n", + "\\end{align}\n", + "Similarly, $P_{-1}$ annihilates states with even parity, while leaving states with odd parity unaffected.\n", + "\n", + "\n", + "Now we express the given state in the Hadamard basis. We note that it is possible to go from the computational basis to the Hadamard basis using the following relations\n", + "$$\n", + "\\ket{0} = \\frac{1}{\\sqrt{2}} \\left( \\ket{+} + \\ket{-} \\right)\\\\\n", + "\\ket{1} = \\frac{1}{\\sqrt{2}} \\left( \\ket{+} - \\ket{-} \\right).\n", + "$$\n", + "Using these, we obtain\n", + "$$ \\alpha |00\\rangle + \\beta |01\\rangle + \\beta |10\\rangle + \\alpha |11\\rangle = (\\alpha + \\beta) |++\\rangle + (\\alpha - \\beta) |--\\rangle.$$\n", + "Thus, this state has an even parity in the Hadamard basis. It follows that an $XX$ Pauli measurement will result in the outcome `Zero` with probability 1, leaving the state unchanged after the measurement.\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "[Return to exercise 10 of the Multi-Qubit System Measurements tutorial.](./MultiQubitSystemMeasurements.ipynb#Exercise-10:-Parity-measurement-in-different-basis)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Q#", + "language": "qsharp", + "name": "iqsharp" + }, + "language_info": { + "file_extension": ".qs", + "mimetype": "text/x-qsharp", + "name": "qsharp", + "version": "0.14" + } + }, + "nbformat": 4, + "nbformat_minor": 5 +}