Exemple #1
0
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)
Exemple #2
0
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
Exemple #3
0
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)
Exemple #4
0
def ask_true_false_on_relation(state, r):
    state.status += 1
    state.variables.affect.frustration += 1  # how to model user's success rate on a particular question
    state.variables.affect.challenge += 1
    state.variables.affect.boredom -= 1
    # print "Is it true?\n", r
    return state


def show_congrats(state, a=0):
    return state


pyhop.declare_operators(print_a_concept_1, print_a_concept_2,
                        print_a_relation_1, print_a_relation_2,
                        ask_true_false_on_concept, ask_true_false_on_relation,
                        show_congrats)
# pyhop.print_operators()

# End - Operators

# Methods


def present_a_concept(state, c):
    if state.variables.affect.boredom < 3:
        if random.randint(0, 100) < 50:
            return [('print_a_concept_1', c)]
        else:
            return [('print_a_concept_2', c)]
    return []
    state.health = state.health - WORK_HEALTH_COST
    return state
  else:
    return False


def eat(state):
  state.fed = state.fed + FED_VAL
  state.health = state.health - WORK_HEALTH_COST
  state.backlog = state.backlog + BACKLOG_INCREMENT_VAL
  return state


def relax(state):
  state.energy = state.energy + RELAX_VAL
  state.backlog = state.backlog + BACKLOG_INCREMENT_VAL
  return state


def gym(state):
  if state.fed >= WORK_FED_REQ:
    state.health = state.health + HEALTH_VAL
    state.energy = state.energy - WORK_ENERGY_COST
    state.fed = state.fed - WORK_FOOD_COST
    state.backlog = state.backlog + BACKLOG_INCREMENT_VAL
    return state
  return False


pyhop.declare_operators(finish_thesis, write_sph, write_other, study, eat, relax, gym)
def visit(state, agent, waypoint):
	state.visited[agent].add(waypoint)
	return state

def unvisit(state, agent, waypoint):
	state.visited[agent].remove(waypoint)
	return state


"""
Below, 'declare_operators(pickup, unstack, putdown, stack)' tells Pyhop
what the operators are. Note that the operator names are *not* quoted.
"""

pyhop.declare_operators(navigate_op, 
	sample, 
	set_up_rock_experiment, 
	set_up_soil_experiment, 
	analyze_rock_sample, 
	analyze_soil_sample,
	drop,
	calibrate,
	take_image,
	communicate_data,
	visit,
	unvisit)


""" 
TODO: Figure out what to do if there are different preconditions for the same operator. For example: Sampling rock or soil depending on where.
"""
		return state
	else:
		return False

# Calculate the total cost for this specific plan
def costForPlan(plan):
	cost = 0
	if plan != False:
		for item in plan:
			if item[0][0:3] == "pay":
				# Add up all cost that have the action 'pay'
				cost = cost + item[2]
	return cost

# Decalare all the operators for pyhop
pyhop.declare_operators(walk, call_taxi, ride_taxi, pay_cab_driver, pay_bus_driver, ride_bus, withdraw_money)

# Main pyhop method to reach the goal state from initial state
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]	
Exemple #8
0
            state.ubi_camion[camion] = destino
            state.ubi_conductor[conductor] = destino
            return state
    else:
        return False


def viajar_a_pie(state, conductor, destino):
    lugar = state.ubi_conductor[conductor]
    if lugar not in state.parada:
        for p in state.parada:
            for x in state.senda:
                if ((destino == x[0]) and (p == x[1])):
                    for y in state.senda:
                        if ((p == y[0]) and (lugar == y[1])):
                            state.ubi_conductor[conductor] = destino
                            return state
    else:
        for i in range(len(state.senda)):
            if ((lugar == state.senda[i][0])
                    and (destino == state.senda[i][1])):
                state.ubi_conductor[conductor] = destino
                return state
    return False


