modelverse.py 28 KB

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