{
  "cells": [
    {
      "cell_type": "markdown",
      "id": "0697d1c5",
      "metadata": {},
      "source": [
        "---\n",
        "title: Qiskit implementation\n",
        "description: Using Qiskit to implement ideas from the entanglement in action lesson.\n",
        "---\n",
        "\n",
        "{/* cspell:ignore ebit operatorname */}\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6ed84269",
      "metadata": {},
      "source": [
        "# Qiskit implementation\n",
        "\n",
        "In this lesson, we implement some of the ideas from the lesson on entanglement in action, using Qiskit.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "073958f0-2367-4dce-b747-7defd256380c",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "2.1.1\n"
          ]
        }
      ],
      "source": [
        "from qiskit import __version__\n",
        "\n",
        "print(__version__)"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "1a60f419",
      "metadata": {},
      "outputs": [],
      "source": [
        "from qiskit import QuantumCircuit, QuantumRegister, ClassicalRegister\n",
        "from qiskit_aer import AerSimulator\n",
        "from qiskit.visualization import plot_histogram, array_to_latex\n",
        "from qiskit.result import marginal_distribution\n",
        "from qiskit.circuit.library import UGate\n",
        "from math import pi\n",
        "import random"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "d823d15a",
      "metadata": {},
      "source": [
        "Here is a quantum circuit implementation of the teleportation protocol.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 3,
      "id": "3eb41206",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/3eb41206-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "qubit = QuantumRegister(1, \"Q\")\n",
        "ebit0 = QuantumRegister(1, \"A\")\n",
        "ebit1 = QuantumRegister(1, \"B\")\n",
        "a = ClassicalRegister(1, \"a\")\n",
        "b = ClassicalRegister(1, \"b\")\n",
        "\n",
        "protocol = QuantumCircuit(qubit, ebit0, ebit1, a, b)\n",
        "\n",
        "# Prepare ebit used for teleportation\n",
        "protocol.h(ebit0)\n",
        "protocol.cx(ebit0, ebit1)\n",
        "protocol.barrier()\n",
        "\n",
        "# Alice's operations\n",
        "protocol.cx(qubit, ebit0)\n",
        "protocol.h(qubit)\n",
        "protocol.barrier()\n",
        "\n",
        "# Alice measures and sends classical bits to Bob\n",
        "protocol.measure(ebit0, a)\n",
        "protocol.measure(qubit, b)\n",
        "protocol.barrier()\n",
        "\n",
        "# Bob uses the classical bits to conditionally apply gates\n",
        "with protocol.if_test((a, 1)):\n",
        "    protocol.x(ebit1)\n",
        "with protocol.if_test((b, 1)):\n",
        "    protocol.z(ebit1)\n",
        "\n",
        "display(protocol.draw(output=\"mpl\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "73ae61c5",
      "metadata": {},
      "source": [
        "The circuit makes use of a few features of Qiskit that we've not yet seen in previous lessons, including the `barrier` and `if_test` functions.\n",
        "The `barrier` function creates a visual separation making the circuit diagram more readable, and it also prevents Qiskit from performing various simplifications and optimizations across the barrier during compilation when circuits are run on real hardware.\n",
        "The `if_test` function applies an operation conditionally depending on a classical bit or register.\n",
        "\n",
        "The circuit first initializes $(\\mathsf{A},\\mathsf{B})$ to be in a $\\vert \\phi^+\\rangle$ state (which is not part of the protocol itself), followed by Alice's operations, then her measurements, and finally Bob's operations.\n",
        "To test that the protocol works correctly, we'll apply a randomly generated single-qubit gate to the initialized $\\vert 0\\rangle$ state of $\\mathsf{Q}$ to obtain a random quantum state vector to be teleported. By applying the inverse (as in, the conjugate transpose) of that gate to $\\mathsf{B}$ after the protocol is run, we can verify that the state was teleported by measuring to see that it has returned to the $\\vert 0\\rangle$ state.\n",
        "\n",
        "First we'll randomly choose a unitary qubit gate.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 4,
      "id": "f1446c8e-4fb5-416e-a74f-37fc186f7097",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/latex": [
              "$$\n",
              "\n",
              "\\begin{bmatrix}\n",
              "0.9897212158 & -0.0195080103 - 0.141673401 i  \\\\\n",
              " 0.0603319186 + 0.1296609988 i & -0.8319925233 + 0.5360378028 i  \\\\\n",
              " \\end{bmatrix}\n",
              "$$"
            ],
            "text/plain": [
              "<IPython.core.display.Latex object>"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "random_gate = UGate(\n",
        "    theta=random.random() * 2 * pi,\n",
        "    phi=random.random() * 2 * pi,\n",
        "    lam=random.random() * 2 * pi,\n",
        ")\n",
        "\n",
        "display(array_to_latex(random_gate.to_matrix()))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ec1b448d",
      "metadata": {},
      "source": [
        "Now we'll create a new testing circuit that first applies our random gate to $\\mathsf{Q},$ then runs the teleportation circuit, and finally applies the inverse of our random gate to the qubit $\\mathsf{B}$ and measures.\n",
        "The outcome should be $0$ with certainty.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 5,
      "id": "ce7568a0-23d2-41d2-aadc-ad898b3a7ebe",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/ce7568a0-23d2-41d2-aadc-ad898b3a7ebe-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Create a new circuit including the same bits and qubits used in the\n",
        "# teleportation protocol.\n",
        "\n",
        "test = QuantumCircuit(qubit, ebit0, ebit1, a, b)\n",
        "\n",
        "# Start with the randomly selected gate on Q\n",
        "\n",
        "test.append(random_gate, qubit)\n",
        "test.barrier()\n",
        "\n",
        "# Append the entire teleportation protocol from above.\n",
        "\n",
        "test = test.compose(protocol)\n",
        "test.barrier()\n",
        "\n",
        "# Finally, apply the inverse of the random unitary to B and measure.\n",
        "\n",
        "test.append(random_gate.inverse(), ebit1)\n",
        "result = ClassicalRegister(1, \"Result\")\n",
        "test.add_register(result)\n",
        "test.measure(ebit1, result)\n",
        "\n",
        "display(test.draw(output=\"mpl\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "13f847a6",
      "metadata": {},
      "source": [
        "Finally, let's run the Aer simulator on this circuit and plot a histogram of the outputs.\n",
        "We'll see the statistics for all three classical bits:\n",
        "the bottom/leftmost bit should always be $0,$ indicating that the qubit $\\mathsf{Q}$ was successfully teleported into $\\mathsf{B},$ while the other two bits should be roughly uniform.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 6,
      "id": "4db32a9d",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/4db32a9d-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "result = AerSimulator().run(test).result()\n",
        "statistics = result.get_counts()\n",
        "display(plot_histogram(statistics))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "29560bcd",
      "metadata": {},
      "source": [
        "We can also filter the statistics to focus solely on the test result qubit if we wish, like this:\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 7,
      "id": "b3e3be9a",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/b3e3be9a-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "filtered_statistics = marginal_distribution(statistics, [2])\n",
        "display(plot_histogram(filtered_statistics))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "32fded1e",
      "metadata": {},
      "source": [
        "## Superdense coding\n",
        "\n",
        "Superdense coding is a protocol that, in some sense, achieves a complementary aim to teleportation.\n",
        "Rather than allowing for the transmission of one qubit using two classical bits of communication (at the cost of one e-bit of entanglement), it allows for the transmission of two classical bits using one qubit of quantum communication (again, at the cost of one e-bit of entanglement).\n",
        "\n",
        "In greater detail, we have a sender (Alice) and a receiver (Bob) that share one e-bit of entanglement.\n",
        "According to the conventions in place for the lesson, this means that Alice holds a qubit $\\mathsf{A},$ Bob holds a qubit $\\mathsf{B},$ and together the pair $(\\mathsf{A},\\mathsf{B})$ is in the state $\\vert\\phi^+\\rangle.$\n",
        "Alice wishes to transmit two classical bits to Bob, which we'll denote by $c$ and $d,$ and she will accomplish this by sending him one qubit.\n",
        "\n",
        "It is reasonable to view this feat as being less interesting than the one that teleportation accomplishes.\n",
        "Sending qubits is likely to be so much more difficult than sending classical bits for the foreseeable future that trading one qubit of quantum communication for two bits of classical communication, at the cost of an e-bit no less, hardly seems worth it.\n",
        "However, this does not imply that superdense coding is not interesting, for it most certainly is.\n",
        "\n",
        "Fitting the theme of the lesson, one reason why superdense coding is interesting is that it demonstrates a concrete and (in the context of information theory) rather striking use of entanglement.\n",
        "A famous theorem in quantum information theory, known as *Holevo's theorem*, implies that without the use of a shared entangled state, it is impossible to communicate more than one bit of classical information by sending a single qubit.\n",
        "(Holevo's theorem is more general than this.\n",
        "Its precise statement is technical and requires explanation, but this is one consequence of it.)\n",
        "So, through superdense coding, shared entanglement effectively allows for the *doubling* of the classical information-carrying capacity of sending qubits.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "7abef6c9",
      "metadata": {},
      "source": [
        "### Protocol\n",
        "\n",
        "The following quantum circuit diagram describes the superdense coding protocol:\n",
        "\n",
        "![Superdense coding circuit](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/superdense-coding.avif)\n",
        "\n",
        "In words, here is what Alice does:\n",
        "\n",
        "1. If $d=1,$ Alice performs a $Z$ gate on her qubit $\\mathsf{A}$ (and if $d=0$ she does not).\n",
        "\n",
        "2. If $c=1,$ Alice performs an $X$ gate on her qubit $\\mathsf{A}$ (and if $c=0$ she does not).\n",
        "\n",
        "Alice then sends her qubit $\\mathsf{A}$ to Bob.\n",
        "\n",
        "What Bob does when he receives the qubit $\\mathsf{A}$ is to first perform a controlled-NOT gate, with $\\mathsf{A}$ being the control and $\\mathsf{B}$ being the target, and then he applies a Hadamard gate to $\\mathsf{A}.$\n",
        "He then measures $\\mathsf{B}$ to obtain $c$ and $\\mathsf{A}$ to obtain $d,$ with standard basis measurements in both cases.\n",
        "\n",
        "### Analysis\n",
        "\n",
        "The idea behind this protocol is simple:\n",
        "Alice effectively chooses which Bell state she would like to be sharing with Bob,\n",
        "she sends Bob her qubit, and Bob measures to determine which Bell state Alice chose.\n",
        "\n",
        "That is, they initially share $\\vert\\phi^+\\rangle,$ and depending upon the bits $c$ and $d,$ Alice either leaves this state alone or shifts it to one of the other Bell states by applying $\\mathbb{I},$ $X,$ $Z,$ or $XZ$ to her qubit\n",
        "$\\mathsf{A}.$\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "(\\mathbb{I} \\otimes \\mathbb{I}) \\vert \\phi^+ \\rangle & = \\vert \\phi^+\\rangle \\\\\n",
        "(\\mathbb{I} \\otimes Z) \\vert \\phi^+ \\rangle & = \\vert \\phi^-\\rangle \\\\\n",
        "(\\mathbb{I} \\otimes X) \\vert \\phi^+ \\rangle & = \\vert \\psi^+\\rangle \\\\\n",
        "(\\mathbb{I} \\otimes XZ) \\vert \\phi^+ \\rangle & = \\vert \\psi^-\\rangle\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "Bob's actions have the following effects on the four Bell states:\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "\\vert \\phi^+\\rangle & \\mapsto \\vert 00\\rangle\\\\\n",
        "\\vert \\phi^-\\rangle & \\mapsto \\vert 01\\rangle\\\\\n",
        "\\vert \\psi^+\\rangle & \\mapsto \\vert 10\\rangle\\\\\n",
        "\\vert \\psi^-\\rangle & \\mapsto -\\vert 11\\rangle\\\\\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "This can be checked directly, by computing the results of Bob's operations on these states one at a time.\n",
        "\n",
        "So, when Bob performs his measurements, he is able to determine which Bell state Alice chose.\n",
        "To verify that the protocol works correctly is a matter of checking each case:\n",
        "\n",
        "* If $cd = 00,$ then the state of $(\\mathsf{B},\\mathsf{A})$ when Bob receives $\\mathsf{A}$ is $\\vert \\phi^+\\rangle.$ He transforms this state into $\\vert 00\\rangle$ and obtains $cd = 00.$\n",
        "\n",
        "* If $cd = 01,$ then the state of $(\\mathsf{B},\\mathsf{A})$ when Bob receives $\\mathsf{A}$ is $\\vert \\phi^-\\rangle.$ He transforms this state into $\\vert 01\\rangle$ and obtains $cd = 01.$\n",
        "\n",
        "* If $cd = 10,$ then the state of $(\\mathsf{B},\\mathsf{A})$ when Bob receives $\\mathsf{A}$ is $\\vert \\psi^+\\rangle.$ He transforms this state into $\\vert 10\\rangle$ and obtains $cd = 10.$\n",
        "\n",
        "* If $cd = 11,$ then the state of $(\\mathsf{B},\\mathsf{A})$ when Bob receives $\\mathsf{A}$ is $\\vert \\psi^-\\rangle.$ He transforms this state into $-\\vert 11\\rangle$ and obtains $cd = 11.$ (The negative-one phase factor has no effect here.)\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0f10b8e4",
      "metadata": {},
      "source": [
        "### Superdense coding implementation\n",
        "\n",
        "Here is a simple implementation of superdense coding where we specify the circuit itself depending on the bits to be transmitted. First we'll choose two bits to be transmitted. (Later we'll choose them randomly, but for now we'll just make an arbitrary choice.)\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 8,
      "id": "a4bdda80",
      "metadata": {},
      "outputs": [],
      "source": [
        "c = \"1\"\n",
        "d = \"0\""
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0b6b0573",
      "metadata": {},
      "source": [
        "Now we'll build the circuit accordingly. Here we'll allow Qiskit to use the default names for the qubits: $\\mathsf{q}_0$ for the top qubit and $\\mathsf{q}_1$ for the bottom one.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 9,
      "id": "05ae9b94",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/05ae9b94-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "protocol = QuantumCircuit(2)\n",
        "\n",
        "# Prepare ebit used for superdense coding\n",
        "protocol.h(0)\n",
        "protocol.cx(0, 1)\n",
        "protocol.barrier()\n",
        "\n",
        "# Alice's operations\n",
        "if d == \"1\":\n",
        "    protocol.z(0)\n",
        "if c == \"1\":\n",
        "    protocol.x(0)\n",
        "protocol.barrier()\n",
        "\n",
        "# Bob's actions\n",
        "protocol.cx(0, 1)\n",
        "protocol.h(0)\n",
        "protocol.measure_all()\n",
        "\n",
        "display(protocol.draw(output=\"mpl\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8d3e094f",
      "metadata": {},
      "source": [
        "Not much is new here, except the `measure_all` function, which measures all of the qubits and puts the results into a single classical register (and therefore having two bits in this case).\n",
        "\n",
        "Running the Aer simulator produces the expected output.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 10,
      "id": "6309a901-c3da-4b7d-b762-c6a7b542457b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Measured 10 with frequency 1024\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/6309a901-c3da-4b7d-b762-c6a7b542457b-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "result = AerSimulator().run(protocol).result()\n",
        "statistics = result.get_counts()\n",
        "\n",
        "for outcome, frequency in statistics.items():\n",
        "    print(f\"Measured {outcome} with frequency {frequency}\")\n",
        "\n",
        "display(plot_histogram(statistics))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a6e90734",
      "metadata": {},
      "source": [
        "Now let's use an additional qubit as a random bit generator — essentially to flip fair coins. We'll use it to randomly choose $c$ and $d,$ and then run the superdense coding protocol.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "06e461e9",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/06e461e9-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "rbg = QuantumRegister(1, \"coin\")\n",
        "ebit0 = QuantumRegister(1, \"A\")\n",
        "ebit1 = QuantumRegister(1, \"B\")\n",
        "\n",
        "Alice_c = ClassicalRegister(1, \"Alice c\")\n",
        "Alice_d = ClassicalRegister(1, \"Alice d\")\n",
        "\n",
        "test = QuantumCircuit(rbg, ebit0, ebit1, Alice_d, Alice_c)\n",
        "\n",
        "# Initialize the ebit\n",
        "test.h(ebit0)\n",
        "test.cx(ebit0, ebit1)\n",
        "test.barrier()\n",
        "\n",
        "# Use the 'coin' qubit twice to generate Alice's bits c and d.\n",
        "test.h(rbg)\n",
        "test.measure(rbg, Alice_c)\n",
        "test.h(rbg)\n",
        "test.measure(rbg, Alice_d)\n",
        "test.barrier()\n",
        "\n",
        "# Now the protocol runs, starting with Alice's actions, which depend\n",
        "# on her bits.\n",
        "with test.if_test((Alice_d, 1), label=\"Z\"):\n",
        "    test.z(ebit0)\n",
        "with test.if_test((Alice_c, 1), label=\"X\"):\n",
        "    test.x(ebit0)\n",
        "test.barrier()\n",
        "\n",
        "# Bob's actions\n",
        "test.cx(ebit0, ebit1)\n",
        "test.h(ebit0)\n",
        "test.barrier()\n",
        "\n",
        "Bob_c = ClassicalRegister(1, \"Bob c\")\n",
        "Bob_d = ClassicalRegister(1, \"Bob d\")\n",
        "test.add_register(Bob_d)\n",
        "test.add_register(Bob_c)\n",
        "test.measure(ebit0, Bob_d)\n",
        "test.measure(ebit1, Bob_c)\n",
        "\n",
        "display(test.draw(output=\"mpl\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "0dcfb5e3",
      "metadata": {},
      "source": [
        "Running the Aer simulator shows the results: Alice and Bob's classical bits always agree.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 12,
      "id": "77fd1434",
      "metadata": {},
      "outputs": [
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/77fd1434-0.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "result = AerSimulator().run(test).result()\n",
        "statistics = result.get_counts()\n",
        "display(plot_histogram(statistics))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "335949b7",
      "metadata": {},
      "source": [
        "## The CHSH game\n",
        "\n",
        "The last example to be discussed in this lesson is not a protocol, but a *game* known as the\n",
        "*CHSH game*.\n",
        "\n",
        "When we speak of a game in this context, we're not talking about something that's meant to be played for fun or sport, but rather a mathematical abstraction in the sense of *game theory*.\n",
        "Mathematical abstractions of games are studied in economics and computer science, for instance, and they are both fascinating and useful.\n",
        "\n",
        "The letters CHSH refer to the authors — John Clauser, Michael Horne, Abner Shimony, and Richard Holt — of a 1969 paper where the example was first described.\n",
        "They did not describe the example as a game, but rather as an experiment.\n",
        "Its description as a game, however, is both natural and intuitive.\n",
        "\n",
        "The CHSH game falls within a class of games known as *nonlocal games*.\n",
        "Nonlocal games are incredibly interesting and have deep connections to physics, computer science, and mathematics — holding mysteries that still remain unsolved.\n",
        "We'll begin the section by explaining what nonlocal games are, and then we'll focus in on the CHSH game and what makes it interesting.\n",
        "\n",
        "### Nonlocal games\n",
        "\n",
        "A nonlocal game is a *cooperative game* where two players, Alice and Bob, work together to achieve a particular outcome.\n",
        "The game is run by a *referee*, who behaves according to strict guidelines that are known to Alice and Bob.\n",
        "\n",
        "Alice and Bob can prepare for the game however they choose, but once the game starts they are *forbidden from communicating*.\n",
        "We might imagine the game taking place in a secure facility of some sort — as if the referee is playing the role of a detective and Alice and Bob are suspects being interrogated in different rooms.\n",
        "But another way to think about the set-up is that Alice and Bob are separated by a vast distance, and communication is prohibited because the speed of light doesn't allow for it within the running time of the game.\n",
        "That is to say, if Alice tries to send a message to Bob, the game will be over by the time he receives it, and vice versa.\n",
        "\n",
        "The way a nonlocal game works is that the referee first asks Alice and Bob one question each.\n",
        "We'll use the letter $x$ to refer to Alice's question and $y$ to refer to Bob's question.\n",
        "Here we're thinking of $x$ and $y$ as being classical states, and in the CHSH game $x$ and $y$ are bits.\n",
        "\n",
        "The referee uses *randomness* to select these questions.\n",
        "To be precise, there is some probability $p(x,y)$ associated with each possible pair $(x,y)$ of questions, and the referee has vowed to choose the questions randomly, at the time of the game, in this way.\n",
        "Everyone, including Alice and Bob, knows these probabilities — but nobody knows specifically which pair $(x,y)$ will be chosen until the game begins.\n",
        "\n",
        "After Alice and Bob receive their questions, they must then provide answers: Alice's answer is $a$ and Bob's answer is $b.$\n",
        "Again, these are classical states in general, and bits in the CHSH game.\n",
        "\n",
        "At this point the referee makes a decision: Alice and Bob either *win* or *lose* depending on whether or not the pair of answers $(a,b)$ is deemed correct for the pair of questions $(x,y)$ according to some fixed set of rules.\n",
        "Different rules mean different games, and the rules for the CHSH game specifically are described in the section following this one.\n",
        "As was already suggested, the rules are known to everyone.\n",
        "\n",
        "The following diagram provides a graphic representation of the interactions.\n",
        "\n",
        "![Nonlocal game](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/nonlocal-game.avif)\n",
        "\n",
        "It is the uncertainty about which questions will be asked, and specifically the fact that each player doesn't know the other player's question, that makes nonlocal games challenging for Alice and Bob — just like colluding suspects in different rooms trying to keep their story straight.\n",
        "\n",
        "A precise description of the referee defines an instance of a nonlocal game.\n",
        "This includes a specification of the probabilities $p(x,y)$ for each question pair along with the rules\n",
        "that determine whether each pair of answers $(a,b)$ wins or loses for each possible question pair $(x,y).$\n",
        "\n",
        "We'll take a look at the CHSH game momentarily, but before that let us briefly acknowledge that it's also interesting to consider other nonlocal games.\n",
        "In fact, it's extremely interesting; there are some pretty simple nonlocal games for which it's currently not known how well Alice and Bob can play using entanglement.\n",
        "The set-up is simple, but there's complexity at work — and for some games it can be impossibly difficult to compute best or near-best strategies for Alice and Bob.\n",
        "This is the surprisingly unintuitive nature of the nonlocal games model.\n",
        "\n",
        "### CHSH game description\n",
        "\n",
        "Here is the precise description of the CHSH game, where (as above) $x$ is Alice's question, $y$ is Bob's question, $a$ is Alice's answer, and $b$ is Bob's answer:\n",
        "\n",
        "* The questions and answers are all bits: $x,y,a,b\\in\\{0,1\\}.$\n",
        "\n",
        "* The referee chooses the questions $(x,y)$ *uniformly at random*. That is, each of the four possibilities, $(0,0),$ $(0,1),$ $(1,0),$ and $(1,1),$ is selected with probability $1/4.$\n",
        "\n",
        "* The answers $(a,b)$ *win* for the questions $(x,y)$ if $a\\oplus b = x\\wedge y$ and *lose* otherwise. The following table expresses this rule by listing the winning and losing conditions on the answers $(a,b)$ for each pair of questions $(x,y).$\n",
        "\n",
        "$$\n",
        "\\begin{array}{ccc}\n",
        "(x,y) & \\text{win} & \\text{lose} \\\\[1mm]\\hline\n",
        "\\rule{0mm}{4mm}(0,0) & a = b & a \\neq b \\\\[1mm]\n",
        "(0,1) & a = b & a \\neq b \\\\[1mm]\n",
        "(1,0) & a = b & a \\neq b \\\\[1mm]\n",
        "(1,1) & a \\neq b & a = b\n",
        "\\end{array}\n",
        "$$\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "5c7b49a1",
      "metadata": {},
      "source": [
        "### Limitation of classical strategies\n",
        "\n",
        "Now let's consider strategies for Alice and Bob in the CHSH game, beginning with *classical* strategies.\n",
        "\n",
        "#### Deterministic strategies\n",
        "\n",
        "We'll start with *deterministic* strategies, where Alice's answer $a$ is a function of the question $x$ that she receives, and likewise Bob's answer $b$ is a function of the question $y$ he receives.\n",
        "So, for instance, we may write $a(0)$ to represent Alice's answer when her question is $0,$ and $a(1)$ to represent Alice's answer when her question is $1.$\n",
        "\n",
        "No deterministic strategy can possibly win the CHSH game every time.\n",
        "One way to understand this is simply to go one-by-one through all of the possible deterministic strategies and check that every one of them loses for at least one of the four possible question pairs.\n",
        "Alice and Bob can each choose from four possible functions from one bit to one bit — which we encountered in the lesson on [Single systems](/learning/courses/basics-of-quantum-information/single-systems/introduction) — and so there are $16$ different deterministic strategies in total to check.\n",
        "\n",
        "We can also reason this analytically.\n",
        "If Alice and Bob's strategy wins when $(x,y) = (0,0),$ then it must be that $a(0) = b(0);$\n",
        "if their strategy wins when $(x,y) = (0,1),$ then $a(0) = b(1);$ and similarly,\n",
        "if the strategy wins for $(x,y)=(1,0)$ then $a(1) = b(0).$\n",
        "So, if their strategy wins for all three possibilities, then\n",
        "\n",
        "$$\n",
        "b(1) = a(0) = b(0) = a(1).\n",
        "$$\n",
        "\n",
        "This implies that the strategy loses in the final case $(x,y) = (1,1),$ and for here winning requires that\n",
        "$a(1) \\neq b(1).$\n",
        "Thus, there can be no deterministic strategy that wins every time.\n",
        "\n",
        "On the other hand, it is easy to find deterministic strategies that win in three of the four cases, such as $a(0)=a(1)=b(0)=b(1)=0.$\n",
        "From this we conclude that the maximum probability for Alice and Bob to win using a deterministic strategy is $3/4.$\n",
        "\n",
        "#### Probabilistic strategies\n",
        "\n",
        "As we just concluded, Alice and Bob cannot do better than winning the CHSH game 75% of the time using a deterministic strategy.\n",
        "But what about a probabilistic strategy?\n",
        "Could it help Alice and Bob to use randomness — including the possibility of *shared randomness*, where their random choices are correlated?\n",
        "\n",
        "It turns out that probabilistic strategies don't help at all to increase the probability that Alice and Bob win.\n",
        "This is because every probabilistic strategy can alternatively be viewed as a random selection of a deterministic strategy, just like (as was mentioned in the [Single systems](/learning/courses/basics-of-quantum-information/single-systems/introduction) lesson) probabilistic operations can be viewed as random selections of deterministic operations.\n",
        "The average is never larger than the maximum, and so it follows that probabilistic strategies don't offer any advantage in terms of their overall winning probability.\n",
        "\n",
        "Thus, winning with probability $3/4$ is the best that Alice and Bob can do using any classical strategy, whether deterministic or probabilistic.\n",
        "\n",
        "### CHSH game strategy\n",
        "\n",
        "A natural question to ask at this point is whether Alice and Bob can do any better using a *quantum* strategy.\n",
        "In particular, if they share an entangled quantum state as the following figure suggests, which they could have prepared prior to playing the game, can they increase their winning probability?\n",
        "\n",
        "![Nonlocal game with entanglement](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/nonlocal-game-entanglement.avif)\n",
        "\n",
        "The answer is yes, and this is the main point of the example and why it's so interesting.\n",
        "So let's see exactly how Alice and Bob can do better in this game using entanglement.\n",
        "\n",
        "#### Required vectors and matrices\n",
        "\n",
        "The first thing we need to do is to define a qubit state vector $\\vert \\psi_{\\theta}\\rangle,$ for each real number\n",
        "$\\theta$ (which we'll think of as an angle measured in radians) as follows.\n",
        "\n",
        "$$\n",
        "\\vert\\psi_{\\theta}\\rangle = \\cos(\\theta)\\vert 0\\rangle + \\sin(\\theta) \\vert 1\\rangle\n",
        "$$\n",
        "\n",
        "Here are some simple examples:\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "  \\vert\\psi_{0}\\rangle & = \\vert 0\\rangle \\\\\n",
        "  \\vert\\psi_{\\pi/2}\\rangle & = \\vert 1\\rangle \\\\\n",
        "  \\vert\\psi_{\\pi/4}\\rangle & = \\vert + \\rangle \\\\\n",
        "  \\vert\\psi_{-\\pi/4}\\rangle & = \\vert - \\rangle\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "We also have the following examples, which arise in the analysis below:\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "  \\vert\\psi_{-\\pi/8}\\rangle & = \\frac{\\sqrt{2 + \\sqrt{2}}}{2}\\vert 0\\rangle -\\frac{\\sqrt{2 - \\sqrt{2}}}{2}\\vert 1\\rangle \\\\[1mm]\n",
        "  \\vert\\psi_{\\pi/8}\\rangle & = \\frac{\\sqrt{2 + \\sqrt{2}}}{2}\\vert 0\\rangle + \\frac{\\sqrt{2 - \\sqrt{2}}}{2}\\vert 1\\rangle \\\\[1mm]\n",
        "  \\vert\\psi_{3\\pi/8}\\rangle & = \\frac{\\sqrt{2 - \\sqrt{2}}}{2}\\vert 0\\rangle + \\frac{\\sqrt{2 + \\sqrt{2}}}{2}\\vert 1\\rangle \\\\[1mm]\n",
        "  \\vert\\psi_{5\\pi/8}\\rangle & = -\\frac{\\sqrt{2 - \\sqrt{2}}}{2}\\vert 0\\rangle + \\frac{\\sqrt{2 + \\sqrt{2}}}{2}\\vert 1\\rangle\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "Looking at the general form, we see that the inner product between any two of these vectors has this formula:\n",
        "\n",
        "$$\n",
        "\\langle \\psi_{\\alpha} \\vert \\psi_{\\beta} \\rangle\n",
        "= \\cos(\\alpha)\\cos(\\beta) + \\sin(\\alpha)\\sin(\\beta)\n",
        "= \\cos(\\alpha-\\beta).\n",
        "\\tag{3}\n",
        "$$\n",
        "\n",
        "In detail, there are only real number entries in these vectors, so there are no complex conjugates to worry about:\n",
        "the inner product is the product of the cosines plus the product of the sines.\n",
        "Using one of the *angle addition formulas* from trigonometry leads to the simplification above.\n",
        "This formula reveals the geometric interpretation of the inner product between real unit vectors as the cosine of the angle between them.\n",
        "\n",
        "If we compute the inner product of the *tensor product* of any two of these vectors with the $\\vert \\phi^+\\rangle$ state, we obtain a similar expression, except that it has a $\\sqrt{2}$ in the denominator:\n",
        "\n",
        "$$\n",
        "\\langle \\psi_{\\alpha} \\otimes \\psi_{\\beta} \\vert \\phi^+ \\rangle\n",
        "= \\frac{\\cos(\\alpha)\\cos(\\beta) + \\sin(\\alpha)\\sin(\\beta)}{\\sqrt{2}}\n",
        "= \\frac{\\cos(\\alpha-\\beta)}{\\sqrt{2}}.\n",
        "\\tag{4}\n",
        "$$\n",
        "\n",
        "Our interest in this particular inner product will become clear shortly, but for now we're simply observing this as a formula.\n",
        "\n",
        "Next, define a unitary matrix $U_{\\theta}$ for each angle $\\theta$ as follows.\n",
        "\n",
        "$$\n",
        "U_{\\theta} = \\vert 0 \\rangle \\langle \\psi_{\\theta} \\vert + \\vert 1\\rangle\\langle \\psi_{\\theta+\\pi/2} \\vert\n",
        "$$\n",
        "\n",
        "Intuitively speaking, this matrix transforms $\\vert\\psi_{\\theta}\\rangle$ into $\\vert 0\\rangle$ and $\\vert \\psi_{\\theta + \\pi/2}\\rangle$ into $\\vert 1\\rangle.$\n",
        "To check that this is a unitary matrix, a key observation is that the vectors $\\vert\\psi_{\\theta}\\rangle$ and $\\vert\\psi_{\\theta + \\pi/2}\\rangle$ are orthogonal for every angle $\\theta$:\n",
        "\n",
        "$$\n",
        "\\langle \\psi_{\\theta} \\vert \\psi_{\\theta + \\pi/2} \\rangle = \\cos(\\pi/2) = 0.\n",
        "$$\n",
        "\n",
        "Thus, we find that\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "U_{\\theta} U_{\\theta}^{\\dagger}\n",
        "& = \\bigl(\\vert 0 \\rangle \\langle \\psi_{\\theta} \\vert + \\vert 1\\rangle\\langle \\psi_{\\theta+\\pi/2} \\vert\\bigr)\n",
        "\\bigl(\\vert \\psi_{\\theta} \\rangle \\langle 0 \\vert + \\vert \\psi_{\\theta+\\pi/2}\\rangle\\langle 1 \\vert\\bigr) \\\\[1mm]\n",
        "& =\n",
        "\\vert 0 \\rangle \\langle \\psi_{\\theta} \\vert \\psi_{\\theta} \\rangle \\langle 0 \\vert\n",
        "+ \\vert 0 \\rangle \\langle \\psi_{\\theta} \\vert \\psi_{\\theta+\\pi/2} \\rangle \\langle 1 \\vert\n",
        "+ \\vert 1 \\rangle \\langle \\psi_{\\theta+\\pi/2} \\vert \\psi_{\\theta} \\rangle \\langle 0 \\vert\n",
        "+ \\vert 1 \\rangle \\langle \\psi_{\\theta+\\pi/2} \\vert \\psi_{\\theta+\\pi/2} \\rangle \\langle 1 \\vert \\\\[1mm]\n",
        "& =\n",
        "\\vert 0 \\rangle \\langle 0 \\vert + \\vert 1 \\rangle \\langle 1 \\vert\\\\[1mm]\n",
        "& = \\mathbb{I}.\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "We may alternatively write this matrix explicitly as\n",
        "\n",
        "$$\n",
        "U_{\\theta}\n",
        "= \\begin{pmatrix}\n",
        "\\cos(\\theta) & \\sin(\\theta)\\\\[1mm]\n",
        "\\cos(\\theta+ \\pi/2) & \\sin(\\theta + \\pi/2)\n",
        "\\end{pmatrix}\n",
        "= \\begin{pmatrix}\n",
        "\\cos(\\theta) & \\sin(\\theta)\\\\[1mm]\n",
        "-\\sin(\\theta) & \\cos(\\theta)\n",
        "\\end{pmatrix}.\n",
        "$$\n",
        "\n",
        "This is an example of a *rotation matrix*, and specifically it rotates two-dimensional vectors with real number entries by an angle of $-\\theta$ about the origin.\n",
        "If we follow a standard convention for naming and parameterizing rotations of various forms, we have\n",
        "$U_{\\theta} = R_y(-2\\theta)$ where\n",
        "\n",
        "$$\n",
        "R_y(\\theta) = \\begin{pmatrix}\n",
        "\\cos(\\theta/2) & -\\sin(\\theta/2)\\\\[1mm]\n",
        "\\sin(\\theta/2) & \\cos(\\theta/2)\n",
        "\\end{pmatrix}.\n",
        "$$\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "f85a94d1",
      "metadata": {},
      "source": [
        "#### Strategy description\n",
        "\n",
        "Now we can describe the quantum strategy.\n",
        "\n",
        "* **Set-up:** Alice and Bob start the game sharing an e-bit: Alice holds a qubit $\\mathsf{A},$ Bob holds a qubit $\\mathsf{B},$ and together the two qubits $(\\mathsf{X},\\mathsf{Y})$ are in the $\\vert\\phi^+\\rangle$ state.\n",
        "\n",
        "* **Alice's actions:**\n",
        "\n",
        "  * If Alice receives the question $x=0,$ she applies $U_{0}$ to her qubit $\\mathsf{A}.$\n",
        "  * If Alice receives the question  $x=1,$ she applies $U_{\\pi/4}$ to her qubit $\\mathsf{A}.$\n",
        "\n",
        "  The operation Alice performs on $\\mathsf{A}$ may alternatively be described like this:\n",
        "\n",
        "  $$\n",
        "  \\begin{cases}\n",
        "  U_0 & \\text{if $x = 0$}\\\\\n",
        "  U_{\\pi/4} & \\text{if $x = 1$}\n",
        "  \\end{cases}\n",
        "  $$\n",
        "\n",
        "  After Alice applies this operation, she measures $\\mathsf{A}$ with a standard basis measurement and sets her answer $a$ to be the measurement outcome.\n",
        "\n",
        "* **Bob's actions:**\n",
        "\n",
        "  * If Bob receives the question $y=0,$ he applies $U_{\\pi/8}$ to his qubit $\\mathsf{B}.$\n",
        "  * If Bob receives the question $y=1,$ he applies $U_{-\\pi/8}$ to his qubit $\\mathsf{B}.$\n",
        "\n",
        "  Like we did for Alice, we can express Bob's operation on $\\mathsf{B}$ like this:\n",
        "\n",
        "  $$\n",
        "  \\begin{cases}\n",
        "  U_{\\pi/8} & \\text{if $y = 0$}\\\\\n",
        "  U_{-\\pi/8} & \\text{if $y = 1$}\n",
        "  \\end{cases}\n",
        "  $$\n",
        "\n",
        "  After Bob applies this operation, he measures $\\mathsf{B}$ with a standard basis measurement and sets his answer $b$ to be the measurement outcome.\n",
        "\n",
        "Here is a quantum circuit diagram that describes this strategy:\n",
        "\n",
        "![CHSH game circuit](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/CHSH.avif)\n",
        "\n",
        "In this diagram we see two ordinary controlled gates, one for $U_{-\\pi/8}$ on the top and one for $U_{\\pi/4}$ on the bottom.\n",
        "We also have two gates that look like controlled gates, one for $U_{\\pi/8}$ on the top and one for $U_{0}$ on the bottom, except that the circle representing the control is not filled in.\n",
        "This denotes a different type of controlled gate where the gate is performed if the control is set to $0$ (rather than $1$ like an ordinary controlled gate).\n",
        "So, effectively, Bob performs $U_{\\pi/8}$ on his qubit if $y=0$ and $U_{-\\pi/8}$ if $y=1;$\n",
        "and Alice performs $U_0$ on her qubit if $x=0$ and $U_{\\pi/4}$ if $x=1,$ which is consistent with the description of the protocol in words above.\n",
        "\n",
        "It remains to figure out how well this strategy for Alice and Bob works.\n",
        "We'll do this by going through the four possible question pairs individually.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "eafe1025",
      "metadata": {},
      "source": [
        "#### Case-by-case analysis\n",
        "\n",
        "* Case 1:  $(x,y) = (0,0).$\n",
        "\n",
        "  In this case Alice performs $U_{0}$ on her qubit and Bob performs $U_{\\pi/8}$ on his, so the state of the two qubits $(\\mathsf{A},\\mathsf{B})$ after they perform their operations is\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\bigl(U_0 \\otimes U_{\\pi/8}\\bigr) \\vert \\phi^+\\rangle\n",
        "  & =\n",
        "  \\vert 00 \\rangle \\langle \\psi_0 \\otimes \\psi_{\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 01 \\rangle \\langle \\psi_0 \\otimes\\psi_{5\\pi/8}\\vert \\phi^+\\rangle \\\\\n",
        "  & \\qquad + \\vert 10 \\rangle \\langle \\psi_{\\pi/2} \\otimes \\psi_{\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 11 \\rangle \\langle \\psi_{\\pi/2} \\otimes \\psi_{5\\pi/8}\\vert \\phi^+\\rangle\\\\[2mm]\n",
        "  & = \\frac{\n",
        "      \\cos\\bigl(-\\frac{\\pi}{8}\\bigr) \\vert 00\\rangle\n",
        "    + \\cos\\bigl(-\\frac{5\\pi}{8}\\bigr) \\vert 01\\rangle\n",
        "    + \\cos\\bigl(\\frac{3\\pi}{8}\\bigr) \\vert 10\\rangle\n",
        "    + \\cos\\bigl(-\\frac{\\pi}{8}\\bigr) \\vert 11\\rangle}{\\sqrt{2}}.\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  The probabilities for the four possible answer pairs $(a,b)$ are therefore as follows.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8} \\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{5\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{3\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  We can then obtain the probabilities that $a=b$ and $a\\neq b$ by summing.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}(a = b) & = \\frac{2 + \\sqrt{2}}{4}\\\\[2mm]\n",
        "  \\operatorname{Pr}(a \\neq b) & = \\frac{2 - \\sqrt{2}}{4}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  For the question pair $(0,0),$ Alice and Bob win if $a=b,$ and therefore they win in this case with probability\n",
        "\n",
        "  $$\n",
        "  \\frac{2 + \\sqrt{2}}{4}.\n",
        "  $$\n",
        "\n",
        "* Case 2:  $(x,y) = (0,1).$\n",
        "\n",
        "  In this case Alice performs $U_{0}$ on her qubit and Bob performs $U_{-\\pi/8}$ on his, so the state of the two qubits $(\\mathsf{A},\\mathsf{B})$ after they perform their operations is\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\bigl(U_0 \\otimes U_{-\\pi/8}\\bigr) \\vert \\phi^+\\rangle\n",
        "  & =\n",
        "  \\vert 00 \\rangle \\langle \\psi_0 \\otimes \\psi_{-\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 01 \\rangle \\langle \\psi_0 \\otimes\\psi_{3\\pi/8}\\vert \\phi^+\\rangle \\\\\n",
        "  & \\qquad + \\vert 10 \\rangle \\langle \\psi_{\\pi/2} \\otimes \\psi_{-\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 11 \\rangle \\langle \\psi_{\\pi/2} \\otimes \\psi_{3\\pi/8}\\vert \\phi^+\\rangle\\\\[2mm]\n",
        "  & = \\frac{\n",
        "      \\cos\\bigl(\\frac{\\pi}{8}\\bigr) \\vert 00\\rangle\n",
        "    + \\cos\\bigl(-\\frac{3\\pi}{8}\\bigr) \\vert 01\\rangle\n",
        "    + \\cos\\bigl(\\frac{5\\pi}{8}\\bigr) \\vert 10\\rangle\n",
        "    + \\cos\\bigl(\\frac{\\pi}{8}\\bigr) \\vert 11\\rangle}{\\sqrt{2}}.\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  The probabilities for the four possible answer pairs $(a,b)$ are therefore as follows.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8} \\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{3\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{5\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  Again, we can obtain the probabilities that $a=b$ and $a\\neq b$ by summing.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}(a = b) & = \\frac{2 + \\sqrt{2}}{4}\\\\[2mm]\n",
        "  \\operatorname{Pr}(a \\neq b) & = \\frac{2 - \\sqrt{2}}{4}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  For the question pair $(0,1),$ Alice and Bob win if $a=b,$ and therefore they win in this case with probability\n",
        "\n",
        "  $$\n",
        "  \\frac{2 + \\sqrt{2}}{4}.\n",
        "  $$\n",
        "\n",
        "* Case 3:  $(x,y) = (1,0).$\n",
        "\n",
        "  In this case Alice performs $U_{\\pi/4}$ on her qubit and Bob performs $U_{\\pi/8}$ on his, so the state of the two qubits $(\\mathsf{A},\\mathsf{B})$ after they perform their operations is\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\bigl(U_{\\pi/4} \\otimes U_{\\pi/8}\\bigr) \\vert \\phi^+\\rangle\n",
        "  & =\n",
        "  \\vert 00 \\rangle \\langle \\psi_{\\pi/4} \\otimes \\psi_{\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 01 \\rangle \\langle \\psi_{\\pi/4} \\otimes\\psi_{5\\pi/8}\\vert \\phi^+\\rangle \\\\\n",
        "  & \\qquad + \\vert 10 \\rangle \\langle \\psi_{3\\pi/4} \\otimes \\psi_{\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 11 \\rangle \\langle \\psi_{3\\pi/4} \\otimes \\psi_{5\\pi/8}\\vert \\phi^+\\rangle\\\\[2mm]\n",
        "  & = \\frac{\n",
        "      \\cos\\bigl(\\frac{\\pi}{8}\\bigr) \\vert 00\\rangle\n",
        "    + \\cos\\bigl(-\\frac{3\\pi}{8}\\bigr) \\vert 01\\rangle\n",
        "    + \\cos\\bigl(\\frac{5\\pi}{8}\\bigr) \\vert 10\\rangle\n",
        "    + \\cos\\bigl(\\frac{\\pi}{8}\\bigr) \\vert 11\\rangle}{\\sqrt{2}}.\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  The probabilities for the four possible answer pairs $(a,b)$ are therefore as follows.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8} \\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{3\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{5\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  We find, once again, that probabilities that $a=b$ and $a\\neq b$ are as follows.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}(a = b) & = \\frac{2 + \\sqrt{2}}{4}\\\\[2mm]\n",
        "  \\operatorname{Pr}(a \\neq b) & = \\frac{2 - \\sqrt{2}}{4}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  For the question pair $(1,0),$ Alice and Bob win if $a=b,$ so they win in this case with probability\n",
        "\n",
        "  $$\n",
        "  \\frac{2 + \\sqrt{2}}{4}.\n",
        "  $$\n",
        "\n",
        "* Case 4:  $(x,y) = (1,1).$\n",
        "\n",
        "  The last case is a little bit different, as we might expect because the winning condition is different in this case. When $x$ and $y$ are both $1,$ Alice and Bob win when $a$ and $b$ are *different*. In this case Alice performs $U_{\\pi/4}$ on her qubit and Bob performs $U_{-\\pi/8}$ on his, so the state of the two qubits $(\\mathsf{A},\\mathsf{B})$ after they perform their operations is\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\bigl(U_{\\pi/4} \\otimes U_{-\\pi/8}\\bigr) \\vert \\phi^+\\rangle\n",
        "  & =\n",
        "  \\vert 00 \\rangle \\langle \\psi_{\\pi/4} \\otimes \\psi_{-\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 01 \\rangle \\langle \\psi_{\\pi/4} \\otimes\\psi_{3\\pi/8}\\vert \\phi^+\\rangle \\\\\n",
        "  & \\qquad + \\vert 10 \\rangle \\langle \\psi_{3\\pi/4} \\otimes \\psi_{-\\pi/8}\\vert \\phi^+\\rangle\n",
        "  + \\vert 11 \\rangle \\langle \\psi_{3\\pi/4} \\otimes \\psi_{3\\pi/8}\\vert \\phi^+\\rangle\\\\[2mm]\n",
        "  & = \\frac{\n",
        "      \\cos\\bigl(\\frac{3\\pi}{8}\\bigr) \\vert 00\\rangle\n",
        "    + \\cos\\bigl(-\\frac{\\pi}{8}\\bigr) \\vert 01\\rangle\n",
        "    + \\cos\\bigl(\\frac{7\\pi}{8}\\bigr) \\vert 10\\rangle\n",
        "    + \\cos\\bigl(\\frac{3\\pi}{8}\\bigr) \\vert 11\\rangle}{\\sqrt{2}}.\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  The probabilities for the four possible answer pairs $(a,b)$ are therefore as follows.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{3\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8} \\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(0,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(-\\frac{\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,0)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{7\\pi}{8}\\Bigr) = \\frac{2+\\sqrt{2}}{8}\\\\[2mm]\n",
        "  \\operatorname{Pr}\\bigl((a,b)=(1,1)\\bigr) & = \\frac{1}{2}\\cos^2\\Bigl(\\frac{3\\pi}{8}\\Bigr) = \\frac{2-\\sqrt{2}}{8}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  The probabilities have effectively swapped places from in the three other cases.\n",
        "  We obtain the probabilities that $a=b$ and $a\\neq b$ by summing.\n",
        "\n",
        "  $$\n",
        "  \\begin{aligned}\n",
        "  \\operatorname{Pr}(a = b) & = \\frac{2 - \\sqrt{2}}{4}\\\\[2mm]\n",
        "  \\operatorname{Pr}(a \\neq b) & = \\frac{2 + \\sqrt{2}}{4}\n",
        "  \\end{aligned}\n",
        "  $$\n",
        "\n",
        "  For the question pair $(1,1),$ Alice and Bob win if $a\\neq b,$ and therefore they win in this case with probability\n",
        "\n",
        "  $$\n",
        "  \\frac{2 + \\sqrt{2}}{4}.\n",
        "  $$\n",
        "\n",
        "They win in every case with the same probability:\n",
        "\n",
        "$$\n",
        "  \\frac{2 + \\sqrt{2}}{4} \\approx 0.85.\n",
        "$$\n",
        "\n",
        "This is therefore the probability that they win overall.\n",
        "That's significantly better than any classical strategy can do for this game; classical strategies have winning probability bounded by $3/4.$ And that makes this a very interesting example.\n",
        "\n",
        "This happens to be the *optimal* winning probability for quantum strategies; we can't do any better than this, no matter what entangled state or measurements we choose.\n",
        "This fact is known as *Tsirelson's inequality*, named for Boris Tsirelson who first proved it — and who first described the CHSH experiment as a game.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e9d02fe9",
      "metadata": {},
      "source": [
        "#### Geometric picture\n",
        "\n",
        "It is possible to think about the strategy described above geometrically, which may be helpful for understanding the relationships among the various angles chosen for Alice and Bob's operations.\n",
        "\n",
        "What Alice effectively does is to choose an angle $\\alpha,$ depending on her question $x,$ and then to apply $U_{\\alpha}$ to her qubit and measure.\n",
        "Similarly, Bob chooses an angle $\\beta,$ depending on $y,$ and then he applies $U_{\\beta}$ to his qubit and measures.\n",
        "We've chosen $\\alpha$ and $\\beta$ as follows.\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "\\alpha & = \\begin{cases}\n",
        "0 & x=0\\\\\n",
        "\\pi/4 & x=1\n",
        "\\end{cases}\\\\[4mm]\n",
        "\\beta & = \\begin{cases}\n",
        "\\pi/8 & y = 0\\\\\n",
        "-\\pi/8 & y = 1\n",
        "\\end{cases}\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "For the moment, though, let's take $\\alpha$ and $\\beta$ to be arbitrary.\n",
        "By choosing $\\alpha,$ Alice effectively defines an orthonormal basis of vectors that looks like this:\n",
        "\n",
        "![Basis for Alice](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/alpha-basis.avif)\n",
        "\n",
        "Bob does likewise, except that his angle is $\\beta$:\n",
        "\n",
        "![Basis for Bob](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/beta-basis.avif)\n",
        "\n",
        "The colors of the vectors correspond to Alice and Bob's answers: blue for $0$ and red for $1.$\n",
        "\n",
        "Now, if we combine together ($3$) and ($4$) we get the formula\n",
        "\n",
        "$$\n",
        "\\langle \\psi_{\\alpha} \\otimes\\psi_{\\beta} \\vert \\phi^+ \\rangle\n",
        "= \\frac{1}{\\sqrt{2}} \\langle \\psi_{\\alpha} \\vert \\psi_{\\beta} \\rangle;\n",
        "$$\n",
        "\n",
        "this works for all real numbers $\\alpha$ and $\\beta.$\n",
        "\n",
        "Following the same sort of analysis that we went through above, but with $\\alpha$ and $\\beta$ being variables, we find this:\n",
        "\n",
        "$$\n",
        "  \\begin{aligned}\n",
        "  & \\bigl(U_{\\alpha} \\otimes U_{\\beta}\\bigr) \\vert \\phi^+\\rangle\\\\[1mm]\n",
        "  & \\qquad =\n",
        "    \\vert 00 \\rangle \\langle \\psi_{\\alpha} \\otimes \\psi_{\\beta}\\vert \\phi^+\\rangle\n",
        "    + \\vert 01 \\rangle \\langle \\psi_{\\alpha} \\otimes\\psi_{\\beta + \\pi/2}\\vert \\phi^+\\rangle \\\\\n",
        "  & \\qquad \\qquad + \\vert 10 \\rangle \\langle \\psi_{\\alpha+\\pi/2} \\otimes \\psi_{\\beta}\\vert \\phi^+\\rangle\n",
        "    + \\vert 11 \\rangle \\langle \\psi_{\\alpha+\\pi/2} \\otimes \\psi_{\\beta+\\pi/2}\\vert \\phi^+\\rangle\\\\[2mm]\n",
        "  & \\qquad = \\frac{\n",
        "        \\langle \\psi_\\alpha \\vert \\psi_\\beta \\rangle \\vert 00\\rangle\n",
        "      + \\langle \\psi_\\alpha \\vert \\psi_{\\beta+\\pi/2} \\rangle \\vert 01\\rangle\n",
        "      + \\langle \\psi_{\\alpha+\\pi/2} \\vert \\psi_\\beta \\rangle \\vert 10\\rangle\n",
        "      + \\langle \\psi_{\\alpha+\\pi/2} \\vert \\psi_{\\beta+\\pi/2} \\rangle \\vert 11\\rangle\n",
        "      }{\\sqrt{2}}.\n",
        "  \\end{aligned}\n",
        "$$\n",
        "\n",
        "We conclude these two formulas:\n",
        "\n",
        "$$\n",
        "\\begin{aligned}\n",
        "\\operatorname{Pr}(a = b)  & = \\frac{1}{2} \\vert \\langle \\psi_\\alpha \\vert \\psi_\\beta \\rangle \\vert^2\n",
        "+ \\frac{1}{2} \\vert \\langle \\psi_{\\alpha+\\pi/2} \\vert \\psi_{\\beta+\\pi/2} \\rangle \\vert^2\n",
        "= \\cos^2(\\alpha - \\beta)\\\\[2mm]\n",
        "\\operatorname{Pr}(a \\neq b) & = \\frac{1}{2} \\vert \\langle \\psi_\\alpha \\vert \\psi_{\\beta+\\pi/2} \\rangle \\vert^2\n",
        "+ \\frac{1}{2} \\vert \\langle \\psi_{\\alpha+\\pi/2} \\vert \\psi_\\beta \\rangle \\vert^2\n",
        "= \\sin^2(\\alpha - \\beta).\n",
        "\\end{aligned}\n",
        "$$\n",
        "\n",
        "These equations can be connected to the figures above by imagining that we superimpose the bases chosen by Alice and Bob.\n",
        "\n",
        "#### Explore the strategy\n",
        "\n",
        "When $(x,y) = (0,0),$ Alice and Bob choose $\\alpha = 0$ and $\\beta = \\pi/8,$ and by superimposing their bases we obtain this figure:\n",
        "\n",
        "![Alice and Bob bases case 1](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/strategy00.avif)\n",
        "\n",
        "The angle between the red vectors is $\\pi/8,$ which is the same as the angle between the two blue vectors.\n",
        "The probability that Alice and Bob's outcomes agree is the cosine-squared of this angle,\n",
        "\n",
        "$$\n",
        "\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 + \\sqrt{2}}{4},\n",
        "$$\n",
        "\n",
        "while the probability they disagree is the sine-squared of this angle,\n",
        "\n",
        "$$\n",
        "\\sin^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 - \\sqrt{2}}{4}.\n",
        "$$\n",
        "\n",
        "When $(x,y) = (0,1),$ Alice and Bob choose $\\alpha = 0$ and $\\beta = -\\pi/8,$ and by superimposing their bases we obtain this figure:\n",
        "\n",
        "![Alice and Bob bases case 1](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/strategy01.avif)\n",
        "\n",
        "The angle between the red vectors is again $\\pi/8,$ as is the angle between the blue vectors.\n",
        "The probability that Alice and Bob's outcomes agree is again the cosine-squared of this angle,\n",
        "\n",
        "$$\n",
        "\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 + \\sqrt{2}}{4},\n",
        "$$\n",
        "\n",
        "while the probability they disagree is the sine-squared of this angle,\n",
        "\n",
        "$$\n",
        "\\sin^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 - \\sqrt{2}}{4}.\n",
        "$$\n",
        "\n",
        "When $(x,y) = (1,0),$ Alice and Bob choose $\\alpha = \\pi/4$ and $\\beta = \\pi/8,$ and by superimposing their bases we obtain this figure:\n",
        "\n",
        "![Alice and Bob bases case 1](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/strategy10.avif)\n",
        "\n",
        "The bases have changed but the angles haven't — once again the angle between vectors of the same color is $\\pi/8.$\n",
        "The probability that Alice and Bob's outcomes agree is\n",
        "\n",
        "$$\n",
        "\\cos^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 + \\sqrt{2}}{4},\n",
        "$$\n",
        "\n",
        "and the probability they disagree is\n",
        "\n",
        "$$\n",
        "\\sin^2\\Bigl(\\frac{\\pi}{8}\\Bigr) = \\frac{2 - \\sqrt{2}}{4}.\n",
        "$$\n",
        "\n",
        "When $(x,y) = (1,1),$ Alice and Bob choose $\\alpha = \\pi/4$ and $\\beta = -\\pi/8.$ When we superimpose their bases, we see that something different has happened:\n",
        "\n",
        "![Alice and Bob bases case 1](https://quantum.cloud.ibm.com/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/strategy11.avif)\n",
        "\n",
        "By the way the angles were chosen, this time the angle between vectors having the same color is $3\\pi/8$ rather than $\\pi/8.$\n",
        "The probability that Alice and Bob's outcomes agree is still the cosine-squared of this angle, but this time the value is\n",
        "\n",
        "$$\n",
        "\\cos^2\\Bigl(\\frac{3\\pi}{8}\\Bigr) = \\frac{2 - \\sqrt{2}}{4}.\n",
        "$$\n",
        "\n",
        "The probability the outcomes disagree is the sine-squared of this angle, which in this case is this:\n",
        "\n",
        "$$\n",
        "\\sin^2\\Bigl(\\frac{3\\pi}{8}\\Bigr) = \\frac{2 + \\sqrt{2}}{4}.\n",
        "$$\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8ce0e191",
      "metadata": {},
      "source": [
        "### Remarks\n",
        "\n",
        "The basic idea of an experiment like the CHSH game, where entanglement leads to statistical results that are inconsistent with purely classical reasoning, is due to John Bell, the namesake of the Bell states.\n",
        "For this reason, people often refer to experiments of this sort as *Bell tests*.\n",
        "Sometimes people also refer to *Bell's theorem*, which can be formulated in different ways — but the essence of it is that quantum mechanics is not compatible with so-called *local hidden variable theories*.\n",
        "The CHSH game is a particularly clean and simple example of a Bell test, and can be viewed as a proof, or demonstration, of Bell's theorem.\n",
        "\n",
        "The CHSH game offers a way to experimentally test the theory of quantum information.\n",
        "We can perform experiments that implement the CHSH game, and test the sorts of strategies based on entanglement described above.\n",
        "This provides us with a high degree of confidence that entanglement is real — and unlike the sometimes vague or poetic ways that we come up with to explain entanglement, the CHSH game gives us a concrete and testable way to *observe* entanglement.\n",
        "The 2022 Nobel Prize in Physics acknowledges the importance of this line of work: the prize was awarded to Alain Aspect, John Clauser (the C in CHSH), and Anton Zeilinger, for observing entanglement through Bell tests on entangled photons.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "edbf2b68",
      "metadata": {},
      "source": [
        "### Qiskit implementation\n",
        "\n",
        "We can implement the CHSH game, together with the quantum strategy defined above, in Qiskit as follows.\n",
        "\n",
        "First, here's the definition of the game itself, which allows an arbitrary strategy to be plugged in as an argument.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "854d0fbf",
      "metadata": {},
      "outputs": [],
      "source": [
        "def chsh_game(strategy):\n",
        "    # This function runs the CHSH game, using the strategy (a function\n",
        "    # from two bits to two bits), returning 1 for a win and 0 for a loss.\n",
        "\n",
        "    # Choose x and y randomly\n",
        "    x, y = random.randint(0, 1), random.randint(0, 1)\n",
        "\n",
        "    # Use the strategy to determine a and b\n",
        "    a, b = strategy(x, y)\n",
        "\n",
        "    # Decide if the strategy wins or loses\n",
        "    if (a != b) == (x & y):\n",
        "        return 1  # Win\n",
        "    return 0  # Lose"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "38a10fe4",
      "metadata": {},
      "source": [
        "Now we'll create a function that outputs a circuit depending on the questions for Alice and Bob. We'll let the qubits have their default names for simplicity, and we'll use the built-in $R_y(\\theta)$ gate for Alice and Bob's actions.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 14,
      "id": "072bbab3",
      "metadata": {},
      "outputs": [],
      "source": [
        "def chsh_circuit(x, y):\n",
        "    # This function creates a `QuantumCircuit` implementing the quantum\n",
        "    # strategy described above (including the e-bit preparation).\n",
        "\n",
        "    qc = QuantumCircuit(2, 2)\n",
        "\n",
        "    # Prepare an e-bit\n",
        "    qc.h(0)\n",
        "    qc.cx(0, 1)\n",
        "    qc.barrier()\n",
        "\n",
        "    # Alice's actions\n",
        "    if x == 0:\n",
        "        qc.ry(0, 0)\n",
        "    else:\n",
        "        qc.ry(-pi / 2, 0)\n",
        "    qc.measure(0, 0)\n",
        "\n",
        "    # Bob's actions\n",
        "    if y == 0:\n",
        "        qc.ry(-pi / 4, 1)\n",
        "    else:\n",
        "        qc.ry(pi / 4, 1)\n",
        "    qc.measure(1, 1)\n",
        "\n",
        "    return qc"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "574ac485",
      "metadata": {},
      "source": [
        "Here are the four possible circuits, depending on which questions are asked.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 15,
      "id": "4f57a9c8",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "(x,y) = (0,0)\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/4f57a9c8-1.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "(x,y) = (0,1)\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/4f57a9c8-3.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "(x,y) = (1,0)\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/4f57a9c8-5.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        },
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "(x,y) = (1,1)\n"
          ]
        },
        {
          "data": {
            "text/plain": [
              "<Image src=\"/learning/images/courses/basics-of-quantum-information/entanglement-in-action/qiskit-implementation/extracted-outputs/4f57a9c8-7.avif\" alt=\"Output of the previous code cell\" />"
            ]
          },
          "metadata": {},
          "output_type": "display_data"
        }
      ],
      "source": [
        "# Draw the four possible circuits\n",
        "\n",
        "print(\"(x,y) = (0,0)\")\n",
        "display(chsh_circuit(0, 0).draw(output=\"mpl\"))\n",
        "\n",
        "print(\"(x,y) = (0,1)\")\n",
        "display(chsh_circuit(0, 1).draw(output=\"mpl\"))\n",
        "\n",
        "print(\"(x,y) = (1,0)\")\n",
        "display(chsh_circuit(1, 0).draw(output=\"mpl\"))\n",
        "\n",
        "print(\"(x,y) = (1,1)\")\n",
        "display(chsh_circuit(1, 1).draw(output=\"mpl\"))"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "008fa3e8",
      "metadata": {},
      "source": [
        "Now we'll create a job using the Aer simulator that runs the circuit a single time for a given input pair $(x,y).$\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 16,
      "id": "a8799503-f844-4099-b3a6-47137d72b499",
      "metadata": {},
      "outputs": [],
      "source": [
        "def quantum_strategy(x, y):\n",
        "    # This function runs the appropriate quantum circuit defined above\n",
        "    # one time and returns the measurement results\n",
        "\n",
        "    # Setting `shots=1` to run the circuit once\n",
        "    result = AerSimulator().run(chsh_circuit(x, y), shots=1).result()\n",
        "    statistics = result.get_counts()\n",
        "\n",
        "    # Determine the output bits and return them\n",
        "    bits = list(statistics.keys())[0]\n",
        "    a, b = bits[0], bits[1]\n",
        "    return a, b"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "b0afbdfa",
      "metadata": {},
      "source": [
        "Finally, we'll play the game 1000 times and compute the fraction that the strategy wins.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 17,
      "id": "26306e3c",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Fraction of games won: 0.867\n"
          ]
        }
      ],
      "source": [
        "NUM_GAMES = 1000\n",
        "TOTAL_SCORE = 0\n",
        "\n",
        "for _ in range(NUM_GAMES):\n",
        "    TOTAL_SCORE += chsh_game(quantum_strategy)\n",
        "\n",
        "print(\"Fraction of games won:\", TOTAL_SCORE / NUM_GAMES)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "2ba5960a",
      "metadata": {},
      "source": [
        "We can also define a classical strategy and see how well it works.\n",
        "This is just one strategy — others can be tested by changing the code — but it is among the optimal classical strategies.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 18,
      "id": "b8eb8d23",
      "metadata": {},
      "outputs": [],
      "source": [
        "def classical_strategy(x, y):\n",
        "    # This function implements just one example of an optimal classical\n",
        "    # strategy for the CHSH game. Other classical strategies can be\n",
        "    # implemented by changing the bit values assigned to a and b.\n",
        "\n",
        "    # Alice's answer\n",
        "    if x == 0:\n",
        "        a = 0\n",
        "    elif x == 1:\n",
        "        a = 1\n",
        "\n",
        "    # Bob's answer\n",
        "    if y == 0:\n",
        "        b = 1\n",
        "    elif y == 1:\n",
        "        b = 0\n",
        "\n",
        "    return a, b"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "6ced89cf",
      "metadata": {},
      "source": [
        "Again let's play the game 1000 times to see how well it works.\n",
        "\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 19,
      "id": "2b26410d",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "Fraction of games won: 0.747\n"
          ]
        }
      ],
      "source": [
        "NUM_GAMES = 1000\n",
        "TOTAL_SCORE = 0\n",
        "\n",
        "for _ in range(NUM_GAMES):\n",
        "    TOTAL_SCORE += chsh_game(classical_strategy)\n",
        "\n",
        "print(\"Fraction of games won:\", TOTAL_SCORE / NUM_GAMES)"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "a2582a40",
      "metadata": {},
      "source": [
        "Although there's randomness involved, the statistics are very unlikely to deviate too much after 1000 runs. The quantum strategy wins about 85% of the time while a classical strategy can't win more than about 75% of the time.\n",
        "\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "id": "a1b8767d",
      "source": "© IBM Corp., 2017-2026"
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "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"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}