{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "a2f48f2b",
      "metadata": {},
      "source": [
        "Import the Q# module.\n",
        "\n",
        "This enables the `%%qsharp` magic and initializes a Q# interpreter singleton."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ed1b75bf",
      "metadata": {},
      "source": []
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "1e8e4faa",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "application/javascript": "// Copyright (c) Microsoft Corporation.\n// Licensed under the MIT License.\n\n// This file provides CodeMirror syntax highlighting for Q# magic cells\n// in classic Jupyter Notebooks. It does nothing in other (Jupyter Notebook 7,\n// VS Code, Azure Notebooks, etc.) environments.\n\n// Detect the prerequisites and do nothing if they don't exist.\nif (window.require && window.CodeMirror && window.Jupyter) {\n  // The simple mode plugin for CodeMirror is not loaded by default, so require it.\n  window.require([\"codemirror/addon/mode/simple\"], function defineMode() {\n    let rules = [\n      {\n        token: \"comment\",\n        regex: /(\\/\\/).*/,\n        beginWord: false,\n      },\n      {\n        token: \"string\",\n        regex: String.raw`^\\\"(?:[^\\\"\\\\]|\\\\[\\s\\S])*(?:\\\"|$)`,\n        beginWord: false,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(namespace|open|as|operation|function|body|adjoint|newtype|controlled|internal)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(if|elif|else|repeat|until|fixup|for|in|return|fail|within|apply)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(Adjoint|Controlled|Adj|Ctl|is|self|auto|distribute|invert|intrinsic)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"keyword\",\n        regex: String.raw`(let|set|use|borrow|mutable)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"operatorKeyword\",\n        regex: String.raw`(not|and|or)\\b|(w/)`,\n        beginWord: true,\n      },\n      {\n        token: \"operatorKeyword\",\n        regex: String.raw`(=)|(!)|(<)|(>)|(\\+)|(-)|(\\*)|(/)|(\\^)|(%)|(\\|)|(&&&)|(~~~)|(\\.\\.\\.)|(\\.\\.)|(\\?)`,\n        beginWord: false,\n      },\n      {\n        token: \"meta\",\n        regex: String.raw`(Int|BigInt|Double|Bool|Qubit|Pauli|Result|Range|String|Unit)\\b`,\n        beginWord: true,\n      },\n      {\n        token: \"atom\",\n        regex: String.raw`(true|false|Pauli(I|X|Y|Z)|One|Zero)\\b`,\n        beginWord: true,\n      },\n    ];\n    let simpleRules = [];\n    for (let rule of rules) {\n      simpleRules.push({\n        token: rule.token,\n        regex: new RegExp(rule.regex, \"g\"),\n        sol: rule.beginWord,\n      });\n      if (rule.beginWord) {\n        // Need an additional rule due to the fact that CodeMirror simple mode doesn't work with ^ token\n        simpleRules.push({\n          token: rule.token,\n          regex: new RegExp(String.raw`\\W` + rule.regex, \"g\"),\n          sol: false,\n        });\n      }\n    }\n\n    // Register the mode defined above with CodeMirror\n    window.CodeMirror.defineSimpleMode(\"qsharp\", { start: simpleRules });\n    window.CodeMirror.defineMIME(\"text/x-qsharp\", \"qsharp\");\n\n    // Tell Jupyter to associate %%qsharp magic cells with the qsharp mode\n    window.Jupyter.CodeCell.options_default.highlight_modes[\"qsharp\"] = {\n      reg: [/^%%qsharp/],\n    };\n\n    // Force re-highlighting of all cells the first time this code runs\n    for (const cell of window.Jupyter.notebook.get_cells()) {\n      cell.auto_highlight();\n    }\n  });\n}\n",
            "text/plain": []
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import qsharp\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3a536d53",
      "metadata": {},
      "source": [
        "Run Q# using the `%%qsharp` magic.\n",
        "\n",
        "`DumpMachine()` and `Message()` output get formatted as HTML. Return value is shown as cell output."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "9df62352",
      "metadata": {
        "vscode": {
          "languageId": "qsharp"
        }
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>The result of the measurement is One</p>"
            ],
            "text/plain": [
              "The result of the measurement is One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/plain": [
              "One"
            ]
          },
          "execution_count": 2,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "%%qsharp\n",
        "\n",
        "operation Main() : Result {\n",
        "    use q = Qubit();\n",
        "    X(q);\n",
        "    Microsoft.Quantum.Diagnostics.DumpMachine();\n",
        "    let r = M(q);\n",
        "    Message($\"The result of the measurement is {r}\");\n",
        "    Reset(q);\n",
        "    r\n",
        "}\n",
        "\n",
        "Main()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "4584c494",
      "metadata": {},
      "source": [
        "`qsharp.eval()` does the same thing as the `%%qsharp` magic.\n",
        "\n",
        "`DumpMachine()` and `Message()` print to stdout and get displayed in the notebook as plain text"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "7d0995bf",
      "metadata": {
        "scrolled": true
      },
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "STATE:\n",
            "|1⟩: 1.0000+0.0000𝑖\n",
            "The result of the measurement is One\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "One"
            ]
          },
          "execution_count": 3,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "qsharp.eval(\"Main()\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a3bde193",
      "metadata": {},
      "source": [
        "Assign a result to a Python variable."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "50383f8a",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Result: 3 (type: int)\n"
          ]
        }
      ],
      "source": [
        "result = qsharp.eval(\"1 + 2\")\n",
        "\n",
        "print(f\"Result: {result} (type: {type(result).__name__})\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b06b7857",
      "metadata": {},
      "source": [
        "Errors are exceptions. \n",
        "\n",
        "Catch and handle compilation errors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "33fd3c4d",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "\u001b[31mQsc.Resolve.NotFound\u001b[0m\n",
            "\n",
            "  \u001b[31m×\u001b[0m name error\n",
            "\u001b[31m  ╰─▶ \u001b[0m`Bar` not found\n",
            "   ╭─[\u001b[36;1;4mline_3\u001b[0m:2:1]\n",
            " \u001b[2m2\u001b[0m │ operation Foo() : Unit {\n",
            " \u001b[2m3\u001b[0m │     Bar();\n",
            "   · \u001b[35;1m    ───\u001b[0m\n",
            " \u001b[2m4\u001b[0m │     Baz();\n",
            "   ╰────\n",
            "\u001b[31mQsc.Resolve.NotFound\u001b[0m\n",
            "\n",
            "  \u001b[31m×\u001b[0m name error\n",
            "\u001b[31m  ╰─▶ \u001b[0m`Baz` not found\n",
            "   ╭─[\u001b[36;1;4mline_3\u001b[0m:3:1]\n",
            " \u001b[2m3\u001b[0m │     Bar();\n",
            " \u001b[2m4\u001b[0m │     Baz();\n",
            "   · \u001b[35;1m    ───\u001b[0m\n",
            " \u001b[2m5\u001b[0m │ }\n",
            "   ╰────\n",
            "\u001b[31mQsc.TypeCk.AmbiguousTy\u001b[0m\n",
            "\n",
            "  \u001b[31m×\u001b[0m type error\n",
            "\u001b[31m  ╰─▶ \u001b[0minsufficient type information to infer type\n",
            "   ╭─[\u001b[36;1;4mline_3\u001b[0m:2:1]\n",
            " \u001b[2m2\u001b[0m │ operation Foo() : Unit {\n",
            " \u001b[2m3\u001b[0m │     Bar();\n",
            "   · \u001b[35;1m    ─────\u001b[0m\n",
            " \u001b[2m4\u001b[0m │     Baz();\n",
            "   ╰────\n",
            "\u001b[36m  help: \u001b[0mprovide a type annotation\n",
            "\u001b[31mQsc.TypeCk.AmbiguousTy\u001b[0m\n",
            "\n",
            "  \u001b[31m×\u001b[0m type error\n",
            "\u001b[31m  ╰─▶ \u001b[0minsufficient type information to infer type\n",
            "   ╭─[\u001b[36;1;4mline_3\u001b[0m:3:1]\n",
            " \u001b[2m3\u001b[0m │     Bar();\n",
            " \u001b[2m4\u001b[0m │     Baz();\n",
            "   · \u001b[35;1m    ─────\u001b[0m\n",
            " \u001b[2m5\u001b[0m │ }\n",
            "   ╰────\n",
            "\u001b[36m  help: \u001b[0mprovide a type annotation\n",
            "\n"
          ]
        }
      ],
      "source": [
        "from qsharp import QSharpError\n",
        "\n",
        "try:\n",
        "    qsharp.eval(\n",
        "        \"\"\"\n",
        "operation Foo() : Unit {\n",
        "    Bar();\n",
        "    Baz();\n",
        "}\n",
        "\"\"\"\n",
        "    )\n",
        "except QSharpError as ex:\n",
        "    print(ex)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "00f82a16",
      "metadata": {},
      "source": [
        "Catch and handle runtime errors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "e70a95d9",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Error: Qubit0 released while not in |0⟩ state\n",
            "Call stack:\n",
            "    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n",
            "    at Foo in line_4\n",
            "\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n",
            "\n",
            "  \u001b[31m×\u001b[0m runtime error\n",
            "\u001b[31m  ╰─▶ \u001b[0mQubit0 released while not in |0⟩ state\n",
            "   ╭─[\u001b[36;1;4mline_4\u001b[0m:1:1]\n",
            " \u001b[2m1\u001b[0m │ operation Foo() : Unit { use q = Qubit(); X(q) } Foo()\n",
            "   · \u001b[35;1m                         ────────┬───────\u001b[0m\n",
            "   ·                                  \u001b[35;1m╰── \u001b[35;1mQubit0\u001b[0m\u001b[0m\n",
            "   ╰────\n",
            "\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n",
            "        satisfy the assumption that allocated qubits start in the |0⟩ state\n",
            "\n"
          ]
        }
      ],
      "source": [
        "try:\n",
        "    qsharp.eval(\"operation Foo() : Unit { use q = Qubit(); X(q) } Foo()\")\n",
        "except QSharpError as ex:\n",
        "    print(ex)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "3e294471",
      "metadata": {},
      "source": [
        "A runtime error that's not caught gets reported as a Python exception."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "d40d86cb",
      "metadata": {},
      "outputs": [
        {
          "ename": "QSharpError",
          "evalue": "Error: Qubit1 released while not in |0⟩ state\nCall stack:\n    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n    at Foo in line_5\n\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n\n  \u001b[31m×\u001b[0m runtime error\n\u001b[31m  ╰─▶ \u001b[0mQubit1 released while not in |0⟩ state\n   ╭─[\u001b[36;1;4mline_5\u001b[0m:1:1]\n \u001b[2m1\u001b[0m │ operation Foo() : Unit { use q = Qubit(); X(q) } Foo()\n   · \u001b[35;1m                         ────────┬───────\u001b[0m\n   ·                                  \u001b[35;1m╰── \u001b[35;1mQubit1\u001b[0m\u001b[0m\n   ╰────\n\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n        satisfy the assumption that allocated qubits start in the |0⟩ state\n",
          "output_type": "error",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mQSharpError\u001b[0m                               Traceback (most recent call last)",
            "Cell \u001b[0;32mIn[7], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mqsharp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43meval\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43moperation Foo() : Unit \u001b[39;49m\u001b[38;5;124;43m{\u001b[39;49m\u001b[38;5;124;43m use q = Qubit(); X(q) } Foo()\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m)\u001b[49m\n",
            "File \u001b[0;32m~/Programming/qsharp/pip/qsharp/_qsharp.py:120\u001b[0m, in \u001b[0;36meval\u001b[0;34m(source)\u001b[0m\n\u001b[1;32m    117\u001b[0m \u001b[38;5;28;01mdef\u001b[39;00m \u001b[38;5;21mcallback\u001b[39m(output: Output) \u001b[38;5;241m-\u001b[39m\u001b[38;5;241m>\u001b[39m \u001b[38;5;28;01mNone\u001b[39;00m:\n\u001b[1;32m    118\u001b[0m     \u001b[38;5;28mprint\u001b[39m(output)\n\u001b[0;32m--> 120\u001b[0m \u001b[38;5;28;01mreturn\u001b[39;00m \u001b[43mget_interpreter\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43minterpret\u001b[49m\u001b[43m(\u001b[49m\u001b[43msource\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mcallback\u001b[49m\u001b[43m)\u001b[49m\n",
            "\u001b[0;31mQSharpError\u001b[0m: Error: Qubit1 released while not in |0⟩ state\nCall stack:\n    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n    at Foo in line_5\n\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n\n  \u001b[31m×\u001b[0m runtime error\n\u001b[31m  ╰─▶ \u001b[0mQubit1 released while not in |0⟩ state\n   ╭─[\u001b[36;1;4mline_5\u001b[0m:1:1]\n \u001b[2m1\u001b[0m │ operation Foo() : Unit { use q = Qubit(); X(q) } Foo()\n   · \u001b[35;1m                         ────────┬───────\u001b[0m\n   ·                                  \u001b[35;1m╰── \u001b[35;1mQubit1\u001b[0m\u001b[0m\n   ╰────\n\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n        satisfy the assumption that allocated qubits start in the |0⟩ state\n"
          ]
        }
      ],
      "source": [
        "qsharp.eval(\"operation Foo() : Unit { use q = Qubit(); X(q) } Foo()\")\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ba2f98ad",
      "metadata": {},
      "source": [
        "In `%%qsharp` cells, exceptions are handled and displayed as error text."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "1b55e53c",
      "metadata": {
        "scrolled": false,
        "vscode": {
          "languageId": "qsharp"
        }
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|110⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|110⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "ename": "QSharpCellError",
          "evalue": "Error: Qubit2 released while not in |0⟩ state\nCall stack:\n    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n    at Bar in line_6\n\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n\n  \u001b[31m×\u001b[0m runtime error\n\u001b[31m  ╰─▶ \u001b[0mQubit2 released while not in |0⟩ state\n   ╭─[\u001b[36;1;4mline_6\u001b[0m:2:1]\n \u001b[2m2\u001b[0m │ operation Bar() : Unit {\n \u001b[2m3\u001b[0m │     use q = Qubit();\n   · \u001b[35;1m    ────────┬───────\u001b[0m\n   ·             \u001b[35;1m╰── \u001b[35;1mQubit2\u001b[0m\u001b[0m\n \u001b[2m4\u001b[0m │     Microsoft.Quantum.Diagnostics.DumpMachine();\n   ╰────\n\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n        satisfy the assumption that allocated qubits start in the |0⟩ state\n",
          "output_type": "error",
          "traceback": [
            "Error: Qubit2 released while not in |0⟩ state",
            "Call stack:",
            "    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs",
            "    at Bar in line_6",
            "\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m",
            "",
            "  \u001b[31m×\u001b[0m runtime error",
            "\u001b[31m  ╰─▶ \u001b[0mQubit2 released while not in |0⟩ state",
            "   ╭─[\u001b[36;1;4mline_6\u001b[0m:2:1]",
            " \u001b[2m2\u001b[0m │ operation Bar() : Unit {",
            " \u001b[2m3\u001b[0m │     use q = Qubit();",
            "   · \u001b[35;1m    ────────┬───────\u001b[0m",
            "   ·             \u001b[35;1m╰── \u001b[35;1mQubit2\u001b[0m\u001b[0m",
            " \u001b[2m4\u001b[0m │     Microsoft.Quantum.Diagnostics.DumpMachine();",
            "   ╰────",
            "\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to",
            "        satisfy the assumption that allocated qubits start in the |0⟩ state"
          ]
        }
      ],
      "source": [
        "%%qsharp\n",
        "\n",
        "operation Bar() : Unit {\n",
        "    use q = Qubit();\n",
        "    Microsoft.Quantum.Diagnostics.DumpMachine();\n",
        "    X(q);\n",
        "}\n",
        "\n",
        "Bar()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "98247ac2",
      "metadata": {},
      "source": [
        "Streaming output for long running operations."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "bd25ae87",
      "metadata": {
        "vscode": {
          "languageId": "qsharp"
        }
      },
      "outputs": [
        {
          "data": {
            "text/html": [
              "<p>Generating random bit... </p>"
            ],
            "text/plain": [
              "Generating random bit... "
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1111⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1111⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>Result: One</p>"
            ],
            "text/plain": [
              "Result: One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1111⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1111⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>Result: One</p>"
            ],
            "text/plain": [
              "Result: One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1111⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1111⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>Result: One</p>"
            ],
            "text/plain": [
              "Result: One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1111⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1111⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>Result: One</p>"
            ],
            "text/plain": [
              "Result: One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<table>\n",
              "  <thead>\n",
              "    <tr>\n",
              "      <th style=\"text-align: left\">Basis State<br />(|𝜓₁…𝜓ₙ⟩)</th>\n",
              "      <th style=\"text-align: left\">Amplitude</th>\n",
              "      <th style=\"text-align: left\">Measurement Probability</th>\n",
              "      <th style=\"text-align: left\" colspan=\"2\">Phase</th>\n",
              "    </tr>\n",
              "  </thead>\n",
              "  <tbody>\n",
              "    <tr>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">|1111⟩</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">1.0000+0.0000𝑖</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <progress max=\"100\" value=\"100\"></progress>\n",
              "    <span style=\"display: inline-block\">100.0000%</span>\n",
              "  </td>\n",
              "  <td style=\"text-align: left; transform: rotate(0.0000rad)\">↑</td>\n",
              "  <td style=\"text-align: left\">\n",
              "    <span style=\"display: inline-block\">0.0000</span>\n",
              "  </td>\n",
              "</tr>\n",
              "\n",
              "  </tbody>\n",
              "</table>\n"
            ],
            "text/plain": [
              "STATE:\n",
              "|1111⟩: 1.0000+0.0000𝑖"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "data": {
            "text/html": [
              "<p>Result: One</p>"
            ],
            "text/plain": [
              "Result: One"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "%%qsharp\n",
        "\n",
        "open Microsoft.Quantum.Diagnostics;\n",
        "\n",
        "operation Main() : Unit {\n",
        "    Message(\"Generating random bit... \");\n",
        "    for i in 0..400000 {\n",
        "        use q = Qubit();\n",
        "        H(q);\n",
        "        let r = M(q);\n",
        "        if (i % 100000) == 0 {\n",
        "            DumpMachine();\n",
        "            Message($\"Result: {r}\");\n",
        "        }\n",
        "        Reset(q);\n",
        "    }\n",
        "}\n",
        "\n",
        "Main()\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2a2d9e7d",
      "metadata": {},
      "source": [
        "Running multiple shots for an expression. Each shot uses an independent instance of the simulator. A list of results (or runtime errors) is returned."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "eb3cd29f",
      "metadata": {
        "vscode": {
          "languageId": "qsharp"
        }
      },
      "outputs": [],
      "source": [
        "%%qsharp\n",
        "\n",
        "operation RandomBit() : Result {\n",
        "    use q = Qubit();\n",
        "    H(q);\n",
        "    let res = M(q);\n",
        "    Reset(q);\n",
        "    return res;\n",
        "}\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "9a9f5335",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "[One, Zero, Zero, Zero, Zero, Zero, Zero, One, Zero, Zero]"
            ]
          },
          "execution_count": 11,
          "metadata": {},
          "output_type": "execute_result"
        }
      ],
      "source": [
        "results = qsharp.run(\"RandomBit()\", 10)\n",
        "\n",
        "results\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6a476e6d",
      "metadata": {},
      "source": [
        "The results can then be processed, e.g. plotted in a histogram using popular Python libraries."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "7bd77379",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Requirement already satisfied: matplotlib in /opt/homebrew/lib/python3.11/site-packages (3.8.2)\n",
            "Requirement already satisfied: contourpy>=1.0.1 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (1.2.0)\n",
            "Requirement already satisfied: cycler>=0.10 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (0.12.1)\n",
            "Requirement already satisfied: fonttools>=4.22.0 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (4.46.0)\n",
            "Requirement already satisfied: kiwisolver>=1.3.1 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (1.4.5)\n",
            "Requirement already satisfied: numpy<2,>=1.21 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (1.23.5)\n",
            "Requirement already satisfied: packaging>=20.0 in /Users/swernli/Library/Python/3.11/lib/python/site-packages (from matplotlib) (23.2)\n",
            "Requirement already satisfied: pillow>=8 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (10.1.0)\n",
            "Requirement already satisfied: pyparsing>=2.3.1 in /opt/homebrew/lib/python3.11/site-packages (from matplotlib) (3.1.1)\n",
            "Requirement already satisfied: python-dateutil>=2.7 in /Users/swernli/Library/Python/3.11/lib/python/site-packages (from matplotlib) (2.8.2)\n",
            "Requirement already satisfied: six>=1.5 in /opt/homebrew/lib/python3.11/site-packages (from python-dateutil>=2.7->matplotlib) (1.16.0)\n",
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "%pip install matplotlib\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "83cee4e8",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "image/png": "[encoded data, 8596 characters]",
            "text/plain": [
              "<Figure size 640x480 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import matplotlib.pyplot as plt\n",
        "import numpy as np\n",
        "from collections import Counter\n",
        "\n",
        "# Sort the results so that the histogram labels appear in the correct order\n",
        "results.sort()\n",
        "# Count the number of times each result appears\n",
        "counts = Counter(results)\n",
        "\n",
        "(values, counts) = counts.keys(), counts.values()\n",
        "xlabels = np.arange(len(counts))\n",
        "plt.bar(xlabels, counts)\n",
        "plt.xticks(xlabels, values)\n",
        "plt.show()\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "eaf766f4",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Requirement already satisfied: pandas in /opt/homebrew/lib/python3.11/site-packages (2.1.3)\n",
            "Requirement already satisfied: numpy<2,>=1.23.2 in /opt/homebrew/lib/python3.11/site-packages (from pandas) (1.23.5)\n",
            "Requirement already satisfied: python-dateutil>=2.8.2 in /Users/swernli/Library/Python/3.11/lib/python/site-packages (from pandas) (2.8.2)\n",
            "Requirement already satisfied: pytz>=2020.1 in /opt/homebrew/lib/python3.11/site-packages (from pandas) (2023.3.post1)\n",
            "Requirement already satisfied: tzdata>=2022.1 in /opt/homebrew/lib/python3.11/site-packages (from pandas) (2023.3)\n",
            "Requirement already satisfied: six>=1.5 in /opt/homebrew/lib/python3.11/site-packages (from python-dateutil>=2.8.2->pandas) (1.16.0)\n",
            "Note: you may need to restart the kernel to use updated packages.\n"
          ]
        }
      ],
      "source": [
        "%pip install pandas\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 13,
      "id": "8095640a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Axes: >"
            ]
          },
          "execution_count": 13,
          "metadata": {},
          "output_type": "execute_result"
        },
        {
          "data": {
            "image/png": "[encoded data, 9032 characters]",
            "text/plain": [
              "<Figure size 640x480 with 1 Axes>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "import pandas\n",
        "from collections import Counter\n",
        "\n",
        "# Sort the results so that the histogram labels appear in the correct order\n",
        "results.sort()\n",
        "pandas.Series(results).value_counts(sort=False).plot(kind='bar')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "990642e4",
      "metadata": {},
      "source": [
        "A compiler error in the entry expression:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "f045ad9c",
      "metadata": {},
      "outputs": [
        {
          "ename": "QSharpError",
          "evalue": "\u001b[31mQsc.TypeCk.TyMismatch\u001b[0m\n\n  \u001b[31m×\u001b[0m type error\n\u001b[31m  ╰─▶ \u001b[0mexpected Unit, found String\n   ╭─[\u001b[36;1;4m<entry>\u001b[0m:1:1]\n \u001b[2m1\u001b[0m │ RandomBit(\"a\")\n   · \u001b[35;1m──────────────\u001b[0m\n   ╰────\n",
          "output_type": "error",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mQSharpError\u001b[0m                               Traceback (most recent call last)",
            "Cell \u001b[0;32mIn[14], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mqsharp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\"\"\u001b[39;49m\u001b[38;5;124;43mRandomBit(\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43ma\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43m)\u001b[39;49m\u001b[38;5;124;43m\"\"\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m)\u001b[49m\n",
            "File \u001b[0;32m~/Programming/qsharp/pip/qsharp/_qsharp.py:165\u001b[0m, in \u001b[0;36mrun\u001b[0;34m(entry_expr, shots, on_result, save_events)\u001b[0m\n\u001b[1;32m    163\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(shots):\n\u001b[1;32m    164\u001b[0m     results\u001b[38;5;241m.\u001b[39mappend({\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;28;01mNone\u001b[39;00m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mevents\u001b[39m\u001b[38;5;124m\"\u001b[39m: []})\n\u001b[0;32m--> 165\u001b[0m     run_results \u001b[38;5;241m=\u001b[39m \u001b[43mget_interpreter\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m    166\u001b[0m \u001b[43m        \u001b[49m\u001b[43mentry_expr\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mon_save_events\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43msave_events\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mprint_output\u001b[49m\n\u001b[1;32m    167\u001b[0m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    168\u001b[0m     results[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_results\n\u001b[1;32m    169\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m on_result:\n",
            "\u001b[0;31mQSharpError\u001b[0m: \u001b[31mQsc.TypeCk.TyMismatch\u001b[0m\n\n  \u001b[31m×\u001b[0m type error\n\u001b[31m  ╰─▶ \u001b[0mexpected Unit, found String\n   ╭─[\u001b[36;1;4m<entry>\u001b[0m:1:1]\n \u001b[2m1\u001b[0m │ RandomBit(\"a\")\n   · \u001b[35;1m──────────────\u001b[0m\n   ╰────\n"
          ]
        }
      ],
      "source": [
        "qsharp.run(\"\"\"RandomBit(\"a\")\"\"\", 10)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0ba56462",
      "metadata": {},
      "source": [
        "Some shots throw runtime errors:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "9b85eb2d",
      "metadata": {
        "vscode": {
          "languageId": "qsharp"
        }
      },
      "outputs": [],
      "source": [
        "%%qsharp\n",
        "\n",
        "operation Bad() : Unit {\n",
        "    use q = Qubit();\n",
        "    H(q);\n",
        "    let res = M(q);\n",
        "    if (res == One) {\n",
        "        // Do something bad, sometimes\n",
        "        use q2 = Qubit();\n",
        "        X(q2);\n",
        "    }\n",
        "}\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "2445df05",
      "metadata": {},
      "outputs": [
        {
          "ename": "QSharpError",
          "evalue": "Error: Qubit1 released while not in |0⟩ state\nCall stack:\n    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n    at Bad in line_9\n\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n\n  \u001b[31m×\u001b[0m runtime error\n\u001b[31m  ╰─▶ \u001b[0mQubit1 released while not in |0⟩ state\n   ╭─[\u001b[36;1;4mline_9\u001b[0m:7:1]\n \u001b[2m7\u001b[0m │         // Do something bad, sometimes\n \u001b[2m8\u001b[0m │         use q2 = Qubit();\n   · \u001b[35;1m        ────────┬────────\u001b[0m\n   ·                 \u001b[35;1m╰── \u001b[35;1mQubit1\u001b[0m\u001b[0m\n \u001b[2m9\u001b[0m │         X(q2);\n   ╰────\n\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n        satisfy the assumption that allocated qubits start in the |0⟩ state\n",
          "output_type": "error",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mQSharpError\u001b[0m                               Traceback (most recent call last)",
            "Cell \u001b[0;32mIn[16], line 1\u001b[0m\n\u001b[0;32m----> 1\u001b[0m \u001b[43mqsharp\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[38;5;124;43mBad()\u001b[39;49m\u001b[38;5;124;43m\"\u001b[39;49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;241;43m10\u001b[39;49m\u001b[43m)\u001b[49m\n",
            "File \u001b[0;32m~/Programming/qsharp/pip/qsharp/_qsharp.py:165\u001b[0m, in \u001b[0;36mrun\u001b[0;34m(entry_expr, shots, on_result, save_events)\u001b[0m\n\u001b[1;32m    163\u001b[0m \u001b[38;5;28;01mfor\u001b[39;00m _ \u001b[38;5;129;01min\u001b[39;00m \u001b[38;5;28mrange\u001b[39m(shots):\n\u001b[1;32m    164\u001b[0m     results\u001b[38;5;241m.\u001b[39mappend({\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m\"\u001b[39m: \u001b[38;5;28;01mNone\u001b[39;00m, \u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mevents\u001b[39m\u001b[38;5;124m\"\u001b[39m: []})\n\u001b[0;32m--> 165\u001b[0m     run_results \u001b[38;5;241m=\u001b[39m \u001b[43mget_interpreter\u001b[49m\u001b[43m(\u001b[49m\u001b[43m)\u001b[49m\u001b[38;5;241;43m.\u001b[39;49m\u001b[43mrun\u001b[49m\u001b[43m(\u001b[49m\n\u001b[1;32m    166\u001b[0m \u001b[43m        \u001b[49m\u001b[43mentry_expr\u001b[49m\u001b[43m,\u001b[49m\u001b[43m \u001b[49m\u001b[43mon_save_events\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01mif\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43msave_events\u001b[49m\u001b[43m \u001b[49m\u001b[38;5;28;43;01melse\u001b[39;49;00m\u001b[43m \u001b[49m\u001b[43mprint_output\u001b[49m\n\u001b[1;32m    167\u001b[0m \u001b[43m    \u001b[49m\u001b[43m)\u001b[49m\n\u001b[1;32m    168\u001b[0m     results[\u001b[38;5;241m-\u001b[39m\u001b[38;5;241m1\u001b[39m][\u001b[38;5;124m\"\u001b[39m\u001b[38;5;124mresult\u001b[39m\u001b[38;5;124m\"\u001b[39m] \u001b[38;5;241m=\u001b[39m run_results\n\u001b[1;32m    169\u001b[0m     \u001b[38;5;28;01mif\u001b[39;00m on_result:\n",
            "\u001b[0;31mQSharpError\u001b[0m: Error: Qubit1 released while not in |0⟩ state\nCall stack:\n    at QIR.Runtime.__quantum__rt__qubit_release in core/qir.qs\n    at Bad in line_9\n\u001b[31mQsc.Eval.ReleasedQubitNotZero\u001b[0m\n\n  \u001b[31m×\u001b[0m runtime error\n\u001b[31m  ╰─▶ \u001b[0mQubit1 released while not in |0⟩ state\n   ╭─[\u001b[36;1;4mline_9\u001b[0m:7:1]\n \u001b[2m7\u001b[0m │         // Do something bad, sometimes\n \u001b[2m8\u001b[0m │         use q2 = Qubit();\n   · \u001b[35;1m        ────────┬────────\u001b[0m\n   ·                 \u001b[35;1m╰── \u001b[35;1mQubit1\u001b[0m\u001b[0m\n \u001b[2m9\u001b[0m │         X(q2);\n   ╰────\n\u001b[36m  help: \u001b[0mqubits should be returned to the |0⟩ state before being released to\n        satisfy the assumption that allocated qubits start in the |0⟩ state\n"
          ]
        }
      ],
      "source": [
        "qsharp.run(\"Bad()\", 10)\n"
      ]
    }
  ],
  "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.6"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