pyhop.declare_operators(cargar_paquete, descargar_paquete,
                        conductor_subir_camion, conductor_bajar_camion,
                        viajar_en_camion, viajar_a_pie)
pyhop.print_operators()
Exemple #9
0
sys.setrecursionlimit(30000)
global num_states_explored


## Operators
def move(state, disk, source, dest):
    global num_states_explored
    if state.loc[disk] == source:
        state.loc[disk] = dest
        num_states_explored = num_states_explored + 1
        return state
    else:
        return False


pyhop.declare_operators(move)
print('')
pyhop.print_operators()


## Methods
def move_stack(state, disk, source, dest, spare):
    global num_states_explored
    if disk > 0:
        return [('move_tower', disk - 1, source, spare, dest),
                ('move', disk, source, dest),
                ('move_tower', disk - 1, spare, dest, source)]
    else:
        num_states_explored = num_states_explored + 1
        return False
		state.wood = state.wood + GATHER_WOOD
		return state
	else:
		return False

def train_peon(state):
	if state.gold >= PEON_COST_GOLD and state.free_places > 0:
		state.gold = state.gold - PEON_COST_GOLD
		state.free_places = state.free_places - 1
		state.peons = state.peons + 1
		return state
	return False

def build_house(state):
	if state.gold >= HOUSE_COST_GOLD:
		state.gold = state.gold - HOUSE_COST_GOLD
		state.free_places = state.free_places + 5
		state.houses = state.houses + 1
		return state
	return False

def build_watchtower(state):
	if state.gold >= WATCHTOWER_COST_GOLD and state.wood >= WATCHTOWER_COST_WOOD and state.peons > 0:
		state.gold = state.gold - WATCHTOWER_COST_GOLD
		state.peons = state.peons - 1
		state.wood = state.wood - WATCHTOWER_COST_WOOD
		return state
	return False

pyhop.declare_operators(build_barracks,gather_gold,gather_wood,train_peon,build_house,build_watchtower)
def declare_ops():
    pyhop.declare_operators(pickup, unstack, unstack_mortared, putdown, stack,
                            stack_mortared, putoutfire, apprehend, searchfor,
                            get_from_store)
Exemple #12
0
def ride_taxi(state,a,x,y):
    if state.loc['taxi']==x and state.loc[a]==x:
        state.loc['taxi'] = y
        state.loc[a] = y
        state.owe[a] = taxi_rate(state.dist[x][y])
        return state
    else: return False

def pay_driver(state,a):
    if state.cash[a] >= state.owe[a]:
        state.cash[a] = state.cash[a] - state.owe[a]
        state.owe[a] = 0
        return state
    else: return False

pyhop.declare_operators(walk, call_taxi, ride_taxi, pay_driver)
print('')
pyhop.print_operators()



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), ('ride_taxi',a,x,y), ('pay_driver',a)]
    return False
Exemple #13
0
    if (state.robot_location == room):
        state.clean.append(room)
        return state
    else:
        return False


def lock(state, room):
    if (state.robot_location == room) and (room in state.clean):
        state.locked.append(room)
        return state
    else:
        return False


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]),
Exemple #14
0
    return False


def call_taxi(state, x):
    if state.loc['taxi'] != x and \
                    state.time >= 5:
        state.time -= 5
        state.loc['taxi'] = x
        return state
    return False


pyhop.declare_operators(
    ride_car,
    ride_public_transport,
    walk,
    ride_taxi,
    call_taxi
)


def travel_car(state, x, y):
    return [('ride_car', x, y)]


def travel_taxi_pt(state, x, y):
    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)]
	state.time[agent] = state.time[agent] - 280
	state.money[agent] = state.money[agent] - 168
	return state 

def pocket(state, agent):
	state.time[agent] = state.time[agent] - 240
	state.money[agent] = state.money[agent] - 190
	return state
	
def foam(state, agent):
	state.time[agent] = state.time[agent] - 390
	state.money[agent] = state.money[agent] - 130
	return state

