main.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. import matplotlib
  2. matplotlib.use("TkAgg")
  3. from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
  4. from matplotlib.figure import Figure
  5. from Tkinter import *
  6. import tkSimpleDialog
  7. import urllib
  8. import urllib2
  9. JUMP = 40
  10. MAX_WIDTH = 20 * JUMP
  11. MAX_HEIGHT = 20 * JUMP
  12. address = "http://127.0.0.1:8001"
  13. root = Tk()
  14. canvas = Canvas(root, width=MAX_WIDTH, height=MAX_HEIGHT, bg="white")
  15. canvas.pack()
  16. name = 0
  17. class FakeLayer():
  18. def __init__(self, address):
  19. self.types = {}
  20. self.sources = {}
  21. self.targets = {}
  22. self.attrs = {}
  23. def read_available_attributes(self, name):
  24. if self.types[name] == "const":
  25. return ["value"]
  26. else:
  27. return []
  28. def read_attribute(self, name, attr):
  29. return self.attr.get(name, {}).get(attr, None)
  30. def set_attribute(self, name, attr, value):
  31. self.attrs[name][attr] = value
  32. def instantiate_block(self, name, block_type):
  33. self.types[name] = block_type
  34. def instantiate_link(self, name, link_type, source, target):
  35. self.types[name] = link_type
  36. self.sources[name] = source
  37. self.targets[name] = target
  38. self.attrs[name] = {}
  39. def simulate(self):
  40. pass
  41. def step(self):
  42. pass
  43. def pause(self):
  44. pass
  45. attribute = []
  46. available_attrs = []
  47. simulation = []
  48. #simulation = [(1, {"a": 1, "b": 2}), (2, {"a": 3}), (3, {"a": 4, "b": 6})]
  49. def poll(address):
  50. working_available_attrs = []
  51. working_simulation = None
  52. while 1:
  53. returnvalue = urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "username": "CBD_env"}))).read()
  54. print("Process " + str(returnvalue))
  55. if (returnvalue.startswith("AVAILABLE_ATTR_VALUE")):
  56. working_available_attrs.append(returnvalue.split(" ", 1)[1])
  57. elif (returnvalue.startswith("AVAILABLE_ATTR_END")):
  58. available_attrs.append(working_available)
  59. working_available = []
  60. elif (returnvalue.startswith("ATTR_VALUE")):
  61. attribute.append(returnvalue.split(" ", 1)[1])
  62. elif (returnvalue.startswith("SIM_TIME")):
  63. working_simulation = (float(returnvalue.split(" ", 1)[1]), {})
  64. elif (returnvalue.startswith("SIM_PROBE")):
  65. blockname, blockvalue = returnvalue.split(" ", 1)[1].rsplit(" ", 1)
  66. working_simulation[1][blockname] = blockvalue
  67. elif (returnvalue.startswith("SIM_END")):
  68. simulation.append(working_simulation)
  69. working_simulation = None
  70. class MvLayer():
  71. def __init__(self, address):
  72. import threading
  73. self.address = address
  74. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"CBD_env"', "username": "user_manager"}))).read()
  75. threading.Thread(target=poll, args=[address])
  76. def read_available_attributes(self, name):
  77. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"read_available_attributes"', "username": "CBD_env"}))).read()
  78. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "username": "CBD_env"}))).read()
  79. while not available_attrs:
  80. time.sleep(0.1)
  81. return available_attrs.pop(0)
  82. def read_attribute(self, name, attr):
  83. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"read_attribute"', "username": "CBD_env"}))).read()
  84. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "username": "CBD_env"}))).read()
  85. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % attr, "username": "CBD_env"}))).read()
  86. while not attribute:
  87. time.sleep(0.1)
  88. return attribute.pop(0)
  89. def set_attribute(self, name, attr, value):
  90. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"set_attribute"', "username": "CBD_env"}))).read()
  91. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "username": "CBD_env"}))).read()
  92. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % attr, "username": "CBD_env"}))).read()
  93. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % value, "username": "CBD_env"}))).read()
  94. def instantiate_block(self, name, block_type):
  95. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"instantiate_node"', "username": "CBD_env"}))).read()
  96. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (block_type), "username": "CBD_env"}))).read()
  97. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (name), "username": "CBD_env"}))).read()
  98. def instantiate_link(self, name, link_type, source, target):
  99. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"instantiate_association"', "username": "CBD_env"}))).read()
  100. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (link_type), "username": "CBD_env"}))).read()
  101. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (name), "username": "CBD_env"}))).read()
  102. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (source), "username": "CBD_env"}))).read()
  103. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (target), "username": "CBD_env"}))).read()
  104. def simulate(self):
  105. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"simulate"', "username": "CBD_env"}))).read()
  106. def step(self):
  107. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"step"', "username": "CBD_env"}))).read()
  108. def pause(self):
  109. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"pause"', "username": "CBD_env"}))).read()
  110. def lower(value):
  111. return value / JUMP * JUMP
  112. def upper(value):
  113. return (value / JUMP + 1) * JUMP
  114. def avg(a, b):
  115. return float(a + b) / 2
  116. class InterfaceCore():
  117. mode = ""
  118. drawn = set()
  119. refs = dict()
  120. mappings = {"+": "AdditionBlock",
  121. "-": "NegationBlock",
  122. }
  123. #mv = MvLayer(address)
  124. mv = FakeLayer(address)
  125. def set_mode(self, mode):
  126. self.mode = mode
  127. def clicked(self, event):
  128. if self.mode not in ["+", "-"]:
  129. print("Cannot create something not guaranteed to be block type!")
  130. else:
  131. if self.find((event.x, event.y)):
  132. # Something already there, so don't add, but modify
  133. lname = self.find((event.x, event.y))
  134. attrs = self.mv.read_available_attributes(lname)
  135. if not attrs:
  136. print("No attrs to manage!")
  137. for attr in attrs:
  138. old_value = self.mv.read_attribute(lname, attr)
  139. new_value = tkSimpleDialog.askstring("Attribute modification", attr, initialvalue=old_value)
  140. self.mv.set_attribute(lname, attr, new_value)
  141. else:
  142. global name
  143. x = event.x
  144. y = event.y
  145. self.mv.instantiate_block(str(name), self.mappings[self.mode])
  146. r = canvas.create_rectangle(lower(x), lower(y), upper(x), upper(y), fill="white")
  147. t = canvas.create_text(avg(lower(x), upper(x)), avg(lower(y), upper(y)), text=self.mode, fill="black")
  148. b = (lower(x), lower(y), upper(x), upper(y), str(name))
  149. self.drawn.add(b)
  150. self.refs[str(name)] = [r, t]
  151. name += 1
  152. def find(self, location):
  153. x, y = location
  154. for e in self.drawn:
  155. if (e[0] <= x and
  156. e[1] <= y and
  157. e[2] >= x and
  158. e[3] >= y):
  159. return e[4]
  160. print("Found nothing at that location!")
  161. return []
  162. def draw(self, start, end):
  163. source = self.find(start)
  164. target = self.find(end)
  165. print("Connect from %s to %s" % (source, target))
  166. if source and target:
  167. if self.mode not in ["Link", "IC"]:
  168. print("Cannot create something not guaranteed to be link type!")
  169. else:
  170. global name
  171. self.mv.instantiate_link(str(name), self.mode, source, target)
  172. self.refs[str(name)] = [canvas.create_line(start[0], start[1], end[0], end[1], fill="black", arrow=LAST)]
  173. name += 1
  174. core = InterfaceCore()
  175. def addition():
  176. core.set_mode("+")
  177. def negation():
  178. core.set_mode("-")
  179. def link():
  180. core.set_mode("Link")
  181. def clicked(event):
  182. core.clicked(event)
  183. def draw(event):
  184. global start_location
  185. start_location = (event.x, event.y)
  186. def release(event):
  187. core.draw(start_location, (event.x, event.y))
  188. def simulate():
  189. core.mv.simulate()
  190. def step():
  191. core.mv.step()
  192. def pause():
  193. core.mv.pause()
  194. Button(root, text="+", command=addition).pack()
  195. Button(root, text="-", command=negation).pack()
  196. Button(root, text="Link", command=link).pack()
  197. Button(root, text="SIM", command=simulate).pack()
  198. Button(root, text="STEP", command=step).pack()
  199. Button(root, text="PAUSE", command=pause).pack()
  200. core.canvas = canvas
  201. for i in range(JUMP, MAX_HEIGHT, JUMP):
  202. canvas.create_line(0, i, MAX_HEIGHT, i, fill="grey")
  203. for i in range(JUMP, MAX_WIDTH, JUMP):
  204. canvas.create_line(i, 0, i, MAX_WIDTH, fill="grey")
  205. canvas.bind("<Button-1>", clicked)
  206. canvas.bind("<Button-3>", draw)
  207. canvas.bind("<ButtonRelease-3>", release)
  208. visual = Toplevel(root)
  209. probes = {}
  210. values = {}
  211. #simulation = [(1, {"a": 1, "b": 2}), (2, {"a": 3}), (3, {"a": 4, "b": 6})]
  212. def update_graphs():
  213. while simulation:
  214. t, results = simulation.pop(0)
  215. for k, v in results.items():
  216. if k in probes:
  217. fcanvas, a = probes[k]
  218. else:
  219. f = Figure(figsize=(5,5), dpi=100)
  220. a = f.add_subplot(111)
  221. a.plot([], [])
  222. fcanvas = FigureCanvasTkAgg(f, visual)
  223. fcanvas.show()
  224. fcanvas.get_tk_widget().pack()
  225. probes[k] = (fcanvas, a)
  226. values[k] = ([], [])
  227. values[k][0].append(t)
  228. values[k][1].append(v)
  229. a.clear()
  230. a.plot(values[k][0], values[k][1], linestyle="none", marker="o")
  231. fcanvas.draw()
  232. root.after(50, update_graphs)
  233. root.after(50, update_graphs)
  234. root.mainloop()