├── ProgrammingAssignmentSamples ├── AutogradedProblems │ ├── qsharp.json │ ├── Solutions.pptx │ ├── src │ │ ├── StatePrep.qs │ │ ├── Gate.qs │ │ ├── Measurement.qs │ │ ├── MarkingOracle.qs │ │ └── Test.qs │ ├── test_assignment.py │ └── README.md ├── ResourcesEstimation │ ├── expected_output.txt │ ├── README.md │ └── DeutschJozsaCode.qs └── DebuggingQuantumCode │ ├── DebuggingDJAgorithm-Solutions.pptx │ ├── README.md │ ├── DeutschJozsaCode.qs │ └── DeutschJozsaCode.ans ├── CODE_OF_CONDUCT.md ├── LICENSE ├── SUPPORT.md ├── SECURITY.md ├── .gitignore ├── README.md └── FinalProjects └── README.md /ProgrammingAssignmentSamples/AutogradedProblems/qsharp.json: -------------------------------------------------------------------------------- 1 | {} -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/ResourcesEstimation/expected_output.txt: -------------------------------------------------------------------------------- 1 | N Physical qubits Runtime 2 | 2 600 4 3 | 4 1764 11 4 | 6 2254 17 5 | 8 2744 22 6 | 10 3234 28 -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/Solutions.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/quantum-curriculum-samples/HEAD/ProgrammingAssignmentSamples/AutogradedProblems/Solutions.pptx -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/DebuggingQuantumCode/DebuggingDJAgorithm-Solutions.pptx: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/microsoft/quantum-curriculum-samples/HEAD/ProgrammingAssignmentSamples/DebuggingQuantumCode/DebuggingDJAgorithm-Solutions.pptx -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/src/StatePrep.qs: -------------------------------------------------------------------------------- 1 | // Task 1. Prepare the state 1/2 (|00⟩ + i|01⟩ - |10⟩ - i|11⟩). 2 | // Input: two qubits in the |00⟩ state (stored in an array of length 2). 3 | // Goal: prepare the following state on these qubits: 1/2 (|00⟩ + i|01⟩ - |10⟩ - i|11⟩). 4 | // The states of the qubits are given in order |qs[0], qs[1]⟩. 5 | operation Task1(qs : Qubit[]) : Unit { 6 | // Write your solution here. 7 | // ... 8 | } 9 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/src/Gate.qs: -------------------------------------------------------------------------------- 1 | import Std.Math.PI; 2 | // Task 3. Implement a controlled Rz gate. 3 | // Input: two qubits in an arbitrary state (stored in an array of length 2). 4 | // Goal: Apply a controlled Rz gate, using the first qubit as control and the second qubit as target, 5 | // with π/4 as the angle argument for the gate. 6 | operation Task3(qs : Qubit[]) : Unit { 7 | // Write your solution here. 8 | // ... 9 | } 10 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Microsoft Open Source Code of Conduct 2 | 3 | This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). 4 | 5 | Resources: 6 | 7 | - [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/) 8 | - [Microsoft Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) 9 | - Contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with questions or concerns 10 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/src/Measurement.qs: -------------------------------------------------------------------------------- 1 | // Task 2. Distinguish |0...0⟩ state from W state. 2 | // Input: N qubits (stored in an array of length N) which are guaranteed 3 | // to be either in the |0...0⟩ state or in the W state - 4 | // an equal superposition of all basis states that have exactly one |1⟩ in them. 5 | // Output: 0 if the qubits were in the |0...0⟩ state, 6 | // 1 if the qubits were in the W state. 7 | operation Task2(qs : Qubit[]) : Int { 8 | // Write your solution here. 9 | // ... 10 | -1 11 | } 12 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/src/MarkingOracle.qs: -------------------------------------------------------------------------------- 1 | // Task 4. Marking oracle for a function marking an arbitrary bit string 2 | // Inputs: 3 | // 1. N qubits in an arbitrary state |x⟩ (input/query register). 4 | // 2. A qubit in an arbitrary state |y⟩ (target qubit). 5 | // 3. A boolean array of length N representing a basis state; true and false elements correspond to |1⟩ and |0⟩, respectively. 6 | // Goal: 7 | // Flip the state of the qubit |y⟩ if the input register matches the basis state represented by the pattern. 8 | // For example, for N = 2 a pattern [false, true] would match the basis state: |01⟩. 9 | operation Task4( 10 | x : Qubit[], 11 | y : Qubit, 12 | pattern : Bool[] 13 | ) : Unit is Adj + Ctl { 14 | // Write your solution here. 15 | // ... 16 | } 17 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/DebuggingQuantumCode/README.md: -------------------------------------------------------------------------------- 1 | # Debugging Quantum Programs (Example) 2 | 3 | The Q# code in this task implements Deutsch-Jozsa algorithm for two example functions (one constant and one balanced). It contains exactly **7 bugs**, ranging from issues that will manifest as compilation errors to problems that will require running the fixed algorithm and analyzing its output. The list of bugs and their explanations is included in [DebuggingDJAgorithm-Solutions.pptx](.\DebuggingDJAgorithm-Solutions.pptx). 4 | 5 | The assignment is distributed as a single file, DeutschJozsaCode.qs. The students should identify the bugs, fix them, 6 | and submit the code with fixed bugs, (optionally) accompanied by brief explanations of each bug. 7 | 8 | > You can find the corresponding learning exercises in the [Deutsch-Jozsa Algorithm kata](https://quantum.microsoft.com/en-us/experience/quantum-katas?kataId=deutsch_jozsa§ionId=deutsch_jozsa__overview). -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Microsoft Corporation. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE 22 | -------------------------------------------------------------------------------- /SUPPORT.md: -------------------------------------------------------------------------------- 1 | # TODO: The maintainer of this repo has not yet edited this file 2 | 3 | **REPO OWNER**: Do you want Customer Service & Support (CSS) support for this product/project? 4 | 5 | - **No CSS support:** Fill out this template with information about how to file issues and get help. 6 | - **Yes CSS support:** Fill out an intake form at [aka.ms/spot](https://aka.ms/spot). CSS will work with/help you to determine next steps. More details also available at [aka.ms/onboardsupport](https://aka.ms/onboardsupport). 7 | - **Not sure?** Fill out a SPOT intake as though the answer were "Yes". CSS will help you decide. 8 | 9 | *Then remove this first heading from this SUPPORT.MD file before publishing your repo.* 10 | 11 | # Support 12 | 13 | ## How to file issues and get help 14 | 15 | This project uses GitHub Issues to track bugs and feature requests. Please search the existing 16 | issues before filing new issues to avoid duplicates. For new issues, file your bug or 17 | feature request as a new Issue. 18 | 19 | For help and questions about using this project, please **REPO MAINTAINER: INSERT INSTRUCTIONS HERE 20 | FOR HOW TO ENGAGE REPO OWNERS OR COMMUNITY FOR HELP. COULD BE A STACK OVERFLOW TAG OR OTHER 21 | CHANNEL. WHERE WILL YOU HELP PEOPLE?**. 22 | 23 | ## Microsoft Support Policy 24 | 25 | Support for this **PROJECT or PRODUCT** is limited to the resources listed above. 26 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/ResourcesEstimation/README.md: -------------------------------------------------------------------------------- 1 | # Resource Estimation for Quantum Programs (Example) 2 | 3 | This week's programming assignment introduces the task of resource estimation, i.e., figuring out the resources required to run the circuit implemented by the Q# code. 4 | 5 | The Q# program defines the circuit that needs to be estimated. `expected_output.txt`. 6 | 7 | For this assignment, share with the students the following instructions, together with the file `DeutschJozsaCode.qs`. The students submit a single text file with the results of resource estimation. This file should match the file `expected_output.txt`. Additionally, you can ask the students to explain the results in a free-form text note. 8 | 9 | ## Assignment instructions 10 | 11 | In this task you will explore the Deutsch-Jozsa algorithm and learn to run resource estimation for quantum algorithms. 12 | You do not need to submit the code you write; you submit only the file with the required output. 13 | 14 | Take the file `DeutschJozsaCode.qs` that contains the implementation of the Deutsch-Jozsa algorithm for an N-bit function f(x) = "1 if x has odd number of 1s, and 0 otherwise". 15 | Use [Azure Quantum Resource Estimator](https://learn.microsoft.com/azure/quantum/intro-to-resource-estimation) 16 | to get the number of physical qubits required to execute this program and the estimated runtime in microseconds. 17 | Use qubit model `qubit_gate_ns_e3` and error budget `0.001`. 18 | 19 | Fill the following table (in tab-separated format): 20 | ``` 21 | N Physical qubits Runtime 22 | 2 23 | 4 24 | 6 25 | 8 26 | 10 27 | ``` 28 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/test_assignment.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | import qsharp 3 | from cmath import exp 4 | from math import pi 5 | from qsharp.utils import dump_operation 6 | 7 | @pytest.fixture(autouse=True) 8 | def setup(): 9 | """Fixture to execute before each test is run""" 10 | qsharp.init(project_root=".") 11 | yield 12 | 13 | 14 | def test_1() -> None: 15 | """Test for task 1: check that Q# code prepares the expected state exactly (not up to a global phase).""" 16 | expected_state = [0.5, 0.5j, -0.5, -0.5j] 17 | 18 | # Run Q# code that allocates the qubits and prepares the state but doesn't deallocate the qubits. 19 | qsharp.eval(f"use qs = Qubit[2]; StatePrep.Task1(qs);") 20 | 21 | # Get the state of the allocated qubits and convert it to a vector. 22 | state = qsharp.dump_machine().as_dense_state() 23 | 24 | # Compare two vectors. 25 | assert state == pytest.approx(expected_state) 26 | 27 | 28 | def test_2() -> None: 29 | """Test for task 2: check that Q# code distinguishes states correctly.""" 30 | correct = qsharp.eval("Test.Test2()") 31 | assert correct 32 | 33 | 34 | def test_3() -> None: 35 | """Test for task 3: check that Q# code implementing an operation has the correct matrix.""" 36 | expected_matrix = [ 37 | [1, 0, 0, 0], 38 | [0, 1, 0, 0], 39 | [0, 0, exp(-1j * pi/8), 0], 40 | [0, 0, 0, exp(1j * pi/8)] 41 | ] 42 | matrix = dump_operation("Gate.Task3", 2) 43 | for (row, expected_row) in zip(matrix, expected_matrix): 44 | assert row == pytest.approx(expected_row) 45 | 46 | 47 | def test_4() -> None: 48 | """Test for task 4: check that Q# code implements the correct marking oracle.""" 49 | correct = qsharp.eval("Test.Test4()") 50 | assert correct 51 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/ResourcesEstimation/DeutschJozsaCode.qs: -------------------------------------------------------------------------------- 1 | // This programming assignment is focused on debugging Deutsch-Jozsa algorithm. 2 | // The code contains exactly 7 bugs. Find them all! 3 | 4 | // Marking oracle implementing a balanced function f(x) = 1 if x has odd number of 1s, and 0 otherwise 5 | operation MarkingOracleOddNumberOfOnes (x : Qubit[], y : Qubit) : Unit { 6 | ApplyToEachA(CNOT(_, y), x); 7 | } 8 | 9 | operation ApplyMarkingOracleAsPhaseOracle ( 10 | markingOracle : ((Qubit[], Qubit) => Unit), 11 | inputRegister : Qubit[] 12 | ) : Unit { 13 | use target = Qubit(); 14 | // Put the target into the |-⟩ state 15 | X(target); 16 | H(target); 17 | // Apply the marking oracle; since the target is in the |-⟩ state, 18 | // this will apply a -1 factor to the states that satisfy the oracle condition 19 | markingOracle(inputRegister, target); 20 | H(target); 21 | X(target); 22 | } 23 | 24 | operation IsFunctionConstant (nQubits : Int, phaseOracle : (Qubit[] => Unit)) : Bool { 25 | mutable isConstant = true; 26 | use qubits = Qubit[nQubits]; 27 | // Apply the H gates, the oracle and the H gates again 28 | within { 29 | ApplyToEachA(H, qubits); 30 | } apply { 31 | phaseOracle(qubits); 32 | } 33 | // Measure all qubits 34 | let measurementResults = MResetEachZ(qubits); 35 | for m in measurementResults { 36 | if m == One { 37 | set isConstant = false; 38 | } 39 | } 40 | return isConstant; 41 | } 42 | 43 | function ConstantOrBalanced (value : Bool) : String { 44 | return value ? "constant" | "balanced"; 45 | } 46 | 47 | @EntryPoint() 48 | operation RunDeutschJozsaAlgorithm () : Unit { 49 | let N = 10; 50 | let phaseOracle = ApplyMarkingOracleAsPhaseOracle(MarkingOracleOddNumberOfOnes, _); 51 | let isConstant = IsFunctionConstant(N, phaseOracle); 52 | Message($"f(x) classified as {ConstantOrBalanced(isConstant)}"); 53 | } 54 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/DebuggingQuantumCode/DeutschJozsaCode.qs: -------------------------------------------------------------------------------- 1 | // This programming assignment is focused on debugging Deutsch-Jozsa algorithm. 2 | // The code contains exactly 7 bugs. Find them all! 3 | 4 | // Phase oracle implementing a constant function f(x) = 0 5 | operation PhaseOracleZero (inputRegister : Qubit[]) : Unit { 6 | // Do nothing! 7 | } 8 | 9 | // Marking oracle implementing a balanced function f(x) = xₖ (the value of k-th bit) 10 | operation MarkingOracleKthBit (inputRegister : Qubit[], target : Qubit, k : Int) : Unit { 11 | Controlled X(inputRegister[k], target); 12 | } 13 | 14 | operation ApplyMarkingOracleAsPhaseOracle ( 15 | markingOracle : ((Qubit[], Qubit) => Unit), 16 | inputRegister : Qubit[] 17 | ) : Unit { 18 | use target = Qubit(1); 19 | // Put the target into the |-⟩ state 20 | X(target); 21 | H(target); 22 | // Apply the marking oracle; since the target is in the |-⟩ state, 23 | // this will apply a -1 factor to the states that satisfy the oracle condition 24 | markingOracle(inputRegister, target); 25 | } 26 | 27 | operation IsFunctionConstant (nQubits : Int, phaseOracle : (Qubit[] => Unit)) : Bool { 28 | mutable isConstant = true; 29 | use qubits = Qubit[nQubits]; 30 | // Apply the H gates, the oracle and the H gates again 31 | within { 32 | ApplyToEach(H, qubits); 33 | } apply { 34 | phaseOracle(qubits); 35 | } 36 | // Measure all qubits 37 | let measurementResults = MResetEachZ(qubits); 38 | for m in measurementResults { 39 | if m == Zero { 40 | set isConstant = false; 41 | } 42 | } 43 | return isConstant; 44 | } 45 | 46 | function ConstantOrBalanced (value : Bool) : String { 47 | return value ? "constant" | "balanced"; 48 | } 49 | 50 | @EntryPoint() 51 | operation RunDeutschJozsaAlgorithm () : Unit { 52 | // for constant function 53 | let isZeroConstant = IsFunctionConstant(2, PhaseOracleZero); 54 | Message($"f(x) = 0 classified as {ConstantOrBalanced(isZeroConstant)}"); 55 | 56 | // for balanced function 57 | let markingOracleSecondBit = MarkingOracleKthBit(_, _, 2); 58 | let phaseOracleSecondBit = ApplyMarkingOracleAsPhaseOracle(markingOracleSecondBit, _); 59 | let isSecondBitConstant = IsFunctionConstant(2, phaseOracleSecondBit); 60 | Message("f(x) = x₂ classified as {ConstantOrBalanced(isSecondBitConstant)}"); 61 | } 62 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/README.md: -------------------------------------------------------------------------------- 1 | # Automatically Graded Programming Assignments (Example) 2 | 3 | This folder contains an example of the automatically graded programming assignments. 4 | They include the testing harness that can be shared with the students as part of the homework to help them verify their solutions before submitting. 5 | 6 | This testing harness is logically very similar to the testing harnesses used in the Quantum Katas. 7 | However, the structure of the projects used here is different. It relies on Q# integration with Python 8 | and running tests for Q# code from Python using `pytest` library. 9 | 10 | To use assignments that follow this structure, share the whole project with the students and ask them to fill in the code marked with "Write your solution here." Notice that the tests for the tasks don't include the solution code, so they are safe to share with the students. 11 | 12 | To run the tests (both as a student working on the assignment and as the person grading it), navigate to the root folder of the assignment (the folder containing the Python file and `qsharp.json`) and run `pytest`. 13 | Initially, all tests will be failing. The goal is to fill in the code for each task to make the tests pass. 14 | 15 | You can combine all the code for the tasks into one Q# file for simplicity; in this case, the students have to turn in only that one file for grading. 16 | 17 | ## Examples of problems included in this project 18 | 19 | 1. Preparing a certain quantum state (similar to the "Preparing Quantum States" kata). 20 | 2. Using measurements to distinguish orthogonal quantum states (similar to the "Distinguishing Quantum States" kata). 21 | 3. Implementing a quantum operation described by a given matrix (similar to the "Multi-Qubit Gates" kata). 22 | 4. Implementing a marking oracle that matches a given classical function (similar to the "Marking Oracles" kata). 23 | 24 | ## Resources 25 | 26 | - [The Quantum Katas](https://quantum.microsoft.com/experience/quantum-katas) - a collection of tutorials and programming problems on quantum computing. 27 | - You can find more examples of programming problems and ways they were tested at 28 | https://github.com/microsoft/qsharp/tree/main/katas/content. 29 | - [Documentation on testing and debugging Q# code](https://learn.microsoft.com/azure/quantum/testing-debugging). 30 | - [Samples of testing Q# code](https://github.com/microsoft/qsharp/tree/main/samples/testing). 31 | 32 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/DebuggingQuantumCode/DeutschJozsaCode.ans: -------------------------------------------------------------------------------- 1 | // This programming assignment is focused on debugging Deutsch-Jozsa algorithm. 2 | // The code contains exactly 7 bugs. Find them all! 3 | 4 | // Phase oracle implementing a constant function f(x) = 0 5 | operation PhaseOracleZero (inputRegister : Qubit[]) : Unit { 6 | // Do nothing! 7 | } 8 | 9 | // Marking oracle implementing a balanced function f(x) = xₖ (the value of k-th bit) 10 | operation MarkingOracleKthBit (inputRegister : Qubit[], target : Qubit, k : Int) : Unit { 11 | Controlled X([inputRegister[k]], target); 12 | } 13 | 14 | operation ApplyMarkingOracleAsPhaseOracle ( 15 | markingOracle : ((Qubit[], Qubit) => Unit), 16 | inputRegister : Qubit[] 17 | ) : Unit { 18 | use target = Qubit(); 19 | // Put the target into the |-⟩ state 20 | X(target); 21 | H(target); 22 | // Apply the marking oracle; since the target is in the |-⟩ state, 23 | // this will apply a -1 factor to the states that satisfy the oracle condition 24 | markingOracle(inputRegister, target); 25 | H(target); 26 | X(target); 27 | } 28 | 29 | operation IsFunctionConstant (nQubits : Int, phaseOracle : (Qubit[] => Unit)) : Bool { 30 | mutable isConstant = true; 31 | use qubits = Qubit[nQubits]; 32 | // Apply the H gates, the oracle and the H gates again 33 | within { 34 | ApplyToEachA(H, qubits); 35 | } apply { 36 | phaseOracle(qubits); 37 | } 38 | // Measure all qubits 39 | let measurementResults = MResetEachZ(qubits); 40 | for m in measurementResults { 41 | if m == One { 42 | set isConstant = false; 43 | } 44 | } 45 | return isConstant; 46 | } 47 | 48 | function ConstantOrBalanced (value : Bool) : String { 49 | return value ? "constant" | "balanced"; 50 | } 51 | 52 | @EntryPoint() 53 | operation RunDeutschJozsaAlgorithm () : Unit { 54 | // for constant function 55 | let isZeroConstant = IsFunctionConstant(2, PhaseOracleZero); 56 | Message($"f(x) = 0 classified as {ConstantOrBalanced(isZeroConstant)}"); 57 | 58 | // for balanced function 59 | let markingOracleSecondBit = MarkingOracleKthBit(_, _, 1); 60 | let phaseOracleSecondBit = ApplyMarkingOracleAsPhaseOracle(markingOracleSecondBit, _); 61 | let isSecondBitConstant = IsFunctionConstant(2, phaseOracleSecondBit); 62 | Message($"f(x) = x₂ classified as {ConstantOrBalanced(isSecondBitConstant)}"); 63 | } 64 | -------------------------------------------------------------------------------- /SECURITY.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## Security 4 | 5 | Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). 6 | 7 | If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://docs.microsoft.com/en-us/previous-versions/tn-archive/cc751383(v=technet.10)), please report it to us as described below. 8 | 9 | ## Reporting Security Issues 10 | 11 | **Please do not report security vulnerabilities through public GitHub issues.** 12 | 13 | Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://msrc.microsoft.com/create-report). 14 | 15 | If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://www.microsoft.com/en-us/msrc/pgp-key-msrc). 16 | 17 | You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://www.microsoft.com/msrc). 18 | 19 | Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: 20 | 21 | * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) 22 | * Full paths of source file(s) related to the manifestation of the issue 23 | * The location of the affected source code (tag/branch/commit or direct URL) 24 | * Any special configuration required to reproduce the issue 25 | * Step-by-step instructions to reproduce the issue 26 | * Proof-of-concept or exploit code (if possible) 27 | * Impact of the issue, including how an attacker might exploit the issue 28 | 29 | This information will help us triage your report more quickly. 30 | 31 | If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://microsoft.com/msrc/bounty) page for more details about our active programs. 32 | 33 | ## Preferred Languages 34 | 35 | We prefer all communications to be in English. 36 | 37 | ## Policy 38 | 39 | Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://www.microsoft.com/en-us/msrc/cvd). 40 | 41 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Git ignore file for the Solid project 2 | 3 | # Build artifacts 4 | bin/ 5 | obj/ 6 | Documentation/Help/ 7 | packages/ 8 | src/simulation/Runtime/x64/ 9 | *.obj 10 | *.dll 11 | *.pdb 12 | *.exe 13 | *.chm 14 | *.html 15 | Tests/build 16 | 17 | # test outputs 18 | TestResults/ 19 | *.qxe 20 | 21 | # Random VS files 22 | *.suo 23 | *.vssscc 24 | *.vspscc 25 | UpgradeLog.htm 26 | .vs 27 | *.user 28 | 29 | # Random non-solution files 30 | *.user 31 | StyleCop.Cache 32 | *.sublime-workspace 33 | build_log.txt 34 | .DS_store 35 | 36 | # Q# code-behind files: 37 | *.g.cs 38 | 39 | ## Core latex/pdflatex auxiliary files: 40 | *.aux 41 | *.lof 42 | *.log 43 | *.lot 44 | *.fls 45 | *.out 46 | *.toc 47 | *.fmt 48 | *.fot 49 | *.cb 50 | *.cb2 51 | .*.lb 52 | 53 | ## Intermediate documents: 54 | *.dvi 55 | *.xdv 56 | *-converted-to.* 57 | # these rules might exclude image files for figures etc. 58 | # *.ps 59 | # *.eps 60 | 61 | ## Generated if empty string is given at "Please type another file name for output:" 62 | .pdf 63 | 64 | ## Bibliography auxiliary files (bibtex/biblatex/biber): 65 | *.bbl 66 | *.bcf 67 | *.blg 68 | *-blx.aux 69 | *-blx.bib 70 | *.run.xml 71 | 72 | ## Build tool auxiliary files: 73 | *.fdb_latexmk 74 | *.synctex 75 | *.synctex(busy) 76 | *.synctex.gz 77 | *.synctex.gz(busy) 78 | *.pdfsync 79 | 80 | ## Build tool directories for auxiliary files 81 | # latexrun 82 | latex.out/ 83 | 84 | ## Auxiliary and intermediate files from other packages: 85 | # algorithms 86 | *.alg 87 | *.loa 88 | 89 | # achemso 90 | acs-*.bib 91 | 92 | # amsthm 93 | *.thm 94 | 95 | # beamer 96 | *.nav 97 | *.pre 98 | *.snm 99 | *.vrb 100 | 101 | # changes 102 | *.soc 103 | 104 | # cprotect 105 | *.cpt 106 | 107 | # elsarticle (documentclass of Elsevier journals) 108 | *.spl 109 | 110 | # endnotes 111 | *.ent 112 | 113 | # fixme 114 | *.lox 115 | 116 | # feynmf/feynmp 117 | *.mf 118 | *.mp 119 | *.t[1-9] 120 | *.t[1-9][0-9] 121 | *.tfm 122 | 123 | #(r)(e)ledmac/(r)(e)ledpar 124 | *.end 125 | *.?end 126 | *.[1-9] 127 | *.[1-9][0-9] 128 | *.[1-9][0-9][0-9] 129 | *.[1-9]R 130 | *.[1-9][0-9]R 131 | *.[1-9][0-9][0-9]R 132 | *.eledsec[1-9] 133 | *.eledsec[1-9]R 134 | *.eledsec[1-9][0-9] 135 | *.eledsec[1-9][0-9]R 136 | *.eledsec[1-9][0-9][0-9] 137 | *.eledsec[1-9][0-9][0-9]R 138 | 139 | # glossaries 140 | *.acn 141 | *.acr 142 | *.glg 143 | *.glo 144 | *.gls 145 | *.glsdefs 146 | 147 | # gnuplottex 148 | *-gnuplottex-* 149 | 150 | # gregoriotex 151 | *.gaux 152 | *.gtex 153 | 154 | # htlatex 155 | *.4ct 156 | *.4tc 157 | *.idv 158 | *.lg 159 | *.trc 160 | *.xref 161 | 162 | # hyperref 163 | *.brf 164 | 165 | # knitr 166 | *-concordance.tex 167 | # TODO Comment the next line if you want to keep your tikz graphics files 168 | *.tikz 169 | *-tikzDictionary 170 | 171 | # listings 172 | *.lol 173 | 174 | # makeidx 175 | *.idx 176 | *.ilg 177 | *.ind 178 | *.ist 179 | 180 | # minitoc 181 | *.maf 182 | *.mlf 183 | *.mlt 184 | *.mtc[0-9]* 185 | *.slf[0-9]* 186 | *.slt[0-9]* 187 | *.stc[0-9]* 188 | 189 | # minted 190 | _minted* 191 | *.pyg 192 | 193 | # morewrites 194 | *.mw 195 | 196 | # nomencl 197 | *.nlg 198 | *.nlo 199 | *.nls 200 | 201 | # pax 202 | *.pax 203 | 204 | # pdfpcnotes 205 | *.pdfpc 206 | 207 | # sagetex 208 | *.sagetex.sage 209 | *.sagetex.py 210 | *.sagetex.scmd 211 | 212 | # scrwfile 213 | *.wrt 214 | 215 | # sympy 216 | *.sout 217 | *.sympy 218 | sympy-plots-for-*.tex/ 219 | 220 | # pdfcomment 221 | *.upa 222 | *.upb 223 | 224 | # pythontex 225 | *.pytxcode 226 | pythontex-files-*/ 227 | 228 | # thmtools 229 | *.loe 230 | 231 | # TikZ & PGF 232 | *.dpth 233 | *.md5 234 | *.auxlock 235 | 236 | # todonotes 237 | *.tdo 238 | 239 | # easy-todo 240 | *.lod 241 | 242 | # xmpincl 243 | *.xmpi 244 | 245 | # xindy 246 | *.xdy 247 | 248 | # xypic precompiled matrices 249 | *.xyc 250 | 251 | # endfloat 252 | *.ttt 253 | *.fff 254 | 255 | # Latexian 256 | TSWLatexianTemp* 257 | 258 | ## Editors: 259 | # WinEdt 260 | *.bak 261 | *.sav 262 | 263 | # Texpad 264 | .texpadtmp 265 | 266 | # Kile 267 | *.backup 268 | 269 | # KBibTeX 270 | *~[0-9]* 271 | 272 | # auto folder when using emacs and auctex 273 | ./auto/* 274 | *.el 275 | 276 | # expex forward references with \gathertags 277 | *-tags.tex 278 | 279 | # standalone packages 280 | *.sta 281 | 282 | # jupyter notebooks checkpoints: 283 | .ipynb_checkpoints 284 | 285 | # test results 286 | Check.ipynb 287 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | This is a demo of programming assignments developed using Q#, Azure Quantum Development Kit, and Azure Quantum that can be used to teach an "Introduction to Quantum Computing and Quantum Programming" course. 2 | 3 | > These assignments have been created and tested with Modern QDK, version 1.8.0. 4 | 5 | ## Table of contents 6 | 7 | - [Table of contents](#table-of-contents) 8 | - [List of programming assignments](#list-of-programming-assignments) 9 | - [Example syllabus](#example-syllabus) 10 | - [Use Azure Quantum in your course](#use-azure-quantum-in-your-course) 11 | - [Experience reports](#experience-reports) 12 | - [Trademarks](#trademarks) 13 | 14 | ## List of programming assignments 15 | 16 | This preview contains examples of the programming assignments included in the curriculum. 17 | 18 | * [Automatically graded assignments focused on solving quantum computing problems of varying complexity](./ProgrammingAssignmentSamples/AutogradedProblems). 19 | * [Assignments focused on debugging quantum programs](./ProgrammingAssignmentSamples/DebuggingQuantumCode). 20 | * [Assignments focused on resources estimation of quantum programs](./ProgrammingAssignmentSamples/ResourcesEstimation). 21 | * [Ideas of final projects and examples of final projects done by our past students](./FinalProjects). 22 | 23 | 24 | ## Example syllabus 25 | 26 | Here is the syllabus of the course taught at Northeastern University in 2020. 27 | 28 | **Course Structure** 29 | * One three-hour session per week (lecture + lab time combined); 14 weeks. 30 | * Weekly programming homework assignments during the first part of the course. 31 | * Final project during the second part of the course. 32 | 33 | **Course Outline** 34 | 35 | *Week 1.* Fundamentals, part 1. 36 | 37 | * Motivation: Why quantum computing? 38 | * Quick review: complex numbers, matrices and vectors, tensor product. 39 | * The qubit, superposition, Dirac notation, single-qubit quantum gates, entanglement. 40 | 41 | *Week 2.* Fundamentals, part 2. 42 | 43 | * Multi-qubit quantum gates, Dirac notation for gates representation. 44 | * Comparison of different notations: matrix, Dirac, circuit, Q# code. 45 | * Measurements: single-qubit, multi-qubit, partial measurement of multi-qubit system. 46 | * No-cloning theorem. 47 | 48 | *Week 3.* Simple algorithms. 49 | 50 | * Teleportation. 51 | * Superdense coding. 52 | * Quantum oracles (phase oracles). 53 | * Deutsch, Deutsch-Jozsa and Bernstein-Vazirani algorithms. 54 | 55 | *Week 4.* Reversible computing. 56 | 57 | * Reversible Boolean logic. 58 | * Reversible circuit synthesis: converting classical functions to quantum circuits, exercises. 59 | * Toffoli simulator. 60 | * Quantum oracles: marking oracles, converting marking oracles to phase oracles. 61 | * Example: building oracle for SAT problems. 62 | 63 | *Week 5.* Grover's search algorithm. 64 | 65 | * Search problem. 66 | * Unitary transformations used in Grover's search algorithm, their representation as reflections. 67 | * Grover's search algorithm, its visualization. 68 | * Practical aspects of using Grover's search algorithm. 69 | 70 | *Week 6.* Quantum Fourier transform. 71 | 72 | * Definition and circuit implementation of quantum Fourier transform. 73 | * Examples of QFT effect on various states. 74 | 75 | *Week 7.* Quantum phase estimation. 76 | 77 | * Linear algebra review: eigenvalues and eigenvectors. 78 | * Eigenvalues and eigenphases of quantum operations: properties and examples. 79 | * Single-bit phase estimation, measuring an operator. 80 | * Quantum phase estimation. 81 | * Application: quantum counting. 82 | 83 | *Week 8.* Integer factoring (Shor's algorithm). 84 | 85 | * RSA review. 86 | * Order finding problem. 87 | * Integer factoring (Shor's algorithm). 88 | 89 | *Week 9.* Error correction. 90 | 91 | * Problem description, comparison of classical and quantum information, inherent challenges of error correcting quantum information. 92 | * Joint measurements. 93 | * Simple error correction codes: bit-flip, sign-flip, Shor's code. 94 | * Fault-tolerant quantum computation. 95 | 96 | *Week 10.* Applications overview. 97 | 98 | * True random number generation. 99 | * Quantum cryptography, quantm key distribution, example: BB84 protocol. 100 | * Quantum machine learning, example: quantum perceptron. 101 | * Quantum simulation. 102 | 103 | *Week 11.* Building a full-stack quantum computer. 104 | 105 | * Software and hardware stack necessary to build a viable quantum computing system. 106 | 107 | The last week(s) are used for students' presentations of their final projects. 108 | 109 | 110 | ## Use Azure Quantum in your course 111 | 112 | Microsoft offers several credits programs to support using Azure Quantum in the classroom. 113 | 114 | * Every student can [use up to $500 in credits to experiment with each of the participating quantum hardware partners](https://devblogs.microsoft.com/qsharp/explore-quantum-hardware-for-free-with-azure-quantum/). 115 | * Additionally, you can [apply for up to $10,000 in credits](https://aka.ms/aq/credits) to share them with your students. 116 | 117 | 118 | ## Experience reports 119 | 120 | The first version of the curriculum relying on this kind of assignments was piloted in a University of Washington course taught by Microsoft Quantum team in 2019. You can read about this experience in the paper ["Teaching Quantum Computing through a Practical Software-driven Approach: Experience Report" by Mariia Mykhailova, Krysta M. Svore](https://arxiv.org/abs/2010.07729). 121 | 122 | Later, similar programming assignments have been used in Northeastern University courses in 2020-2024. You can read about this experience in the paper ["Teaching Quantum Computing using Microsoft Quantum Development Kit and Azure Quantum" by Mariia Mykhailova](https://arxiv.org/abs/2311.12960). 123 | 124 | We shared our curriculum with multiple university partners who used the materials to teach their own versions of this course. You can read more about the experience of one of our partners, University of Montevideo, in the paper ["Quantum Computing for Undergraduate Engineering Students: Report of an Experience" by Laura Gatti, Rafael Sotelo](http://ingenieria.um.edu.uy/pdf/QCE21_Workforce_UM_LG_RS_final.pdf). 125 | 126 | 127 | ## Trademarks 128 | 129 | This project may contain trademarks or logos for projects, products, or services. Authorized use of Microsoft 130 | trademarks or logos is subject to and must follow 131 | [Microsoft's Trademark & Brand Guidelines](https://www.microsoft.com/en-us/legal/intellectualproperty/trademarks/usage/general). 132 | Use of Microsoft trademarks or logos in modified versions of this project must not cause confusion or imply Microsoft sponsorship. 133 | Any use of third-party trademarks or logos are subject to those third-party's policies. 134 | -------------------------------------------------------------------------------- /FinalProjects/README.md: -------------------------------------------------------------------------------- 1 | # Final Projects: Approach and Ideas 2 | 3 | The curriculum relies on final projects in lieu of final written exams. 4 | Final projects are a great way to make sure the students have mastered the skills necessary to complete an end-to-end quantum software project. 5 | They are the best approximation of real quantum software engineering work, since they go beyond solving small well-defined tasks (like the ones offered in the homework assignments) to larger open-ended problems. 6 | 7 | ## Final project 8 | 9 | Choose a problem/algorithm not covered in the class (and in the existing Q# code base), learn, implement, test and analyze. 10 | The deliverables of a final project include: 11 | 12 | * Written summary (30%) – 2-3 pages: problem statement, importance, technical results (math solution, implementation subtleties, test results, analysis). 13 | * Code implementation (50%). 14 | * Class presentation (20%) – teach your classmates the topic you’ve learned (in 20 minutes or less). 15 | 16 | Approximate timeline: 17 | 18 | * Topic selection: by mid-term. 19 | * Working on the project: second half of the term in parallel with the lectures (fewer or no weekly programming assignments at this point). 20 | * Project submission (the implementation and the written summary): a week or two before the end of the term. 21 | * Final presentations to the class: last 2-3 lectures. 22 | 23 | 24 | ## Examples of future project ideas 25 | 26 | *The projects offered in the past that have been completed and contributed to open source projects don't necessarily make for great projects going forward, 27 | since we want the students to perform independent work rather than explore a project done previously. 28 | At the same time students (especially undergraduate) can have trouble coming up with a project idea and especially estimating its difficulty. 29 | We recommend to offer a list of project ideas to show the expected level of complexity, and to verify that the student correctly estimates the difficulty of their chosen project early.* 30 | 31 | Here are some ideas of final projects. 32 | 33 | * Implement an algorithm and explore its behavior on a simulator vs on real hardware. 34 | This include a general scalable implementation, resources estimation, choosing a small instance that can be simulated and executed on NISQ hardware, possibly tweaking the implementation to reduce circuit depth and complexity, and results analysis. 35 | Get started: ["Quantum programming with Q# and running on hardware with Azure Quantum" by Mariia Mykhailova](https://www.youtube.com/watch?v=c9Df90CVHkc). 36 | * Solve a specific classical problem (for example, a cryptarithm or a Sudoku puzzle) using Grover's search algorithm. 37 | Learn reversible computing and practicality of Grover's search, and optimize the implementation. 38 | Get started: ["Analyzing a Sudoku solver using resources estimation" by Mariia Mykhailova](https://devblogs.microsoft.com/qsharp/analyzing-sudoku-solver-using-resources-estimation/). 39 | * Implement an algorithm following a specific paper. 40 | Papers often either omit implementation details or implement only a special case of the problem (as a hardcoded quantum circuit) rather than a general case. Exploring the nuances of a general-purpose implementation can be an interesting challenge for the student. 41 | * Optimizing code to run on a quantum simulator. 42 | Explore and exploit implementation details of a simulator (for example, tweak circuit width to reduce the memory required) 43 | and explore emulation (efficient implementation of unitaries that are permutations). 44 | Get started: ["Decorating the Christmas Tree Using Grover's Search, part 3: Optimizing the Simulation" by Mariia Mykhailova](https://github.com/tcNickolas/MiscQSharp/tree/master/DecoratingTheTree2019-Optimize#decorating-the-christmas-tree-using-grovers-search). 45 | * Error correction. 46 | Explore a lower-level component of quantum software stack. 47 | * Implement a custom simulator that introduces certain types of errors and use it to demonstrate an error correcting code. 48 | See an example of such custom simulator [here](https://github.com/microsoft/Quantum/tree/main/samples/runtime/simulator-with-overrides). 49 | * Use [noise simulator](https://docs.microsoft.com/en-us/azure/quantum/user-guide/machines/noise-simulator) to explore different types of errors and use it to demonstrate an error correcting code. 50 | * Unitary synthesis. 51 | Explore a lower-level component of quantum software stack. 52 | * How to decompose 1-qubit and 2-qubit unitaries into sequences of rotations and rotations/CNOT gates (Pauli or Cartan decomposition and Krauss-Cirac decomposition, respectively). 53 | Get started: ["Explorations in Quantum Computing" by Williams, chapter 2](http://iontrap.umd.edu/wp-content/uploads/2016/01/Quantum-Gates-c2.pdf). 54 | * How to implement an arbitrary unitary. 55 | Get started: ["Decomposition of unitary matrix into quantum gates" by Dmytro Fedoriaka](https://www.researchgate.net/publication/334615236_Decomposition_of_unitary_matrix_into_quantum_gates) 56 | 57 | 58 | ## Examples of past projects 59 | 60 | Here is a list of projects done by the students in our courses in the past and contributed to our open-source repositories. 61 | The contribution included only the code/tutorial part of the projects; the final projects themselves also included a brief writeup describing the algorithm and the implementation, and a presentation to the class. 62 | *Contributing the projects to open source was not a hard requirement of the projects, but rather a voluntary follow-up activity.* 63 | 64 | * Entanglement games (a set of three katas: [CHSHGame](https://github.com/microsoft/QuantumKatas/tree/main/CHSHGame), [GHZGame](https://github.com/microsoft/QuantumKatas/tree/main/GHZGame), [MagicSquareGame](https://github.com/microsoft/QuantumKatas/tree/main/MagicSquareGame)) (3 students) 65 | * [BB84 key distribution protocol](https://github.com/microsoft/QuantumKatas/tree/main/KeyDistribution_BB84) (2 students) 66 | * [Solving graph coloring problems using Grover's search](https://github.com/microsoft/QuantumKatas/tree/main/GraphColoring) (3 students) 67 | * [Quantum arithmetic](https://github.com/microsoft/QuantumKatas/pull/84) (1 student) (not merged, superseded by [RippleCarryAdder kata](https://github.com/microsoft/QuantumKatas/tree/main/RippleCarryAdder)). 68 | This project compared several implementations of quantum arithmetic and explored specialized simulators (Toffoli simulator). 69 | * [Quantum Fourier transform (kata)](https://github.com/microsoft/QuantumKatas/pull/88) (2 students) 70 | * [Hidden shift algorithm (kata)](https://github.com/microsoft/QuantumKatas/pull/83) (3 students) 71 | * [Simon's algorithm (tutorial)](https://github.com/microsoft/QuantumKatas/pull/327) (1 student). 72 | This project explored combining quantum processing with classical (quantum coprocessor model), 73 | and to experiment with classical language interoperability supported by Q# (in this case Python interop). 74 | 75 | 76 | > Note that most of the katas have been updated compared to the original project, often by the maintainer or by other contributors rather by the original authors. You can see the [pull requests that created each kata](https://github.com/Microsoft/QuantumKatas/pulls?utf8=%E2%9C%93&q=is%3Apr+created%3A2019-03-19..2019-03-27) for the original versions that went into the projects. 77 | -------------------------------------------------------------------------------- /ProgrammingAssignmentSamples/AutogradedProblems/src/Test.qs: -------------------------------------------------------------------------------- 1 | // This file contains parts of the testing harness for the tasks that need it. 2 | // You should not modify anything in this file. 3 | 4 | import Std.Arrays.Zipped; 5 | import Std.Convert.*; 6 | import Std.Diagnostics.*; 7 | import Std.Math.*; 8 | import Std.Random.*; 9 | import Measurement.Task2; 10 | import MarkingOracle.Task4; 11 | 12 | //////////////////////////////////////////////////////////////////////////// 13 | 14 | // Helper operation that prepares the W state, starting from the |0⟩ state. 15 | operation WStatePrep(qs : Qubit[]) : Unit is Adj + Ctl { 16 | let N = Length(qs); 17 | 18 | if N == 1 { 19 | // base case of recursion: |1⟩ 20 | X(qs[0]); 21 | } else { 22 | // |W_N⟩ = |0⟩|W_(N-1)⟩ + |1⟩|0...0⟩ 23 | // do a rotation on the first qubit to split it into |0⟩ and |1⟩ with proper weights 24 | // |0⟩ -> sqrt((N-1)/N) |0⟩ + 1/sqrt(N) |1⟩ 25 | let theta = ArcSin(1.0 / Sqrt(IntAsDouble(N))); 26 | Ry(2.0 * theta, qs[0]); 27 | 28 | // do a zero-controlled W-state generation for qubits 1..N-1 29 | X(qs[0]); 30 | Controlled WStatePrep(qs[0..0], qs[1..N - 1]); 31 | X(qs[0]); 32 | } 33 | } 34 | 35 | 36 | // Helper operation that either leaves the qubits in the |0⟩ state or prepares W state on them. 37 | operation StatePrep_AllZerosOrWState( 38 | qs : Qubit[], 39 | state : Int 40 | ) : Unit is Adj { 41 | if state == 1 { 42 | // Prepare W state 43 | WStatePrep(qs); 44 | } 45 | } 46 | 47 | 48 | // Framework operation that takes a list of orthogonal quantum states and the code that is supposed to distinguish them 49 | // and checks that this code performs the task correctly. 50 | operation DistinguishStates_MultiQubit( 51 | nQubits : Int, 52 | nStates : Int, 53 | statePrep : (Qubit[], Int) => Unit is Adj, 54 | testImpl : Qubit[] => Int, 55 | stateNames : String[] 56 | ) : Bool { 57 | 58 | let nTotal = 100; 59 | // misclassifications will store the number of times state i has been classified as state j (dimension nStates^2) 60 | mutable misclassifications = [0, size = nStates * nStates]; 61 | // unknownClassifications will store the number of times state i has been classified as some invalid state (index < 0 or >= nStates) 62 | mutable unknownClassifications = [0, size = nStates]; 63 | 64 | use qs = Qubit[nQubits]; 65 | for _ in 1 .. nTotal { 66 | // get a random integer to define the state of the qubits 67 | let state = DrawRandomInt(0, nStates - 1); 68 | 69 | // do state prep: convert |0...0⟩ to outcome with return equal to state 70 | statePrep(qs, state); 71 | 72 | // get the solution's answer and verify that it's a match, if not, increase the exact mismatch count 73 | let ans = testImpl(qs); 74 | if ans >= 0 and ans < nStates { 75 | // classification result is a valid state index - check if is it correct 76 | if ans != state { 77 | set misclassifications w/= ((state * nStates) + ans) <- (misclassifications[(state * nStates) + ans] + 1); 78 | } 79 | } 80 | else { 81 | // classification result is an invalid state index - file it separately 82 | set unknownClassifications w/= state <- (unknownClassifications[state] + 1); 83 | } 84 | 85 | // we're not checking the state of the qubit after the operation 86 | ResetAll(qs); 87 | } 88 | 89 | mutable totalMisclassifications = 0; 90 | for i in 0 .. nStates - 1 { 91 | for j in 0 .. nStates - 1 { 92 | if misclassifications[(i * nStates) + j] != 0 { 93 | set totalMisclassifications += misclassifications[i * nStates + j]; 94 | Message($"Misclassified {stateNames[i]} as {stateNames[j]} in {misclassifications[(i * nStates) + j]} test runs."); 95 | } 96 | } 97 | if unknownClassifications[i] != 0 { 98 | set totalMisclassifications += unknownClassifications[i]; 99 | Message($"Misclassified {stateNames[i]} as Unknown State in {unknownClassifications[i]} test runs."); 100 | } 101 | } 102 | totalMisclassifications == 0 103 | } 104 | 105 | 106 | // The test logic for task 2 (distinguishing orthogonal states). 107 | operation Test2() : Bool { 108 | for n in 2 .. 6 { 109 | let isCorrect = DistinguishStates_MultiQubit( 110 | n, 2, 111 | StatePrep_AllZerosOrWState, 112 | Task2, 113 | ["|0...0⟩", "|W⟩"]); 114 | 115 | if not isCorrect { 116 | Message($"Test failed for n = {n}."); 117 | return false; 118 | } 119 | } 120 | true 121 | } 122 | 123 | //////////////////////////////////////////////////////////////////////////// 124 | 125 | // Helper function to convert a boolean array to its ket state representation 126 | function BoolArrayAsKetState (bits : Bool[]) : String { 127 | mutable stateName = "|"; 128 | for i in 0 .. Length(bits) - 1 { 129 | set stateName += (bits[i] ? "1" | "0"); 130 | } 131 | 132 | return stateName + "⟩"; 133 | } 134 | 135 | 136 | // Helper operation that, given a marking oracle acting on N inputs, and a classical function acting on N bits, 137 | // checks whether the oracle effect matches that of the function on every classical input. 138 | operation CheckOracleImplementsFunction ( 139 | N : Int, 140 | oracle : (Qubit[], Qubit) => Unit, 141 | f : Bool[] -> Bool 142 | ) : Bool { 143 | let size = 1 <<< N; 144 | use (input, target) = (Qubit[N], Qubit()); 145 | for k in 0 .. size - 1 { 146 | // Prepare k-th bit vector 147 | let binaryLE = IntAsBoolArray(k, N); 148 | 149 | // "binary" is little-endian notation, so the second vector tried has qubit 0 in state 1 and the rest in state 0 150 | ApplyPauliFromBitString(PauliX, true, binaryLE, input); 151 | 152 | // Apply the operation 153 | oracle(input, target); 154 | 155 | // Calculate the expected classical result 156 | let val = f(binaryLE); 157 | 158 | // Apply operations that will revert the qubits to the 0 state if the oracle acted correctly. 159 | if val { 160 | X(target); 161 | } 162 | ApplyPauliFromBitString(PauliX, true, binaryLE, input); 163 | 164 | if not CheckAllZero(input + [target]) { 165 | Message($"Unexpected result on input {BoolArrayAsKetState(binaryLE)}."); 166 | if not CheckAllZero(input) { 167 | Message("The state of the input qubits changed, or they ended up entangled with the target qubit."); 168 | Message("The state of the system after oracle application:"); 169 | DumpMachine(); 170 | } else { 171 | Message($"Expected result `{val}`, got `{not val}`."); 172 | } 173 | ResetAll(input + [target]); 174 | return false; 175 | } 176 | } 177 | return true; 178 | } 179 | 180 | 181 | // Classical function that has to be implemented by the oracle in task 4. 182 | function F_MatchesPattern(args : Bool[], r : Bool[]) : Bool { 183 | for i in 0 .. Length(args) - 1 { 184 | if args[i] != r[i] { 185 | return false; 186 | } 187 | } 188 | return true; 189 | } 190 | 191 | 192 | // The test logic for task 4 (implementing marking oracle for a function). 193 | operation Test4() : Bool { 194 | for n in 1 .. 3 { 195 | for k in 0 .. 2^n - 1 { 196 | let pattern = IntAsBoolArray(k, n); 197 | 198 | let isCorrect = CheckOracleImplementsFunction(n, Task4(_, _, pattern), F_MatchesPattern(_, pattern)); 199 | 200 | if not isCorrect { 201 | return false; 202 | } 203 | } 204 | } 205 | true 206 | } 207 | --------------------------------------------------------------------------------