modelverse.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888
  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: model_exit()):
  372. """Create a new model transformation."""
  373. _goto_mode(MODE_MODELLING)
  374. try:
  375. compiled = _compile_model(code)
  376. except Exception as e:
  377. raise CompilationError(e)
  378. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  379. _input(["transformation_add_MT"] + mv_dict_rep + [operation_name])
  380. #mode = MODE_MANUAL
  381. #callback()
  382. #mode = MODE_MODELLING
  383. _handle_output("Waiting for model constructors...")
  384. _input(compiled)
  385. _handle_output("Success")
  386. def transformation_add_AL(source_metamodels, target_metamodels, operation_name, code, callback=lambda: model_exit()):
  387. """Create a new action language model, which can be executed."""
  388. _goto_mode(MODE_MODELLING)
  389. try:
  390. compiled = _compile_AL(code)
  391. except Exception as e:
  392. raise CompilationError(e)
  393. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  394. _input(["transformation_add_AL"] + mv_dict_rep + [operation_name])
  395. _handle_output("Waiting for code constructors...")
  396. _input(compiled)
  397. _output("Success")
  398. def transformation_add_MANUAL(source_metamodels, target_metamodels, operation_name, callback=lambda: model_exit()):
  399. """Create a new manual model operation."""
  400. _goto_mode(MODE_MODELLING)
  401. mv_dict_rep = _dict_to_list(source_metamodels) + [""] + _dict_to_list(target_metamodels) + [""]
  402. _input(["transformation_add_MANUAL"] + mv_dict_rep + [operation_name])
  403. _handle_output("Success")
  404. def transformation_execute_AL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  405. """Execute an existing model operation."""
  406. global mode
  407. _goto_mode(MODE_MODELLING)
  408. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  409. _input(["transformation_execute", operation_name] + mv_dict_rep)
  410. _handle_output("Success: ready for AL execution")
  411. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  412. while _output() not in ["Success", "Failure"]:
  413. mode = MODE_DIALOG
  414. reply = callback(_last_output())
  415. mode = MODE_MODELLING
  416. if reply is not None:
  417. _input(reply)
  418. # Got termination message, so we are done!
  419. if _last_output() == "Success":
  420. return True
  421. else:
  422. return False
  423. def transformation_execute_MANUAL(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  424. """Execute an existing model operation."""
  425. global mode
  426. _goto_mode(MODE_MODELLING)
  427. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  428. _input(["transformation_execute", operation_name] + mv_dict_rep)
  429. _handle_output("Success: ready for MANUAL execution")
  430. # Skip over the begin of mini_modify
  431. _output() # Please perform manual operation X
  432. _output() # Model loaded, ready for commands
  433. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  434. mode = MODE_MANUAL
  435. callback()
  436. # Finished, so leave
  437. _input("exit")
  438. mode = MODE_MODELLING
  439. # Got termination message, so we are done!
  440. if _output() == "Success":
  441. return True
  442. else:
  443. return False
  444. def transformation_execute_MT(operation_name, input_models_dict, output_models_dict, callback=lambda i: None):
  445. """Execute an existing model operation."""
  446. global mode
  447. _goto_mode(MODE_MODELLING)
  448. mv_dict_rep = _dict_to_list(input_models_dict) + [""] + _dict_to_list(output_models_dict) + [""]
  449. _input(["transformation_execute", operation_name] + mv_dict_rep)
  450. _handle_output("Success: ready for MT execution")
  451. # We are now executing, so everything we get is part of the dialog, except if it is the string for transformation termination
  452. while _output() not in ["Success", "Failure"]:
  453. mode = MODE_DIALOG
  454. reply = callback(_last_output())
  455. mode = MODE_MODELLING
  456. if reply is not None:
  457. _input(reply)
  458. # Got termination message, so we are done!
  459. if _last_output() == "Success":
  460. return True
  461. else:
  462. return False
  463. def transformation_list():
  464. """List existing model operations."""
  465. _goto_mode(MODE_MODELLING)
  466. _input("transformation_list")
  467. output = _handle_output("Success: ", split=" ")
  468. if output == "":
  469. return set([])
  470. lst = set([])
  471. value = output.strip().split("\n")
  472. for v in value:
  473. t, m = v.strip().split(" ", 1)
  474. t = t[1:-1].strip()
  475. m = m.strip().split(":")[0].strip()
  476. lst.add((t, m))
  477. return lst
  478. def process_execute(process_name, prefix, callbacks):
  479. """Execute a process model."""
  480. global mode
  481. _goto_mode(MODE_MODELLING)
  482. _input(["process_execute", process_name, prefix])
  483. _handle_output("Success")
  484. while _output() != "Success":
  485. output = _last_output()
  486. if output.startswith("Enacting "):
  487. # Next activity!
  488. t = output.split(" ", 1)[1].split(":", 1)[0]
  489. name = output.split(": ", 1)[1]
  490. if name in callbacks:
  491. callback = callbacks[name]
  492. if t == "ModelTransformation" or t == "ActionLanguage":
  493. while not (_output().startswith("Enacting ") or _last_output() == "Success"):
  494. mode = MODE_DIALOG
  495. reply = callback(_last_output())
  496. mode = MODE_MODELLING
  497. if reply is not None:
  498. _input(reply)
  499. elif t == "ManualOperation":
  500. _output() # Please perform manual operation X
  501. _output() # Model loaded, ready for commands
  502. mode = MODE_MANUAL
  503. callback()
  504. _input("exit")
  505. mode = MODE_MODELLING
  506. def permission_modify():
  507. """Modify permissions of a model."""
  508. raise NotImplementedError()
  509. def permission_owner():
  510. """Modify the owning user of a model."""
  511. raise NotImplementedError()
  512. def permission_group():
  513. """Modify the owning group of a model."""
  514. raise NotImplementedError()
  515. def group_create():
  516. """Create a new group."""
  517. raise NotImplementedError()
  518. def group_delete():
  519. """Delete a group of which you are an owner."""
  520. raise NotImplementedError()
  521. def group_owner_add():
  522. """Add a new owning user to a group you own."""
  523. raise NotImplementedError()
  524. def group_owner_delete():
  525. """Delete an owning user to a group you own."""
  526. raise NotImplementedError()
  527. def group_join():
  528. """Add a new user to a group you own."""
  529. raise NotImplementedError()
  530. def group_kick():
  531. """Delete a user from a group you own."""
  532. raise NotImplementedError()
  533. def group_list():
  534. """List existing groups."""
  535. raise NotImplementedError()
  536. def admin_promote():
  537. """Promote a user to admin status."""
  538. raise NotImplementedError()
  539. def admin_demote():
  540. """Demote a user from admin status."""
  541. raise NotImplementedError()
  542. # Actual operations on the model
  543. def element_list(model_name):
  544. """Return a list of all IDs and the type of the element"""
  545. # return [(name1, type1), (name2, type2), ...]
  546. # raises UnknownError
  547. _goto_mode(MODE_MODIFY, model_name)
  548. _input("list_full")
  549. lst = set([])
  550. output = _handle_output("Success: ", split=" ")
  551. if output == "":
  552. return set([])
  553. for v in output.split("\n"):
  554. m, mm = v.split(":")
  555. m = m.strip()
  556. mm = mm.strip()
  557. lst.add((m, mm))
  558. return lst
  559. def types(model_name):
  560. """Return a list of all types usable in the model"""
  561. # return [type1, type2, ...]
  562. # raises UnknownError
  563. _goto_mode(MODE_MODIFY, model_name)
  564. _input("types")
  565. lst = set([])
  566. output = _handle_output("Success: ", split=" ")
  567. if output == "":
  568. return set([])
  569. for v in output.split("\n"):
  570. m, mm = v.split(":")
  571. m = m.strip()
  572. lst.add(m)
  573. return lst
  574. def types_full(model_name):
  575. """Return a list of full types usable in the model"""
  576. # return [(type1, typetype1), (type2, typetype2), ...]
  577. # raises UnknownError
  578. _goto_mode(MODE_MODIFY, model_name)
  579. _input("types")
  580. lst = set([])
  581. output = _handle_output("Success: ", split=" ")
  582. if output == "":
  583. return set([])
  584. for v in output.split("\n"):
  585. m, mm = v.split(":")
  586. m = m.strip()
  587. mm = mm.strip()
  588. lst.add((m, mm))
  589. return lst
  590. def read(model_name, ID):
  591. """Return a tuple of information on the element: its type and source/target (None if not an edge)"""
  592. # return (type, (source, target))
  593. # raises UnknownError
  594. # raises UnknownIdentifier
  595. _goto_mode(MODE_MODIFY, model_name)
  596. _input(["read", ID])
  597. output = _handle_output("Success: ", split=" ")
  598. v = output.split("\n")
  599. print(v)
  600. t = v[1].split(":")[1].strip()
  601. if (not v[2].startswith("Source:")):
  602. rval = (t, None)
  603. else:
  604. src = v[2].split(":")[1].strip()
  605. trg = v[3].split(":")[1].strip()
  606. rval = (t, (src, trg))
  607. return rval
  608. def read_attrs(model_name, ID):
  609. """Return a dictionary of attribute value pairs"""
  610. # return {attr1: value1, attr2: value2, ...}
  611. # raises UnknownError
  612. # raises UnknownIdentifier
  613. _goto_mode(MODE_MODIFY, model_name)
  614. _input(["read", ID])
  615. output = _handle_output("Success: ", split=" ")
  616. v = output.split("\n")
  617. searching = True
  618. rval = {}
  619. for r in v:
  620. if searching:
  621. if r == "Attributes:":
  622. # Start working on attributes
  623. searching = False
  624. else:
  625. key, value = r.split(":", 1)
  626. _, value = value.split("=", 1)
  627. key = json.loads(key.strip())
  628. value = value.strip()
  629. if value == "None":
  630. value = None
  631. elif value == "True":
  632. value = True
  633. elif value == "False":
  634. value = False
  635. else:
  636. value = json.loads(value)
  637. rval[key] = value
  638. return rval
  639. def instantiate(model_name, typename, edge=None, ID=""):
  640. """Create a new instance of the specified typename, between the selected elements (if not None), and with the provided ID (if any)"""
  641. # return instantiated_ID
  642. # raises UnknownError
  643. # raises UnknownType
  644. # raises UnknownIdentifier
  645. # raises NotAnEdge
  646. _goto_mode(MODE_MODIFY, model_name)
  647. if edge is None:
  648. _input(["instantiate_node", typename, ID])
  649. else:
  650. _input(["instantiate_edge", typename, ID, edge[0], edge[1]])
  651. return _handle_output("Success: ", split=" ")
  652. def delete_element(model_name, ID):
  653. """Delete the element with the given ID"""
  654. # return None
  655. # raises UnknownError
  656. # raises UnknownIdentifier
  657. _goto_mode(MODE_MODIFY, model_name)
  658. _input(["delete", ID])
  659. _handle_output("Success")
  660. def attr_assign(model_name, ID, attr, value):
  661. """Assign a value to an attribute"""
  662. # return None
  663. # raises UnknownError
  664. # raises UnknownIdentifier
  665. # raises NoSuchAttribute
  666. # raises UnsupportedValue
  667. _goto_mode(MODE_MODIFY, model_name)
  668. _input(["attr_add", ID, attr, value])
  669. _handle_output("Success")
  670. def attr_assign_code(model_name, ID, attr, code):
  671. """Assign a piece of Action Language code to the attribute"""
  672. # return None
  673. # raises UnknownError
  674. # raises UnknownIdentifier
  675. # raises NoSuchAttribute
  676. # raises UnsupportedValue
  677. try:
  678. compiled = _compile_AL(code)
  679. except Exception as e:
  680. raise CompilationError(e)
  681. _goto_mode(MODE_MODIFY, model_name)
  682. _input(["attr_add", ID, attr])
  683. _handle_output("Waiting for code constructors...")
  684. _input(compiled)
  685. _output("Success")
  686. def attr_delete(model_name, ID, attr):
  687. """Remove an attribute."""
  688. _goto_mode(MODE_MODIFY, model_name)
  689. _input(["attr_del", ID, attr])
  690. _handle_output("Success")
  691. def read_outgoing(model_name, ID, typename):
  692. """Returns a list of all outgoing associations of a specific type ("" = all)"""
  693. # return [name1, name2, ...]
  694. # raises UnknownError
  695. # raises UnknownIdentifier
  696. _goto_mode(MODE_MODIFY, model_name)
  697. _input(["read_outgoing", ID, typename])
  698. output = _handle_output("Success: ", split=" ")
  699. if output == "":
  700. return set([])
  701. else:
  702. return set(output.split("\n"))
  703. def read_incoming(model_name, ID, typename):
  704. """Returns a list of all incoming associations of a specific type ("" = all)"""
  705. # return [name1, name2, ...]
  706. # raises UnknownError
  707. # raises UnknownIdentifier
  708. # raises UnknownType
  709. _goto_mode(MODE_MODIFY, model_name)
  710. _input(["read_incoming", ID, typename])
  711. output = _handle_output("Success: ", split=" ")
  712. if output == "":
  713. return set([])
  714. else:
  715. return set(output.split("\n"))
  716. def read_association_source(model_name, ID):
  717. """Returns the source of an association."""
  718. # returns name
  719. # raises UnknownError
  720. # raises UnknownIdentifier
  721. # raises NotAnAssociation
  722. _goto_mode(MODE_MODIFY, model_name)
  723. _input(["read_association_source", ID])
  724. return _handle_output("Success: ", split=" ")
  725. def read_association_destination(model_name, ID):
  726. """Returns the destination of an association."""
  727. # returns name
  728. # raises UnknownError
  729. # raises UnknownIdentifier
  730. # raises NotAnAssociation
  731. _goto_mode(MODE_MODIFY, model_name)
  732. _input(["read_association_destination", ID])
  733. return _handle_output("Success: ", split=" ")
  734. def model_exit():
  735. """Leave model modify mode."""
  736. # return None
  737. # raises UnknownError
  738. global mode
  739. global prev_mode
  740. if prev_mode == MODE_MANUAL:
  741. mode = MODE_MANUAL
  742. return
  743. if mode != MODE_MODIFY:
  744. raise InvalidMode()
  745. _input("exit")
  746. _output("Success")
  747. mode = MODE_MODELLING