def plan(domain, state0, tasks, verbose=0): # Register planning operations with pyhop ops = domain.htn_operators() methods = domain.htn_methods() ph.declare_operators(*ops.values()) for name, fun in methods.items(): ph.declare_methods(name, fun) # one method per task name # Run pyhop planner actions = ph.pyhop(state0, tasks, verbose=verbose) return actions
continue # # if we get here, no blocks can be moved to their final locations b1 = pyhop.find_if(lambda x: status(x, state, goal) == 'waiting', all_blocks(state)) if b1 != None: return [('move_one', b1, 'table'), ('move_blocks', goal)] # # if we get here, there are no blocks that need moving return [] """ declare_methods must be called once for each taskname. Below, 'declare_methods('get',get_m)' tells Pyhop that 'get' has one method, get_m. Notice that 'get' is a quoted string, and get_m is the actual function. """ pyhop.declare_methods('move_blocks', moveb_m) ### methods for "move_one" def move1(state, b1, dest): """ Generate subtasks to get b1 and put it at dest. """ return [('get', b1), ('put', b1, dest)] pyhop.declare_methods('move_one', move1) ### methods for "get"
""" The "travel from home to the park" example from my lectures. Author: Dana Nau <*****@*****.**>, November 15, 2012 This file should work correctly in both Python 2.7 and Python 3.2. """ import pyhop def travel_by_foot(state,a,x,y): if state.dist[x][y] <= 2: return [('walk',a,x,y)] return False def travel_by_taxi(state,a,x,y): if state.cash[a] >= 1.5 + 0.5 * state.dist[x][y]: return [('call_taxi',a,x), ('ride_taxi',a,x,y), ('pay_driver',a,x,y)] return False pyhop.declare_methods('travel',travel_by_foot,travel_by_taxi)
return False def order_chinese(state, agent, full): if state.time[agent] >= 18: if state.money[agent] >= 25: if state.fullness[agent] + 0.6 < full: return [('chinese', agent),("eating", agent, full)] else: return [('chinese', agent)] return False pyhop.declare_methods('eating', order_pizza, order_burger, order_chinese, cook) print '\n' pyhop.print_methods() person = pyhop.State('state') person.fullness = {'me_friends': 0.0} person.time = {'me_friends': 200} person.money = {'me_friends': 80} pyhop.pyhop(person, [('eating', 'me_friends', 3.0)], verbose=3) person.fullness = {'me_friends': 0.0} person.time = {'me_friends': 220} person.money = {'me_friends': 100} pyhop.pyhop(person, [('eating', 'me_friends', 3.0)], verbose=3)
else: return False else: return False def order_kebab(state, agent): if state.time[agent] >= 18: if wallet() >= 13: return [('eat_kebab', agent)] else: return False else: return False ####################### Methods declaration: pyhop.declare_methods('eat', order_in_restaurant, cook_myself, order_in_milkbar, order_kebab) print('\n#########################################################\n') pyhop.print_methods() ############################### State definition: state = pyhop.State('state') money = 78 # how much money booked for dinners this week 78 ############################### ####################### Week: #Monday state.time = {'me': 60} # time for lunch today. pyhop.pyhop(state, [('eat', 'me')], verbose = 3) print('\n#########################################################\n') #Tuesday state.time = {'me' : 40}
else: return False def build_barracks_task_c(state): if state.gold < BARRACKS_COST_GOLD: return [('gather_gold_task',),('build_barracks_task',)] else: return False def build_barracks_task_d(state): if state.wood < BARRACKS_COST_WOOD: return [('gather_wood_task',),('build_barracks_task',)] return False pyhop.declare_methods('build_barracks_task',build_barracks_task_a,build_barracks_task_b,build_barracks_task_c,build_barracks_task_d) def build_house_task_a(state): if state.gold >= HOUSE_COST_GOLD: return [('build_house',)] else: return False def build_house_task_b(state): if state.gold < HOUSE_COST_GOLD: return [('gather_gold_task',),('build_house_task',)] else: return False pyhop.declare_methods('build_house_task',build_house_task_a,build_house_task_b)
('move_tower', disk - 1, spare, dest, source)] else: num_states_explored = num_states_explored + 1 return False def move_disk(state, disk, source, dest, spare): global num_states_explored if disk == 0: return [('move', disk, source, dest)] else: num_states_explored = num_states_explored + 1 return False pyhop.declare_methods('move_tower', move_stack, move_disk) print('') pyhop.print_methods() ## Num Disks num_disks = int(sys.argv[1]) num_states_explored = 0 ## Define state state1 = pyhop.State('state1') state1.loc = {} for i in range(0, num_disks): state1.loc[i] = 0 ## Run SHOP planner t0 = time.time() result = pyhop.pyhop(state1, [('move_tower', num_disks - 1, 0, 2, 1)],
#from pyhop import * import pyhop import methods state1 = pyhop.State('state1') state1.gold = 100 state1.peons = 1 state1.houses = 0 state1.free_places = 2 state1.wood = 20 #pyhop.print_methods() #pyhop.print_operators() def build_town(state): print state return [('build_barracks_task', ), ('build_watchtower_task', )] pyhop.declare_methods('build_town', build_town) pyhop.pyhop(state1, [('build_town', )], verbose=2)
return [('move_one',b1,goal.pos[b1]), ('move_blocks',goal)] else: continue # # if we get here, no blocks can be moved to their final locations b1 = pyhop.find_if(lambda x: status(x,state,goal) == 'waiting', all_blocks(state)) if b1 != None: return [('move_one',b1,'table'), ('move_blocks',goal)] # # if we get here, there are no blocks that need moving return [] """ declare_methods must be called once for each taskname. Below, 'declare_methods('get',get_m)' tells Pyhop that 'get' has one method, get_m. Notice that 'get' is a quoted string, and get_m is the actual function. """ pyhop.declare_methods('move_blocks',moveb_m) ### methods for "move_one" def move1(state,b1,dest): """ Generate subtasks to get b1 and put it at dest. """ return [('get', b1), ('put', b1,dest)] pyhop.declare_methods('move_one',move1) ### methods for "get"
return False def buy_pocket(state, agent): if state.time[agent] >= 340: #Offline if ((state.money[agent] >= 220) and (state.time[agent] >= 380)): return [('own_transport', agent),('pocket', agent), ('offline', agent)] elif state.money[agent] >= 250: return [('post_transport', agent),('pocket', agent), ('offline', agent)] elif state.time[agent] >= 300: #Online if state.money[agent] >= 260: return [('post_transport', agent),('pocket', agent)] else: return False return False ####################### Methods declaration: pyhop.declare_methods('buy', buy_foam, buy_bonell, buy_pocket) print('\n#########################################################\n') pyhop.print_methods() ############################### State definition: state = pyhop.State('state') ############################### ####################### Customers: #1st customer state.time = {'me': 300} state.money = {'me' : 1000} pyhop.pyhop(state, [('buy', 'me')], verbose = 3) print('\n#########################################################\n') #2nd customer state.time = {'me' : 700}
Author: [email protected] """ import random, pyhop, navigation, heapq from rovers_world_operators import * def empty_store_m(state, store, rover, rand=False): possible_decomp = [] if state.empty[store]: possible_decomp.append([]) else: possible_decomp.append([('drop', rover, store)]) return possible_decomp pyhop.declare_methods('empty_store',empty_store_m) def can_traverse(state, source, sink): num_col = state.prop["num_col"] num_row = state.prop["num_row"] a = min(source, sink) b = max(source, sink) if (b-a == 1) and (a % num_col != 0): return True elif (b-a == num_col): return True def navigate_m(state, agent, sink, rand=False): if state.a_star: return [navigation.a_star(state, agent, sink)]
def declare_methods(longApprehend = True): pyhop.declare_methods("achieve_goals", achieve_goals) pyhop.declare_methods('create_order',c_order)
import pyhop def move_disk(state, disk, peg_source, peg_dest): if state.diskLocation[disk] == peg_source: state.diskLocation[disk] = peg_dest return state else: return False pyhop.declare_operators(move_disk) def move_multiple(state, disk, peg_source, peg_dest, peg_via): if disk > 0: return [('move', disk - 1, peg_source, peg_via, peg_dest), ('move_disk', disk, peg_source, peg_dest), ('move', disk - 1, peg_via, peg_dest, peg_source)] else: return False def move_single(state, disk , peg_source, peg_dest, peg_via): if disk <= 0: return [('move_disk', disk, peg_source, peg_dest)] else: return False pyhop.declare_methods('move', move_single, move_multiple)
def travel_by_bus(state,a,x,y): global static_state bs = state.nearest_bus_stop[a] bus_fair = bus_rate(distance(bs,y)) # Check precondition if distance(x,bs) <= 3 and state.cash[a] >= bus_fair and (bs+':'+y in static_state.bus_route): return [('walk',a,x,bs), ('pay_bus_driver',a,bus_fair), ('ride_bus',a,bs,y)] else: return False # Withdraw money from bank def withdraw_money_from_bank(state,a,amount): # Check precondition if amount <= state.balance_bank[a]: state = withdraw_money(state,a,amount) return [('withdraw_money',a,amount)] else: return False # Decalare the pyhop method pyhop.declare_methods('travel_by_goal', travel_by_goal_state) def generate_new_state(stateName): return pyhop.State(stateName) def find_plan(state, goal): return pyhop.pyhop(state,[('travel_by_goal', goal)],verbose=0) def print_state(state): pyhop.print_state(state)
# return [('moveOne',b1,goal.pos[b1]), ('moveBlocks',goal)] # else: # continue ## ## if we get here, no blocks can be moved to their final locations #b1 = pyhop.find_if(lambda x: status(x,state,goal) == 'waiting', all_blocks(state)) #if b1 != None: # return [('moveOne',b1,'table'), ('moveBlocks',goal)] ## ## if we get here, there are no blocks that need moving #return [] """ declare_methods must be called once for each taskname. Below, 'declare_methods('get',get_m)' tells Pyhop that 'get' has one method, get_m. Notice that 'get' is a quoted string, and get_m is the actual function. """ pyhop.declare_methods('moveBlocks',moveBlocks_m) ### methods for "move_one" def moveOne_m(state,locI,locF): """ Generate subtasks to get b1 and put it at dest. """ #TODO: POTENTIALLY CHANGE WHERE THIS EFFECT HAPPENS # when a block is moved to its final resting place, it should be removed from blocksAvail list state.blocksAvail.remove(state.locContents[locI]) return [('moveRobot', locI),('pickUp', locI), ('moveRobot', locF), ('putDown', locF)] pyhop.declare_methods('moveOne',moveOne_m)
def move_disk(state, disk, peg_source, peg_dest): if state.diskLocation[disk] == peg_source: state.diskLocation[disk] = peg_dest return state else: return False pyhop.declare_operators(move_disk) def move_multiple(state, disk, peg_source, peg_dest, peg_via): if disk > 0: return [('move', disk - 1, peg_source, peg_via, peg_dest), ('move_disk', disk, peg_source, peg_dest), ('move', disk - 1, peg_via, peg_dest, peg_source)] else: return False def move_single(state, disk, peg_source, peg_dest, peg_via): if disk <= 0: return [('move_disk', disk, peg_source, peg_dest)] else: return False pyhop.declare_methods('move', move_single, move_multiple)
def teach_knowledge(state, target_heard_count): for hc in state.concepts_heard_count: if hc < target_heard_count: return [('next_step', target_heard_count), ('teach', target_heard_count)] for hc in state.relations_heard_count: if hc < target_heard_count: return [('next_step', target_heard_count), ('teach', target_heard_count)] return [('done', target_heard_count)] # have to specify the data structure of map and then how that is to be disseminated using the existing methods pyhop.declare_methods('present_a_concept', present_a_concept) pyhop.declare_methods('present_a_relation', present_a_relation) pyhop.declare_methods('quest_on_concept', quest_on_concept) pyhop.declare_methods('quest_on_relation', quest_on_relation) pyhop.declare_methods('next_step', next_step) pyhop.declare_methods('done', done) pyhop.declare_methods('teach', teach_knowledge) # print('') # pyhop.print_methods() # End - Methods #result format: ('print_a_concept_1', 'Concept B'), ('print_a_concept_2', 'Concept A'), # query
return [('call_taxi', x), ('ride_taxi', x, 'train_station'), ('ride_public_transport', 'train_station', y)] def travel_car_pt(state, x, y): return [('ride_car', x, 'train_station'), ('ride_public_transport', 'train_station', y)] def travel_pt_pt(state, x, y): return [('ride_public_transport', x, 'train_station'), ('ride_public_transport', 'train_station', y)] def travel_walk_pt(state, x, y): return [('walk', x, 'train_station'), ('ride_public_transport', 'train_station', y)] pyhop.declare_methods('travel', travel_car, travel_taxi_pt, travel_car_pt, travel_pt_pt, travel_walk_pt) state = pyhop.State('state') state.loc = { 'me': 'home', 'car': 'home', 'taxi': 'anywhere', } state.dist = { 'home': {'train_station': 10, 'target': 100}, 'train_station': {'target': 100}, } state.cash = 100 state.time = 97
# como maximo. Deben devolver un conjunto de operadores/tareas (aunque sea vacio) o False # si no se puede aplicar def do_read(state,a,x,y): if not state.read_book[a]: return [('read_book',a)] return False def dont_read(state,a,x,y): if state.read_book[a]: return [] return False # Indicamos cual es la descomposicion de "read_if_necessary_book" pyhop.declare_methods('read_if_necessary_book', do_read, dont_read) # Definicion de dos metodos para "travel". Solo uno de ellos se ejecutara como maximo def travel_by_foot(state,a,x,y): if state.dist[x][y] <= 2: return [('walk',a,x,y)] return False def travel_by_taxi(state,a,x,y): if state.cash[a] >= taxi_rate(state.dist[x][y]): return [('call_taxi',a,x), ('wait_taxi',a), ('read_if_necessary_book',a,x,y), ('ride_taxi',a,x,y), ('pay_driver',a)] return False
""" METHODS """ # Methods for FindGoal def walk(state, a): """If player has not reached goal, walk in a single direction""" if status(state, a) == 'done': return [] else: return [('WalkTask', a)] pyhop.declare_methods('FindGoal', walk) # Methods for WalkTask def north(state, a): """Walk 1 unit north, then recurse for next direction""" return [('up', a), ('FindGoal', a)] def south(state, a): """Walk 1 unit south, then recurse for next direction""" return [('down', a), ('FindGoal', a)] def west(state, a):
def main(): state = pyhop.State('state') state.people = {'me': 1, 'assistant': 2, 'janitor': 5, 'professor': 8} state.side = { 'left': {person for person in state.people.keys()}, 'right': set() } state.chosen = [] state.torch = 'left' state.time = 15 pyhop.declare_operators(all_on_right_within_time, none_on_left, walk_people, is_person_on_side, is_not_chosen, has_time, append_person_to_chosen) pyhop.declare_methods( 'pick_person', *[ fun_factory('chose_{:d}'.format(i), i - 1) for i in range(len(state.people.keys())) ]) pyhop.declare_methods('chose_person', chose_person) pyhop.declare_methods('travel_person', travel_person) pyhop.declare_methods('travel_2_people', travel_2_people) pyhop.declare_methods('assert_escape', assert_escape) pyhop.declare_methods('escape', assert_escape, travel_person, travel_2_people) pyhop.pyhop(state, [('escape', )], verbose=3)
pyhop.failure_reason = "{} can't initialize and transfer {} from {} to {}".format( actor, actee, from_, to_) return False def transfer(state, actor, actee, from_, to_): if actor == "arm": if state.initialized["arm"]: return [('grab', actor, actee, from_), ('put', actor, actee, to_)] pyhop.failure_reason = "{} can't transfer {} from {} to {}".format( actor, actee, from_, to_) return False pyhop.declare_methods('transfer_ball_to_container', initialize_transfer) pyhop.declare_methods('transfer_ball_to_container2', put_grabbed, transfer) print('') pyhop.print_methods() current_world_model = pyhop.State('current_world_model') current_world_model.tick = 0 current_world_model.timestamp = time.time() current_world_model.location = {'ball': 'table'} current_world_model.grabbed = {'ball': True} current_world_model.initialized = {'arm': True} current_world_model.min_bounds = {'xyz': [-25, -25, -25]} current_world_model.max_bounds = {'xyz': [25, 25, 25]} current_world_model.plans = "None"
z = select_new_city(state, y) g = pyhop.Goal('g') g.final = y return [('travel_op', z), ('travel', g)] return False def already_there(state, goal): x = state.location y = goal.final if x == y: return [] return False pyhop.declare_methods('travel', travel_m, already_there) print('') pyhop.print_methods() #INITIAL STATE state1 = pyhop.State('state1') state1.coordinates = { 'Huelva': { 'X': 25, 'Y': 275 }, 'Cadiz': { 'X': 200, 'Y': 50 },
y=goal.final if x!=y: z=select_new_city(state,y) g=pyhop.Goal('g') g.final=y return [('travel_op',z), ('travel_to_city',g)] return False def already_there(state,goal): x=state.location_car y=goal.final if x==y: return [] return False pyhop.declare_methods('travel_to_city',travel_m, already_there) def travel_by_car(state,goal): x=state.location y=goal.final if x!=y: return [('load_car_op',), ('travel_to_city',goal), ('unload_car_op',)] return False pyhop.declare_methods('travel',travel_by_car) print('') pyhop.print_methods() #INITIAL STATE state1 = pyhop.State('state1')
print('El conductor '+conductor+' no existe') return False cond = state.ubi_conductor[conductor] if cond != destino: return[('conseguir_conductor',conductor,destino)] else: return[] # Declaración de métodos #pyhop.declare_methods('traer_conductor',traer_andando, traer_conduciendo) #pyhop.declare_methods('conseguir_conductor', no_traer_conductor, traer_cond) pyhop.declare_methods('conseguir_camion',no_conseguir_camion,traer_camion) pyhop.declare_methods('conseguir_conductor', no_traer_conductor, traer_conduciendo,traer_andando) pyhop.declare_methods('mover_camion_ciudad', func_mover_camion_ciudad) pyhop.declare_methods('mover_conductor_destino', func_mover_conductor_destino) pyhop.declare_methods('mover_paquete_ciudad', func_paquete_destino) pyhop.declare_methods('mover_todo_destino', func_main) #Metodos Auxiliares pyhop.print_methods()
""" The "travel from home to the park" example from my lectures. Author: Dana Nau <*****@*****.**>, November 15, 2012 This file should work correctly in both Python 2.7 and Python 3.2. """ import pyhop def travel_by_foot(state, a, x, y): if state.dist[x][y] <= 2: return [('walk', a, x, y)] return False def travel_by_taxi(state, a, x, y): if state.cash[a] >= 1.5 + 0.5 * state.dist[x][y]: return [('call_taxi', a, x), ('ride_taxi', a, x, y), ('pay_driver', a, x, y)] return False pyhop.declare_methods('travel', travel_by_foot, travel_by_taxi)
return False def travel_by_taxi(state, a, x, y): if state.cash[a] >= taxi_rate(state.dist[x][y]): return [('call_taxi', a, x), ('ride_taxi', a, x, y), ('pay_driver', a)] return False def travel_by_flying(state, a, x, y): if state.superhero['superman']: return [('fly', a, x, y)] return False pyhop.declare_methods('travel', travel_by_flying, travel_by_foot, travel_by_bicycle, travel_by_taxi) print('') pyhop.print_methods() state1 = pyhop.State('state1') state1.loc = {'me': 'home'} state1.cash = {'me': 20} # state1.cash = {'me': 1} state1.weather = {'raining': False} # state1.superhero = {'superman': True} state1.superhero = {'superman': True} # state1.weather = {'raining': True} state1.owe = {'me': 0} # state1.dist = {'home': {'park': 8}, 'park': {'home': 8}} state1.dist = {'home': {'park': 2}, 'park': {'home': 2}}
HEALTH_VAL = 100 def finish_thesis_task_1(state): if state.sph_left <= 0: return [('finish_thesis',)] return False def finish_thesis_task_2(state): if state.sph_left > 0: return [('write_sph_task',), ('finish_thesis_task',)] return False pyhop.declare_methods('finish_thesis_task', finish_thesis_task_1, finish_thesis_task_2) def write_sph_task_1(state): if state.energy >= WORK_ENERGY_REQ and state.fed >= WORK_FED_REQ and state.health >= WORK_HEALTH_REQ and state.backlog < BACKLOG_REDUCE_VAL: return [('write_sph', ), ('study_task', )] return False def write_sph_task_2(state): if state.energy < WORK_ENERGY_REQ: return [('relax_task',), ('write_sph_task',)] else: return False
('store_ingredient', 'wood', 1)] else: return False def punch_for_wood(state, num): if state.time >= 4: if num == 1: return [('store_ingredient', 'wood', 1), ('use_time', 4)] else: return [('store_ingredient', 'wood', 1), ('use_time', 4), ('produce_wood', num - 1)] #pyhop.declare_methods('produce_wood', punch_for_wood, iron_axe_for_wood, stone_axe_for_wood, wooden_axe_for_wood) pyhop.declare_methods('produce_wood', punch_for_wood) # state init state = pyhop.State('state1') state.ingredients = { 'wood': 0, 'plank': 0, 'cobble': 0, 'ingot': 0, 'coal': 0, 'ore': 0, 'stick': 0 } state.tool = { 'wooden_axe': True,
def perimeterize(state, agent, beacon_locs): # if there are no more beacon locs we are done #print('beacon_locs are '+str(beacon_locs)) if beacon_locs: xy_str = state.agents[agent] # get the first beacon loc return [('navigate',agent,beacon_locs[0]), ('dropbeacon', agent), ('make_perimeter', agent, beacon_locs[1:])] elif beacon_locs == []: return [] # done else: return False pyhop.declare_methods('navigate',move) pyhop.declare_methods('make_perimeter',perimeterize) #pyhop.declare_methods('movenorth',movenorth) #pyhop.declare_methods('moveeast',moveeast) #pyhop.declare_methods('movewest',movewest) #pyhop.declare_methods('movesouth',movesouth) ###################################################################### ## This model is how we could do it in a pure vanilla way but I when I ## do it this way, it runs in an infinite loop because the planner ## does depth first search instead of breadth first search # def movenorth(state, agent, dest): # if state.agents[agent] == dest:
from holidays_travalling_helper import \ go_by_ferry, \ fly, \ call_taxi, \ ride_taxi, \ buy_ferry_ticket, \ buy_plane_ticket, \ pay_taxi_driver, \ travel_by_plane, \ travel_by_ferry, \ travel_by_taxi, \ get_souvenir from holidays_planner_data_helper import state0, places pyhop.declare_operators(fly, buy_plane_ticket, call_taxi, ride_taxi, pay_taxi_driver, buy_ferry_ticket, go_by_ferry, get_souvenir) print('') pyhop.print_operators() pyhop.declare_methods('travel', travel_by_plane, travel_by_taxi, travel_by_ferry) print('') pyhop.print_methods() # Call # pyhop.pyhop(state0, [('travel', 'me', places[0], places[-1], 0)], verbose=3)
def declare_methods(longApprehend = True): if longApprehend: pyhop.declare_methods("catch_arsonist", long_apprehend_m) else: pyhop.declare_methods("catch_arsonist", quick_apprehend_m) pyhop.declare_methods("put_out", put_out_m) pyhop.declare_methods('put',put_m) pyhop.declare_methods('unstack_task',unstack_m) pyhop.declare_methods('pickup_task',pickup_m) pyhop.declare_methods('get',get_by_pickup,get_by_unstack) pyhop.declare_methods('move_one',move1) pyhop.declare_methods('move_blocks',moveb_m)
def drop(state, obj, location): if state.at['robot'] == location and state.holding == obj: state.holding = None state.at[obj] = location return state else: return False pyhop.declare_operators(move, take, drop) print('') pyhop.print_operators() def deliver(state, obj, destination): obj_start = state.at[obj] return [('move', 'robot', state.at['robot'], obj_start), ('take', obj, obj_start), ('move', 'robot', obj_start, destination), ('drop', obj, destination)] pyhop.declare_methods('deliver', deliver) state1 = pyhop.State('state1') state1.at = {'robot': 'dock', 'mail': 'mailroom'} state1.holding = None pyhop.pyhop(state1, [('deliver', 'mail', 'office')], verbose=3)
#from pyhop import * import pyhop import methods state1 = pyhop.State('state1') state1.gold = 100 state1.peons = 1 state1.houses = 0 state1.free_places = 2 state1.wood = 20 #pyhop.print_methods() #pyhop.print_operators() def build_town(state): print state return [('build_barracks_task',),('build_watchtower_task',)] pyhop.declare_methods('build_town',build_town) pyhop.pyhop(state1,[('build_town',)],verbose=2)
travel_by_plane, \ travel_by_ferry, \ travel_by_taxi, \ get_souvenir from holidays_planner_data_helper import state0, places pyhop.declare_operators( fly, buy_plane_ticket, call_taxi, ride_taxi, pay_taxi_driver, buy_ferry_ticket, go_by_ferry, get_souvenir) print('') pyhop.print_operators() pyhop.declare_methods('travel', travel_by_plane, travel_by_taxi, travel_by_ferry) print('') pyhop.print_methods() # Call # pyhop.pyhop(state0, [('travel', 'me', places[0], places[-1], 0)], verbose = 3)
if c == next(x for x in goal.onStack if x not in self_state.onStack and self_name in self_state.isReachableBy[x]): return [("move_one", c, goal), ("stack", goal)] return False def make_stack_robot(agents, self_state, self_name, goal): if hasattr(goal, "stack_location") and goal.stack_location is not None: self_state.stack_location = goal.stack_location if not hasattr( self_state, "stack_location" ) or self_state.stack_location is None or self_state.stack_location == []: return False pyhop.declare_methods("human", "move_one", moveb_m_human) pyhop.declare_methods("robot", "move_one", moveb_m_robot) pyhop.declare_methods("human", "stack", wait_uncoop_human, stack_human) pyhop.declare_methods("robot", "stack", stack_robot) pyhop.print_operators() pyhop.print_methods() def make_reachable_by(state, cubes, agent): if not hasattr(state, "isReachableBy"): state.isReachableBy = {} state.isReachableBy.update({c: agent for c in cubes})
else: continue # # if we get here, no blocks can be moved to their final locations b1 = pyhop.find_if(lambda x: status(x, state, goal) == "waiting", all_blocks(state)) if b1 != None: return [("move_one", b1, "table"), ("move_blocks", goal)] # # if we get here, there are no blocks that need moving return [] """ declare_methods must be called once for each taskname. Below, 'declare_methods('get',get_m)' tells Pyhop that 'get' has one method, get_m. Notice that 'get' is a quoted string, and get_m is the actual function. """ pyhop.declare_methods("move_blocks", moveb_m) ### methods for "move_one" def move1(state, b1, dest): """ Generate subtasks to get b1 and put it at dest. """ return [("get", b1), ("put", b1, dest)] pyhop.declare_methods("move_one", move1)
return [('walk',driver, state.ruta_cond[driverAt][0]),('walk_to_dest',driver,dest)] #Si el conductor tiene varios destinos desde su posicion actual y ninguno de ellos es el destino final else: minValue=100 indexMinDest='' for i in state.ruta_cond[driverAt]: print i if state.distancias[i][dest]<minValue: minValue=state.distancias[i][dest] indexMinDest = i return [('walk',driver, i),('walk_to_dest',driver,dest)] pyhop.declare_methods('walk_to_dest', walk_to_dest_m) def drive_to_dest_m(state,transport,dest): #Localizacion del camion transpAt = state.at_camiones[transport] #Comprobamos si hay conductor en la posicion origen del camion y si hay lo guardamos hayDriver=False for i in state.at_cond: if state.at_cond[i]==transpAt: hayDriver=True driver=i if dest==transpAt: return [('already_there',)]
def __init__(self): self.failure_reason = "" self.verbose = 0 # Helper methods def is_within_bounds(location1, min_bounds, max_bounds): for i in range(len(location1)): if location1[i] < min_bounds[i] or location1[i] > max_bounds[i]: return False return True # Operators (primitive tasks) def move_arm(state, to_): arm_min_bounds = state.min_bounds["xyz"] arm_max_bounds = state.max_bounds["xyz"] if to_ == "target_object" or to_ == "container": xyz = state.xyz[to_] if not is_within_bounds(xyz, arm_min_bounds, arm_max_bounds): self.failure_reason = "can't move arm to {}: {} outside of bounds: {} {}"\ .format(to_, xyz, arm_min_bounds, arm_max_bounds) return False return state return state def move_arm_above(state, to_): return move_arm(state, to_) def close_hand(state): gripper_min_bounds = state.min_bounds["object_side_length"] gripper_max_bounds = state.max_bounds["object_side_length"] distance = state.size['object_side_length'] if distance < gripper_min_bounds or distance > gripper_max_bounds: self.failure_reason = "can't close hand to distance {}".format( distance) print(self.failure_reason) return False return state def open_hand(state): gripper_min_bounds = state.min_bounds["object_side_length"] gripper_max_bounds = state.max_bounds["object_side_length"] distance = state.size['object_side_length'] if distance < gripper_min_bounds or distance > gripper_max_bounds: self.failure_reason = "can't open hand to distance {}".format( distance) return False return state def initialize(state, actor): if actor == "arm": state.initialized["arm"] = True return state self.failure_reason = "{} can't initialize".format(actor) return False pyhop.declare_operators(initialize, move_arm, move_arm_above, close_hand, open_hand) if self.verbose > 0: pyhop.print_operators() # Methods (compound tasks) def put_grabbed(state, actor, actee, from_, to_): if actor == "arm": if state.grabbed["target_object"]: return [('move_arm_above', to_), ('open_hand', )] return False def full_transfer(state, actor, actee, from_, to_): if actor == "arm": return [('initialize', actor), ('open_hand', ), ('move_arm_above', 'target_object'), ('move_arm', 'target_object'), ('close_hand', ), ('move_arm_above', 'target_object'), ('move_arm_above', to_), ('open_hand', )] return False def transfer(state, actor, actee, from_, to_): if actor == "arm": if state.initialized["arm"]: return [('move_arm_above', 'target_object'), ('move_arm', 'target_object'), ('close_hand', ), ('move_arm_above', 'target_object'), ('move_arm_above', to_), ('open_hand', )] return False pyhop.declare_methods('transfer_target_object_to_container', full_transfer, put_grabbed, transfer)
import pyhop def go_to_waypoint_m(state,rover,waypoint): if state.at[rover]==waypoint: return [('already_there', rover)] else: for path in state.can_traverse[rover]: if state.at[rover]==path[0] and path[1] not in state.crossed[rover]: next_waypoint=path[1] break return [('navigate', rover, next_waypoint), ('go_to_waypoint', rover, waypoint)] pyhop.declare_methods('go_to_waypoint', go_to_waypoint_m) def communicate_soil_data_m(state, rover, waypoint): if state.equipped_for_soil_analysis: return [('go_to_waypoint', rover, waypoint), ('sample_soil', rover), ('drop', rover), ('communicate_soil_data_to_lander', rover, waypoint)] pyhop.declare_methods('communicate_soil_data', communicate_soil_data_m) def communicate_rock_data_m(state, rover, waypoint): if state.equipped_for_rock_analysis: return [('go_to_waypoint', rover, waypoint), ('sample_rock', rover), ('drop', rover), ('communicate_rock_data_to_lander', rover, waypoint)] pyhop.declare_methods('communicate_rock_data', communicate_rock_data_m) def communicate_image_data_m(state, rover, objective, mode): camlist=[key for key,value in state.supports[rover].items() if mode in value] #list of cameras with mode support if camlist and rover in state.equipped_for_imaging: # rover in state.equipped_for_imaging is exscessively #cam=camlist[0] #ill send the whole camlist return [('calibrate',rover,camlist,objective), ('take_image',rover, camlist, objective, mode), ('communicate_image_data_to_lander', rover, objective, mode)]#Calibrate, Take_image y Communicate_image_data_to_lander pyhop.declare_methods('communicate_image_data', communicate_image_data_m)
def declare_methods(longApprehend=True): if longApprehend: pyhop.declare_methods("catch_arsonist", long_apprehend_m) else: pyhop.declare_methods("catch_arsonist", quick_apprehend_m) pyhop.declare_methods("put_out", put_out_m) pyhop.declare_methods('put', put_m) pyhop.declare_methods('unstack_task', unstack_m) pyhop.declare_methods('pickup_task', pickup_m) pyhop.declare_methods('get', get_by_pickup, get_by_unstack) pyhop.declare_methods('move_one', move1) pyhop.declare_methods('move_blocks', moveb_m)
import pyhop pyhop.declare_methods('move', move_iterative) def move_iterative(state,goal): for who in goal.loc.keys(): x = state.loc[who] y = goal.loc[who] if x != y: return [('travel_method',who,x,y), ('travel',goal)] return [] def mover_paqueteM1(state, paquete, ubicacion_paquete, destino): return[('conseguir_camion', ubicacion_paquete), ('conseguir_conductor', destino), ('cargar_paquete', paquete), ('conducir_al_destino', ubicacion_paquete, destino), ('descargar_paquete', paquete)] pyhop.declare_methods('mover_paquete', mover_paqueteM1) def ya_disponible(state, destino): for truck in state.trucks.keys(): if state.trucks[truck] == destino: return [] else: return False def mover_camion(state, destino): for truck in state.trucks.keys(): ubicacion = state.trucks[truck] return[('conseguir_conductor', ubicacion), ('conducir_al_destino', ubicacion, destino)]
state.num_victims -= 1; return state; def call_success(state, goal): for a in state.ambulances.items(): print(a[0], ": ", a[1]["t"]); if(state.num_victims <= 0): print("Success!!"); return []; else: return False; #############################PYHOP############################ state1 = pyhop.State("state1"); state1.hospitals = hospitals; state1.ambulances = ambulances; state1.victims = victims; state1.num_victims = len(victims); goal1 = pyhop.Goal("goal1"); goal1.num_victims = 0; pyhop.declare_operators(move_ambulance, enter_ambulance, exit_ambulance); pyhop.declare_methods('save_the_victims', save_victim, call_success); pyhop.pyhop(state1,[('save_the_victims', goal1)], verbose=1);
def sign(state, document, office): if (state.at[document] == office): state.signed.append(document) return state else: return False pyhop.declare_operators(GoTo, shred, take, leave, sign) def goAndGet(state, document): robot_start = state.at['robot'] doc_start = state.at[document] return [('GoTo', robot_start, doc_start), ('take', document, doc_start)] pyhop.declare_methods('goAndGet', goAndGet) def deliver(state, document, office): robot_start = state.at['robot'] return[('GoTo', robot_start, office), ('leave', document, office)] pyhop.declare_methods('deliver', deliver) def takeAndSign(state, document, office): return [('deliver', document, office), ('sign', document, office), ('take', document, office)] pyhop.declare_methods('takeAndSign', takeAndSign) def seek_destroy(state, document): return[('goAndGet', document),
def setupTeaAtHome(): '''!@brief Setup tea at home. This method declares operators, tasks and methods to pyhop. This must be called BEFORE running pyhop with teaathome. ''' pyhop.declare_operators(goto, openitem, grasp, place, close, check, weigh, placein, turnonkettlebase, access, opencoldtap, pourintocup) pyhop.declare_methods('taskmaketea', maketea) pyhop.declare_methods('taskpreparehotwater', preparehotwater_fullhotk, preparehotwater_fullk, preparehotwater) pyhop.declare_methods('taskcheckkettlefill', checkkettlefill) pyhop.declare_methods('tasplacekettleinsink', placekettleinsink) pyhop.declare_methods('taskfillkettle', fillkettle_kopen, fillkettle) pyhop.declare_methods('taskplacekettleonbase', placekettleonbase) pyhop.declare_methods('taskbringkettletobase', bringkettletobase) pyhop.declare_methods('taskboilwater', boilwater) pyhop.declare_methods('taskgetcleancup', getcleancup) pyhop.declare_methods('taskcheckcupdirty', checkcupdirty) pyhop.declare_methods('taskplacecup', placecup) pyhop.declare_methods('taskfinalizetea', finalizetea) pyhop.declare_methods('taskprepareteabag', prepareteabag) pyhop.declare_methods('taskgetteabag', getteabag) pyhop.declare_methods('taskplacebagincup', placebagincup) pyhop.declare_methods('taskbrewtea', brewtea_kopen, brewtea)
else: num_states_explored = num_states_explored + 1; return False def move_disk(state, disk, source, dest, spare): global num_states_explored; if disk == 0: return [('move', disk, source, dest)] else: num_states_explored = num_states_explored + 1; return False pyhop.declare_methods('move_tower', move_stack, move_disk) print('') pyhop.print_methods() ## Num Disks num_disks = int(sys.argv[1]); num_states_explored = 0; ## Define state state1 = pyhop.State('state1') state1.loc = {}; for i in range(0,num_disks): state1.loc[i] = 0 ## Run SHOP planner t0 = time.time() result = pyhop.pyhop(state1, [('move_tower', num_disks -1, 0, 2, 1)], verbose=0);