### Import Libraries and Setup for Linear Algebra Exercises (Python) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/LinearAlgebra/LinearAlgebra.ipynb Imports necessary functions and constants for linear algebra exercises, including testing utilities and complex number support. This setup is crucial before running any of the provided exercises. ```Python # Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise, create_empty_matrix from typing import List import math, cmath Matrix = List[List[complex]] ``` -------------------------------- ### Setup Environment and Import Libraries Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/QuantumClassification/ExploringQuantumClassificationLibrary.ipynb This Python code prepares the environment for quantum classification tasks. It imports necessary libraries like numpy and matplotlib, configures plotting routines, and initializes the Q# environment and relevant Q# namespaces. ```python import math import random from typing import List import numpy as np from matplotlib import pyplot pyplot.style.use('ggplot') import warnings warnings.simplefilter('ignore') %matplotlib inline # Plotting configuration cases = [(0, 0), (0, 1), (1, 1), (1, 0)] markers = [ '.' if actual == classified else 'X' for (actual, classified) in cases ] colors = ['blue', 'blue', 'red', 'red'] # Q# configuration and necessary imports import qsharp import Microsoft.Quantum.Kata.QuantumClassification as QuantumClassification print() print("Setup complete!") ``` -------------------------------- ### Q# Example Test Harness Operation Source: https://context7.com/microsoft/quantumkatas/llms.txt Demonstrates an example test operation within the Quantum Katas, specifically for verifying solutions using `AssertOperationsEqualReferenced`. It also includes a helper operation `DumpDiff` for visualizing and comparing quantum states produced by different implementations. ```qsharp namespace Quantum.Kata.BasicGates { open Microsoft.Quantum.Diagnostics; // Test that verifies your solution matches reference @Test("QuantumSimulator") operation T101_StateFlip () : Unit { AssertOperationsEqualReferenced(2, ArrayWrapperControlled(StateFlip, _), ArrayWrapperControlled(StateFlip_Reference, _)); } // Helper to show difference between solutions operation DumpDiff (N : Int, statePrep : (Qubit[] => Unit), testImpl : (Qubit[] => Unit), refImpl : (Qubit[] => Unit)) : Unit { use qs = Qubit[N]; statePrep(qs); Message("The starting state:"); DumpMachine(); // ... compare implementations } } ``` -------------------------------- ### Start Jupyter Notebook in Docker Source: https://github.com/microsoft/quantumkatas/blob/main/README.md Starts a Jupyter Notebook server within the Docker container, making it accessible from the host machine. It navigates to the kata directory and configures Jupyter to listen on all interfaces. ```bash cd ~/BasicGates/ && jupyter notebook --ip=0.0.0.0 --no-browser ``` -------------------------------- ### Run Grover's Search Algorithm Example (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/GroversAlgorithm/GroversAlgorithm.ipynb Defines and runs an example of Grover's search algorithm, utilizing previously implemented operations. This allows for experimentation with the algorithm's parameters and behavior. ```qsharp operation Run_GroversSearch_Algorithm () : Unit { // ... } ``` ```qsharp %simulate Run_GroversSearch_Algorithm ``` -------------------------------- ### Open Kata Folder in VS Code Source: https://github.com/microsoft/quantumkatas/blob/main/README.md Launches Visual Studio Code and opens a specified kata directory. This is useful for quickly accessing the kata's files and starting development. ```bash code QuantumKatas/BasicGates/ ``` -------------------------------- ### Controlled Gate Application Example in C# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitGates/MultiQubitGates.ipynb Demonstrates how to apply controlled gates in Q# using the Controlled functor. It shows equivalent CNOT and Controlled X applications, and how to apply a controlled SWAP gate with a tuple of arguments. ```csharp Controlled X([control], target); CNOT(control, target); ``` ```csharp Controlled SWAP([control], (q1, q2)); ``` -------------------------------- ### Implement Classical Functions in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ExploringDeutschJozsaAlgorithm/DeutschJozsaAlgorithmTutorial_P1.ipynb Provides Q# implementations for classical functions: f(x) = 0, f(x) = 1, f(x) = x mod 2, and f(x) = number of ones in binary representation of x is odd. These functions serve as examples for the Deutsch-Jozsa algorithm. ```Q# function Function_Zero (x : Int) : Int { return 0; } // Function 2. f(x) = 1 function Function_One (x : Int) : Int { return 1; } // Function 3. f(x) = x mod 2 (least significant bit of x) function Function_Xmod2 (x : Int) : Int { return x % 2; } // Function 4. f(x) = 1 if the binary notation of x has odd number of 1s, and 0 otherwise function Function_OddNumberOfOnes (x : Int) : Int { mutable nOnes = 0; mutable xBits = x; while (xBits > 0) { if xBits % 2 > 0 { set nOnes += 1; } set xBits /= 2; } return nOnes % 2; } ``` -------------------------------- ### Bash: Running Quantum Katas and Tests Source: https://context7.com/microsoft/quantumkatas/llms.txt Provides commands to clone the Quantum Katas repository, navigate into a specific kata's directory, and run its tests using the .NET CLI. It also shows how to launch Jupyter Notebooks for interactive exploration. ```bash # Clone the repository git clone https://github.com/Microsoft/QuantumKatas.git cd QuantumKatas # Run a specific kata's tests (e.g., BasicGates) cd BasicGates dotnet test # Expected output shows which tests pass/fail: # Starting test execution, please wait... # Passed T101_StateFlip [< 1 ms] # Failed T102_BasisChange [< 1 ms] # ... # Run Jupyter Notebooks jupyter notebook index.ipynb # Project structure for each kata: # BasicGates/ # ├── Tasks.qs # Fill in your solutions here # ├── Tests.qs # Unit tests (don't modify) # ├── ReferenceImplementation.qs # Reference solutions # ├── BasicGates.csproj # Project file # └── BasicGates.ipynb # Jupyter notebook version # Global configuration in global.json: # { # "sdk": { "version": "6.0.100" }, # "msbuild-sdks": { # "Microsoft.Quantum.Sdk": "0.28.302812" # } # } ``` -------------------------------- ### Q# Demo: Compare Measurement Statistics for Full vs. Sequential Qubit Measurement Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb This Q# operation, DemoBasisMeasurement, demonstrates that measuring qubits sequentially yields the same probabilities as a simultaneous full measurement. It prepares a specific quantum state and compares simulated measurement probabilities with theoretical ones over a given number of runs. Dependencies include Microsoft.Quantum.Diagnostics, Microsoft.Quantum.Preparation, Microsoft.Quantum.Arithmetic, and Microsoft.Quantum.Convert. ```Q# open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Preparation; open Microsoft.Quantum.Arithmetic; open Microsoft.Quantum.Convert; operation DemoBasisMeasurement(numRuns : Int) : Unit { // Define coefficients and obtain measurement probabilities // for the state corresponding to Exercise 1 // |𝜓❭ = 0.33 |00❭ + 0.67 |01❭ + 0.67 |11❭ // Use little endian format to encode basis states as integer indices. let coefficients = [0.333, 0.0, 0.667, 0.667]; let expected_probabilities = [0.111, 0.0, 0.445, 0.445]; // Set up counter array for measurements. mutable countArray = [0, 0, 0, 0]; use qs = Qubit[2]; for i in 1 .. numRuns { let register = LittleEndian(qs); // Prepare the state using PrepareArbitraryStateD library operation: PrepareArbitraryStateD(coefficients, register); if i == 1 { Message("The state |𝜓❭ of the system before measurement is:"); DumpMachine(); } // Measure the first qubit, followed by the second qubit, and convert the result to little endian integer let result = MeasureInteger(register); // Update countArray set countArray w/= result <- countArray[result] + 1; } // Obtain simulated probability of measurement for each outcome mutable simulated_probabilities = []; for i in 0 .. 3 { set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)]; } Message($"Theoretical measurement probabilities are {expected_probabilities}"); Message($"Simulated measurement probabilities are {simulated_probabilities}"); } ``` -------------------------------- ### Oracle Conversion Demo in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/Oracles/Oracles.ipynb Demonstrates the conversion of a marking oracle to a phase oracle using the implementation from Task 2.1. It compares the output state after applying a direct phase oracle (from Task 1.2) with the state after applying the converted marking oracle (from Task 1.3). This demo requires Tasks 1.2, 1.3, and 2.1 to be solved correctly. ```qsharp open Microsoft.Quantum.Diagnostics; operation OracleConverterDemo () : Unit { // Allocate the qubits in the state |000⟩ use register = Qubit[3]; // Prepare an equal superposition state ApplyToEachA(H, register); Message("The equal superposition state:"); DumpMachine(); // Apply the oracle from task 1.2 IsSeven_PhaseOracle(register); // Dump the state after application of the oracle Message("The state after applying the phase oracle from task 1.2:"); DumpMachine(); // Reset the qubits for deallocation ResetAll(register); // Prepare an equal superposition state again ApplyToEachA(H, register); // Apply the marking oracle from task 1.3 as a phase oracle ApplyMarkingOracleAsPhaseOracle(IsSeven_MarkingOracle, register); // Dump the state after application of the oracle Message("The state after applying the converted marking oracle from task 1.3:"); DumpMachine(); // reset the qubits for deallocation ResetAll(register); } ``` -------------------------------- ### Demo: DumpMachine for Multi-Qubit Systems in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/VisualizationTools/VisualizationTools.ipynb Demonstrates the use of DumpMachine to display the quantum state of a program acting on two qubits. It shows the state transitions after applying X, CNOT, Rx, Ry, and Rz gates. The DumpMachine operation visualizes the amplitudes of the basis states. ```qsharp open Microsoft.Quantum.Diagnostics; operation MultiQubitDumpMachineDemo () : Unit { // This line allocates two qubits in state |00⟩. use qs = Qubit[2]; Message("State |00⟩:"); // This line prints out the state of the quantum system. DumpMachine(); // X gate changes the second qubit into state |1⟩. // The entire system is now in state |01⟩, or, in little-endian notation, |2⟩. X(qs[1]); Message("State |01⟩:"); DumpMachine(); CNOT(qs[1], qs[0]); Rx(1.0, qs[0]); Ry(2.0, qs[1]); Rz(3.0, qs[1]); Message("Uneven superposition state:"); DumpMachine(); // This line returns the qubits to state |0⟩ before releasing them. ResetAll(qs); } ``` ```python %simulate MultiQubitDumpMachineDemo ``` -------------------------------- ### Determine if an edge contains a vertex (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/GraphColoring/Workbook_GraphColoring.ipynb Checks if a given vertex is part of a specified edge. The function takes an edge represented as a tuple of two integers (start and end vertex indices) and a single vertex index. It returns true if the vertex matches either the start or end of the edge, and false otherwise. ```qsharp %kata T31_DoesEdgeContainVertex function DoesEdgeContainVertex (edge: (Int, Int), vertex : Int) : Bool { // Deconstruct the edge tuple let (start, end) = edge; // Check if start vertex or end vertex is same as the given vertex return start == vertex or end == vertex; } ``` -------------------------------- ### Demonstrate DumpOperation for Q# Operations Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/VisualizationTools/VisualizationTools.ipynb This Q# operation demonstrates the usage of the DumpOperation diagnostic tool. It applies a specified operation (e.g., CNOT) to a set of qubits and prints the resulting matrix. This is useful for verifying that a Q# operation implements a desired unitary transformation. ```qsharp open Microsoft.Quantum.Diagnostics; operation DumpOperationDemo () : Unit { DumpOperation(2, ApplyToFirstTwoQubitsCA(CNOT, _)); } ``` -------------------------------- ### Apply Hadamard Transform to Register (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/GroversAlgorithm/GroversAlgorithm.ipynb Applies the Hadamard transform to each qubit in a given register. If the register starts in the |0...0> state, this operation prepares an equal superposition of all 2^N basis states. ```qsharp %kata T21_HadamardTransform operation HadamardTransform (register : Qubit[]) : Unit is Adj { // ... } ``` -------------------------------- ### Prepare State using Post-Selection with Repeat-Until-Success in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/Workbook_MultiQubitSystemMeasurements.ipynb This Q# operation prepares a target quantum state using the post-selection technique combined with a repeat-until-success loop. It applies Hadamard gates, a CCNOT gate, and measures an auxiliary qubit. The loop continues until the measurement result is 'Zero', indicating success. The 'fixup' section resets qubits if the loop condition is not met. This method is efficient for preparing specific quantum states. ```qsharp open Microsoft.Quantum.Measurement; operation PostSelection (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); } } ``` -------------------------------- ### Initial Python Setup for Complex Arithmetic Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ComplexArithmetic/Workbook_ComplexArithmetic.ipynb This code block sets up the necessary imports and type definitions for the Complex Arithmetic exercises. It imports the 'exercise' decorator for testing and defines type aliases for complex numbers and polar coordinates. ```python # Run this cell using Ctrl+Enter (⌘+Enter on Mac). from testing import exercise from typing import Tuple import math Complex = Tuple[float, float] Polar = Tuple[float, float] ``` -------------------------------- ### Q# Demo: Partial Measurement Statistics Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb This Q# operation demonstrates partial measurement statistics. It prepares a specific quantum state, performs a computational basis measurement on the first qubit multiple times, and calculates the simulated probabilities of observing each outcome. It then compares these simulated probabilities with theoretically expected values. Dependencies include Microsoft.Quantum.Diagnostics, Microsoft.Quantum.Preparation, Microsoft.Quantum.Arithmetic, Microsoft.Quantum.Convert, and Microsoft.Quantum.Math. ```qsharp open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Preparation; open Microsoft.Quantum.Arithmetic; open Microsoft.Quantum.Convert; open Microsoft.Quantum.Math; operation DemoPartialMeasurement(numRuns : Int) : Unit { let divider = "--------------------------------------------------------------------------------------------------"; // // We can use coefficients without normalization in PrepareArbitraryStateD, // the operation will normalize them automatically. let coefficients = [3., 1., 1., 1.]; let expected_probabilities = [0.833, 0.167]; // Set up the counter array for measurements. mutable countArray = [0, 0]; use qs = Qubit[2]; for i in 1 .. numRuns { // Prepare the state from Exercise 4: // |𝜓❭ = (1/√12)(3|00⟩+|01⟩+|10⟩+|11⟩) PrepareArbitraryStateD(coefficients, LittleEndian(qs)); // Display the state of the qubits. if i == 1 { Message("The state |𝜓❭ of the system before measurement is:"); DumpMachine(); Message(divider); } // Measure the first qubit. let outcome = M(qs[0]) == Zero ? 0 | 1; set countArray w/= outcome <- countArray[outcome] + 1; if countArray[outcome] == 1 { // The first time the outcome is 0/1, print the system state afterwards. Message("For outcome {outcome}, the post-measurement state of the system is:"); DumpMachine(); } ResetAll(qs); } // Obtain simulated probability of measurement for each outcome mutable simulated_probabilities = []; for i in 0 .. 1 { set simulated_probabilities += [IntAsDouble(countArray[i]) / IntAsDouble(numRuns)]; } Message($"Theoretical measurement probabilities are {expected_probabilities}"); Message($"Simulated measurement probabilities are {simulated_probabilities}"); } ``` -------------------------------- ### Prepare Environment and Import Libraries (Python) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ExploringGroversAlgorithm/VisualizingGroversAlgorithm.ipynb Initializes the Q# environment and imports necessary Python libraries and Q# operations for running Grover's algorithm. It also suppresses warnings and configures matplotlib for inline plotting. ```python import qsharp import Quantum.Kata.ExploringGroversAlgorithm as Grover import warnings warnings.simplefilter('ignore') %matplotlib inline from matplotlib import pyplot ``` -------------------------------- ### State Preparation using Post-Selection (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb Prepares a specific three-qubit state (|00> + |01> + |10>) from an initial |00> state using post-selection. This technique involves preparing an auxiliary state and measuring it to collapse the target qubits into the desired state with high probability. ```qsharp %kata T4_PostSelection operation PostSelection (qs : Qubit[]) : Unit { // ... } ``` -------------------------------- ### Get Frequency of Signal using Q# Source: https://github.com/microsoft/quantumkatas/blob/main/QFT/QFT.ipynb Determines the frequency of a signal represented in a quantum state using Q#. This operation is part of state analysis tasks using QFT. It takes a register of qubits and returns an integer representing the frequency. ```qsharp %kata T26_Frequency operation Frequency (register : Qubit[]) : Int { // ... return -1; } ``` -------------------------------- ### Get Azure Quantum Job Status Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ExploringDeutschJozsaAlgorithm/AQ/DeutschJozsaAlgorithmTutorial_P4.ipynb Retrieves the status of the latest executed job in the current notebook session. If a specific job ID is provided as an argument, it fetches the status for that particular job. This is useful for monitoring job progress. ```python %azure.status ``` -------------------------------- ### Implement 2x2 Chessboard Pattern for N Qubits in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/UnitaryPatterns/UnitaryPatterns.ipynb Implements a unitary transformation on N qubits where zero and non-zero elements form a 2x2 chessboard pattern, starting with non-zero elements in the top-left square. The operation takes an array of Qubits as input. ```qsharp operation ChessPattern2x2 (qs : Qubit[]) : Unit { // ... } ``` -------------------------------- ### Simulate Deutsch Algorithm Wrapper in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ExploringDeutschJozsaAlgorithm/AQ/DeutschJozsaAlgorithmTutorial_P4.ipynb Demonstrates running the DeutschAlgorithmWrapper operation on a simulator using the %simulate magic command in a Q# notebook. This is used to test the implementation before running on hardware. ```qsharp %simulate DeutschAlgorithmWrapper oracleFunction=0 ``` ```qsharp %simulate DeutschAlgorithmWrapper oracleFunction=x ``` -------------------------------- ### Complex Number Example in Python Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/LinearAlgebra/Workbook_LinearAlgebra.ipynb Demonstrates the usage of Python's built-in complex data type and the cmath library for complex number operations. It shows how to create complex numbers, access their real and imaginary parts, and convert them to polar representation. ```Python # Import the cmath library import cmath # Create a new complex number 5 + 3i; the two arguments are the real and the imaginary parts of the number complexNumber = complex(5, 3) # Print the real and the imaginary parts of the number print(complexNumber.real) print(complexNumber.imag) # Convert the complex number to its polar representation using the cmath library polar = cmath.polar(complexNumber) print(polar) # This prints: (5.830951894845301, 0.5404195002705842) ``` -------------------------------- ### Q# Solution for State Preparation and Basis Transformation Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/Workbook_MultiQubitSystemMeasurements.ipynb This Q# code prepares a specific quantum state using rotations and then applies Hadamard gates to transform the basis. It utilizes DumpMachine to display the state before and after the transformation. Dependencies include Microsoft.Quantum.Diagnostics and Microsoft.Quantum.Math. ```qsharp open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Math; operation SetInitialState (qs: Qubit[]) : Unit is Adj + Ctl { // Next two lines set the second qubit into the desired state let second_bit_angle = 2.0 * ArcCos(2.0 / 3.0); Ry(second_bit_angle, qs[1]); // Next two lines set the first qubit into the desired state let first_bit_angle = 2.0 * ArcCos(1.0 / Sqrt(5.0)); Controlled Ry([qs[1]], (first_bit_angle, qs[0])); } operation ChangeBasis (qs: Qubit[]) : Unit is Adj + Ctl { H(qs[0]); H(qs[1]); } operation CalculateProbabilities () : Unit { // This allocates qubits for us to work with use qs = Qubit[2]; SetInitialState(qs); // Check that we've prepared the state |𝜓⟩ Message("The state of the system before the transformation:"); DumpMachine(); ChangeBasis(qs); Message("Final state of the two-qubit system:"); DumpMachine(); // This returns the qubit array into state |00❭ ResetAll(qs); } ``` ```qsharp %simulate CalculateProbabilities ``` -------------------------------- ### Demonstrate Measurement Statistics in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/SingleQubitSystemMeasurements/SingleQubitSystemMeasurements.ipynb Shows how to collect measurement statistics by repeatedly preparing a qubit in the same superposition state and measuring it. It counts the occurrences of 'Zero' and 'One' outcomes over a specified number of runs and compares them to theoretical probabilities. Requires Microsoft.Quantum.Diagnostics and Microsoft.Quantum.Math. ```qsharp open Microsoft.Quantum.Diagnostics; open Microsoft.Quantum.Math; operation MeasumentStatisticsDemo () : Unit { mutable countZero = 0; let numRuns = 100; use q = Qubit(); for i in 1 .. numRuns { // Prepare the qubit in the superposition state // |𝜓❭ = 0.6 |0❭ + 0.8 |1❭ Ry(2.0 * ArcTan2(0.8, 0.6), q); // Measure in the computational basis, and update the counts according to the outcomes if M(q) == Zero { set countZero += 1; } // Reset the qubit for use in the next iteration Reset(q); } let countOne = numRuns - countZero; Message($"Simulated probability of measuring 0 is 0.{countZero}."); Message("Theoretical probability of measuring 0 is 0.36."); Message($"Simulated probability of measuring 1 is 0.{countOne}."); Message("Theoretical probability of measuring 0 is 0.64."); } ``` -------------------------------- ### Classify Data and Calculate Miss Rate (Python) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/QuantumClassification/ExploringQuantumClassificationLibrary.ipynb This Python code snippet classifies validation data using a trained quantum model and calculates the miss rate. It calls the Q# operation `ClassifyLinearlySeparableModel` to get predicted labels and then compares them to the actual labels to determine the miss rate. ```python # Validation parameters tolerance = 0.0005 nMeasurements = 10_000 # Classify validation data set using training results classified_labels = QuantumClassification.ClassifyLinearlySeparableModel.simulate( samples = validation_data['Features'], parameters = parameters, bias = bias, tolerance = tolerance, nMeasurements = nMeasurements ) # Calculate miss rate mask = np.not_equal(validation_data['Labels'], classified_labels) miss_count = np.array(classified_labels)[np.where(mask)].size miss_rate = miss_count / len(classified_labels) print(f"Miss rate: {miss_rate:0.2%}") ``` -------------------------------- ### Get Clause Qubits in Python Source: https://github.com/microsoft/quantumkatas/blob/main/SolveSATWithGrover/Workbook_SolveSATWithGrover.ipynb This Python function, GetClauseQubits, identifies and returns the qubits that correspond to the variables present in a given SAT clause. It iterates through the clause definition and collects the relevant qubits from the query register. This is a helper function for the Oracle_SATClause operation. ```python // Find all qubits which are variables in clause function GetClauseQubits (queryRegister : Qubit[], clause: (Int,Bool)[]) : Qubit[] { mutable clauseQubits = []; for (index, _) in clause { set clauseQubits += [queryRegister[index]]; } return clauseQubits; } ``` -------------------------------- ### Build Docker Image for Katas Source: https://github.com/microsoft/quantumkatas/blob/main/README.md Builds a Docker image tagged as 'katas' from the provided Dockerfile. This image contains all necessary tools to run the Quantum Katas. ```bash docker build -t katas . ``` -------------------------------- ### Implement Bob's Classical Strategy in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/CHSHGame/CHSHGame.ipynb This task involves implementing Bob's classical strategy function, 'BobClassical'. It takes Bob's starting bit (Y) as input and should return the bit (B) that maximizes their chance of winning the CHSH game. The provided code is a stub that needs to be completed. ```qsharp operation BobClassical (y : Bool) : Bool { // ... fail "Bob's strategy in task 1.2 not implemented yet"; } ``` -------------------------------- ### Prepare Arbitrary State using Ry and R1 in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/SingleQubitGates/Workbook_SingleQubitGates.ipynb Prepares an arbitrary single-qubit state $\alpha|0\rangle + e^{i\theta}\beta|1\rangle$ using Ry and R1 gates. It takes real coefficients alpha, beta, and a phase theta as input. ```qsharp open Microsoft.Quantum.Math; operation PrepareArbitraryState (alpha : Double, beta : Double, theta : Double, q : Qubit) : Unit is Adj+Ctl { Ry(2.0 * ArcTan2(beta, alpha), q); // Step 1 R1(theta, q); // Step 2 } ``` -------------------------------- ### Implement Alice's Classical Strategy in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/CHSHGame/CHSHGame.ipynb This task involves implementing Alice's classical strategy function, 'AliceClassical'. It takes Alice's starting bit (X) as input and should return the bit (A) that maximizes their chance of winning the CHSH game. The provided code is a stub that needs to be completed. ```qsharp operation AliceClassical (x : Bool) : Bool { // ... fail "Alice's strategy in task 1.2 not implemented yet"; } ``` -------------------------------- ### Q# Simulation and Tracing Commands Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/SingleQubitGates/SingleQubitGates.ipynb Commands to simulate a Q# operation and trace its execution, displaying the circuit diagram. These commands are typically used in an interactive environment like a Jupyter notebook. ```qsharp %simulate PauliGatesDemo %trace PauliGatesDemo ``` -------------------------------- ### Implement MultiControls using ControlledOnBitString (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitGates/Workbook_MultiQubitGates.ipynb This Q# code demonstrates the most concise way to implement the MultiControls operation by utilizing the pre-defined library function ControlledOnBitString. This function abstracts away the complexity of conditional gate application, allowing for a direct and readable solution. ```qsharp operation MultiControls (controls : Qubit[], target : Qubit, controlBits : Bool[]) : Unit is Adj { (ControlledOnBitString(controlBits, X))(controls, target); } ``` -------------------------------- ### Create Bell State |Φ⁺⟩ on Two Qubits in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/Superposition/Superposition.ipynb This snippet shows how to create the Bell state |Φ⁺⟩ = 1/√2 (|00⟩ + |11⟩) using two qubits. Starting from the |00⟩ state, it involves applying a Hadamard gate to the first qubit and a CNOT gate controlled by the first qubit targeting the second. ```qsharp operation BellState (qs : Qubit[]) : Unit { // ... } ``` -------------------------------- ### Play CHSH Game with Quantum Strategies (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/CHSHGame/CHSHGame.ipynb Implements Task 2.5 to play the CHSH game using quantum strategies. This operation takes functions representing Alice and Bob's quantum strategies and returns their output bits (A, B). It assumes Alice and Bob have already been assigned their starting bits (X and Y). ```qsharp %kata T25_PlayQuantumCHSH operation PlayQuantumCHSH (askAlice : (Qubit => Bool), askBob : (Qubit => Bool)): (Bool, Bool) { // ... fail "Task 2.5 not implemented yet"; } ``` -------------------------------- ### DumpMachine for Single-Qubit State Visualization in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/VisualizationTools/VisualizationTools.ipynb Demonstrates the use of the DumpMachine function in Q# to display the quantum state of a single-qubit system. It shows the state at different stages of computation, including initial state, after Hadamard gate, and after rotation gates. DumpMachine provides the exact state without disturbing it, useful for debugging simulators. ```qsharp open Microsoft.Quantum.Diagnostics; operation SingleQubitDumpMachineDemo () : Unit { // This line allocates a qubit in state |0⟩. use q = Qubit(); Message("State |0⟩:"); // This line prints out the state of the quantum system. // Since only one qubit is allocated, only its state is printed. DumpMachine(); // This line changes the qubit to state |+⟩ = (1/sqrt(2))(|0⟩ + |1⟩). // 1/sqrt(2) is approximately 0.707107. H(q); Message("State |+⟩:"); DumpMachine(); // This will put the qubit into an uneven superposition, // where the amplitudes of |0⟩ and |1⟩ have different absolute values and relative phases. Rx(1.0, q); Ry(2.0, q); Rz(3.0, q); Message("Uneven superposition state:"); DumpMachine(); // This line returns the qubit to state |0⟩ before releasing it. Reset(q); } ``` -------------------------------- ### Setup Environment and Import Libraries for Quantum Classification Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/QuantumClassification/QuantumClassificationWithFeatureEngineering.ipynb This Python code block sets up the necessary environment for quantum classification tasks. It imports essential libraries like numpy and matplotlib for data manipulation and visualization, and configures Q# packages for machine learning. It also defines plotting configurations for visualizing classification results. ```python import math import random from typing import List import numpy as np from matplotlib import pyplot pyplot.style.use('ggplot') import warnings warnings.simplefilter('ignore') %matplotlib inline # Plotting configuration cases = [(0, 0), (0, 1), (1, 1), (1, 0)] markers = [ '.' if actual == classified else 'X' for (actual, classified) in cases ] colors = ['blue', 'blue', 'red', 'red'] # Q# configuration and necessary imports import qsharp qsharp.packages.add("Microsoft.Quantum.MachineLearning") qsharp.reload() print() print("Setup complete!") ``` -------------------------------- ### Q# Exercise: Distinguish Four Basis States Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb This Q# operation, `BasisStateMeasurement`, is designed to identify which of the four basis states ($|00 angle$, $|01 angle$, $|10 angle$, or $|11 angle$) a two-qubit system is in. It takes an array of two qubits as input and returns an integer (0, 1, 2, or 3) corresponding to the identified state. The order of qubits in the array matches the state description (e.g., $|10 angle$ means `qs[0]` is $|1 angle$ and `qs[1]` is $|0 angle$). ```Q# %kata T1_BasisStateMeasurement operation BasisStateMeasurement(qs : Qubit[]) : Int { // Type your answer below // Then run the cell using Ctrl+Enter (⌘+Enter on macOS). // ... } ``` -------------------------------- ### Simulate Oracle Conversion Demo in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/Oracles/Oracles.ipynb Executes the OracleConverterDemo operation to simulate and observe the effects of applying a direct phase oracle versus a converted marking oracle. ```qsharp %simulate OracleConverterDemo ``` -------------------------------- ### Prepare Minus State using X and Hadamard Gates in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/Superposition/Workbook_Superposition.ipynb This Q# operation prepares the |-> state by applying an X gate to $|0\rangle$ to get $|1\rangle$, followed by a Hadamard gate. The X gate transforms $|0\rangle$ to $|1\rangle$, and the Hadamard gate transforms $|1\rangle$ to $\frac{1}{\sqrt{2}}(|0\rangle - |1\rangle)$. ```qsharp operation MinusState (q : Qubit) : Unit { X(q); H(q); } ``` -------------------------------- ### Oracle: Check if bit string contains substring at position (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/MarkingOracles/MarkingOracles.ipynb Implements a quantum oracle to check if an input register (bit string) contains a specific pattern (substring) starting at a given position. It operates on qubits in superposition without measurements and leaves the input register unchanged. Dependencies include Q# language features for quantum operations. ```qsharp operation ContainsSubstringAtPositionOracle (input : Qubit[], target : Qubit, pattern : Bool[], P : Int) : Unit is Adj { // ... } ``` -------------------------------- ### Simulate Phase Oracle Demo (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/Oracles/Oracles.ipynb Executes the PhaseOracle_Demo operation using the Q# simulator. This allows observation of the quantum state before and after the application of the AlternatingBitPattern_PhaseOracle. ```qsharp %simulate PhaseOracle_Demo ``` -------------------------------- ### Implement Bob's Quantum Strategy (Q#) Source: https://github.com/microsoft/quantumkatas/blob/main/CHSHGame/CHSHGame.ipynb Implements Bob's quantum strategy for Task 2.4. This operation takes Bob's starting bit and his half of a Bell pair. It measures Bob's qubit in either the pi/8 or -pi/8 basis based on his bit and returns the measurement result. The final state of the qubit is not relevant. ```qsharp %kata T24_BobQuantum operation BobQuantum (bit : Bool, qubit : Qubit) : Bool { // ... fail "Task 2.4 not implemented yet"; } ``` -------------------------------- ### Q# Simulation: Run DemoBasisMeasurement with 100 Runs Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/MultiQubitSystemMeasurements/MultiQubitSystemMeasurements.ipynb This code snippet simulates the Q# operation `DemoBasisMeasurement` with the parameter `numRuns` set to 100. It's used to observe the simulated measurement probabilities and compare them with the theoretical ones, illustrating the probabilistic nature of quantum measurements. ```Python %simulate DemoBasisMeasurement numRuns=100 ``` -------------------------------- ### Get Magic Square Observables (Python) Source: https://github.com/microsoft/quantumkatas/blob/main/MagicSquareGame/MagicSquareGame.ipynb Retrieves the observable for a given cell in a magic square. It takes row and column indices as input and outputs a tuple representing the observable, including its sign and an array of Pauli observables. The magic square must satisfy specific properties regarding commuting observables and products within rows and columns. ```python %kata T22_GetMagicObservables function GetMagicObservables (rowIndex : Int, columnIndex : Int) : (Int, Pauli[]) { // ... } ``` -------------------------------- ### Apply Magic Square Observables (Python) Source: https://github.com/microsoft/quantumkatas/blob/main/MagicSquareGame/MagicSquareGame.ipynb Applies a magic square observable to a given array of qubits. The observable is provided as a tuple (sign, Pauli[]), and the operation acts on a 2-qubit register. For example, applying (-1, [PauliX, PauliY]) would apply X to the first qubit, Y to the second, and a global phase of -1 to the two-qubit state. This operation supports adjoint and controlled variants. ```python %kata T23_ApplyMagicObservables operation ApplyMagicObservables (observable : (Int, Pauli[]), qs : Qubit[]) : Unit is Adj+Ctl { // ... } ``` -------------------------------- ### Simulate Q# SAT Instance Conversion Source: https://github.com/microsoft/quantumkatas/blob/main/tutorials/ExploringGroversAlgorithm/ExploringGroversAlgorithmTutorial.ipynb This code snippet simulates the execution of the `ConvertSATInstanceToString` Q# function. The `%simulate` directive is used to run the defined Q# operation within the simulation environment. ```Q# %simulate ConvertSATInstanceToString ``` -------------------------------- ### Implement Alice's Quantum Strategy in Q# Source: https://github.com/microsoft/quantumkatas/blob/main/CHSHGame/CHSHGame.ipynb This task involves implementing Alice's quantum strategy function, 'AliceQuantum'. It takes Alice's starting bit (bit) and her half of a Bell pair (qubit) as input. The goal is to measure the qubit in the Z basis if the bit is false, or in the X basis if the bit is true, and return the measurement result. The state of the qubit after the operation does not matter. The provided code is a stub. ```qsharp operation AliceQuantum (bit : Bool, qubit : Qubit) : Bool { // ... fail "Task 2.2 not implemented yet"; } ```