{ "cells": [ { "cell_type": "markdown", "id": "4b1ce9ef-6970-49bf-bae4-332d3eef0423", "metadata": {}, "source": [ "# Control-Flow\n", "\n", "**Download this notebook - {nb-download}`control-flow.ipynb`**" ] }, { "cell_type": "code", "execution_count": 1, "id": "0ef5d6cd-cb12-4485-97fb-eae6e4c1cd32", "metadata": {}, "outputs": [], "source": [ "from guppylang import guppy\n", "from guppylang.std.builtins import result\n", "from guppylang.std.quantum import measure, qubit, discard, h, tdg, cx, t, z" ] }, { "cell_type": "markdown", "id": "9ab7cb6e-b11b-4b0b-aab9-a113bb2618b0", "metadata": {}, "source": [ "Implement an $V_3 = R_z(-2\\arctan(2)) = (I + 2iZ)/\\sqrt{5}$ gate using the repeat-until-success scheme from https://arxiv.org/abs/1311.1074." ] }, { "cell_type": "code", "execution_count": 2, "id": "1be5c488-36df-4a8b-b0af-0a330a8293fd", "metadata": {}, "outputs": [], "source": [ "@guppy\n", "def repeat_until_success(q: qubit) -> None:\n", " attempts = 0\n", " while True:\n", " attempts += 1\n", "\n", " # Prepare ancillas\n", " a, b = qubit(), qubit()\n", " h(a)\n", " h(b)\n", "\n", " tdg(a)\n", " cx(b, a)\n", " t(a)\n", " h(a)\n", " if measure(a):\n", " # First part failed, try again\n", " discard(b)\n", " continue\n", "\n", " t(q)\n", " z(q)\n", " cx(q, b)\n", " t(b)\n", " h(b)\n", " if measure(b):\n", " # Second part failed, apply correction\n", " # and try again\n", " z(q)\n", " continue\n", "\n", " result(\"attempts\", attempts)\n", " break" ] }, { "cell_type": "code", "execution_count": 3, "id": "fbd490b3-8cc4-43c2-87f8-e799d00fa2c2", "metadata": {}, "outputs": [], "source": [ "@guppy\n", "def main() -> None:\n", " q = qubit()\n", " repeat_until_success(q)\n", " measure(q)" ] }, { "cell_type": "code", "execution_count": 4, "id": "831c0673-a3f1-4159-bf39-aae7ec9e3323", "metadata": {}, "outputs": [ { "data": { "text/plain": [ "1.49" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "shots = main.emulator(n_qubits=3).with_seed(0).with_shots(100).run()\n", "sum(int(shot.as_dict()[\"attempts\"]) for shot in shots) / len(shots)" ] } ], "metadata": { "kernelspec": { "display_name": "venv", "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.2" } }, "nbformat": 4, "nbformat_minor": 5 }