コード例 #1
0
ファイル: main.py プロジェクト: senenpalanca/PlanningPyhop
def 

#INITIAL STATE

state1 = pyhop.State('state1')

state1.connectionRoad = {'C0':{'C1', 'C2'}, 'C1':{'C0', 'C2'}, 'C2':{'C0', 'C2'}} 
コード例 #2
0
ファイル: main.py プロジェクト: bwalkowi/msi
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)
コード例 #3
0
    def __init__(self):
        self.current_world_model = pyhop.State("current_world_model")
        self.current_world_model.tick = 0
        self.current_world_model.max_ticks = 100
        self.current_world_model.timestamp = time.time()

        self.current_world_model.location = {
            "target_object": "table",
            "servo_values": [1500, 1500, 1500, 1500, 1500, 1500],
            "init_servo_values": [1500, 1500, 1500, 1500, 1500, 1500]
        }
        self.current_world_model.xyz = {
            "target_object": [-30, -30, 0],
            "container": [-0.1, 24.0, 12],
            "end_effector": [-0.1, 24.0, 12]
        }
        self.current_world_model.size = {"object_side_length": 4.0}
        self.current_world_model.min_bounds = {
            "xyz": [-25, -25, -25],
            "object_side_length": 0.5
        }
        self.current_world_model.max_bounds = {
            "xyz": [25, 25, 25],
            "object_side_length": 6.0
        }
        self.current_world_model.threshold = {"grabbing_distance": 4.5}  # cm
        self.current_world_model.distance = {"distance_to_gripper": 11.2}  # cm
        self.current_world_model.grabbed = {"target_object": False}
        self.current_world_model.initialized = {"arm": False}
        self.current_world_model.url = {"arm": "ESP_02662E"}
        self.current_world_model.init_delay_seconds = {"arm": 5}
        self.current_world_model.real_time_clock_period_seconds = {"arm": 0.5}

        # Control
        if os.path.isfile('json/control.json'):
            with open('json/control.json') as f:
                self.current_world_model.control = json.load(f)

        # Planner
        if os.path.isfile('json/planner.json'):
            with open('json/planner.json') as f:
                self.current_world_model.planner = json.load(f)

        # Goals
        self.current_world_model.goals = [
            tuple(self.current_world_model.planner["goals"])
        ]

        # Perception
        if os.path.isfile('json/perception.json'):
            with open('json/perception.json') as f:
                self.current_world_model.perception = json.load(f)

        self.world_model_history = []
