Bläddra i källkod

Improve server

master
Pete Shadbolt 8 år sedan
förälder
incheckning
b24debbd14
8 ändrade filer med 73 tillägg och 35 borttagningar
  1. +11
    -2
      abp/client.py
  2. +1
    -0
      abp/graphstate.py
  3. +0
    -3
      examples/client.py
  4. +32
    -27
      server/server.py
  5. +10
    -1
      server/static/main.js
  6. +1
    -1
      server/static/poll.js
  7. +1
    -1
      tests/test_against_circuit_model.py
  8. +17
    -0
      tests/test_client.py

+ 11
- 2
abp/client.py Visa fil

@@ -1,6 +1,10 @@
import requests import requests
import abp, json import abp, json


class ClientError(Exception):
def __init__(self, message):
self.message = message

class Client(object): class Client(object):
def __init__(self, host="localhost", port=5000, clear=False): def __init__(self, host="localhost", port=5000, clear=False):
self.session = requests.Session() self.session = requests.Session()
@@ -11,7 +15,9 @@ class Client(object):
def get(self, endpoint): def get(self, endpoint):
url =self.root+endpoint url =self.root+endpoint
response = self.session.get(url) response = self.session.get(url)
assert response.status_code == 200
if response.status_code == 404:
message = "404. Check that the server is running!".format(self.root, endpoint)
raise ClientError(message)
return response.content return response.content


def get_state(self): def get_state(self):
@@ -21,7 +27,10 @@ class Client(object):
return output return output


def set_state(self, state): def set_state(self, state):
return self.session.post(self.root+"/state", data=state.to_json())
response = self.session.post(self.root+"/state", data=state.to_json())
if not response.status_code == 200:
print response.status_code
return response.content


def add_node(self, node): def add_node(self, node):
return self.get("/add_node/{}".format(node)) return self.get("/add_node/{}".format(node))


+ 1
- 0
abp/graphstate.py Visa fil

@@ -6,6 +6,7 @@ import itertools as it
import clifford import clifford
import json import json
import qi import qi
import shelve
try: try:
import networkx as nx import networkx as nx
except ImportError: except ImportError:


+ 0
- 3
examples/client.py Visa fil

@@ -5,17 +5,14 @@ import time
client = abp.Client(clear=True) client = abp.Client(clear=True)


client.add_node(0) client.add_node(0)
time.sleep(2)
client.add_node(1) client.add_node(1)
client.add_node(99) client.add_node(99)
time.sleep(2)
client.act_local_rotation(0, 10) client.act_local_rotation(0, 10)
client.act_local_rotation(1, 10) client.act_local_rotation(1, 10)
client.act_local_rotation(99, 10) client.act_local_rotation(99, 10)
client.act_cz(0, 1) client.act_cz(0, 1)
client.act_cz(0, 99) client.act_cz(0, 99)
client.act_cz(1, 99) client.act_cz(1, 99)
time.sleep(2)
for i in range(10): for i in range(10):
client.add_node(i+10) client.add_node(i+10)
client.act_local_rotation(i+10, 10) client.act_local_rotation(i+10, 10)


+ 32
- 27
server/server.py Visa fil

@@ -1,7 +1,8 @@
from flask import Flask, request, render_template, jsonify
from flask import Flask, request, render_template, jsonify, g
from werkzeug.contrib.cache import SimpleCache from werkzeug.contrib.cache import SimpleCache
import json import json
import abp import abp
import argparse


#TODO: only send deltas #TODO: only send deltas


@@ -10,6 +11,15 @@ cache = SimpleCache(default_timeout = 10000)
cache.set("state", abp.GraphState()) cache.set("state", abp.GraphState())
app = Flask(__name__) app = Flask(__name__)


@app.before_request
def before_request():
g.state = cache.get("state")

@app.after_request
def after_request(response):
cache.set("state", g.state)
return response

@app.route("/") @app.route("/")
def index(): def index():
return render_template("index.html") return render_template("index.html")
@@ -17,59 +27,54 @@ def index():
@app.route("/state", methods = ["GET", "POST"]) @app.route("/state", methods = ["GET", "POST"])
def state(): def state():
if request.method == "GET": if request.method == "GET":
state = cache.get("state")
output = state.to_json()
output["update_required"] = cache.get("update")
cache.set("update", False)
output = g.state.to_json()
output["needs_update"] = cache.get("needs_update")
cache.set("needs_update", False)
return jsonify(output) return jsonify(output)
elif request.method == "POST": elif request.method == "POST":
cache.set("update", True)
graphstate = abp.GraphState()
graphstate.from_json(json.loads(request.data))
cache.set("state", graphstate)
g.state = abp.GraphState()
g.state.from_json(json.loads(request.data))
cache.set("needs_update", True)
return jsonify({"update": "ok"}) return jsonify({"update": "ok"})