####################### Operators declaration:
pyhop.declare_operators(offline, own_transport, post_transport, bonell, pocket, foam)
print('\n#########################################################\n')
pyhop.print_operators()

####################### Ordering and dependencies:
def buy_foam(state, agent):
	if state.time[agent] >= 490: #Offline
		if ((state.money[agent] >= 160) and (state.time[agent] >= 530)):
			return [('own_transport', agent),('foam', agent), ('offline', agent)]
		elif state.money[agent] >= 190:
			return [('post_transport', agent),('foam', agent), ('offline', agent)]			
	elif state.time[agent] >= 450: #Online
		if state.money[agent] >= 200:
			return [('post_transport', agent),('foam', agent)]
	else:
		return False
Exemple #16
0
            state.empty[truck].extend(state.empty[cran])
        state.empty[cran]=True
        return state
    else:
        return False


def find_shortest_path(graph, start, end, path=[]):
        path = path + [start]
        if start == end:
            return path
        if start not in graph.keys():
            return None
        shortest = None
        for node in graph[start]:
            if node not in path:
                newpath = find_shortest_path(graph, node, end, path)
                if newpath:
                    if not shortest or len(newpath) < len(shortest):
                        shortest = newpath
        return shortest
    
    
    
def done(state, container_list, destination):
    return state
#find_shortest_path(path,'D', 'D5')

pyhop.declare_operators(already_there,already_unloaded,lift,drop,load,unload,find_shortest_path,done)
#pyhop.declare_operators(already_there,navigatsample_soil,sample_rock,drop,calibrate,take_image,communicate_soil_data_to_lander,communicate_rock_data_to_lander,communicate_image_data_to_lander)
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)
Exemple #18
0
    return agents


def robot_stack(agents, self_state, self_name):
    if self_state.isCarrying[self_name] is not None:
        c = self_state.isCarrying[self_name]
        for a in agents.values():
            a.state.isOnStack[c] = True
            a.state.onStack.append(c)
            a.state.isCarrying[self_name] = None
        return agents
    else:
        return False


pyhop.declare_operators("human", human_pick, human_stack, human_wait)
pyhop.declare_operators("robot", robot_pick, robot_stack)

### Methods definitions


def moveb_m_human(agents, self_state, self_name, c, goal):
    if self_name in self_state.isReachableBy[
            c] and c in goal.isOnStack and goal.isOnStack[
                c] and not self_state.isOnStack[c]:
        return [("human_pick", c), ("human_stack", )]
    return []


