qsharp-lang 0.1.0-dev.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/LICENSE.txt +21 -0
  2. package/README.md +74 -0
  3. package/dist/browser.d.ts +26 -0
  4. package/dist/browser.js +156 -0
  5. package/dist/cancellation.d.ts +10 -0
  6. package/dist/cancellation.js +31 -0
  7. package/dist/compiler/common.d.ts +31 -0
  8. package/dist/compiler/common.js +47 -0
  9. package/dist/compiler/compiler.d.ts +28 -0
  10. package/dist/compiler/compiler.js +62 -0
  11. package/dist/compiler/events.d.ts +54 -0
  12. package/dist/compiler/events.js +92 -0
  13. package/dist/compiler/worker-browser.d.ts +1 -0
  14. package/dist/compiler/worker-browser.js +43 -0
  15. package/dist/compiler/worker-node.d.ts +1 -0
  16. package/dist/compiler/worker-node.js +41 -0
  17. package/dist/compiler/worker-proxy.d.ts +7 -0
  18. package/dist/compiler/worker-proxy.js +16 -0
  19. package/dist/debug-service/debug-service.d.ts +35 -0
  20. package/dist/debug-service/debug-service.js +136 -0
  21. package/dist/debug-service/worker-browser.d.ts +1 -0
  22. package/dist/debug-service/worker-browser.js +32 -0
  23. package/dist/debug-service/worker-node.d.ts +1 -0
  24. package/dist/debug-service/worker-node.js +30 -0
  25. package/dist/debug-service/worker-proxy.d.ts +7 -0
  26. package/dist/debug-service/worker-proxy.js +22 -0
  27. package/dist/katas-content.generated.d.ts +61 -0
  28. package/dist/katas-content.generated.js +2499 -0
  29. package/dist/katas.d.ts +55 -0
  30. package/dist/katas.js +16 -0
  31. package/dist/language-service/language-service.d.ts +48 -0
  32. package/dist/language-service/language-service.js +85 -0
  33. package/dist/language-service/worker-browser.d.ts +1 -0
  34. package/dist/language-service/worker-browser.js +32 -0
  35. package/dist/language-service/worker-node.d.ts +1 -0
  36. package/dist/language-service/worker-node.js +30 -0
  37. package/dist/language-service/worker-proxy.d.ts +6 -0
  38. package/dist/language-service/worker-proxy.js +20 -0
  39. package/dist/log.d.ts +33 -0
  40. package/dist/log.js +92 -0
  41. package/dist/main.d.ts +11 -0
  42. package/dist/main.js +82 -0
  43. package/dist/samples.generated.d.ts +6 -0
  44. package/dist/samples.generated.js +62 -0
  45. package/dist/vsdiagnostic.d.ts +27 -0
  46. package/dist/vsdiagnostic.js +117 -0
  47. package/dist/worker-proxy.d.ts +95 -0
  48. package/dist/worker-proxy.js +226 -0
  49. package/lib/node/qsc_wasm.cjs +1010 -0
  50. package/lib/node/qsc_wasm.d.cts +266 -0
  51. package/lib/node/qsc_wasm_bg.wasm +0 -0
  52. package/lib/web/qsc_wasm.d.ts +328 -0
  53. package/lib/web/qsc_wasm.js +1026 -0
  54. package/lib/web/qsc_wasm_bg.wasm +0 -0
  55. package/package.json +35 -0
