<jupyter_start><jupyter_text>Single-Qubit GatesThis tutorial introduces you to single-qubit gates. Quantum gates are the quantum counterpart to classical logic gates, acting as the building blocks of quantum algorithms. Quantum gates transform qubit states in various ways, and can be applied sequentially to perform complex quantum calculations. Single-qubit gates, as their name implies, act on individual qubits. You can learn more at [Wikipedia](https://en.wikipedia.org/wiki/Quantum_logic_gate).We recommend to go through the [tutorial that introduces the concept of qubit](../Qubit/Qubit.ipynb) before starting this one.This tutorial covers the following topics:* Matrix representation* Ket-bra representation* The most important single-qubit gatesA quick summary of the gates can also be found in [this cheatsheet](https://github.com/microsoft/QuantumKatas/blob/main/quickref/qsharp-quick-reference.pdf).  The BasicsThere are certain properties common to all quantum gates. This section will introduce those properties, using the $X$ gate as an example.  Matrix RepresentationQuantum gates are represented as $2^N \times 2^N$ [unitary matrices](../LinearAlgebra/LinearAlgebra.ipynbUnitary-Matrices), where $N$ is the number of qubits the gate operates on. As a quick reminder, a unitary matrix is a square matrix whose inverse is its adjoint. Single-qubit gates are represented by $2 \times 2$ matrices.Our example for this section, the $X$ gate, is represented by the following matrix:$$\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$$You may recall that the state of a qubit is represented by a vector of size $2$. You can apply a gate to a qubit by [multiplying](../LinearAlgebra/LinearAlgebra.ipynbMatrix-Multiplication) the gate's matrix by the qubit's state vector. The result will be another vector, representing the new state of the qubit. For example, applying the $X$ gate to the computational basis states looks like this:$$X|0\rangle =\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} 1 \\ 0 \end{bmatrix} =\begin{bmatrix} 0 \cdot 1 + 1 \cdot 0 \\ 1 \cdot 1 + 0 \cdot 0 \end{bmatrix} =\begin{bmatrix} 0 \\ 1 \end{bmatrix} \\X|1\rangle =\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} 0 \\ 1 \end{bmatrix} =\begin{bmatrix} 0 \cdot 0 + 1 \cdot 1 \\ 1 \cdot 0 + 0 \cdot 1 \end{bmatrix} =\begin{bmatrix} 1 \\ 0 \end{bmatrix}$$The general case:$$|\psi\rangle = \alpha|0\rangle + \beta|1\rangle \\X|\psi\rangle =\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}\begin{bmatrix} \alpha \\ \beta \end{bmatrix} =\begin{bmatrix} 0 \cdot \alpha + 1 \cdot \beta \\ 1 \cdot \alpha + 0 \cdot \beta \end{bmatrix} =\begin{bmatrix} \beta \\ \alpha \end{bmatrix}$$> If you need a reminder of what $|0\rangle$, $|1\rangle$, and $|\psi\rangle$ mean, you can review the section on [Dirac notation](../Qubit/Qubit.ipynbDirac-Notation) in the previous tutorial.Because this is the most common way to represent quantum gates, the terms "gate" and "gate matrix" will be used interchangeably in this tutorial.Applying several quantum gates in sequence is equivalent to performing several of these multiplications. For example, if you have gates $A$ and $B$ and a qubit in state $|\psi\rangle$, the result of applying $A$ followed by $B$ to that qubit would be $B\big(A|\psi\rangle\big)$ (the gates closest to the qubit state get applied first). Matrix multiplication is associative, so this is equivalent to multiplying the $B$ matrix by the $A$ matrix, producing a compound gate of the two, and then applying that to the qubit: $\big(BA\big)|\psi\rangle$.All quantum gates are reversible - there is another gate which will undo any given gate's transformation, returning the qubit to its original state. This means that when dealing with quantum gates, information about qubit states is never lost, as opposed to classical logic gates, some of which destroy information. Quantum gates are represented by unitary matrices, so the inverse of a gate is its adjoint; these terms are also used interchangeably in quantum computing.  Effects on Basis States (Dirac Notation, Continued)There is a simple way to find out what a gate does to the two computational basis states ($|0\rangle$ and $|1\rangle$) from looking at its matrix that comes in handy when you want to work with states in Dirac notation. Consider an arbitrary gate:$$A = \begin{bmatrix} \epsilon & \zeta \\ \eta & \mu \end{bmatrix}$$Watch what happens when we apply it to these states:$$A|0\rangle =\begin{bmatrix} \epsilon & \zeta \\ \eta & \mu \end{bmatrix}\begin{bmatrix} 1 \\ 0 \end{bmatrix} =\begin{bmatrix} \epsilon \cdot 1 + \zeta \cdot 0 \\ \eta \cdot 1 + \mu \cdot 0 \end{bmatrix} =\begin{bmatrix} \epsilon \\ \eta \end{bmatrix} = \epsilon|0\rangle + \eta|1\rangle \\A|1\rangle =\begin{bmatrix} \epsilon & \zeta \\ \eta & \mu \end{bmatrix}\begin{bmatrix} 0 \\ 1 \end{bmatrix} =\begin{bmatrix} \epsilon \cdot 0 + \zeta \cdot 1 \\ \eta \cdot 0 + \mu \cdot 1 \end{bmatrix} =\begin{bmatrix} \zeta \\ \mu \end{bmatrix} = \zeta|0\rangle + \mu|1\rangle$$Notice that applying the gate to the $|0\rangle$ state transforms it into the state written as the first column of the gate's matrix. Likewise, applying the gate to the $|1\rangle$ state transforms it into the state written as the second column. This holds true for any quantum gate, including, of course, the $X$ gate:$$X = \begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix} \\X|0\rangle = \begin{bmatrix} 0 \\ 1 \end{bmatrix} = |1\rangle \\X|1\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix} = |0\rangle$$Once you understand how a gate affects the computational basis states, you can easily find how it affects any state.Recall that any qubit state vector can be written as a linear combination of the basis states:$$|\psi\rangle = \begin{bmatrix} \alpha \\ \beta \end{bmatrix} = \alpha|0\rangle + \beta|1\rangle$$Because matrix multiplication distributes over addition, once you know how a gate affects those two basis states, you can calculate how it affects any state:$$X|\psi\rangle = X\big(\alpha|0\rangle + \beta|1\rangle\big) = X\big(\alpha|0\rangle\big) + X\big(\beta|1\rangle\big) = \alpha X|0\rangle + \beta X|1\rangle = \alpha|1\rangle + \beta|0\rangle$$That is, applying a gate to a qubit in superposition is equivalent to applying that gate to the basis states that make up that superposition and adding the results with appropriate weights.  Ket-bra RepresentationThere is another way to represent quantum gates, this time using Dirac notation. However, the kets we've been using aren't enough to represent arbitrary matrices. We need to introduce another piece of notation: the **bra** (this is why Dirac notation is sometimes called **bra-ket notation**).Recall that kets represent column vectors; a bra is a ket's row vector counterpart. For any ket $|\psi\rangle$, the corresponding bra is its adjoint (conjugate transpose): $\langle\psi| = |\psi\rangle^\dagger$.> As a quick reminder, the [adjoint](../LinearAlgebra/LinearAlgebra.ipynbUnary-Operations), also known as the conjugate transpose of a matrix, well, the conjugate of that matrix's transpose.Some examples:                    Ket        Bra                $|0\rangle = \begin{bmatrix} 1 \\ 0 \end{bmatrix}$        $\langle0| = \begin{bmatrix} 1 & 0 \end{bmatrix}$                $|1\rangle = \begin{bmatrix} 0 \\ 1 \end{bmatrix}$        $\langle1| = \begin{bmatrix} 0 & 1 \end{bmatrix}$                $|i\rangle = \begin{bmatrix} \frac{1}{\sqrt{2}} \\ \frac{i}{\sqrt{2}} \end{bmatrix}$        $\langle i| = \begin{bmatrix} \frac{1}{\sqrt{2}} & -\frac{i}{\sqrt{2}} \end{bmatrix}$                $|\psi\rangle = \begin{bmatrix} \alpha \\ \beta \end{bmatrix}$        $\langle\psi| = \begin{bmatrix} \overline{\alpha} & \overline{\beta} \end{bmatrix}$                $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        $\langle\psi| = \overline{\alpha}\langle0| + \overline{\beta}\langle1|$     Kets and bras give us a neat way to express [inner](../LinearAlgebra/LinearAlgebra.ipynbInner-Product) and [outer](../LinearAlgebra/LinearAlgebra.ipynbOuter-Product) products. The inner product of $|\phi\rangle$ and $|\psi\rangle$ is the matrix product of $\langle\phi|$ and $|\psi\rangle$, denoted as $\langle\phi|\psi\rangle$, and their outer product is the matrix product of $|\phi\rangle$ and $\langle\psi|$, denoted as $|\phi\rangle\langle\psi|$. Notice that the norm of $|\psi\rangle$ is $\sqrt{\langle\psi|\psi\rangle}$.This brings us to representing matrices. Recall that the outer product of two vectors of the same size produces a square matrix. We can use a linear combination of several outer products of simple vectors (such as basis vectors) to express any square matrix. For example, the $X$ gate can be expressed as follows:$$X = |0\rangle\langle1| + |1\rangle\langle0| \\|0\rangle\langle1| + |1\rangle\langle0| =\begin{bmatrix} 1 \\ 0 \end{bmatrix}\begin{bmatrix} 0 & 1 \end{bmatrix} +\begin{bmatrix} 0 \\ 1 \end{bmatrix}\begin{bmatrix} 1 & 0 \end{bmatrix} =\begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix} + \begin{bmatrix} 0 & 0 \\ 1 & 0 \end{bmatrix} =\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$$This representation can be used to carry out calculations in Dirac notation without ever switching back to matrix representation:$$X|0\rangle = \big(|0\rangle\langle1| + |1\rangle\langle0|\big)|0\rangle = |0\rangle\langle1|0\rangle + |1\rangle\langle0|0\rangle = |0\rangle\big(\langle1|0\rangle\big) + |1\rangle\big(\langle0|0\rangle\big) = |0\rangle(0) + |1\rangle(1) = |1\rangle$$> That last step may seem a bit confusing. Recall that $|0\rangle$ and $|1\rangle$ form an **orthonormal basis**. That is, they are both normalized, and they are orthogonal to each other.>> A vector is normalized if its norm is equal to $1$, which only happens if its inner product with itself is equal to $1$. This means that $\langle0|0\rangle = \langle1|1\rangle = 1$>> Two vectors are orthogonal to each other if their inner product equals $0$. This means that $\langle0|1\rangle = \langle 1|0\rangle = 0$. In general case, a matrix $$A = \begin{bmatrix} a_{00} & a_{01} \\ a_{10} & a_{11} \end{bmatrix}$$will have the following ket-bra representation:$$A = a_{00} |0\rangle\langle0| + a_{01} |0\rangle\langle1| + a_{10} |1\rangle\langle0| + a_{11} |1\rangle\langle1|$$ >  Ket-bra decomposition>> This section describes a more formal process of finding the ket-bra decompositions of quantum gates. This section is not necessary to start working with quantum gates, so feel free to skip it for now, and come back to it later.>> You can use the properties of [eigenvalues and eigenvectors](../LinearAlgebra/LinearAlgebra.ipynbPart-III:-Eigenvalues-and-Eigenvectors) to find the ket-bra decomposition of any gate. Given a gate $A$, and its orthogonal eigenvectors $|\phi\rangle$ and $|\psi\rangle$, if:>> $$A|\phi\rangle = x_\phi|\phi\rangle \\A|\psi\rangle = x_\psi|\psi\rangle$$>> Then:>> $$A = x_\phi|\phi\rangle\langle\phi| + x_\psi|\psi\rangle\langle\psi|$$>> Let's use our $X$ gate as a simple example. The $X$ gate has two eigenvectors: $|+\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle + |1\rangle\big)$ and $|-\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle - |1\rangle\big)$. Their eigenvalues are $1$ and $-1$ respectively:>> $$X|+\rangle = |+\rangle \\X|-\rangle = -|-\rangle$$>> Here's what the decomposition looks like:>> $$X = |+\rangle\langle+| - |-\rangle\langle-| = \\= \frac{1}{2}\big[\big(|0\rangle + |1\rangle\big)\big(\langle0| + \langle1|\big) - \big(|0\rangle - |1\rangle\big)\big(\langle0| - \langle1|\big)\big] = \\= \frac{1}{2}\big(\color{red}{|0\rangle\langle0|} + |0\rangle\langle1| + |1\rangle\langle0| + \color{red}{|1\rangle\langle1|} - \color{red}{|0\rangle\langle0|} + |0\rangle\langle1| + |1\rangle\langle0| - \color{red}{|1\rangle\langle1|}\big) = \\= \frac{1}{2}\big(2|0\rangle\langle1| + 2|1\rangle\langle0|\big) = |0\rangle\langle1| + |1\rangle\langle0|$$  Important GatesThis section introduces some of the common single-qubit gates, including their matrix form, their ket-bra decomposition, and a brief "cheatsheet" listing their effect on some common qubit states.You can use a tool called [Quirk](https://algassert.com/quirk) to visualize how these gates interact with various qubit states.This section relies on the following notation:                    $|+\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle + |1\rangle\big)$        $|-\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle - |1\rangle\big)$                $|i\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle + i|1\rangle\big)$        $|-i\rangle = \frac{1}{\sqrt{2}}\big(|0\rangle - i|1\rangle\big)$      Pauli GatesThe Pauli gates, named after [Wolfgang Pauli](https://en.wikipedia.org/wiki/Wolfgang_Pauli), are based on the so-called **Pauli matrices**. All three Pauli gates are **self-adjoint**, meaning that each one is its own inverse.                                    Gate        Matrix        Ket-Bra        Applying to $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        Applying to basis states        Q Documentation                $X$        $\begin{bmatrix} 0 & 1 \\ 1 & 0 \end{bmatrix}$        $|0\rangle\langle1| + |1\rangle\langle0|$        $X|\psi\rangle = \alpha|1\rangle + \beta|0\rangle$        $X|0\rangle = |1\rangle \\X|1\rangle = |0\rangle \\X|+\rangle = |+\rangle \\X|-\rangle = -|-\rangle \\X|i\rangle = i|-i\rangle \\X|-i\rangle = -i|i\rangle$         X                $Y$        $\begin{bmatrix} 0 & -i \\ i & 0 \end{bmatrix}$        $i(|1\rangle\langle0| - |0\rangle\langle1|)$        $Y|\psi\rangle = i\big(\alpha|1\rangle - \beta|0\rangle\big)$        $Y|0\rangle = i|1\rangle \\Y|1\rangle = -i|0\rangle \\Y|+\rangle = -i|-\rangle \\Y|-\rangle = i|+\rangle \\Y|i\rangle = |i\rangle \\Y|-i\rangle = -|-i\rangle$        Y                $Z$        $\begin{bmatrix} 1 & 0 \\ 0 & -1 \end{bmatrix}$        $|0\rangle\langle0| - |1\rangle\langle1|$        $Z|\psi\rangle = \alpha|0\rangle - \beta|1\rangle$        $Z|0\rangle = |0\rangle \\Z|1\rangle = -|1\rangle \\Z|+\rangle = |-\rangle \\Z|-\rangle = |+\rangle \\Z|i\rangle = |-i\rangle \\Z|-i\rangle = |i\rangle$         Z     > The $X$ gate is sometimes referred to as the **bit flip** gate, or the **NOT** gate, because it acts like the classical NOT gate on the computational basis.>> The $Z$ gate is sometimes referred to as the **phase flip** gate.Here are several properties of the Pauli gates that are easy to verify and convenient to remember:* Different Pauli gates *anti-commute*:  $$XZ = -ZX, XY = -YX, YZ = -ZY$$* A product of any two Pauli gates equals the third gate, with an extra $i$ (or $-i$) phase:  $$XY = iZ, YZ = iX, ZX = iY$$* A product of all three Pauli gates equals identity (with an extra $i$ phase):  $$XYZ = iI$$  Demo: Pauli GatesThe following cell contains code demonstrating how to apply gates in Q, using the Pauli $X$ gate as an example. It sets up a series of quantum states, and then shows the result of applying the $X$ gate to each one. To run the demo, run the next cell using `Ctrl+Enter` (`⌘+Enter` on a Mac).In the previous tutorial we discussed that the qubit state in Q cannot be directly assigned or accessed. The same logic is extended to the quantum gates: applying a gate to a qubit modifies the internal state of that qubit but doesn't return the resulting state of the qubit. This is why we never assign the output of these gates to any variables in this demo - they don't produce any output.Applying several gates in a row follows the same principle. In the mathematical notation applying an $X$ gate followed by a $Z$ gate to a state $|\psi\rangle$ is denoted as $Z(X(|\psi\rangle))$, because the result of applying a gate to a state is another state. In Q, applying a gate doesn't return anything, so you can't use its output as an input to another gate - something like `Z(X(q))` will not produce expected result. Instead, to apply several gates to the same qubit, you need to call them separately in the order in which they are applied:```X(q);Z(q);```All the basic gates we will be covering in this tutorial are part of the [Intrinsic](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.intrinsic) namespace. We're also using the function [DumpMachine](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.diagnostics.dumpmachine) to print the state of the quantum simulator.<jupyter_code>// Run this cell using Ctrl+Enter (⌘+Enter on Mac)
// Run the next cell to see the output

// To use a namespace, you need to use the `open` keyword to access it
open Microsoft.Quantum.Diagnostics;

operation PauliGatesDemo () : Unit {
    // This allocates a qubit for us to work with
    use q = Qubit();

    // This will put the qubit into an uneven superposition |𝜓❭,
    // where the amplitudes of |0⟩ and |1⟩ have different moduli
    Ry(1.0, q);

    Message("Qubit in state |𝜓❭:");
    DumpMachine();

    // Let's apply the X gate; notice how it swaps the amplitudes of the |0❭ and |1❭ basis states
    X(q);
    Message("Qubit in state X|𝜓❭:");
    DumpMachine();

    // Applying the Z gate adds -1 relative phase to the |1❭ basis states
    Z(q);
    Message("Qubit in state ZX|𝜓❭:");
    DumpMachine();

    // Finally, applying the Y gate returns the qubit to its original state |𝜓❭, with an extra global phase of i
    Y(q);
    Message("Qubit in state YZX|𝜓❭:");
    DumpMachine();

    // This returns the qubit into state |0❭
    Reset(q);
}<jupyter_output><empty_output><jupyter_text>In the previous tutorials we used `%simulate` command to run the Q code on the full-state simulator. Here we will use an additional `%trace` command: it will print the circuit diagram of the run after the output.<jupyter_code>%simulate PauliGatesDemo
%trace PauliGatesDemo<jupyter_output>Qubit in state |𝜓❭:<jupyter_text>ExercisesThe following exercises are designed to test your understanding of the concepts you've learned so far. In each exercise your task is to implement an operation that applies a particular transformation to a qubit. Unlike the demos you have seen so far, you don't have to allocate the qubit or to put it into a certain initial state - the qubit is already allocated, prepared in some state and provided to you as an input to the operation. Exercise 1: The $Y$ gate**Input:** A qubit in an arbitrary state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$.**Goal:** Apply the $Y$ gate to the qubit, i.e., transform the given state into $i\alpha|1\rangle - i\beta|0\rangle$.<jupyter_code>%kata T1_ApplyY

operation ApplyY (q : Qubit) : Unit is Adj+Ctl {
    // Fill in your code here, then run the cell to test your work.
    // For this exercise, just apply the Y gate.
    
    // add a Y gate on the qubit q 
    Y(q);
    
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbExercise-1:-The-$Y$-gate).*  Exercise 2: Applying a global phase $i$**Input:** A qubit in an arbitrary state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$.**Goal:** Use several Pauli gates to change the qubit state to $i|\psi\rangle = i\alpha|0\rangle + i\beta|1\rangle$.<jupyter_code>%kata T2_GlobalPhaseI

operation GlobalPhaseI (q : Qubit) : Unit is Adj+Ctl {
    // just add a phase of i 
    Y(q);
    X(q);
    Z(q); // nice!
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbExercise-2:-Applying-a-global-phase-$i$).*  Exercise 3*: Applying a $-1$ phase to $|0\rangle$ state**Input:** A qubit in an arbitrary state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$.**Goal:** Use several Pauli gates to change the qubit state to $- \alpha|0\rangle + \beta|1\rangle$, i.e., apply the transformation represented by the following matrix::$$\begin{bmatrix} -1 & 0 \\ 0 & 1 \end{bmatrix}$$    Need a hint? Click here    Experiment with different sequences of Pauli gates and observe their effect on the state.<jupyter_code>%kata T3_SignFlipOnZero

operation SignFlipOnZero (q : Qubit) : Unit is Adj+Ctl {
    // this is basically the Z gate with phase - nice! 
    
    // XZX basically changes the sign of the |0> state!!
    X(q);
    Z(q);
    X(q);
    
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbexercise-3).*  IdentityThe identity gate is mostly here for completeness, at least for now. It will come in handy when dealing with multi-qubit systems and multi-qubit gates. It is represented by the identity matrix, and does not affect the state of the qubit.                                Gate        Matrix        Ket-Bra        Applying to $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        Q Documentation                $I$        $\begin{bmatrix} 1 & 0 \\ 0 & 1 \end{bmatrix}$        $|0\rangle\langle0| + |1\rangle\langle1|$        $I|\psi\rangle = |\psi\rangle$        I      HadamardThe **Hadamard** gate is an extremely important quantum gate. Unlike the previous gates, applying the Hadamard gate to a qubit in a computational basis state puts that qubit into a superposition.Like the Pauli gates, the Hadamard gate is self-adjoint.                                    Gate        Matrix        Ket-Bra        Applying to $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        Applying to basis states        Q Documentation                $H$        $\begin{bmatrix} \frac{1}{\sqrt{2}} & \frac{1}{\sqrt{2}} \\ \frac{1}{\sqrt{2}} & -\frac{1}{\sqrt{2}} \end{bmatrix} = \frac{1}{\sqrt{2}}\begin{bmatrix} 1 & 1 \\ 1 & -1 \end{bmatrix}$        $|0\rangle\langle+| + |1\rangle\langle-|$        $H|\psi\rangle = \alpha|+\rangle + \beta|-\rangle = \frac{\alpha + \beta}{\sqrt{2}}|0\rangle + \frac{\alpha - \beta}{\sqrt{2}}|1\rangle$        $H|0\rangle = |+\rangle \\H|1\rangle = |-\rangle \\H|+\rangle = |0\rangle \\H|-\rangle = |1\rangle \\H|i\rangle = e^{i\pi/4}|-i\rangle \\H|-i\rangle = e^{-i\pi/4}|i\rangle$        H    > As a reminder, $e^{i\pi/4} = \frac{1}{\sqrt2} (1 + i)$ and $e^{-i\pi/4} = \frac{1}{\sqrt2} (1 - i)$. > If you need a refresher on calculating expressions like $e^{i\theta}$, you should review the section on [complex exponentiation](../ComplexArithmetic/ComplexArithmetic.ipynbImaginary-Exponents).  Exercise 4: Preparing a $|-\rangle$ state**Input:** A qubit in state $|0\rangle$.**Goal:** Transform the qubit into state $|-\rangle$.<jupyter_code>%kata T4_PrepareMinus

operation PrepareMinus (q : Qubit) : Unit is Adj+Ctl {
    X(q);
    H(q);
    
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbExercise-4:-Preparing-a-$|-\rangle$-state).*  Phase Shift GatesThe next two gates are known as phase shift gates. They apply a phase to the $|1\rangle$ state, and leave the $|0\rangle$ state unchanged.                                    Gate        Matrix        Ket-Bra        Applying to $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        Applying to basis states        Q Documentation                $S$        $\begin{bmatrix} 1 & 0 \\ 0 & i \end{bmatrix}$        $|0\rangle\langle0| + i|1\rangle\langle1|$        $S|\psi\rangle = \alpha|0\rangle + i\beta|1\rangle$        $S|0\rangle = |0\rangle \\S|1\rangle = i|1\rangle \\S|+\rangle = |i\rangle \\S|-\rangle = |-i\rangle \\S|i\rangle = |-\rangle \\S|-i\rangle = |+\rangle$        S                $T$        $\begin{bmatrix} 1 & 0 \\ 0 & e^{i\pi/4} \end{bmatrix}$        $|0\rangle\langle0| + e^{i\pi/4}|1\rangle$$\langle1|$        $T|\psi\rangle = \alpha|0\rangle + e^{i\pi/4} \beta |1\rangle$        $T|0\rangle = |0\rangle \\T|1\rangle = e^{i\pi/4}|1\rangle$        T    > Notice that applying the $T$ gate twice is equivalent to applying the $S$ gate, and applying the $S$ gate twice is equivalent to applying the $Z$ gate: $$T^2 = S, S^2 = Z$$  Exercise 5: Three-fourths phase**Input:** A qubit in an arbitrary state $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$.**Goal:** Use several phase shift gates to apply the transformation represented by the following matrix to the given qubit:$$\begin{bmatrix} 1 & 0 \\ 0 & e^{3i\pi/4} \end{bmatrix}$$    Need a hint? Click here    As a reminder, $i = e^{i\pi/2}$.<jupyter_code>%kata T5_ThreeQuatersPiPhase

operation ThreeQuatersPiPhase (q : Qubit) : Unit is Adj+Ctl {
    S(q);
    T(q);
    
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbExercise-5:-Three-fourths-phase).*  Rotation GatesThe next few gates are parametrized: their exact behavior depends on a numeric parameter - an angle $\theta$, given in radians. These gates are the $X$ rotation gate $R_x(\theta)$, $Y$ rotation gate $R_y(\theta)$, $Z$ rotation gate $R_z(\theta)$, and the arbitrary phase gate $R_1(\theta)$. Note that for the first three gates the parameter $\theta$ is multiplied by $\frac{1}{2}$ within the gate's matrix.> These gates are known as rotation gates, because they represent rotations around various axes on the Bloch sphere. The Bloch sphere is a way of representing the qubit states visually, mapping them onto the surface of a sphere. > Unfortunately, this visualization isn't very useful beyond single-qubit states, which is why we have opted not to go into details in this tutorial series. > If you are curious about it, you can learn more in [this slide deck](http://www.vcpc.univie.ac.at/~ian/hotlist/qc/talks/bloch-sphere.pdf) or in [Wikipedia article](https://en.wikipedia.org/wiki/Bloch_sphere).                                Gate        Matrix        Applying to $|\psi\rangle = \alpha|0\rangle + \beta|1\rangle$        Applying to basis states        Q Documentation                $R_x(\theta)$        $\begin{bmatrix} \cos\frac{\theta}{2} & -i\sin\frac{\theta}{2} \\ -i\sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}$        $R_x(\theta)|\psi\rangle = (\alpha\cos\frac{\theta}{2} - i\beta\sin\frac{\theta}{2})|0\rangle + (\beta\cos\frac{\theta}{2} - i\alpha\sin\frac{\theta}{2})|1\rangle$        $R_x(\theta)|0\rangle = \cos\frac{\theta}{2}|0\rangle - i\sin\frac{\theta}{2}|1\rangle \\R_x(\theta)|1\rangle = \cos\frac{\theta}{2}|1\rangle - i\sin\frac{\theta}{2}|0\rangle$        Rx                $R_y(\theta)$        $\begin{bmatrix} \cos\frac{\theta}{2} & -\sin\frac{\theta}{2} \\ \sin\frac{\theta}{2} & \cos\frac{\theta}{2} \end{bmatrix}$        $R_y(\theta)|\psi\rangle = (\alpha\cos\frac{\theta}{2} - \beta\sin\frac{\theta}{2})|0\rangle + (\beta\cos\frac{\theta}{2} + \alpha\sin\frac{\theta}{2})|1\rangle$        $R_y(\theta)|0\rangle = \cos\frac{\theta}{2}|0\rangle + \sin\frac{\theta}{2}|1\rangle \\R_y(\theta)|1\rangle = \cos\frac{\theta}{2}|1\rangle - \sin\frac{\theta}{2}|0\rangle$        Ry                $R_z(\theta)$        $\begin{bmatrix} e^{-i\theta/2} & 0 \\ 0 & e^{i\theta/2} \end{bmatrix}$        $R_z(\theta)|\psi\rangle = \alpha e^{-i\theta/2}|0\rangle + \beta e^{i\theta/2}|1\rangle$        $R_z(\theta)|0\rangle = e^{-i\theta/2}|0\rangle \\R_z(\theta)|1\rangle = e^{i\theta/2}|1\rangle$        Rz                $R_1(\theta)$        $\begin{bmatrix} 1 & 0 \\ 0 & e^{i\theta} \end{bmatrix}$        $R_1(\theta)|\psi\rangle = \alpha|0\rangle + \beta e^{i\theta}|1\rangle$        $R_1(\theta)|0\rangle = |0\rangle \\R_1(\theta)|1\rangle = e^{i\theta}|1\rangle$        R1    You have already encountered some special cases of the $R_1$ gate: $$T = R_1(\frac{\pi}{4}), S = R_1(\frac{\pi}{2}), Z = R_1(\pi)$$In addition, this gate is closely related to the $R_z$ gate: applying $R_1$ gate is equivalent to applying the $R_z$ gate, and then applying a global phase: $$R_1(\theta) = e^{i\theta/2}R_z(\theta)$$In addition, the rotation gates are very closely related to their respective Pauli gates: $$X = iR_x(\pi), Y = iR_y(\pi), Z = iR_z(\pi)$$  Exercise 6: Preparing a rotated state**Inputs:**1. Real numbers $\alpha$ and $\beta$ such that $\alpha^2 + \beta^2 = 1$.3. A qubit in state $|0\rangle$.**Goal:** Use a rotation gate to transform the qubit into state $\alpha|0\rangle -i\beta|1\rangle$.> You will probably need functions from the [Math](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.math) namespace, specifically [ArcTan2](https://docs.microsoft.com/qsharp/api/qsharp/microsoft.quantum.math.arctan2).> > You can assign variables in Q by using the `let` keyword: `let num = 3;` or `let result = Function(input);`    Need a hint? Click here    Don't forget, you can tell what a matrix does to the basis states by looking at its matrix: the first column of the matrix is the state into which it will transform the $|0\rangle$ state.<jupyter_code>%kata T6_PrepareRotatedState

open Microsoft.Quantum.Math;

operation PrepareRotatedState (alpha : Double, beta : Double, q : Qubit) : Unit is Adj+Ctl {
    
    let theta = 2.0*ArcTan2(beta, alpha);
    
    // nice, find the angle then put in superposition! 
    Rx(theta, q);
}<jupyter_output><empty_output><jupyter_text>*Can't come up with a solution? See the explained solution in the [Single-Qubit Gates Workbook](./Workbook_SingleQubitGates.ipynbExercise-6:-Preparing-a-rotated-state).*  Exercise 7**: Preparing an arbitrary state**Inputs:**1. A non-negative real number $\alpha$.2. A non-negative real number $\beta = \sqrt{1 - \alpha^2}$.3. A real number $\theta$.4. A qubit in state $|0\rangle$.**Goal:** Transform the qubit into state $\alpha|0\rangle + e^{i\theta}\beta|1\rangle$.> Since only the relative amplitudes and relative phase have any physical meaning, this allows us to prepare any single-qubit quantum state we want to.<jupyter_code>%kata T7_PrepareArbitraryState

open Microsoft.Quantum.Math;

operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl {
    
    let theta_y = 2.0 * ArcTan2(beta, alpha);
    Ry(theta_y, q); // takes the qubit to alpha|0> + beta|1>
    R1(theta, q); // takes qubit to alpha|0> + exp(i\theta)beta|1>
    
}<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1436337720025193, 'fraction_numerical': 0.018961116451751914, 'mean_word_length': 3.4534986713906113, 'pattern_counts': {'":': 0, '<': 36, '<?xml version=': 0, '>': 80, 'https://': 9, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 9, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '9', 'dir': 'jupyter-structured-clean-dedup', 'id': '589610', 'license': 'MIT', 'n_tokens_mistral': 9780, 'n_tokens_neox': 9159, 'n_words': 3401, 'path': 'tutorials/SingleQubitGates/SingleQubitGates.ipynb', 'repo_name': 'TheGupta2012/QuantumKatas', 'size': '30167'}