modelverse.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894
  1. import urllib
  2. import urllib2
  3. import json
  4. import random
  5. from urllib2 import URLError
  6. import sys
  7. import time
  8. COMPILER_PATH = "interface/HUTN"
  9. MODE_UNCONNECTED = 0
  10. MODE_UNAUTHORIZED = 1
  11. MODE_MODELLING = 2
  12. MODE_MODIFY = 3
  13. MODE_DIALOG = 4
  14. MODE_MANUAL = 5
  15. # Bind to the compiler (might have to update path manually!)
  16. sys.path.append(COMPILER_PATH)
  17. from hutn_compiler.compiler import main as do_compile
  18. # Exceptions
  19. class ModelverseException(Exception):
  20. pass
  21. class UnknownError(ModelverseException):
  22. pass
  23. class UnknownIdentifier(ModelverseException):
  24. pass
  25. class UnknownType(ModelverseException):
  26. pass
  27. class NotAnAssociation(ModelverseException):
  28. pass
  29. class UnsupportedValue(ModelverseException):
  30. pass
  31. class CompilationError(ModelverseException):
  32. pass
  33. class NoSuchAttribute(ModelverseException):
  34. pass
  35. class UnknownModel(ModelverseException):
  36. pass
  37. class ConnectionError(ModelverseException):
  38. pass
  39. class ModelExists(ModelverseException):
  40. pass
  41. class PermissionDenied(ModelverseException):
  42. pass
  43. class InvalidMode(ModelverseException):
  44. pass
  45. class InterfaceMismatch(ModelverseException):
  46. pass
  47. # Helper functions and configuration: do not use yourself!
  48. taskname = None
  49. address = None
  50. last_output = None
  51. mode = MODE_UNCONNECTED
  52. prev_mode = None
  53. current_model = None
  54. def _dict_to_list(python_dict):
  55. lst = []
  56. for k, v in python_dict.items():
  57. lst += [k, v]
  58. return lst
  59. def _goto_mode(new_mode, model_name=None):
  60. global mode
  61. if mode == MODE_MANUAL and new_mode == MODE_MODIFY:
  62. if model_name != None and current_model != model_name:
  63. raise InvalidMode("Mode error: cannot modify other models!")
  64. else:
  65. return
  66. elif mode == MODE_MODELLING and new_mode == MODE_MODIFY:
  67. # Are in root view, but want to modify a model
  68. model_modify(model_name)
  69. elif mode == MODE_MODIFY and new_mode == MODE_MODIFY and model_name != None and current_model != model_name:
  70. # Are in modify mode, but want to modify a different model
  71. model_exit()
  72. model_modify(model_name)
  73. elif mode == MODE_MODIFY and new_mode == MODE_MODELLING:
  74. model_exit()
  75. elif mode == new_mode:
  76. return
  77. else:
  78. # Go to a mode that we have no automatic transfer to: raise exception
  79. raise InvalidMode("Required mode: %s, current mode: %s" % (new_mode, mode))
  80. def _input(value):
  81. # Ugly json encoding of primitives
  82. #print("[IN] %s" % value)
  83. if isinstance(value, type([])):
  84. value = json.dumps(value)
  85. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "data": value, "taskname": taskname}))).read()
  86. else:
  87. value = json.dumps(value)
  88. #print("Set input: " + str(value))
  89. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  90. def _input_raw(value, taskname):
  91. # Ugly json encoding of primitives
  92. urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "set_input", "value": value, "taskname": taskname}))).read()
  93. def _compile_AL(code):
  94. # Compile an action language file and send the compiled code
  95. code_fragments = code.split("\n")
  96. code_fragments = [i for i in code_fragments if i.strip() != ""]
  97. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  98. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  99. code_fragments = [i[initial_tabs:] for i in code_fragments]
  100. code_fragments.append("")
  101. code = "\n".join(code_fragments)
  102. with open("__constraint.alc", "w") as f:
  103. f.write(code)
  104. f.flush()
  105. return do_compile("__constraint.alc", COMPILER_PATH + "/grammars/actionlanguage.g", "CS")
  106. def _compile_model(code):
  107. # Compile a model and send the compiled graph
  108. # First change multiple spaces to a tab
  109. code_fragments = code.split("\n")
  110. code_fragments = [i for i in code_fragments if i.strip() != ""]
  111. code_fragments = [i.replace(" ", "\t") for i in code_fragments]
  112. initial_tabs = min([len(i) - len(i.lstrip("\t")) for i in code_fragments])
  113. code_fragments = [i[initial_tabs:] for i in code_fragments]
  114. code_fragments.append("")
  115. code = "\n".join(code_fragments)
  116. with open("__model.mvc", "w") as f:
  117. f.write(code)
  118. f.flush()
  119. return do_compile("__model.mvc", COMPILER_PATH + "/grammars/modelling.g", "M") + ["exit"]
  120. def _output(expected=None):
  121. try:
  122. global last_output
  123. last_output = json.loads(urllib2.urlopen(urllib2.Request(address, urllib.urlencode({"op": "get_output", "taskname": taskname}))).read())
  124. #print("[OUT] %s" % last_output)
  125. except:
  126. raise UnknownError()
  127. if expected is not None and last_output != expected:
  128. raise InterfaceMismatch(_last_output(), expected)
  129. return last_output
  130. def _last_output():
  131. return last_output
  132. # Raise common exceptions
  133. def _handle_output(requested=None, split=None):
  134. value = _output()
  135. if value.startswith("Model exists: "):
  136. raise ModelExists(value.split(": ", 1)[1])
  137. elif value.startswith("Permission denied"):
  138. raise PermissionDenied(value.split(": ", 1)[1])
  139. elif value.startswith("Model not found: "):
  140. raise UnknownModel(value.split(": ", 1)[1])
  141. elif value.startswith("Element not found: "):
  142. raise UnknownIdentifier(value.split(": ", 1)[1])
  143. elif value.startswith("Element exists: "):
  144. raise ElementExists(value.split(": ", 1)[1])
  145. elif value.startswith("Attribute not found: "):
  146. raise NoSuchAttribute(value.split(": ", 1)[1])
  147. elif requested is not None and value.startswith(requested):
  148. if split is None:
  149. return value
  150. else:
  151. splitted = value.strip().split(split, 1)
  152. if len(splitted) == 1:
  153. return ""
  154. else:
  155. return splitted[1].rstrip()
  156. else:
  157. raise InterfaceMismatch(value)
  158. # Main MvC operations
  159. def init(address_param="http://127.0.0.1:8001", timeout=20.0):
  160. """Starts up the connection to the Modelverse."""
  161. # return None
  162. # raises ConnectionError
  163. # raises UnknownError
  164. # raises InvalidMode
  165. global mode
  166. global address
  167. global taskname
  168. address = address_param
  169. start_time = time.time()
  170. taskname = random.random()
  171. while 1:
  172. try:
  173. _input_raw('"%s"' % taskname, "task_manager")
  174. mode = MODE_UNAUTHORIZED
  175. break
  176. except URLError as e:
  177. if time.time() - start_time > timeout:
  178. raise ConnectionError(e.reason)
  179. else:
  180. time.sleep(0.1)
  181. def login(username, password):
  182. """Log in a user, if user doesn't exist, it is created."""
  183. # return None
  184. # raises UnknownError
  185. # raises PermissionDenied
  186. # raises InterfaceMismatch
  187. global mode
  188. _goto_mode(MODE_UNAUTHORIZED)
  189. _output("Log on as which user?")
  190. _input(username)
  191. if _output() == "Password for existing user?":
  192. _input(password)
  193. if _output() == "Welcome to the Model Management Interface v2.0!":
  194. _output("Use the 'help' command for a list of possible commands")
  195. _input("quiet")
  196. mode = MODE_MODELLING
  197. elif _last_output() == "Wrong password!":
  198. raise PermissionDenied()
  199. else:
  200. raise InterfaceMismatch(_last_output())
  201. elif _last_output() == "This is a new user: please give password!":
  202. _input(password)
  203. _output("Please repeat the password")
  204. _input(password)
  205. if _output() == "Passwords match!":
  206. _output("Welcome to the Model Management Interface v2.0!")
  207. _output("Use the 'help' command for a list of possible commands")
  208. _input("quiet")
  209. mode = MODE_MODELLING
  210. elif _last_output() == "Not the same password!":
  211. # We just sent the same password, so it should be identical, unless the interface changed
  212. raise InterfaceMismatch(_last_output())
  213. else:
  214. raise InterfaceMismatch(_last_output())
  215. else:
  216. raise InterfaceMismatch(_last_output())
  217. def model_add(model_name, metamodel_name, model_code=None):
  218. """Instantiate a new model."""
  219. # return None
  220. # raises UnknownModel
  221. # raises ModelExists
  222. # raises UnknownError
  223. # raises PermissionDenied
  224. # raises CompilationError
  225. _goto_mode(MODE_MODELLING)
  226. # Do this before creating the model, as otherwise compilation errors would make us inconsistent
  227. if model_code is not None:
  228. try:
  229. compiled = _compile_model(model_code)
  230. except Exception as e:
  231. raise CompilationError(e)
  232. else:
  233. compiled = ["exit"]
  234. _input(["model_add", metamodel_name, model_name])
  235. _handle_output("Waiting for model constructors...")
  236. _input(compiled)
  237. _output("Success")
  238. def upload_code(code):
  239. try:
  240. compiled = _compile_AL(code)
  241. except Exception as e:
  242. raise CompilationError(e)
  243. _input(compiled)
  244. def model_delete(model_name):
  245. """Delete an existing model."""
  246. _goto_mode(MODE_MODELLING)
  247. _input(["model_delete", model_name])
  248. _handle_output("Success")
  249. def model_modify(model_name):
  250. """Modify an existing model."""
  251. # raises UnknownModel
  252. # raises PermissionDenied
  253. # raises UnknownError
  254. global mode
  255. global prev_mode
  256. if mode == MODE_MANUAL:
  257. prev_mode = MODE_MANUAL
  258. mode = MODE_MODIFY
  259. return None
  260. _goto_mode(MODE_MODELLING)
  261. prev_mode = MODE_MODELLING
  262. _input(["model_modify", model_name])
  263. _handle_output("Success")
  264. global current_model
  265. current_model = model_name
  266. # Mode has changed
  267. mode = MODE_MODIFY
  268. _output("Model loaded, ready for commands!")
  269. def model_list():
  270. """List all models."""
  271. # return [(model1, metamodel1), (model2, metamodel2), ...]
  272. # raises UnknownError
  273. _goto_mode(MODE_MODELLING)
  274. _input("model_list")
  275. output = _handle_output("Success: ", split=" ")
  276. if output == "":
  277. return set([])
  278. lst = set([])
  279. value = output.strip().split("\n")
  280. for v in value:
  281. m, mm = v.split(":")
  282. m = m.strip()
  283. mm = mm.strip()
  284. lst.add((m, mm))
  285. return lst
  286. def model_list_full():
  287. """List full information on all models."""
  288. # return [(model1, metamodel1, owner1, group1, permissions1), (model2, metamodel2, owner2, group2, permissions2), ...]
  289. # raises UnknownError
  290. _goto_mode(MODE_MODELLING)
  291. _input("model_list_full")
  292. output = _handle_output("Success: ", split=" ")
  293. if output == "":
  294. return set([])
  295. lst = set([])
  296. value = output.strip().split("\n")
  297. for v in value:
  298. m, mm = v.split(":")
  299. m = m.strip()
  300. mm = mm.strip()
  301. perm, own, grp, m = m.split(" ")
  302. lst.add((m, mm, own, grp, perm))
  303. return lst
  304. def verify(model):
  305. """Verify if a model conforms to its metamodel."""
  306. # return "verification_result"
  307. # raises UnknownError
  308. # raises UnknownModel
  309. _goto_mode(MODE_MODELLING)
  310. _input(["verify", model])
  311. return _handle_output("Success: ", split=" ")
  312. def model_overwrite(model_name, new_model=None):
  313. """Upload a new model and overwrite an existing model."""
  314. # return None
  315. # raises UnknownModel
  316. # raises PermissionDenied
  317. # raises CompilationError
  318. # raises UnknownError
  319. if mode not in [MODE_MODELLING, MODE_MODIFY, MODE_MANUAL]:
  320. raise InvalidMode()
  321. if new_model is not None:
  322. try:
  323. compiled = _compile_model(new_model)
  324. except Exception as e:
  325. raise CompilationError(e)
  326. else:
  327. compiled = ["exit"]
  328. if mode == MODE_MODIFY:
  329. _goto_mode(MODE_MODELLING)
  330. if mode == MODE_MODELLING:
  331. _input(["model_overwrite", model_name])
  332. elif mode == MODE_MANUAL:
  333. _input("upload")
  334. else:
  335. raise InvalidMode()
  336. _handle_output("Waiting for model constructors...")
  337. _input(compiled)
  338. _output("Success")
  339. def user_logout():
  340. """Log out the current user and break the connection."""
  341. # return None
  342. # raises UnknownError
  343. global mode
  344. _goto_mode(MODE_MODELLING)
  345. _input("exit")
  346. mode = MODE_UNCONNECTED
  347. def user_delete():
  348. """Removes the current user and break the connection."""
  349. # return None
  350. # raises UnknownError
  351. global mode
  352. _goto_mode(MODE_MODELLING)
  353. _input("self-destruct")
  354. mode = MODE_UNCONNECTED
  355. def model_render(model_name, mapper_name):
  356. """Fetch a rendered verion of a model."""
  357. # return JSON_representation
  358. # raises UnknownError
  359. # raises UnknownIdentifier
  360. # raises InterfaceMismatch
  361. _goto_mode(MODE_MODELLING)
  362. _input(["model_render", model_name, mapper_name])
  363. return _handle_output("Success: ", split=" ")
  364. def transformation_between(source, target):
  365. _goto_mode(MODE_MODELLING)
  366. _input(["transformation_between", source, target])
  367. output = _handle_output("Success: ", split=" ")
  368. if output == "":
  369. return set([])
  370. lst = set([v for v in output.split("\n")])
  371. def transformation_add_MT(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  372. """Create a new model transformation."""
  373. global mode
  374. _goto_mode(MODE_MODELLING)
  375. try:
  376. compiled = _compile_model(code)
  377. except Exception as e:
  378. raise CompilationError(e)
  379. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  380. _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
  381. # Possibly modify the merged metamodel first (add tracability links)
  382. mode = MODE_MANUAL
  383. _output() # Model loaded, ready for commands
  384. callback()
  385. _input("exit")
  386. mode = MODE_MODELLING
  387. # Done, so RAMify and upload the model
  388. _handle_output("Waiting for model constructors...")
  389. _input(compiled)
  390. _handle_output("Success")
  391. def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: None):
  392. """Create a new action language model, which can be executed."""
  393. _goto_mode(MODE_MODELLING)
  394. try:
  395. compiled = _compile_AL(code)
  396. except Exception as e:
  397. raise CompilationError(e)
  398. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  399. _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
  400. _handle_output("Waiting for code constructors...")
  401. _input(compiled)
  402. _output("Success")
  403. def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: None):
  404. """Create a new manual model operation."""
  405. _goto_mode(MODE_MODELLING)
  406. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  407. _input(["transformation_add_MANUAL"] + mv_dict_rep + [operation_name])
  408. _handle_output("Success")
  409. def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  410. """Execute an existing model operation."""
  411. global mode
  412. _goto_mode(MODE_MODELLING)
  413. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  414. _input(["transformation_execute", operation_name] + mv_dict_rep)
  415. _handle_output("Success: ready for AL execution")
  416. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  417. while _output() not in ["Success", "Failure"]:
  418. mode = MODE_DIALOG
  419. reply = callback(_last_output())
  420. mode = MODE_MODELLING
  421. if reply is not None:
  422. _input(reply)
  423. # Got termination message, so we are done!
  424. if _last_output() == "Success":
  425. return True
  426. else:
  427. return False
  428. def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  429. """Execute an existing model operation."""
  430. global mode
  431. _goto_mode(MODE_MODELLING)
  432. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  433. _input(["transformation_execute", operation_name] + mv_dict_rep)
  434. _handle_output("Success: ready for MANUAL execution")
  435. # Skip over the begin of mini_modify
  436. _output() # Please perform manual operation X
  437. _output() # Model loaded, ready for commands
  438. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  439. mode = MODE_MANUAL
  440. callback()
  441. # Finished, so leave
  442. _input("exit")
  443. mode = MODE_MODELLING
  444. # Got termination message, so we are done!
  445. if _output() == "Success":
  446. return True
  447. else:
  448. return False
  449. def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  450. """Execute an existing model operation."""
  451. global mode
  452. _goto_mode(MODE_MODELLING)
  453. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  454. _input(["transformation_execute", operation_name] + mv_dict_rep)
  455. _handle_output("Success: ready for MT execution")
  456. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  457. while _output() not in ["Success", "Failure"]:
  458. mode = MODE_DIALOG
  459. reply = callback(_last_output())
  460. mode = MODE_MODELLING
  461. if reply is not None:
  462. _input(reply)
  463. # Got termination message, so we are done!
  464. if _last_output() == "Success":
  465. return True
  466. else:
  467. return False
  468. def transformation_list():
  469. """List existing model operations."""
  470. _goto_mode(MODE_MODELLING)
  471. _input("transformation_list")
  472. output = _handle_output("Success: ", split=" ")
  473. if output == "":
  474. return set([])
  475. lst = set([])
  476. value = output.strip().split("\n")
  477. for v in value:
  478. t, m = v.strip().split(" ", 1)
  479. t = t[1:-1].strip()
  480. m = m.strip().split(":")[0].strip()
  481. lst.add((t, m))
  482. return lst
  483. def process_execute(process_name, prefix, callbacks):
  484. """Execute a process model."""
  485. global mode
  486. _goto_mode(MODE_MODELLING)
  487. _input(["process_execute", process_name, prefix])
  488. _handle_output("Success")
  489. while _output() != "Success":
  490. output = _last_output()
  491. if output.startswith("Enacting "):
  492. # Next activity!
  493. t = output.split(" ", 1)[1].split(":", 1)[0]
  494. name = output.split(": ", 1)[1]
  495. if name in callbacks:
  496. callback = callbacks[name]
  497. if t == "ModelTransformation" or t == "ActionLanguage":
  498. while not (_output().startswith("Enacting ") or _last_output() == "Success"):
  499. mode = MODE_DIALOG
  500. reply = callback(_last_output())
  501. mode = MODE_MODELLING
  502. if reply is not None:
  503. _input(reply)
  504. elif t == "ManualOperation":
  505. _output() # Please perform manual operation X
  506. _output() # Model loaded, ready for commands
  507. mode = MODE_MANUAL
  508. callback()
  509. _input("exit")
  510. mode = MODE_MODELLING
  511. def permission_modify():
  512. """Modify permissions of a model."""
  513. raise NotImplementedError()
  514. def permission_owner():
  515. """Modify the owning user of a model."""
  516. raise NotImplementedError()
  517. def permission_group():
  518. """Modify the owning group of a model."""
  519. raise NotImplementedError()
  520. def group_create():
  521. """Create a new group."""
  522. raise NotImplementedError()
  523. def group_delete():
  524. """Delete a group of which you are an owner."""
  525. raise NotImplementedError()
  526. def group_owner_add():
  527. """Add a new owning user to a group you own."""
  528. raise NotImplementedError()
  529. def group_owner_delete():
  530. """Delete an owning user to a group you own."""
  531. raise NotImplementedError()
  532. def group_join():
  533. """Add a new user to a group you own."""
  534. raise NotImplementedError()
  535. def group_kick():
  536. """Delete a user from a group you own."""
  537. raise NotImplementedError()
  538. def group_list():
  539. """List existing groups."""
  540. raise NotImplementedError()
  541. def admin_promote():
  542. """Promote a user to admin status."""
  543. raise NotImplementedError()
  544. def admin_demote():
  545. """Demote a user from admin status."""
  546. raise NotImplementedError()
  547. # Actual operations on the model
  548. def element_list(model_name):
  549. """Return a list of all IDs and the type of the element"""
  550. # return [(name1, type1), (name2, type2), ...]
  551. # raises UnknownError
  552. _goto_mode(MODE_MODIFY, model_name)
  553. _input("list_full")
  554. lst = set([])
  555. output = _handle_output("Success: ", split=" ")
  556. if output == "":
  557. return set([])
  558. for v in output.split("\n"):
  559. m, mm = v.split(":")
  560. m = m.strip()
  561. mm = mm.strip()
  562. lst.add((m, mm))
  563. return lst
  564. def types(model_name):
  565. """Return a list of all types usable in the model"""
  566. # return [type1, type2, ...]
  567. # raises UnknownError
  568. _goto_mode(MODE_MODIFY, model_name)
  569. _input("types")
  570. lst = set([])
  571. output = _handle_output("Success: ", split=" ")
  572. if output == "":
  573. return set([])
  574. for v in output.split("\n"):
  575. m, mm = v.split(":")
  576. m = m.strip()
  577. lst.add(m)
  578. return lst
  579. def types_full(model_name):
  580. """Return a list of full types usable in the model"""
  581. # return [(type1, typetype1), (type2, typetype2), ...]
  582. # raises UnknownError
  583. _goto_mode(MODE_MODIFY, model_name)
  584. _input("types")
  585. lst = set([])
  586. output = _handle_output("Success: ", split=" ")
  587. if output == "":
  588. return set([])
  589. for v in output.split("\n"):
  590. m, mm = v.split(":")
  591. m = m.strip()
  592. mm = mm.strip()
  593. lst.add((m, mm))
  594. return lst
  595. def read(model_name, ID):
  596. """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
  597. # return (type, (source, target))
  598. # raises UnknownError
  599. # raises UnknownIdentifier
  600. _goto_mode(MODE_MODIFY, model_name)
  601. _input(["read", ID])
  602. output = _handle_output("Success: ", split=" ")
  603. v = output.split("\n")
  604. t = v[1].split(":")[1].strip()
  605. if (not v[2].startswith("Source:")):
  606. rval = (t, None)
  607. else:
  608. src = v[2].split(":")[1].strip()
  609. trg = v[3].split(":")[1].strip()
  610. rval = (t, (src, trg))
  611. return rval
  612. def read_attrs(model_name, ID):
  613. """Return a dictionary of attribute value pairs"""
  614. # return {attr1: value1, attr2: value2, ...}
  615. # raises UnknownError
  616. # raises UnknownIdentifier
  617. _goto_mode(MODE_MODIFY, model_name)
  618. _input(["read", ID])
  619. output = _handle_output("Success: ", split=" ")
  620. v = output.split("\n")
  621. searching = True
  622. rval = {}
  623. for r in v:
  624. if searching:
  625. if r == "Attributes:":
  626. # Start working on attributes
  627. searching = False
  628. else:
  629. key, value = r.split(":", 1)
  630. _, value = value.split("=", 1)
  631. key = json.loads(key.strip())
  632. value = value.strip()
  633. if value == "None":
  634. value = None
  635. elif value == "True":
  636. value = True
  637. elif value == "False":
  638. value = False
  639. else:
  640. value = json.loads(value)
  641. rval[key] = value
  642. return rval
  643. def instantiate(model_name, typename, edge=None, ID=""):
  644. """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
  645. # return instantiated_ID
  646. # raises UnknownError
  647. # raises UnknownType
  648. # raises UnknownIdentifier
  649. # raises NotAnEdge
  650. _goto_mode(MODE_MODIFY, model_name)
  651. if edge is None:
  652. _input(["instantiate_node", typename, ID])
  653. else:
  654. _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
  655. return _handle_output("Success: ", split=" ")
  656. def delete_element(model_name, ID):
  657. """Delete the element with the given ID"""
  658. # return None
  659. # raises UnknownError
  660. # raises UnknownIdentifier
  661. _goto_mode(MODE_MODIFY, model_name)
  662. _input(["delete", ID])
  663. _handle_output("Success")
  664. def attr_assign(model_name, ID, attr, value):
  665. """Assign a value to an attribute"""
  666. # return None
  667. # raises UnknownError
  668. # raises UnknownIdentifier
  669. # raises NoSuchAttribute
  670. # raises UnsupportedValue
  671. _goto_mode(MODE_MODIFY, model_name)
  672. _input(["attr_add", ID, attr, value])
  673. _handle_output("Success")
  674. def attr_assign_code(model_name, ID, attr, code):
  675. """Assign a piece of Action Language code to the attribute"""
  676. # return None
  677. # raises UnknownError
  678. # raises UnknownIdentifier
  679. # raises NoSuchAttribute
  680. # raises UnsupportedValue
  681. try:
  682. compiled = _compile_AL(code)
  683. except Exception as e:
  684. raise CompilationError(e)
  685. _goto_mode(MODE_MODIFY, model_name)
  686. _input(["attr_add", ID, attr])
  687. _handle_output("Waiting for code constructors...")
  688. _input(compiled)
  689. _output("Success")
  690. def attr_delete(model_name, ID, attr):
  691. """Remove an attribute."""
  692. _goto_mode(MODE_MODIFY, model_name)
  693. _input(["attr_del", ID, attr])
  694. _handle_output("Success")
  695. def read_outgoing(model_name, ID, typename):
  696. """Returns a list of all outgoing associations of a specific type ("" = all)"""
  697. # return [name1, name2, ...]
  698. # raises UnknownError
  699. # raises UnknownIdentifier
  700. _goto_mode(MODE_MODIFY, model_name)
  701. _input(["read_outgoing", ID, typename])
  702. output = _handle_output("Success: ", split=" ")
  703. if output == "":
  704. return set([])
  705. else:
  706. return set(output.split("\n"))
  707. def read_incoming(model_name, ID, typename):
  708. """Returns a list of all incoming associations of a specific type ("" = all)"""
  709. # return [name1, name2, ...]
  710. # raises UnknownError
  711. # raises UnknownIdentifier
  712. # raises UnknownType
  713. _goto_mode(MODE_MODIFY, model_name)
  714. _input(["read_incoming", ID, typename])
  715. output = _handle_output("Success: ", split=" ")
  716. if output == "":
  717. return set([])
  718. else:
  719. return set(output.split("\n"))
  720. def read_association_source(model_name, ID):
  721. """Returns the source of an association."""
  722. # returns name
  723. # raises UnknownError
  724. # raises UnknownIdentifier
  725. # raises NotAnAssociation
  726. _goto_mode(MODE_MODIFY, model_name)
  727. _input(["read_association_source", ID])
  728. return _handle_output("Success: ", split=" ")
  729. def read_association_destination(model_name, ID):
  730. """Returns the destination of an association."""
  731. # returns name
  732. # raises UnknownError
  733. # raises UnknownIdentifier
  734. # raises NotAnAssociation
  735. _goto_mode(MODE_MODIFY, model_name)
  736. _input(["read_association_destination", ID])
  737. return _handle_output("Success: ", split=" ")
  738. def model_exit():
  739. """Leave model modify mode."""
  740. # return None
  741. # raises UnknownError
  742. global mode
  743. global prev_mode
  744. if prev_mode == MODE_MANUAL:
  745. mode = MODE_MANUAL
  746. return
  747. if mode != MODE_MODIFY:
  748. raise InvalidMode()
  749. _input("exit")
  750. _output("Success")
  751. mode = MODE_MODELLING