@@ -0,0 +1,62 @@
1
+ export default [
2
+ {
3
+ "title": "Minimal",
4
+ "shots": 100,
5
+ "code": "/// # Sample\n/// Getting started\n///\n/// # Description\n/// This is a minimal Q# program that can be used to start writing Q# code.\nnamespace MyQuantumProgram {\n open Microsoft.Quantum.Intrinsic;\n\n @EntryPoint()\n operation Main() : Result[] {\n // TODO: Write your Q# code here.\n return [];\n }\n}\n"
6
+ },
7
+ {
8
+ "title": "Superposition",
9
+ "shots": 100,
10
+ "code": "/// # Sample\n/// Superposition\n///\n/// # Description\n/// This Q# program sets a qubit in a superposition of the computational basis\n/// states |0〉 and |1〉 by applying a Hadamard transformation.\nnamespace Sample {\n\n @EntryPoint()\n operation Superposition() : Result {\n // Qubits are only accesible for the duration of the scope where they\n // are allocated and are automatically released at the end of the scope.\n use qubit = Qubit();\n\n // Set the qubit in superposition by applying a Hadamard transformation.\n H(qubit);\n\n // Measure the qubit. There is a 50% probability of measuring either \n // `Zero` or `One`.\n let result = M(qubit);\n\n // Reset the qubit so it can be safely released.\n Reset(qubit);\n return result;\n }\n}"
11
+ },
12
+ {
13
+ "title": "Entanglement",
14
+ "shots": 100,
15
+ "code": "/// # Sample\n/// Entanglement\n///\n/// # Description\n/// Qubits are said to be entangled when the state of each one of them cannot be\n/// described independently from the state of the others.\n///\n/// This Q# program entangles two qubits.\nnamespace Sample {\n open Microsoft.Quantum.Diagnostics;\n\n @EntryPoint()\n operation EntangleQubits() : (Result, Result) {\n // Allocate the two qubits that will be entangled.\n use (q1, q2) = (Qubit(), Qubit());\n\n // Set the first qubit in superposition by calling the `H` operation, \n // which applies a Hadamard transformation to the qubit.\n // Then, entangle the two qubits using the `CNOT` operation.\n H(q1);\n CNOT(q1, q2);\n\n // Show the entangled state using the `DumpMachine` function.\n DumpMachine();\n\n // Measurements of entangled qubits are always correlated.\n let (m1, m2) = (M(q1), M(q2));\n Reset(q1);\n Reset(q2);\n return (m1, m2);\n }\n}"
16
+ },
17
+ {
18
+ "title": "Bell States",
19
+ "shots": 100,
20
+ "code": "/// # Sample\n/// Bell States\n///\n/// # Description\n/// Bell states or EPR pairs are specific quantum states of two qubits\n/// that represent the simplest (and maximal) examples of quantum entanglement.\n///\n/// This Q# program implements the four different Bell states.\nnamespace Sample {\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Measurement;\n\n @EntryPoint()\n operation BellStates() : (Result, Result)[] {\n // Allocate the two qubits that will be used to create a Bell state.\n use register = Qubit[2];\n\n // This array contains a label and a preparation operation for each one\n // of the four Bell states.\n let bellStateTuples = [\n (\"|Φ+〉\", PreparePhiPlus),\n (\"|Φ-〉\", PreparePhiMinus),\n (\"|Ψ+〉\", PreparePsiPlus),\n (\"|Ψ-〉\", PreparePsiMinus)\n ];\n\n // Prepare all Bell states, show them using the `DumpMachine` operation\n // and measure the Bell state qubits.\n mutable measurements = [];\n for (label, prepare) in bellStateTuples {\n prepare(register);\n Message($\"Bell state {label}:\");\n DumpMachine();\n set measurements += [(M(register[0]), M(register[1]))];\n ResetAll(register);\n }\n return measurements;\n }\n\n operation PreparePhiPlus(register : Qubit[]) : Unit {\n ResetAll(register); // |00〉\n H(register[0]); // |+0〉\n CNOT(register[0], register[1]); // 1/sqrt(2)(|00〉 + |11〉)\n }\n\n operation PreparePhiMinus(register : Qubit[]) : Unit {\n ResetAll(register); // |00〉\n H(register[0]); // |+0〉\n Z(register[0]); // |-0〉\n CNOT(register[0], register[1]); // 1/sqrt(2)(|00〉 - |11〉)\n }\n\n operation PreparePsiPlus(register : Qubit[]) : Unit {\n ResetAll(register); // |00〉\n H(register[0]); // |+0〉\n X(register[1]); // |+1〉\n CNOT(register[0], register[1]); // 1/sqrt(2)(|01〉 + |10〉)\n }\n\n operation PreparePsiMinus(register : Qubit[]) : Unit {\n ResetAll(register); // |00〉\n H(register[0]); // |+0〉\n Z(register[0]); // |-0〉\n X(register[1]); // |-1〉\n CNOT(register[0], register[1]); // 1/sqrt(2)(|01〉 - |10〉)\n }\n}\n"
21
+ },
22
+ {
23
+ "title": "Teleportation",
24
+ "shots": 1,
25
+ "code": "/// # Sample\n/// Quantum Teleportation\n///\n/// # Description\n/// Quantum teleportation provides a way of moving a quantum state from one\n/// location to another without having to move physical particle(s) along with\n/// it. This is done with the help of previously shared quantum entanglement\n/// between the sending and the receiving locations, and classical\n/// communication.\n///\n/// This Q# program implements quantum teleportation.\nnamespace Sample {\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Intrinsic;\n open Microsoft.Quantum.Measurement;\n\n @EntryPoint()\n operation Main () : Result[] {\n // Allocate the message and target qubits.\n use (message, target) = (Qubit(), Qubit());\n\n // Use the `Teleport` operation to send different quantum states.\n let stateInitializerBasisTuples = [\n (\"|0〉\", I, PauliZ),\n (\"|1〉\", X, PauliZ),\n (\"|+〉\", SetToPlus, PauliX),\n (\"|-〉\", SetToMinus, PauliX)\n ];\n\n mutable results = [];\n for (state, initializer, basis) in stateInitializerBasisTuples {\n // Initialize the message and show its state using the `DumpMachine`\n // function.\n initializer(message);\n Message($\"Teleporting state {state}\");\n DumpMachine();\n\n // Teleport the message and show the quantum state after\n // teleportation.\n Teleport(message, target);\n Message($\"Received state {state}\");\n DumpMachine();\n\n // Measure target in the corresponding basis and reset the qubits to\n // continue teleporting more messages.\n let result = Measure([basis], [target]);\n set results += [result];\n ResetAll([message, target]);\n }\n\n return results;\n }\n\n /// # Summary\n /// Sends the state of one qubit to a target qubit by using teleportation.\n ///\n /// Notice that after calling Teleport, the state of `message` is collapsed.\n ///\n /// # Input\n /// ## message\n /// A qubit whose state we wish to send.\n /// ## target\n /// A qubit initially in the |0〉 state that we want to send\n /// the state of message to.\n operation Teleport(message : Qubit, target : Qubit) : Unit {\n // Allocate an auxiliary qubit.\n use auxiliary = Qubit();\n\n // Create some entanglement that we can use to send our message.\n H(auxiliary);\n CNOT(auxiliary, target);\n\n // Encode the message into the entangled pair.\n CNOT(message, auxiliary);\n H(message);\n\n // Measure the qubits to extract the classical data we need to decode\n // the message by applying the corrections on the target qubit\n // accordingly.\n if M(message) == One {\n Z(target);\n }\n if M(auxiliary) == One {\n X(target);\n }\n\n // Reset auxiliary qubit before releasing.\n Reset(auxiliary);\n }\n\n /// # Summary\n /// Sets a qubit in state |0⟩ to |+⟩.\n operation SetToPlus(q: Qubit) : Unit is Adj + Ctl {\n H(q);\n }\n\n /// # Summary\n /// Sets a qubit in state |0⟩ to |−⟩.\n operation SetToMinus(q: Qubit) : Unit is Adj + Ctl {\n X(q);\n H(q);\n }\n}\n"
26
+ },
27
+ {
28
+ "title": "Random Bit",
29
+ "shots": 100,
30
+ "code": "/// # Sample\n/// Random Bit\n///\n/// # Description\n/// This Q# program generates a random bit by setting a qubit in a superposition\n/// of the computational basis states |0〉 and |1〉, and returning the measurement\n/// result.\nnamespace Sample {\n\n @EntryPoint()\n operation RandomBit() : Result {\n // Qubits are only accesible for the duration of the scope where they\n // are allocated and are automatically released at the end of the scope.\n use qubit = Qubit();\n\n // Set the qubit in superposition by applying a Hadamard transformation.\n H(qubit);\n\n // Measure the qubit. There is a 50% probability of measuring either \n // `Zero` or `One`.\n let result = M(qubit);\n\n // Reset the qubit so it can be safely released.\n Reset(qubit);\n return result;\n }\n}\n"
31
+ },
32
+ {
33
+ "title": "Random Number Generator",
34
+ "shots": 1000,
35
+ "code": "/// # Sample\n/// Quantum Random Number Generator\n///\n/// # Description\n/// This program implements a quantum ranndom number generator by setting qubits\n/// in superposition and then using the measurement results as random bits.\nnamespace Sample {\n open Microsoft.Quantum.Convert;\n open Microsoft.Quantum.Intrinsic;\n open Microsoft.Quantum.Math;\n\n @EntryPoint()\n operation Main() : Int {\n let max = 100;\n Message($\"Sampling a random number between 0 and {max}: \");\n\n // Generate random number in the 0..max range.\n return GenerateRandomNumberInRange(max);\n }\n\n /// # Summary\n /// Generates a random number between 0 and `max`.\n operation GenerateRandomNumberInRange(max : Int) : Int {\n // Determine the number of bits needed to represent `max` and store it\n // in the `nBits` variable. Then generate `nBits` random bits which will\n // represent the generated random number.\n mutable bits = [];\n let nBits = BitSizeI(max);\n for idxBit in 1..nBits {\n set bits += [GenerateRandomBit()];\n }\n let sample = ResultArrayAsInt(bits);\n\n // Return random number if it is within the requested range.\n // Generate it again if it is outside the range.\n return sample > max ? GenerateRandomNumberInRange(max) | sample;\n }\n\n /// # Summary\n /// Generates a random bit.\n operation GenerateRandomBit() : Result {\n // Allocate a qubit.\n use q = Qubit();\n\n // Set the qubit into superposition of 0 and 1 using the Hadamard \n // operation `H`.\n H(q);\n\n // At this point the qubit `q` has 50% chance of being measured in the\n // |0〉 state and 50% chance of being measured in the |1〉 state.\n // Measure the qubit value using the `M` operation, and store the\n // measurement value in the `result` variable.\n let result = M(q);\n\n // Reset qubit to the |0〉 state.\n // Qubits must be in the |0〉 state by the time they are released.\n Reset(q);\n\n // Return the result of the measurement.\n return result;\n\n // Note that Qubit `q` is automatically released at the end of the block.\n }\n}\n"
36
+ },
37
+ {
38
+ "title": "Deutsch-Jozsa",
39
+ "shots": 1,
40
+ "code": "/// # Sample\n/// Deutsch–Jozsa algorithm\n///\n/// # Description\n/// Deutsch–Jozsa is a quantum algorithm that determines whether a given Boolean\n/// function 𝑓 is constant (0 on all inputs or 1 on all inputs) or balanced\n/// (1 for exactly half of the input domain and 0 for the other half).\n///\n/// This Q# program implements the Deutsch–Jozsa algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Canon;\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Measurement;\n\n @EntryPoint()\n operation Main() : (String, Bool)[] {\n // A Boolean function is a function that maps bits trings to a bit:\n // 𝑓 : {0, 1}^n → {0, 1}.\n\n // We say that 𝑓 is constant if 𝑓(𝑥⃗) = 𝑓(𝑦⃗) for all bitstrings 𝑥⃗ and\n // 𝑦⃗, and that 𝑓 is balanced if 𝑓 evaluates to true for exactly half of\n // its inputs.\n\n // If we are given a function 𝑓 as a quantum operation 𝑈 |𝑥〉|𝑦〉 =\n // |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉, and are promised that 𝑓 is either constant or is\n // balanced, then the Deutsch–Jozsa algorithm decides between these\n // cases with a single application of 𝑈.\n\n // Here, we demonstrate the use of the Deutsch-Jozsa algorithm by\n // determining the type (constant or balanced) of various functions.\n let nameFunctionTypeTuples = [\n (\"SimpleConstantBoolF\", SimpleConstantBoolF, true),\n (\"SimpleBalancedBoolF\", SimpleBalancedBoolF, false),\n (\"ConstantBoolF\", ConstantBoolF, true),\n (\"BalancedBoolF\", BalancedBoolF, false)\n ];\n\n mutable results = [];\n for (name, fn, shouldBeConstant) in nameFunctionTypeTuples {\n let isConstant = DeutschJozsa(fn, 5);\n if (isConstant != shouldBeConstant) {\n let shouldBeConstantStr = shouldBeConstant ?\n \"constant\" | \n \"balanced\";\n fail $\"{name} should be detected as {shouldBeConstantStr}\";\n }\n\n let isConstantStr = isConstant ? \"constant\" | \"balanced\";\n Message($\"{name} is {isConstantStr}\");\n set results += [(name, isConstant)];\n }\n\n return results;\n }\n\n /// # Summary\n /// This operation implements the DeutschJozsa algorithm.\n /// It returns the Boolean value `true` if the function is constant and\n /// `false` if it is not.\n /// It is assumed that the function is either constant or balanced.\n ///\n /// # Input\n /// ## Uf\n /// A quantum operation that implements |𝑥〉|𝑦〉 ↦ |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉, where 𝑓 is a\n /// Boolean function, 𝑥 is an 𝑛 bit register and 𝑦 is a single qubit.\n /// ## n\n /// The number of bits in the input register |𝑥〉.\n ///\n /// # Output\n /// A boolean value `true` that indicates that the function is constant and\n /// `false` that indicates that the function is balanced.\n ///\n /// # See Also\n /// - For details see Section 1.4.3 of Nielsen & Chuang.\n ///\n /// # References\n /// - [ *Michael A. Nielsen , Isaac L. Chuang*,\n /// Quantum Computation and Quantum Information ]\n /// (http://doi.org/10.1017/CBO9780511976667)\n operation DeutschJozsa(Uf : ((Qubit[], Qubit) => Unit), n : Int) : Bool {\n // We allocate n + 1 clean qubits. Note that the function `Uf` is defined\n // on inputs of the form (x, y), where x has n bits and y has 1 bit.\n use queryRegister = Qubit[n];\n use target = Qubit();\n\n // The last qubit needs to be flipped so that the function will actually\n // be computed into the phase when Uf is applied.\n X(target);\n\n // Now, a Hadamard transform is applied to each of the qubits.\n H(target);\n // We use a within-apply block to ensure that the Hadamard transform is\n // correctly inverted on the |𝑥〉 register.\n within {\n for q in queryRegister {\n H(q);\n }\n } apply {\n // We apply Uf to the n+1 qubits, computing |𝑥, 𝑦〉 ↦ |𝑥, 𝑦 ⊕ 𝑓(𝑥)〉.\n Uf(queryRegister, target);\n }\n\n // The following for-loop measures all qubits and resets them to the |0〉\n // state so that they can be safely deallocated at the end of the block.\n // The loop also sets `result` to `true` if all measurement results are\n // `Zero`, i.e. if the function is a constant function, and sets\n // `result` to `false` if not, which according to the assumption on 𝑓 \n // means that it must be balanced.\n mutable result = true;\n for q in queryRegister {\n if MResetZ(q) == One {\n set result = false;\n }\n }\n\n // Finally, the last qubit, which held the 𝑦-register, is reset.\n Reset(target);\n return result;\n }\n\n // Simple constant Boolean function\n operation SimpleConstantBoolF(args : Qubit[], target : Qubit) : Unit {\n X(target);\n }\n\n // Simple balanced Boolean function\n operation SimpleBalancedBoolF(args : Qubit[], target : Qubit) : Unit {\n CX(args[0], target);\n }\n\n // A more complex constant Boolean function.\n // It applies X to every input basis vector.\n operation ConstantBoolF(args : Qubit[], target : Qubit) : Unit {\n for i in 0..(2^Length(args))-1 {\n ApplyControlledOnInt(i, X, args, target);\n }\n }\n\n // A more complex balanced Boolean function.\n // It applies X to half of the input basis vectors.\n operation BalancedBoolF(args : Qubit[], target : Qubit) : Unit {\n for i in 0..2..(2^Length(args))-1 {\n ApplyControlledOnInt(i, X, args, target);\n }\n }\n}\n"
41
+ },
42
+ {
43
+ "title": "Bernstein–Vazirani",
44
+ "shots": 1,
45
+ "code": "/// # Sample\n/// Bernstein-Vazirani algorithm\n///\n/// # Description\n/// The Bernstein-Vazirani algorithm determines the value of a bit string\n/// encoded in a function.\n///\n/// This Q# program implements the Bernstein-Vazirani algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Arrays;\n open Microsoft.Quantum.Convert;\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Measurement;\n\n @EntryPoint()\n operation Main() : Int[] {\n // Consider a function 𝑓(𝑥⃗) on bitstrings 𝑥⃗ = (𝑥₀, …, 𝑥ₙ₋₁) of the form\n // 𝑓(𝑥⃗) ≔ Σᵢ 𝑥ᵢ 𝑟ᵢ\n // where 𝑟⃗ = (𝑟₀, …, 𝑟ₙ₋₁) is an unknown bitstring that determines the\n // parity of 𝑓.\n\n // The Bernstein–Vazirani algorithm allows determining 𝑟 given a\n // quantum operation that implements\n // |𝑥〉|𝑦〉 ↦ |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉.\n\n // The entry point function of this program, `Main`, shows how to use\n // the `BernsteinVazirani` operation to determine the value of various\n // integers whose bits describe 𝑟.\n let nQubits = 10;\n\n // Use the Bernstein–Vazirani algorithm to determine the bit strings\n // that various integers represent.\n let integers = [127, 238, 512];\n mutable decodedIntegers = [];\n for integer in integers {\n // Create an operation that encodes a bit string represented by an\n // integer as a parity operation.\n let parityOperation = EncodeIntegerAsParityOperation(integer);\n\n // Use the parity operation as input to the Bernstein-Vazirani\n // algorithm to determine the bit string.\n let decodedBitString = BernsteinVazirani(parityOperation, nQubits);\n let decodedInteger = ResultArrayAsInt(decodedBitString);\n Fact(\n decodedInteger == integer,\n $\"Decoded integer {decodedInteger}, but expected {integer}.\");\n\n Message($\"Successfully decoded bit string as int: {decodedInteger}\");\n set decodedIntegers += [decodedInteger];\n }\n\n return decodedIntegers;\n }\n\n /// # Summary\n /// This operation implements the Bernstein-Vazirani quantum algorithm.\n /// This algorithm computes for a given Boolean function that is promised to\n /// be a parity 𝑓(𝑥₀, …, 𝑥ₙ₋₁) = Σᵢ 𝑟ᵢ 𝑥ᵢ a result in the form of a bit\n /// vector (𝑟₀, …, 𝑟ₙ₋₁) corresponding to the parity function.\n /// Note that it is promised that the function is actually a parity\n /// function.\n ///\n /// # Input\n /// ## Uf\n /// A quantum operation that implements |𝑥〉|𝑦〉 ↦ |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉,\n /// where 𝑓 is a Boolean function that implements a parity Σᵢ 𝑟ᵢ 𝑥ᵢ.\n /// ## n\n /// The number of bits in the input register |𝑥〉.\n ///\n /// # Output\n /// An array of type `Result[]` that contains the parity 𝑟⃗ = (𝑟₀, …, 𝑟ₙ₋₁).\n ///\n /// # See Also\n /// - For details see Section 1.4.3 of Nielsen & Chuang.\n ///\n /// # References\n /// - [ *Ethan Bernstein and Umesh Vazirani*,\n /// SIAM J. Comput., 26(5), 1411–1473, 1997 ]\n /// (https://doi.org/10.1137/S0097539796300921)\n operation BernsteinVazirani(Uf : ((Qubit[], Qubit) => Unit), n : Int)\n : Result[] {\n // We allocate n + 1 clean qubits. Note that the function Uf is defined\n // on inputs of the form (x, y), where x has n bits and y has 1 bit.\n use queryRegister = Qubit[n];\n use target = Qubit();\n\n // The last qubit needs to be flipped so that the function will actually\n // be computed into the phase when Uf is applied.\n X(target);\n\n within {\n // Now, a Hadamard transform is applied to each of the qubits. As\n // the last step before the measurement, a Hadamard transform is\n // applied to all qubits except last one. We could apply the\n // transform to the last qubit also, but this would not affect the\n // final outcome.\n // We use a within-apply block to ensure that the Hadamard transform\n // is correctly inverted.\n ApplyToEachA(H, queryRegister);\n } apply {\n H(target);\n // We now apply Uf to the n+1 qubits, computing\n // |x, y〉 ↦ |x, y ⊕ f(x)〉.\n Uf(queryRegister, target);\n }\n\n // Measure all qubits and reset them to the |0〉 state so that they can\n // be safely deallocated at the end of the block.\n let resultArray = ForEach(MResetZ, queryRegister);\n\n // Finally, the last qubit, which held the y-register, is reset.\n Reset(target);\n\n // The result is already contained in resultArray so no further\n // post-processing is necessary.\n return resultArray;\n }\n\n /// # Summary\n /// Given an integer that can be represented as a bit string\n /// 𝑟⃗ = (r₀, …, rₙ₋₁), this operation applies a unitary 𝑈 that acts on 𝑛 + 1\n /// qubits as:\n /// 𝑈 |𝑥〉|𝑦〉 = |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉\n /// where 𝑓(𝑥) = Σᵢ 𝑥ᵢ 𝑟ᵢ mod 2.\n ///\n /// # Input\n /// ## bitStringAsInt\n /// An integer that can be represented as a bit string 𝑟⃗ used to define the\n /// function 𝑓.\n /// ## xRegister\n /// Represents the |𝑥〉 register that 𝑈 acts on.\n /// ## yQubit\n /// Represents the |𝑦〉 qubit that 𝑈 acts on.\n operation ApplyParityOperation(\n bitStringAsInt : Int,\n xRegister : Qubit[],\n yQubit : Qubit)\n : Unit {\n // `xRegister` muts have enough qubits to represent the integer.\n let requiredBits = BitSizeI(bitStringAsInt);\n let availableQubits = Length(xRegister);\n Fact(\n availableQubits >= requiredBits,\n $\"Integer value {bitStringAsInt} requires {requiredBits} bits to \" +\n $\"be represented but the quantum register only has \" +\n $\"{availableQubits} qubits\");\n\n // Apply the quantum operations that encode the bit string.\n for index in IndexRange(xRegister) {\n if ((bitStringAsInt &&& 2^index) != 0) {\n CNOT(xRegister[index], yQubit);\n }\n }\n }\n\n /// # Summary\n /// Returns black-box operations (Qubit[], Qubit) => () of the form\n /// U_f |𝑥〉|𝑦〉 = |𝑥〉|𝑦 ⊕ 𝑓(𝑥)〉.\n /// We define 𝑓 by providing the bit string 𝑟⃗ as an integer.\n operation EncodeIntegerAsParityOperation(bitStringAsInt : Int)\n : (Qubit[], Qubit) => Unit {\n return ApplyParityOperation(bitStringAsInt, _, _);\n }\n}\n"
46
+ },
47
+ {
48
+ "title": "Grover's search",
49
+ "shots": 100,
50
+ "code": "/// # Sample\n/// Grover's search algorithm\n///\n/// # Description\n/// Grover's search algorithm is a quantum algorithm that finds with high\n/// probability the unique input to a black box function that produces a\n/// particular output value.\n///\n/// This Q# program implements the Grover's search algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Convert;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Arrays;\n open Microsoft.Quantum.Measurement;\n open Microsoft.Quantum.Diagnostics;\n\n @EntryPoint()\n operation Main() : Result[] {\n let nQubits = 5;\n\n // Grover's algorithm relies on performing a \"Grover iteration\" an\n // optimal number of times to maximize the probability of finding the\n // value we are searching for.\n // You can set the number iterations to a value lower than optimal to\n // intentionally reduce precision.\n let iterations = CalculateOptimalIterations(nQubits);\n Message($\"Number of iterations: {iterations}\");\n\n // Use Grover's algorithm to find a particular marked state.\n let results = GroverSearch(nQubits, iterations, ReflectAboutMarked);\n return results;\n }\n\n /// # Summary\n /// Implements Grover's algorithm, which searches all possible inputs to an\n /// operation to find a particular marked state.\n operation GroverSearch(\n nQubits: Int,\n iterations: Int,\n phaseOracle: Qubit[] => Unit): Result[] {\n\n use qubits = Qubit[nQubits];\n\n // Initialize a uniform superposition over all possible inputs.\n PrepareUniform(qubits);\n\n // The search itself consists of repeatedly reflecting about the marked\n // state and our start state, which we can write out in Q# as a for loop.\n for _ in 1..iterations {\n phaseOracle(qubits);\n ReflectAboutUniform(qubits);\n }\n\n // Measure and return the answer.\n return MResetEachZ(qubits);\n }\n\n /// # Summary\n /// Returns the optimal number of Grover iterations needed to find a marked\n /// item, given the number of qubits in a register.\n function CalculateOptimalIterations(nQubits : Int) : Int {\n let nItems = 1 <<< nQubits; // 2^nQubits\n let angle = ArcSin(1. / Sqrt(IntAsDouble(nItems)));\n let iterations = Round(0.25 * PI() / angle - 0.5);\n return iterations;\n }\n\n /// # Summary\n /// Reflects about the basis state marked by alternating zeros and ones.\n /// This operation defines what input we are trying to find in the search.\n operation ReflectAboutMarked(inputQubits : Qubit[]) : Unit {\n Message(\"Reflecting about marked state...\");\n use outputQubit = Qubit();\n within {\n // We initialize the outputQubit to (|0⟩ - |1⟩) / √2, so that\n // toggling it results in a (-1) phase.\n X(outputQubit);\n H(outputQubit);\n // Flip the outputQubit for marked states.\n // Here, we get the state with alternating 0s and 1s by using the X\n // operation on every other qubit.\n for q in inputQubits[...2...] {\n X(q);\n }\n } apply {\n Controlled X(inputQubits, outputQubit);\n }\n }\n\n /// # Summary\n /// Given a register in the all-zeros state, prepares a uniform\n /// superposition over all basis states.\n operation PrepareUniform(inputQubits : Qubit[]): Unit is Adj + Ctl {\n for q in inputQubits {\n H(q);\n }\n }\n\n /// # Summary\n /// Reflects about the all-ones state.\n operation ReflectAboutAllOnes(inputQubits : Qubit[]): Unit {\n Controlled Z(Most(inputQubits), Tail(inputQubits));\n }\n\n /// # Summary\n /// Reflects about the uniform superposition state.\n operation ReflectAboutUniform(inputQubits : Qubit[]): Unit {\n within {\n // Transform the uniform superposition to all-zero.\n Adjoint PrepareUniform(inputQubits);\n // Transform the all-zero state to all-ones\n for q in inputQubits {\n X(q);\n }\n } apply {\n // Now that we've transformed the uniform superposition to the\n // all-ones state, reflect about the all-ones state, then let the\n // within/apply block transform us back.\n ReflectAboutAllOnes(inputQubits);\n }\n }\n}\n"
51
+ },
52
+ {
53
+ "title": "Hidden shift",
54
+ "shots": 1,
55
+ "code": "/// # Sample\n/// Hidden shift\n///\n/// # Description\n/// There is a family of problems known as hidden shift problems, in which it\n/// is given that two Boolean functions 𝑓 and 𝑔 satisfy the relation\n/// 𝑔(𝑥) = 𝑓(𝑥 ⊕ 𝑠) for all 𝑥\n/// where 𝑠 is a hidden bit string that we would like to find.\n///\n/// This Q# program implements an algorithm to solve the hidden shift problem.\nnamespace Sample {\n open Microsoft.Quantum.Arithmetic;\n open Microsoft.Quantum.Arrays;\n open Microsoft.Quantum.Convert;\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Measurement;\n\n @EntryPoint()\n operation Main(): Int[] {\n let nQubits = 10;\n\n // Consider the case of finding a hidden shift 𝑠 between two Boolean\n // functions 𝑓(𝑥) and 𝑔(𝑥) = 𝑓(𝑥 ⊕ 𝑠).\n // This problem can be solved on a quantum computer with one call to\n // each of 𝑓 and 𝑔 in the special case that both functions are bent;\n // that is, that they are as far from linear as possible.\n\n // Here, we find the hidden shift for various pairs of bent functions.\n let shifts = [170, 512, 999];\n mutable hiddenShifts = [];\n for shift in shifts {\n let hiddenShiftBitString = FindHiddenShift(\n BentFunction,\n register => ShiftedBentFunction(shift, register),\n nQubits);\n let hiddenShift = ResultArrayAsInt(hiddenShiftBitString);\n Fact(\n hiddenShift == shift,\n $\"Found shift {hiddenShift}, but expected {shift}.\");\n Message($\"Found {shift} successfully!\");\n set hiddenShifts += [hiddenShift];\n }\n\n return hiddenShifts;\n }\n\n /// # Summary\n /// Implements a correlation-based algorithm to solve the hidden shift\n /// problem for bent functions.\n ///\n /// # Description\n /// Implements a solution for the hidden shift problem, which is to identify\n /// an unknown shift 𝑠 of the arguments of two Boolean functions 𝑓 and 𝑔\n /// that are promised to satisfy the relation 𝑔(𝑥) = 𝑓(𝑥 ⊕ 𝑠) for all 𝑥.\n ///\n /// 𝑓 and 𝑔 are assumed to be bent functions. A Boolean function is bent if\n /// it is as far from linear as possible. In particular, bent functions have\n /// flat Fourier (Walsh–Hadamard) spectra.\n ///\n /// In this case, the Roetteler algorithm (see References, below) uses\n /// black-box oracles for 𝑓^* and 𝑔, where 𝑓^* is the dual bent function to\n /// 𝑓, and computes the hidden shift 𝑠 between 𝑓 and 𝑔.\n ///\n /// # Input\n /// ## Ufstar\n /// A quantum operation that implements\n /// $U_f^*: |𝑥〉 ↦ (-1)^{f^*(x)} |𝑥〉$,\n /// where $f^*$ is a Boolean function, 𝑥 is an $n$ bit register\n /// ## Ug\n /// A quantum operation that implements\n /// $U_g:|𝑥〉 ↦ (-1)^{g(x)} |𝑥〉$,\n /// where 𝑔 is a Boolean function that is shifted by unknown\n /// 𝑠 from 𝑓, and 𝑥 is an $n$ bit register.\n /// ## n\n /// The number of bits of the input register |𝑥〉.\n ///\n /// # Output\n /// An array of type `Result[]` which encodes the bit representation\n /// of the hidden shift.\n ///\n /// # References\n /// - [*Martin Roetteler*,\n /// Proc. SODA 2010, ACM, pp. 448-457, 2010]\n /// (https://doi.org/10.1137/1.9781611973075.37)\n operation FindHiddenShift (\n Ufstar : (Qubit[] => Unit),\n Ug : (Qubit[] => Unit),\n n: Int)\n : Result[] {\n // We allocate n clean qubits. Note that the function Ufstar and Ug are\n // unitary operations on n qubits defined via phase encoding.\n use qubits = Qubit[n];\n\n // First, a Hadamard transform is applied to each of the qubits.\n ApplyToEach(H, qubits);\n\n // We now apply the shifted function Ug to the n qubits, computing\n // |x〉 -> (-1)^{g(x)} |x〉.\n Ug(qubits);\n\n within {\n // A Hadamard transform is applied to each of the n qubits.\n ApplyToEachA(H, qubits);\n } apply {\n // we now apply the dual function of the unshifted function, i.e.,\n // Ufstar, to the n qubits, computing |x〉 -> (-1)^{fstar(x)} |x〉.\n Ufstar(qubits);\n }\n\n // Measure the n qubits and reset them to zero so that they can be\n // safely deallocated at the end of the block.\n return ForEach(MResetZ, qubits);\n }\n\n /// # Summary\n /// Implements an oracle for a bent function constructed from the inner\n /// product of Boolean functions.\n ///\n /// # Description\n /// This operation defines the Boolean function IP(x_0, ..., x_{n-1}) which\n /// is computed into the phase, i.e., a diagonal operator that maps\n /// |x〉 -> (-1)^{IP(x)} |x〉, where x stands for x=(x_0, ..., x_{n-1}) and all\n /// the x_i are binary. The IP function is defined as\n /// IP(y, z) = y_0 z_0 + y_1 z_1 + ... y_{u-1} z_{u-1} where\n /// y = (y_0, ..., y_{u-1}) and z = (z_0, ..., z_{u-1}) are two bit vectors\n /// of length u. Notice that the function IP is a Boolean function on n = 2u\n /// bits. IP is a special case of bent function. These are functions for\n /// which the Walsh-Hadamard transform is perfectly flat (in absolute\n /// value).\n /// Because of this flatness, the Walsh-Hadamard spectrum of any bent\n /// function defines a +1/-1 function, i.e., gives rise to another Boolean\n /// function, called the dual bent function. Moreover, for the case of the\n /// IP function it can be shown that IP is equal to its own dual bent\n /// function.\n ///\n /// # Remarks\n /// Notice that a diagonal operator implementing IP between 2 variables y_0\n /// and z_0 is nothing but the AND function between those variables, i.e.,\n /// in phase encoding it is computed by a Controlled-Z gate.\n /// Extending this to an XOR of the AND of more variables, as required in\n /// the definition of the IP function can then be accomplished by applying\n /// several Controlled-Z gates between the respective inputs.\n operation BentFunction(register : Qubit[]) : Unit {\n Fact(Length(register) % 2 == 0, \"Length of register must be even.\");\n let u = Length(register) / 2;\n let xs = register[0 .. u - 1];\n let ys = register[u...];\n for index in 0..u-1 {\n CZ(xs[index], ys[index]);\n }\n }\n\n /// # Summary\n /// Implements a shifted bend function 𝑔(𝑥) = 𝑓(𝑥 ⊕ 𝑠).\n ///\n /// # Description\n /// For the hidden shift problem we need another function g which is related\n /// to IP via g(x) = IP(x + s), i.e., we have to shift the argument of the\n /// IP function by a given shift. Notice that the '+' operation here is the\n /// Boolean addition, i.e., a bit-wise operation. Notice further, that in\n /// general a diagonal operation |x〉 -> (-1)^{f(x)} can be turned into a\n /// shifted version by applying a bit flip to the |x〉 register first, then\n /// applying the diagonal operation, and then undoing the bit flips to the\n /// |x〉 register. We use this principle to define shifted versions of the IP\n /// operation.\n operation ShiftedBentFunction(shift: Int, register: Qubit[]) : Unit {\n Fact(Length(register) % 2 == 0, \"Length of register must be even.\");\n let u = Length(register) / 2;\n within {\n // Flips the bits in shift.\n ApplyXorInPlace(shift, register);\n } apply {\n // Compute the IP function into the phase.\n BentFunction(register);\n }\n }\n}\n"
56
+ },
57
+ {
58
+ "title": "Shor",
59
+ "shots": 1,
60
+ "code": "/// # Sample\n/// Shor's algorithm\n///\n/// # Description\n/// Shor's algorithm is a quantum algorithm for finding the prime factors of an\n/// integer.\n///\n/// This Q# program implements Shor's algorithm.\nnamespace Sample {\n open Microsoft.Quantum.Diagnostics;\n open Microsoft.Quantum.Random;\n open Microsoft.Quantum.Math;\n open Microsoft.Quantum.Arithmetic;\n open Microsoft.Quantum.Arrays;\n\n @EntryPoint()\n operation Main() : (Int, Int) {\n let n = 143; // 11*13;\n // You can try these other examples for a lengthier computation.\n // let n = 16837; // = 113*149\n // let n = 22499; // = 149*151\n\n // Use Shor's algorithm to factor a semiprime integer.\n let (a, b) = FactorSemiprimeInteger(n);\n Message($\"Found factorization {n} = {a} * {b} \");\n return (a, b);\n }\n\n /// # Summary\n /// Uses Shor's algorithm to factor an input number.\n ///\n /// # Input\n /// ## number\n /// A semiprime integer to be factored.\n ///\n /// # Output\n /// Pair of numbers p > 1 and q > 1 such that p⋅q = `number`\n operation FactorSemiprimeInteger(number : Int) : (Int, Int) {\n // First check the most trivial case (the provided number is even).\n if number % 2 == 0 {\n Message(\"An even number has been given; 2 is a factor.\");\n return (number / 2, 2);\n }\n // These mutables will keep track of whether we found the factors, and\n // if so, what they are. The default value for the factors is (1,1).\n mutable foundFactors = false;\n mutable factors = (1, 1);\n mutable attempt = 1;\n repeat {\n Message($\"*** Factorizing {number}, attempt {attempt}.\");\n // Try to guess a number co-prime to `number` by getting a random\n // integer in the interval [1, number-1]\n let generator = DrawRandomInt(1, number - 1);\n\n // Check if the random integer is indeed co-prime.\n // If true use Quantum algorithm for Period finding.\n if GreatestCommonDivisorI(generator, number) == 1 {\n Message($\"Estimating period of {generator}.\");\n\n // Call Quantum Period finding algorithm for\n // `generator` mod `number`.\n let period = EstimatePeriod(generator, number);\n\n // Set the flag and factors values if the continued\n // fractions classical algorithm succeeds.\n set (foundFactors, factors) =\n MaybeFactorsFromPeriod(number, generator, period);\n }\n // In this case, we guessed a divisor by accident.\n else {\n // Find divisor.\n let gcd = GreatestCommonDivisorI(number, generator);\n Message($\"We have guessed a divisor {gcd} by accident. \" + \n \"No quantum computation was done.\");\n\n // Set the flag `foundFactors` to true, indicating that we\n // succeeded in finding factors.\n set foundFactors = true;\n set factors = (gcd, number / gcd);\n }\n set attempt = attempt+1;\n if (attempt > 100) {\n fail \"Failed to find factors: too many attempts!\";\n }\n }\n until foundFactors\n fixup {\n Message(\"The estimated period did not yield a valid factor. \" + \n \"Trying again.\");\n }\n\n // Return the factorization\n return factors;\n }\n\n /// # Summary\n /// Tries to find the factors of `modulus` given a `period` and `generator`.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## period\n /// The estimated period (multiplicative order) of the generator mod\n /// `modulus`.\n ///\n /// # Output\n /// A tuple of a flag indicating whether factors were found successfully,\n /// and a pair of integers representing the factors that were found.\n /// Note that the second output is only meaningful when the first output is\n /// `true`.\n function MaybeFactorsFromPeriod(\n modulus : Int,\n generator : Int,\n period : Int)\n : (Bool, (Int, Int)) {\n\n // Period finding reduces to factoring only if period is even\n if period % 2 == 0 {\n // Compute `generator` ^ `period/2` mod `number`.\n let halfPower = ExpModI(generator, period / 2, modulus);\n\n // If we are unlucky, halfPower is just -1 mod N, which is a trivial\n // case and not useful for factoring.\n if halfPower != modulus - 1 {\n // When the halfPower is not -1 mod N, halfPower-1 or\n // halfPower+1 share non-trivial divisor with `number`. Find it.\n let factor = MaxI(\n GreatestCommonDivisorI(halfPower - 1, modulus),\n GreatestCommonDivisorI(halfPower + 1, modulus)\n );\n\n // Add a flag that we found the factors, and return computed\n // non-trivial factors.\n Message($\"Found factor={factor}\");\n return (true, (factor, modulus / factor));\n } else {\n // Return a flag indicating we hit a trivial case and didn't get\n // any factors.\n Message($\"Found trivial factors.\");\n return (false, (1, 1));\n }\n } else {\n // When period is odd we have to pick another generator to estimate\n // period of and start over.\n Message($\"Estimated period {period} was odd, trying again.\");\n return (false, (1, 1));\n }\n }\n\n /// # Summary\n /// Find the period of a number from an input frequency.\n ///\n /// # Input\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## frequencyEstimate\n /// The frequency that we want to convert to a period.\n /// ## bitsPrecision\n /// Number of bits of precision with which we need to estimate s/r to\n /// recover period r using continued fractions algorithm.\n /// ## currentDivisor\n /// The divisor of the generator period found so far.\n ///\n /// # Output\n /// The period as calculated from the estimated frequency via the continued\n /// fractions algorithm.\n function PeriodFromFrequency(\n modulus : Int,\n frequencyEstimate : Int,\n bitsPrecision : Int,\n currentDivisor : Int)\n : Int {\n // Now we use the ContinuedFractionConvergentI function to recover s/r\n // from dyadic fraction k/2^bitsPrecision.\n let (numerator, period) = ContinuedFractionConvergentI(\n (frequencyEstimate, 2 ^ bitsPrecision),\n modulus);\n\n // ContinuedFractionConvergentI does not guarantee the signs of the\n // numerator and denominator. Here we make sure that both are positive\n // using AbsI.\n let (numeratorAbs, periodAbs) = (AbsI(numerator), AbsI(period));\n\n // Compute and return the newly found divisor.\n let period =\n (periodAbs * currentDivisor) /\n GreatestCommonDivisorI(currentDivisor, periodAbs);\n Message($\"Found period={period}\");\n return period;\n }\n\n /// # Summary\n /// Finds a multiplicative order of the generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n ///\n /// # Output\n /// The period (multiplicative order) of the generator mod `modulus`\n operation EstimatePeriod(generator : Int, modulus : Int) : Int {\n // Here we check that the inputs to the EstimatePeriod operation are\n // valid.\n Fact(\n GreatestCommonDivisorI(generator, modulus) == 1,\n \"`generator` and `modulus` must be co-prime\");\n\n // Number of bits in the modulus with respect to which we are estimating\n // the period.\n let bitsize = BitSizeI(modulus);\n\n // The EstimatePeriod operation estimates the period r by finding an\n // approximation k/2^(bits precision) to a fraction s/r, where s is some\n // integer. Note that if s and r have common divisors we will end up\n // recovering a divisor of r and not r itself.\n\n // Number of bits of precision with which we need to estimate s/r to\n // recover period r, using continued fractions algorithm.\n let bitsPrecision = 2 * bitsize + 1;\n\n // Current estimate for the frequency of the form s/r.\n let frequencyEstimate = EstimateFrequency(generator, modulus, bitsize);\n if frequencyEstimate != 0 {\n return PeriodFromFrequency(\n modulus, frequencyEstimate, bitsPrecision, 1);\n }\n else {\n Message(\"The estimated frequency was 0, trying again.\");\n return 1;\n }\n }\n\n /// # Summary\n /// Estimates the frequency of a generator in the residue ring Z mod\n /// `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## bitsize\n /// Number of bits needed to represent the modulus.\n ///\n /// # Output\n /// The numerator k of dyadic fraction k/2^bitsPrecision approximating s/r.\n operation EstimateFrequency(generator : Int,modulus : Int, bitsize : Int)\n : Int {\n mutable frequencyEstimate = 0;\n let bitsPrecision = 2 * bitsize + 1;\n Message($\"Estimating frequency with bitsPrecision={bitsPrecision}.\");\n\n // Allocate qubits for the superposition of eigenstates of the oracle\n // that is used in period finding.\n use eigenstateRegister = Qubit[bitsize];\n\n // Initialize eigenstateRegister to 1, which is a superposition of the\n // eigenstates we are estimating the phases of.\n // We are interpreting the register as encoding an unsigned integer in\n // little-endian format.\n ApplyXorInPlace(1, eigenstateRegister);\n\n // Use phase estimation with a semiclassical Fourier transform to\n // estimate the frequency.\n use c = Qubit();\n for idx in bitsPrecision-1..-1..0 {\n H(c);\n Controlled ApplyOrderFindingOracle(\n [c],\n (generator, modulus, 1 <<< idx, eigenstateRegister));\n R1Frac(frequencyEstimate, bitsPrecision-1-idx, c);\n H(c);\n if M(c) == One {\n X(c); // Reset\n set frequencyEstimate += 1 <<< (bitsPrecision-1-idx);\n }\n }\n\n // Return all the qubits used for oracle's eigenstate back to 0 state\n // using ResetAll.\n ResetAll(eigenstateRegister);\n Message($\"Estimated frequency={frequencyEstimate}\");\n return frequencyEstimate;\n }\n\n /// # Summary\n /// Interprets `target` as encoding unsigned little-endian integer k and\n /// performs transformation |k⟩ ↦ |gᵖ⋅k mod N ⟩ where p is `power`, g is \n /// `generator` and N is `modulus`.\n ///\n /// # Input\n /// ## generator\n /// The unsigned integer multiplicative order (period) of which is being\n /// estimated. Must be co-prime to `modulus`.\n /// ## modulus\n /// The modulus which defines the residue ring Z mod `modulus` in which the\n /// multiplicative order of `generator` is being estimated.\n /// ## power\n /// Power of `generator` by which `target` is multiplied.\n /// ## target\n /// Register interpreted as little-endian which is multiplied by given power\n /// of the generator. The multiplication is performed modulo `modulus`.\n operation ApplyOrderFindingOracle(\n generator : Int,\n modulus : Int,\n power : Int,\n target : Qubit[])\n : Unit is Adj + Ctl {\n // Check that the parameters satisfy the requirements.\n Fact(\n GreatestCommonDivisorI(generator, modulus) == 1,\n \"`generator` and `modulus` must be co-prime\");\n\n // The oracle we use for order finding implements |x⟩ ↦ |x⋅a mod N⟩.\n // We also use `ExpModI` to compute a by which x must be multiplied.\n // Also note that we interpret target as unsigned integer in\n // little-endian fromat.\n ModularMultiplyByConstant(\n modulus,\n ExpModI(generator, power, modulus),\n target);\n }\n\n //\n // Arithmetic helper functions to implement order-finding oracle.\n //\n\n /// # Summary\n /// Returns the number of trailing zeroes of a number.\n ///\n /// ## Example\n /// let zeroes = NTrailingZeroes(21); // NTrailingZeroes(0b1101) = 0\n /// let zeroes = NTrailingZeroes(20); // NTrailingZeroes(0b1100) = 2\n function NTrailingZeroes(number : Int) : Int {\n Fact(number != 0, \"NTrailingZeroes: number cannot be 0.\");\n mutable nZeroes = 0;\n mutable copy = number;\n while (copy % 2 == 0) {\n set nZeroes += 1;\n set copy /= 2;\n }\n return nZeroes;\n }\n\n /// # Summary\n /// Performs modular in-place multiplication by a classical constant.\n ///\n /// # Description\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes \n /// `(c*x) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular multiplication\n /// ## c\n /// Constant by which to multiply |𝑦⟩\n /// ## y\n /// Quantum register of target\n operation ModularMultiplyByConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n use qs = Qubit[Length(y)];\n for idx in IndexRange(y) {\n let shiftedC = (c <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, shiftedC, qs));\n }\n for idx in IndexRange(y) {\n SWAP(y[idx], qs[idx]);\n }\n let invC = InverseModI(c, modulus);\n for idx in IndexRange(y) {\n let shiftedC = (invC <<< idx) % modulus;\n Controlled ModularAddConstant(\n [y[idx]],\n (modulus, modulus - shiftedC, qs));\n }\n }\n\n /// # Summary\n /// Performs modular in-place addition of a classical constant into a\n /// quantum register.\n ///\n /// # Description\n /// Given the classical constants `c` and `modulus`, and an input quantum\n /// register |𝑦⟩ in little-endian format, this operation computes\n /// `(x+c) % modulus` into |𝑦⟩.\n ///\n /// # Input\n /// ## modulus\n /// Modulus to use for modular addition\n /// ## c\n /// Constant to add to |𝑦⟩\n /// ## y\n /// Quantum register of target\n operation ModularAddConstant(modulus : Int, c : Int, y : Qubit[])\n : Unit is Adj + Ctl {\n body (...) {\n Controlled ModularAddConstant([], (modulus, c, y));\n }\n controlled (ctrls, ...) {\n // We apply a custom strategy to control this operation instead of\n // letting the compiler create the controlled variant for us in\n // which the `Controlled` functor would be distributed over each\n // operation in the body.\n //\n // Here we can use some scratch memory to save ensure that at most\n // one control qubit is used for costly operations such as\n // `AddConstant` and `CompareGreaterThenOrEqualConstant`.\n if Length(ctrls) >= 2 {\n use control = Qubit();\n within {\n Controlled X(ctrls, control);\n } apply {\n Controlled ModularAddConstant(\n [control],\n (modulus, c, y));\n }\n } else {\n use carry = Qubit();\n Controlled AddConstant(\n ctrls, (c, y + [carry]));\n Controlled Adjoint AddConstant(\n ctrls, (modulus, y + [carry]));\n Controlled AddConstant(\n [carry], (modulus, y));\n Controlled CompareGreaterThanOrEqualConstant(\n ctrls, (c, y, carry));\n }\n }\n }\n\n /// # Summary\n /// Performs in-place addition of a constant into a quantum register.\n ///\n /// # Description\n /// Given a non-empty quantum register |𝑦⟩ of length 𝑛+1 and a positive\n // constant 𝑐 < 2ⁿ, computes |𝑦 + c⟩ into |𝑦⟩.\n ///\n /// # Input\n /// ## c\n /// Constant number to add to |𝑦⟩.\n /// ## y\n /// Quantum register of second summand and target; must not be empty.\n operation AddConstant(c : Int, y : Qubit[]): Unit is Adj + Ctl {\n // We are using this version instead of the library version that is\n // based on Fourier angles to show an advantage of sparse simulation\n // in this sample.\n let n = Length(y);\n Fact(n > 0, \"Bit width must be at least 1\");\n Fact(c >= 0, \"constant must not be negative\");\n Fact(c < 2^n, \"constant must be smaller than {2^n)}\");\n if c != 0 {\n // If c has j trailing zeroes than the j least significant bits of y\n // won't be affected by the addition and can therefore be ignored by\n // applying the addition only to the other qubits and shifting c\n // accordingly.\n let j = NTrailingZeroes(c);\n use x = Qubit[n - j];\n within {\n ApplyXorInPlace(c >>> j, x);\n } apply {\n AddI(x, y[j...]);\n }\n }\n }\n\n /// # Summary\n /// Performs greater-than-or-equals comparison to a constant.\n ///\n /// # Description\n /// Toggles output qubit `target` if and only if input register `x` is\n /// greater than or equal to `c`.\n ///\n /// # Input\n /// ## c\n /// Constant value for comparison.\n /// ## x\n /// Quantum register to compare against.\n /// ## target\n /// Target qubit for comparison result.\n ///\n /// # Reference\n /// This construction is described in [Lemma 3, arXiv:2201.10200]\n operation CompareGreaterThanOrEqualConstant(\n c : Int,\n x : Qubit[],\n target : Qubit)\n : Unit is Adj+Ctl {\n let bitWidth = Length(x);\n if c == 0 {\n X(target);\n } elif c >= (2^bitWidth) {\n // do nothing\n } elif c == (2^(bitWidth - 1)) {\n CNOT(Tail(x), target);\n } else {\n // normalize constant\n let l = NTrailingZeroes(c);\n let cNormalized = c >>> l;\n let xNormalized = x[l...];\n let bitWidthNormalized = Length(xNormalized);\n use qs = Qubit[bitWidthNormalized - 1];\n let cs1 = [Head(xNormalized)] + Most(qs);\n Fact(Length(cs1) == Length(qs),\n \"Arrays should be of the same length.\");\n within {\n for i in 0..Length(cs1)-1 {\n let op =\n cNormalized &&& (1 <<< (i+1)) != 0 ?\n ApplyAnd | ApplyOr;\n op(cs1[i], xNormalized[i+1], qs[i]);\n }\n } apply {\n CNOT(Tail(qs), target);\n }\n }\n }\n\n /// # Summary\n /// Inverts a given target qubit if and only if both control qubits are in\n /// the 1 state, using measurement to perform the adjoint operation.\n ///\n /// # Description\n /// Inverts `target` if and only if both controls are 1, but assumes that\n /// `target` is in state 0. The operation has T-count 4, T-depth 2 and\n /// requires no helper qubit, and may therefore be preferable to a CCNOT\n /// operation, if `target` is known to be 0.\n /// The adjoint of this operation is measurement based and requires no T\n /// gates.\n /// Although the Toffoli gate (CCNOT) will perform faster in in simulations,\n /// this version has lower T gate requirements.\n ///\n /// # Input\n /// ## control1\n /// First control qubit\n /// ## control2\n /// Second control qubit\n /// ## target\n /// Target auxiliary qubit; must be in state 0\n ///\n /// # References\n /// - Cody Jones: \"Novel constructions for the fault-tolerant\n /// Toffoli gate\",\n /// Phys. Rev. A 87, 022328, 2013\n /// [arXiv:1212.5069](https://arxiv.org/abs/1212.5069)\n /// doi:10.1103/PhysRevA.87.022328\n /// - Craig Gidney: \"Halving the cost of quantum addition\",\n /// Quantum 2, page 74, 2018\n /// [arXiv:1709.06648](https://arxiv.org/abs/1709.06648)\n /// doi:10.1103/PhysRevA.85.044302\n /// - Mathias Soeken: \"Quantum Oracle Circuits and the Christmas\n /// Tree Pattern\",\n /// [Blog article from December 19, 2019](https://msoeken.github.io/blog_qac.html)\n /// (note: explains the multiple controlled construction)\n operation ApplyAnd(control1 : Qubit, control2 : Qubit, target : Qubit)\n : Unit is Adj {\n body (...) {\n H(target);\n T(target);\n CNOT(control1, target);\n CNOT(control2, target);\n within {\n CNOT(target, control1);\n CNOT(target, control2);\n }\n apply {\n Adjoint T(control1);\n Adjoint T(control2);\n T(target);\n }\n H(target);\n S(target);\n }\n adjoint (...) {\n H(target);\n if (M(target) == One) {\n X(target);\n CZ(control1, control2);\n }\n }\n }\n\n /// # Summary\n /// Applies X to the target if any of the controls are 1.\n operation ApplyOr(control1 : Qubit, control2 : Qubit, target : Qubit)\n : Unit is Adj {\n within {\n ApplyToEachA(X, [control1, control2]);\n } apply {\n ApplyAnd(control1, control2, target);\n X(target);\n }\n }\n}\n"
61
+ }
62
+ ];
@@ -0,0 +1,27 @@
1
+ export interface VSDiagnostic {
2
+ start_pos: number;
3
+ end_pos: number;
4
+ message: string;
5
+ severity: "error" | "warning" | "info";
6
+ code?: {
7
+ value: string;
8
+ target: string;
9
+ };
10
+ }
11
+ /**
12
+ * @param positions - An array of utf-8 code unit indexes to map to utf-16 code unit indexes
13
+ * @param source - The source code to do the mapping on
14
+ * @returns An object where the keys are the utf-8 index and the values are the utf-16 index
15
+ */
16
+ export declare function mapUtf16UnitsToUtf8Units(positions: Array<number>, source: string): {
17
+ [index: number]: number;
18
+ };
19
+ /**
20
+ * @param positions - An array of utf-8 code unit indexes to map to utf-16 code unit indexes
21
+ * @param source - The source code to do the mapping on
22
+ * @returns An object where the keys are the utf-8 index and the values are the utf-16 index
23
+ */
24
+ export declare function mapUtf8UnitsToUtf16Units(positions: Array<number>, source: string): {
25
+ [index: number]: number;
26
+ };
27
+ export declare function mapDiagnostics(diags: VSDiagnostic[], code: string): VSDiagnostic[];
@@ -0,0 +1,117 @@
1
+ // Copyright (c) Microsoft Corporation.
2
+ // Licensed under the MIT License.
3
+ // The QSharp compiler returns positions in utf-8 code unit positions (basically a byte[]
4
+ // index), however VS Code and Monaco handle positions as utf-16 code unit positions
5
+ // (basically JavaScript string index positions). Thus the positions returned from the
6
+ // wasm calls needs to be mapped between the two for editor integration.
7
+ /**
8
+ * @param positions - An array of utf-8 code unit indexes to map to utf-16 code unit indexes
9
+ * @param source - The source code to do the mapping on
10
+ * @returns An object where the keys are the utf-8 index and the values are the utf-16 index
11
+ */
12
+ export function mapUtf16UnitsToUtf8Units(positions, source) {
13
+ return mapStringIndexes(source, positions, "utf16");
14
+ }
15
+ /**
16
+ * @param positions - An array of utf-8 code unit indexes to map to utf-16 code unit indexes
17
+ * @param source - The source code to do the mapping on
18
+ * @returns An object where the keys are the utf-8 index and the values are the utf-16 index
19
+ */
20
+ export function mapUtf8UnitsToUtf16Units(positions, source) {
21
+ return mapStringIndexes(source, positions, "utf8");
22
+ }
23
+ function mapStringIndexes(buffer, indexes, sourceIndexType) {
24
+ const result = {};
25
+ if (indexes.length === 0)
26
+ return result;
27
+ // Remove any duplicates by converting to a set and back to an array
28
+ const dedupedIndexes = [...new Set(indexes)];
29
+ // Do one pass through the string, so ensure the indexes are in ascending order
30
+ const sortedIndexes = dedupedIndexes.sort((a, b) => (a < b ? -1 : 1));
31
+ // Assume that Rust handles utf-8 correctly in strings, and that the UTF-8 code units
32
+ // per Unicode code point are as per the ranges below:
33
+ // - 0x000000 to 0x00007F = 1 utf-8 code unit
34
+ // - 0x000080 to 0x0007FF = 2 utf-8 code units
35
+ // - 0x000800 to 0x00FFFF = 3 utf-8 code units
36
+ // - 0x010000 to 0x10FFFF = 4 utf-8 code units
37
+ //
38
+ // Also assume the string is valid UTF-16 and all characters
39
+ // outside the BMP (i.e. > 0xFFFF) are encoded with valid 'surrogate pairs', and
40
+ // no other UTF-16 code units in the D800 - DFFF range occur.
41
+ // A valid pair must be "high" surrogate (D800–DBFF) then "low" surrogates (DC00–DFFF)
42
+ function isValidSurrogatePair(first, second) {
43
+ if (first < 0xd800 ||
44
+ first > 0xdbff ||
45
+ second < 0xdc00 ||
46
+ second > 0xdfff) {
47
+ return false;
48
+ }
49
+ return true;
50
+ }
51
+ let utf16Index = 0;
52
+ let utf8Index = 0;
53
+ let sourceIndex = 0; // depending on the conversion requested, this will be equal to utf8Index or utf16Index
54
+ let targetIndex = 0; // depending on the conversion requested, this will be equal to utf8Index or utf16Index
55
+ let posArrayIndex = 0;
56
+ let nextIndex = sortedIndexes[posArrayIndex];
57
+ for (;;) {
58
+ // Walk though the string, maintaining a UTF-8 to UTF-16 code unit index mapping.
59
+ // When the string index >= the next searched for index, save that result and increment.
60
+ // If the end of string or end of searched for indexes is reached, then break.
61
+ if (sourceIndex >= nextIndex) {
62
+ result[sourceIndex] = targetIndex;
63
+ if (++posArrayIndex >= sortedIndexes.length)
64
+ break;
65
+ nextIndex = sortedIndexes[posArrayIndex];
66
+ }
67
+ if (utf16Index >= buffer.length)
68
+ break;
69
+ // Get the code unit (not code point) at the string index.
70
+ const utf16CodeUnit = buffer.charCodeAt(utf16Index);
71
+ // Advance the utf-8 index by the correct amount for the utf-16 code unit value.
72
+ if (utf16CodeUnit < 0x80) {
73
+ utf8Index += 1;
74
+ }
75
+ else if (utf16CodeUnit < 0x800) {
76
+ utf8Index += 2;
77
+ }
78
+ else if (utf16CodeUnit < 0xd800 || utf16CodeUnit > 0xdfff) {
79
+ // Not a surrogate pair, so one utf-16 code unit over 0x7FF == three utf-8 code utits
80
+ utf8Index += 3;
81
+ }
82
+ else {
83
+ // Need to consume the extra utf16 code unit for the pair also.
84
+ const nextCodeUnit = buffer.charCodeAt(++utf16Index) || 0;
85
+ if (!isValidSurrogatePair(utf16CodeUnit, nextCodeUnit))
86
+ throw "Invalid surrogate pair";
87
+ // Valid utf-16 surrogate pair implies code point over 0xFFFF implies 4 utf-8 code units.
88
+ utf8Index += 4;
89
+ }
90
+ ++utf16Index; // Don't break here if EOF. We need to handle EOF being the final position to resolve.
91
+ sourceIndex = sourceIndexType === "utf8" ? utf8Index : utf16Index;
92
+ targetIndex = sourceIndexType === "utf8" ? utf16Index : utf8Index;
93
+ }
94
+ // TODO: May want to have a more configurable error reporting at some point. Avoid throwing here,
95
+ // and just report and continue.
96
+ if (posArrayIndex < sortedIndexes.length) {
97
+ console.error(`Failed to map all ${sourceIndexType} indexes. Remaining indexes are: ${sortedIndexes.slice(posArrayIndex)}`);
98
+ }
99
+ return result;
100
+ }
101
+ export function mapDiagnostics(diags, code) {
102
+ // Get a map of the Rust source positions to the JavaScript source positions
103
+ const positions = [];
104
+ diags.forEach((diag) => {
105
+ positions.push(diag.start_pos);
106
+ positions.push(diag.end_pos);
107
+ });
108
+ const positionMap = mapUtf8UnitsToUtf16Units(positions, code);
109
+ // Return the diagnostics with the positions mapped (or EOF if couldn't resolve)
110
+ const results = diags.map((diag) => ({
111
+ ...diag,
112
+ // The mapped position may well be 0, so need to use ?? rather than ||
113
+ start_pos: positionMap[diag.start_pos] ?? code.length,
114
+ end_pos: positionMap[diag.end_pos] ?? code.length,
115
+ }));
116
+ return results;
117
+ }
@@ -0,0 +1,95 @@
1
+ /**
2
+ * Used as a type constraint for a "service", i.e. an object
3
+ * we can create proxy methods for. The type shouldn't define
4
+ * any non-method properties.
5
+ */
6
+ type ServiceMethods<T> = {
7
+ [x in keyof T]: (...args: any[]) => any;
8
+ };
9
+ /**
10
+ * Defines the service methods that the proxy will handle and their types.
11
+ * "request" is a normal async method.
12
+ * "requestWithProgress" methods take an @see IServiceEventTarget to
13
+ * communicate events back to the main thread as they run. They also set
14
+ * the service state to "busy" while they run.
15
+ * "addEventListener" and "removeEventListener" methods are used to
16
+ * subscribe to events from the service.
17
+ */
18
+ export type MethodMap<T> = {
19
+ [M in keyof T]: "request" | "requestWithProgress" | "addEventListener" | "removeEventListener";
20
+ };
21
+ /** Methods added to the service when wrapped in a proxy */
22
+ export type IServiceProxy = {
23
+ onstatechange: ((state: ServiceState) => void) | null;
24
+ terminate: () => void;
25
+ };
26
+ /** "requestWithProgress" type methods will set the service state to "busy" */
27
+ export type ServiceState = "idle" | "busy";
28
+ /** Request message from a main thread to the worker */
29
+ export type RequestMessage<T extends ServiceMethods<T>> = {
30
+ [K in keyof T]: {
31
+ type: K;
32
+ args: Parameters<T[K]>;
33
+ };
34
+ }[keyof T];
35
+ /** Response message for a request from the worker to the main thread */
36
+ export type ResponseMessage<T extends ServiceMethods<T>> = {
37
+ messageType: "response";
38
+ } & {
39
+ [K in keyof T]: {
40
+ type: K;
41
+ result: {
42
+ success: true;
43
+ result: Awaited<ReturnType<T[K]>>;
44
+ } | {
45
+ success: false;
46
+ error: unknown;
47
+ };
48
+ };
49
+ }[keyof T];
50
+ /** Event message from the worker to the main thread */
51
+ export type EventMessage<TEventMsg extends IServiceEventMessage> = {
52
+ messageType: "event";
53
+ } & TEventMsg;
54
+ /** Used as a constraint for events defined by the service */
55
+ interface IServiceEventMessage {
56
+ type: string;
57
+ detail: unknown;
58
+ }
59
+ /**
60
+ * Strongly typed EventTarget interface. Used as a constraint for the
61
+ * event target that "requestWithProgress" methods should take in the service.
62
+ */
63
+ export interface IServiceEventTarget<TEvents extends IServiceEventMessage> {
64
+ addEventListener<T extends TEvents["type"]>(type: T, listener: (event: Event & Extract<TEvents, {
65
+ type: T;
66
+ }>) => void): void;
67
+ removeEventListener<T extends TEvents["type"]>(type: T, listener: (event: Event & Extract<TEvents, {
68
+ type: T;
69
+ }>) => void): void;
70
+ dispatchEvent(event: Event & TEvents): boolean;
71
+ }
72
+ /**
73
+ * Function to create the proxy for a type. To be used from the main thread.
74
+ *
75
+ * @param postMessage A function to post messages to the worker
76
+ * @param terminator A function to call to tear down the worker thread
77
+ * @param methods A map of method names to be proxied and some metadata @see MethodMap
78
+ * @returns The proxy object. The caller should then set the onMsgFromWorker
79
+ * property to a callback that will receive messages from the worker.
80
+ */
81
+ export declare function createProxy<TService extends ServiceMethods<TService>, TServiceEventMsg extends IServiceEventMessage>(postMessage: (msg: RequestMessage<TService>) => void, terminator: () => void, methods: MethodMap<TService>): TService & IServiceProxy & {
82
+ onMsgFromWorker: (msg: ResponseMessage<TService> | EventMessage<TServiceEventMsg>) => void;
83
+ };
84
+ /**
85
+ * Function to wrap a service in a dispatcher. To be used in the worker thread.
86
+ *
87
+ * @param service The service to be wrapped
88
+ * @param methods A map of method names. Should match the list passed into @see createProxy.
89
+ * @param eventNames The list of event names that the service can emit
90
+ * @param postMessage A function to post messages back to the main thread
91
+ * @returns A function that takes a message and invokes the corresponding
92
+ * method on the service. The caller should then set this method as a message handler.
93
+ */
94
+ export declare function createDispatcher<TService extends ServiceMethods<TService>, TServiceEventMsg extends IServiceEventMessage>(postMessage: (msg: ResponseMessage<TService> | EventMessage<TServiceEventMsg>) => void, service: TService, methods: MethodMap<TService>, eventNames: TServiceEventMsg["type"][]): (req: RequestMessage<TService>) => any;
95
+ export {};