File size: 28,961 Bytes
8568004 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 |
{
"cells": [
{
"cell_type": "markdown",
"metadata": {
"id": "WZ1G8QHhdHZR"
},
"source": [
"##### Copyright 2020 The Cirq Developers"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"cellView": "form",
"execution": {
"iopub.execute_input": "2025-03-01T10:30:30.446798Z",
"iopub.status.busy": "2025-03-01T10:30:30.446341Z",
"iopub.status.idle": "2025-03-01T10:30:30.450288Z",
"shell.execute_reply": "2025-03-01T10:30:30.449623Z"
},
"id": "KQa9t_gadIuR"
},
"outputs": [],
"source": [
"#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
"# you may not use this file except in compliance with the License.\n",
"# You may obtain a copy of the License at\n",
"#\n",
"# https://www.apache.org/licenses/LICENSE-2.0\n",
"#\n",
"# Unless required by applicable law or agreed to in writing, software\n",
"# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
"# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
"# See the License for the specific language governing permissions and\n",
"# limitations under the License."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "xwec7FrkdFmi"
},
"source": [
"# Custom gates"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "5KZia7jmdJ3V"
},
"source": [
"<table class=\"tfo-notebook-buttons\" align=\"left\">\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://quantumai.google/cirq/build/custom_gates\"><img src=\"https://quantumai.google/site-assets/images/buttons/quantumai_logo_1x.png\" />View on QuantumAI</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://colab.research.google.com/github/quantumlib/Cirq/blob/main/docs/build/custom_gates.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/colab_logo_1x.png\" />Run in Google Colab</a>\n",
" </td>\n",
" <td>\n",
" <a target=\"_blank\" href=\"https://github.com/quantumlib/Cirq/blob/main/docs/build/custom_gates.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/github_logo_1x.png\" />View source on GitHub</a>\n",
" </td>\n",
" <td>\n",
" <a href=\"https://storage.googleapis.com/tensorflow_docs/Cirq/docs/build/custom_gates.ipynb\"><img src=\"https://quantumai.google/site-assets/images/buttons/download_icon_1x.png\" />Download notebook</a>\n",
" </td>\n",
"</table>"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:30.453242Z",
"iopub.status.busy": "2025-03-01T10:30:30.452740Z",
"iopub.status.idle": "2025-03-01T10:30:49.820952Z",
"shell.execute_reply": "2025-03-01T10:30:49.820063Z"
},
"id": "bd9529db1c0b"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"installing cirq...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"\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.\r\n",
"tensorflow-metadata 1.16.1 requires protobuf<4.21,>=3.20.3; python_version < \"3.11\", but you have protobuf 4.25.6 which is incompatible.\u001b[0m\u001b[31m\r\n",
"\u001b[0m"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"installed cirq.\n"
]
}
],
"source": [
"try:\n",
" import cirq\n",
"except ImportError:\n",
" print(\"installing cirq...\")\n",
" !pip install --quiet cirq\n",
" print(\"installed cirq.\")\n",
" import cirq\n",
" \n",
"import numpy as np"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "y8P1T6duC-yo"
},
"source": [
"Standard gates such as Pauli gates and `CNOT`s are defined in `cirq.ops` as described [here](gates.ipynb). To use a unitary which is not a standard gate in a circuit, one can create a custom gate as described in this guide."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "71ae01d45738"
},
"source": [
"## General pattern"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ce675022b0b4"
},
"source": [
"Gates are classes in Cirq. To define custom gates, we inherit from a base gate class and define a few methods.\n",
"\n",
"The general pattern is to:\n",
"\n",
" - Inherit from `cirq.Gate`.\n",
" - Define one of the `_num_qubits_` or `_qid_shape_` methods.\n",
" - Define one of the `_unitary_` or `_decompose_` methods.\n",
" \n",
"\n",
"> *Note*: Methods beginning and ending with one or more underscores are *magic methods* and are used by Cirq's protocols or built-in Python functions. More information about magic methods is included at the end of this guide.\n",
"\n",
"We demonstrate these patterns via the following examples.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "38c6a07df259"
},
"source": [
"## From a unitary"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "58228b4b49f4"
},
"source": [
"One can create a custom Cirq gate from a unitary matrix in the following manner. Here, we define a gate which corresponds to the unitary\n",
"\n",
"\n",
"$$ U = \\frac{1}{\\sqrt{2}} \\left[ \\begin{matrix} 1 & 1 \\\\ -1 & 1 \\end{matrix} \\right] . $$"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.825674Z",
"iopub.status.busy": "2025-03-01T10:30:49.824765Z",
"iopub.status.idle": "2025-03-01T10:30:49.830558Z",
"shell.execute_reply": "2025-03-01T10:30:49.829866Z"
},
"id": "66346efdd520"
},
"outputs": [],
"source": [
"\"\"\"Define a custom single-qubit gate.\"\"\"\n",
"class MyGate(cirq.Gate):\n",
" def __init__(self):\n",
" super(MyGate, self)\n",
" \n",
" def _num_qubits_(self):\n",
" return 1\n",
" \n",
" def _unitary_(self):\n",
" return np.array([\n",
" [1.0, 1.0],\n",
" [-1.0, 1.0]\n",
" ]) / np.sqrt(2)\n",
" \n",
" def _circuit_diagram_info_(self, args):\n",
" return \"G\"\n",
"\n",
"my_gate = MyGate()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "873c956ccf0e"
},
"source": [
"In this example, the `_num_qubits_` method tells Cirq that this gate acts on a single-qubit, and the `_unitary_` method defines the unitary of the gate. The `_circuit_diagram_info_` method tells Cirq how to display the gate in a circuit, as we will see below.\n",
"\n",
"Once this gate is defined, it can be used like any standard gate in Cirq."
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.833437Z",
"iopub.status.busy": "2025-03-01T10:30:49.832925Z",
"iopub.status.idle": "2025-03-01T10:30:49.838682Z",
"shell.execute_reply": "2025-03-01T10:30:49.838014Z"
},
"id": "ec8550e51178"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Circuit with custom gates:\n",
"0: ───G───\n"
]
}
],
"source": [
"\"\"\"Use the custom gate in a circuit.\"\"\"\n",
"circ = cirq.Circuit(\n",
" my_gate.on(cirq.LineQubit(0))\n",
")\n",
"\n",
"print(\"Circuit with custom gates:\")\n",
"print(circ)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "dc0e4ee48211"
},
"source": [
"When we print the circuit, we see the symbol we specified in the `_circuit_diagram_info_` method.\n",
"\n",
"Circuits with custom gates can be simulated in the same manner as circuits with standard gates."
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.841511Z",
"iopub.status.busy": "2025-03-01T10:30:49.841010Z",
"iopub.status.idle": "2025-03-01T10:30:49.846952Z",
"shell.execute_reply": "2025-03-01T10:30:49.846263Z"
},
"id": "3885c629a1ef"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"measurements: (no measurements)\n",
"\n",
"qubits: (cirq.LineQubit(0),)\n",
"output vector: 0.707|0⟩ - 0.707|1⟩\n",
"\n",
"phase:\n",
"output vector: |⟩\n"
]
}
],
"source": [
"\"\"\"Simulate a circuit with a custom gate.\"\"\"\n",
"sim = cirq.Simulator()\n",
"\n",
"res = sim.simulate(circ)\n",
"print(res)"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.849662Z",
"iopub.status.busy": "2025-03-01T10:30:49.849087Z",
"iopub.status.idle": "2025-03-01T10:30:49.854351Z",
"shell.execute_reply": "2025-03-01T10:30:49.853689Z"
},
"id": "71dd8d4666fc"
},
"outputs": [],
"source": [
"\"\"\"Define a custom two-qubit gate.\"\"\"\n",
"class AnotherGate(cirq.Gate):\n",
" def __init__(self):\n",
" super(AnotherGate, self)\n",
"\n",
" def _num_qubits_(self):\n",
" return 2\n",
" \n",
" def _unitary_(self):\n",
" return np.array([\n",
" [1.0, -1.0, 0.0, 0.0],\n",
" [0.0, 0.0, 1.0, 1.0],\n",
" [1.0, 1.0, 0.0, 0.0],\n",
" [0.0, 0.0, 1.0, -1.0]\n",
" ]) / np.sqrt(2)\n",
" \n",
" def _circuit_diagram_info_(self, args):\n",
" return \"Top wire symbol\", \"Bottom wire symbol\"\n",
"\n",
"this_gate = AnotherGate()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9c79b54f0ab4"
},
"source": [
"Here, the `_circuit_diagram_info_` method returns two symbols (one for each wire) since it is a two-qubit gate."
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.857084Z",
"iopub.status.busy": "2025-03-01T10:30:49.856652Z",
"iopub.status.idle": "2025-03-01T10:30:49.861391Z",
"shell.execute_reply": "2025-03-01T10:30:49.860709Z"
},
"id": "280e34a34bd6"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Circuit with custom two-qubit gate:\n",
"0: ───Top wire symbol──────\n",
" │\n",
"1: ───Bottom wire symbol───\n"
]
}
],
"source": [
"\"\"\"Use the custom two-qubit gate in a circuit.\"\"\"\n",
"circ = cirq.Circuit(\n",
" this_gate.on(*cirq.LineQubit.range(2))\n",
")\n",
"\n",
"print(\"Circuit with custom two-qubit gate:\")\n",
"print(circ)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "45a8342180aa"
},
"source": [
"As above, this circuit can also be simulated in the expected way."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "c896c2bb5f23"
},
"source": [
"### With parameters"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "ef59ca39c94c"
},
"source": [
"Custom gates can be defined and used with parameters. For example, to define the gate\n",
"\n",
"$$ R(\\theta) = \\left[ \\begin{matrix} \\cos \\theta & \\sin \\theta \\\\ \\sin \\theta & - \\cos \\theta \\end{matrix} \\right], $$\n",
"\n",
"we can do the following."
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.864308Z",
"iopub.status.busy": "2025-03-01T10:30:49.863892Z",
"iopub.status.idle": "2025-03-01T10:30:49.868943Z",
"shell.execute_reply": "2025-03-01T10:30:49.868283Z"
},
"id": "262d28526fef"
},
"outputs": [],
"source": [
"\"\"\"Define a custom gate with a parameter.\"\"\"\n",
"class RotationGate(cirq.Gate):\n",
" def __init__(self, theta):\n",
" super(RotationGate, self)\n",
" self.theta = theta\n",
" \n",
" def _num_qubits_(self):\n",
" return 1\n",
" \n",
" def _unitary_(self):\n",
" return np.array([\n",
" [np.cos(self.theta), np.sin(self.theta)],\n",
" [np.sin(self.theta), -np.cos(self.theta)]\n",
" ]) / np.sqrt(2)\n",
" \n",
" def _circuit_diagram_info_(self, args):\n",
" return f\"R({self.theta})\""
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "8a10fdb09fca"
},
"source": [
"This gate can be used in a circuit as shown below."
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.871773Z",
"iopub.status.busy": "2025-03-01T10:30:49.871205Z",
"iopub.status.idle": "2025-03-01T10:30:49.875861Z",
"shell.execute_reply": "2025-03-01T10:30:49.875171Z"
},
"id": "485c560f0d25"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Circuit with a custom rotation gate:\n",
"0: ───R(0.1)───\n"
]
}
],
"source": [
"\"\"\"Use the custom gate in a circuit.\"\"\"\n",
"circ = cirq.Circuit(\n",
" RotationGate(theta=0.1).on(cirq.LineQubit(0))\n",
")\n",
"\n",
"print(\"Circuit with a custom rotation gate:\")\n",
"print(circ)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "baf273b2fe60"
},
"source": [
"## From a known decomposition"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "708300eb2c33"
},
"source": [
"Custom gates can also be defined from a known decomposition (of gates). This is useful, for example, when groups of gates appear repeatedly in a circuit, or when a standard decomposition of a gate into primitive gates is known.\n",
"\n",
"We show an example below of a custom swap gate defined from a known decomposition of three CNOT gates."
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.878807Z",
"iopub.status.busy": "2025-03-01T10:30:49.878256Z",
"iopub.status.idle": "2025-03-01T10:30:49.883075Z",
"shell.execute_reply": "2025-03-01T10:30:49.882426Z"
},
"id": "2c656362cd95"
},
"outputs": [],
"source": [
"class MySwap(cirq.Gate):\n",
" def __init__(self):\n",
" super(MySwap, self)\n",
"\n",
" def _num_qubits_(self):\n",
" return 2\n",
"\n",
" def _decompose_(self, qubits):\n",
" a, b = qubits\n",
" yield cirq.CNOT(a, b)\n",
" yield cirq.CNOT(b, a)\n",
" yield cirq.CNOT(a, b)\n",
" \n",
" def _circuit_diagram_info_(self, args):\n",
" return [\"CustomSWAP\"] * self.num_qubits()\n",
"\n",
"my_swap = MySwap()"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "829c4602757a"
},
"source": [
"The `_decompose_` method yields the operations which implement the custom gate. (One can also return a list of operations instead of a generator.)\n",
"\n",
"When we use this gate in a circuit, the individual gates in the decomposition do not appear in the circuit. Instead, the `_circuit_diagram_info_` appears in the circuit. As mentioned, this can be useful for interpreting circuits at a higher level than individual (primitive) gates."
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.885806Z",
"iopub.status.busy": "2025-03-01T10:30:49.885292Z",
"iopub.status.idle": "2025-03-01T10:30:49.890896Z",
"shell.execute_reply": "2025-03-01T10:30:49.890204Z"
},
"id": "psYGZcjUEF5V"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Circuit:\n",
"0: ───X───CustomSWAP───\n",
" │\n",
"1: ───────CustomSWAP───\n"
]
}
],
"source": [
"\"\"\"Use the custom gate in a circuit.\"\"\"\n",
"qreg = cirq.LineQubit.range(2)\n",
"circ = cirq.Circuit(\n",
" cirq.X(qreg[0]),\n",
" my_swap.on(*qreg)\n",
")\n",
"\n",
"print(\"Circuit:\")\n",
"print(circ)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "856b1cdf0117"
},
"source": [
"We can simulate this circuit and verify it indeed swaps the qubits."
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.893697Z",
"iopub.status.busy": "2025-03-01T10:30:49.893128Z",
"iopub.status.idle": "2025-03-01T10:30:49.902576Z",
"shell.execute_reply": "2025-03-01T10:30:49.901930Z"
},
"id": "0cafcf4c4197"
},
"outputs": [
{
"data": {
"text/plain": [
"measurements: (no measurements)\n",
"\n",
"qubits: (cirq.LineQubit(0), cirq.LineQubit(1))\n",
"output vector: |01⟩\n",
"\n",
"phase:\n",
"output vector: |⟩"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"\"\"\"Simulate the circuit.\"\"\"\n",
"sim.simulate(circ)"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "09f425a61484"
},
"source": [
"## More on magic methods and protocols"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d63f32eb1ac7"
},
"source": [
"As mentioned, methods such as `_unitary_` which we have seen are known as \"magic\n",
"methods.\" Much of Cirq relies on \"magic methods\", which are methods prefixed with one or\n",
"two underscores and used by Cirq's protocols or built-in Python methods.\n",
"For instance, Python translates `cirq.Z**0.25` into\n",
"`cirq.Z.__pow__(0.25)`. Other uses are specific to cirq and are found in the\n",
"protocols subdirectory. They are defined below.\n",
"\n",
"At minimum, you will need to define either the ``_num_qubits_`` or\n",
"``_qid_shape_`` magic method to define the number of qubits (or qudits) used\n",
"in the gate."
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "d05fa2e8d1ab"
},
"source": [
"### Standard Python magic methods\n",
"\n",
"There are many standard magic methods in Python. Here are a few of the most\n",
"important ones used in Cirq:\n",
" * `__str__` for user-friendly string output and `__repr__` is the Python-friendly string output, meaning that `eval(repr(y))==y` should always be true.\n",
" * `__eq__` and `__hash__` which define whether objects are equal or not. You\n",
" can also use `cirq.value.value_equality` for objects that have a small list\n",
" of sub-values that can be compared for equality.\n",
" * Arithmetic functions such as `__pow__`, `__mul__`, `__add__` define the\n",
" action of `**`, `*`, and `+` respectively.\n",
" \n",
"### `cirq.num_qubits` and `def _num_qubits_`\n",
"\n",
"A `Gate` must implement the `_num_qubits_` (or `_qid_shape_`) method.\n",
"This method returns an integer and is used by `cirq.num_qubits` to determine\n",
"how many qubits this gate operates on.\n",
"\n",
"### `cirq.qid_shape` and `def _qid_shape_`\n",
"\n",
"A qudit gate or operation must implement the `_qid_shape_` method that returns a\n",
"tuple of integers. This method is used to determine how many qudits the gate or\n",
"operation operates on and what dimension each qudit must be. If only the\n",
"`_num_qubits_` method is implemented, the object is assumed to operate only on\n",
"qubits. Callers can query the qid shape of the object by calling\n",
"`cirq.qid_shape` on it. See [qudit documentation](qudits.ipynb) for more\n",
"information.\n",
"\n",
"### `cirq.unitary` and `def _unitary_`\n",
"\n",
"When an object can be described by a unitary matrix, it can expose that unitary\n",
"matrix by implementing a `_unitary_(self) -> np.ndarray` method.\n",
"Callers can query whether or not an object has a unitary matrix by calling\n",
"`cirq.unitary` on it.\n",
"The `_unitary_` method may also return `NotImplemented`, in which case\n",
"`cirq.unitary` behaves as if the method is not implemented.\n",
"\n",
"### `cirq.decompose` and `def _decompose_`\n",
"\n",
"Operations and gates can be defined in terms of other operations by implementing\n",
"a `_decompose_` method that returns those other operations. Operations implement\n",
"`_decompose_(self)` whereas gates implement `_decompose_(self, qubits)`\n",
"(since gates don't know their qubits ahead of time).\n",
"\n",
"The main requirements on the output of `_decompose_` methods are:\n",
"\n",
"1. DO NOT CREATE CYCLES. The `cirq.decompose` method will iterative decompose until it finds values satisfying a `keep` predicate. Cycles cause it to enter an infinite loop.\n",
"2. Head towards operations defined by Cirq, because these operations have good decomposition methods that terminate in single-qubit and two qubit gates.\n",
"These gates can be understood by the simulator, optimizers, and other code.\n",
"3. All that matters is functional equivalence.\n",
"Don't worry about staying within or reaching a particular gate set; it's too hard to predict what the caller will want. Gate-set-aware decomposition is useful, but *this is not the protocol that does that*.\n",
"Instead, use features available in the [transformer API](../transform/transformers.ipynb#compiling_to_nisq_targets_cirqcompilationtargetgateset).\n",
"\n",
"For example, `cirq.CCZ` decomposes into a series of `cirq.CNOT` and `cirq.T` operations.\n",
"This allows code that doesn't understand three-qubit operation to work with `cirq.CCZ`; by decomposing it into operations they do understand.\n",
"As another example, `cirq.TOFFOLI` decomposes into a `cirq.H` followed by a `cirq.CCZ` followed by a `cirq.H`.\n",
"Although the output contains a three qubit operation (the CCZ), that operation can be decomposed into two qubit and one qubit operations.\n",
"So code that doesn't understand three qubit operations can deal with Toffolis by decomposing them, and then decomposing the CCZs that result from the initial decomposition.\n",
"\n",
"In general, decomposition-aware code consuming operations is expected to recursively decompose unknown operations until the code either hits operations it understands or hits a dead end where no more decomposition is possible.\n",
"The `cirq.decompose` method implements logic for performing exactly this kind of recursive decomposition.\n",
"Callers specify a `keep` predicate, and optionally specify intercepting and fallback decomposers, and then `cirq.decompose` will repeatedly decompose whatever operations it was given until the operations satisfy the given `keep`.\n",
"If `cirq.decompose` hits a dead end, it raises an error.\n",
"\n",
"Cirq doesn't make any guarantees about the \"target gate set\" decomposition is heading towards.\n",
"`cirq.decompose` is not a method\n",
"Decompositions within Cirq happen to converge towards X, Y, Z, CZ, PhasedX, specified-matrix gates, and others.\n",
"But this set will vary from release to release, and so it is important for consumers of decompositions to look for generic properties of gates,\n",
"such as \"two qubit gate with a unitary matrix\", instead of specific gate types such as CZ gates.\n",
"\n",
"### `cirq.inverse` and `__pow__`\n",
"\n",
"Gates and operations are considered to be *invertible* when they implement a `__pow__` method that returns a result besides `NotImplemented` for an exponent of -1.\n",
"This inverse can be accessed either directly as `value**-1`, or via the utility method `cirq.inverse(value)`.\n",
"If you are sure that `value` has an inverse, saying `value**-1` is more convenient than saying `cirq.inverse(value)`.\n",
"`cirq.inverse` is for cases where you aren't sure if `value` is invertible, or where `value` might be a *sequence* of invertible operations.\n",
"\n",
"`cirq.inverse` has a `default` parameter used as a fallback when `value` isn't invertible.\n",
"For example, `cirq.inverse(value, default=None)` returns the inverse of `value`, or else returns `None` if `value` isn't invertible.\n",
"(If no `default` is specified and `value` isn't invertible, a `TypeError` is raised.)\n",
"\n",
"When you give `cirq.inverse` a list, or any other kind of iterable thing, it will return a sequence of operations that (if run in order) undoes the operations of the original sequence (if run in order).\n",
"Basically, the items of the list are individually inverted and returned in reverse order.\n",
"For example, the expression `cirq.inverse([cirq.S(b), cirq.CNOT(a, b)])` will return the tuple `(cirq.CNOT(a, b), cirq.S(b)**-1)`.\n",
"\n",
"Gates and operations can also return values beside `NotImplemented` from their `__pow__` method for exponents besides `-1`.\n",
"This pattern is used often by Cirq.\n",
"For example, the square root of X gate can be created by raising `cirq.X` to 0.5:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"execution": {
"iopub.execute_input": "2025-03-01T10:30:49.905640Z",
"iopub.status.busy": "2025-03-01T10:30:49.905111Z",
"iopub.status.idle": "2025-03-01T10:30:49.909931Z",
"shell.execute_reply": "2025-03-01T10:30:49.909287Z"
},
"id": "a37d151e71ed"
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"[[0.+0.j 1.+0.j]\n",
" [1.+0.j 0.+0.j]]\n",
"[[0.5+0.5j 0.5-0.5j]\n",
" [0.5-0.5j 0.5+0.5j]]\n"
]
}
],
"source": [
"print(cirq.unitary(cirq.X))\n",
"# prints\n",
"# [[0.+0.j 1.+0.j]\n",
"# [1.+0.j 0.+0.j]]\n",
"\n",
"sqrt_x = cirq.X**0.5\n",
"print(cirq.unitary(sqrt_x))\n",
"# prints\n",
"# [[0.5+0.5j 0.5-0.5j]\n",
"# [0.5-0.5j 0.5+0.5j]]"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "6fe65e2eb967"
},
"source": [
"The Pauli gates included in Cirq use the convention ``Z**0.5 ≡ S ≡ np.diag(1, i)``, ``Z**-0.5 ≡ S**-1``, ``X**0.5 ≡ H·S·H``, and the square root of ``Y`` is inferred via the right hand rule.\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"id": "9d8cecee52e8"
},
"source": [
"### `_circuit_diagram_info_(self, args)` and `cirq.circuit_diagram_info(val, [args], [default])`\n",
"\n",
"Circuit diagrams are useful for visualizing the structure of a `Circuit`.\n",
"Gates can specify compact representations to use in diagrams by implementing a `_circuit_diagram_info_` method.\n",
"For example, this is why SWAP gates are shown as linked '×' characters in diagrams.\n",
"\n",
"The `_circuit_diagram_info_` method takes an `args` parameter of type `cirq.CircuitDiagramInfoArgs` and returns either\n",
"a string (typically the gate's name), a sequence of strings (a label to use on each qubit targeted by the gate), or an\n",
"instance of `cirq.CircuitDiagramInfo` (which can specify more advanced properties such as exponents and will expand\n",
"in the future).\n",
"\n",
"You can query the circuit diagram info of a value by passing it into `cirq.circuit_diagram_info`."
]
}
],
"metadata": {
"colab": {
"collapsed_sections": [
"Sh9QBnKbFf_B"
],
"name": "custom_gates.ipynb",
"toc_visible": true
},
"kernelspec": {
"display_name": "Python 3",
"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.10.16"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
|