Anders and Briegel in Python
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

49 řádky
1.6KB

  1. import time, atexit, json
  2. import networkx
  3. import numpy as np
  4. import websocket
  5. from socket import error as socket_error
  6. import graphstate
  7. import util
  8. class GraphState(graphstate.GraphState, networkx.Graph):
  9. def __init__(self, *args, **kwargs):
  10. graphstate.GraphState.__init__(self, *args, **kwargs)
  11. self.connect_to_server()
  12. def connect_to_server(self, uri = "ws://localhost:5000"):
  13. """ Attempt to connect to the websocket server """
  14. try:
  15. self.ws = websocket.create_connection(uri)
  16. atexit.register(self.shutdown)
  17. except socket_error:
  18. self.ws = None
  19. def shutdown(self):
  20. """ Close the connection to the websocket """
  21. self.update()
  22. self.ws.close()
  23. def update(self, delay = 0.5):
  24. """ Call this function when you are ready to send data to the browser """
  25. if not self.ws:
  26. return
  27. # Automatically perform layout if position is not provided
  28. if not all(("position" in node) for node in self.node.values()):
  29. self.layout()
  30. # Send data to browser and rate-limit
  31. self.ws.send(json.dumps(self.to_json()))
  32. time.sleep(delay)
  33. def layout(self, dim=3):
  34. """ Automatically lay out the graph """
  35. pos = networkx.spring_layout(self, dim, scale=np.sqrt(self.order()))
  36. middle = np.average(pos.values(), axis=0)
  37. pos = {key: value - middle for key, value in pos.items()}
  38. for key, (x, y, z) in pos.items():
  39. self.node[key]["position"] = util.xyz(x, y, z)