コード例 #4
0
def get_start_state():
    state = pyhop.State('init')
    state.days = {}
    state.days['green'] = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
                           [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0],
                           [0, 0, 0, 0]]
    state.days['blue'] = [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0,
                                                       0], [0, 0, 0, 0],
                          [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
    state.pills = list(state.days.keys())
    return state
コード例 #5
0
ファイル: test1alt2.py プロジェクト: pkoduganty/TeaAtHomeHTN
def test1():
	"""!@brief (Helper function) Create a state object for test 1 with a slightly different environment.
	The kettle is open, full and has cold water.
	@return state state
	"""
	state = pyhop.State('Test1 alt 2')
	state.TOTAL_NUMBER_OF_TEACUPS = 1
	state.NUMBER_OF_DIRTY_TEACUPS = 0
	state.loc = {'robot':teaathome.Location.startlocation, 'teacup1':teaathome.Location.countertop, 'coldtap':teaathome.Location.kitchensink, 'kettle':teaathome.Location.kettlebase, 'teabag':teaathome.Location.countertop}
	teacups = 1
	while teacups <= state.TOTAL_NUMBER_OF_TEACUPS:
		state.loc['teacup'+str(teacups)] = teaathome.Location.countertop
		teacups = teacups + 1
		
	state.accessible = {'kettle':teaathome.Accessible.yes, 'kettlebase':teaathome.Accessible.yes, 'coldtap':teaathome.Accessible.yes, 'teabag':teaathome.Accessible.yes}
	teacups = 1
	while teacups <= state.TOTAL_NUMBER_OF_TEACUPS:
		state.accessible['teacup'+str(teacups)] = teaathome.Accessible.yes
		teacups = teacups + 1
		
	state.itemstate = {'kettle':{'openstate':teaathome.Itemstate.closed, 'fillstate':teaathome.Itemstate.full, 'tempstate':teaathome.Itemstate.cold}, 'coldtap':{'openstate':teaathome.Itemstate.closed}}

	for x in range(1, state.TOTAL_NUMBER_OF_TEACUPS + 1):
		state.itemstate['teacup'+str(x)] = {'cleanstate':teaathome.Itemstate.clean, 'fillstate':teaathome.Itemstate.empty, 'tempstate':teaathome.Itemstate.cold}
	#dirtycups = 1
	'''while dirtycups <= state.NUMBER_OF_DIRTY_TEACUPS:
		cup = 'teacup'+str(random.randint(1,state.TOTAL_NUMBER_OF_TEACUPS))
		if(state.itemstate[cup]['cleanstate'] == teaathome.Itemstate.unknown):
			state.itemstate[cup]['cleanstate'] = teaathome.Itemstate.dirty
			dirtycups = dirtycups + 1'''
	'''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
コード例 #6
0
def test2():
	"""!@brief (Helper function) Create a state object for test 2.
	@return state state
	"""
	state = pyhop.State('Test2')
	state.TOTAL_NUMBER_OF_TEACUPS = 76
	state.NUMBER_OF_DIRTY_TEACUPS = 30
	state.loc = {'robot':teaathome.Location.startlocation, 'coldtap':teaathome.Location.kitchensink, 'kettle':teaathome.Location.kettlebase, 'teabag':teaathome.Location.countertop}
	teacups = 1
	while teacups <= state.TOTAL_NUMBER_OF_TEACUPS:
		state.loc['teacup'+str(teacups)] = teaathome.Location((random.randint(6, 13)))
		teacups = teacups + 1
		
	state.accessible = {'kettle':teaathome.Accessible.yes, 'kettlebase':teaathome.Accessible.yes, 'coldtap':teaathome.Accessible.yes, 'teabag':teaathome.Accessible.yes}
	teacups = 1
	while teacups <= state.TOTAL_NUMBER_OF_TEACUPS:
		state.accessible['teacup'+str(teacups)] = teaathome.Accessible.yes
		teacups = teacups + 1
		
	state.itemstate = {'kettle':{'openstate':teaathome.Itemstate.closed, 'fillstate':teaathome.Itemstate.empty, 'tempstate':teaathome.Itemstate.cold}, 'coldtap':{'openstate':teaathome.Itemstate.closed}}

	for x in range(1, state.TOTAL_NUMBER_OF_TEACUPS + 1):
		state.itemstate['teacup'+str(x)] = {'cleanstate':teaathome.Itemstate.unknown, 'fillstate':teaathome.Itemstate.empty, 'tempstate':teaathome.Itemstate.cold}
	dirtycups = 1
	while dirtycups < state.NUMBER_OF_DIRTY_TEACUPS:
		cup = 'teacup'+str(random.randint(1,state.TOTAL_NUMBER_OF_TEACUPS))
		if(state.itemstate[cup]['cleanstate'] == teaathome.Itemstate.unknown):
			state.itemstate[cup]['cleanstate'] = teaathome.Itemstate.dirty
			dirtycups = dirtycups + 1
	"""cleancups = 0
	while cleancups <= numcupsknownclean:
		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
コード例 #7
0
ファイル: main.py プロジェクト: AlfME/sin_laboratorio
	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);
コード例 #8
0
ファイル: towers_of_hanoi.py プロジェクト: RIP2014/HW1_Team3
    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)
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]
コード例 #9
0

def get_travel_data(state, pos):
    x = places[pos]
    y = places[pos + 1]
    data = {'from': x, 'to': y, 'dist': state.dist[x][y]}
    return data


places = [
    'Cracow', 'Cracow-Airport', 'Cayo Guilermo-Airport', 'Cayo Guilermo',
    'Long Island', 'Crooked Island', 'Mayaguana', 'Rum Cay', 'Cat Island',
    'Cat Island-Airport', 'Cracow-Airport', 'Cracow'
]

state0 = pyhop.State('state0')
state0.loc = {'me': 'Cracow'}
state0.money = {'me': 150000}
state0.souvenirs_bought = {'me': 0}
state0.souvenirs_made = {'me': 0}
state0.photos_available = {'me': 7}
state0.dist = {
    'Cracow': {
        'Cracow-Airport': 20
    },
    'Cracow-Airport': {
        'Cayo Guilermo-Airport': 7292.18,
        'Cat Island-Airport': 10063.81,
        'Cracow': 20
    },
    'Cayo Guilermo': {
コード例 #10
0
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})


def put_on_stack(state, cubes, is_stacked):
    if not hasattr(state, "isOnStack"):
        state.isOnStack = {}
    state.isOnStack.update({c: is_stacked for c in cubes})


state1_h = pyhop.State("state1_h")
state1_h.cubes = ["cube1", "cube2", "cube3", "cube4", "cube5", "cube6"]
make_reachable_by(state1_h, state1_h.cubes[:3], ["human"])
make_reachable_by(state1_h, state1_h.cubes[3:], ["robot"])
make_reachable_by(state1_h, state1_h.cubes[0:1], ["human", "robot"])
put_on_stack(state1_h, state1_h.cubes, False)
state1_h.isCarrying = {"human": None, "robot": None}
state1_h.onStack = []

state1_r = deepcopy(state1_h)

goal1_h = pyhop.Goal("goal1_h")
goal1_h.isOnStack = {"cube4": True, "cube1": True, "cube6": True}
goal1_h.onStack = ["cube4", "cube1", "cube6"]
goal1_r = deepcopy(goal1_h)
コード例 #11
0
"""
The "travel from home to the park" example from my lectures.
Author: Dana Nau <*****@*****.**>, May 31, 2013
This file should work correctly in both Python 2.7 and Python 3.2.
"""

import pyhop
import random
import sys
from utils_plan import *
from util_plot import *

# state variables

state1 = pyhop.State('state')
state1.status = 3
state1.concepts = ["Concept A", "Concept B", "Concept C"]
state1.relations = ["Relation A", "Relation B", "Relation C"]
state1.concepts_heard_count = [0, 0, 0]
state1.relations_heard_count = [0, 0, 0]
state1.variables = pyhop.State('variables')
state1.variables.affect = pyhop.State('affect')
state1.variables.affect.skill = 0
state1.variables.affect.challenge = 0
state1.variables.affect.boredom = 2
state1.variables.affect.frustration = -2
state1.variables.affect.confidence = DictEx(2)

# end - state variables

# Operators
コード例 #12
0
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)

person.fullness = {'me_friends': 0.0}
person.time = {'me_friends': 1000}
person.money = {'me_friends': 30}
コード例 #13
0
    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"

htn_plans = pyhop.pyhop(
    current_world_model,
    [('transfer_ball_to_container', 'arm', 'ball', 'table', 'container')],
    verbose=1,
    all_plans=True,
    sort_asc=True)
コード例 #14
0
'''
Created on Sep 2, 2018

@author: Shane
'''
import pyhop
import Queue
state1 = pyhop.State('state1')
state1.at = {'robot': 'dock', 'birthCertificate': 'Office 1'}
state1.holding = None
state1.signed = []
state1.shredded = []

prob1 = [('goAndGet', 'birthCertificate'),
         ('takeAndSign', 'birthCertificate', 'Office 2'),
         ('deliver', 'birthCertificate', 'Office 1')]

prob12 = [('take_deliver', 'birthCertificate', 'Office 2')]
prob13 = [('take_sign_deliver', 'birthCertificate', 'Office 3', 'Office 2')]

state2 = pyhop.State('state2')
state2.at = {
    'robot': 'dock',
    'Doc1': 'AlbertsOffice',
    'Doc2': 'StusOffice',
    'Doc3': 'TedsOffice'
}
state2.holding = None
state2.signed = []
state2.shredded = []
コード例 #15
0
def generate_new_state(stateName):
    return pyhop.State(stateName)
コード例 #16
0
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