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)
def testOneMoreThanGoal(self): state = game1.get_start_state() state.days['green'] = [[2, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]] state.days['blue'] = [[0, 2, 0, 0], [0, 0, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [2, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] self.assertEqual( len(pyhop.pyhop(state, [('sort_meds', game1.get_goal())])), 1)
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
def get_plans(self, world_model, goal): """ Returns all the suggested plans, given a world model (state object), goal (list) and an internal collection of primitive and compound tasks. :param world_model: The current perceived world state (json object). :param goal: The end goal we try to achieve (tuple). :return: List of suggested plans. """ if goal is not "": return pyhop.pyhop(world_model, goal, verbose=self.verbose, all_plans=True, sort_asc=True) else: return ""
def get_plans(self, world_model, goal): """ :param world_model: The current perceived world state (json object). :param goal: The end goal we try to achieve (tuple). :return: List of suggested plans. """ if goal is not "": return pyhop.pyhop(world_model, goal, verbose=self.verbose, all_plans=True, sort_asc=True) else: return ""
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) t1 = time.time() total = t1 - t0 ## Print state count = 0 for i in result: print count, '- Move disk', i[1] + 1, 'from', i[2], 'to', i[3] count = count + 1 print '--------------------' print 'Time taken:', total, 'seconds' print 'Total number of states explored:', num_states_explored
def find_plan(state, goal): return pyhop.pyhop(state, [('travel_by_goal', goal)], verbose=0)
def testStart(self): state = game1.get_start_state() self.assertEqual( len(pyhop.pyhop(state, [('sort_meds', game1.get_goal())])), 13)
# from pyhop import * import pyhop import methods_and_operators state0 = pyhop.State('state0') state0.energy = 50 state0.knowledge = 10 state0.health = 50 state0.fed = 100 state0.backlog = 10 state0.sph_left = 100 pyhop.pyhop(state0, [('finish_thesis_task',)], verbose=2)
pyhop.print_methods() state1 = pyhop.State('state1') state1.loc = {'me':'home'} state1.cash = {'me':20} # To get multidimensional tables in Python, # you have to use nested lists # (or in this case, nested dictionaries) state1.dist = {'home':{'park':8}} print(""" **************************************** Call pyhop.pyhop(state1,[('travel','me','home','park')]) with different levels of verbosity **************************************** """) print('- verbosity 0:') pyhop.pyhop(state1,[('travel','me','home','park')]) print('- verbosity 1:') pyhop.pyhop(state1,[('travel','me','home','park')],verbose=1) print('- verbosity 2:') pyhop.pyhop(state1,[('travel','me','home','park')],verbose=2) print('- verbosity 3:') pyhop.pyhop(state1,[('travel','me','home','park')],verbose=3)
import pyhop import transp_methods import transp_tasks state1=pyhop.State('state1') #Informacion dinamica state1.at_camiones={'t1':'c1','t2':'c0'} state1.carga_camion={'t1':[],'t2':[]} state1.at_cond={'d1':'pi_01','d2':'c1'} state1.at_paquete={'p1':'c0','p2':'c0'} #Informacion estatica state1.ruta_cam={'c0':['c1','c2'],'c1':['c0','c2'],'c2':['c0','c1']} state1.ruta_cond={'c0':['pi_01'],'pi_01':['c0','c1'],'c1':['pi_01','pi_12'],'pi_12':['c1','c2'],'c2':['pi_12']} state1.distancias={'c0':{'pi_01':1,'c1':2,'pi_12':3,'c2':4}, 'pi_01':{'c0':1,'c1':1,'pi_12':2,'c2':3}, 'c1':{'c0':2,'pi_01':1,'pi_12':1,'c2':2}, 'pi_12':{'c0':3,'p_01':2,'c1':1,'c2':1}, 'c2':{'c0':4,'pi_01':3,'c1':2,'pi_12':1}} #GOAL pyhop.pyhop(state1, [('pack_to_dest','p1','c1'),('pack_to_dest','p2','c2'),('drive_to_dest','t1','c1'),('walk_to_dest','d1','c1')],verbose=3)
# pyhop.print_methods() # End - Methods #result format: ('print_a_concept_1', 'Concept B'), ('print_a_concept_2', 'Concept A'), # query versbose_level = 1 target_heard_count = 5 if len(sys.argv) > 1: if sys.argv[1] == "--help": print "args: target_heard_count versbose_level" exit(0) target_heard_count = int(sys.argv[1]) if len(sys.argv) > 2: versbose_level = int(sys.argv[2]) print "planning for target_heard_count:", target_heard_count, " with versbose_level:", versbose_level result = pyhop.pyhop(state1, [('teach', target_heard_count)], verbose=versbose_level) # plot_plan(result) state_data = simulate_plan_execute(result, state1) plot_plan(result, state_data, [ "/affect/challenge", "/affect/boredom", "/affect/skill", '/affect/frustration' ]) #end - query
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)
#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, 'wooden_pickaxe': False, 'stone_axe': False, 'stone_pickaxe': False, 'iron_axe': False, 'iron_pickaxe': False } state.time = 50 if __name__ == '__main__': print("starting") pyhop.pyhop(state, [('produce_wood', 5)], verbose=1)
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}} # state1.dist = {'home': {'park': 5}, 'park': {'home': 5}} print(""" ******************************************************************************** Call pyhop.pyhop(state1,[('travel','me','home','park')]) with different verbosity levels ******************************************************************************** """) # print("- If verbose=0 (the default), Pyhop returns the solution but prints nothing.\n") # pyhop.pyhop(state1, [('travel', 'me', 'home', 'park')]) # print('- If verbose=1, Pyhop prints the problem and solution, and returns the solution:') # pyhop.pyhop(state1, [('travel', 'me', 'home', 'park')], verbose=1, all_plans=True) # print('- If verbose=2, Pyhop also prints a note at each recursive call:') # pyhop.pyhop(state1, [('travel', 'me', 'home', 'park')], verbose=2) print('- If verbose=3, Pyhop also prints the intermediate states:') pyhop.pyhop(state1, [('travel', 'me', 'home', 'park')], verbose=3) # TODO: Terms: # TODO: Operators: parameterized descriptions of what the basic actions do # TODO: Actions: operators with arguments # TODO: Method: parameterized description of a possible way to perform a compound task by performing a collection of subtasks # TODO: There may be more than one method for the same task
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" htn_plans = pyhop.pyhop( current_world_model, [('transfer_ball_to_container', 'arm', 'ball', 'table', 'container')], verbose=1, all_plans=True, sort_asc=True) print() if not htn_plans: print("-- No valid plan. Failure_reason: {}".format(pyhop.failure_reason)) else: current_world_model.plans = htn_plans print("Best current_world_model.plan: ", current_world_model.plans[0])
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 result = pyhop.pyhop(state, [('travel', 'home', 'target')], verbose=3)
pyhop.declare_operators(move, mop, lock) def clean_lock(state, room): return [('move', state.robot_location, room), ('mop', room), ('lock', room)] pyhop.declare_methods('clean_lock', clean_lock) def clean_lock_all(state, rooms): return [[('clean_lock', room)] for room in rooms] # return [('clean_lock', rooms[0]), # ('clean_lock', rooms[1]), # ('clean_lock', rooms[2]), # ('clean_lock', rooms[3]), # ('clean_lock', rooms[4])] # Ideally, this function would include all dirty rooms in the state and # iteratively or recursively break the function down into the smaller # methods and operations. I can't seem to figure out how to recurse or # iterate with pyhop's source code. pyhop.declare_methods('clean_lock_all', clean_lock_all) # pyhop.pyhop(domains.mopper1, domains.moprob, verbose=3) pyhop.pyhop(domains.mopper2, domains.mopall, verbose=3)
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} state.money = {'me' : 200} pyhop.pyhop(state, [('buy', 'me')], verbose = 3) print('\n#########################################################\n') #3rd customer state.time = {'me' : 700} state.money = {'me' : 500} pyhop.pyhop(state, [('buy', 'me')], verbose = 3) print('\n#########################################################\n') #4th customer state.time = {'me' : 700} state.money = {'me' : 450} pyhop.pyhop(state, [('buy', 'me')], verbose = 3)
def find_plan(state, goal): return pyhop.pyhop(state,[('travel_by_goal', goal)],verbose=0)
def result_length(state, event): modify_state(state, event[0], event[1], event[2], event[3], event[4]) temp_state = deepcopy(state) return len(pyhop.pyhop(temp_state, [('sort_meds', get_goal())], verbose=1))
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)
else: return False def classify(state): if (state.holding == 'red'): state.red = True return state elif (state.holding == 'green'): state.green = True return state elif (state.holding == 'blue'): state.blue = True return state else: return False def leave(state): if (state.holding == state.robot_location): state.amounts[state.holding] += 1 state.holding = None return state else: return False pyhop.declare_operators(move, take, classify, leave) pyhop.pyhop(domains.state22, domains.prob22, verbose=3)
state1.communicated_soil_data = [] state1.communicated_rock_data = [] state1.communicated_image_data = [] state1.crossed = {'r0': ['w3']} #Static info state1.can_traverse = { 'r0': [['w0', 'w3'], ['w1', 'w3'], ['w1', 'w2'], ['w2', 'w0'], ['w3', 'w0'], ['w3', 'w1'], ['w2', 'w1'], ['w0', 'w2']] } state1.equipped_for_soil_analysis = {'r0'} state1.equipped_for_rock_analysis = {'r0'} state1.equipped_for_imaging = {'r0'} state1.supports = {'r0': {'c0': {'colour', 'high-res'}}} state1.calibration_target = {'c0': 'o1'} state1.on_board = {'r0': {'c0'}} state1.visible = { 'w0': {'w1', 'w2', 'w3'}, 'w1': {'w0', 'w2', 'w3'}, 'w2': {'w0', 'w1', 'w3'}, 'w3': {'w0', 'w1', 'w2'} } state1.visible_from = {'o1': {'w0', 'w1', 'w2', 'w3'}} state1.store_of = {'r0': 'r0store'} state1.rovers = ['r0'] #GOAL pyhop.pyhop(state1, [('communicate_soil_data', 'w2')], verbose=3) #pyhop.pyhop(state1, [('communicate_rock_data','w3')], verbose=3) #pyhop.pyhop(state1, [('communicate_image_data','o1','high-res')], 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)
#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 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} pyhop.pyhop(state, [('eat', 'me')], verbose = 3) print('\n#########################################################\n') #Wednesday state.time = {'me' : 20} pyhop.pyhop(state, [('eat', 'me')], verbose = 3) print('\n#########################################################\n') #Thursday state.time = {'me' : 100} pyhop.pyhop(state, [('eat', 'me')], verbose = 3) print('\n#########################################################\n') #Friday state.time = {'me' : 25}
state1.crossed={'T1':['D0'],'T0':['D1']} #Static info #state1.can_traverse=[['D0','D1'],['D1','D0'],['D1','D2'],['D2','D1'],['D0','D2'],['D2','D0']] state1.can_traverse={'D0':['D1','D2'], 'D1':['D0','D2','FUEL'], 'D2':['D0','D1','D3'], 'D3':['D2','D4'], 'D4':['D3'], 'FUEL':['D1']} state1.pallet_board={'D0':{'P00','P01'},'D1':{'P10'},'D2':{'P20'},'D3':{'P30'},'D4':{'P40'}} state1.crans={'H0':'D0', 'H1':'D1', 'H2':'D2', 'H3':'D3', 'H4':'D4'} state1.fuel_limit={'T0':'8','T1':'8'} state1.carry_limit={'T0':'2','T1':'2'} state1.truck=['T1','T0'] #GOAL pyhop.print_methods() pyhop.print_operators() #pyhop.pyhop(state1, [('go_to_waypoint','T1','D4')], verbose=3) pyhop.pyhop(state1,[('move_container', ['C0','C11','C05'], 'P40')], verbose=3) #pyhop.pyhop(state1,[('move_container', ['C01'], 'P40')], verbose=3) #find shortestpath -done #move method replaced on base of shortpath - done #find nearest truck - done #fuel count, limit, consumption - done #refuel if needed-done #select nearest truck based on fuel limit (if path consumptin is lesser,than truck limit) - done #add check if its on truck -done #double pallet container replacement use instead of truck moving if available #add check if its on cran - done,but removed. #truck carry_limit added and managed
return [('deliver', document, office), ('sign', document, office), ('take', document, office)] pyhop.declare_methods('takeAndSign', takeAndSign) def seek_destroy(state, document): return[('goAndGet', document), ('shred', document)] pyhop.declare_methods('seek_destroy', seek_destroy) def take_deliver(state, document, end): return[('goAndGet', document), ('deliver', document, end)] pyhop.declare_methods('take_deliver', take_deliver) def take_sign_deliver(state, document, sign, end): return[('goAndGet', document), ('takeAndSign', document, sign), ('deliver', document, end)] pyhop.declare_methods('take_sign_deliver', take_sign_deliver) pyhop.pyhop(domains.state1, domains.prob13, verbose=2) pyhop.pyhop(domains.state2, domains.prob2, verbose=2) pyhop.pyhop(domains.state3, domains.prob3, verbose=2)
def testSameState(self): state = game1.get_start_state() game1.modify_state(state, 'green', 0, 0, 'add_pill', 1) game1.modify_state(state, 'green', 0, 0, 'remove_pill', 1) self.assertEqual( len(pyhop.pyhop(state, [('sort_meds', game1.get_goal())])), 13)
'''cleancups = 0 while cleancups <= state.NUMBER_OF_DIRTY_TEACUPS: cup = 'teacup'+str(random.randint(1, state.TOTAL_NUMBER_OF_TEACUPS)) if(state2.itemstate[cup]['cleanstate'] == Itemstate.unknown): state2.itemstate[cup]['cleanstate'] = Itemstate.clean cleancups = cleancups + 1''' state.currentcup = '' return state print( '''Running: pyhop.pyhop(teaathome.setupRobotArm(test1()),[('taskmaketea','robot','teabag', 1)],verbose=2)''' ) print('') teaathome.setupTeaAtHome() pyhop.print_operators() print('') pyhop.print_methods() print('') pyhop.pyhop(teaathome.setupRobotArm(test1()), [('taskmaketea', 'robot', 'teabag', 1)], verbose=2) sys.stdout.close() sys.stdout = sys.__stdout__ print('Result log file: logs/test1.log')
# Definicion del objetivo goal1 = pyhop.Goal('goal1') goal1.loc = {'me':'park', 'you':'university'} print(""" ******************************************************************************** Call pyhop.pyhop(state1,[('travel','me','home','park')]) with different verbosity levels ******************************************************************************** """) # Buscamos un plan a partir de un estado inicial para que "me" viaje de "home" a "park" # pyhop.pyhop(state1, [('travel','me','home','park')], verbose=1) pyhop.pyhop(state1, [('travel', goal1)], verbose=1) """ Importante para depurar: Necesitamos: import pdb Ponemos la instruccion "pdb.set_trace()" donde queramos en nuestro codigo y se detendra la ejecucion Luego simplemente escribimos la letra 'n' desde el shell que ejecutara la siguiente sentencia y podemos ir viendo el valor de las variables """
def travel_by_goal_state(state, goal): # Get the problem domain info related file fo = openFile('static_value.txt') exec('content=' + fo.read()) global static_state static_state = pyhop.State("static") for stateItem in content: # Load the problem domain info into the state exec("static_state." + stateItem) a = state.target x = state.loc[a] y = goal.loc[a] t = state.time[a] cashX = state.cash[a] if hasattr(goal, 'cash'): cashY = goal.cash[a] else: cashY = 0 # Get the nearest bus stop bs = state.nearest_bus_stop[state.target] # Get the bus fair bus_fair = bus_rate(distance(bs, y)) if distance(x, y) <= 2 and t >= time_cost_walk(distance(x, y)): # If walking is possible, then travel by foot return travel_by_foot(state, a, x, y) elif cashX >= taxi_rate(distance(x,y)) and cashY<=cashX-taxi_rate(distance(x,y)) \ and t >= time_cost_taxi(distance(x,y)): # If taxi travel is possible, then travel by taxi return travel_by_taxi(state, a, x, y) elif cashX >= bus_fair and cashY <= cashX - bus_fair \ and distance(x,bs) <= 2 and (bs+':'+y in static_state.bus_route) \ and t >= time_cost_bus(distance(x,y)): # If bus travel is possible, then travel by bus return travel_by_bus(state, a, x, y) elif y != 'bank': # If no travel is possible, now we will try to go to the bank to withdraw some money # and continue the journey from there # Intermediate state will be the bank location intermediateState = generate_new_state('intermediateState') intermediateState.loc = {} intermediateState.cash = {} intermediateState.cash = {} intermediateState.time = {} intermediateState.balance_bank = {} intermediateState.nearest_bus_stop = {} intermediateState.target = 'me' intermediateState.loc[state.target] = 'bank' intermediateState.loc['bus'] = state.loc['bus'] intermediateState.cash[state.target] = taxi_rate(distance('bank', y)) intermediateState.balance_bank[state.target] = state.balance_bank[ state.target] intermediateState.nearest_bus_stop[ state.target] = state.nearest_bus_stop[state.target] # Find the plan to the bank from the source state plan1 = pyhop.pyhop(state, [('travel_by_goal', intermediateState)], verbose=0) # Get the cost of this intermediate plan cost1 = costForPlan(plan1) # Reduce the amount by cost1 intermediateState.cash[state.target] = state.cash[state.target] - cost1 if plan1 != False: # Now we have a plan to travel to the bank # Need one more plan to travel to the goal from the bank # Amount needed to reach the goal from the bank amount_needed = cost1+taxi_rate(distance('bank',y))+\ goal.cash[state.target]-state.cash[state.target]+3.0 # Get a plan to withdraw necessary amount from the bank plan2 = withdraw_money_from_bank(intermediateState, a, amount_needed) # If we have that much money in the bank, the plan will pass if plan2 != False: # Append the withdraw money plan at the end of the first plan plan1.extend(plan2) # Reflect the time remaining intermediateState.time[state.target] = state.time[state.target] # Find the next plan of going to the destination from the bank plan3 = pyhop.pyhop(intermediateState, [('travel_by_goal', goal)], verbose=0) if plan3 != False: # All plans are passed, extend the last plan at the end plan1.extend(plan3) return plan1 return False else: return False
pyhop.declare_methods('travel',travel_by_car) print('') pyhop.print_methods() #INITIAL STATE state1 = pyhop.State('state1') state1.coordinates = {'Huelva':{'X':25,'Y':275}, 'Cadiz':{'X':200,'Y':50}, 'Sevilla':{'X':250,'Y':325}, 'Cordoba':{'X':475,'Y':450}, 'Malaga':{'X':550,'Y':100}, 'Jaen':{'X':750,'Y':425}, 'Granada':{'X':800,'Y':250}, 'Almeria':{'X':1000,'Y':150}} state1.connection = {'Huelva':{'Sevilla'}, 'Sevilla':{'Cadiz','Huelva','Cordoba','Malaga'}, 'Cadiz':{'Sevilla','Malaga'}, 'Cordoba':{'Sevilla','Malaga','Jaen'}, 'Malaga':{'Cadiz','Huelva','Cordoba','Sevilla','Granada','Almeria'}, 'Jaen':{'Cordoba','Granada'},'Granada':{'Jaen','Malaga','Almeria'}, 'Almeria':{'Granada','Malaga'}} state1.location = 'Huelva' state1.location_car = 'Huelva' state1.path = ['Huelva'] state1.cost = 0 #GOAL goal1 = pyhop.Goal('goal1') goal1.final = 'Almeria' print('- If verbose=3, Pyhop also prints the intermediate states:') result=pyhop.pyhop(state1,[('travel',goal1)],verbose=3) print(result)
def travel_by_goal_state(state, goal): # Get the problem domain info related file fo = openFile('static_value.txt') exec('content=' + fo.read()) global static_state static_state = pyhop.State("static") for stateItem in content: # Load the problem domain info into the state exec("static_state."+stateItem) a = state.target x = state.loc[a] y = goal.loc[a] t = state.time[a] cashX = state.cash[a] if hasattr(goal, 'cash'): cashY = goal.cash[a] else: cashY = 0 # Get the nearest bus stop bs = state.nearest_bus_stop[state.target] # Get the bus fair bus_fair = bus_rate(distance(bs,y)) if distance(x,y) <= 2 and t >= time_cost_walk(distance(x,y)): # If walking is possible, then travel by foot return travel_by_foot(state,a,x,y) elif cashX >= taxi_rate(distance(x,y)) and cashY<=cashX-taxi_rate(distance(x,y)) \ and t >= time_cost_taxi(distance(x,y)): # If taxi travel is possible, then travel by taxi return travel_by_taxi(state,a,x,y) elif cashX >= bus_fair and cashY <= cashX - bus_fair \ and distance(x,bs) <= 2 and (bs+':'+y in static_state.bus_route) \ and t >= time_cost_bus(distance(x,y)): # If bus travel is possible, then travel by bus return travel_by_bus(state,a,x,y) elif y != 'bank': # If no travel is possible, now we will try to go to the bank to withdraw some money # and continue the journey from there # Intermediate state will be the bank location intermediateState = generate_new_state('intermediateState') intermediateState.loc = {} intermediateState.cash = {} intermediateState.cash = {} intermediateState.time = {} intermediateState.balance_bank = {} intermediateState.nearest_bus_stop = {} intermediateState.target = 'me' intermediateState.loc[state.target] = 'bank' intermediateState.loc['bus'] = state.loc['bus'] intermediateState.cash[state.target] = taxi_rate(distance('bank',y)) intermediateState.balance_bank[state.target] = state.balance_bank[state.target] intermediateState.nearest_bus_stop[state.target] = state.nearest_bus_stop[state.target] # Find the plan to the bank from the source state plan1 = pyhop.pyhop(state,[('travel_by_goal', intermediateState)],verbose=0) # Get the cost of this intermediate plan cost1 = costForPlan(plan1) # Reduce the amount by cost1 intermediateState.cash[state.target] = state.cash[state.target] - cost1 if plan1 != False: # Now we have a plan to travel to the bank # Need one more plan to travel to the goal from the bank # Amount needed to reach the goal from the bank amount_needed = cost1+taxi_rate(distance('bank',y))+\ goal.cash[state.target]-state.cash[state.target]+3.0 # Get a plan to withdraw necessary amount from the bank plan2 = withdraw_money_from_bank(intermediateState,a,amount_needed) # If we have that much money in the bank, the plan will pass if plan2 != False: # Append the withdraw money plan at the end of the first plan plan1.extend(plan2) # Reflect the time remaining intermediateState.time[state.target] = state.time[state.target] # Find the next plan of going to the destination from the bank plan3 = pyhop.pyhop(intermediateState,[('travel_by_goal', goal)],verbose=0) if plan3 != False: # All plans are passed, extend the last plan at the end plan1.extend(plan3) return plan1 return False else: return False
state1.paquete = ['P1', 'P2'] ''' state1.senda = {'W01':{'C0','C1'}, 'W12':{'C1', 'C2'} } ''' state1.senda = [['C0', 'S1'], ['S1', 'C0'], ['S1', 'C1'], ['C1', 'S1'], ['C1', 'S2'], ['S2', 'C1'], ['S2', 'C2'], ['C2', 'S2']] state1.carretera = [['C0', 'C1'], ['C1', 'C0'], ['C1', 'C2'], ['C2', 'C1'], ['C0', 'C2'], ['C2', 'C0']] #ESTADO DINAMICO state1.ubi_camion = {'T1': 'C1', 'T2': 'C0'} state1.ubi_conductor = {'D1': 'S1', 'D2': 'C1'} state1.ubi_paquete = {'P1': 'C0', 'P2': 'C0'} state1.contenido_camiones = {'T1': [], 'T2': []} goal1 = pyhop.Goal('goal1') #goal1 = [ ['D1', 'C1'], ['D2', 'C2'], ['T1', 'C1'], ['T2', 'C0'], ['P1', 'C1'], ['P2','C2'] ] goal1 = { 'D1': 'C1', 'D2': 'C2', 'T1': 'C1', 'T2': 'C0', 'P1': 'C1', 'P2': 'C2' } pyhop.pyhop(state1, [('mover_todo_destino', goal1)], verbose=3)
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) person.fullness = {'me_friends': 0.0} person.time = {'me_friends': 1000} person.money = {'me_friends': 30} pyhop.pyhop(person, [('eating', 'me_friends', 3.0)], verbose=3) person.fullness = {'me_friends': 0.0} person.time = {'me_friends': 110} person.money = {'me_friends': 2000}
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);
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); t1 = time.time() total = t1 - t0; ## Print state count = 0; for i in result: print count,'- Move disk', i[1]+1, 'from', i[2], 'to',i[3] count = count + 1; print '--------------------' print 'Time taken:',total,'seconds' print 'Total number of states explored:', num_states_explored