woods_pysem.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. import functools
  2. import random
  3. import math
  4. from state.devstate import DevState
  5. from bootstrap.scd import bootstrap_scd
  6. from framework.conformance import Conformance, render_conformance_check_result
  7. from concrete_syntax.textual_od import parser, renderer
  8. from concrete_syntax.common import indent
  9. from concrete_syntax.plantuml import renderer as plantuml
  10. from util import prompt
  11. from transformation.cloner import clone_od
  12. from api.od import ODAPI
  13. state = DevState()
  14. print("Loading meta-meta-model...")
  15. scd_mmm = bootstrap_scd(state)
  16. print("Done")
  17. # Design meta-model
  18. woods_mm_cs = """
  19. Animal:Class {
  20. abstract = True;
  21. }
  22. Bear:Class
  23. :Inheritance (Bear -> Animal)
  24. Man:Class {
  25. lower_cardinality = 1;
  26. upper_cardinality = 2;
  27. constraint = `get_value(get_slot(this, "weight")) > 20`;
  28. }
  29. :Inheritance (Man -> Animal)
  30. Man_weight:AttributeLink (Man -> Integer) {
  31. name = "weight";
  32. optional = False;
  33. }
  34. afraidOf:Association (Man -> Animal) {
  35. source_upper_cardinality = 6;
  36. target_lower_cardinality = 1;
  37. }
  38. """
  39. woods_mm = parser.parse_od(
  40. state,
  41. m_text=woods_mm_cs,
  42. mm=scd_mmm)
  43. print("MM valid?")
  44. conf = Conformance(state, woods_mm, scd_mmm)
  45. print(render_conformance_check_result(conf.check_nominal()))
  46. # Runtime meta-model
  47. woods_rt_mm_cs = woods_mm_cs + """
  48. AnimalState:Class {
  49. abstract = True;
  50. }
  51. AnimalState_dead:AttributeLink (AnimalState -> Boolean) {
  52. name = "dead";
  53. optional = False;
  54. }
  55. of:Association (AnimalState -> Animal) {
  56. source_lower_cardinality = 1;
  57. source_upper_cardinality = 1;
  58. target_lower_cardinality = 1;
  59. target_upper_cardinality = 1;
  60. }
  61. BearState:Class {
  62. constraint = `get_type_name(get_target(get_outgoing(this, "of")[0])) == "Bear"`;
  63. }
  64. :Inheritance (BearState -> AnimalState)
  65. BearState_hunger:AttributeLink (BearState -> Integer) {
  66. name = "hunger";
  67. optional = False;
  68. constraint = ```
  69. val = get_value(get_target(this))
  70. val >= 0 and val <= 100
  71. ```;
  72. }
  73. ManState:Class {
  74. constraint = `get_type_name(get_target(get_outgoing(this, "of")[0])) == "Man"`;
  75. }
  76. :Inheritance (ManState -> AnimalState)
  77. attacking:Association (AnimalState -> ManState) {
  78. # Animal can only attack one Man at a time
  79. target_upper_cardinality = 1;
  80. # Man can only be attacked by one Animal at a time
  81. source_upper_cardinality = 1;
  82. constraint = ```
  83. attacker = get_source(this)
  84. if get_type_name(attacker) == "BearState":
  85. # only BearState has 'hunger' attribute
  86. hunger = get_value(get_slot(attacker, "hunger"))
  87. else:
  88. hunger = 100 # Man can always attack
  89. attacker_dead = get_value(get_slot(attacker, "dead"))
  90. attacked_state = get_target(this)
  91. attacked_dead = get_value(get_slot(attacked_state, "dead"))
  92. (
  93. hunger >= 50
  94. and not attacker_dead # cannot attack while dead
  95. and not attacked_dead # cannot attack whoever is dead
  96. )
  97. ```;
  98. }
  99. attacking_starttime:AttributeLink (attacking -> Integer) {
  100. name = "starttime";
  101. optional = False;
  102. constraint = ```
  103. val = get_value(get_target(this))
  104. _, clock = get_all_instances("Clock")[0]
  105. current_time = get_slot_value(clock, "time")
  106. val >= 0 and val <= current_time
  107. ```;
  108. }
  109. # Just a clock singleton for keeping the time
  110. Clock:Class {
  111. lower_cardinality = 1;
  112. upper_cardinality = 1;
  113. }
  114. Clock_time:AttributeLink (Clock -> Integer) {
  115. name = "time";
  116. optional = False;
  117. constraint = `get_value(get_target(this)) >= 0`;
  118. }
  119. """
  120. woods_rt_mm = parser.parse_od(
  121. state,
  122. m_text=woods_rt_mm_cs,
  123. mm=scd_mmm)
  124. print("RT-MM valid?")
  125. conf = Conformance(state, woods_rt_mm, scd_mmm)
  126. print(render_conformance_check_result(conf.check_nominal()))
  127. # print("--------------")
  128. # print(indent(
  129. # renderer.render_od(state,
  130. # m_id=woods_rt_mm,
  131. # mm_id=scd_mmm),
  132. # 4))
  133. # print("--------------")
  134. # Our design model - the part that doesn't change
  135. woods_m_cs = """
  136. george:Man {
  137. weight = 80;
  138. }
  139. bill:Man {
  140. weight = 70;
  141. }
  142. teddy:Bear
  143. mrBrown:Bear
  144. # george is afraid of both bears
  145. :afraidOf (george -> teddy)
  146. :afraidOf (george -> mrBrown)
  147. # the men are afraid of each other
  148. :afraidOf (bill -> george)
  149. :afraidOf (george -> bill)
  150. """
  151. woods_m = parser.parse_od(
  152. state,
  153. m_text=woods_m_cs,
  154. mm=woods_mm)
  155. print("M valid?")
  156. conf = Conformance(state, woods_m, woods_mm)
  157. print(render_conformance_check_result(conf.check_nominal()))
  158. # Our runtime model - the part that changes with every execution step
  159. woods_rt_initial_m_cs = woods_m_cs + """
  160. georgeState:ManState {
  161. dead = False;
  162. }
  163. :of (georgeState -> george)
  164. billState:ManState {
  165. dead = False;
  166. }
  167. :of (billState -> bill)
  168. teddyState:BearState {
  169. dead = False;
  170. hunger = 40;
  171. }
  172. :of (teddyState -> teddy)
  173. mrBrownState:BearState {
  174. dead = False;
  175. hunger = 80;
  176. }
  177. :of (mrBrownState -> mrBrown)
  178. clock:Clock {
  179. time = 0;
  180. }
  181. """
  182. woods_rt_m = parser.parse_od(
  183. state,
  184. m_text=woods_rt_initial_m_cs,
  185. mm=woods_rt_mm)
  186. print("RT-M valid?")
  187. conf = Conformance(state, woods_rt_m, woods_rt_mm)
  188. print(render_conformance_check_result(conf.check_nominal()))
  189. # Helpers
  190. def state_of(od, animal):
  191. return od.get_source(od.get_incoming(animal, "of")[0])
  192. def animal_of(od, state):
  193. return od.get_target(od.get_outgoing(state, "of")[0])
  194. def get_time(od):
  195. _, clock = od.get_all_instances("Clock")[0]
  196. return clock, od.get_slot_value(clock, "time")
  197. def advance_time(od):
  198. msgs = []
  199. clock, old_time = get_time(od)
  200. new_time = old_time + 1
  201. od.set_slot_value(clock, "time", new_time)
  202. for _, attacking_link in od.get_all_instances("attacking"):
  203. man_state = od.get_target(attacking_link)
  204. animal_state = od.get_source(attacking_link)
  205. if od.get_type_name(animal_state) == "BearState":
  206. od.set_slot_value(animal_state, "hunger", max(od.get_slot_value(animal_state, "hunger") - 50, 0))
  207. od.set_slot_value(man_state, "dead", True)
  208. od.delete(attacking_link)
  209. msgs.append(f"{od.get_name(animal_of(od, animal_state))} kills {od.get_name(animal_of(od, man_state))}.")
  210. for _, bear_state in od.get_all_instances("BearState"):
  211. if od.get_slot_value(bear_state, "dead"):
  212. continue # bear already dead
  213. old_hunger = od.get_slot_value(bear_state, "hunger")
  214. new_hunger = min(old_hunger + 5, 100)
  215. od.set_slot_value(bear_state, "hunger", new_hunger)
  216. bear = od.get_target(od.get_outgoing(bear_state, "of")[0])
  217. bear_name = od.get_name(bear)
  218. if new_hunger == 100:
  219. od.set_slot_value(bear_state, "dead", True)
  220. msgs.append(f"Bear {bear_name} dies of hunger.")
  221. else:
  222. msgs.append(f"Bear {bear_name}'s hunger level is now {new_hunger}.")
  223. return msgs
  224. # we must use the names of the objects as parameters, because when cloning, the IDs of objects change!
  225. def attack(od, animal_name: str, man_name: str):
  226. msgs = []
  227. animal = od.get(animal_name)
  228. man = od.get(man_name)
  229. animal_state = state_of(od, animal)
  230. man_state = state_of(od, man)
  231. attack_link = od.create_link(None, # auto-generate link name
  232. "attacking", animal_state, man_state)
  233. _, clock = od.get_all_instances("Clock")[0]
  234. current_time = od.get_slot_value(clock, "time")
  235. od.set_slot_value(attack_link, "starttime", current_time)
  236. msgs.append(f"{animal_name} is now attacking {man_name}")
  237. return msgs
  238. def get_actions(od):
  239. # can always advance time:
  240. actions = { "advance time": advance_time }
  241. # who can attack whom?
  242. for _, afraid_link in od.get_all_instances("afraidOf"):
  243. man = od.get_source(afraid_link)
  244. animal = od.get_target(afraid_link)
  245. animal_name = od.get_name(animal)
  246. man_name = od.get_name(man)
  247. man_state = state_of(od, man)
  248. animal_state = state_of(od, animal)
  249. descr = f"{animal_name} ({od.get_type_name(animal)}) attacks {man_name} ({od.get_type_name(man)})"
  250. actions[descr] = functools.partial(attack, animal_name=animal_name, man_name=man_name)
  251. return { action_descr: functools.partial(exec_pure, action, od) for action_descr, action in actions.items() }
  252. # Copy model before modifying it
  253. def exec_pure(action, od):
  254. cloned_rt_m = clone_od(state, od.m, od.mm)
  255. new_od = ODAPI(state, cloned_rt_m, od.mm)
  256. msgs = action(new_od)
  257. return (new_od, msgs)
  258. def filter_actions(actions):
  259. result = {}
  260. def make_tuple(new_od, msgs):
  261. return (new_od, msgs)
  262. for name, callback in actions.items():
  263. print(f"attempt '{name}' ...", end='\r')
  264. (new_od, msgs) = callback()
  265. conf = Conformance(state, new_od.m, new_od.mm)
  266. errors = conf.check_nominal()
  267. # erase current line:
  268. print(" ", end='\r')
  269. if len(errors) == 0:
  270. # updated RT-M is conform, we have a valid action:
  271. yield (name, functools.partial(make_tuple, new_od, msgs))
  272. def unfilter_actions(actions, od):
  273. for name, callback in actions.items():
  274. yield (name, callback)
  275. conf = Conformance(state, od.m, od.mm)
  276. yield ("check conformance", lambda: (od, [render_conformance_check_result(conf.check_nominal())]))
  277. def render_woods(od):
  278. txt = ""
  279. _, time = get_time(od)
  280. txt += f"T = {time}.\n"
  281. txt += "Bears:\n"
  282. def render_attacking(animal_state):
  283. attacking = od.get_outgoing(animal_state, "attacking")
  284. if len(attacking) == 1:
  285. whom_state = od.get_target(attacking[0])
  286. whom_name = od.get_name(animal_of(od, whom_state))
  287. return f" attacking {whom_name}"
  288. else:
  289. return ""
  290. def render_dead(animal_state):
  291. return 'dead' if od.get_slot_value(animal_state, 'dead') else 'alive'
  292. for _, bear_state in od.get_all_instances("BearState"):
  293. bear = animal_of(od, bear_state)
  294. hunger = od.get_slot_value(bear_state, "hunger")
  295. txt += f" 🐻 {od.get_name(bear)} (hunger: {hunger}, {render_dead(bear_state)}) {render_attacking(bear_state)}\n"
  296. txt += "Men:\n"
  297. for _, man_state in od.get_all_instances("ManState"):
  298. man = animal_of(od, man_state)
  299. attacked_by = od.get_incoming(man_state, "attacking")
  300. if len(attacked_by) == 1:
  301. whom_state = od.get_source(attacked_by[0])
  302. whom_name = od.get_name(animal_of(od, whom_state))
  303. being_attacked = f" being attacked by {whom_name}"
  304. else:
  305. being_attacked = ""
  306. txt += f" 👨 {od.get_name(man)} ({render_dead(man_state)}) {render_attacking(man_state)}{being_attacked}\n"
  307. return txt
  308. od = ODAPI(state, woods_rt_m, woods_rt_mm)
  309. RANDOM_SEED = 0
  310. r = random.Random(RANDOM_SEED)
  311. def random_choice(options):
  312. arr = [action for descr, action in options]
  313. i = math.floor(r.random()*len(arr))
  314. return arr[i]
  315. def termination_condition(od):
  316. _, time = get_time(od)
  317. return time >= 10 # stop after 10 steps
  318. print(f"Using random seed: {RANDOM_SEED} (only applicable to random simulation)")
  319. while True:
  320. print("--------------")
  321. print(indent(render_woods(od), 4))
  322. print("--------------")
  323. if termination_condition(od):
  324. print("Termination condition satisfied. Quit.")
  325. break
  326. # print(indent(
  327. # renderer.render_od(state,
  328. # m_id=od.m,
  329. # mm_id=od.mm),
  330. # 4))
  331. # 1. Only 'valid' actions or all actions?
  332. # actions = unfilter_actions(get_actions(od), od)
  333. actions = filter_actions(get_actions(od))
  334. # 2. Manual or random selection?
  335. # action = prompt.choose("Select action:", actions)
  336. action = random_choice(actions)
  337. if action == None:
  338. print("No enabled actions. Quit.")
  339. break
  340. (od, msgs) = action()
  341. print(indent('\n'.join(f"▸ {msg}" for msg in msgs), 2))