{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": [
     "remove_cell"
    ]
   },
   "source": [
    "<h1 style=\"font-size:35px;\n",
    "        color:black;\n",
    "        \">Lab 2: Quantum Circuits by IBM Quantum</h1>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from qiskit import *\n",
    "from qiskit_aer import Aer\n",
    "from qiskit.visualization import plot_histogram\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "tags": []
   },
   "source": [
    "<h2 style=\"font-size:24px;\">2.1: Classical logic gates with quantum circuits</h2>\n",
    "\n",
    "<br>\n",
    "<div style=\"background: #E8E7EB; border-radius: 5px;\n",
    "-moz-border-radius: 5px;\">\n",
    "  <p style=\"background: #800080;\n",
    "            border-radius: 5px 5px 0px 0px;\n",
    "            padding: 10px 0px 10px 10px;\n",
    "            font-size:18px;\n",
    "            color:white;\n",
    "            \"><b>Goal</b></p>\n",
    "    <p style=\" padding: 0px 0px 10px 10px;\n",
    "              font-size:16px;\">Create quantum circuit functions that can compute the XOR, AND, NAND and OR gates using the NOT gate (expressed as x in Qiskit), the CNOT gate (expressed as cx in Qiskit) and the Toffoli gate (expressed as ccx in Qiskit) .</p>\n",
    "</div>\n",
    "\n",
    "An implementation of the `NOT` gate is provided as an example."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def NOT(inp):\n",
    "    \"\"\"An NOT gate.\n",
    "    \n",
    "    Parameters:\n",
    "        inp (str): Input, encoded in qubit 0.\n",
    "        \n",
    "    Returns:\n",
    "        QuantumCircuit: Output NOT circuit.\n",
    "        str: Output value measured from qubit 0.\n",
    "    \"\"\"\n",
    "\n",
    "    qc = QuantumCircuit(1, 1) # A quantum circuit with a single qubit and a single classical bit\n",
    "    qc.reset(0)\n",
    "    \n",
    "    # We encode '0' as the qubit state |0⟩, and '1' as |1⟩\n",
    "    # Since the qubit is initially |0⟩, we don't need to do anything for an input of '0'\n",
    "    # For an input of '1', we do an x to rotate the |0⟩ to |1⟩\n",
    "    if inp=='1':\n",
    "        qc.x(0)\n",
    "        \n",
    "    # barrier between input state and gate operation \n",
    "    qc.barrier()\n",
    "    \n",
    "    # Now we've encoded the input, we can do a NOT on it using x\n",
    "    qc.x(0)\n",
    "    \n",
    "    #barrier between gate operation and measurement\n",
    "    qc.barrier()\n",
    "    \n",
    "    # Finally, we extract the |0⟩/|1⟩ output of the qubit and encode it in the bit c[0]\n",
    "    qc.measure(0,0)\n",
    "    qc.draw('mpl')\n",
    "    \n",
    "    # We'll run the program on a simulator\n",
    "    backend = Aer.get_backend('aer_simulator')\n",
    "    # Since the output will be deterministic, we can use just a single shot to get it\n",
    "    job = backend.run(qc, shots=1, memory=True)\n",
    "    output = job.result().get_memory()[0]\n",
    "    \n",
    "    return qc, output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Test the function\n",
    "for inp in ['0', '1']:\n",
    "    qc, out = NOT(inp)\n",
    "    print('NOT with input',inp,'gives output',out)\n",
    "    display(qc.draw())\n",
    "    print('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">&#128211; XOR gate</h3>\n",
    "\n",
    "Takes two binary strings as input and gives one as output.\n",
    "\n",
    "The output is '0' when the inputs are equal and  '1' otherwise."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def XOR(inp1,inp2):\n",
    "    \"\"\"An XOR gate.\n",
    "    \n",
    "    Parameters:\n",
    "        inpt1 (str): Input 1, encoded in qubit 0.\n",
    "        inpt2 (str): Input 2, encoded in qubit 1.\n",
    "        \n",
    "    Returns:\n",
    "        QuantumCircuit: Output XOR circuit.\n",
    "        str: Output value measured from qubit 1.\n",
    "    \"\"\"\n",
    "  \n",
    "    qc = QuantumCircuit(2, 1) \n",
    "    qc.reset(range(2))\n",
    "    \n",
    "    if inp1=='1':\n",
    "        qc.x(0)\n",
    "    if inp2=='1':\n",
    "        qc.x(1)\n",
    "    \n",
    "    # barrier between input state and gate operation \n",
    "    qc.barrier()\n",
    "    \n",
    "    # this is where your program for quantum XOR gate goes\n",
    "    #\n",
    "    #\n",
    "    # FILL YOUR CODE IN HERE\n",
    "    #\n",
    "    #\n",
    "    # barrier between input state and gate operation \n",
    "    qc.barrier()\n",
    "    \n",
    "    qc.measure(1,0) # output from qubit 1 is measured\n",
    "  \n",
    "    #We'll run the program on a simulator\n",
    "    backend = Aer.get_backend('aer_simulator')\n",
    "    #Since the output will be deterministic, we can use just a single shot to get it\n",
    "    job = backend.run(qc, shots=1, memory=True)\n",
    "    output = job.result().get_memory()[0]\n",
    "  \n",
    "    return qc, output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Test the function\n",
    "for inp1 in ['0', '1']:\n",
    "    for inp2 in ['0', '1']:\n",
    "        qc, output = XOR(inp1, inp2)\n",
    "        print('XOR with inputs',inp1,inp2,'gives output',output)\n",
    "        display(qc.draw())\n",
    "        print('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">&#128211; AND gate</h3>\n",
    "\n",
    "Takes two binary strings as input and gives one as output.\n",
    "\n",
    "The output is `'1'` only when both the inputs are `'1'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def AND(inp1,inp2):\n",
    "    \"\"\"An AND gate.\n",
    "    \n",
    "    Parameters:\n",
    "        inpt1 (str): Input 1, encoded in qubit 0.\n",
    "        inpt2 (str): Input 2, encoded in qubit 1.\n",
    "        \n",
    "    Returns:\n",
    "        QuantumCircuit: Output XOR circuit.\n",
    "        str: Output value measured from qubit 2.\n",
    "    \"\"\"\n",
    "    qc = QuantumCircuit(3, 1) \n",
    "    qc.reset(range(2))\n",
    "  \n",
    "    if inp1=='1':\n",
    "        qc.x(0)\n",
    "    if inp2=='1':\n",
    "        qc.x(1)\n",
    "        \n",
    "    qc.barrier()\n",
    "\n",
    "    # this is where your program for quantum AND gate goes\n",
    "    #\n",
    "    #\n",
    "    # FILL YOUR CODE IN HERE\n",
    "    #\n",
    "    #\n",
    "    qc.barrier()\n",
    "    qc.measure(2, 0) # output from qubit 2 is measured\n",
    "  \n",
    "    # We'll run the program on a simulator\n",
    "    backend = Aer.get_backend('aer_simulator')\n",
    "    # Since the output will be deterministic, we can use just a single shot to get it\n",
    "    job = backend.run(qc, shots=1, memory=True)\n",
    "    output = job.result().get_memory()[0]\n",
    "  \n",
    "    return qc, output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Test the function\n",
    "for inp1 in ['0', '1']:\n",
    "    for inp2 in ['0', '1']:\n",
    "        qc, output = AND(inp1, inp2)\n",
    "        print('AND with inputs',inp1,inp2,'gives output',output)\n",
    "        display(qc.draw())\n",
    "        print('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">&#128211; NAND gate</h3>\n",
    "\n",
    "Takes two binary strings as input and gives one as output.\n",
    "\n",
    "The output is `'0'` only when both the inputs are `'1'`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def NAND(inp1,inp2):\n",
    "    \"\"\"An NAND gate.\n",
    "    \n",
    "    Parameters:\n",
    "        inpt1 (str): Input 1, encoded in qubit 0.\n",
    "        inpt2 (str): Input 2, encoded in qubit 1.\n",
    "        \n",
    "    Returns:\n",
    "        QuantumCircuit: Output NAND circuit.\n",
    "        str: Output value measured from qubit 2.\n",
    "    \"\"\"\n",
    "    qc = QuantumCircuit(3, 1) \n",
    "    qc.reset(range(3))\n",
    "    \n",
    "    if inp1=='1':\n",
    "        qc.x(0)\n",
    "    if inp2=='1':\n",
    "        qc.x(1)\n",
    "    \n",
    "    qc.barrier()\n",
    "    \n",
    "    # this is where your program for quantum NAND gate goes\n",
    "    #\n",
    "    #\n",
    "    #\n",
    "    # FILL YOUR CODE IN HERE\n",
    "    #\n",
    "    #\n",
    "    qc.barrier()\n",
    "    qc.measure(2, 0) # output from qubit 2 is measured\n",
    "  \n",
    "    # We'll run the program on a simulator\n",
    "    backend = Aer.get_backend('aer_simulator')\n",
    "    # Since the output will be deterministic, we can use just a single shot to get it\n",
    "    job = backend.run(qc,shots=1,memory=True)\n",
    "    output = job.result().get_memory()[0]\n",
    "  \n",
    "    return qc, output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Test the function\n",
    "for inp1 in ['0', '1']:\n",
    "    for inp2 in ['0', '1']:\n",
    "        qc, output = NAND(inp1, inp2)\n",
    "        print('NAND with inputs',inp1,inp2,'gives output',output)\n",
    "        display(qc.draw())\n",
    "        print('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">&#128211; OR gate</h3>\n",
    "\n",
    "Takes two binary strings as input and gives one as output.\n",
    "\n",
    "The output is '1' if either input is '1'."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def OR(inp1,inp2):\n",
    "    \"\"\"An OR gate.\n",
    "    \n",
    "    Parameters:\n",
    "        inpt1 (str): Input 1, encoded in qubit 0.\n",
    "        inpt2 (str): Input 2, encoded in qubit 1.\n",
    "        \n",
    "    Returns:\n",
    "        QuantumCircuit: Output XOR circuit.\n",
    "        str: Output value measured from qubit 2.\n",
    "    \"\"\"\n",
    "\n",
    "    qc = QuantumCircuit(3, 1) \n",
    "    qc.reset(range(3))\n",
    "    \n",
    "    if inp1=='1':\n",
    "        qc.x(0)\n",
    "    if inp2=='1':\n",
    "        qc.x(1)\n",
    "    \n",
    "    qc.barrier()\n",
    "   \n",
    "    # this is where your program for quantum OR gate goes\n",
    "    #\n",
    "    #\n",
    "    # FILL YOUR CODE IN HERE\n",
    "    #\n",
    "    #\n",
    "    qc.barrier()\n",
    "    qc.measure(2, 0) # output from qubit 2 is measured\n",
    "  \n",
    "    # We'll run the program on a simulator\n",
    "    backend = Aer.get_backend('aer_simulator')\n",
    "    # Since the output will be deterministic, we can use just a single shot to get it\n",
    "    job = backend.run(qc,shots=1,memory=True)\n",
    "    output = job.result().get_memory()[0]\n",
    "  \n",
    "    return qc, output"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "## Test the function\n",
    "for inp1 in ['0', '1']:\n",
    "    for inp2 in ['0', '1']:\n",
    "        qc, output = OR(inp1, inp2)\n",
    "        print('OR with inputs',inp1,inp2,'gives output',output)\n",
    "        display(qc.draw())\n",
    "        print('\\n')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h2 style=\"font-size:24px;\">2.2: AND gate on Quantum Computer</h2>\n",
    "<br>\n",
    "<div style=\"background: #E8E7EB; border-radius: 5px;\n",
    "-moz-border-radius: 5px;\">\n",
    "  <p style=\"background: #800080;\n",
    "            border-radius: 5px 5px 0px 0px;\n",
    "            padding: 10px 0px 10px 10px;\n",
    "            font-size:18px;\n",
    "            color:white;\n",
    "            \"><b>Goal</b></p>\n",
    "    <p style=\" padding: 0px 0px 10px 10px;\n",
    "              font-size:16px;\">Execute AND gate on a real quantum system and learn how the noise properties affect the result.</p>\n",
    "</div>\n",
    "\n",
    "In Part 1 you made an `AND` gate from quantum gates, and executed it on the simulator.  Here in Part 2 you will do it again, but instead run the circuits on a real quantum computer.  When using a real quantum system, one thing you should keep in mind is that present day quantum computers are not fault tolerant; they are noisy.\n",
    "\n",
    "The 'noise' in a quantum system is the collective effects of all the things that should not happen, but nevertheless do. Noise results in outputs are not always what we would expect. There is noise associated with all processes in a quantum circuit: preparing the initial state, applying gates, and qubit measurement.  For the gates, noise levels can vary between different gates and between different qubits. `cx` gates are typically more noisy than any single qubit gate.\n",
    "\n",
    "Here we will use the quantum systems from the IBM Quantum Experience.  If you do not have access, you can do so [here](https://qiskit.org/documentation/install.html#access-ibm-quantum-systems).\n",
    "\n",
    "Now that you are ready to use the real quantum computer, let's begin."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">Step 1. Choosing a device</h3>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Provides access to the IBM Quantum services available to an account. Authenticate against IBM Quantum for use from saved credentials or during session. Credentials can be saved to disk by calling the save_account() method:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "from qiskit_ibm_provider import IBMProvider\n",
    "IBMProvider.save_account(token='MY_API_TOKEN')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Then load the account from the credentials saved on disk by running the following cell:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": []
   },
   "outputs": [],
   "source": [
    "provider = IBMProvider()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "After your account is loaded, you can see the list of providers that you have access to by running the cell below. Each provider offers different systems for use. For open users, there is typically only one provider `ibm-q/open/main`:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let us grab the provider using `get_provider`.  The command, `provider.backends( )` shows you the list of backends that are available to you from the selected provider."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "provider.backends()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Among these options, you may pick one of the systems to run your circuits on.  All except the `ibmq_qasm_simulator` all are real quantum computers that you can use.  The differences among these systems resides in the number of qubits, their connectivity, and the system error rates.  \n",
    "\n",
    "Upon executing the following cell you will be presented the error map about your choice of the backend. It reveals the latest noise information for the system. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "import qiskit.utils\n",
    "from qiskit.visualization import plot_error_map\n",
    "backend_ex = provider.get_backend('ibm_kyoto')\n",
    "\n",
    "qiskit.visualization.plot_error_map(backend_ex)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "For our AND gate circuit, we need a backend with three or more qubits, which is true for all the real systems.  Below is an example of how to filter backends, where we filter for number of qubits, and remove simulators:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "backends = provider.backends(filters = lambda x:x.configuration().n_qubits >= 3 and not x.configuration().simulator\n",
    "                             and x.status().operational==True)\n",
    "backends"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "One convenient way to choose a system is using the `least_busy` function to get the backend with the lowest number of jobs in queue.  The downside is that the result might have relatively poor accuracy because, not surprisingly, the lowest error rate systems are the most popular."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "from qiskit_ibm_provider import least_busy\n",
    "backend = least_busy(provider.backends(filters=lambda x: x.configuration().n_qubits >= 3 and \n",
    "                                        not x.configuration().simulator and x.status().operational==True))\n",
    "backend"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Real quantum computers need to be recalibrated regularly, and the fidelity of a specific qubit or gate can change over time. Therefore, which system would produce results with less error can vary. \n",
    "\n",
    "In this exercise, we select one of the IBM Quantum systems: `ibm_kyoto`."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "# run this cell\n",
    "backend = provider.get_backend('ibm_kyoto')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">Step 2. Define AND function for a real device</h3>\n",
    "\n",
    "We now define the AND function.  We choose 8192 as the number of shots, the maximum number of shots for open IBM systems, to reduce the variance in the final result. Related information is well explained [here](https://quantum-computing.ibm.com/docs/manage/backends/configuration)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h4 style=\"font-size: 16px\">Qiskit Transpiler</h4>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It is important to know that when running a circuit on a real quantum computer, circuits typically need to be transpiled for the backend that you select so that the circuit contains only those gates that the quantum computer can actually perform. Primarily this involves the addition of swap gates so that two-qubit gates in the circuit map to those pairs of qubits on the device that can actually perform these gates. The following cell shows the AND gate represented as a Toffoli gate decomposed into single- and two-qubit gates, which are the only types of gate that can be run on IBM hardware."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "qc_and = QuantumCircuit(3)\n",
    "qc_and.ccx(0,1,2)\n",
    "print('AND gate')\n",
    "display(qc_and.draw())\n",
    "print('\\n\\nTranspiled AND gate with all the required connectivity')\n",
    "qc_and.decompose().draw()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In addition, there are often optimizations that the transpiler can perform that reduce the overall gate count, and thus total length of the input circuits.  Note that the addition of swaps to match the device topology, and optimizations for reducing the length of a circuit are at odds with each other. In what follows we will make use of `initial_layout` that allows us to pick the qubits on a device used for the computation and `optimization_level`, an argument that allows selecting from internal defaults for circuit swap mapping and optimization methods to perform.\n",
    "\n",
    "You can learn more about transpile function in depth [here](https://qiskit.org/documentation/apidoc/transpiler.html)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's modify AND function in Part1 properly for the real system with the transpile step included."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "from qiskit_ibm_provider.job import job_monitor"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "uses-hardware"
    ]
   },
   "outputs": [],
   "source": [
    "# run the cell to define AND gate for real quantum system\n",
    "\n",
    "def AND(inp1, inp2, backend, layout):\n",
    "    \n",
    "    qc = QuantumCircuit(3, 1) \n",
    "    qc.reset(range(3))\n",
    "    \n",
    "    if inp1=='1':\n",
    "        qc.x(0)\n",
    "    if inp2=='1':\n",
    "        qc.x(1)\n",
    "        \n",
    "    qc.barrier()\n",
    "    qc.ccx(0, 1, 2) \n",
    "    qc.barrier()\n",
    "    qc.measure(2, 0) \n",
    "  \n",
    "    qc_trans = transpile(qc, backend, initial_layout=layout, optimization_level=3)\n",
    "    job = backend.run(qc_trans, shots=8192)\n",
    "    print(job.job_id())\n",
    "    job_monitor(job)\n",
    "    \n",
    "    output = job.result().get_counts()\n",
    "    \n",
    "    return qc_trans, output"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When you submit jobs to quantum systems, `job_monitor` will start tracking where your submitted job is in the pipeline."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First, examine `ibmq_quito` through the widget by running the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "qiskit.visualization.plot_error_map(backend)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>&#128211; Determine three qubit initial layout considering the error map and assign it to the list variable layout.</p>"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "layout = [3,1,0]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>&#128211; Describe the reason for your choice of initial layout.</p>\n",
    "\n",
    "**your answer:**              "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Execute `AND` gate on `ibmq_quito` by running the cell below."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "output_all = []\n",
    "qc_trans_all = []\n",
    "prob_all = []\n",
    "\n",
    "worst = 1\n",
    "best = 0\n",
    "for input1 in ['0','1']:\n",
    "    for input2 in ['0','1']:\n",
    "        qc_trans, output = AND(input1, input2, backend, layout)\n",
    "        \n",
    "        output_all.append(output)\n",
    "        qc_trans_all.append(qc_trans)\n",
    "        \n",
    "        prob = output[str(int( input1=='1' and input2=='1' ))]/8192\n",
    "        prob_all.append(prob)\n",
    "        \n",
    "        print('\\nProbability of correct answer for inputs',input1,input2)\n",
    "        print('{:.2f}'.format(prob) )\n",
    "        print('---------------------------------')\n",
    "        \n",
    "        worst = min(worst,prob)\n",
    "        best = max(best, prob)\n",
    "        \n",
    "print('')\n",
    "print('\\nThe highest of these probabilities was {:.2f}'.format(best))\n",
    "print('The lowest of these probabilities was {:.2f}'.format(worst))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h3 style=\"font-size: 20px\">Step 3. Interpret the result</h3>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "There are several quantities that distinguish the circuits.  Chief among them is the  **circuit depth**.  Circuit depth is defined in detail [here](https://qiskit.org/documentation/apidoc/circuit.html) (See the Supplementary Information and click the Quantum Circuit Properties tab). Circuit depth is proportional to the number of gates in a circuit, and loosely corresponds to the runtime of the circuit on hardware.   Therefore, circuit depth is an easy to compute metric that can be used to estimate the fidelity of an executed circuit.\n",
    "\n",
    "A second important value is the number of **nonlocal** (multi-qubit) **gates** in a circuit.  On IBM Quantum systems, the only nonlocal gate that can physically be performed is the CNOT gate.  Recall that CNOT gates are the most expensive gates to perform, and thus the total number of these gates also serves as a good benchmark for the accuracy of the final output."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<h4 style=\"font-size: 16px\"> Circuit depth and result accuracy</h4>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Running the cells below will display the four transpiled AND gate circuit diagrams with the corresponding inputs that executed on `ibm_lagos` and their circuit depths with the success probability for producing correct answer."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Transpiled AND gate circuit for ibmq_vigo with input 0 0')\n",
    "print('\\nThe circuit depth : {}'.format (qc_trans_all[0].depth()))\n",
    "print('# of nonlocal gates : {}'.format (qc_trans_all[0].num_nonlocal_gates()))\n",
    "print('Probability of correct answer : {:.2f}'.format(prob_all[0]) )\n",
    "qc_trans_all[0].draw('mpl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Transpiled AND gate circuit for ibmq_vigo with input 0 1')\n",
    "print('\\nThe circuit depth : {}'.format (qc_trans_all[1].depth()))\n",
    "print('# of nonlocal gates : {}'.format (qc_trans_all[1].num_nonlocal_gates()))\n",
    "print('Probability of correct answer : {:.2f}'.format(prob_all[1]) )\n",
    "qc_trans_all[1].draw('mpl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Transpiled AND gate circuit for ibmq_vigo with input 1 0')\n",
    "print('\\nThe circuit depth : {}'.format (qc_trans_all[2].depth()))\n",
    "print('# of nonlocal gates : {}'.format (qc_trans_all[2].num_nonlocal_gates()))\n",
    "print('Probability of correct answer : {:.2f}'.format(prob_all[2]) )\n",
    "qc_trans_all[2].draw('mpl')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Transpiled AND gate circuit for ibmq_vigo with input 1 1')\n",
    "print('\\nThe circuit depth : {}'.format (qc_trans_all[3].depth()))\n",
    "print('# of nonlocal gates : {}'.format (qc_trans_all[3].num_nonlocal_gates()))\n",
    "print('Probability of correct answer : {:.2f}'.format(prob_all[3]) )\n",
    "qc_trans_all[3].draw('mpl')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "<p>&#128211; Explain reason for the dissimilarity of the circuits.  Describe the relations between the property of the circuit and the accuracy of the outcomes.</p>"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**your answer:**"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Qiskit v1.0.2 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.8"
  },
  "widgets": {
   "application/vnd.jupyter.widget-state+json": {
    "state": {},
    "version_major": 2,
    "version_minor": 0
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
