main.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. from PIL import Image, ImageTk
  7. import tkSimpleDialog
  8. import urllib
  9. import urllib2
  10. import json
  11. import time
  12. JUMP = 50
  13. MAX_WIDTH = 20 * JUMP
  14. MAX_HEIGHT = 20 * JUMP
  15. address = "http://127.0.0.1:8001"
  16. taskname = "test"
  17. root = Tk()
  18. canvas = Canvas(root, width=MAX_WIDTH, height=MAX_HEIGHT, bg="white")
  19. name = 0
  20. class FakeLayer():
  21. def __init__(self, address):
  22. self.types = {}
  23. self.sources = {}
  24. self.targets = {}
  25. self.attrs = {}
  26. def read_available_attributes(self, name):
  27. if self.types[name] == "const":
  28. return ["value"]
  29. else:
  30. return []
  31. def read_attribute(self, name, attr):
  32. return self.attr.get(name, {}).get(attr, None)
  33. def set_attribute(self, name, attr, value):
  34. self.attrs[name][attr] = value
  35. def instantiate_block(self, name, block_type):
  36. self.types[name] = block_type
  37. def instantiate_link(self, name, link_type, source, target):
  38. self.types[name] = link_type
  39. self.sources[name] = source
  40. self.targets[name] = target
  41. self.attrs[name] = {}
  42. def simulate(self):
  43. pass
  44. def step(self):
  45. pass
  46. def pause(self):
  47. pass
  48. attribute = []
  49. available_attrs = []
  50. simulation = []
  51. def poll(address):
  52. working_available_attrs = []
  53. working_simulation = None
  54. while 1:
  55. returnvalue = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read())
  56. print("Process " + str(returnvalue))
  57. if (returnvalue.startswith("AVAILABLE_ATTR_VALUE")):
  58. working_available_attrs.append([json.loads(returnvalue.split(" ", 1)[1]), None])
  59. elif (returnvalue.startswith("AVAILABLE_ATTR_TYPE")):
  60. working_available_attrs[-1][1] = json.loads(returnvalue.split(" ", 1)[1])
  61. elif (returnvalue.startswith("AVAILABLE_ATTR_END")):
  62. available_attrs.append(working_available_attrs)
  63. working_available_attrs = []
  64. elif (returnvalue.startswith("ATTR_VALUE")):
  65. v = returnvalue.split(" ", 1)[1]
  66. if v == "None":
  67. v = None
  68. else:
  69. v = json.loads(v)
  70. attribute.append(v)
  71. elif (returnvalue.startswith("SIM_TIME")):
  72. working_simulation = (json.loads(returnvalue.split(" ", 1)[1]), {})
  73. elif (returnvalue.startswith("SIM_PROBE")):
  74. blockname, blockvalue = returnvalue.split(" ", 1)[1].rsplit(" ", 1)
  75. working_simulation[1][json.loads(blockname)] = json.loads(blockvalue)
  76. elif (returnvalue.startswith("SIM_END")):
  77. simulation.append(working_simulation)
  78. working_simulation = None
  79. elif (returnvalue.startswith("CONFORMANCE_OK")):
  80. root.configure(background="grey")
  81. elif (returnvalue.startswith("CONFORMANCE_FAIL")):
  82. root.configure(background="red")
  83. elif (returnvalue.startswith("ALGEBRAIC_LOOP")):
  84. root.configure(background="blue")
  85. else:
  86. print("Error: got unknown result: " + returnvalue)
  87. class MvLayer():
  88. def __init__(self, address):
  89. import threading
  90. self.address = address
  91. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % taskname, "taskname": "task_manager"}))).read()
  92. thrd = threading.Thread(target=poll, args=[address])
  93. thrd.daemon = True
  94. thrd.start()
  95. def read_available_attributes(self, name):
  96. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"read_available_attributes"', "taskname": taskname}))).read()
  97. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "taskname": taskname}))).read()
  98. while not available_attrs:
  99. time.sleep(0.1)
  100. return available_attrs.pop(0)
  101. def read_attribute(self, name, attr):
  102. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"read_attribute"', "taskname": taskname}))).read()
  103. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "taskname": taskname}))).read()
  104. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % attr, "taskname": taskname}))).read()
  105. while not attribute:
  106. time.sleep(0.1)
  107. return attribute.pop(0)
  108. def set_attribute(self, name, attr, value):
  109. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"set_attribute"', "taskname": taskname}))).read()
  110. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % name, "taskname": taskname}))).read()
  111. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % attr, "taskname": taskname}))).read()
  112. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": json.dumps(value), "taskname": taskname}))).read()
  113. def instantiate_block(self, name, block_type):
  114. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"instantiate_node"', "taskname": taskname}))).read()
  115. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (block_type), "taskname": taskname}))).read()
  116. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (name), "taskname": taskname}))).read()
  117. def instantiate_link(self, name, link_type, source, target):
  118. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"instantiate_association"', "taskname": taskname}))).read()
  119. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (link_type), "taskname": taskname}))).read()
  120. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (name), "taskname": taskname}))).read()
  121. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (source), "taskname": taskname}))).read()
  122. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (target), "taskname": taskname}))).read()
  123. def simulate(self):
  124. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"simulate"', "taskname": taskname}))).read()
  125. def step(self):
  126. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"step"', "taskname": taskname}))).read()
  127. def pause(self):
  128. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"pause"', "taskname": taskname}))).read()
  129. def delete(self, block):
  130. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"delete_element"', "taskname": taskname}))).read()
  131. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": '"%s"' % (block), "taskname": taskname}))).read()
  132. def lower(value):
  133. return value / JUMP * JUMP
  134. def upper(value):
  135. return (value / JUMP + 1) * JUMP
  136. def avg(a, b):
  137. return float(a + b) / 2
  138. class InterfaceCore():
  139. mode = ""
  140. drawn = set()
  141. refs = dict()
  142. #mv = MvLayer(address)
  143. mv = FakeLayer(address)
  144. def set_mode(self, mode):
  145. self.mode = mode
  146. def delete(self, x, y):
  147. lname = self.find((x, y))
  148. self.mv.delete(lname)
  149. for i in self.refs[lname]:
  150. canvas.delete(i)
  151. del self.refs[lname]
  152. self.drawn = set([e for e in self.drawn if e[4] != lname])
  153. def clicked(self, event):
  154. if self.find((event.x, event.y)):
  155. # Something already there, so don't add, but modify
  156. lname = self.find((event.x, event.y))
  157. attrs = self.mv.read_available_attributes(lname)
  158. print("Managing " + str(attrs))
  159. if not attrs:
  160. print("No attrs to manage!")
  161. for attr, t in attrs:
  162. print("Reading data from " + str(attr))
  163. old_value = self.mv.read_attribute(lname, attr)
  164. if old_value == "None":
  165. old_value = None
  166. new_value = tkSimpleDialog.askstring("Attribute modification", attr, initialvalue=old_value)
  167. if t == "Float":
  168. new_value = float(new_value)
  169. elif t == "String":
  170. new_value = str(new_value)
  171. else:
  172. print("Got unknown type: " + str(t))
  173. self.mv.set_attribute(lname, attr, new_value)
  174. elif self.mode not in ["AdditionBlock", "NegatorBlock", "ConstantBlock", "MultiplyBlock", "ConstantBlock", "InverseBlock", "DelayBlock", "IntegratorBlock", "DerivatorBlock", "ProbeBlock"]:
  175. print("Cannot create something not guaranteed to be block type!")
  176. else:
  177. global name
  178. x = event.x
  179. y = event.y
  180. self.mv.instantiate_block(str(name), self.mode)
  181. r = canvas.create_rectangle(lower(x), lower(y), upper(x), upper(y), fill="white")
  182. t = canvas.create_image(avg(lower(x), upper(x)), avg(lower(y), upper(y)), image=photos[self.mode])
  183. b = (lower(x), lower(y), upper(x), upper(y), str(name))
  184. self.drawn.add(b)
  185. self.refs[str(name)] = [r, t]
  186. name += 1
  187. def find(self, location):
  188. x, y = location
  189. for e in self.drawn:
  190. if (e[0] <= x and
  191. e[1] <= y and
  192. e[2] >= x and
  193. e[3] >= y):
  194. return e[4]
  195. print("Found nothing at that location!")
  196. return []
  197. def draw(self, start, end):
  198. source = self.find(start)
  199. target = self.find(end)
  200. print("Connect from %s to %s" % (source, target))
  201. if source and target:
  202. if self.mode not in ["Link", "InitialCondition"]:
  203. print("Cannot create something not guaranteed to be link type!")
  204. elif source == target:
  205. print("Cannot create link to self")
  206. else:
  207. global name
  208. self.mv.instantiate_link(str(name), self.mode, source, target)
  209. self.refs[str(name)] = [canvas.create_line(start[0], start[1], end[0], end[1], fill="black" if self.mode == "Link" else "red", arrow=LAST)]
  210. name += 1
  211. core = InterfaceCore()
  212. def clicked(event):
  213. core.clicked(event)
  214. def draw(event):
  215. global start_location
  216. start_location = (event.x, event.y)
  217. def release(event):
  218. core.draw(start_location, (event.x, event.y))
  219. def simulate():
  220. core.mv.simulate()
  221. def step():
  222. core.mv.step()
  223. def pause():
  224. core.mv.pause()
  225. def addition():
  226. core.set_mode("AdditionBlock")
  227. def negation():
  228. core.set_mode("NegatorBlock")
  229. def link():
  230. core.set_mode("Link")
  231. def multiply():
  232. core.set_mode("MultiplyBlock")
  233. def constant():
  234. core.set_mode("ConstantBlock")
  235. def inverse():
  236. core.set_mode("InverseBlock")
  237. def ic():
  238. core.set_mode("InitialCondition")
  239. def delay():
  240. core.set_mode("DelayBlock")
  241. def derivator():
  242. core.set_mode("DerivatorBlock")
  243. def integrator():
  244. core.set_mode("IntegratorBlock")
  245. def delete(event):
  246. core.delete(event.x, event.y)
  247. def probe():
  248. core.set_mode("ProbeBlock")
  249. images = {
  250. "ConstantBlock": Image.open("figures/constant.png"),
  251. "AdditionBlock": Image.open("figures/summation.png"),
  252. "NegatorBlock": Image.open("figures/negation.png"),
  253. "MultiplyBlock": Image.open("figures/multiply.png"),
  254. "InverseBlock": Image.open("figures/inverse.png"),
  255. "DerivatorBlock": Image.open("figures/derivative.png"),
  256. "IntegratorBlock": Image.open("figures/integrator.png"),
  257. "DelayBlock": Image.open("figures/delay.png"),
  258. "ProbeBlock": Image.open("figures/probe.png"),
  259. }
  260. hsize = 20
  261. for k, v in images.items():
  262. old_vsize, old_hsize = v.size
  263. vsize = int(old_vsize * hsize / float(old_hsize))
  264. images[k] = v.resize((vsize, hsize), Image.ANTIALIAS)
  265. photos = {k: ImageTk.PhotoImage(v) for k, v in images.items()}
  266. bound_functions = {
  267. "ConstantBlock": constant,
  268. "AdditionBlock": addition,
  269. "MultiplyBlock": multiply,
  270. "NegatorBlock": negation,
  271. "InverseBlock": inverse,
  272. "DerivatorBlock": derivator,
  273. "IntegratorBlock": integrator,
  274. "DelayBlock": delay,
  275. "ProbeBlock": probe,
  276. }
  277. buttons = []
  278. for k, v in bound_functions.items():
  279. buttons.append(Button(root, image=photos[k], command=v))
  280. buttons.extend([
  281. Button(root, text="Link", command=link, bg="blue"),
  282. Button(root, text="InitialCondition", command=ic, bg="blue"),
  283. Button(root, text="SIM", command=simulate, bg="green"),
  284. Button(root, text="STEP", command=step, bg="green"),
  285. Button(root, text="PAUSE", command=pause, bg="green"),
  286. ])
  287. for i, b in enumerate(buttons):
  288. b.grid(row=0, column=i)
  289. canvas.grid(row=1,column=0,columnspan=len(buttons))
  290. core.canvas = canvas
  291. for i in range(JUMP, MAX_HEIGHT, JUMP):
  292. canvas.create_line(0, i, MAX_HEIGHT, i, fill="grey")
  293. for i in range(JUMP, MAX_WIDTH, JUMP):
  294. canvas.create_line(i, 0, i, MAX_WIDTH, fill="grey")
  295. canvas.bind("<Button-1>", clicked)
  296. canvas.bind("<Button-2>", delete)
  297. canvas.bind("<Button-3>", draw)
  298. canvas.bind("<ButtonRelease-3>", release)
  299. visual = Toplevel(root)
  300. probes = {}
  301. values = {}
  302. # Example:
  303. # simulation = [(1, {"a": 1, "b": 2}), (2, {"a": 3}), (3, {"a": 4, "b": 6})]
  304. # Class from StackOverflow
  305. class VerticalScrolledFrame(Frame):
  306. """A pure Tkinter scrollable frame that actually works!
  307. * Use the 'interior' attribute to place widgets inside the scrollable frame
  308. * Construct and pack/place/grid normally
  309. * This frame only allows vertical scrolling
  310. """
  311. def __init__(self, parent, *args, **kw):
  312. Frame.__init__(self, parent, *args, **kw)
  313. # create a canvas object and a vertical scrollbar for scrolling it
  314. vscrollbar = Scrollbar(self, orient=VERTICAL)
  315. vscrollbar.pack(fill=Y, side=RIGHT, expand=FALSE)
  316. canvas = Canvas(self, bd=0, highlightthickness=0,
  317. yscrollcommand=vscrollbar.set)
  318. canvas.pack(side=LEFT, fill=BOTH, expand=TRUE)
  319. vscrollbar.config(command=canvas.yview)
  320. # reset the view
  321. canvas.xview_moveto(0)
  322. canvas.yview_moveto(0)
  323. # create a frame inside the canvas which will be scrolled with it
  324. self.interior = interior = Frame(canvas)
  325. interior_id = canvas.create_window(0, 0, window=interior,
  326. anchor=NW)
  327. # track changes to the canvas and frame width and sync them,
  328. # also updating the scrollbar
  329. def _configure_interior(event):
  330. # update the scrollbars to match the size of the inner frame
  331. size = (interior.winfo_reqwidth(), interior.winfo_reqheight())
  332. canvas.config(scrollregion="0 0 %s %s" % size)
  333. if interior.winfo_reqwidth() != canvas.winfo_width():
  334. # update the canvas's width to fit the inner frame
  335. canvas.config(width=interior.winfo_reqwidth())
  336. interior.bind('<Configure>', _configure_interior)
  337. def _configure_canvas(event):
  338. if interior.winfo_reqwidth() != canvas.winfo_width():
  339. # update the inner frame's width to fill the canvas
  340. canvas.itemconfigure(interior_id, width=canvas.winfo_width())
  341. canvas.bind('<Configure>', _configure_canvas)
  342. frame = VerticalScrolledFrame(visual)
  343. frame.pack(fill=BOTH,expand=True)
  344. def update_graphs():
  345. while simulation:
  346. t, results = simulation.pop(0)
  347. for k, v in results.items():
  348. if k in probes:
  349. fcanvas, a = probes[k]
  350. else:
  351. f = Figure()
  352. a = f.add_subplot(111)
  353. a.plot([], [])
  354. print(k)
  355. f.suptitle(k)
  356. fcanvas = FigureCanvasTkAgg(f, frame.interior)
  357. fcanvas.show()
  358. fcanvas.get_tk_widget().pack()
  359. probes[k] = (fcanvas, a)
  360. values[k] = ([], [])
  361. values[k][0].append(t)
  362. values[k][1].append(v)
  363. a.clear()
  364. a.plot(values[k][0], values[k][1], linestyle="none", marker="o")
  365. fcanvas.draw()
  366. root.after(100, update_graphs)
  367. root.after(100, update_graphs)
  368. root.mainloop()