Anders and Briegel in Python
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

75 行
2.4KB

  1. import time, atexit, json
  2. import sys
  3. import networkx
  4. import numpy as np
  5. import websocket
  6. from socket import error as socket_error
  7. import graphstate
  8. import clifford
  9. import util
  10. class GraphState(graphstate.GraphState, networkx.Graph):
  11. def __init__(self, *args, **kwargs):
  12. graphstate.GraphState.__init__(self, *args, **kwargs)
  13. self.connect_to_server()
  14. def connect_to_server(self, uri = "ws://localhost:5000"):
  15. """ Attempt to connect to the websocket server """
  16. try:
  17. self.ws = websocket.create_connection(uri, timeout=0.1)
  18. atexit.register(self.shutdown)
  19. except: #TODO: bad practice
  20. self.ws = None
  21. def from_nx(self, g):
  22. """ Clone from a networkx graph. Hacky af """
  23. self.adj = g.adj.copy()
  24. self.node = g.node.copy()
  25. # TODO: hacky af
  26. for key, value in self.node.items():
  27. self.node[key]["vop"] = clifford.by_name["identity"]
  28. def shutdown(self):
  29. """ Close the connection to the websocket """
  30. if not self.ws:
  31. return
  32. self.update()
  33. self.ws.close()
  34. def update(self, delay = 0.5):
  35. """ Call this function when you are ready to send data to the browser """
  36. if not self.ws:
  37. return
  38. # Automatically perform layout if position is not provided
  39. if not all(("position" in node) for node in self.node.values()):
  40. self.layout()
  41. # Send data to browser and rate-limit
  42. try:
  43. self.ws.send(json.dumps(self.to_json(stringify=True)))
  44. self.ws.recv()
  45. time.sleep(delay)
  46. except websocket._exceptions.WebSocketTimeoutException:
  47. print "Timed out ... you might be pushing a bit hard"
  48. sys.exit(0)
  49. #self.ws.close()
  50. #self.connect_to_server()
  51. def layout(self):
  52. """ Automatically lay out the graph """
  53. pos = networkx.spring_layout(self, dim=3, scale=np.sqrt(self.order()))
  54. middle = np.average(pos.values(), axis=0)
  55. pos = {key: value - middle for key, value in pos.items()}
  56. for key, (x, y, z) in pos.items():
  57. self.node[key]["position"] = util.xyz(x, y, z)
  58. def add_vops(self):
  59. """ Automatically add vops if they're not present """
  60. for key in self.node:
  61. if not "vop" in self.node[key]:
  62. self.node[key]["vop"] = clifford.by_name["identity"]