modelverse.py 27 KB

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