Proof of Concept #3: Web application for solving expressions using Grover's Search

Proof of Concept is a new exciting tutorial series that will show you how to create quantum applications step by step.

Introduction

Interested in learning how to program quantum computers? Then check out our Qiskit textbook Introduction to Quantum Computing with Qiskit.

In this tutorial we will create a web application that allows users to solve logical expressions using Grover’s search on IBM’s quantum computers. This web application will consist of a backend and frontend.

For the frontend we will use a bootstrap site consisting of HTML/CSS and JavaScript

For the backend we will use Django as the webservice and the Qiskit quantum framework.

Step 1: Install Django and Qiskit

If you don’t have Django and Qiskit then open up your terminal and enter the following:

To install Django type in:

pip install Django==3.1.5

To install Qiskit type in:

pip install qiskit

Step 2: Setting up the Django project

Now that we have django installed we need to setup the project that will contain the webservice. In your terminal point to the directory you wish to put the project and type in the following:

django-admin startproject qsite

After this the project folder will be created named qsite with the following structure:

  • qsite/     
    • manage.py     
    • qsite/         
      • __init__.py         
      • settings.py         
      • urls.py         
      • asgi.py         
      • wsgi.py

Next cd in to the outer qsite directory (the directory with manage.py) and type in the following:

python manage.py runserver

Then go to your web browser and enter localhost:8000 and you will see the following:

Congratulations! Your server has been setup successfully.

Step 3: Setup the Grover app

Now that the project has been setup we now need to create the grover app.

In Django the project is basically a container for an application. So in our case qsite is the project that will contain our grover application. You can have multiple applications in each project.

To setup the factorization app type in to the terminal:

python manage.py startapp grovers

This will create a new folder called shor with the following structure:

  • grovers/     
    • __init__.py     
    • admin.py     
    • apps.py     
    • migrations/         
      • __init__.py     
    • models.py     
    • tests.py     
    • views.py
  1. Next we will need to add the Grover’s search code in to views.py:

from django.shortcuts import render
import json

from qiskit import IBMQ
from qiskit.utils import QuantumInstance
from qiskit.circuit.library import PhaseOracle
from qiskit.algorithms import Grover, AmplificationProblem
from qiskit.tools.monitor import job_monitor

IBMQ.enable_account('ENTER API KEY HERE')
provider = IBMQ.get_provider(hub='ibm-q')

def home(request):
    return render(request, 'index.html', {})

def grovers(request):

    print(request.body)

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode);

    device = body['device']
    backend = provider.get_backend(device)

    expression = body['expression']
    oracle = PhaseOracle(expression)

    problem = AmplificationProblem(oracle=oracle, is_good_state=oracle.evaluate_bitstring)
    grover = Grover(quantum_instance=backend)

    result = grover.amplify(problem)

    counts = result.circuit_results

    response = JsonResponse({'result': str(counts)})
    return response

Note: In the code you will see a line called IBMQ.enable_account('ENTER API KEY HERE'). This is where you need to put in an API token. In order to get an API key you will have to register to the IBM quantum experience: https://quantum-computing.ibm.com

Now in the grovers directory we will need to create a file called urls.py. This file will contain all the url endpoints for our application.

Once created enter the following code:

from django.urls import path
from grovers import views

urlpatterns = [
    path('',  views.home, name='home'),
    path('grovers/', views.grovers)]

Here we have two url patterns:

  • path('', views.home, name='home') which will serve the web application to the user when they browse to localhost:8000 in their browser

  • path('grovers/', views.grovers) which will point to our code (in views.grovers) and send the results returned by IBMs quantum devices to the user in the web application

Now in qsite/urls.py enter the following code:

from django.contrib import admin
from django.urls import path, include

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('grovers.urls'))
]

In qsite/settings.py add ‘grovers’ to the list of installed apps such that it looks like this:

INSTALLED_APPS = [

'django.contrib.admin',

'django.contrib.auth',

'django.contrib.contenttypes',

'django.contrib.sessions',

'django.contrib.messages',

'django.contrib.staticfiles',

'grovers’

]

Next in qsite/settings.py replace ROOT_URLCONF = 'qsite.urls' to:

ROOT_URLCONF = 'grovers.urls'

Next in qsite/settings.py under MIDDLEWARE get rid of 'django.middleware.csrf.CsrfViewMiddleware',

Step 4: Create the Website

Now we need to create the website that will server as the frontend. The website will be a simple bootstrap site that will allow the user to do the following things:

1.) Pick a quantum device to use to factor an integer

3.) A button called Generate that will call a script which in turn will send a request to ‘grovers/’ which will contain json data for the target device and the logical expression to be solved

4.) A loading animation that will run while the request is being processed

To implement the site we will need to create a folder called templates within the grovers directory. Then within the templates folder add a file called index.html

