my_planning_graph.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. from aimacode.planning import Action
  2. from aimacode.search import Problem
  3. from aimacode.utils import expr
  4. from lp_utils import decode_state
  5. class PgNode():
  6. """Base class for planning graph nodes.
  7. includes instance sets common to both types of nodes used in
  8. a planning graph
  9. parents: the set of nodes in the previous level
  10. children: the set of nodes in the subsequent level
  11. mutex: the set of sibling nodes that are mutually exclusive with this node
  12. """
  13. def __init__(self):
  14. self.parents = set()
  15. self.children = set()
  16. self.mutex = set()
  17. def is_mutex(self, other) -> bool:
  18. """Boolean test for mutual exclusion
  19. :param other: PgNode
  20. the other node to compare with
  21. :return: bool
  22. True if this node and the other are marked
  23. mutually exclusive (mutex)
  24. """
  25. if other in self.mutex:
  26. return True
  27. return False
  28. def show(self):
  29. """helper print for debugging shows counts of
  30. parents, children, siblings
  31. :return:
  32. print only
  33. """
  34. print("{} parents".format(len(self.parents)))
  35. print("{} children".format(len(self.children)))
  36. print("{} mutex".format(len(self.mutex)))
  37. class PgNode_s(PgNode):
  38. """A planning graph node representing a state (literal fluent) from a
  39. planning problem.
  40. Args:
  41. symbol : str
  42. A string representing a literal expression from a planning problem
  43. domain.
  44. is_pos : bool
  45. Boolean flag indicating whether the literal expression is positive or
  46. negative.
  47. """
  48. def __init__(self, symbol: str, is_pos: bool):
  49. """S-level Planning Graph node constructor.
  50. :param symbol: expr
  51. :param is_pos: bool
  52. Instance variables calculated:
  53. literal: expr
  54. fluent in its literal form including negative operator
  55. if applicable
  56. Instance variables inherited from PgNode:
  57. parents: set of nodes connected to this node in previous A level;
  58. children: set of nodes connected to this node in next A level;
  59. mutex: set of sibling S-nodes that this node has
  60. mutual exclusion with;
  61. """
  62. PgNode.__init__(self)
  63. self.symbol = symbol
  64. self.is_pos = is_pos
  65. self.literal = expr(self.symbol)
  66. if not self.is_pos:
  67. self.literal = expr('~{}'.format(self.symbol))
  68. def show(self):
  69. """Helper print for debugging shows literal plus counts of parents,
  70. children, siblings.
  71. :return:
  72. print only
  73. """
  74. print("\n*** {}".format(self.literal))
  75. PgNode.show(self)
  76. def __eq__(self, other):
  77. '''equality test for nodes - compares only the literal for equality
  78. :param other: PgNode_s
  79. :return: bool
  80. '''
  81. if isinstance(other, self.__class__):
  82. return (self.symbol == other.symbol) \
  83. and (self.is_pos == other.is_pos)
  84. def __hash__(self):
  85. return hash(self.symbol) ^ hash(self.is_pos)
  86. class PgNode_a(PgNode):
  87. """A-type (action) Planning Graph node - inherited from PgNode """
  88. def __init__(self, action: Action):
  89. """A-level Planning Graph node constructor
  90. :param action: Action
  91. a ground action, i.e. this action cannot contain any variables
  92. Instance variables calculated:
  93. An A-level will always have an S-level as its parent and an S-level
  94. as its child.
  95. The preconditions and effects will become the parents and children
  96. of the A-level node. However, when this node is created, it is not
  97. yet connected to the graph.
  98. prenodes: set of *possible* parent S-nodes
  99. effnodes: set of *possible* child S-nodes
  100. is_persistent: bool True if this is a persistence action,
  101. i.e. a no-op action
  102. Instance variables inherited from PgNode:
  103. parents: set of nodes connected to this node in previous A level;
  104. children: set of nodes connected to this node in next A level;
  105. mutex: set of sibling S-nodes that this node has
  106. mutual exclusion with;
  107. """
  108. PgNode.__init__(self)
  109. self.action = action
  110. self.prenodes = self.precond_s_nodes()
  111. self.effnodes = self.effect_s_nodes()
  112. self.is_persistent = False
  113. if self.prenodes == self.effnodes:
  114. self.is_persistent = True
  115. def show(self):
  116. """helper print for debugging shows action plus counts of
  117. parents, children, siblings.
  118. :return:
  119. print only
  120. """
  121. print("\n*** {}{}".format(self.action.name, self.action.args))
  122. PgNode.show(self)
  123. def precond_s_nodes(self):
  124. """precondition literals as S-nodes
  125. (represents possible parents for this node).
  126. It is computationally expensive to call this function;
  127. it is only called by the class constructor to populate the
  128. `prenodes` attribute.
  129. :return: set of PgNode_s
  130. """
  131. nodes = set()
  132. for p in self.action.precond_pos:
  133. n = PgNode_s(p, True)
  134. nodes.add(n)
  135. for p in self.action.precond_neg:
  136. n = PgNode_s(p, False)
  137. nodes.add(n)
  138. return nodes
  139. def effect_s_nodes(self):
  140. """effect literals as S-nodes
  141. (represents possible children for this node).
  142. It is computationally expensive to call this function;
  143. it is only called by the class constructor to populate the
  144. `effnodes` attribute.
  145. :return: set of PgNode_s
  146. """
  147. nodes = set()
  148. for e in self.action.effect_add:
  149. n = PgNode_s(e, True)
  150. nodes.add(n)
  151. for e in self.action.effect_rem:
  152. n = PgNode_s(e, False)
  153. nodes.add(n)
  154. return nodes
  155. def __eq__(self, other):
  156. """equality test for nodes - compares only the action name for equality
  157. :param other: PgNode_a
  158. :return: bool
  159. """
  160. if isinstance(other, self.__class__):
  161. return (self.action.name == other.action.name) \
  162. and (self.action.args == other.action.args)
  163. def __hash__(self):
  164. return hash(self.action.name) ^ hash(self.action.args)
  165. def mutexify(node1: PgNode, node2: PgNode):
  166. """Adds sibling nodes to each other's mutual exclusion (mutex) set.
  167. These should be sibling nodes!
  168. :param node1: PgNode (or inherited PgNode_a, PgNode_s types)
  169. :param node2: PgNode (or inherited PgNode_a, PgNode_s types)
  170. :return:
  171. node mutex sets modified
  172. """
  173. if type(node1) != type(node2):
  174. raise TypeError('Attempted to mutex two nodes of different types')
  175. node1.mutex.add(node2)
  176. node2.mutex.add(node1)
  177. class PlanningGraph():
  178. """
  179. A planning graph as described in chapter 10 of the AIMA text. The planning
  180. graph can be used to reason about
  181. """
  182. def __init__(self, problem: Problem, state: str, serial_planning=True):
  183. """
  184. :param problem: PlanningProblem
  185. (or subclass such as AirCargoProblem or HaveCakeProblem)
  186. :param state: str (will be in form TFTTFF... representing fluent states)
  187. :param serial_planning: bool
  188. (whether or not to assume that only one action can occur at a time)
  189. Instance variable calculated:
  190. fs: FluentState
  191. the state represented as positive and
  192. negative fluent literal lists
  193. all_actions: list of the PlanningProblem valid ground actions
  194. combined with calculated no-op actions
  195. s_levels: list of sets of PgNode_s,
  196. where each set in the list represents an S-level
  197. in the planning graph.
  198. a_levels: list of sets of PgNode_a,
  199. where each set in the list represents an A-level
  200. in the planning graph.
  201. """
  202. self.problem = problem
  203. self.fs = decode_state(state, problem.state_map)
  204. self.serial = serial_planning
  205. self.all_actions = self.problem.actions_list + \
  206. self.noop_actions(self.problem.state_map)
  207. self.s_levels = []
  208. self.a_levels = []
  209. self.create_graph()
  210. def noop_actions(self, literal_list):
  211. """create persistent action for each possible fluent
  212. "No-Op" actions are virtual actions (i.e., actions that only exist in
  213. the planning graph, not in the planning problem domain) that operate
  214. on each fluent (literal expression) from the problem domain. No op
  215. actions "pass through" the literal expressions from one level of the
  216. planning graph to the next.
  217. The no-op action list requires both a positive and a negative action
  218. for each literal expression. Positive no-op actions require the literal
  219. as a positive precondition and add the literal expression as an effect
  220. in the output, and negative no-op actions require the literal as a
  221. negative precondition and remove the literal expression as an effect in
  222. the output.
  223. This function should only be called by the class constructor.
  224. :param literal_list:
  225. :return: list of Action
  226. """
  227. action_list = []
  228. for fluent in literal_list:
  229. act1 = Action(expr("Noop_pos({})".format(fluent)),\
  230. ([fluent], []), ([fluent], []))
  231. action_list.append(act1)
  232. act2 = Action(expr("Noop_neg({})".format(fluent)),\
  233. ([], [fluent]), ([], [fluent]))
  234. action_list.append(act2)
  235. return action_list
  236. def create_graph(self):
  237. """Build a Planning Graph as described in Russell-Norvig 3rd Ed 10.3
  238. or 2nd Ed 11.4
  239. The S0 initial level has been implemented for you.
  240. It has no parents and includes all of the literal fluents that are part
  241. of the initial state passed to the constructor. At the start
  242. of a problem planning search, this will be the same as the initial
  243. state of the problem. However, the planning graph can be built from
  244. any state in the Planning Problem.
  245. This function should only be called by the class constructor.
  246. :return:
  247. builds the graph by filling s_levels[] and a_levels[] lists with
  248. node sets for each level.
  249. """
  250. # the graph should only be built during class construction
  251. if (len(self.s_levels) != 0) or (len(self.a_levels) != 0):
  252. raise Exception(
  253. 'Planning Graph already created;\
  254. construct a new planning graph for each new state in the\
  255. planning sequence')
  256. # initialize S0 to literals in initial state provided.
  257. leveled = False
  258. level = 0
  259. self.s_levels.append(set()) # S0 set of s_nodes - empty to start
  260. # for each fluent in the initial state, add the correct literal PgNode_s
  261. for literal in self.fs.pos:
  262. self.s_levels[level].add(PgNode_s(literal, True))
  263. for literal in self.fs.neg:
  264. self.s_levels[level].add(PgNode_s(literal, False))
  265. # no mutexes at the first level
  266. # continue to build the graph alternating A,
  267. # S levels until last two S levels contain the same literals,
  268. # i.e. until it is "leveled"
  269. while not leveled:
  270. self.add_action_level(level)
  271. self.update_a_mutex(self.a_levels[level])
  272. level += 1
  273. self.add_literal_level(level)
  274. self.update_s_mutex(self.s_levels[level])
  275. if self.s_levels[level] == self.s_levels[level - 1]:
  276. leveled = True
  277. def add_action_level(self, level):
  278. """ add an A (action) level to the Planning Graph
  279. :param level: int
  280. the level number alternates S0, A0, S1, A1, S2, ...etc.
  281. the level number is also used as the
  282. index for the node set lists self.a_levels[] and self.s_levels[]
  283. :return:
  284. adds A nodes to the current level in self.a_levels[level]
  285. """
  286. previous_s_level = self.s_levels[level]
  287. # Previous state level (previous to this level of actions)
  288. actions = self.all_actions # List of all possible actions
  289. self.a_levels.append(set()) # Initialize this level of actions
  290. for action in actions:
  291. a_node = PgNode_a(action)
  292. if a_node.prenodes.issubset(previous_s_level):
  293. for s_node in previous_s_level:
  294. # Connect action level to state and vice-versa
  295. s_node.children.add(a_node)
  296. a_node.parents.add(s_node)
  297. # Add newly created action to this new level of actions
  298. self.a_levels[level].add(a_node)
  299. def add_literal_level(self, level):
  300. """ add an S (literal) level to the Planning Graph
  301. :param level: int
  302. the level number alternates S0, A0, S1, A1, S2, ....etc.
  303. the level number is also used as the
  304. index for the node set lists self.a_levels[] and self.s_levels[]
  305. :return:
  306. adds S nodes to the current level in self.s_levels[level]
  307. """
  308. previous_a_level = self.a_levels[level - 1]
  309. #Previous action level (previous to this level of states)
  310. self.s_levels.append(set()) # Initialize this level of states
  311. for a_node in previous_a_level:
  312. for effect_node in a_node.effnodes:
  313. # Connect state level to action and vice-versa
  314. a_node.children.add(effect_node)
  315. effect_node.parents.add(a_node)
  316. # Add newly state to this new level of states
  317. self.s_levels[level].add(effect_node)
  318. def update_a_mutex(self, nodeset):
  319. """ Determine and update sibling mutual exclusion for A-level nodes
  320. Mutex action tests section from 3rd Ed. 10.3 or 2nd Ed. 11.4
  321. A mutex relation holds between two actions a given level
  322. if the planning graph is a serial planning graph and the pair are
  323. nonpersistence actions or if any of the three conditions hold between
  324. the pair:
  325. Inconsistent Effects
  326. Interference
  327. Competing needs
  328. :param nodeset: set of PgNode_a (siblings in the same level)
  329. :return:
  330. mutex set in each PgNode_a in the set is appropriately updated
  331. """
  332. nodelist = list(nodeset)
  333. for i, n1 in enumerate(nodelist[:-1]):
  334. for n2 in nodelist[i + 1:]:
  335. if (self.serialize_actions(n1, n2) or
  336. self.inconsistent_effects_mutex(n1, n2) or
  337. self.interference_mutex(n1, n2) or
  338. self.competing_needs_mutex(n1, n2)):
  339. mutexify(n1, n2)
  340. def serialize_actions(self, node_a1: PgNode_a, node_a2: PgNode_a) -> bool:
  341. '''
  342. Test a pair of actions for mutual exclusion, returning True if the
  343. planning graph is serial, and if either action is persistent; otherwise
  344. return False. Two serial actions are mutually exclusive if they are
  345. both non-persistent.
  346. :param node_a1: PgNode_a
  347. :param node_a2: PgNode_a
  348. :return: bool
  349. '''
  350. #
  351. if not self.serial:
  352. return False
  353. if node_a1.is_persistent or node_a2.is_persistent:
  354. return False
  355. return True
  356. def inconsistent_effects_mutex(self, node_a1: PgNode_a,\
  357. node_a2: PgNode_a) -> bool:
  358. '''
  359. Test a pair of actions for inconsistent effects, returning True if
  360. one action negates an effect of the other, and False otherwise.
  361. :param node_a1: PgNode_a
  362. :param node_a2: PgNode_a
  363. :return: bool
  364. '''
  365. return bool(
  366. # Are actions from node 1 negated by actions in node 2?
  367. set(node_a1.action.effect_add) & set(node_a2.action.effect_rem) |
  368. # Are actions from node 2 negated by actions in node 1?
  369. set(node_a2.action.effect_add) & set(node_a1.action.effect_rem)
  370. )
  371. def interference_mutex(self, node_a1: PgNode_a, node_a2: PgNode_a) -> bool:
  372. '''
  373. Test a pair of actions for mutual exclusion, returning True if the
  374. effect of one action is the negation of a precondition of the other.
  375. :param node_a1: PgNode_a
  376. :param node_a2: PgNode_a
  377. :return: bool
  378. '''
  379. return bool(
  380. # Are actions in node 1 the negation of a precondition of node 2?
  381. set(node_a1.action.effect_add) & set(node_a2.action.precond_neg) |
  382. set(node_a1.action.effect_rem) & set(node_a2.action.precond_pos) |
  383. # Are actions in node 2 the negation of a precondition of node 1?
  384. set(node_a2.action.effect_add) & set(node_a1.action.precond_neg) |
  385. set(node_a2.action.effect_rem) & set(node_a1.action.precond_pos)
  386. )
  387. def competing_needs_mutex(self, node_a1: PgNode_a,\
  388. node_a2: PgNode_a) -> bool:
  389. '''
  390. Test a pair of actions for mutual exclusion, returning True if one of
  391. the precondition of one action is mutex with a precondition of the
  392. other action.
  393. :param node_a1: PgNode_a
  394. :param node_a2: PgNode_a
  395. :return: bool
  396. '''
  397. for a1_parent in node_a1.parents:
  398. for a2_parent in node_a2.parents:
  399. if a1_parent.is_mutex(a2_parent):
  400. return True
  401. return False
  402. def update_s_mutex(self, nodeset: set):
  403. ''' Determine and update sibling mutual exclusion for S-level nodes
  404. Mutex action tests section from 3rd Ed. 10.3 or 2nd Ed. 11.4
  405. A mutex relation holds between literals at a given level
  406. if either of the two conditions hold between the pair:
  407. Negation
  408. Inconsistent support
  409. :param nodeset: set of PgNode_a (siblings in the same level)
  410. :return:
  411. mutex set in each PgNode_a in the set is appropriately updated
  412. '''
  413. nodelist = list(nodeset)
  414. for i, n1 in enumerate(nodelist[:-1]):
  415. for n2 in nodelist[i + 1:]:
  416. if self.negation_mutex(n1, n2) or\
  417. self.inconsistent_support_mutex(n1, n2):
  418. mutexify(n1, n2)
  419. def negation_mutex(self, node_s1: PgNode_s, node_s2: PgNode_s) -> bool:
  420. '''
  421. Test a pair of state literals for mutual exclusion, returning True if
  422. one node is the negation of the other, and False otherwise.
  423. :param node_s1: PgNode_s
  424. :param node_s2: PgNode_s
  425. :return: bool
  426. '''
  427. # Verify both state represent the same symbol
  428. is_same_symbol = node_s1.symbol == node_s2.symbol
  429. # Verify 1 state is the negation of the other
  430. is_negation = node_s1.is_pos != node_s2.is_pos
  431. return is_same_symbol and is_negation
  432. def inconsistent_support_mutex(self, node_s1: PgNode_s, node_s2: PgNode_s):
  433. '''
  434. Test a pair of state literals for mutual exclusion, returning True if
  435. there are no actions that could achieve the two literals at the same
  436. time, and False otherwise. In other words, the two literal nodes are
  437. mutex if all of the actions that could achieve the first literal node
  438. are pairwise mutually exclusive with all of the actions that could
  439. achieve the second literal node.
  440. :param node_s1: PgNode_s
  441. :param node_s2: PgNode_s
  442. :return: bool
  443. '''
  444. for s1_parent in node_s1.parents:
  445. for s2_parent in node_s2.parents:
  446. if not s1_parent.is_mutex(s2_parent):
  447. return False
  448. return True
  449. def h_levelsum(self) -> int:
  450. '''The sum of the level costs of the individual goals
  451. (admissible if goals independent)
  452. :return: int
  453. '''
  454. level_sum = 0
  455. goals = self.problem.goal
  456. s_levels = self.s_levels
  457. for goal in goals:
  458. node = PgNode_s(goal, True)
  459. s_levels_list = enumerate(s_levels)
  460. for level, s_nodes in s_levels_list:
  461. if node in s_nodes:
  462. level_sum += level
  463. break
  464. return level_sum