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

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