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

65 行
2.1KB

  1. import time, atexit, json
  2. import sys
  3. import networkx as nx
  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, nx.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 shutdown(self):
  22. """ Close the connection to the websocket """
  23. if not self.ws:
  24. return
  25. self.ws.close()
  26. def update(self, delay = 0.5):
  27. """ Call this function when you are ready to send data to the browser """
  28. if not self.ws:
  29. return
  30. # Automatically perform layout if position is not provided
  31. if not all(("position" in node) for node in self.node.values()):
  32. self.layout()
  33. # Send data to browser and rate-limit
  34. try:
  35. self.ws.send(json.dumps(self.to_json(stringify=True)))
  36. self.ws.recv()
  37. time.sleep(delay)
  38. except websocket._exceptions.WebSocketTimeoutException:
  39. print "Timed out ... you might be pushing a bit hard"
  40. time.sleep(delay)
  41. #self.ws.close()
  42. #self.connect_to_server()
  43. def layout(self):
  44. """ Automatically lay out the graph """
  45. pos = nx.spring_layout(self, dim=3, scale=np.sqrt(self.order()))
  46. middle = np.average(pos.values(), axis=0)
  47. pos = {key: value - middle for key, value in pos.items()}
  48. for key, (x, y, z) in pos.items():
  49. self.node[key]["position"] = util.xyz(x, y, z)
  50. def add_vops(self):
  51. """ Automatically add vops if they're not present """
  52. for key in self.node:
  53. if not "vop" in self.node[key]:
  54. self.node[key]["vop"] = clifford.identity