def moveb_m_robot(agents, self_state: pyhop.State, self_name, c, goal):
    if self_name in self_state.isReachableBy[
        arm_xyz, servo_values = get_xyz(to_)
        if arm_xyz != False:
            state.location['arm_xyz'] = arm_xyz
            state.location['servo_values'] = servo_values
            arm_xyz, servo_values = move_arm(state, to_)
            if arm_xyz != False:
                actee_diameter = get_diameter(actee)
                if open_hand(actee_diameter):
                    state.location['arm_xyz'] = arm_xyz
                    state.location['servo_values'] = servo_values
                    return state
    pyhop.failure_reason = "{} can't put {} to {}".format(actor, actee, to_)
    return False


pyhop.declare_operators(initialize, grab, put, move_arm, close_hand, open_hand)
print('')
pyhop.print_operators()

# Methods (compound tasks)


def put_grabbed(state, actor, actee, from_, to_):
    if actor == "arm":
        if state.grabbed["ball"]:
            return [('put', actor, actee, to_)]

    pyhop.failure_reason = "{} can't put_grabbed {} from {} to {}".format(
        actor, actee, from_, to_)
    return False
        return state
    else: return False

def pay_driver(state,a):
    if state.cash[a] >= state.owe[a]:
        state.cash[a] = state.cash[a] - state.owe[a]
        state.owe[a] = 0
        return state
    else: return False


# Declaracion de los operadores. NO BASTA con definirlos con "def" sino que 
# tambien hay que indicarselo a pyhop.
# Importante: se deben declarar TODOS los operadores en un UNICO "declare_operators"

pyhop.declare_operators(walk, call_taxi, wait_taxi, read_book, ride_taxi, pay_driver)


print('')
pyhop.print_operators()


# Definición de dos metodos para "read_if_necessary_book". Solo uno de ellos se ejecutara
# 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
        state.pos[b] = 'hand'
        state.clear[b] = False
        state.holding = b
        state.clear[c] = True
        return state
    else: return False
    
def putdown(state,b):
    if state.pos[b] == 'hand':
        state.pos[b] = 'table'
        state.clear[b] = True
        state.holding = False
        return state
    else: return False

def stack(state,b,c):
    if state.pos[b] == 'hand' and state.clear[c] == True:
        state.pos[b] = c
        state.clear[b] = True
        state.holding = False
        state.clear[c] = False
        return state
    else: return False

"""
Below, 'declare_operators(pickup, unstack, putdown, stack)' tells Pyhop
what the operators are. Note that the operator names are *not* quoted.
"""

pyhop.declare_operators(pickup, unstack, putdown, stack)
Exemple #22
0
    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 completed(state, plan): 
    if state.objects[plan] == False:
        state.objects[plan] = True
        return state
    else:
        return state
def not_completed(state, plan): 
    if state.objects[plan] == True:
        state.objects[plan] = False
        return state
    else:
        return state
def skip(state, plan): 
    return state

pyhop.declare_operators(completed, not_completed, skip)
Exemple #24
0
def declare_ops():
    pyhop.declare_operators(pickup, unstack, putdown, stack, putoutfire, apprehend, searchfor)
Exemple #25
0
        state.owe[a] = taxi_rate(state.dist[x][y])
        return state
    else:
        return False


def pay_driver(state, a):
    if state.cash[a] >= state.owe[a]:
        state.cash[a] = state.cash[a] - state.owe[a]
        state.owe[a] = 0
        return state
    else:
        return False


pyhop.declare_operators(walk, cycle, call_taxi, ride_taxi, pay_driver, fly)
print('')
pyhop.print_operators()

# Methods (compound tasks)


def travel_by_foot(state, a, x, y):
    if state.dist[x][y] <= 2:
        return [('walk', a, x, y)]
    return False


def travel_by_bicycle(state, a, x, y):
    if not state.weather['raining'] and state.dist[x][y] < 8:
        return [('cycle', a, x, y)]
Exemple #26
0
def stack(state,b,c):
    if state.pos[b] == 'hand' and state.clear[c] == True:
        state.pos[b] = c
        state.clear[b] = True
        state.holding = False
        state.clear[c] = False
        return state
    else: return False

def putoutfire(state, b):
	if state.fire[b] == True:
		state.fire[b] == False
		return state
	else: 
		return False

def apprehend(state, perp):
	if state.free[perp] == True:
		state.free[perp] = False
		return state
	else:
		return False

"""
Below, 'declare_operators(pickup, unstack, putdown, stack)' tells Pyhop
what the operators are. Note that the operator names are *not* quoted.
"""

pyhop.declare_operators(pickup, unstack, putdown, stack, putoutfire, apprehend)
Exemple #27
0
    else:
        return False


def store_ingredient(state, elem, num):
    #print("store_ingredient" + elem + str(num))
    state.ingredients[elem] += num
    return state


def store_tool(state, tool):
    state.tool[tool] = True
    return state


pyhop.declare_operators(check_tool, check_ingredients, use_ingredient,
                        store_ingredient, use_time)

# mehtods


def wooden_axe_for_wood(state, num):
    #print("wooden_axe for wood")
    if state.time >= 1:
        state.time -= 1
        return [('check_ingredients', 'wood', num),
                ('check_tool', 'wooden_axe'), ('store_ingredient', 'wood', 1)]
    else:
        return False


def stone_axe_for_wood(state, num):
Exemple #28
0
def pizza(state, agent):
    state.time[agent] -= 60
    state.money[agent] -= 35
    state.fullness[agent] += 1.0
    return state


def chinese(state, agent):
    state.time[agent] -= 18
    state.money[agent] -= 25
    state.fullness[agent] += 0.6
    return state


pyhop.declare_operators(buy_ingredients, actually_cook, burger, pizza, chinese)
print '\n'
pyhop.print_operators()


def cook(state, agent, full):
    if state.time[agent] >= 90:
        if state.money[agent] >= 10:
            if state.fullness[agent] + 1.5 < full:
                return [('buy_ingredients', agent), ('actually_cook', agent), ("eating", agent, full)]
            else:
                return [('buy_ingredients', agent), ('actually_cook', agent)]

    return False

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)
Exemple #30
0
def carga(state,transp,paquete):
	print "Entro en carga"
	ciudad=state.at_paquete[paquete]
	if state.at_camiones[transp]==ciudad:
		state.at_paquete[paquete]=transp
		state.carga_camion[transp].append(paquete)
		return state
	else:
		return False

