modelverse.py 25 KB

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