Procházet zdrojové kódy

Add from_json, a buncha server/client stuff

master
Pete Shadbolt před 8 roky
rodič
revize
58ced9272d
7 změnil soubory, kde provedl 71 přidání a 67 odebrání
  1. +19
    -17
      abp/clifford.py
  2. +12
    -1
      abp/graphstate.py
  3. +8
    -0
      examples/client.py
  4. +20
    -41
      server/server.py
  5. +8
    -7
      server/templates/index.html
  6. +0
    -0
      setup.py
  7. +4
    -1
      tests/test_json.py

+ 19
- 17
abp/clifford.py Zobrazit soubor

@@ -9,7 +9,7 @@ from functools import reduce
import itertools as it
import numpy as np
from tqdm import tqdm
import argparse
#import argparse

import qi

@@ -122,27 +122,28 @@ def get_cz_table(unitaries):

# First try to load tables from cache. If that fails, build them from
# scratch and store in /tmp/
os.chdir(tempfile.gettempdir())
tempdir = tempfile.gettempdir()
temp = lambda filename: os.path.join(tempdir, filename)
try:
if __name__ == "__main__":
raise IOError

# Parse command line args
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--legacy", help="Use legacy CZ table", action="store_true", default=False)
args = parser.parse_args()
legacy_cz = args.legacy
unitaries = np.load("unitaries.npy")
conjugation_table = np.load("conjugation_table.npy")
times_table = np.load("times_table.npy")
#parser = argparse.ArgumentParser()
#parser.add_argument("-l", "--legacy", help="Use legacy CZ table", action="store_true", default=False)
#args = parser.parse_args()
legacy_cz = False
unitaries = np.load(temp("unitaries.npy"))
conjugation_table = np.load(temp("conjugation_table.npy"))
times_table = np.load(temp("times_table.npy"))
if legacy_cz:
import anders_cz
cz_table = anders_cz.cz_table
else:
cz_table = np.load("cz_table.npy")
cz_table = np.load(temp("cz_table.npy"))

with open("by_name.json") as f:
with open(temp("by_name.json")) as f:
by_name = json.load(f)


@@ -156,10 +157,11 @@ except IOError:
cz_table = get_cz_table(unitaries)

# Write it all to disk
np.save("unitaries.npy", unitaries)
np.save("conjugation_table.npy", conjugation_table)
np.save("times_table.npy", times_table)
np.save("cz_table.npy", cz_table)
np.save(temp("unitaries.npy"), unitaries)
np.save(temp("conjugation_table.npy"), conjugation_table)
np.save(temp("times_table.npy"), times_table)
np.save(temp("cz_table.npy"), cz_table)

with open("by_name.json", "wb") as f:
with open(temp("by_name.json"), "wb") as f:
json.dump(by_name, f)


+ 12
- 1
abp/graphstate.py Zobrazit soubor

@@ -159,7 +159,15 @@ class GraphState(object):
""" Convert the graph to JSON form """
meta = {key: value for key, value in self.meta.items()}
edge = self.edgelist()
return json.dumps({"nodes": self.vops, "edges": edge, "meta": meta})
return {"nodes": self.vops, "edges": edge, "meta": meta}

def from_json(self, data):
""" Reconstruct from JSON """
self.__init__([])
self.vops = data["nodes"]
self.meta = data["meta"]
self.ngbh = {key: set() for key in self.vops}
self.add_edges(data["edges"])

def to_networkx(self):
""" Convert the graph to a networkx graph """
@@ -222,3 +230,6 @@ class GraphState(object):
rows.append(s)
return " \n".join(rows) + " \n"

def __eq__(self, other):
""" Check equality between graphs """
return self.ngbh == other.ngbh and self.vops == other.vops

+ 8
- 0
examples/client.py Zobrazit soubor

@@ -0,0 +1,8 @@
import requests
import abp, json

s = requests.Session()
output = json.loads(s.get("http://localhost:5000/state").content)
print output
state = json.loads(s.post("http://localhost:5000/state").content)


+ 20
- 41
server/server.py Zobrazit soubor