def subir_camion(state,transp,driver):
	print "Entro en subir_camion"
	if state.at_camiones[transp]==state.at_cond[driver]:
		state.at_cond[driver]=transp
		return state
	else:
		return False

def bajar_camion(state,transp,driver):
	print "Entro en bajar_camion"
	ciudad = state.at_camiones[transp]
	if state.at_cond[driver]==transp:
		state.at_cond[driver]=ciudad
		return state
	else:
		return False
	
pyhop.declare_operators(walk,drive,carga,descarga,subir_camion,bajar_camion,already_there)

    
        del state.at[obj]
        return state
    else:
        return False


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')
Exemple #32
0
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)
    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
Exemple #34
0
        return state
    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)
Exemple #35
0
def declare_ops():
	pyhop.declare_operators(pickup, unstack, putdown, stack, putoutfire, apprehend, searchfor)
Exemple #36
0

def communicate_rock_data_to_lander(
        state, rover,
        probe_p):  #    зачем передавать позицию бича,когда она и так в стейте
    rstate = state.at[rover]
    if state.at_lander in state.visible[state.at[rover]]:
        state.communicated_rock_data.append(probe_p)
        return state
    else:
        return False


def communicate_image_data_to_lander(
        state, rover, obj,
        mode):  #    зачем передавать позицию бича,когда она и так в стейте
    rstate = state.at[rover]
    if state.have_image[rover] and state.at_lander in state.visible[
            state.at[rover]]:  #add. check,if we made some photos
        state.communicated_image_data.append(state.have_image[rover])
        return state
    else:
        return False


pyhop.declare_operators(already_there, navigate, sample_soil, sample_rock,
                        drop, calibrate, take_image,
                        communicate_soil_data_to_lander,
                        communicate_rock_data_to_lander,
                        communicate_image_data_to_lander)
def declare_ops():
	pyhop.declare_operators(pickup, unstack, unstack_mortared, putdown, stack, stack_mortared, putoutfire, apprehend, searchfor, get_from_store)
def declare_ops():
	pyhop.declare_operators(pickup, unstack, putdown, stack, putoutfire, apprehend, searchfor, pickup_extinguisher, putdown_extinguisher)
