def problem(distancemat, agentcount, verbose=True): agents = [i for i in range(agentcount)] trashcount = len(distancemat) - agentcount trash_cans = [i + agentcount for i in range(trashcount)] agentDict = dict([(i,0) for i in agents]) domain = Domain(( Action( "Check", # Send agent A1 from T1 to pick up trash at T2 parameters=( ("agent", "A1"), ("trash_can", "T1"), ("trash_can", "T2"), ), preconditions=( ("at", "A1", "T1"), ("unchecked", "T2"), ), effects=( # A1 is no longer at T1 neg(("at", "A1", "T1")), # A1 is now at T2 ("at", "A1", "T2"), # T2 is checked. ("checked", "T2"), neg(("unchecked", "T2")), ) ), )) problem = Problem( domain, { # List of all agents "agent": agents, # list of trash cans. Note: Starting positions are # treated as trash cans. "trash_can": [i for i in range(len(distancemat))], }, init=[("at", i, i) for i in agents] + \ [("unchecked", i) for i in trash_cans], goal=[("checked", i) for i in trash_cans] ) # Heuristics based on the agent that has travelled the farthest def heuristic(state): # copy prepared table agent2cost = agentDict.copy() # calculate cost for a in [action.sig for action in state.plan()]: agent2cost[a[1]] += distancemat[a[2]][a[3]] cost = max(agent2cost.values()) #heur = ? return cost return planner(problem, heuristic=heuristic, verbose=verbose)
def define_domain(city): a1 = Action('switch-priority', parameters=(('suburb', 'S1'), ('suburb', 'S2')), preconditions=(('prioritised', 'S1'), ), effects=(neg(('prioritised', 'S1')), ('prioritised', 'S2'), ('-=', ('total-cars', 'S2'), city.get_cars_out_from_action)), external_actor=city, unique=True) a2 = Action('extend-priority', parameters=(('suburb', 'S'), ), preconditions=(('prioritised', 'S'), ), effects=(('-=', ('total-cars', 'S'), city.get_cars_out_from_action), ), external_actor=city) return Domain((a1, a2))
def problem(verbose): domain = Domain(( #ready-for-battle & defencable -> enemy is defenced Action( 'enemy-defenced', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('defencable', '_state'), ('ready-for-battle', ''), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=( neg(('character_prev_state', '_prev_state')), neg(('character_state', '_state')), ('character_prev_state', '_state'), ('character_state', 'defenced'), ('use-defence', ''), ), ), #ready-for-battle & exhaustable -> enemy is exhausted Action( 'enemy-exhausted', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('exhaustable', '_state'), ('ready-for-battle', ''), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=( neg(('character_prev_state', '_prev_state')), neg(('character_state', '_state')), ('character_state', 'exhausted'), ('character_prev_state', '_state'), ), ), #ready-for-battle & ignitable -> enemy is ignited Action( 'enemy-ignited', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('ignitable', '_state'), ('ready-for-battle', ''), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=( neg(('character_prev_state', '_prev_state')), neg(('character_state', '_state')), ('character_prev_state', '_state'), ('character_state', 'ignited'), ('use-ignite', ''), ), ), # ready-for-battle & electric ready & electric shockable -> enemy is electric shocked Action( 'electric-shock', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('electric-shockable', '_state', '_prev_state'), ('electric-ready', ''), ('ready-for-battle', ''), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=( neg(('character_prev_state', '_prev_state')), neg(('character_state', '_state')), ('character_prev_state', '_state'), ('character_state', 'electric-shocked'), ), ), # ready-for-battle & electric preparable -> electric is prepared Action( 'electric-ready-perfectly', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('electric-preparable', '_state'), ('ready-for-battle', ''), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=(('electric-ready', ''), ), ), # idle -> ready for battle Action( 'ready-for-battle', parameters=( ('state', '_state'), ('state', '_prev_state'), ), preconditions=( ('character_state', 'idle'), ('character_state', '_state'), ('character_prev_state', '_prev_state'), ), effects=(('ready-for-battle', ''), ), ), )) problem = Problem( domain, { 'state': ('electric-shocked', 'idle', 'defenced', 'ignited', 'exhausted', 'NONE'), }, init=( ('electric-shockable', 'exhausted', 'defenced' ), #defenced -> exghausted -> now it can use electric shock ('electric-shockable', 'exhausted', 'ignited' ), #ignited -> exghausted -> now it can use electric shock ('electric-preparable', 'ignited'), #prepare electric when enemy was ignited ('electric-preparable', 'defenced'), #prepare electric when enemy was exhausted ('defencable', 'idle'), ('ignitable', 'idle'), ('exhaustable', 'ignited'), ('exhaustable', 'defenced'), ('character_state', 'idle'), ('character_prev_state', 'NONE'), ), goal=( ('character_state', 'electric-shocked'), # case 1 use ignite ('use-ignite', ''), # 1. ready for battle # 2. ignite to enemy # 3. ready electric # 4. enemy was exhausted # 5. electric shock to enemy ################ # case 2 use defence # ('use-defence',''), # 1. ready for battle # 2. enemy was defenced # 3. ready electric # 4. enemy was exhausted # 5. electric shock to enemy )) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def problem(verbose): domain = Domain(( Action( 'cross-right', preconditions=( ('at', 'left-bank'), ('>', ('occupants', ), 0), ), effects=( neg(('at', 'left-bank')), ('at', 'right-bank'), ), ), Action( 'cross-left', preconditions=( ('at', 'right-bank'), ('>', ('occupants', ), 0), ), effects=( neg(('at', 'right-bank')), ('at', 'left-bank'), ), ), Action( 'onboard-cannibal', parameters=(('location', 'l'), ), preconditions=( ('at', 'l'), ('>', ('cannibals', 'l'), 0), ('<', ('occupants', ), 2), ), effects=( ('-=', ('cannibals', 'l'), 1), ('+=', ('cannibals', 'boat'), 1), ('+=', ('occupants', ), 1), ), ), Action( 'onboard-missionary', parameters=(('location', 'l'), ), preconditions=( ('at', 'l'), ('>', ('missionaries', 'l'), 0), ('>', ('missionaries', 'l'), ('cannibals', 'l')), ('<', ('occupants', ), 2), ), effects=( ('-=', ('missionaries', 'l'), 1), ('+=', ('missionaries', 'boat'), 1), ('+=', ('occupants', ), 1), ), ), Action( 'offboard-cannibal', parameters=(('location', 'l'), ), preconditions=( ('at', 'l'), ('>', ('cannibals', 'boat'), 0), ('>', ('missionaries', 'l'), ('cannibals', 'l')), ), effects=( ('-=', ('cannibals', 'boat'), 1), ('-=', ('occupants', ), 1), ('+=', ('cannibals', 'l'), 1), ), ), Action( 'offboard-missionary', parameters=(('location', 'l'), ), preconditions=( ('at', 'l'), ('>', ('missionaries', 'boat'), 0), ), effects=( ('-=', ('missionaries', 'boat'), 1), ('-=', ('occupants', ), 1), ('+=', ('missionaries', 'l'), 1), ), ), )) problem = Problem(domain, { 'location': ('left-bank', 'right-bank'), }, init=( ('at', 'left-bank'), ('=', ('missionaries', 'boat'), 0), ('=', ('cannibals', 'boat'), 0), ('=', ('occupants', ), 0), ('=', ('missionaries', 'left-bank'), 3), ('=', ('cannibals', 'left-bank'), 3), ('=', ('missionaries', 'right-bank'), 0), ('=', ('cannibals', 'right-bank'), 0), ), goal=( ('=', ('missionaries', 'right-bank'), 3), ('=', ('cannibals', 'right-bank'), 3), )) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
parameters=( ('object_name', 'obj_c'), ('gripper_name', 'gripper'), ('object_position', 'o_x'), ('object_position', 'o_y'), ('object_position', 'o_z'), ('gripper_position', 'g_x'), ('gripper_position', 'g_y'), ('gripper_position', 'g_z'), ), preconditions=( ('at', 'obj_c', 'o_x', 'o_y', 'o_z'), ('at', 'gripper', 'g_x', 'g_y', 'g_z'), ), effects=( neg(('at', 'gripper', 'g_x', 'g_y', 'g_z')), ('at', 'gripper', 'o_x', 'o_y', 'o_z'), ), ) pushButton = Action( 'push_button', parameters=( ('button_name', 'button_1'), ('gripper_name', 'gripper'), ('button_position', 'b_x'), ('button_position', 'b_y'), ('button_position', 'b_z'), ('gripper_position', 'g_x'), ('gripper_position', 'g_y'), ('gripper_position', 'g_z'),
def problem(verbose): domain = Domain(( Action( 'move', parameters=( ('position', 'wp_prec'), ('position', 'wp_effe'), ), preconditions=( ('connect', 'wp_prec', 'wp_effe'), ('base', 'wp_prec'), ('arm', 'unreach'), ), effects=( neg(('base', 'wp_prec')), ('base', 'wp_effe'), ), ), Action( 'reach', parameters=( ('position', 'wp'), ('location', 'loc'), ), preconditions=( ('reachable', 'wp', 'loc'), ('base', 'wp'), ('arm', 'unreach'), ), effects=( neg(('arm', 'unreach')), ('arm', 'reach'), ), ), Action( 'grip', parameters=( ('position', 'wp'), ('object', 'obj'), ('location', 'loc'), ), preconditions=( ('locate', 'obj', 'loc'), ('ungripped', 'obj'), ('reachable', 'wp', 'loc'), ('base', 'wp'), ('arm', 'reach'), ), effects=( neg(('ungripped', 'obj')), ('gripped', 'obj'), ), ), Action( 'unreach', parameters=(), preconditions=(('arm', 'reach'), ), effects=( ('arm', 'unreach'), neg(('arm', 'reach')), ), ), Action( 'reach-when-gripping', parameters=( ('position', 'wp'), ('location', 'loc'), ('object', 'obj'), ), preconditions=( ('reachable', 'wp', 'loc'), ('base', 'wp'), ('gripped', 'obj'), ('arm', 'unreach'), ), effects=( neg(('arm', 'unreach')), ('arm', 'reach'), ('locate', 'obj', 'loc'), ), ), Action( 'ungrip', parameters=(('object', 'obj'), ), preconditions=(('gripped', 'obj'), ), effects=( neg(('gripped', 'obj')), ('ungripped', 'obj'), ), ), )) problem = Problem( domain, { 'position': ('wp1', 'wp2', 'wp3', 'wp4'), 'location': ('loc1', 'loc2', 'loc3'), 'object': ('obj1', 'obj2'), }, init=( ('connect', 'wp4', 'wp3'), ('connect', 'wp3', 'wp2'), ('connect', 'wp2', 'wp1'), ('connect', 'wp1', 'wp3'), ('reachable', 'wp1', 'loc1'), ('reachable', 'wp3', 'loc3'), ('base', 'wp4'), ('locate', 'obj1', 'loc1'), ('ungripped', 'obj1'), ('arm', 'unreach'), #('locate','obj2','loc2'), #('ungripped','obj2'), ), goal=( #('base','wp1'), #('gripped','obj1'), ('locate', 'obj1', 'loc3'), ('ungripped', 'obj1'), )) plan = planner(problem, verbose=verbose) #action_string = [] rank = 1 rank_return = rank if plan is None: print('No Plan!') else: for action in plan: str_arr = StringArray() i = 1 str_arr.strings.append(str(rank)) for arg in action.sig: str_arr.strings.append(str(arg)) print(str_arr) flag = 'unfinish' while (flag != 'finish' or rank_return != rank): #finish and rank pub.publish(str_arr) #print(str_arr,i) i = i + 1 #print(listening.action_state.strings,str_arr) if listening.action_state.strings: #empty check flag = listening.action_state.strings[1] rank_return = int(listening.action_state.strings[0]) #while listening.action_state.strings[1] == 'finish':{} #may get previous 'finish', wait for a new unfinish if rospy.is_shutdown(): return 0 #r.sleep() print('finish', i) rank = rank + 1 return 0
def find_a_path(hand_start_node_id, object_start_node_id, graph, goal_node_labels, verbose=False): locations = ['l' + str(i) for i in range(len(graph.nodes))] connections = [('connected', 'l' + str(e.node_id_start), 'l' + str(e.node_id_end)) for e in graph.edges] grasping_locations = [('is_grasping_location', 'l' + str(i)) for i, n in enumerate(graph.nodes) if n.label in goal_node_labels or n.label + '_' + str(i) in goal_node_labels] # define possible actions domain = pyddl.Domain(( pyddl.Action( 'move_hand', parameters=( ('location', 'from'), ('location', 'to'), ), preconditions=( ('hand_at', 'from'), ('connected', 'from', 'to'), ), effects=( pyddl.neg(('hand_at', 'from')), ('hand_at', 'to'), ), ), pyddl.Action( 'move_object', parameters=( ('location', 'from'), ('location', 'to'), ), preconditions=( ('hand_at', 'from'), ('object_at', 'from'), ('connected', 'from', 'to'), ), effects=( pyddl.neg(('hand_at', 'from')), pyddl.neg(('object_at', 'from')), ('hand_at', 'to'), ('object_at', 'to'), ), ), pyddl.Action( 'grasp_object', parameters=(('location', 'l'), ), preconditions=(('hand_at', 'l'), ('object_at', 'l'), ('is_grasping_location', 'l')), effects=(('grasped', 'object'), ), ), )) # each node in the graph is a location problem = pyddl.Problem(domain, { 'location': locations, }, init=[ ('hand_at', 'l' + str(hand_start_node_id)), ('object_at', 'l' + str(object_start_node_id)), ] + connections + grasping_locations, goal=(('grasped', 'object'), )) plan = pyddl.planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action) return plan
# logic states predicates focus = "focus" # set focus on a block block in_hand = "in_hand" # a block is in hand (block, gripper) block_free = "block_free" # condition a block is graspable hand_empty = "hand_empty" # condition a hand is free b_on_b = "block_on_block" # condition block is on block actions = [ Action("Grab_Block", parameters=( (type_gripper, "g"), (type_block, "b"), ), preconditions=((hand_empty, "g"), (block_free, "b")), effects=( neg((hand_empty, "g")), (in_hand, "b", "g"), ), unique=True), Action("Place_Block", parameters=((type_gripper, "g"), (type_block, "b"), (type_block, "b_placed")), preconditions=((in_hand, "b", "g"), (block_free, "b_placed")), effects=( (b_on_b, "b", "b_placed"), neg((block_free, "b_placed")), neg((in_hand, "b", "g")), (hand_empty, "g"), ), unique=True) ]
def problem(verbose): domain = Domain( ( Action( "cross-right", preconditions=(("at", "left-bank"), (">", ("occupants",), 0)), effects=(neg(("at", "left-bank")), ("at", "right-bank")), ), Action( "cross-left", preconditions=(("at", "right-bank"), (">", ("occupants",), 0)), effects=(neg(("at", "right-bank")), ("at", "left-bank")), ), Action( "onboard-cannibal", parameters=(("location", "l"),), preconditions=(("at", "l"), (">", ("cannibals", "l"), 0), ("<", ("occupants",), 2)), effects=(("-=", ("cannibals", "l"), 1), ("+=", ("cannibals", "boat"), 1), ("+=", ("occupants",), 1)), ), Action( "onboard-missionary", parameters=(("location", "l"),), preconditions=( ("at", "l"), (">", ("missionaries", "l"), 0), (">", ("missionaries", "l"), ("cannibals", "l")), ("<", ("occupants",), 2), ), effects=( ("-=", ("missionaries", "l"), 1), ("+=", ("missionaries", "boat"), 1), ("+=", ("occupants",), 1), ), ), Action( "offboard-cannibal", parameters=(("location", "l"),), preconditions=( ("at", "l"), (">", ("cannibals", "boat"), 0), (">", ("missionaries", "l"), ("cannibals", "l")), ), effects=(("-=", ("cannibals", "boat"), 1), ("-=", ("occupants",), 1), ("+=", ("cannibals", "l"), 1)), ), Action( "offboard-missionary", parameters=(("location", "l"),), preconditions=(("at", "l"), (">", ("missionaries", "boat"), 0)), effects=( ("-=", ("missionaries", "boat"), 1), ("-=", ("occupants",), 1), ("+=", ("missionaries", "l"), 1), ), ), ) ) problem = Problem( domain, {"location": ("left-bank", "right-bank")}, init=( ("at", "left-bank"), ("=", ("missionaries", "boat"), 0), ("=", ("cannibals", "boat"), 0), ("=", ("occupants",), 0), ("=", ("missionaries", "left-bank"), 3), ("=", ("cannibals", "left-bank"), 3), ("=", ("missionaries", "right-bank"), 0), ("=", ("cannibals", "right-bank"), 0), ), goal=(("=", ("missionaries", "right-bank"), 3), ("=", ("cannibals", "right-bank"), 3)), ) plan = planner(problem, verbose=verbose) if plan is None: print("No Plan!") else: for action in plan: print(action)
def problem(verbose): domain = Domain(( # 일반 공격 : me와 enemy 모두 가능한 액션, 현재 턴(now_turn)인 공격자가 상대방(prev_turn)의 hp를 20 깎음 Action( 'normal-attack', parameters=( ('turn', 't'), ('turn', 'prev_t'), ), preconditions=( ('now_turn', 't'), ('prev_turn', 'prev_t'), ), effects=( neg(('now_turn', 't')), neg(('prev_turn', 'prev_t')), ('now_turn', 'prev_t'), ('prev_turn', 't'), ('+=', ('hp', 'prev_t'), -20), ('-=', ('damaged', 'prev_t'), ('damaged', 'prev_t')), ('+=', ('damaged', 'prev_t'), -20), ), ), # 마법 공격 : me와 enemy 모두 가능한 액션, 현재 턴(now_turn)인 공격자가 상대방(prev_turn)의 hp를 35 깎고, mp를 40 소모 # mp가 40 이상일 때만 사용 가능 Action( 'magic-attack', parameters=( ('turn', 't'), ('turn', 'prev_t'), ), preconditions=( ('now_turn', 't'), ('prev_turn', 'prev_t'), ('>=', ('mp', 't'), 40), ), effects=( neg(('now_turn', 't')), neg(('prev_turn', 'prev_t')), ('now_turn', 'prev_t'), ('prev_turn', 't'), ('+=', ('hp', 'prev_t'), -35), ('+=', ('mp', 't'), -40), ('-=', ('damaged', 'prev_t'), ('damaged', 'prev_t')), ('+=', ('damaged', 'prev_t'), -35), ), ), # hp 회복 : me 만 사용 가능한 스킬, me의 mp를 60 소모하여, hp를 55 회복 함 # mp가 60 이상일 때만 사용 가능, 현재 hp가 0 보다 클 때만 사용 가능(부활 불가) Action( 'heal-me', preconditions=( ('now_turn', 'me'), ('prev_turn', 'enemy'), ('>', ('hp', 'me'), 0), ('>=', ('mp', 'me'), 60), ), effects=( neg(('now_turn', 'me')), neg(('prev_turn', 'enemy')), ('now_turn', 'enemy'), ('prev_turn', 'me'), ('+=', ('hp', 'me'), 55), ('+=', ('mp', 'me'), -60), ), ), # mp 회복 : me 만 사용 가능한 스킬, me의 mp를 40 회복 함 Action( 'charge-my-magicka', preconditions=( ('now_turn', 'me'), ('prev_turn', 'enemy'), ), effects=( neg(('now_turn', 'me')), neg(('prev_turn', 'enemy')), ('now_turn', 'enemy'), ('prev_turn', 'me'), ('+=', ('mp', 'me'), 40), ), ), # 반격 : me 만 사용 가능한 스킬, me의 mp를 60 소모하여, 바로 직전 턴에 enemy 에게 받은 데미지 만큼 hp를 회복함 # mp가 60 이상일 때만 사용 가능, 직전 턴에 받은 데미지를 회복한 hp가 0 보다 커야만 사용 가능 Action( 'reflect-enemy-attack', preconditions=( ('now_turn', 'me'), ('prev_turn', 'enemy'), ('>', ('hp', 'me'), ('damaged', 'me')), ('>=', ('mp', 'me'), 60), ), effects=( neg(('now_turn', 'me')), neg(('prev_turn', 'enemy')), ('now_turn', 'enemy'), ('prev_turn', 'me'), ('-=', ('hp', 'me'), ('damaged', 'me')), ('+=', ('hp', 'enemy'), ('damaged', 'me')), ('+=', ('mp', 'me'), -60), ('-=', ('damaged', 'me'), ('damaged', 'me')), ), ), )) problem = Problem( domain, { 'turn': ('me', 'enemy'), # 가능한 turn Domain }, # hp:100, mp:80 인 enemy와 hp:50, mp:100인 me 중 enemy의 선공으로 게임을 시작하는 초기 state init=( ('now_turn', 'enemy'), # enemy 선공 ('prev_turn', 'me'), # prev_turn 이지만 init 단계이므로 다음 턴 공격자인 me ('=', ('hp', 'me'), 50), # me의 시작 hp ('=', ('mp', 'me'), 100), # me의 시작 mp ('=', ('damaged', 'me'), 0), # me가 입은 데미지 초기 값, reflect-enemy-attack 액션을 통해 받은 데미지를 회복하기 위해 필요 ('=', ('hp', 'enemy'), 100), # enemy의 시작 hp ('=', ('mp', 'enemy'), 80), # enemy의 시작 mp ('=', ('damaged', 'enemy'), 0), # enemy가 입은 데미지 초기 값, enemy는 reflect-enemy-attack 액션을 사용할 수 없지만, domain parameter로 인한 런타임 에러를 막기위해 필요 ), # goal test 직전인 마지막 액션의 turn이 me이고, 생존 상태의 me가 enemy를 쓰러트린 state # me가 생존한 상태에서, enemy를 쓰러트리는 state goal=( ('prev_turn', 'me'), ('>', ('hp', 'me'), 0), ('<=', ('hp', 'enemy'), 0), ) ) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
focus = "focus" # set focus on a block block in_hand = "in_hand" # a block is in hand (block, gripper) block_free = "block_free" # condition a block is graspable hand_empty = "hand_empty" # condition a hand is free b_on_b = "block_on_block" # condition block is on block b_at_goal = "b_at_goal" actions = [ Action("Grab", parameters=( (type_gripper, "g"), (type_block, "b"), ), preconditions=((hand_empty, "g"), (block_free, "b")), effects=( neg((hand_empty, "g")), (in_hand, "b", "g"), ), unique=True), Action("PlaceGoal", parameters=( (type_gripper, "g"), (type_block, "b"), ), preconditions=((in_hand, "b", "g"), ), effects=( (b_at_goal, "b"), neg((in_hand, "b", "g")), (hand_empty, "g"), ), unique=True),
def effect(self, *args): return (self.condition(*args)[0], pyddl.neg(self.neg().condition(*args)[0]))
def effect(self, *args): return (pyddl.neg(self.neg().effect(*args)[0]), )
def problem(verbose, initialState, endState, ValueExchangeMap, mandatoryTimmedTasks, deadline, timeout, mode=1): timeoutStart = int(round(time.time() * 1000)) tasks = tuple([key for key, val in ValueExchangeMap.items()]) listOfLocations = list(set([i['location'] for key, i in ValueExchangeMap.items()])) taskactionsList = [] mandatoryTasksList = [] for idx, mandatoryTasks in enumerate(mandatoryTimmedTasks): startTime = mandatoryTasks[0] endTime = mandatoryTasks[1] startLoc = mandatoryTasks[2] endLoc = mandatoryTasks[3] movable = mandatoryTasks[4] effectResources = mandatoryTasks[5] parameters = [ # ('location', 'l'), ] # ([('<=', ('t',), startTime)] if not movable else []) + \ preconditions = [('>=', i[1], i[2]) for i in effectResources if i[0] == '-='] + \ ([('<=', ('t',), startTime)] if not movable else []) + \ [('=', ('mand',), idx)] + \ ([('at', startLoc)] if startLoc not in ['Undefined', 'Moving'] else []) effects = effectResources + \ ([('==', ('t',), endTime)] if not movable else [('+=', ('t',), endTime - startTime)]) + \ [('+=', ('mand',), 1)] + \ ([(neg(('at', loc)) if loc != endLoc else ('at', endLoc)) for loc in listOfLocations] if endLoc not in ['Undefined', 'Moving'] else []) thisaction = Action( str('#' + str(idx)), parameters=tuple(parameters), preconditions=tuple(preconditions), effects=tuple(effects)) taskactionsList.append(thisaction) mandatoryTasksList.append(effectResources) for task in tasks: for idxin, inMode in enumerate(ValueExchangeMap[task]['in']): for idxout, outMode in enumerate(ValueExchangeMap[task]['out']): location = ValueExchangeMap[task]['location'] parameters = [ # ('location', 'l'), ] preconditions = [('<=', ('t',), int(deadline - int(ValueExchangeMap[task]['time'])))] + \ [('>=', (key,), -int(inMode[key])) for key, val in inMode.items()] + \ [('>=', ('t',), 0)] + \ ([('at', location)] if location not in ['Undefined', 'Moving'] else []) effects = [('+=', (key,), int(inMode[key])) for key, val in inMode.items()] + \ [('+=', (key,), int(outMode[key])) for key, val in outMode.items()] + \ [('+=', ('t',), ValueExchangeMap[task]['time'])] + \ ([(neg(('at', loc)) if loc != ValueExchangeMap[task]['moveto'] else ( 'at', ValueExchangeMap[task]['moveto'])) for loc in listOfLocations if loc not in ['Undefined', 'Moving']] if 'moveto' in ValueExchangeMap[task] else []) thisaction = Action( (str(task) if (idxin + idxout == 0) else (str(task) + ' [' + str(idxin) + '_' + str(idxout) + ']')), parameters=tuple(parameters), preconditions=tuple(preconditions) if len(preconditions) > 0 else ((),), effects=tuple(effects)) taskactionsList.append(thisaction) domain = Domain(tuple(taskactionsList)) problem = Problem( domain, { # 'location': tuple(listOfLocations) }, init=initialState, goal=endState ) def checkCompleteLevel(state, alllevels): statecopy = copy.deepcopy(state.f_dict) planLevel = state.f_dict[('mand',)] realLevel = planLevel progressAbovePlanLevel = 0 if planLevel == len(mandatoryTasksList): return planLevel, 0 for i in range(planLevel, (len(mandatoryTasksList) if alllevels else (planLevel + 1))): for req in mandatoryTasksList[i]: if req[0] == '-=' and req[1] in statecopy: if statecopy[req[1]] > req[2]: progressAbovePlanLevel += req[2] else: progressAbovePlanLevel += statecopy[req[1]] # apply mandatoryTasks and check for req in mandatoryTasksList[i]: if req[0] == '-=': statecopy[req[1]] -= req[2] elif req[0] == '+=': statecopy[req[1]] += req[2] if not all( [(val >= 0) for key, val in statecopy.items() if key in [j[1] for j in mandatoryTasksList[i]]]): break # continue else: realLevel = i + 1 return realLevel, progressAbovePlanLevel def checkCompletedProgress(planLevel): prevProgress = 0 for i in range(0, planLevel): prevProgress += sum([(i[2] if i[2] > 0 else 0) for i in mandatoryTasksList[i]]) return prevProgress def getPlanByState(state): tmpstate = state tmpplan = [] while tmpstate.predecessor is not None: tmpplan.append(tmpstate.predecessor[1].name) tmpstate = tmpstate.predecessor[0] return list(reversed(tmpplan)) def dependancy_heuristic(state): if int(round(time.time() * 1000)) - timeoutStart > timeout: raise planLevel = state.f_dict[('mand',)] if planLevel == 0: return 0 # Current Plan planCurrent = getPlanByState(state) # Progress to next level realLevel, realProgressOnThisLevel = checkCompleteLevel(state, alllevels=False) # Progress to all following levels realLevel, realProgressOnAllLevel = checkCompleteLevel(state, alllevels=True) excessT = '' # Check if time of this level exceeds limit if planLevel > 0 and planLevel < len(mandatoryTimmedTasks): progressAbovePlanTime = sum( [ValueExchangeMap[key]['time'] for key in planCurrent[planCurrent.index('#' + str(planLevel - 1)) + 1:]]) excessT = planCurrent[:planCurrent.index('#' + str(planLevel - 1))] if progressAbovePlanTime > ( mandatoryTimmedTasks[planLevel][0] - mandatoryTimmedTasks[planLevel - 1][1]): realLevel -= 1 planLevel -= 1 realProgressOnThisLevel = 0 realProgressOnAllLevel = 0 # Sum of planned tasks planned = sum( [1 for key in planCurrent[:planCurrent.index('#' + str(planLevel - 1)) + 1] if key.startswith('MOVING')]) if planLevel > 0 else 0 # Sum of resolved resource prevProgress = checkCompletedProgress(planLevel) if mode == 1: # Early the better dist = (planLevel + planned) + prevProgress + realProgressOnAllLevel elif mode == 2: # Early the better Aggressive dist = planLevel + (prevProgress + realProgressOnAllLevel) * 2 elif mode == 3: # Faster the better dist = (planned + planLevel) * 100000 + (realProgressOnThisLevel) else: pass print( str(dist) + ' ' + str(planLevel) + ' ' + str(realLevel) + ' ' + str(prevProgress) + ' ' + str( realProgressOnThisLevel) + ' ' + str(realProgressOnAllLevel) + ' ' + str(planCurrent) ) # + ' ' + str(getPlanByState(state)) return -dist plan = planner(problem, heuristic=dependancy_heuristic, verbose=verbose) resultPlan = [] loc = 'Undefined' for action in plan: duration = 0 for eff in action.add_effects: if eff[0] == 'at': loc = eff[1] for numeff in action.num_effects: if numeff[0] == (('t'),): duration = numeff[1] resultPlan.append([action.name, duration, (loc if (not action.name.startswith('MOVING:')) else 'Moving')]) return resultPlan
def problem(verbose): domain = Domain(( Action( #학교에 갈 짐을 쌉니다. 교재와 펜을 챙겨야 합니다. 'pack', parameters=( ('things', 'th'), ), preconditions=( ('at', 'home'), ), effects=( ('packed', 'th'), ), ), Action( #교재와 펜을 챙기면 밖으로 나올 수 있습니다. 피시방을 가거나 학교에 갑니다. 'walk', parameters=( ('locations', 'loc'), ), preconditions=( ('packed', 'textbook'), ('packed', 'pen'), ), effects=( ('at', 'loc'), ), ), Action( #맞는 교실을 갑니다. 지금은 인공지능 수업을 가야할 때 입니다. 'goclass', parameters=( ('buildings', 'bui'), ), preconditions=( ('at', 'waytoschool'), ), effects=( ('at', 'bui'), neg(('at','waytoschool')), ), ), Action( #가지고 온 것들을 엽니다. 인공지능 수업에 있고 교재가 필요합니다. 'seetextbook', parameters=( ('things', 'th'), ), preconditions=( ('at', 'aiclass'), ('packed','textbook') ), effects=( neg(('packed', 'textbook')), ('open','th') ), ), Action( #수업을 듣습니다. 교재를 핀 상태여야 합니다. 'takeclass', parameters=( ('things', 'th'), ), preconditions=( ('open', 'textbook'), ), effects=( ('study', 'th'), ), ), Action( #수업이 끝나면 물건들을 닫고 마무리합니다. 'endclass', parameters=( ('things', 'th'), ), preconditions=( ('study', 'textbook'), ), effects=( ('closed', 'th'), ), ), )) problem = Problem( domain, { 'things': ('textbook', 'comicbook','pen'), 'locations': ('PCroom', 'waytoschool'), 'buildings': ('aiclass', 'algorithmclass'), }, init=( ('at', 'home'), ), goal=( ('closed', 'textbook'), ) ) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def getProblem(self): init = list() #list predikatov #list pozicii a co sa tam nachadza for i in range(self.__maxX): for j in range(self.__maxY): if (self.__map[(i, j)] == '#'): init.append(["at", str(i), str(j), '#']) elif (self.__map[(i, j)] == 'A'): init.append(["at", str(i), str(j), 'A']) init.append(["at", str(i), str(j), "blank"]) elif (self.__map[(i, j)] == 'W'): init.append(["at", str(i), str(j), 'W']) elif (self.__map[(i, j)] == 'g'): init.append(["at", str(i), str(j), 'g']) init.append(["at", str(i), str(j), "blank"]) elif (self.__map[(i, j)] == ' '): init.append(["at", str(i), str(j), "blank"]) elif (self.__map[(i, j)] == '@'): #startovna pozicia init.append(["at", str(i), str(j), '@']) #inicializacia poctu zlata a sipov init.append(['=', ('arrow', ), 0]) init.append(['=', ('gold', ), 0]) #decrements for i in range(max(self.__maxX, self.__maxY)): init.append(["inc", str(i), str(i + 1)]) init.append(["dec", str(i + 1), str(i)]) # goal = list() # goal.append(['at', str(self.__startX), str(self.__startY), '@']) # goal.append(['=', ('gold',), self.__totalGold]) # goal = list((['at', str(self.__startX), str(self.__startY), '@'],['=', ('gold',), self.__totalGold])) goal = list() goal.append(('at', str(self.__startX), str(self.__startY), '@')) goal.append(('=', ('gold', ), self.__totalGold)) positions = list() #lst stringov, vsetkych moznych pozicii (iba jednu poziciu, #teda max z Y a X) for i in range(max(self.__maxX, self.__maxY)): positions.append(["position", str(i)]) #treba si pamatat poziciu lovca - zadefinovat predikat kde prave stoji print(init) print(goal) domain = pyddl.Domain(( Action( 'move-up', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'by', 'py'), ('at', 'px', 'by', 'blank'), ), effects=( neg(('at', 'px', 'by', 'blank')), neg(('at', 'px', 'py', '@')), ('at', 'px', 'py', 'blank'), ('at', 'px', 'by', '@'), ), ), Action( 'move-down', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('inc', 'by', 'py'), ('at', 'px', 'py', 'blank'), ), effects=( neg(('at', 'px', 'by', "blank")), neg(('at', 'px', 'py', '@')), ('at', 'px', 'py', "blank"), ('at', 'px', 'by', '@'), ), ), Action( 'move-left', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'bx', 'px'), ('at', 'px', 'py', "blank"), ), effects=( neg(('at', 'bx', 'py', "blank")), neg(('at', 'px', 'py', '@')), ('at', 'px', 'py', "blank"), ('at', 'bx', 'py', '@'), ), ), Action( 'move-right', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('at', 'px', 'py', "blank"), ), effects=( neg(('at', 'bx', 'py', "blank")), neg(('at', 'px', 'py', '@')), ('at', 'px', 'py', "blank"), ('at', 'bx', 'py', '@'), ), ), Action( 'take-gold', #done parameters=( ('position', 'px'), ('position', 'py'), ), preconditions=(('at' 'px', 'py', 'g'), ), effects=(neg(('at', 'px', 'py', 'g')), ('+=', ("gold", ), 1)), ), Action( 'take-arrow', #done parameters=( ('position', 'px'), ('position', 'py'), ), preconditions=(('at', 'px', 'py', 'A'), ), effects=(neg(('at', 'px', 'py', 'A')), ('+=', ("arrow", ), 1)), ), Action( 'shoot-wumpus-down', #todo parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('at', 'bx', 'py', 'W'), ('at', 'px', 'py', '@'), ('>', ("arrow", ), 0), ), effects=( neg(('at', 'bx', 'py', 'W')), ('-=', ("arrow", ), 1), ('at', 'bx', 'py', "blank"), ), ), Action( 'shoot-wumpus-left', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('at', 'bx', 'py', 'W'), ('at', 'px', 'py', '@'), ('>', ("arrow", ), 0), ), effects=( neg(('at', 'px', 'py', 'W')), ('-=', ("arrow", ), 1), ('at', 'bx', 'py', "blank"), ), ), Action( 'shoot-wumpus-up', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('at', 'bx', 'py', 'W'), ('at', 'px', 'py', '@'), ('>', ("arrow", ), 0), ), effects=( neg(('at', 'bx', 'py', 'W')), ('-=', ("arrow", ), 1), ('at', 'bx', 'py', "blank"), ), ), Action( 'shoot-wumpus-down', #done parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('at', 'bx', 'py', 'W'), ('at', 'px', 'py', '@'), ('>', ("arrow", ), 0), ), effects=( neg(('at', 'bx', 'py', 'W')), ('-=', ("arrow", ), 1), ('at', 'bx', 'py', "blank"), ), ), )) problem = pyddl.Problem( domain, { 'position': tuple(positions), }, init=tuple(init), goal=tuple(goal), ) return problem
def problem(verbose): domain = Domain(( Action( 'move-up', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'by', 'py'), ('blank', 'px', 'by'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'px', 'by')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'px', 'by'), ), ), Action( 'move-down', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('inc', 'by', 'py'), ('blank', 'px', 'by'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'px', 'by')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'px', 'by'), ), ), Action( 'move-left', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'bx', 'px'), ('blank', 'bx', 'py'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'bx', 'py')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'bx', 'py'), ), ), Action( 'move-right', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('blank', 'bx', 'py'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'bx', 'py')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'bx', 'py'), ), ), )) problem = Problem( domain, { 'tile': (1, 2, 3, 4, 5, 6, 7, 8), 'position': (1, 2, 3), }, init=( ('inc', 1, 2), ('inc', 2, 3), ('dec', 3, 2), ('dec', 2, 1), ('at', 8, 1, 1), ('at', 7, 2, 1), ('at', 6, 3, 1), ('blank', 1, 2), ('at', 4, 2, 2), ('at', 1, 3, 2), ('at', 2, 1, 3), ('at', 5, 2, 3), ('at', 3, 3, 3), ), goal=( ('blank', 1, 1), ('at', 1, 2, 1), ('at', 2, 3, 1), ('at', 3, 1, 2), ('at', 4, 2, 2), ('at', 5, 3, 2), ('at', 6, 1, 3), ('at', 7, 2, 3), ('at', 8, 3, 3), ) ) def to_coordinates(state): grid = {} for p in state: if p[0] == 'at': grid[p[1]] = (p[2], p[3]) return grid goal_coords = to_coordinates(problem.goals) def manhattan_distance_heuristic(state): state_coords = to_coordinates(state.predicates) dist = 0 for k in goal_coords.keys(): c1, r1 = goal_coords[k] c2, r2 = state_coords[k] dist += (abs(c1 - c2) + abs(r1 - r2)) return dist plan = planner(problem, heuristic=manhattan_distance_heuristic, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def getProblem(self): init = list() init.append(('=', ('arrows', ), 0)) init.append(('=', ('gold', ), 0)) init.append(('hunter', str(self.__startX), str(self.__startY))) a = max(self.__maxX, self.__maxY) for i in range(a): init.append(('dec', str(a - i), str(a - i - 1))) for i in range(self.__maxX + 1): for j in range(self.__maxY + 1): x = () if self.__map[(i, j)] == '@': x = ('at', '@', str(i), str(j)) if self.__map[(i, j)] == 'W': x = ('at', 'W', str(i), str(j)) if self.__map[(i, j)] == 'A': init.append(('at', 'blank', str(i), str(j))) x = ('at', 'A', str(i), str(j)) if self.__map[(i, j)] == 'g': init.append(('at', 'blank', str(i), str(j))) x = ('at', 'g', str(i), str(j)) if self.__map[(i, j)] == '#': x = ('at', '#', str(i), str(j)) if self.__map[(i, j)] == ' ': x = ('at', 'blank', str(i), str(j)) init.append(x) goal = list() goal.append(('hunter', str(self.__startX), str(self.__startY))) goal.append(('=', ('gold', ), self.__totalGold)) positions = list() for x in range(a + 1): positions.append(str(x)) domain = pyddl.Domain(( Action( 'move-down', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'by', 'py'), ('at', 'blank', 'px', 'by'), ('hunter', 'px', 'py'), ), effects=( neg(('at', 'blank', 'px', 'by')), neg(('hunter', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('hunter', 'px', 'by'), ), ), Action( 'move-up', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'py', 'by'), ('at', 'blank', 'px', 'by'), ('hunter', 'px', 'py'), ), effects=( neg(('at', 'blank', 'px', 'by')), neg(('hunter', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('hunter', 'px', 'by'), ), ), Action( 'move-left', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'px', 'bx'), ('at', 'blank', 'bx', 'py'), ('hunter', 'px', 'py'), ), effects=( neg(('at', 'blank', 'bx', 'py')), neg(('hunter', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('hunter', 'bx', 'py'), ), ), Action( 'move-right', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'bx', 'px'), ('at', 'blank', 'bx', 'py'), ('hunter', 'px', 'py'), ), effects=( neg(('at', 'blank', 'bx', 'py')), neg(('hunter', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('hunter', 'bx', 'py'), ), ), Action( 'shoot-wumpus-down', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'by', 'py'), ('at', 'W', 'px', 'by'), ('>', ('arrows', ), 0), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'W', 'px', 'by')), ('at', 'blank', 'px', 'by'), ('-=', ('arrows', ), 1)), ), Action( 'shoot-wumpus-up', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'py', 'by'), ('at', 'W', 'px', 'by'), ('>', ('arrows', ), 0), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'W', 'px', 'by')), ('at', 'blank', 'px', 'by'), ('-=', ('arrows', ), 1)), ), Action( 'shoot-wumpus-right', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'bx', 'px'), ('at', 'W', 'bx', 'py'), ('>', ('arrows', ), 0), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'W', 'bx', 'py')), ('at', 'blank', 'bx', 'py'), ('-=', ('arrows', ), 1)), ), Action( 'shoot-wumpus-left', parameters=( ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'px', 'bx'), ('at', 'W', 'bx', 'py'), ('>', ('arrows', ), 0), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'W', 'bx', 'py')), ('at', 'blank', 'bx', 'py'), ('-=', ('arrows', ), 1)), ), Action( 'take-gold', parameters=( ('position', 'px'), ('position', 'py'), ), preconditions=( ('at', 'g', 'px', 'py'), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'g', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('+=', ('gold', ), 1)), ), Action( 'take-arrow', parameters=( ('position', 'px'), ('position', 'py'), ), preconditions=( ('at', 'A', 'px', 'py'), ('hunter', 'px', 'py'), ), effects=(neg(('at', 'A', 'px', 'py')), ('at', 'blank', 'px', 'py'), ('+=', ('arrows', ), 1)), ), )) problem = pyddl.Problem( domain, { 'position': tuple(positions), }, init=tuple(init), goal=tuple(goal), ) return problem
def problem(verbose): domain = Domain(( Action( 'move-up', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('dec', 'by', 'py'), ('blank', 'px', 'by'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'px', 'by')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'px', 'by'), ), ), Action( 'move-down', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'by'), ), preconditions=( ('inc', 'by', 'py'), ('blank', 'px', 'by'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'px', 'by')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'px', 'by'), ), ), Action( 'move-left', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('dec', 'bx', 'px'), ('blank', 'bx', 'py'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'bx', 'py')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'bx', 'py'), ), ), Action( 'move-right', parameters=( ('tile', 't'), ('position', 'px'), ('position', 'py'), ('position', 'bx'), ), preconditions=( ('inc', 'bx', 'px'), ('blank', 'bx', 'py'), ('at', 't', 'px', 'py'), ), effects=( neg(('blank', 'bx', 'py')), neg(('at', 't', 'px', 'py')), ('blank', 'px', 'py'), ('at', 't', 'bx', 'py'), ), ), )) problem = Problem(domain, { 'tile': (1, 2, 3, 4, 5, 6, 7, 8), 'position': (1, 2, 3), }, init=( ('inc', 1, 2), ('inc', 2, 3), ('dec', 3, 2), ('dec', 2, 1), ('at', 8, 1, 1), ('at', 7, 2, 1), ('at', 6, 3, 1), ('blank', 1, 2), ('at', 4, 2, 2), ('at', 1, 3, 2), ('at', 2, 1, 3), ('at', 5, 2, 3), ('at', 3, 3, 3), ), goal=( ('blank', 1, 1), ('at', 1, 2, 1), ('at', 2, 3, 1), ('at', 3, 1, 2), ('at', 4, 2, 2), ('at', 5, 3, 2), ('at', 6, 1, 3), ('at', 7, 2, 3), ('at', 8, 3, 3), )) def to_coordinates(state): grid = {} for p in state: if p[0] == 'at': grid[p[1]] = (p[2], p[3]) return grid goal_coords = to_coordinates(problem.goals) def manhattan_distance_heuristic(state): state_coords = to_coordinates(state.predicates) dist = 0 for k in goal_coords.keys(): c1, r1 = goal_coords[k] c2, r2 = state_coords[k] dist += (abs(c1 - c2) + abs(r1 - r2)) return dist plan = planner(problem, heuristic=manhattan_distance_heuristic, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def problem(verbose): # problem domain domain = Domain(( # Function to move between tiles. Action( "move", # P1 and P2 are the parameters the solver will tweak. parameters=( ("agent", "A"), ("position", "P1"), ("position", "P2"), ), # Agent(a), Adjacent(P1, P2), At(a, P1), Blank(P2) preconditions=( ("adjacent", "P1", "P2"), ("at", "A", "P1"), ("blank", "P2"), ), # At(a, P2), Blank(P1), not(At(a, P1)), not(Blank(P2)) effects=( ("at", "A", "P2"), ("blank", "P1"), neg(("at", "A", "P1")), neg(("blank", "P2")), )), )) problem = Problem( domain, { # type values "agent": ("a", "b"), "position": (1, 2, 3, 4, 5, 6, 7, 8, 9), }, init=( # initial KB for our problem ("at", "a", 1), ("at", "b", 9), ("blank", 2), ("blank", 3), ("blank", 4), ("blank", 5), ("blank", 6), ("blank", 7), ("blank", 8), ("adjacent", 1, 2), ("adjacent", 1, 4), ("adjacent", 2, 1), ("adjacent", 2, 5), ("adjacent", 2, 3), ("adjacent", 3, 2), ("adjacent", 3, 6), ("adjacent", 4, 1), ("adjacent", 4, 5), ("adjacent", 4, 7), ("adjacent", 5, 2), ("adjacent", 5, 4), ("adjacent", 5, 6), ("adjacent", 5, 8), ("adjacent", 6, 3), ("adjacent", 6, 5), ("adjacent", 6, 9), ("adjacent", 7, 4), ("adjacent", 7, 8), ("adjacent", 8, 7), ("adjacent", 8, 5), ("adjacent", 8, 9), ("adjacent", 9, 6), ("adjacent", 9, 8), ), goal=( ("at", "a", 9), ("at", "b", 1), )) postable = { 1: (1, 1), 2: (1, 2), 3: (1, 3), 4: (2, 1), 5: (2, 2), 6: (2, 3), 7: (3, 1), 8: (3, 2), 9: (3, 3) } def to_coordinates(state): poslist = {} for p in state: if p[0] == "at": poslist[p[1]] = postable[p[2]] return poslist goal_coords = to_coordinates(problem.goals) def manhattan_distance_heuristic(state): state_coords = to_coordinates(state.predicates) dist = 0 for k in goal_coords.keys(): c1, r1 = goal_coords[k] c2, r2 = state_coords[k] dist += (abs(c1 - c2) + abs(r1 - r2)) return dist plan = planner(problem, heuristic=manhattan_distance_heuristic, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def problem(verbose): domain = Domain(( Action( 'walk', parameters=( ('person', 'p'), ('location', 'l1'), ('location', 'l2'), ), preconditions=(('at', 'p', 'l1'), ), effects=( ('at', 'p', 'l2'), neg(('at', 'p', 'l1')), ), ), Action( 'pick_from', parameters=( ('person', 'p'), ('object', 'o1'), ('object', 'o2'), ('location', 'l'), ), preconditions=( ('at', 'o1', 'l'), ('contains', 'o1', 'o2'), ('at', 'p', 'l'), ('found', 'p', 'o2'), ), effects=( ('has', 'p', 'o2'), neg(('contains', 'o1', 'o2')), ), ), Action( 'look_n_found', parameters=( ('person', 'p'), ('object', 'o1'), ('object', 'o2'), ('location', 'l'), ), preconditions=( ('at', 'p', 'l'), ('at', 'o1', 'l'), ('contains', 'o1', 'o2'), ('>=', ('brave', 'p'), 10), ), effects=(('found', 'p', 'o2'), ), ), Action( 'sing_for', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ('>=', ('brave', 'p1'), 10), ), effects=( ('+=', ('delighted', 'p2'), 10), ('+=', ('jealousy', 'Jack'), 5), ), ), Action( 'propose', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ('>=', ('brave', 'p1'), 10), ), effects=( ('+=', ('like', 'p2', 'p1'), 5), ('+=', ('jealousy', 'Jack'), 5), ), ), Action( 'steal', parameters=( ('person', 'p1'), ('person', 'p2'), ('object', 'o'), ('location', 'l'), ), preconditions=( ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('has', 'p2', 'ring'), ('>=', ('jealousy', 'p1'), 10), ), effects=( neg(('has', 'p2', 'ring')), ('has', 'p1', 'ring'), ('+=', ('upset', 'p2'), 5), ), ), Action( 'give_ring', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('has', 'p1', 'ring'), ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ), effects=( ('wait_accept', 'p1', 'p2', 'l'), ('+=', ('happy', 'p2'), 5), ('+=', ('jealousy', 'Jack'), 5), ), ), Action( 'accept_ring', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('wait_accept', 'p2', 'p1', 'l'), ('has', 'p2', 'ring'), ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ('>=', ('happy', 'p1'), 10), ('>=', ('delighted', 'p1'), 10), ), effects=( neg(('has', 'p2', 'ring')), ('has', 'p1', 'ring'), ('+=', ('happy', 'p2'), 5), ('propose_accepted', 'p1', 'p2'), ('+=', ('jealousy', 'Jack'), 5), ), ), Action( 'wisper', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ), effects=(('-=', ('upset', 'p2'), 5), ), ), Action( 'accept_propose', parameters=( ('person', 'p1'), ('person', 'p2'), ('location', 'l'), ), preconditions=( ('at', 'p1', 'l'), ('at', 'p2', 'l'), ('>=', ('like', 'p1', 'p2'), 10), ('>=', ('happy', 'p1'), 10), ('>=', ('delighted', 'p1'), 10), ('<=', ('upset', 'p1'), 1), ('<=', ('jealousy', 'p1'), 1), ), effects=( ('propose_accepted', 'p1', 'p2'), ('+=', ('happy', 'p2'), 5), ('+=', ('desparate', 'Jack'), 10), ), ), )) problem = Problem( domain, { 'location': ('loc1', 'loc2', 'loc3', 'loc4'), 'person': ('Bob', 'Marry', 'Jack'), 'object': ('ring', 'box', 'bench'), }, init=( ('at', 'Bob', 'loc1'), ('at', 'Marry', 'loc2'), ('at', 'Jack', 'loc3'), ('at', 'bench', 'loc2'), ('at', 'box', 'loc4'), ('contains', 'box', 'ring'), ('sit_on', 'Marry', 'bench'), ('=', ('like', 'Marry', 'Bob'), 5), ('=', ('like', 'Marry', 'Jack'), 1), ('=', ('like', 'Bob', 'Marry'), 10), ('=', ('like', 'Bob', 'Jack'), 1), ('=', ('like', 'Jack', 'Marry'), 10), ('=', ('like', 'Jack', 'Bob'), 1), ('=', ('like', 'Bob', 'Bob'), -1), ('=', ('like', 'Marry', 'Marry'), -1), ('=', ('like', 'Jack', 'Jack'), -1), ('=', ('happy', 'Bob'), 5), ('=', ('happy', 'Marry'), 5), ('=', ('happy', 'Jack'), 5), ('=', ('brave', 'Bob'), 10), ('=', ('brave', 'Marry'), 1), ('=', ('brave', 'Jack'), 1), ('=', ('delighted', 'Bob'), 5), ('=', ('delighted', 'Marry'), 5), ('=', ('delighted', 'Jack'), 5), ('=', ('jealousy', 'Bob'), 1), ('=', ('jealousy', 'Marry'), 1), ('=', ('jealousy', 'Jack'), 5), ('=', ('desparate', 'Bob'), 1), ('=', ('desparate', 'Marry'), 1), ('=', ('desparate', 'Jack'), 1), ('=', ('upset', 'Bob'), 1), ('=', ('upset', 'Marry'), 1), ('=', ('upset', 'Jack'), 1), ), goal=( # ('propose_accepted', 'Marry', 'Bob'), # ('>=', ('desparate', 'Jack'), 5), # ('>=', ('happy', 'Marry'), 10), # ('>=', ('happy', 'Bob'), 10), # ('has', 'Jack', 'ring'), ('has', 'Jack', 'ring'), ('>=', ('jealousy', 'Jack'), 10), ('>=', ('happy', 'Marry'), 10), ('>=', ('happy', 'Bob'), 10), )) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def problem(verbose): domain = Domain(( Action( 'oppoint', parameters=( ('location', 'loc'), ), preconditions=( ('energy', 'high'), ('emotion', 'bad'), ), effects=( ('at','loc'), ('emotion', 'good'), neg(('emotion', 'bad')), ), ), Action( 'dating', parameters=( ('storelist', 'store'), ('decidelist', 'dec'), ), preconditions=( neg(('at', 'home')), ), effects=( ('at', 'store'), neg(('at','dec')), ), ), Action( 'buy', parameters=( ('buylist', 'buy'), ('storelist','store'), ), preconditions=( ('at', 'store'), ), effects=( ('have','buy'), ), ), Action( 'pack', parameters=( ('buylist', 'buy'), ), preconditions=( ('have','buy'), ), effects=( ('packed','buy'), ), ), Action( 'give', parameters=( ('buylist', 'buy'), ), preconditions=( ('packed', 'buy'), ), effects=( ('loverget','present'), ), ), )) problem = Problem( domain, { 'storelist': ('restaurant', 'bookstore'), 'buylist': ('book', 'food'), 'decidelist': ('outside', 'playground'), }, init=( ('at', 'home'), ), goal=( ('loverget', 'present'), ) ) plan = planner(problem, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)
def __init__(self): #self.con = sqlite3.connect("story_demo.db") self.domain = Domain((Action( 'go', parameters=( ('character', 'p'), ('location', 'l1'), ('location', 'l2'), ), preconditions=(('at', 'p', 'l1'), ), effects=( ('at', 'p', 'l2'), neg(('at', 'p', 'l1')), ), ), Action( 'purchase', parameters=( ('character', 'p'), ('product', 'pr'), ('location', 'l'), ), preconditions=( ('at', 'p', 'l'), ('instock', 'pr', 'l'), ('want', 'p', 'pr'), ('need', 'p', 'pr'), ), effects=( ('purchased', 'p', 'pr'), ('have', 'p', 'pr'), neg(('instock', 'pr', 'l')), ('outstock', 'pr', 'l'), neg(('need', 'p', 'pr')), ), ), Action( 'fail_buy', parameters=( ('character', 'p'), ('product', 'pr'), ('location', 'l'), ), preconditions=( ('at', 'p', 'l'), ('outstock', 'pr', 'l'), ('want', 'p', 'pr'), ('need', 'p', 'pr'), ), effects=(('failedbuy', 'p', 'pr'), ), ), Action( 'refund', parameters=( ('character', 'p'), ('product', 'pr'), ('location', 'l'), ), preconditions=( ('at', 'p', 'l'), ('have', 'p', 'pr'), ('outstock', 'pr', 'l'), ), effects=( ('instock', 'pr', 'l'), neg(('have', 'p', 'pr')), neg(('outstock', 'pr', 'l')), neg(('purchased', 'p', 'pr')), ), ), Action( 'change_mind', parameters=( ('character', 'p'), ('product', 'pr'), ), preconditions=( ('have', 'p', 'pr'), ('want', 'p', 'pr'), ), effects=(neg(('want', 'p', 'pr')), ), ))) self.problem = Problem( self.domain, { 'location': ('Ahome', 'Shop', 'Bhome'), 'character': ('A', 'B'), 'product': ('D'), }, init=( ('at', 'A', 'Ahome'), ('at', 'B', 'Bhome'), ('want', 'A', 'D'), ('want', 'B', 'D'), ('need', 'A', 'D'), ('need', 'B', 'D'), ('instock', 'D', 'Shop'), ), goal=( ('failedbuy', 'A', 'D'), ('at', 'B', 'Shop'), ('instock', 'D', 'Shop'), ('at', 'A', 'Ahome'), ('need', 'A', 'D'), ), ) #self.actions={} #self.ground_actions() grounder = Grounder(self) self.predicate_comb = grounder.get_predicate_combination( self.problem, self.domain) self.action_comb = [ str(action) for action in self.problem.grounded_actions ] self.num_states = len(self.predicate_comb) self.num_actions = len(self.action_comb) self.init_state = self.problem.initial_state print(self.predicate_comb) #print(self.action_comb) #print(self.actions) #self.state_binarizer = OneHotEncoder(categories=self.predicate_comb) #self.state_binarizer.fit(self.predicate_comb) self.goal = (self.problem.goals, self.problem.num_goals) self.goal_set = set(self.problem.goals)
def problem(verbose): with open("all_data.csv", "r") as f: data = f.readlines() data = [x.strip().strip(punctuation) for x in data] data = data[:40] medicines = [] symptoms = [] domain = Domain((Action( 'take', parameters=( ('medicine', 'med'), ('symptom', 'sym1'), ('symptom', 'sym2'), ('symptom', 'sym3'), ), preconditions=( ('cures', 'med', 'sym1'), ('cures', 'med', 'sym2'), ('cures', 'med', 'sym3'), ('have_med', 'med'), ('has', 'sym1'), ('has', 'sym2'), ('has', 'sym3'), ), effects=( ('had', 'sym1'), ('had', 'sym2'), ('had', 'sym3'), neg(('have_med', 'med')), ), ), )) user_init = [] user_goal = [] user_symptoms = [] for x in data: y = x.split(',') y = [z.strip(punctuation) for z in y] if len(y) < 2 or len(y) > 4: continue medicines.append(y[0]) user_init.append(('have_med', str(y[0]))) symptoms += y[1:] for sym in y[1:]: user_init.append(('cures', str(y[0]), str(sym))) with open("user_symptoms.txt", "r") as f: syms = f.readlines() syms = [s.strip().strip(punctuation) for s in syms] for sym in syms: user_init.append(('has', str(sym))) user_symptoms.append(str(sym)) user_goal.append(('had', str(sym))) total_symptoms = len(user_init) user_symptoms = list(set(user_symptoms)) problem = Problem( domain, { 'medicine': list(set(medicines)), 'symptom': list(set(symptoms)), }, init=user_init, goal=user_goal, ) def distance_heuristic(state): num_satisfied = len([ p for p in state.predicates if p[0] == "had" and p[1] in user_symptoms ]) return total_symptoms - num_satisfied plan = planner(problem, heuristic=distance_heuristic, verbose=verbose) if plan is None: print('No Plan!') else: for action in plan: print(action)