From 7fc063f429a3d34055889a5d50905859077a0079 Mon Sep 17 00:00:00 2001 From: Christos Koromilas <84716677+Infi-DOS@users.noreply.github.com> Date: Thu, 13 Jun 2024 11:26:22 +0200 Subject: [PATCH] Update subm1 --- .../Christos_Koromilas_HW1_QClass2024.ipynb | 567 +++++++++++++++++- 1 file changed, 566 insertions(+), 1 deletion(-) diff --git a/community/QClass_2024/Submissions/HW1/Christos_Koromilas_HW1_QClass2024.ipynb b/community/QClass_2024/Submissions/HW1/Christos_Koromilas_HW1_QClass2024.ipynb index 8783fcc2..e2913c39 100644 --- a/community/QClass_2024/Submissions/HW1/Christos_Koromilas_HW1_QClass2024.ipynb +++ b/community/QClass_2024/Submissions/HW1/Christos_Koromilas_HW1_QClass2024.ipynb @@ -1 +1,566 @@ -{"cells":[{"cell_type":"markdown","metadata":{"id":"lQUnery_Agot"},"source":["# The Qmod Workshop - Introduction\n","\n","The Classiq platform features a high-level quantum modeling language called Qmod. Qmod is compiled into concrete gate-level implementation using a powerful synthesis engine that optimizes and adapts the implementation to different target hardware/simulation environments.\n","\n","In this workshop, we will learn how to write quantum models using Qmod. We will be using the Python embedding of Qmod, available as part of the Classiq Python SDK. We will learn basic concepts in the Qmod language, such as functions, operators, quantum variables, and quantum types. We will develop useful building blocks and small algorithms.\n","\n","The [QMOD language reference](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/) covers these concepts more systematically and includes more examples.\n","\n","This workshop consists of step-by-step exercises. It is structured as follows:\n","\n","- Part 1: Language Fundamentals - Exercises 1-5\n","- Part 2: Higher-Level Concepts - Exercises 6-10\n","- Part 3: Execution Flows - Exercises 11, 12\n","\n","The introduction and Part 1 are included in this notebook. Part 2 and 3 are each in its own separate notebook. For each exercise you will find the solution to the exercises at the bottom of the same notebook.\n","\n","### Preparations\n","\n","Make sure you have a Python version of 3.8 through 3.11 installed. Unfortunately, Classiq is not yet supported with Python 3.12.\n","\n","Install Classiq’s Python SDK by following the instructions on this page: [Getting Started - Classiq](https://docs.classiq.io/latest/getting-started/).\n","\n","### Python Qmod Exercises - General Instructions\n","\n","In order to synthesize and execute your Qmod code, you should:\n","1. Make sure you define a `main` function that calls functions you create.\n","2. Use `create_model` by running `qmod = create_model(main)` to construct a representation of your model.\n","3. You can synthesize the model (using `qprog = synthesize(qmod)`) to obtain an implementation - a quantum program.\n","4. You can then visualize the quantum program (`show(qprog)`) or execute it (using `execute(qprog)`. See: [Execution - Classiq](https://docs.classiq.io/latest/user-guide/platform/executor/#full-example)). You can also execute it with the IDE after visualizing the circuit.\n"]},{"cell_type":"markdown","metadata":{"id":"JHxeLndXAgo0"},"source":["### Exercise 0: From Model to Execution\n","\n","The following model defines a function that applies X and H gates on a single qubit, and subsequently calls it:"]},{"cell_type":"code","source":["!pip install -U -q classiq"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"R0QdrOXUB4uZ","executionInfo":{"status":"ok","timestamp":1716212630747,"user_tz":-120,"elapsed":51480,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"699522f2-0728-407b-ac51-12da76264970"},"execution_count":1,"outputs":[{"output_type":"stream","name":"stdout","text":["\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m398.1/398.1 kB\u001b[0m \u001b[31m5.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m10.7/10.7 MB\u001b[0m \u001b[31m860.7 kB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.8/1.8 MB\u001b[0m \u001b[31m43.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m75.6/75.6 kB\u001b[0m \u001b[31m3.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m2.0/2.0 MB\u001b[0m \u001b[31m48.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m42.6/42.6 kB\u001b[0m \u001b[31m4.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m3.1/3.1 MB\u001b[0m \u001b[31m68.9 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m6.4/6.4 MB\u001b[0m \u001b[31m58.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m77.9/77.9 kB\u001b[0m \u001b[31m9.1 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m58.3/58.3 kB\u001b[0m \u001b[31m5.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m49.6/49.6 kB\u001b[0m \u001b[31m5.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n","\u001b[?25h\u001b[31mERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n","torch 2.2.1+cu121 requires nvidia-cublas-cu12==12.1.3.1; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cuda-cupti-cu12==12.1.105; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cuda-nvrtc-cu12==12.1.105; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cuda-runtime-cu12==12.1.105; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cudnn-cu12==8.9.2.26; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cufft-cu12==11.0.2.54; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-curand-cu12==10.3.2.106; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cusolver-cu12==11.4.5.107; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-cusparse-cu12==12.1.0.106; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-nccl-cu12==2.19.3; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\n","torch 2.2.1+cu121 requires nvidia-nvtx-cu12==12.1.105; platform_system == \"Linux\" and platform_machine == \"x86_64\", which is not installed.\u001b[0m\u001b[31m\n","\u001b[0m"]}]},{"cell_type":"code","source":["import classiq\n","classiq.authenticate()"],"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"enQxfYzrDUtN","executionInfo":{"status":"ok","timestamp":1716212670835,"user_tz":-120,"elapsed":40094,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"df2cf1af-6b54-458e-8eb6-a02caa5e8572"},"execution_count":2,"outputs":[{"output_type":"stream","name":"stdout","text":["Your user code: VZJJ-BHDQ\n","If a browser doesn't automatically open, please visit this URL from any trusted device: https://auth.classiq.io/activate?user_code=VZJJ-BHDQ\n"]}]},{"cell_type":"code","execution_count":3,"metadata":{"id":"7LOSZxZZAgo0","executionInfo":{"status":"ok","timestamp":1716212670836,"user_tz":-120,"elapsed":23,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}}},"outputs":[],"source":["from classiq import *\n","\n","# Define a quantum function using the @qfunc decorator\n","@qfunc\n","def foo(q: QBit) -> None:\n"," X(target=q)\n"," H(target=q)\n","\n","\n","# Define a main function\n","@qfunc\n","def main(res: Output[QBit]) -> None:\n"," allocate(1, res)\n"," foo(q=res)"]},{"cell_type":"markdown","metadata":{"id":"IjgCnTivAgo2"},"source":["Create a model from it, and synthesize, visualize, and execute it.\n","\n","Use the General Instructions above to do so.\n"]},{"cell_type":"code","execution_count":4,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"PFjiFM9lAgo2","executionInfo":{"status":"ok","timestamp":1716212674199,"user_tz":-120,"elapsed":3385,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"344e09da-e2d9-4344-f2ec-e2edf8513726"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/8eabeea1-3414-4298-bde2-d8e5c613ea0f?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","quantum_model = create_model(main)\n","quantum_program = synthesize(quantum_model)\n","show(quantum_program)"]},{"cell_type":"markdown","metadata":{"id":"32EsU1FeAgo3"},"source":["In Qmod `QBit` is the simplest quantum type, and in this example, `q` is a quantum variable of type `QBit`. Quantum variables abstract away the mapping of quantum objects to qubits in the actual circuit.\n","\n","See also [Quantum Variables](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/quantum-variables/).\n","\n","We will discuss other quantum types during the workshop.\n"]},{"cell_type":"markdown","metadata":{"id":"TbyanakdAgo3"},"source":["# The Qmod Workshop - Part 1: Language Fundamentals\n","\n","Follow exercises 1 through 5 for the first session of the workshop."]},{"cell_type":"markdown","metadata":{"id":"N_l2zHdMAgo4"},"source":["## Exercise 1 - Bell Pair\n","\n","Create a function that takes two single-qubit (`QBit`) quantum arguments and prepares the bell state on them ([Bell state](https://en.wikipedia.org/wiki/Bell_state)) by applying `H` on one variable and then using it as the control of a `CX` function with the second variable as the target.\n","Create a main function that uses this function and has two single-qubit outputs, initialize them to the |0> state (using the `allocate` function), and apply your function to them.\n","\n","See also [Functions](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/functions#syntax)\n"]},{"cell_type":"code","execution_count":5,"metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"Rq2bZmvrAgo4","executionInfo":{"status":"ok","timestamp":1716212680358,"user_tz":-120,"elapsed":6164,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"6ec3ec01-35e3-426e-c4e2-5a65f16305c5"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/0aa7325d-eb52-40db-a7b6-b41e8f64c6c8?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def create_bell_pair(q1: QBit, q2: QBit) -> None:\n"," H(target=q1)\n"," CX(control=q1, target=q2)\n","@qfunc\n","def main(res1: Output[QBit], res2: Output[QBit]) -> None:\n"," allocate(1, res1) # Properly allocating qubits\n"," allocate(1, res2) # Properly allocating qubits\n"," create_bell_pair(q1=res1, q2=res2)\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"V6dRtfjJAgo5"},"source":["Use qubit array subscript (the syntax - _variable_ **[** _index-expression_ **]**) to change the function from subsection 1 to receive a single quantum variable, a qubit array (`QArray`) of size 2.\n","Change your main function to declare a single output (also an array of size 2).\n"]},{"cell_type":"code","execution_count":6,"metadata":{"id":"t7qRsO8mAgo5","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212683781,"user_tz":-120,"elapsed":3442,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"040ede1b-6f58-4ce3-882c-d351b0c74bd8"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/f8b71ef5-5673-4534-ad6d-fba105e34063?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def create_bell_pair(qubits: QArray) -> None:\n"," H(target=qubits[0])\n"," CX(control=qubits[0], target=qubits[1])\n","\n","@qfunc\n","def main(res: Output[QArray]) -> None:\n"," allocate(2, res) # Properly allocating qubits\n"," create_bell_pair(qubits=res)\n"," return res\n","\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"hd6lobWyAgo5"},"source":["## Exercise 2 - Repeat\n","\n","Use the built-in `repeat` operator to create your own Hadamard transform function (call it `my_hadamard_transform`). The Hadamard transform function is a function that takes as argument a qubit array of an unspecified size and applies `H` to each of its qubit.\n","\n","See also [Classical repeat](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/classical-control-flow/#classical-repeat).\n","\n","Set your main function to have a quantum array output of unspecified size, allocate 10 qubits, and then apply your Hadamard transform function.\n"]},{"cell_type":"code","execution_count":7,"metadata":{"id":"gL2tJxLKAgo6","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212687317,"user_tz":-120,"elapsed":3568,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"ac841a01-753e-46a1-a840-94e4b864a9b3"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/4326268a-6f0d-4706-88c0-e183ccf0e36a?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def my_hadamard_transform(q: QArray[QBit]) -> None:\n"," repeat(q.len, lambda i: H(q[i]))\n","\n","\n","@qfunc\n","def main(q: Output[QArray[QBit]]) -> None:\n"," allocate(10, q)\n"," my_hadamard_transform(q)\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"rq3Zm7zqAgo6"},"source":["### Note: Quantum Variable Capture\n","The `repeat` operator invokes a statement block multiple times. The statement block is specified using a Python callable, typically a lambda expression. Inside the block you can refer to variables declared in the outer function scope.\n","This concept is called `quantum variable capture`, equivalent to [capture](https://en.wikipedia.org/wiki/Closure_(computer_programming)) in classical languages.\n","\n","See also [Capturing context variables and parameters](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/operators/#capturing-context-variables-and-parameters)."]},{"cell_type":"markdown","metadata":{"id":"H0Oohc4WAgo6"},"source":["## Exercise 3 - Power\n","Raising a quantum operation to a power appears in many known algorithms, for examples, in Grover search and Quantum Phase Estimation.\n","For most operations, it simply means repeating the same circuit multiple times.\n","\n","Sometimes, however, power can be simplified, thus saving computational resources.\n","The most trivial example is a quantum operation expressed as a single explicit unitary matrix (i.e., all n*n matrix terms are given) - raising the operation can be done by raising the matrix to that power via classical programming.\n","\n","See also [Power operator](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/#syntax).\n","\n","Use the following code to generate a 2-qubit (real) unitary matrix:"]},{"cell_type":"code","execution_count":8,"metadata":{"id":"DhnAInaAAgo7","executionInfo":{"status":"ok","timestamp":1716212687318,"user_tz":-120,"elapsed":19,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}}},"outputs":[],"source":["from typing import List\n","\n","import numpy as np\n","\n","from classiq import *\n","\n","rng = np.random.default_rng(seed=0)\n","random_matrix = rng.random((4, 4))\n","qr_unitary, _ = np.linalg.qr(random_matrix)\n","\n","unitary_matrix = QConstant(\"unitary_matrix\", List[List[float]], qr_unitary.tolist())"]},{"cell_type":"markdown","metadata":{"id":"tyBqHvq_Ago7"},"source":["In order to reuse some classical value we can define a `QConstant` to store that value.\n","\n","1. Create a model that applies `unitary_matrix` on a 2 qubit variable.\n","2. Create another model that applies `unitary_matrix` raised to power 3 on a 2 qubit variable.\n","3. Compare the gate count via the Classiq’s IDE in both cases.\n","\n","Note - the signature of function `unitary` is:"]},{"cell_type":"code","execution_count":9,"metadata":{"id":"uDQ4_MtkAgo7","executionInfo":{"status":"ok","timestamp":1716212687318,"user_tz":-120,"elapsed":18,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}}},"outputs":[],"source":["def unitary(\n"," elements: CArray[CArray[CReal]],\n"," target: QArray[QBit],\n",") -> None:\n"," pass"]},{"cell_type":"code","execution_count":10,"metadata":{"id":"vdxrDzCaAgo8","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212695556,"user_tz":-120,"elapsed":8255,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"ed5af99f-0b61-439c-e5c7-e7fa5a269a62"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/291c0291-e5e1-4d50-8dea-44ff23d0d17a?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def main(q: Output[QArray[QBit]]) -> None:\n"," allocate(2, q)\n"," power(3, lambda: unitary(unitary_matrix, q))\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"ompaUAFgAgo8"},"source":["## Exercise 4 - User-defined Operators\n","Create a function that applies a given single-qubit operation to all qubits in its quantum argument (Call your function `my_apply_to_all`). Such a function is also called an operator, i.e. a function that one of its arguments is another function (its operand).\n","\n","See also [Operators](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/operators/).\n","\n","Follow these guidelines:\n","1. Your function should declare a quantum argument of type qubit array. It should also declare an argument of a function type with a single qubit argument.\n","2. The body should apply the operand to all qubits in the argument.\n","\n","When you're done, re-implement `my_hadamard_transform` from exercise 2 using this function instead of `repeat`.\n","Use the same main function from exercise 2."]},{"cell_type":"code","execution_count":11,"metadata":{"id":"b_7lTnWmAgo8","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212702672,"user_tz":-120,"elapsed":7124,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"345c955e-be83-490e-9051-12c1c0e132a4"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/816f1bd0-d3c1-4269-b20b-01b0032d6f67?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def my_apply_to_all(operand: QCallable[QBit], q: QArray[QBit]) -> None:\n"," repeat(q.len, lambda i: operand(q[i]))\n","\n","\n","@qfunc\n","def my_hadamard_transform(q: QArray[QBit]) -> None:\n"," my_apply_to_all(lambda t: H(t), q)\n","\n","\n","@qfunc\n","def main(q: Output[QArray[QBit]]) -> None:\n"," allocate(10, q)\n"," my_hadamard_transform(q)\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"j4dAb5PQAgo8"},"source":["# Exercise 5 - Quantum Conditionals\n","\n","### Exercise 5a - Control Operator\n","Use the built-in `control` operator to create a function that receives two single qubit variables and uses one of the variables to control an RY gate with a `pi/2` angle acting on the other variable (without using the `CRY` function).\n","\n","See also [Quantum operators](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/#syntax).\n"]},{"cell_type":"code","execution_count":12,"metadata":{"id":"1E9kFY1sAgo9","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212706068,"user_tz":-120,"elapsed":3401,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"8461ff20-43d0-4769-dc4e-6e83e1c3706e"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/7d3e3443-19e3-4b71-b5a9-5f5088005a9b?version=0.41.1\n"]}],"source":["from classiq import *\n","from classiq.qmod.symbolic import pi\n","\n","@qfunc\n","def my_controlled_ry(control_bit: QBit, target: QBit) -> None:\n"," control(control_bit, lambda: RY(pi / 2, target))\n","\n","\n","@qfunc\n","def main(control_bit: Output[QBit], target: Output[QBit]) -> None:\n"," allocate(1, control_bit)\n"," allocate(1, target)\n"," my_controlled_ry(control_bit, target)\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]},{"cell_type":"markdown","metadata":{"id":"ReKCKMQPAgo9"},"source":["### Exercise 5b - Control (\"Quantum If\")\n","The `control` operator is the conditional application of some operation, with the condition being that all control qubits are in the state |1>. This notion is generalized in QMOD to other control states, where the condition is specified as a comparison between a quantum numeric variable and a numeric value, similar to a classical `if` statement. Quantum numeric variables are declared with class `QNum`.\n","\n","See also [Numeric types](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/quantum-types/#syntax).\n","\n","In QMOD this generalization is available as a native statement - control.\n","\n","See also [control](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/).\n","\n","1. Declare a `QNum` output argument using `Output[QNum]` and name it `x`.\n","2. Use the `prepare_int` function to initialize it to `9`. Note that you don't need to specify the `QNum` attributes - size, sign, and fraction digits, as they are inferred at the point of initialization.\n","3. Execute the circuit and observe the results.\n","4. Declare another output argument of type `QBit` and perform a `control` such that under the condition that `x` is 9, the qubit is flipped. Execute the circuit and observe the results. Repeat for a different condition."]},{"cell_type":"code","execution_count":13,"metadata":{"id":"tISW82ILAgo9","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1716212713430,"user_tz":-120,"elapsed":7382,"user":{"displayName":"Christos Koromilas","userId":"17599903479737751299"}},"outputId":"e23bf946-2b7e-4511-ec24-a380004da7ad"},"outputs":[{"output_type":"stream","name":"stdout","text":["Opening: https://platform.classiq.io/circuit/b6600985-72b5-46b8-a02d-bff53d677218?version=0.41.1\n"]}],"source":["from classiq import *\n","\n","@qfunc\n","def main(x: Output[QNum], target: Output[QBit]) -> None:\n"," prepare_int(9, x)\n"," allocate(1, target)\n"," control(x == 9, lambda: X(target))\n","\n","qmod = create_model(main)\n","qprog = synthesize(qmod)\n","show(qprog)"]}],"metadata":{"kernelspec":{"display_name":"Python 3 (ipykernel)","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.11.8"},"colab":{"provenance":[]}},"nbformat":4,"nbformat_minor":0} \ No newline at end of file +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# The Qmod Workshop - Introduction\n", + "\n", + "The Classiq platform features a high-level quantum modeling language called Qmod. Qmod is compiled into concrete gate-level implementation using a powerful synthesis engine that optimizes and adapts the implementation to different target hardware/simulation environments.\n", + "\n", + "In this workshop, we will learn how to write quantum models using Qmod. We will be using the Python embedding of Qmod, available as part of the Classiq Python SDK. We will learn basic concepts in the Qmod language, such as functions, operators, quantum variables, and quantum types. We will develop useful building blocks and small algorithms.\n", + "\n", + "The [QMOD language reference](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/) covers these concepts more systematically and includes more examples.\n", + "\n", + "This workshop consists of step-by-step exercises. It is structured as follows:\n", + "\n", + "- Part 1: Language Fundamentals - Exercises 1-5\n", + "- Part 2: Higher-Level Concepts - Exercises 6-10\n", + "- Part 3: Execution Flows - Exercises 11, 12\n", + "\n", + "The introduction and Part 1 are included in this notebook. Part 2 and 3 are each in its own separate notebook. For each exercise you will find the solution to the exercises at the bottom of the same notebook.\n", + "\n", + "### Preparations\n", + "\n", + "Make sure you have a Python version of 3.8 through 3.11 installed. Unfortunately, Classiq is not yet supported with Python 3.12.\n", + "\n", + "Install Classiq’s Python SDK by following the instructions on this page: [Getting Started - Classiq](https://docs.classiq.io/latest/getting-started/).\n", + "\n", + "### Python Qmod Exercises - General Instructions\n", + "\n", + "In order to synthesize and execute your Qmod code, you should:\n", + "1. Make sure you define a `main` function that calls functions you create.\n", + "2. Use `create_model` by running `qmod = create_model(main)` to construct a representation of your model.\n", + "3. You can synthesize the model (using `qprog = synthesize(qmod)`) to obtain an implementation - a quantum program.\n", + "4. You can then visualize the quantum program (`show(qprog)`) or execute it (using `execute(qprog)`. See: [Execution - Classiq](https://docs.classiq.io/latest/user-guide/platform/executor/#full-example)). You can also execute it with the IDE after visualizing the circuit.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 0: From Model to Execution\n", + "\n", + "The following model defines a function that applies X and H gates on a single qubit, and subsequently calls it:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "ERROR: pip's dependency resolver does not currently take into account all the packages that are installed. This behaviour is the source of the following dependency conflicts.\n", + "dwave-cloud-client 0.11.4 requires pydantic<3,>=2, but you have pydantic 1.10.16 which is incompatible.\n", + "poetry 1.8.3 requires keyring<25.0.0,>=24.0.0, but you have keyring 23.13.1 which is incompatible.\n", + "poetry 1.8.3 requires packaging>=23.1, but you have packaging 22.0 which is incompatible.\n" + ] + } + ], + "source": [ + "!pip install -U -q classiq" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Your user code: LMFG-TPCJ\n", + "If a browser doesn't automatically open, please visit this URL from any trusted device: https://auth.classiq.io/activate?user_code=LMFG-TPCJ\n" + ] + } + ], + "source": [ + "import classiq\n", + "classiq.authenticate()" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "from classiq import *\n", + "\n", + "\n", + "# Define a quantum function using the @qfunc decorator\n", + "@qfunc\n", + "def foo(q: QBit) -> None:\n", + " X(target=q)\n", + " H(target=q)\n", + "\n", + "\n", + "# Define a main function\n", + "@qfunc\n", + "def main(res: Output[QBit]) -> None:\n", + " allocate(1, res)\n", + " foo(q=res)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Create a model from it, and synthesize, visualize, and execute it.\n", + "\n", + "Use the General Instructions above to do so.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/7e889e54-69b5-4ee1-9572-7b13e0343234?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "quantum_model = create_model(main)\n", + "quantum_program = synthesize(quantum_model)\n", + "show(quantum_program)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In Qmod `QBit` is the simplest quantum type, and in this example, `q` is a quantum variable of type `QBit`. Quantum variables abstract away the mapping of quantum objects to qubits in the actual circuit.\n", + "\n", + "See also [Quantum Variables](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/quantum-variables/).\n", + "\n", + "We will discuss other quantum types during the workshop.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# The Qmod Workshop - Part 1: Language Fundamentals\n", + "\n", + "Follow exercises 1 through 5 for the first session of the workshop." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 1 - Bell Pair\n", + "\n", + "Create a function that takes two single-qubit (`QBit`) quantum arguments and prepares the bell state on them ([Bell state](https://en.wikipedia.org/wiki/Bell_state)) by applying `H` on one variable and then using it as the control of a `CX` function with the second variable as the target.\n", + "Create a main function that uses this function and has two single-qubit outputs, initialize them to the |0> state (using the `allocate` function), and apply your function to them.\n", + "\n", + "See also [Functions](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/functions#syntax)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/eb04c776-477b-45ba-8ba1-ee5c996e7965?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def create_bell_pair(q1: QBit, q2: QBit) -> None:\n", + " H(target=q1)\n", + " CX(control=q1, target=q2)\n", + "@qfunc\n", + "def main(res1: Output[QBit], res2: Output[QBit]) -> None:\n", + " allocate(1, res1) \n", + " allocate(1, res2) \n", + " create_bell_pair(q1=res1, q2=res2)\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use qubit array subscript (the syntax - _variable_ **[** _index-expression_ **]**) to change the function from subsection 1 to receive a single quantum variable, a qubit array (`QArray`) of size 2.\n", + "Change your main function to declare a single output (also an array of size 2).\n" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/5f7efea8-6c98-47db-98b3-05e067722517?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def create_bell_pair(qubits: QArray) -> None:\n", + " H(target=qubits[0])\n", + " CX(control=qubits[0], target=qubits[1])\n", + "\n", + "@qfunc\n", + "def main(res: Output[QArray]) -> None:\n", + " allocate(2, res) # Properly allocating qubits\n", + " create_bell_pair(qubits=res)\n", + " return res\n", + "\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 2 - Repeat\n", + "\n", + "Use the built-in `repeat` operator to create your own Hadamard transform function (call it `my_hadamard_transform`). The Hadamard transform function is a function that takes as argument a qubit array of an unspecified size and applies `H` to each of its qubit.\n", + "\n", + "See also [Classical repeat](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/classical-control-flow/#classical-repeat).\n", + "\n", + "Set your main function to have a quantum array output of unspecified size, allocate 10 qubits, and then apply your Hadamard transform function.\n" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/3be67af9-6bb3-4314-8686-e2e6dfe4df27?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def my_hadamard_transform(q: QArray[QBit]) -> None:\n", + " repeat(q.len, lambda i: H(q[i]))\n", + "\n", + "\n", + "@qfunc\n", + "def main(q: Output[QArray[QBit]]) -> None:\n", + " allocate(10, q)\n", + " my_hadamard_transform(q)\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Note: Quantum Variable Capture\n", + "The `repeat` operator invokes a statement block multiple times. The statement block is specified using a Python callable, typically a lambda expression. Inside the block you can refer to variables declared in the outer function scope.\n", + "This concept is called `quantum variable capture`, equivalent to [capture](https://en.wikipedia.org/wiki/Closure_(computer_programming)) in classical languages.\n", + "\n", + "See also [Capturing context variables and parameters](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/operators/#capturing-context-variables-and-parameters)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 3 - Power\n", + "Raising a quantum operation to a power appears in many known algorithms, for examples, in Grover search and Quantum Phase Estimation.\n", + "For most operations, it simply means repeating the same circuit multiple times.\n", + "\n", + "Sometimes, however, power can be simplified, thus saving computational resources.\n", + "The most trivial example is a quantum operation expressed as a single explicit unitary matrix (i.e., all n*n matrix terms are given) - raising the operation can be done by raising the matrix to that power via classical programming.\n", + "\n", + "See also [Power operator](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/#syntax).\n", + "\n", + "Use the following code to generate a 2-qubit (real) unitary matrix:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "from typing import List\n", + "\n", + "import numpy as np\n", + "\n", + "from classiq import *\n", + "\n", + "rng = np.random.default_rng(seed=0)\n", + "random_matrix = rng.random((4, 4))\n", + "qr_unitary, _ = np.linalg.qr(random_matrix)\n", + "\n", + "unitary_matrix = QConstant(\"unitary_matrix\", List[List[float]], qr_unitary.tolist())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In order to reuse some classical value we can define a `QConstant` to store that value.\n", + "\n", + "1. Create a model that applies `unitary_matrix` on a 2 qubit variable.\n", + "2. Create another model that applies `unitary_matrix` raised to power 3 on a 2 qubit variable.\n", + "3. Compare the gate count via the Classiq’s IDE in both cases.\n", + "\n", + "Note - the signature of function `unitary` is:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def unitary(\n", + " elements: CArray[CArray[CReal]],\n", + " target: QArray[QBit],\n", + ") -> None:\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/0036f036-0ede-44f5-aa3f-6b876d08467a?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def main(q: Output[QArray[QBit]]) -> None:\n", + " allocate(2, q)\n", + " power(3, lambda: unitary(unitary_matrix, q))\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exercise 4 - User-defined Operators\n", + "Create a function that applies a given single-qubit operation to all qubits in its quantum argument (Call your function `my_apply_to_all`). Such a function is also called an operator, i.e. a function that one of its arguments is another function (its operand).\n", + "\n", + "See also [Operators](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/operators/).\n", + "\n", + "Follow these guidelines:\n", + "1. Your function should declare a quantum argument of type qubit array. It should also declare an argument of a function type with a single qubit argument.\n", + "2. The body should apply the operand to all qubits in the argument.\n", + "\n", + "When you're done, re-implement `my_hadamard_transform` from exercise 2 using this function instead of `repeat`.\n", + "Use the same main function from exercise 2." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/ba045335-2706-4ee2-80df-8886f1cf67b4?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def my_apply_to_all(operand: QCallable[QBit], q: QArray[QBit]) -> None:\n", + " repeat(q.len, lambda i: operand(q[i]))\n", + "\n", + "\n", + "@qfunc\n", + "def my_hadamard_transform(q: QArray[QBit]) -> None:\n", + " my_apply_to_all(lambda t: H(t), q)\n", + "\n", + "\n", + "@qfunc\n", + "def main(q: Output[QArray[QBit]]) -> None:\n", + " allocate(10, q)\n", + " my_hadamard_transform(q)\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Exercise 5 - Quantum Conditionals\n", + "\n", + "### Exercise 5a - Control Operator\n", + "Use the built-in `control` operator to create a function that receives two single qubit variables and uses one of the variables to control an RY gate with a `pi/2` angle acting on the other variable (without using the `CRY` function).\n", + "\n", + "See also [Quantum operators](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/#syntax).\n" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/43018914-1bb0-4c33-b819-538d648255f6?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "from classiq.qmod.symbolic import pi\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def my_controlled_ry(control_bit: QBit, target: QBit) -> None:\n", + " control(control_bit, lambda: RY(pi / 2, target))\n", + "\n", + "\n", + "@qfunc\n", + "def main(control_bit: Output[QBit], target: Output[QBit]) -> None:\n", + " allocate(1, control_bit)\n", + " allocate(1, target)\n", + " my_controlled_ry(control_bit, target)\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Exercise 5b - Control (\"Quantum If\")\n", + "The `control` operator is the conditional application of some operation, with the condition being that all control qubits are in the state |1>. This notion is generalized in QMOD to other control states, where the condition is specified as a comparison between a quantum numeric variable and a numeric value, similar to a classical `if` statement. Quantum numeric variables are declared with class `QNum`.\n", + "\n", + "See also [Numeric types](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/quantum-types/#syntax).\n", + "\n", + "In QMOD this generalization is available as a native statement - control.\n", + "\n", + "See also [control](https://docs.classiq.io/latest/user-guide/platform/qmod/language-reference/statements/quantum-operators/).\n", + "\n", + "1. Declare a `QNum` output argument using `Output[QNum]` and name it `x`.\n", + "2. Use the `prepare_int` function to initialize it to `9`. Note that you don't need to specify the `QNum` attributes - size, sign, and fraction digits, as they are inferred at the point of initialization.\n", + "3. Execute the circuit and observe the results.\n", + "4. Declare another output argument of type `QBit` and perform a `control` such that under the condition that `x` is 9, the qubit is flipped. Execute the circuit and observe the results. Repeat for a different condition." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Opening: https://platform.classiq.io/circuit/2682e185-f4bf-4ff7-a21a-37ddca29e45e?version=0.42.1\n" + ] + } + ], + "source": [ + "from classiq import *\n", + "\n", + "# Your code here:\n", + "\n", + "@qfunc\n", + "def main(x: Output[QNum], target: Output[QBit]) -> None:\n", + " prepare_int(9, x)\n", + " allocate(1, target)\n", + " control(x == 9, lambda: X(target))\n", + "\n", + "qmod = create_model(main)\n", + "qprog = synthesize(qmod)\n", + "show(qprog)" + ] + } + ], + "metadata": { + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.11.9" + } + }, + "nbformat": 4, + "nbformat_minor": 4 +}