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

79 行
2.6KB

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