@@ -1,48 +1,27 @@
import urlparse
from BaseHTTPServer import BaseHTTPRequestHandler
from SimpleHTTPServer import SimpleHTTPRequestHandler
import SocketServer
import sys, json, time, os
from graphstate import GraphState
import requests
from flask import Flask, request, render_template, jsonify
import abp

graphstate = abp.GraphState()
app = Flask(__name__)

class VizHandler(SimpleHTTPRequestHandler):
@app.route("/")
def index():
return render_template("index.html")

""" Handles requests to the server """
@app.route("/state")
def state():
if request.method == "GET":
return jsonify(graphstate.to_json())
elif request.method == "POST":
graphstate.from_json(request.data)
return jsonify(graphstate.to_json())

def get_state(self):
""" Get the current graphstate state """
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(state.to_json())
@app.route("/state")
def state():
return jsonify(graphstate.to_json())

def do_GET(self, *args, **kwargs):
""" Someone belled the server """
parsed_path = urlparse.urlparse(self.path)
if parsed_path.path == "/state":
return self.get_state()
else:
return SimpleHTTPRequestHandler.do_GET(self, *args, **kwargs)
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0")


class Server(SocketServer.TCPServer):

""" Serves the good stuff """
allow_reuse_address = True

def __init__(self, port=8000):
self.port = port
self.state = None
SocketServer.TCPServer.__init__(self, ("127.0.0.1", self.port), VizHandler)
print "Serving on port {} (Press CTRL-C to quit)".format(self.port)
self.serve_forever()


if __name__ == '__main__':
os.chdir(os.path.join(sys.path[0], "../static"))
server = Server()
server.shutdown()

requests.get("http://localhost:8000/state")

server/static/index.html → server/templates/index.html Zobrazit soubor

@@ -9,16 +9,17 @@
</head>

<body>
<script type="text/javascript" src="three.js"></script>
<script type="text/javascript" src="libs.js"></script>
<script type="text/javascript" src="materials.js"></script>
<script type="text/javascript" src="poll.js"></script>
<script type="text/javascript" src="grid.js"></script>
<script type="text/javascript" src="curve.js"></script>
<script type="text/javascript" src="main.js"></script>
<script type="text/javascript" src="/static/three.js"></script>
<script type="text/javascript" src="/static/libs.js"></script>
<script type="text/javascript" src="/static/materials.js"></script>
<script type="text/javascript" src="/static/poll.js"></script>
<script type="text/javascript" src="/static/grid.js"></script>
<script type="text/javascript" src="/static/curve.js"></script>
<script type="text/javascript" src="/static/main.js"></script>
<img id="ball" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAYAAACqaXHeAAAABmJLR0QAAAAAAAD5Q7t/AAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH4AMSEwYRRarOuwAAABl0RVh0Q29tbWVudABDcmVhdGVkIHdpdGggR0lNUFeBDhcAAA2ySURBVHja5VtriCRHHf9VVT+q59E7Ozt7t3tmk7C53KkxUcQv+eIDRfEVRAyoBFGToIh+UVQEURAFQY0YEAkGJEIEISoqvgJCDFGJRiUxusZLPM+93N7uze7tvLqne6qr/ZCptqauenb2di8IaWh63l3/3//3f9eQP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ECIIAvu+Dc158Rl3NjeFXZnIJoAEgBLAEIL7xRoRhCMaYGsEXm7P1Q+3xU9coilB/7DH8B8BFAF1KAUrhum6xhd7zPHieNyG02kushFbv6xut1DbbKwaADQwKoKJdTfsbAJAA+pqP2R2/VkxyxtpTW+eUkGpzpWKEP2aIDpS+3U6165+f/w6Pz8PaKWI2RBST9H3C+p8rfN+HEGKC+sph/hckywMtfS8qcQAAAABJRU5ErkJggg=="/
style=display:none;>

<div id=test>Hello World</div>
<div id=infoholder class=hidden>
</div>
</body>

+ 0
- 0
setup.py Zobrazit soubor


+ 4
- 1
tests/test_json.py Zobrazit soubor

@@ -10,6 +10,9 @@ def test_json_basic():
js = g.to_json()
assert "edges" in js
assert "nodes" in js
json.loads(js)
e = GraphState()
assert e != g
e.from_json(js)
assert e == g



Načítá se…
Zrušit
Uložit