@app.route("/add_node/<int:node>") @app.route("/add_node/<int:node>")
def add_node(node): def add_node(node):
""" Add a node to the graph """ """ Add a node to the graph """
graphstate = cache.get("state")
graphstate.add_node(node)
graphstate.layout()
cache.set("update", True)
cache.set("state", graphstate)
g.state.add_node(node)
g.state.layout()
cache.set("needs_update", True)
return jsonify({"add_node": "okay"}) return jsonify({"add_node": "okay"})


@app.route("/act_local_rotation/<int:node>/<int:operation>") @app.route("/act_local_rotation/<int:node>/<int:operation>")
def act_local_rotation(node, operation): def act_local_rotation(node, operation):
""" Add a node to the graph """ """ Add a node to the graph """
# TODO: try to lookup the operation first # TODO: try to lookup the operation first
graphstate = cache.get("state")
graphstate.act_local_rotation(node, operation)
cache.set("update", True)
cache.set("state", graphstate)
g.state.act_local_rotation(node, operation)
cache.set("needs_update", True)
return jsonify({"act_local_rotation": "okay"}) return jsonify({"act_local_rotation": "okay"})


@app.route("/act_cz/<int:a>/<int:b>") @app.route("/act_cz/<int:a>/<int:b>")
def act_cz(a, b): def act_cz(a, b):
""" Add a node to the graph """ """ Add a node to the graph """
graphstate = cache.get("state")
graphstate.act_cz(a, b)
graphstate.layout()
cache.set("update", True)
cache.set("state", graphstate)
g.state.act_cz(a, b)
g.state.layout()
cache.set("needs_update", True)
return jsonify({"act_cz": "okay"}) return jsonify({"act_cz": "okay"})


@app.route("/clear") @app.route("/clear")
def clear(): def clear():
""" Clear the current state """ """ Clear the current state """
graphstate = abp.GraphState()
cache.set("update", True)
cache.set("state", graphstate)
g.state = abp.GraphState()
cache.set("needs_update", True)
return jsonify({"clear": "okay"}) return jsonify({"clear": "okay"})


if __name__ == "__main__": if __name__ == "__main__":
app.debug = True
parser = argparse.ArgumentParser()
parser.add_argument("-d", "--debug", help="Run in debug mode", action="store_true", default=False)
args = parser.parse_args()
app.debug = args.debug

app.run(host="0.0.0.0") app.run(host="0.0.0.0")





+ 10
- 1
server/static/main.js Visa fil

@@ -49,6 +49,14 @@ function startMainLoop() {
loopForever(); loopForever();
} }


// Someone resized the window
function onWindowResize(evt){
camera.aspect = window.innerWidth / window.innerHeight;
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, window.innerHeight);
render();
}



// Called on startup // Called on startup
function init() { function init() {
@@ -61,6 +69,7 @@ function init() {
renderer.setSize(width, height); renderer.setSize(width, height);
renderer.setClearColor(0xffffff, 1); renderer.setClearColor(0xffffff, 1);
document.querySelector("body").appendChild(renderer.domElement); document.querySelector("body").appendChild(renderer.domElement);
window.addEventListener("resize", onWindowResize, false);


// Time to load the materials // Time to load the materials
loadMaterials(); loadMaterials();
@@ -75,7 +84,7 @@ function init() {
camera.position.set(0, 0, 20); camera.position.set(0, 0, 20);


// Start polling // Start polling
setInterval(poll, 500);
setInterval(poll, 1000);


// Run // Run
startMainLoop(); startMainLoop();


+ 1
- 1
server/static/poll.js Visa fil

@@ -17,7 +17,7 @@ function poll() {
} }


function updateScene(state) { function updateScene(state) {
//if (state.update_required === false){return;}
if (state.needs_update === false){return;}
var oldState = scene.getObjectByName("graphstate"); var oldState = scene.getObjectByName("graphstate");
scene.remove(oldState); scene.remove(oldState);
oldState = null; oldState = null;


+ 1
- 1
tests/test_against_circuit_model.py Visa fil

@@ -5,7 +5,7 @@ import numpy as np
import random import random
from tqdm import tqdm from tqdm import tqdm


REPEATS = 100
REPEATS = 1


def test_single_qubit(n=1): def test_single_qubit(n=1):
""" A multi qubit test with Hadamards only""" """ A multi qubit test with Hadamards only"""


+ 17
- 0
tests/test_client.py Visa fil

@@ -0,0 +1,17 @@
import requests
import abp, json
import time


def _test_client():
client = abp.Client(clear=True)

client.clear()
for i in range(100):
client.add_node(i)
client.act_local_rotation(i, 10)
for i in range(100-1):
client.act_cz(i, i+1)

print client.get_state()


Laddar…
Avbryt
Spara