Within index.html enter the following code:

<!DOCTYPE html>
<html lang="en">
   <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
      <meta name="description" content="">
      <meta name="author" content="">
      <title>Satisfying Logical Expressions with Grover's Search</title>
      <!-- Bootstrap core CSS -->
      <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
      <!-- Custom styles for this template -->
      <link href="css/business-frontpage.css" rel="stylesheet">
      <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
   </head>
   <body>
      <script>
         function generate() {
           console.log("REQUEST SUCCEEDED");
           document.getElementById("loader").style.display = "block";
           document.getElementById("loader").style.visibility = "visible";
           document.getElementById("keyHeader").innerHTML = "";
           document.getElementById("keyView").innerHTML = "";
         
         targetDevice = document.getElementById("devices").value
         
         expression = document.getElementById("expression").value
         
         data = JSON.stringify({ device: targetDevice,expression:expression});
         
         $.ajax({
         type: "POST",
         url: "http://localhost:8000/grovers/",
         contentType: "application/json; charset=utf-8",
         data: data,
         success: function(d){
           console.log(d);
           document.getElementById("loader").style.display = "none";
           document.getElementById("loader").style.visibility = "hidden";
           document.getElementById("keyHeader").innerHTML = "Result:";
           document.getElementById("keyView").innerHTML = d['result'];
           }
         });
         }
      </script>
      <style>
         .loader,
         .loader:before,
         .loader:after {
         border-radius: 50%;
         width: 2.5em;
         height: 2.5em;
         -webkit-animation-fill-mode: both;
         animation-fill-mode: both;
         -webkit-animation: load7 1.8s infinite ease-in-out;
         animation: load7 1.8s infinite ease-in-out;
         }
         .loader {
         visibility:hidden;
         display:none;
         color: #0277bd;
         font-size: 10px;
         margin: 80px auto;
         position: relative;
         text-indent: -9999em;
         -webkit-transform: translateZ(0);
         -ms-transform: translateZ(0);
         transform: translateZ(0);
         -webkit-animation-delay: -0.16s;
         animation-delay: -0.16s;
         }
         .loader:before,
         .loader:after {
         content: '';
         position: absolute;
         top: 0;
         }
         .loader:before {
         left: -3.5em;
         -webkit-animation-delay: -0.32s;
         animation-delay: -0.32s;
         }
         .loader:after {
         left: 3.5em;
         }
         @-webkit-keyframes load7 {
         0%,
         80%,
         100% {
         box-shadow: 0 2.5em 0 -1.3em;
         }
         40% {
         box-shadow: 0 2.5em 0 0;
         }
         }
         @keyframes load7 {
         0%,
         80%,
         100% {
         box-shadow: 0 2.5em 0 -1.3em;
         }
         40% {
         box-shadow: 0 2.5em 0 0;
         }
         }
      </style>
      <header class="bg-dark py-5 mb-5">
         <div class="container h-100">
            <div class="row h-100 align-items-center">
               <div class="col-lg-12">
                  <h1 class="display-4 text-white mt-5 mb-2">Logical Expressions with Grover's Search</h1>
               </div>
            </div>
         </div>
      </header>
      <div class="container">
         <div class="row">
            <div class="col-md-8 mb-5">
               <h2>Pick a device, enter the expression you wish to solve for and click Generate</h2>
               <hr>
               <span>
                  <label>Pick a quantum device:</label>
                  <select name="devices" id="devices">
                     <option value="ibmq_qasm_simulator">ibmq_qasm_simulator (32 qubits)</option>
		     <option value="ibmq_manila">ibmq_manila (5 qubits)</option>
		     <option value="ibmq_bogota">ibmq_bogota (5 qubits)</option>
		     <option value="ibmq_santiago">ibmq_santiago (5 qubits)</option>
		     <option value="ibmq_quito">ibmq_quito (5 qubits)</option>
                  </select>
               </span>
               <br><br>
               <label>Enter a logical expression to solve:</label>
               <input type="text" id="expression" name="expression" value="(a & b)& ~(c)"><br>
               <div id="loader" class="loader"></div>
               <p id="keyHeader"></p>
               <strong>
                  <p id="keyView"></p>
               </strong>
               <button class="btn btn-primary"  onclick="generate();">Generate &raquo;</button>
            </div>
         </div>
      </div>
      <footer class="bg-dark py-5">
         <div class="container">
            <p class="m-0 text-center text-white">Copyright &copy; Quantum Computing UK 2022</p>
         </div>
      </footer>
   </body>
</html>

Now we just need to test the site! Go in to your terminal and cd in to the outer qsite directory (the directory with manage.py) and type in the following:

python manage.py runserver

Then go to your web browser and enter localhost:8000 and the website should appear!