Anders and Briegel in Python
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

66 行
2.1KB

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