Loading...

Postulate is the best way to take and share notes for classes, research, and other learning.

More info

Using Python in a React webapp

Profile picture of Laura GaoLaura Gao
May 15, 2021Last updated May 15, 20216 min read

The problem with a lot of machine learning, quantum computing, or other algorithm development projects that are commonplace amongst TKS students is that the code just sits around in a GitHub repository till the end of eternity. For example, 2 months ago, I spent ~20 hours building a quantum approximate optimization algorithm that solves the maxcut problem. Given a graph, the algorithm would determine which line cuts through the most of the edges. Pretty neat, right?




After a few hours of headaches, the code worked and got picked as a QOSF model submission. However, it sucks that only people with an understanding of quantum computing code can appreciate it. I mean, just look at this code 🤮. Who wants to dig through it to test it out? One has to download the notebook and manually install all the Python packages to adjust the inputs in order to verify the algorithm works.



I first heard this problem talked about by Evan. And so, after he made a natural language processing algorithm that classifies the sentiment of a sentence, he didn't just leave the code lying around. Instead, he made it into an interactive webapp, where users can input sentences of their choice and the webapp will tell them whether it's a positive or negative sentiment. Anyone, technical background or not, can test out the algorithm without reading a single line of code, and instead, with a clean easy to use UI.



How cool would it be to build a similar webapp that runs my quantum computing algorithm on the backend? Think about all the ways you could market it - "the first of its kind that allows anyone to run a quantum machine learning algorithm"...

In order to build this, one has to somehow be able to send the user input to Python, run the Python, and then render the result in browser. This blog post answers how that is done.

Step 1: Set up a Python server

Make a new empty folder and name it the name of your project. In the terminal, set up virtual environment by running the following commands:

pip3 install virtual env -> set up virtual environment in the folder you are in

virtualenv env -> creates env folder, which houses all files associated with the virtual environment

env\Scripts\activate on Windows or source env/bin/activate on Mac/Linux -> to activate the virtual environment. You know it is activated when the command line changes to have (env) at the beginning.



We use virtual environments so that you can transfer the project around, and the requirements stay localized within the project folder instead of being installed globally somewhere else on your computer. All the Python modules used have to be installed within the virtual environment. For example, I use the Pennylane library for QML. So I install it in the virtual environment.



Create an app.py file, which is where we'll write all our python code. To set up a Python server, we use flask. Here's the boiler plate flask setup:

from flask import Flask, jsonify, request



app = Flask(__name__) # __name__ references this file



@app.route('/')

def index():

return jsonify({"Message": "This is a python server"})



if __name__ == "__main__":

app.run(debug=True)

To run the file, use python app.py which will host our python server on localhost:5000 by default. When you visit the localhost:5000 URL, you will see something like this:



To do something useful: in flask, you can add routes. Each route is additional URL where you can return something. For example, if I added the following to my code:

@app.route('/hello')

def say_hello():

return jsonify({"Message": "Hello world"})

Then when i visit localhost:5000/hello , I'll see "Hello world" printed on screen.

This is esp useful because later, when we make API calls to this server, you'll get the json string that is returned by the route.

Now, onto doing something useful. How do I put my quantum algorithm code? Create a new route. (named qaoa for quantum approximate optimization algorithm)

@app.route('/qaoa', methods=['POST'])

def calculate_maxcut():



#...All 150 lines of my algorithm...



res = f'The answer to our weighted maxcut is: {final_bitstring[2]} or {binary_bit_string}'

return jsonify({"maxcut": res})

At the top of the file, make all imports like a usual Python file.

import pennylane as qml

from pennylane import numpy as np

import networkx as nx

from scipy.optimize import minimize



np.random.seed(42)

The server is set up :)

Step 2: API request

I'm building the frontend of this webapp in React. Axios is used to fetch the data, which can be easily installed with npm install axios and imported with import axios from 'axios'; in the React file.

On the click of the submit button, we send the user input's value over to the Python server. The server does its calculations by running the algorithm, and sends back a response in a json string. To access the maxcut value, we use response.data.maxcut .

const handleClick = async () => {

axios.post("http://localhost:5000/qaoa" {"edges": value})

.then((response) => {

console.log(response);

setRes(response.data.maxcut)

})

.catch((err) => {

console.log(err);

setRes("Error");

});

}

<button onClick={handleClick}>Calculate maxcut</button>

This is how to update the user input value:

const [value, setValue] = useState("");



const handleValueChange = (e) => {

setValue(e.target.value);

console.log(value)

}



<input type="text" onChange={handleValueChange}></input>

Errors

One possible source of error is if you didn't add methods=['POST'] to the route, like this:

@app.route('/qaoa', methods=['POST'])

Because we're sending over a user input, fetching the data is a "post" request.

If you're testing out your API on localhost before hosting, you need to install the CORS Chrome extension, or else you can't fetch data from localhost. In the options page, make sure to allow for the post method as well as access to control-allow-headers.



Now I can send the user input, run the algorithm, and display the algorithm's output, which achieves the goal! (with a very wip UI)






Comments (loading...)

Sign in to comment

Dev/CS

Builders gonna build baby