1{
2 "cells": [
3  {
4   "cell_type": "markdown",
5   "metadata": {
6    "id": "7FV_m2u2Hny8"
7   },
8   "source": [
9    "##### Copyright 2020 The Cirq Developers"
10   ]
11  },
12  {
13   "cell_type": "code",
14   "execution_count": null,
15   "metadata": {
16    "cellView": "form",
17    "id": "2XSh1-J7HrcU"
18   },
19   "outputs": [],
20   "source": [
21    "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
22    "# you may not use this file except in compliance with the License.\n",
23    "# You may obtain a copy of the License at\n",
24    "#\n",
25    "# https://www.apache.org/licenses/LICENSE-2.0\n",
26    "#\n",
27    "# Unless required by applicable law or agreed to in writing, software\n",
28    "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
29    "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
30    "# See the License for the specific language governing permissions and\n",
31    "# limitations under the License."
32   ]
33  },
34  {
35   "cell_type": "markdown",
36   "metadata": {
37    "id": "Me7G0WVTHwHg"
38   },
39   "source": [
40    "# Cirq basics"
41   ]
42  },
43  {
44   "cell_type": "markdown",
45   "metadata": {
46    "id": "aAFfDwu7IFyx"
47   },
48   "source": [
49    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
50    "  <td>\n",
51    "    <a target=\"_blank\" href=\"https://quantumai.google/cirq/tutorials/basics\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
52    "  </td>\n",
53    "  <td>\n",
54    "    <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
55    "  </td>\n",
56    "  <td>\n",
57    "    <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/master/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
58    "  </td>\n",
59    "  <td>\n",
60    "    <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/tutorials/basics.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
61    "  </td>\n",
62    "</table>"
63   ]
64  },
65  {
66   "cell_type": "markdown",
67   "metadata": {
68    "id": "67gUU740MSXd"
69   },
70   "source": [
71    "This tutorial will teach the basics of how to use Cirq.  This tutorial will walk through how to use qubits, gates, and operations to create and simulate your first quantum circuit using Cirq.  It will briefly introduce devices, unitary matrices, decompositions, and optimizers.\n",
72    "\n",
73    "This tutorial isn’t a quantum computing 101 tutorial, we assume familiarity of quantum computing at about the level of the textbook “Quantum Computation and Quantum Information” by Nielsen and Chuang.\n",
74    "\n",
75    "For more in-depth examples closer to those found in current work, check out our tutorials page."
76   ]
77  },
78  {
79   "cell_type": "markdown",
80   "metadata": {
81    "id": "1dOjJlgrNUuz"
82   },
83   "source": [
84    "To begin, please follow the instructions for [installing Cirq](../install.md)."
85   ]
86  },
87  {
88   "cell_type": "code",
89   "execution_count": null,
90   "metadata": {
91    "id": "bd9529db1c0b"
92   },
93   "outputs": [],
94   "source": [
95    "try:\n",
96    "    import cirq\n",
97    "except ImportError:\n",
98    "    print(\"installing cirq...\")\n",
99    "    !pip install --quiet cirq\n",
100    "    print(\"installed cirq.\")"
101   ]
102  },
103  {
104   "cell_type": "markdown",
105   "metadata": {
106    "id": "xr-MMoXgNsUQ"
107   },
108   "source": [
109    "## Qubits\n",
110    "\n",
111    "The first part of creating a quantum circuit is to define a set of qubits (also known as a quantum registers) to act on.\n",
112    "\n",
113    "Cirq has three main ways of defining qubits:\n",
114    "\n",
115    "*   `cirq.NamedQubit`: used to label qubits by an abstract name\n",
116    "*   `cirq.LineQubit`: qubits labelled by number in a linear array \n",
117    "*   `cirq.GridQubit`: qubits labelled by two numbers in a rectangular lattice.\n",
118    "\n",
119    "Here are some examples of defining each type of qubit."
120   ]
121  },
122  {
123   "cell_type": "code",
124   "execution_count": null,
125   "metadata": {
126    "id": "PsgSo-H0Os8X"
127   },
128   "outputs": [],
129   "source": [
130    "import cirq\n",
131    "import cirq_google\n",
132    "\n",
133    "# Using named qubits can be useful for abstract algorithms\n",
134    "# as well as algorithms not yet mapped onto hardware.\n",
135    "q0 = cirq.NamedQubit('source')\n",
136    "q1 = cirq.NamedQubit('target')\n",
137    "\n",
138    "# Line qubits can be created individually\n",
139    "q3 = cirq.LineQubit(3)\n",
140    "\n",
141    "# Or created in a range\n",
142    "# This will create LineQubit(0), LineQubit(1), LineQubit(2)\n",
143    "q0, q1, q2 = cirq.LineQubit.range(3)\n",
144    "\n",
145    "# Grid Qubits can also be referenced individually\n",
146    "q4_5 = cirq.GridQubit(4,5)\n",
147    "\n",
148    "# Or created in bulk in a square\n",
149    "# This will create 16 qubits from (0,0) to (3,3)\n",
150    "qubits = cirq.GridQubit.square(4)"
151   ]
152  },
153  {
154   "cell_type": "markdown",
155   "metadata": {
156    "id": "4zE6AutyQhQ6"
157   },
158   "source": [
159    "There are also pre-packaged sets of qubits called [Devices](../devices.md).  These are qubits along with a set of rules of how they can be used.  A `cirq.Device` can be used to apply adjacency rules and other hardware constraints to a quantum circuit.  For our example, we will use the `cirq_google.Foxtail` device that comes with cirq.  It is a 2x11 grid that mimics early hardware released by Google."
160   ]
161  },
162  {
163   "cell_type": "code",
164   "execution_count": null,
165   "metadata": {
166    "id": "B0Dwgu-lQLpq"
167   },
168   "outputs": [
169    {
170     "name": "stdout",
171     "output_type": "stream",
172     "text": [
173      "(0, 0)───(0, 1)───(0, 2)───(0, 3)───(0, 4)───(0, 5)───(0, 6)───(0, 7)───(0, 8)───(0, 9)───(0, 10)\n",
174      "│        │        │        │        │        │        │        │        │        │        │\n",
175      "│        │        │        │        │        │        │        │        │        │        │\n",
176      "(1, 0)───(1, 1)───(1, 2)───(1, 3)───(1, 4)───(1, 5)───(1, 6)───(1, 7)───(1, 8)───(1, 9)───(1, 10)\n"
177     ]
178    }
179   ],
180   "source": [
181    "print(cirq_google.Foxtail)"
182   ]
183  },
184  {
185   "cell_type": "markdown",
186   "metadata": {
187    "id": "j1QTjyxLSe5c"
188   },
189   "source": [
190    "## Gates and operations\n",
191    "\n",
192    "The next step is to use the qubits to create operations that can be used in our circuit.  Cirq has two concepts that are important to understand here:\n",
193    "\n",
194    "*   A `Gate` is an effect that can be applied to a set of qubits.  \n",
195    "*   An `Operation` is a gate applied to a set of qubits.\n",
196    "\n",
197    "For instance, `cirq.H` is the quantum [Hadamard](https://en.wikipedia.org/wiki/Quantum_logic_gate#Hadamard_(H)_gate) and is a `Gate` object.  `cirq.H(cirq.LineQubit(1))` is an `Operation` object and is the Hadamard gate applied to a specific qubit (line qubit number 1).\n",
198    "\n",
199    "Many textbook gates are included within cirq.  `cirq.X`, `cirq.Y`, and `cirq.Z` refer to the single-qubit Pauli gates.  `cirq.CZ`, `cirq.CNOT`, `cirq.SWAP` are a few of the common two-qubit gates.  `cirq.measure` is a macro to apply a `MeasurementGate` to a set of qubits.  You can find more, as well as instructions on how to creats your own custom gates, on the [Gates documentation](../gates.ipynb) page.\n",
200    "\n",
201    "Many arithmetic operations can also be applied to gates.  Here are some examples:"
202   ]
203  },
204  {
205   "cell_type": "code",
206   "execution_count": null,
207   "metadata": {
208    "id": "wDW-yU-fesDl"
209   },
210   "outputs": [],
211   "source": [
212    "# Example gates\n",
213    "not_gate = cirq.CNOT\n",
214    "pauli_z = cirq.Z\n",
215    "\n",
216    "# Using exponentiation to get square root gates\n",
217    "sqrt_x_gate = cirq.X**0.5\n",
218    "\n",
219    "# Some gates can also take parameters\n",
220    "sqrt_sqrt_y = cirq.YPowGate(exponent=0.25)\n",
221    "\n",
222    "# Example operations\n",
223    "q0, q1 = cirq.LineQubit.range(2)\n",
224    "z_op = cirq.Z(q0)\n",
225    "not_op = cirq.CNOT(q0, q1)\n",
226    "sqrt_iswap_op = cirq.SQRT_ISWAP(q0, q1)"
227   ]
228  },
229  {
230   "cell_type": "markdown",
231   "metadata": {
232    "id": "BnBGLMVvWVkz"
233   },
234   "source": [
235    "## Circuits and moments\n",
236    "\n",
237    "We are now ready to construct a quantum circuit.  A `Circuit` is a collection of `Moment`s. A `Moment` is a collection of `Operation`s that all act during the same abstract time slice.  Each `Operation` must have a disjoint set of qubits from the other `Operation`s in the `Moment`.  A `Moment` can be thought of as a vertical slice of a quantum circuit diagram.\n",
238    "\n",
239    "Circuits can be constructed in several different ways.  By default, cirq will attempt to slide your operation into the earliest possible `Moment` when you insert it.\n"
240   ]
241  },
242  {
243   "cell_type": "code",
244   "execution_count": null,
245   "metadata": {
246    "id": "HEuqEZcXkz3Q"
247   },
248   "outputs": [
249    {
250     "name": "stdout",
251     "output_type": "stream",
252     "text": [
253      "0: ───H───\n",
254      "\n",
255      "1: ───H───\n",
256      "\n",
257      "2: ───H───\n"
258     ]
259    }
260   ],
261   "source": [
262    "circuit = cirq.Circuit()\n",
263    "# You can create a circuit by appending to it\n",
264    "circuit.append(cirq.H(q) for q in cirq.LineQubit.range(3))\n",
265    "# All of the gates are put into the same Moment since none overlap\n",
266    "print(circuit)"
267   ]
268  },
269  {
270   "cell_type": "code",
271   "execution_count": null,
272   "metadata": {
273    "id": "Lbez4guQl31P"
274   },
275   "outputs": [
276    {
277     "name": "stdout",
278     "output_type": "stream",
279     "text": [
280      "0: ───×───────────\n",
281      "      │\n",
282      "1: ───×───×───────\n",
283      "          │\n",
284      "2: ───────×───×───\n",
285      "              │\n",
286      "3: ───────────×───\n"
287     ]
288    }
289   ],
290   "source": [
291    "# We can also create a circuit directly as well:\n",
292    "print(cirq.Circuit(cirq.SWAP(q, q+1) for q in cirq.LineQubit.range(3)))"
293   ]
294  },
295  {
296   "cell_type": "markdown",
297   "metadata": {
298    "id": "3FC9bdlXmShh"
299   },
300   "source": [
301    "Sometimes, you may not want cirq to automatically shift operations all the way to the left.  To construct a circuit without doing this, you can create the circuit moment-by-moment or use a different `InsertStrategy`, explained more in the [Circuit documentation](../circuits.ipynb)."
302   ]
303  },
304  {
305   "cell_type": "code",
306   "execution_count": null,
307   "metadata": {
308    "id": "4AEahodTnYiI"
309   },
310   "outputs": [
311    {
312     "name": "stdout",
313     "output_type": "stream",
314     "text": [
315      "0: ───H───────────\n",
316      "\n",
317      "1: ───────H───────\n",
318      "\n",
319      "2: ───────────H───\n"
320     ]
321    }
322   ],
323   "source": [
324    "# Creates each gate in a separate moment.\n",
325    "print(cirq.Circuit(cirq.Moment([cirq.H(q)]) for q in cirq.LineQubit.range(3)))"
326   ]
327  },
328  {
329   "cell_type": "markdown",
330   "metadata": {
331    "id": "j406AKYsobpq"
332   },
333   "source": [
334    "### Circuits and devices\n",
335    "\n",
336    "One important consideration when using real quantum devices is that there are often hardware constraints on the circuit.  Creating a circuit with a `Device` will allow you to capture some of these requirements.  These `Device` objects will validate the operations you add to the circuit to make sure that no illegal operations are added.\n",
337    "\n",
338    "Let's look at an example using the Foxtail device."
339   ]
340  },
341  {
342   "cell_type": "code",
343   "execution_count": null,
344   "metadata": {
345    "id": "9UV-dXJOpy8B"
346   },
347   "outputs": [
348    {
349     "name": "stdout",
350     "output_type": "stream",
351     "text": [
352      "Unconstrained device:\n",
353      "(0, 0): ───@───@───\n",
354      "           │   │\n",
355      "(0, 1): ───@───┼───\n",
356      "               │\n",
357      "(0, 2): ───────@───\n",
358      "\n",
359      "Foxtail device:\n",
360      "Not allowed. Non-local interaction: cirq.CZ.on(cirq.GridQubit(0, 0), cirq.GridQubit(0, 2)).\n"
361     ]
362    }
363   ],
364   "source": [
365    "q0 = cirq.GridQubit(0, 0)\n",
366    "q1 = cirq.GridQubit(0, 1)\n",
367    "q2 = cirq.GridQubit(0, 2)\n",
368    "adjacent_op = cirq.CZ(q0, q1)\n",
369    "nonadjacent_op = cirq.CZ(q0, q2)\n",
370    "\n",
371    "# This is an unconstrained circuit with no device\n",
372    "free_circuit = cirq.Circuit()\n",
373    "# Both operations are allowed:\n",
374    "free_circuit.append(adjacent_op)\n",
375    "free_circuit.append(nonadjacent_op)\n",
376    "print('Unconstrained device:')\n",
377    "print(free_circuit)\n",
378    "print()\n",
379    "\n",
380    "# This is a circuit on the Foxtail device\n",
381    "# only adjacent operations are allowed.\n",
382    "print('Foxtail device:')\n",
383    "foxtail_circuit = cirq.Circuit(device=cirq_google.Foxtail)\n",
384    "foxtail_circuit.append(adjacent_op)\n",
385    "try:\n",
386    "    # Not allowed, will throw exception\n",
387    "    foxtail_circuit.append(nonadjacent_op)\n",
388    "except ValueError as e:\n",
389    "    print('Not allowed. %s' % e)\n"
390   ]
391  },
392  {
393   "cell_type": "markdown",
394   "metadata": {
395    "id": "xZ68bWEjoMKt"
396   },
397   "source": [
398    "## Simulation\n",
399    "\n",
400    "The results of the application of a quantum circuit can be calculated by a `Simulator`.  Cirq comes bundled with a simulator that can calculate the results of circuits up to about a limit of 20 qubits.  It can be initialized with `cirq.Simulator()`.\n",
401    "\n",
402    "There are two different approaches to using a simulator:\n",
403    "\n",
404    "*   `simulate()`:  Since we are classically simulating a circuit, a simulator can directly access and view the resulting wave function.  This is useful for debugging, learning, and understanding how circuits will function.  \n",
405    "*   `run()`:  When using actual quantum devices, we can only access the end result of a computation and must sample the results to get a distribution of results.  Running the simulator as a sampler mimics this behavior and only returns bit strings as output.\n",
406    "\n",
407    "Let's try to simulate a 2-qubit \"Bell State\":"
408   ]
409  },
410  {
411   "cell_type": "code",
412   "execution_count": null,
413   "metadata": {
414    "id": "AwC4SL6CHpXm"
415   },
416   "outputs": [
417    {
418     "name": "stdout",
419     "output_type": "stream",
420     "text": [
421      "Simulate the circuit:\n",
422      "measurements: (no measurements)\n",
423      "output vector: 0.707|00⟩ + 0.707|11⟩\n",
424      "\n",
425      "Sample the circuit:\n",
426      "Counter({3: 537, 0: 463})\n"
427     ]
428    }
429   ],
430   "source": [
431    "# Create a circuit to generate a Bell State:\n",
432    "# 1/sqrt(2) * ( |00⟩ + |11⟩ )\n",
433    "bell_circuit = cirq.Circuit()\n",
434    "q0, q1 = cirq.LineQubit.range(2)\n",
435    "bell_circuit.append(cirq.H(q0))\n",
436    "bell_circuit.append(cirq.CNOT(q0,q1))\n",
437    "\n",
438    "# Initialize Simulator\n",
439    "s=cirq.Simulator()\n",
440    "\n",
441    "print('Simulate the circuit:')\n",
442    "results=s.simulate(bell_circuit)\n",
443    "print(results)\n",
444    "print()\n",
445    "\n",
446    "# For sampling, we need to add a measurement at the end\n",
447    "bell_circuit.append(cirq.measure(q0, q1, key='result'))\n",
448    "\n",
449    "print('Sample the circuit:')\n",
450    "samples=s.run(bell_circuit, repetitions=1000)\n",
451    "# Print a histogram of results\n",
452    "print(samples.histogram(key='result'))"
453   ]
454  },
455  {
456   "cell_type": "markdown",
457   "metadata": {
458    "id": "06Q_7vlQSu4Z"
459   },
460   "source": [
461    "### Using parameter sweeps\n",
462    "\n",
463    "Cirq circuits allow for gates to have symbols as free parameters within the circuit.  This is especially useful for variational algorithms, which vary parameters within the circuit in order to optimize a cost function, but it can be useful in a variety of circumstances.\n",
464    "\n",
465    "For parameters, cirq uses the library `sympy` to add `sympy.Symbol` as parameters to gates and operations.  \n",
466    "\n",
467    "Once the circuit is complete, you can fill in the possible values of each of these parameters with a `Sweep`.  There are several possibilities that can be used as a sweep:\n",
468    "\n",
469    "*   `cirq.Points`: A list of manually specified values for one specific symbol as a sequence of floats\n",
470    "*   `cirq.Linspace`: A linear sweep from a starting value to an ending value.\n",
471    "*   `cirq.ListSweep`: A list of manually specified values for several different symbols, specified as a list of dictionaries.\n",
472    "*   `cirq.Zip` and `cirq.Product`: Sweeps can be combined list-wise by zipping them together or through their Cartesian product.\n",
473    "\n",
474    "A parameterized circuit and sweep together can be run using the simulator or other sampler by changing `run()` to `run_sweep()` and adding the sweep as a parameter.\n",
475    "\n",
476    "Here is an example of sweeping an exponent of a X gate:"
477   ]
478  },
479  {
480   "cell_type": "code",
481   "execution_count": null,
482   "metadata": {
483    "id": "ElyizofbLGq9"
484   },
485   "outputs": [
486    {
487     "data": {
488      "text/plain": [
489       "<matplotlib.collections.PathCollection at 0x7f54d6c1d320>"
490      ]
491     },
492     "execution_count": 63,
493     "metadata": {
494      "tags": []
495     },
496     "output_type": "execute_result"
497    },
498    {
499     "data": {
500      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAXQAAAD4CAYAAAD8Zh1EAAAABHNCSVQICAgIfAhkiAAAAAlwSFlzAAALEgAACxIB0t1+/AAAADh0RVh0U29mdHdhcmUAbWF0cGxvdGxpYiB2ZXJzaW9uMy4yLjEsIGh0dHA6Ly9tYXRwbG90bGliLm9yZy+j8jraAAAgAElEQVR4nO3dcZCc9X3f8fdXx2JOtsvJlTI1C1hiSkRRFHT2jUOtTGqIgzApcMU2guAZk5DQtMUTML2ZY8wgodJBqYaCO2WaUo+ndUKNBKY7csAjuRWezMgR4eQ7WRa2HBkbocVTLraO1L4zOp2+/WP3gUd7zz777O2zu88++3nNMNzu89ztT889+73ffn/f3+9n7o6IiPS+Zd1ugIiIpEMBXUQkJxTQRURyQgFdRCQnFNBFRHLinG698MqVK3316tXdenkRkZ508ODBv3P3VVHHuhbQV69ezcTERLdeXkSkJ5nZq/WOKeUiIpITCugiIjmhgC4ikhMK6CIiOaGALiKSEw2rXMzsS8A/B95w91+LOG7AF4DrgFngdnf/dtoNFWmH0mSZrbuPMDM3H3veMoMzDsWhQcY2rWV0uNihFookZ41WWzSz3wJ+Dny5TkC/DvgslYD+G8AX3P03Gr3wyMiIq2xRuiFpEG9EwV26wcwOuvtI1LGGPXR3/yszWx1zyo1Ugr0DB8xsyMze7+4/WVJrRdogrSAeVp6Z456dU0y8+jMeGl2f2s8VWao0cuhF4LXQ4xPV5xYxszvNbMLMJqanp1N4aZHGSpNlxp4+lGowDzjw5IHjlCbLqf9skWZ1dKaouz8BPAGVlEsnX1v6S2myzI49R3l9Zo5lZiy0cSMXB+7eOcXndk0pzy5dlUYPvQxcFHp8YfU5ka64v3SYe3ZOUZ6Zw6GtwTzsTPVlyjNz3L1ziuFte9Vzl45Ko4e+G7jLzJ6iMij6pvLn0g3ty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fS4T18vMllMJjF8NPd32a2aVVPAw8GLNobbeXx3dJLofmNmngRHgn4We/oC7l83sEmCfmR129x92qElfA77i7m+Z2b+k8unm6g69dhK3AM+4e3iz2G5er8wys6uoBPTfDD39m9Vr9SvAN8zs+9Xea6d8m8rv6+dW2dmsBFzawddv5Hpgv7uHe/NtvWZm9h4qf0Dudve/T+vnJpG1HnozG1JjZ29IneR729kuzOxjwOeBG9z9reB5dy9X//8K8E0qf7k70i53/2moLV8EPpT0e9vZrpBbqPk43MbrlUS9trfzejVkZr9O5fd3o7u/vQF76Fq9Afwv0kszJuLuf+/uP69+/TxQMLOVdPl6hcTdXyt6wSgAAAGvSURBVKlfMzMrUAnmT7r7sxGntPf+SntgoMVBhXOoDAas4Z2BlHU15/wbzh4U3VX9eh1nD4q+QnqDoknaNUxlEOjSmudXAO+qfr0S+FtSGhxK2K73h77+F8ABf2cQ5kfV9q2ofv2+TrWret5lVAaorBPXK/Qaq6k/yPe7nD1o9Tftvl4J2nQxlTGhj9Q8/27gvaGvvwVcm+a1StC2fxT8/qgExuPVa5foHmhXu6rHz6eSZ393J65Z9d/9ZeCxmHPaen+l+otP6aJcR2V0+IfA56vPbaPS6wU4D3i6eoP/DXBJ6Hs/X/2+o8DHO9yu/w38X2Cq+t/u6vMfAQ5Xb+jDwB0dbtfDwJHq678AXBb63j+oXsdjwO93sl3Vx1uB7TXf1+7r9RXgJ8A8lTzlHcAfA39cPW7A49V2HwZG2n29ErTpi8DJ0L01UX3+kup1OlT9HX8+zWuVsG13he6vA4T+6ETdA51qV/Wc26kUSoS/r23XjEoqzIHvhH5X13Xy/tLUfxGRnMhaDl1ERJZIAV1EJCcU0EVEckIBXUQkJxTQRURyQgFdRCQnFNBFRHLi/wPYMkoH/CCWNgAAAABJRU5ErkJggg==",
501      "text/plain": [
502       "<Figure size 432x288 with 1 Axes>"
503      ]
504     },
505     "metadata": {
506      "tags": []
507     },
508     "output_type": "display_data"
509    }
510   ],
511   "source": [
512    "import matplotlib.pyplot as plt\n",
513    "import sympy\n",
514    "\n",
515    "# Perform an X gate with variable exponent\n",
516    "q = cirq.GridQubit(1,1)\n",
517    "circuit = cirq.Circuit(cirq.X(q) ** sympy.Symbol('t'),\n",
518    "                       cirq.measure(q, key='m'))\n",
519    "\n",
520    "# Sweep exponent from zero (off) to one (on) and back to two (off)\n",
521    "param_sweep = cirq.Linspace('t', start=0, stop=2, length=200)\n",
522    "\n",
523    "# Simulate the sweep\n",
524    "s = cirq.Simulator()\n",
525    "trials = s.run_sweep(circuit, param_sweep, repetitions=1000)\n",
526    "\n",
527    "# Plot all the results\n",
528    "x_data = [trial.params['t'] for trial in trials]\n",
529    "y_data = [trial.histogram(key='m')[1] / 1000.0 for trial in trials]\n",
530    "plt.scatter('t','p', data={'t': x_data, 'p': y_data})\n"
531   ]
532  },
533  {
534   "cell_type": "markdown",
535   "metadata": {
536    "id": "M8oLYwusz4XE"
537   },
538   "source": [
539    "## Unitary matrices and decompositions\n",
540    "\n",
541    "Most quantum operations have a unitary matrix representation.  This matrix can be accessed by applying `cirq.unitary()`.  This can be applied to gates, operations, and circuits that support this protocol and will return the unitary matrix that represents the object."
542   ]
543  },
544  {
545   "cell_type": "code",
546   "execution_count": null,
547   "metadata": {
548    "id": "xn9nnBA70s23"
549   },
550   "outputs": [
551    {
552     "name": "stdout",
553     "output_type": "stream",
554     "text": [
555      "Unitary of the X gate\n",
556      "[[0.+0.j 1.+0.j]\n",
557      " [1.+0.j 0.+0.j]]\n",
558      "Unitary of SWAP operator on two qubits.\n",
559      "[[1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
560      " [0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
561      " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]\n",
562      " [0.+0.j 0.+0.j 0.+0.j 1.+0.j]]\n",
563      "Unitary of a sample circuit\n",
564      "[[0.+0.j 0.+0.j 1.+0.j 0.+0.j]\n",
565      " [1.+0.j 0.+0.j 0.+0.j 0.+0.j]\n",
566      " [0.+0.j 0.+0.j 0.+0.j 1.+0.j]\n",
567      " [0.+0.j 1.+0.j 0.+0.j 0.+0.j]]\n"
568     ]
569    }
570   ],
571   "source": [
572    "print('Unitary of the X gate')\n",
573    "print(cirq.unitary(cirq.X))\n",
574    "\n",
575    "print('Unitary of SWAP operator on two qubits.')\n",
576    "q0, q1 = cirq.LineQubit.range(2)\n",
577    "print(cirq.unitary(cirq.SWAP(q0, q1)))\n",
578    "\n",
579    "print('Unitary of a sample circuit')\n",
580    "print(cirq.unitary(cirq.Circuit(cirq.X(q0), cirq.SWAP(q0, q1))))"
581   ]
582  },
583  {
584   "cell_type": "markdown",
585   "metadata": {
586    "id": "Ls6Tnx90Y94Q"
587   },
588   "source": [
589    "### Decompositions \n",
590    "\n",
591    "Many gates can be decomposed into an equivalent circuit with simpler operations and gates.  This is called decomposition and can be accomplished with the `cirq.decompose` protocol.  \n",
592    "\n",
593    "For instance, a Hadamard H gate can be decomposed into X and Y gates:"
594   ]
595  },
596  {
597   "cell_type": "code",
598   "execution_count": null,
599   "metadata": {
600    "id": "u8JwZaAUfbSv"
601   },
602   "outputs": [
603    {
604     "name": "stdout",
605     "output_type": "stream",
606     "text": [
607      "[(cirq.Y**0.5).on(cirq.LineQubit(0)), cirq.XPowGate(exponent=1.0, global_shift=-0.25).on(cirq.LineQubit(0))]\n"
608     ]
609    }
610   ],
611   "source": [
612    "print(cirq.decompose(cirq.H(cirq.LineQubit(0))))"
613   ]
614  },
615  {
616   "cell_type": "markdown",
617   "metadata": {
618    "id": "B8ciZZSSf2jb"
619   },
620   "source": [
621    "Another example is the 3-qubit Toffoli gate, which is equivalent to a controlled-controlled-X gate.  Many devices do not support a three qubit gate, so it is important "
622   ]
623  },
624  {
625   "cell_type": "code",
626   "execution_count": null,
627   "metadata": {
628    "id": "bbjRWlzjgPwf"
629   },
630   "outputs": [
631    {
632     "name": "stdout",
633     "output_type": "stream",
634     "text": [
635      "0: ───T────────────────@─────────────────────────────────@─────────────────────────────@────────────────────────────@───────────────────────────────────────\n",
636      "                       │                                 │                             │                            │\n",
637      "1: ───T───────Y^-0.5───@───Y^0.5────@───T^-1────Y^-0.5───@────────Y^0.5───@───Y^-0.5───@──────Y^0.5────@───Y^-0.5───@──────Y^0.5────@───────────────────────\n",
638      "                                    │                                     │                            │                            │\n",
639      "2: ───Y^0.5───X────────T───Y^-0.5───@───Y^0.5───T────────Y^-0.5───────────@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5────T^-1───Y^-0.5───@───Y^0.5───Y^0.5───X───\n"
640     ]
641    }
642   ],
643   "source": [
644    "q0, q1, q2 = cirq.LineQubit.range(3)\n",
645    "print(cirq.Circuit(cirq.decompose(cirq.TOFFOLI(q0, q1, q2))))"
646   ]
647  },
648  {
649   "cell_type": "markdown",
650   "metadata": {
651    "id": "VWcik4ZwggXj"
652   },
653   "source": [
654    "The above decomposes the Toffoli into a simpler set of one-qubit gates and CZ gates at the cost of lengthening the circuit considerably.\n",
655    "\n",
656    "Some devices will automatically decompose gates that they do not support.  For instance, if we use the `Foxtail` device from above, we can see this in action by adding an unsupported SWAP gate:"
657   ]
658  },
659  {
660   "cell_type": "code",
661   "execution_count": null,
662   "metadata": {
663    "id": "oS7vWnuHjLhE"
664   },
665   "outputs": [
666    {
667     "name": "stdout",
668     "output_type": "stream",
669     "text": [
670      "(0, 0): ───S^-1───Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───Z───\n",
671      "                           │                          │                   │\n",
672      "(0, 1): ───Z──────Y^-0.5───@───S^-1───Y^0.5───X^0.5───@───S^-1───X^-0.5───@───S^-1───S───\n"
673     ]
674    }
675   ],
676   "source": [
677    "swap = cirq.SWAP(cirq.GridQubit(0, 0), cirq.GridQubit(0, 1))\n",
678    "print(cirq.Circuit(swap, device=cirq_google.Foxtail))"
679   ]
680  },
681  {
682   "cell_type": "markdown",
683   "metadata": {
684    "id": "rIUbvdVQkHbX"
685   },
686   "source": [
687    "### Optimizers\n",
688    "\n",
689    "The last concept in this tutorial is the optimizer.  An optimizer can take a circuit and modify it.  Usually, this will entail combining or modifying operations to make it more efficient and shorter, though an optimizer can, in theory, do any sort of circuit manipulation.\n",
690    "\n",
691    "For example, the `MergeSingleQubitGates` optimizer will take consecutive single-qubit operations and merge them into a single `PhasedXZ` operation."
692   ]
693  },
694  {
695   "cell_type": "code",
696   "execution_count": null,
697   "metadata": {
698    "id": "5WvfOdaG5C_6"
699   },
700   "outputs": [
701    {
702     "name": "stdout",
703     "output_type": "stream",
704     "text": [
705      "(1, 1): ───X^0.25───Y^0.25───T───\n",
706      "           ┌                           ┐\n",
707      "(1, 1): ───│ 0.5  +0.707j -0.   -0.5j  │───────────\n",
708      "           │ 0.354+0.354j  0.146+0.854j│\n",
709      "           └                           ┘\n"
710     ]
711    }
712   ],
713   "source": [
714    "q=cirq.GridQubit(1, 1)\n",
715    "optimizer=cirq.MergeSingleQubitGates()\n",
716    "c=cirq.Circuit(cirq.X(q) ** 0.25, cirq.Y(q) ** 0.25, cirq.Z(q) ** 0.25)\n",
717    "print(c)\n",
718    "optimizer.optimize_circuit(c)\n",
719    "print(c)"
720   ]
721  },
722  {
723   "cell_type": "markdown",
724   "metadata": {
725    "id": "xRfQqzdx7lUI"
726   },
727   "source": [
728    "Other optimizers can assist in transforming a circuit into operations that are native operations on specific hardware devices.  You can find more about optimizers and how to create your own elsewhere in the documentation."
729   ]
730  },
731  {
732   "cell_type": "markdown",
733   "metadata": {
734    "id": "8QbTGmKlYT4i"
735   },
736   "source": [
737    "## Next steps\n",
738    "\n",
739    "After completing this tutorial, you should be able to use gates and operations to construct your own quantum circuits, simulate them, and to use sweeps.  It should give you a brief idea of the commonly used \n",
740    "\n",
741    "There is much more to learn and try out for those who are interested:\n",
742    "\n",
743    "* Learn about the variety of [Gates](../gates.ipynb) available in cirq and more about the different ways to construct [Circuits](../circuits.ipynb)\n",
744    "* Learn more about [Simulations](../simulation.ipynb) and how it works.\n",
745    "* Learn about [Noise](../noise.ipynb) and how to utilize multi-level systems using [Qudits](../qudits.ipynb)\n",
746    "* Dive into some [Examples](_index.yaml) and some in-depth tutorials of how to use cirq.\n",
747    "\n",
748    "Also, join our [cirq-announce mailing list](https://groups.google.com/forum/#!forum/cirq-announce) to hear about changes and releases or go to the [cirq github](https://github.com/quantumlib/Cirq/) to file issues."
749   ]
750  }
751 ],
752 "metadata": {
753  "colab": {
754   "collapsed_sections": [],
755   "name": "basics.ipynb",
756   "toc_visible": true
757  },
758  "kernelspec": {
759   "display_name": "Python 3",
760   "name": "python3"
761  }
762 },
763 "nbformat": 4,
764 "nbformat_minor": 0
765}
766