1{
2 "cells": [
3  {
4   "cell_type": "markdown",
5   "metadata": {
6    "id": "DkA0Fobtb9dM"
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": "tUshu7YfcAAW"
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": "igOQCrBOcF5d"
38   },
39   "source": [
40    "# Protocols"
41   ]
42  },
43  {
44   "cell_type": "markdown",
45   "metadata": {
46    "id": "LHRAvc9TcHOH"
47   },
48   "source": [
49    "<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
50    "  <td>\n",
51    "    <a target=\"_blank\" href=\"https://quantumai.google/cirq/protocols\"><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/protocols.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/protocols.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/protocols.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": "code",
67   "execution_count": 2,
68   "metadata": {
69    "id": "bd9529db1c0b"
70   },
71   "outputs": [],
72   "source": [
73    "try:\n",
74    "    import cirq\n",
75    "except ImportError:\n",
76    "    print(\"installing cirq...\")\n",
77    "    !pip install --quiet cirq\n",
78    "    print(\"installed cirq.\")"
79   ]
80  },
81  {
82   "cell_type": "markdown",
83   "metadata": {
84    "id": "lB__WndjHWGa"
85   },
86   "source": [
87    "# Introduction\n",
88    "\n",
89    "Cirq's protocols are very similar concept to Python's built-in protocols that were introduced in [PEP 544](https://www.python.org/dev/peps/pep-0544/).\n",
90    "Python's built-in protocols are extremely convenient, for example behind all the for loops and list comprehensions you can find the Iterator protocol.\n",
91    "As long as an object has the `__iter__()` magic method that returns an iterator object, it has iterator support.\n",
92    "An iterator object has to define `__iter__()` and `__next__()` magic methods, that defines the iterator protocol.\n",
93    "The `iter(val)` builtin function returns an iterator for `val` if it defines the above methods, otherwise throws a `TypeError`. Cirq protocols work similarly.\n",
94    "\n",
95    "A canonical Cirq protocol example is the `unitary` protocol that allows to check the unitary matrix of values that support the protocol by calling `cirq.unitary(val)`."
96   ]
97  },
98  {
99   "cell_type": "code",
100   "execution_count": null,
101   "metadata": {
102    "id": "4a6bcd71ae5f"
103   },
104   "outputs": [],
105   "source": [
106    "import cirq \n",
107    "\n",
108    "print(cirq.X)\n",
109    "print(\"cirq.X unitary:\\n\", cirq.unitary(cirq.X))\n",
110    "\n",
111    "a, b = cirq.LineQubit.range(2)\n",
112    "circuit = cirq.Circuit(cirq.X(a), cirq.Y(b))\n",
113    "print(circuit)\n",
114    "print(\"circuit unitary:\\n\", cirq.unitary(circuit))\n"
115   ]
116  },
117  {
118   "cell_type": "markdown",
119   "metadata": {
120    "id": "6b3b43b2141b"
121   },
122   "source": [
123    "When an object does not support a given protocol, an error is thrown."
124   ]
125  },
126  {
127   "cell_type": "code",
128   "execution_count": null,
129   "metadata": {
130    "id": "a988c0efc9b7"
131   },
132   "outputs": [],
133   "source": [
134    "try: \n",
135    "    print(cirq.unitary(a)) ## error!\n",
136    "except Exception as e: \n",
137    "    print(\"As expected, a qubit does not have a unitary. The error: \")\n",
138    "    print(e)\n",
139    "    "
140   ]
141  },
142  {
143   "cell_type": "markdown",
144   "metadata": {
145    "id": "b4d4bc702a5e"
146   },
147   "source": [
148    "## What is a protocol? \n",
149    "\n",
150    "A protocol is a combination of the following two items: \n",
151    "- a `SupportsXYZ` class, which defines and documents all the magic functions that need to be implemented in order to support that given protocol \n",
152    "- the entrypoint function(s), which are exposed to the main cirq namespace as `cirq.xyz()`\n",
153    "\n",
154    "Note: While the protocol is technically both of these things, we refer to the public utility functions interchangeably as protocols. See the list of them below.\n",
155    "\n",
156    "\n",
157    "## Cirq's protocols\n",
158    "\n",
159    "For a complete list of Cirq protocols, refer to the `cirq.protocols` package. \n",
160    "Here we provide a list of frequently used protocols for debugging, simulation and testing.\n",
161    "\n",
162    "\n",
163    "| Protocol | Description | \n",
164    "|----------|-------|\n",
165    "|`cirq.apply_channel`| High performance evolution under a channel evolution. |\n",
166    "|`cirq.apply_mixture`| High performance evolution under a mixture of unitaries evolution. |\n",
167    "|`cirq.apply_unitaries`| Apply a series of unitaries onto a state tensor. |\n",
168    "|`cirq.apply_unitary`| High performance left-multiplication of a unitary effect onto a tensor. |\n",
169    "|`cirq.approx_eq`| Approximately compares two objects. |\n",
170    "|`cirq.commutes`| Determines whether two values commute. |\n",
171    "|`cirq.definitely_commutes`| Determines whether two values definitely commute. |\n",
172    "|`cirq.decompose`| Recursively decomposes a value into `cirq.Operation`s meeting a criteria. |\n",
173    "|`cirq.decompose_once`| Decomposes a value into operations, if possible. |\n",
174    "|`cirq.decompose_once_with_qubits`| Decomposes a value into operations on the given qubits. |\n",
175    "|`cirq.equal_up_to_global_phase`| Determine whether two objects are equal up to global phase. |\n",
176    "|`cirq.has_kraus`| Returns whether the value has a Kraus representation. |\n",
177    "|`cirq.has_mixture`| Returns whether the value has a mixture representation. |\n",
178    "|`cirq.has_unitary`| Determines whether the value has a unitary effect. |\n",
179    "|`cirq.inverse`| Returns the inverse `val**-1` of the given value, if defined. |\n",
180    "|`cirq.is_measurement`| Determines whether or not the given value is a measurement. |\n",
181    "|`cirq.is_parameterized`| Returns whether the object is parameterized with any Symbols. |\n",
182    "|`cirq.kraus`| Returns a Kraus representation of the given channel. |\n",
183    "|`cirq.measurement_key`| Get the single measurement key for the given value. |\n",
184    "|`cirq.measurement_keys`| Gets the measurement keys of measurements within the given value. |\n",
185    "|`cirq.mixture`| Return a sequence of tuples representing a probabilistic unitary. |\n",
186    "|`cirq.num_qubits`| Returns the number of qubits, qudits, or qids `val` operates on. |\n",
187    "|`cirq.parameter_names`| Returns parameter names for this object. |\n",
188    "|`cirq.parameter_symbols`| Returns parameter symbols for this object. |\n",
189    "|`cirq.pauli_expansion`| Returns coefficients of the expansion of val in the Pauli basis. |\n",
190    "|`cirq.phase_by`| Returns a phased version of the effect. |\n",
191    "|`cirq.pow`| Returns `val**factor` of the given value, if defined. |\n",
192    "|`cirq.qasm`| Returns QASM code for the given value, if possible. |\n",
193    "|`cirq.qid_shape`| Returns a tuple describing the number of quantum levels of each |\n",
194    "|`cirq.quil`| Returns the QUIL code for the given value. |\n",
195    "|`cirq.read_json`| Read a JSON file that optionally contains cirq objects. |\n",
196    "|`cirq.resolve_parameters`| Resolves symbol parameters in the effect using the param resolver. |\n",
197    "|`cirq.to_json`| Write a JSON file containing a representation of obj. |\n",
198    "|`cirq.trace_distance_bound`| Returns a maximum on the trace distance between this effect's input |\n",
199    "|`cirq.trace_distance_from_angle_list`| Given a list of arguments of the eigenvalues of a unitary matrix, |\n",
200    "|`cirq.unitary`| Returns a unitary matrix describing the given value. |\n",
201    "|`cirq.validate_mixture`| Validates that the mixture's tuple are valid probabilities. |\n",
202    "\n",
203    "\n",
204    "### Quantum operator representation protocols\n",
205    "\n",
206    "The following family of protocols is an important and frequently used set of features of Cirq and it is worthwhile mentioning them and and how they interact with each other. They are, in the order of increasing generality:\n",
207    "\n",
208    "* `*unitary`\n",
209    "* `*kraus`\n",
210    "* `*mixture`\n",
211    "\n",
212    "All these protocols make it easier to work with different representations of quantum operators, namely: \n",
213    "- finding that representation (`unitary`, `kraus`, `mixture`), \n",
214    "- determining whether the operator has that representation (`has_*`) \n",
215    "- and applying them (`apply_*`) on a state vector. \n",
216    "\n",
217    "#### Unitary \n",
218    "\n",
219    "The `*unitary` protocol is the least generic, as only unitary operators should implement it. The `cirq.unitary` function returns the matrix representation of the operator in the computational basis. We saw an example of the unitary protocol above, but let's see the unitary matrix of the Pauli-Y operator as well: \n"
220   ]
221  },
222  {
223   "cell_type": "code",
224   "execution_count": 6,
225   "metadata": {
226    "id": "d2ae567abe99"
227   },
228   "outputs": [
229    {
230     "name": "stdout",
231     "output_type": "stream",
232     "text": [
233      "[[0.+0.j 0.-1.j]\n",
234      " [0.+1.j 0.+0.j]]\n"
235     ]
236    }
237   ],
238   "source": [
239    "print(cirq.unitary(cirq.Y))"
240   ]
241  },
242  {
243   "cell_type": "markdown",
244   "metadata": {
245    "id": "2c8e107b45da"
246   },
247   "source": [
248    "#### Mixture \n",
249    "\n",
250    "The `*mixture` protocol should be implemented by operators that are _unitary-mixtures_. These probabilistic operators are represented by a list of tuples ($p_i$, $U_i$), where each unitary effect $U_i$ occurs with a certain probability $p_i$, and $\\sum p_i = 1$. Probabilities are a Python float between 0.0 and 1.0, and the unitary matrices are numpy arrays.\n",
251    "\n",
252    "Constructing simple probabilistic gates in Cirq is easiest with the `with_probability` method. "
253   ]
254  },
255  {
256   "cell_type": "code",
257   "execution_count": 17,
258   "metadata": {
259    "id": "5f9ec1e69ba6"
260   },
261   "outputs": [
262    {
263     "name": "stdout",
264     "output_type": "stream",
265     "text": [
266      "probability: 0.3\n",
267      "operator:\n",
268      "[[0.+0.j 1.+0.j]\n",
269      " [1.+0.j 0.+0.j]]\n",
270      "probability: 0.7\n",
271      "operator:\n",
272      "[[1. 0.]\n",
273      " [0. 1.]]\n"
274     ]
275    }
276   ],
277   "source": [
278    "probabilistic_x = cirq.X.with_probability(.3)\n",
279    "\n",
280    "for p, op in cirq.mixture(probabilistic_x):\n",
281    "    print(f\"probability: {p}\")\n",
282    "    print(\"operator:\")\n",
283    "    print(op)"
284   ]
285  },
286  {
287   "cell_type": "markdown",
288   "metadata": {
289    "id": "51addeffe113"
290   },
291   "source": [
292    "In case an operator does not implement `SupportsMixture`, but does implement `SupportsUnitary`, `*mixture` functions fall back to the `*unitary` methods. It is easy to see that a unitary operator $U$ is just a \"mixture\" of a single unitary with probability $p=1$. "
293   ]
294  },
295  {
296   "cell_type": "code",
297   "execution_count": 19,
298   "metadata": {
299    "id": "4a8a43eb4cbc"
300   },
301   "outputs": [
302    {
303     "name": "stdout",
304     "output_type": "stream",
305     "text": [
306      "((1.0, array([[0.+0.j, 0.-1.j],\n",
307      "       [0.+1.j, 0.+0.j]])),)\n",
308      "True\n"
309     ]
310    }
311   ],
312   "source": [
313    "# cirq.Y has a unitary effect but does not implement SupportsMixture\n",
314    "# thus mixture protocols will return ((1, cirq.unitary(Y)))\n",
315    "print(cirq.mixture(cirq.Y))\n",
316    "print(cirq.has_mixture(cirq.Y))"
317   ]
318  },
319  {
320   "cell_type": "markdown",
321   "metadata": {
322    "id": "7385326f4a37"
323   },
324   "source": [
325    "#### Channel \n",
326    "\n",
327    "\n",
328    "The `kraus` representation is the operator sum representation of a quantum operator (a channel):  \n",
329    "\n",
330    "        $$\n",
331    "        \\rho \\rightarrow \\sum_{k=0}^{r-1} A_k \\rho A_k^\\dagger\n",
332    "        $$\n",
333    "\n",
334    "These matrices are required to satisfy the trace preserving condition\n",
335    "\n",
336    "        $$\n",
337    "        \\sum_{k=0}^{r-1} A_k^\\dagger A_k = I\n",
338    "        $$\n",
339    "\n",
340    "where $I$ is the identity matrix. The matrices $A_k$ are sometimes called Kraus or noise operators.\n",
341    "    \n",
342    "The `cirq.kraus` returns a tuple of numpy arrays, one for each of the Kraus operators:"
343   ]
344  },
345  {
346   "cell_type": "code",
347   "execution_count": 22,
348   "metadata": {
349    "id": "dbfd41797730"
350   },
351   "outputs": [
352    {
353     "data": {
354      "text/plain": [
355       "(array([[0.83666003, 0.        ],\n",
356       "        [0.        , 0.83666003]]),\n",
357       " array([[0.        +0.j, 0.31622777+0.j],\n",
358       "        [0.31622777+0.j, 0.        +0.j]]),\n",
359       " array([[0.+0.j        , 0.-0.31622777j],\n",
360       "        [0.+0.31622777j, 0.+0.j        ]]),\n",
361       " array([[ 0.31622777+0.j,  0.        +0.j],\n",
362       "        [ 0.        +0.j, -0.31622777+0.j]]))"
363      ]
364     },
365     "execution_count": 22,
366     "metadata": {},
367     "output_type": "execute_result"
368    }
369   ],
370   "source": [
371    "cirq.kraus(cirq.DepolarizingChannel(p=0.3))"
372   ]
373  },
374  {
375   "cell_type": "markdown",
376   "metadata": {
377    "id": "6a0d509482eb"
378   },
379   "source": [
380    "In case the operator does not implement `SupportsKraus`, but it does implement `SupportsMixture`, the `*kraus` protocol will generate the Kraus operators based on the  `*mixture` representation. \n",
381    "\n",
382    "$$\n",
383    "((p_0, U_0),(p_1, U_1),\\ldots,(p_n, U_n)) \\rightarrow (\\sqrt{p_0}U_0, \\sqrt{p_1}U_1, \\ldots, \\sqrt{p_n}U_n)\n",
384    "$$\n",
385    "\n",
386    "Thus for example `((0.25, X), (0.75, I)) -> (0.5 X, sqrt(0.75) I)`:"
387   ]
388  },
389  {
390   "cell_type": "code",
391   "execution_count": 29,
392   "metadata": {
393    "id": "259cadda9d9d"
394   },
395   "outputs": [
396    {
397     "data": {
398      "text/plain": [
399       "(array([[0. +0.j, 0.5+0.j],\n",
400       "        [0.5+0.j, 0. +0.j]]),\n",
401       " array([[0.8660254, 0.       ],\n",
402       "        [0.       , 0.8660254]]))"
403      ]
404     },
405     "execution_count": 29,
406     "metadata": {},
407     "output_type": "execute_result"
408    }
409   ],
410   "source": [
411    "cirq.kraus(cirq.X.with_probability(0.25))"
412   ]
413  },
414  {
415   "cell_type": "markdown",
416   "metadata": {
417    "id": "288ad97dcd90"
418   },
419   "source": [
420    "In the simplest case of a unitary operator, `cirq.kraus` returns a one-element tuple with the same unitary as returned by `cirq.unitary`:"
421   ]
422  },
423  {
424   "cell_type": "code",
425   "execution_count": 31,
426   "metadata": {
427    "id": "d424899d3af2"
428   },
429   "outputs": [
430    {
431     "name": "stdout",
432     "output_type": "stream",
433     "text": [
434      "(array([[0.+0.j, 0.-1.j],\n",
435      "       [0.+1.j, 0.+0.j]]),)\n",
436      "[[0.+0.j 0.-1.j]\n",
437      " [0.+1.j 0.+0.j]]\n",
438      "True\n"
439     ]
440    }
441   ],
442   "source": [
443    "print(cirq.kraus(cirq.Y))\n",
444    "print(cirq.unitary(cirq.Y))\n",
445    "print(cirq.has_kraus(cirq.Y))"
446   ]
447  }
448 ],
449 "metadata": {
450  "colab": {
451   "collapsed_sections": [],
452   "name": "protocols.ipynb",
453   "toc_visible": true
454  },
455  "kernelspec": {
456   "display_name": "Python 3",
457   "name": "python3"
458  }
459 },
460 "nbformat": 4,
461 "nbformat_minor": 0
462}
463