diff --git a/docs/unitary/tic_tac_toe.ipynb b/docs/unitary/tic_tac_toe.ipynb new file mode 100644 index 00000000..2eb09fe1 --- /dev/null +++ b/docs/unitary/tic_tac_toe.ipynb @@ -0,0 +1,510 @@ +{ + "nbformat": 4, + "nbformat_minor": 0, + "metadata": { + "colab": { + "provenance": [] + }, + "kernelspec": { + "name": "python3", + "display_name": "Python 3" + }, + "language_info": { + "name": "python" + } + }, + "cells": [ + { + "cell_type": "markdown", + "source": [ + "# Quantum Tic-Tac-Toe Development Tutorial" + ], + "metadata": { + "id": "n3tYba_Hdxh-" + } + }, + { + "cell_type": "markdown", + "source": [ + "This tutorial will explain the concepts behind a quantum version of Tic-Tac-Toe and how you would build it using the Unitary library.\n", + "\n", + "The following code block installs the unitary library from github." + ], + "metadata": { + "id": "8RA4K_m-d4w-" + } + }, + { + "cell_type": "code", + "source": [ + "!pip install --quiet git+https://github.com/quantumlib/Unitary@main\n", + "\n", + "import unitary.alpha as alpha" + ], + "metadata": { + "id": "2jNr0d0kkFKB", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "e9e5ad6d-adb4-4905-86be-fb40a7dd1318" + }, + "execution_count": 1, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + " Preparing metadata (setup.py) ... \u001b[?25l\u001b[?25hdone\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.8/1.8 MB\u001b[0m \u001b[31m10.8 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m579.1/579.1 kB\u001b[0m \u001b[31m18.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.7/1.7 MB\u001b[0m \u001b[31m25.0 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m536.7/536.7 kB\u001b[0m \u001b[31m28.3 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m1.6/1.6 MB\u001b[0m \u001b[31m30.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m278.3/278.3 kB\u001b[0m \u001b[31m24.4 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m91.2/91.2 kB\u001b[0m \u001b[31m5.5 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m115.3/115.3 kB\u001b[0m \u001b[31m10.2 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[2K \u001b[90m━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\u001b[0m \u001b[32m63.3/63.3 kB\u001b[0m \u001b[31m4.6 MB/s\u001b[0m eta \u001b[36m0:00:00\u001b[0m\n", + "\u001b[?25h Building wheel for unitary (setup.py) ... \u001b[?25l\u001b[?25hdone\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "## Classical Tic-Tac-Toe\n", + "\n", + "[Tic-Tac-Toe](https://en.wikipedia.org/wiki/Tic-tac-toe) is a common game played on a 3x3 grid for two players. The two players take alternating turns placing X's and O's onto the grid until there are either three X's or O's in a row or the grid has been filled.\n", + "\n", + "### Creating Classical Tic-Tac-Toe\n", + "\n", + "We could create a classical version of Tic-Tac-Toe by using a 3x3 array (or list of lists). Each entry would be 0 (empty), 1 (X), or 2 (O) depending on the state of that square. We can define an enumeration (Enum) to conveniently denote that.\n", + "\n", + "For instance," + ], + "metadata": { + "id": "xdTVZxNjeaIk" + } + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "id": "tElowcfudwwf" + }, + "outputs": [], + "source": [ + "import enum\n", + "\n", + "class TicTacSquare(enum.Enum):\n", + " EMPTY = 0\n", + " X = 1\n", + " O = 2\n", + "\n", + "tic_tac_toe_board = [\n", + " [TicTacSquare.EMPTY, TicTacSquare.EMPTY, TicTacSquare.EMPTY],\n", + " [TicTacSquare.EMPTY, TicTacSquare.EMPTY, TicTacSquare.EMPTY],\n", + " [TicTacSquare.EMPTY, TicTacSquare.EMPTY, TicTacSquare.EMPTY],\n", + "]" + ] + }, + { + "cell_type": "markdown", + "source": [ + "This is all that is needed to store a Tic-Tac-Toe game board classically. To finish developing the game, one would need to write a simple user interface (UI) that allows the players to set the grid values to X or O. It would also need to check whether either player has achieved three in a row or if all grid positions are filled up. This will be left up as an exercise to the reader. Instead, we will continue with the quantum version." + ], + "metadata": { + "id": "OGcYx5g-jHl0" + } + }, + { + "cell_type": "markdown", + "source": [ + "## Quantum Tic-Tac-Toe" + ], + "metadata": { + "id": "H5HEvJsGjvoo" + } + }, + { + "cell_type": "markdown", + "source": [ + "We will use the same ideas to create the quantum representation of a Tic-Tac-Toe board.\n", + "\n", + "Rather than a classical array value (integer) representing whether a square has an X or an O, we will use a [qubit](https://en.wikipedia.org/wiki/Qubit) (quantum bit) to represent it. While a classical bit can be in one of two states (0 or 1), a qubit can be in one of two states (denoted |0〉 or |1〉) or in a superposition (i.e. combination) of both states.\n", + "\n", + "For some games, this may be sufficient, as we may only need to denote whether a square is empty or occupied. (For example, this is how the game quantum chess works. Each square is a qubit representing whether a piece is occupying the square. Which kind of piece (knight, rook, etc) is kept track of classically).\n", + "\n", + "However, for Tic-Tac-Toe, we will need three different possibilities (empty, X, or O). Thus, a qubit is insufficient, and we will need to use a [Qutrit](https://en.wikipedia.org/wiki/Qutrit). A qutrit is similar to a qubit but can be in a combination of |0〉, |1〉, or |2〉. Luckily, this is easily done using the unitary repository.\n", + "\n", + "First we will need a name for each square on the board, so we can name the qutrits. We will use a single letter, such as the following:\n", + "\n", + "```\n", + " a | b | c\n", + " -----------\n", + " d | e | f\n", + " -----------\n", + " g | h | i\n", + "```\n", + "\n", + "Then, we can create a `QuantumWorld` object that has nine `QuantumObject`s, one for each square:" + ], + "metadata": { + "id": "2t_dxBOGjyrY" + } + }, + { + "cell_type": "code", + "source": [ + "_SQUARE_NAMES = \"abcdefghi\"\n", + "quantum_board = alpha.QuantumWorld(\n", + " [alpha.QuantumObject(name, TicTacSquare.EMPTY) for name in _SQUARE_NAMES])\n" + ], + "metadata": { + "id": "eP3IGUR33L0w" + }, + "execution_count": 3, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "The above will create a `QuantumWorld` object that contains the representation of our tic-tac-toe board. The `QuantumWorld` will automatically know to use qutrits since we are initializing it with enums that have three possible values.\n", + "\n", + "Since it is a quantum state, we will need to \"measure\" it in order to get our tic-tac-toe board. Quantum states have two important properties:\n", + "\n", + "* Measuring them affects the state. All superpositions will disappear and we will be left in the state that we\n", + "* Results are not deterministic. When we measure, we could get one of several possible results.\n", + "\n", + "Because of that, there are two different ways to get the results from the quantum state. They are named similar to \"stack\" operations.\n", + "\n", + "* `pop()`: Measure the state. This will change the result of the `QuantumWorld` to the state you measured.\n", + "* `peek()`: Retrieve a \"sample\" measurement from the `QuantumWorld` without destructively measuring or changing the state.\n", + "\n", + "Let's try this with our initial state:" + ], + "metadata": { + "id": "eiE6QCOa5hCO" + } + }, + { + "cell_type": "code", + "source": [ + "print(quantum_board.peek())" + ], + "metadata": { + "id": "2GuIFS2c8zxW", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "9d3d0c28-1c18-422a-d96e-16bd46e8166c" + }, + "execution_count": 4, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[[, , , , , , , , ]]\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "We can see that the state is all empty, but it is a little difficult to read. Let's make a function to print it out in a more readable format:" + ], + "metadata": { + "id": "XhKBMbSX84ou" + } + }, + { + "cell_type": "code", + "source": [ + "_MARK_SYMBOLS = {TicTacSquare.EMPTY: \".\", TicTacSquare.X: \"X\", TicTacSquare.O: \"O\"}\n", + "\n", + "def _histogram(results: list[list[TicTacSquare]]) -> list[dict[TicTacSquare, int]]:\n", + " \"\"\"Turns a list of whole board measurements into a histogram.\n", + "\n", + " Returns:\n", + " A 9 element list (one for each square) that contains a dictionary with\n", + " counts for EMPTY, X, and O.\n", + " \"\"\"\n", + " hist = []\n", + " for idx in range(9):\n", + " hist.append({TicTacSquare.EMPTY: 0, TicTacSquare.X: 0, TicTacSquare.O: 0})\n", + " for r in results:\n", + " for idx in range(9):\n", + " hist[idx][r[idx]] += 1\n", + " return hist\n", + "\n", + "def print_board(board) -> str:\n", + " \"\"\"Returns the TicTacToe board in ASCII form.\"\"\"\n", + "\n", + " # Get 100 representative samples\n", + " results = board.peek(count=100)\n", + " # Collect them into a histogram\n", + " hist = _histogram(results)\n", + "\n", + " # Print it out all nice\n", + " output = \"\\n\"\n", + " for row in range(3):\n", + " for mark in TicTacSquare:\n", + " output += \" \"\n", + " for col in range(3):\n", + " idx = row * 3 + col\n", + " output += f\" {_MARK_SYMBOLS[mark]} {hist[idx][mark]:3}\"\n", + " if col != 2:\n", + " output += \" |\"\n", + " output += \"\\n\"\n", + " if idx in [2, 5, 8] and row != 2:\n", + " output += \"--------------------------\\n\"\n", + " return output" + ], + "metadata": { + "id": "Mf29YhvA9KdF" + }, + "execution_count": 5, + "outputs": [] + }, + { + "cell_type": "markdown", + "source": [ + "Now let's print it out again, this time in a more readable format:" + ], + "metadata": { + "id": "ZJFdibbJ95SB" + } + }, + { + "cell_type": "code", + "source": [ + "print(print_board(quantum_board))" + ], + "metadata": { + "id": "JuHW0bdT9-Bj", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "a5c86598-a5b0-4382-a6da-2f8e03eb3595" + }, + "execution_count": 6, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "We can see that, out of 100 trials, each of the squares in the grid was empty. This is expected for the initial state of the board.\n", + "\n", + "Now, let's try to change a square to an X. For this, we will use an effect called `QuditFlip` which will take one state and change it to another. This effect takes three arguments:\n", + "\n", + "* The dimension, which is 3, since we are using qutrits to represent three states.\n", + "* The initial state, which is 0 (Empty)\n", + "* The final state, which is 1 (X)." + ], + "metadata": { + "id": "zK5eHTzB-i3Z" + } + }, + { + "cell_type": "code", + "source": [ + "alpha.QuditFlip(3, 0, 1)(quantum_board.objects[0])\n", + "print(print_board(quantum_board))\n" + ], + "metadata": { + "id": "7e8Hsh_W_8fn", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "da8e7535-92ed-41dc-af9c-85a1c4cd2174" + }, + "execution_count": 7, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + " . 0 | . 100 | . 100\n", + " X 100 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Now, the upper left corner is 'X' in 100 our of 100 samples.\n", + "\n", + "So far, this game is very similar to classical tic-tac-toe. Let's introduce some quantum-ness into our game with a new move particular to quantum states.\n", + "\n", + "This move will be a 'split'. A split move will be defined as marking two grid squares simultaneously. For instance, we will try to mark both 'b' and 'c' with 'O'. This will work by utilizing superposition. The 'O' will be in one of the two squares ('b' or 'c') but we will not know which one until we measure.\n", + "\n" + ], + "metadata": { + "id": "UmPZz8G2ANve" + } + }, + { + "cell_type": "code", + "source": [ + "from unitary.alpha.qudit_gates import QuditXGate, QuditISwapPowGate\n", + "class TicTacSplit(alpha.QuantumEffect):\n", + " \"\"\"\n", + " Flips a qubit from |0> to |1> then splits to another square.\n", + " Depending on the ruleset, the split is done either using a standard\n", + " sqrt-ISWAP gate, or using the custom QuditSplitGate.\n", + "\n", + " Args:\n", + " tic_tac_type: whether to mark X or O\n", + " \"\"\"\n", + "\n", + " def __init__(self, tic_tac_type: TicTacSquare):\n", + " self.tic_tac_type = tic_tac_type\n", + "\n", + " def num_dimension(self) -> int | None:\n", + " return 3\n", + "\n", + " def num_objects(self) -> int | None:\n", + " return 2\n", + "\n", + " def effect(self, *objects):\n", + " square1 = objects[0]\n", + " square2 = objects[1]\n", + " yield QuditXGate(3, 0, self.tic_tac_type.value)(square1.qubit)\n", + " yield QuditISwapPowGate(3, 0.5)(square1.qubit, square2.qubit)\n", + "\n", + "TicTacSplit(TicTacSquare.O)(quantum_board.objects[1],quantum_board.objects[2])\n", + "print(print_board(quantum_board))\n" + ], + "metadata": { + "id": "bS0Uk5eFB4T1", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "926913e1-09c8-437a-dc38-9d74a1a30152" + }, + "execution_count": 8, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "\n", + " . 0 | . 53 | . 47\n", + " X 100 | X 0 | X 0\n", + " O 0 | O 47 | O 53\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Now we can see some variation in the results. If we take 100 sample boards, the O will be in the 'b' square about 50 of them and in 'c' the rest of the time.\n", + "\n", + "Lastly, we can see what happens when we measure with a `pop()` call." + ], + "metadata": { + "id": "yT5iGVTPEVY4" + } + }, + { + "cell_type": "code", + "source": [ + "print(quantum_board.pop())\n", + "print(print_board(quantum_board))\n" + ], + "metadata": { + "id": "E8F1nyllEsZ3", + "colab": { + "base_uri": "https://localhost:8080/" + }, + "outputId": "b6b8d80c-4dfe-4084-fedd-bd6edee26145" + }, + "execution_count": 9, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "[, , , , , , , , ]\n", + "\n", + " . 0 | . 100 | . 0\n", + " X 100 | X 0 | X 0\n", + " O 0 | O 0 | O 100\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "--------------------------\n", + " . 100 | . 100 | . 100\n", + " X 0 | X 0 | X 0\n", + " O 0 | O 0 | O 0\n", + "\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "source": [ + "Now, the board has resolved to the O being in one spot or the other, but not both. This will be in the 'b' square about half the time and 'c' in the other half. However, after the measurement occurs, it will always be in the same place." + ], + "metadata": { + "id": "QuScm2UaE19Z" + } + }, + { + "cell_type": "markdown", + "source": [ + "The full example for Tic-Tac-Toe can be found here:\n", + "https://github.com/quantumlib/unitary/tree/main/unitary/examples/tictactoe" + ], + "metadata": { + "id": "yPTJTPLLFM-m" + } + } + ] +}