"""

import pyhop

def walk(state,a,x,y):
    if state.loc[a] == x:
        state.loc[a] = y
        return state
    else: return False

def call_taxi(state,a,x):
    state.loc['taxi'] = x
    return state
    
def ride_taxi(state,a,x,y):
    if state.loc['taxi']==x and state.loc[a]==x:
        state.loc['taxi'] = y
        state.loc[a] = y
        return state
    else: return False

def pay_driver(state,a,x,y):
    if state.cash[a] >= 1.5 + 0.5 * state.dist[x][y]:
        state.cash[a] = state.cash[a] - (1.5 + 0.5 * state.dist[x][y])
        return state
    else: return False

pyhop.declare_operators(walk, call_taxi, ride_taxi, pay_driver)


def moveRobot(state, locTo):
    state.locRobot = locTo
    return state


#def unstack(state,b,c):
#    if state.pos[b] == c and c != 'table' and state.clear[b] == True and state.holding == False:
#        state.pos[b] = 'hand'
#        state.clear[b] = False
#        state.holding = b
#        state.clear[c] = True
#        return state
#    else: return False
#    
#def stack(state,b,c):
#    if state.pos[b] == 'hand' and state.clear[c] == True:
#        state.pos[b] = c
#        state.clear[b] = True
#        state.holding = False
#        state.clear[c] = False
#        return state
#    else: return False
#
"""
Below, 'declare_operators(pickup, unstack, putdown, stack)' tells Pyhop
what the operators are. Note that the operator names are *not* quoted.
"""

pyhop.declare_operators(moveRobot,pickUp,putDown)
Exemple #41
0
        return False


def putdown(state, b):
    if state.pos[b] == 'hand':
        state.pos[b] = 'table'
        state.clear[b] = True
        state.holding = False
        return state
    else:
        return False


def stack(state, b, c):
    if state.pos[b] == 'hand' and state.clear[c] == True:
        state.pos[b] = c
        state.clear[b] = True
        state.holding = False
        state.clear[c] = False
        return state
    else:
        return False


"""
Below, 'declare_operators(pickup, unstack, putdown, stack)' tells Pyhop
what the operators are. Note that the operator names are *not* quoted.
"""

pyhop.declare_operators(pickup, unstack, putdown, stack)
	state.time[agent] = state.time[agent] - 25
	spend_money(13)
	return state 

def eat_in_restaurant(state, agent):
	state.time[agent] = state.time[agent] - 40
	spend_money(14)
	return state
	
def eat_in_milkbar(state, agent):
	state.time[agent] = state.time[agent] - 20
	spend_money(10)
	return state

####################### Operators declaration:
pyhop.declare_operators(buy_ingredients, cooking_process, eat_kebab, eat_in_restaurant, eat_in_milkbar)
print('\n#########################################################\n')
pyhop.print_operators()

####################### Ordering and dependencies:
def cook_myself(state, agent):
	if state.time[agent] >= 85:
		if wallet() >= 10:
			return [('buy_ingredients', agent),('cooking_process', agent)]
		else:
			return False
	else:
		return False		

def order_in_restaurant(state, agent):
	if state.time[agent] >= 40:
Exemple #43
0
def leave(state, document, office):
    if (state.holding == document):
        state.at[document] = office
        state.holding = None
        return state
    else:
        return False
        
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):
Exemple #44
0
	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);
            h=distance(state.coordinates[c],state.coordinates[y])
            if g+h<best:
                best_city=c
                best=g+h
    return best_city

def travel_op(state,y):
    x=state.location
    if y in state.connection[x]:
        state.location = y
        state.path.append(y)
        state.cost += distance(state.coordinates[x],state.coordinates[y])
        return state
    else: return False

pyhop.declare_operators(travel_op)
print('')
pyhop.print_operators()

def travel_m(state,goal):
    x=state.location_car
    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
Exemple #46
0
import sys
import time
sys.setrecursionlimit(30000)
global num_states_explored;

## Operators
def move(state, disk, source, dest):
	global num_states_explored;
	if state.loc[disk] == source:
		state.loc[disk] = dest
		num_states_explored = num_states_explored +  1;
		return state
	else:
		return False

pyhop.declare_operators(move)
print('')
pyhop.print_operators()


## Methods
def move_stack(state, disk, source, dest, spare):
	global num_states_explored;
	if disk >0:
                return [('move_tower', disk-1, source, spare, dest), ('move', disk, source, dest), ('move_tower', disk-1, spare, dest, source)]
	else:
		num_states_explored = num_states_explored + 1;
		return False


def declare_ops():
    pyhop.declare_operators(take_order, prepare_order, serve_order)