def generate_problems(num_train=50, num_test=10, level=1, **kwargs): domain = PDDLDomainParser(os.path.join(PDDLDIR, f"{DOMAIN_NAME}.pddl"), expect_action_preds=True, operators_as_actions=False) # Create version of the domain for simplicity domain_name_with_level = f"{DOMAIN_NAME}_level{level}" domain.write(os.path.join(PDDLDIR, f"{domain_name_with_level}.pddl")) # Make sure problems are unique seen_problem_ids = set() problem_idx = 0 while problem_idx < num_train + num_test: if problem_idx < num_train: problem_dir = domain_name_with_level else: problem_dir = f"{domain_name_with_level}_test" problem_outfile = f"problem{problem_idx}.pddl" problem_id, problem_filepath = sample_problem(domain, problem_dir, problem_outfile, **kwargs) if problem_id in seen_problem_ids: continue seen_problem_ids.add(problem_id) if problem_is_valid(domain, problem_filepath): problem_idx += 1
def load_pddl(domain_file, problem_dir): """ Parse domain and problem PDDL files. Parameters ---------- domain_file : str Path to a PDDL domain file. problem_dir : str Path to a directory of PDDL problem files. Returns ------- domain : PDDLDomainParser problems : [ PDDLProblemParser ] """ domain = PDDLDomainParser(domain_file) problems = [] problem_files = [ f for f in glob.glob(os.path.join(problem_dir, "*.pddl")) ] for problem_file in sorted(problem_files): problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates) problems.append(problem) return domain, problems
def load_pddl(domain_file, problem_dir, operators_as_actions=False): """ Parse domain and problem PDDL files. Parameters ---------- domain_file : str Path to a PDDL domain file. problem_dir : str Path to a directory of PDDL problem files. operators_as_actions : bool See class docstirng. Returns ------- domain : PDDLDomainParser problems : [ PDDLProblemParser ] """ domain = PDDLDomainParser( domain_file, expect_action_preds=(not operators_as_actions), operators_as_actions=operators_as_actions) problems = [] problem_files = [ f for f in glob.glob(os.path.join(problem_dir, "*.pddl")) ] for problem_file in sorted(problem_files): problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates, domain.actions, domain.constants) problems.append(problem) return domain, problems
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "manygripper.pddl"), expect_action_preds=False, operators_as_actions=True) for problem_idx in range(40): #50): if problem_idx < 40: problem_dir = "manygripper" else: problem_dir = "manygripper_test" problem_outfile = "problem{}.pddl".format(problem_idx) if problem_idx < 40: sample_problem(domain, problem_dir, problem_outfile, min_num_balls=20, max_num_balls=30, min_num_rooms=10, max_num_rooms=20, min_num_balls_goal=2, max_num_balls_goal=5, ) else: sample_problem(domain, problem_dir, problem_outfile, min_num_balls=201, max_num_balls=300, min_num_rooms=101, max_num_rooms=200, min_num_balls_goal=5, max_num_balls_goal=20, )
def generate_problems(problem_dir="maze"): domain = PDDLDomainParser(os.path.join(PDDLDIR, "maze.pddl"), expect_action_preds=False, operators_as_actions=True) train_problem_dir = problem_dir test_problem_dir = problem_dir + "_test" for problem_idx in range(0, 50): if problem_idx < 40: problem_dir = train_problem_dir else: problem_dir = test_problem_dir if not os.path.exists(os.path.join(PDDLDIR, problem_dir)): os.makedirs(os.path.join(PDDLDIR, problem_dir)) problem_outfile = "problem{}.pddl".format(problem_idx) min_maze_sizes = [6, 10, 20, 30, 40] max_maze_sizes = [10, 20, 30, 40, 50] maze_size_index = problem_idx // 10 maze_size = np.random.randint(min_maze_sizes[maze_size_index], max_maze_sizes[maze_size_index]) maze_array = generate_maze_wilsons(maze_size) display(maze_array) sample_problem(domain, problem_dir, problem_outfile, maze_array)
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "manyblockssmallpiles.pddl"), expect_action_preds=False, operators_as_actions=True) for problem_idx in range(50): if problem_idx < 40: problem_dir = "manyquantifiedblocks" else: problem_dir = "manyquantifiedblocks_test" problem_outfile = "problem{}.pddl".format(problem_idx) if problem_idx < 40: sample_problem(domain, problem_dir, problem_outfile, min_num_piles=2, max_num_piles=3, min_num_piles_goal=1, max_num_piles_goal=1, max_num_blocks=5) else: sample_problem(domain, problem_dir, problem_outfile, min_num_piles=5, max_num_piles=8, min_num_piles_goal=1, max_num_piles_goal=1)
def test_hierarchical_spaces(): dir_path = os.path.dirname(os.path.realpath(__file__)) domain_file = os.path.join(dir_path, 'pddl', 'hierarchical_type_test_domain.pddl') problem_file = os.path.join(dir_path, 'pddl', 'hierarchical_type_test_domain', 'hierarchical_type_test_problem.pddl') domain = PDDLDomainParser(domain_file) problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates, domain.actions) actions = list(domain.actions) action_predicates = [domain.predicates[a] for a in actions] space = LiteralSpace(set(domain.predicates.values()) - set(action_predicates), type_to_parent_types=domain.type_to_parent_types) all_ground_literals = space.all_ground_literals( State(problem.initial_state, problem.objects, problem.goal)) ispresent = Predicate("ispresent", 1, [Type("entity")]) islight = Predicate("islight", 1, [Type("object")]) isfurry = Predicate("isfurry", 1, [Type("animal")]) ishappy = Predicate("ishappy", 1, [Type("animal")]) attending = Predicate("attending", 2, [Type("animal"), Type("object")]) nomsy = Type("jindo")("nomsy") rover = Type("corgi")("rover") rene = Type("cat")("rene") block1 = Type("block")("block1") block2 = Type("block")("block2") cylinder1 = Type("cylinder")("cylinder1") assert all_ground_literals == { ispresent(nomsy), ispresent(rover), ispresent(rene), ispresent(block1), ispresent(block2), ispresent(cylinder1), islight(block1), islight(block2), islight(cylinder1), isfurry(nomsy), isfurry(rover), isfurry(rene), ishappy(nomsy), ishappy(rover), ishappy(rene), attending(nomsy, block1), attending(nomsy, block2), attending(nomsy, cylinder1), attending(rover, block1), attending(rover, block2), attending(rover, cylinder1), attending(rene, block1), attending(rene, block2), attending(rene, cylinder1), } print("Test passed.")
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "generated_blocks.pddl"), expect_action_preds=False, operators_as_actions=True) seen_problems = set() for problem_idx in range(50): if problem_idx < 40: problem_dir = "generated_blocks" else: problem_dir = "generated_blocks_test" problem_outfile = "problem{}.pddl".format(problem_idx) if problem_idx < 40: sample_problem(domain, problem_dir, problem_outfile, seen_problems, min_num_piles=2, max_num_piles=5, min_num_piles_goal=2, max_num_piles_goal=5) else: sample_problem(domain, problem_dir, problem_outfile, seen_problems, min_num_piles=2, max_num_piles=5, min_num_piles_goal=2, max_num_piles_goal=5)
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "footwear.pddl"), expect_action_preds=False, operators_as_actions=True) for problem_idx in range(50): problem_outfile = "problem{}.pddl".format(problem_idx) sample_problem(domain, problem_outfile)
def test_hierarchical_types(): dir_path = os.path.dirname(os.path.realpath(__file__)) domain_file = os.path.join(dir_path, 'pddl', 'hierarchical_type_test_domain.pddl') problem_file = os.path.join(dir_path, 'pddl', 'hierarchical_type_test_domain', 'hierarchical_type_test_problem.pddl') domain = PDDLDomainParser(domain_file) problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates) assert set(domain.types.keys()) == { Type("dog"), Type("cat"), Type("animal"), Type("block"), Type("cylinder"), Type("jindo"), Type("corgi"), Type("object"), Type("entity") } assert domain.type_hierarchy == { Type("animal"): {Type("dog"), Type("cat")}, Type("dog"): {Type("jindo"), Type("corgi")}, Type("object"): {Type("block"), Type("cylinder")}, Type("entity"): {Type("object"), Type("animal")}, } assert domain.type_to_parent_types == { Type("entity"): {Type("entity")}, Type("object"): {Type("object"), Type("entity")}, Type("animal"): {Type("animal"), Type("entity")}, Type("dog"): {Type("dog"), Type("animal"), Type("entity")}, Type("cat"): {Type("cat"), Type("animal"), Type("entity")}, Type("corgi"): {Type("corgi"), Type("dog"), Type("animal"), Type("entity")}, Type("jindo"): {Type("jindo"), Type("dog"), Type("animal"), Type("entity")}, Type("block"): {Type("block"), Type("object"), Type("entity")}, Type("cylinder"): {Type("cylinder"), Type("object"), Type("entity")}, } print("Test passed.")
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "manyblocksnopiles.pddl"), expect_action_preds=False, operators_as_actions=True) for problem_idx in range(50): if problem_idx < 40: problem_dir = "manyblocksnopiles" else: problem_dir = "manyblocksnopiles_test" problem_outfile = "problem{}.pddl".format(problem_idx) sample_problem(domain, problem_dir, problem_outfile)
def generate_problems(): domain = PDDLDomainParser(os.path.join(PDDLDIR, "hiking.pddl"), expect_action_preds=False, operators_as_actions=True) for problem_idx, grid in enumerate(TRAIN_GRIDS + TEST_GRIDS): if problem_idx < len(TRAIN_GRIDS): problem_dir = "hiking" else: problem_dir = "hiking_test" problem_outfile = "problem{}.pddl".format(problem_idx) create_problem(grid, domain, problem_dir, problem_outfile)
def generate_problems(problem_dir="newspapers"): domain = PDDLDomainParser(os.path.join(PDDLDIR, "newspapers.pddl"), expect_action_preds=False, operators_as_actions=True) train_problem_dir = problem_dir test_problem_dir = problem_dir + "_test" for problem_idx in range(50): if problem_idx < 40: problem_dir = train_problem_dir else: problem_dir = test_problem_dir if not os.path.exists(os.path.join(PDDLDIR, problem_dir)): os.makedirs(os.path.join(PDDLDIR, problem_dir)) problem_outfile = "problem{}.pddl".format(problem_idx) num_locs = problem_idx + 3 sample_problem(domain, problem_dir, problem_outfile, num_locs)
def integration_test(): dir_path = os.path.dirname(os.path.realpath(__file__)) domain_file = os.path.join(dir_path, 'pddl', 'test_domain.pddl') problem_file = os.path.join(dir_path, 'pddl', 'test_domain', 'test_problem.pddl') domain = PDDLDomainParser(domain_file) problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates) ## Check domain type1 = Type('type1') type2 = Type('type2') # Action predicates action_pred = Predicate('actionpred', 1, [type1]) # Predicates pred1 = Predicate('pred1', 1, [type1]) pred2 = Predicate('pred2', 1, [type2]) pred3 = Predicate('pred3', 1, [type1, type2, type2]) assert set(domain.predicates.values()) == { pred1, pred2, pred3, action_pred } assert domain.actions == { action_pred.name } # Operators assert len(domain.operators) == 1 operator1 = Predicate('action1', 4, [type1, type1, type2, type2]) assert operator1 in domain.operators operator = domain.operators[operator1] # Operator parameters assert len(operator.params) == 4 assert operator.params[0] == type1('?a') assert operator.params[1] == type1('?b') assert operator.params[2] == type2('?c') assert operator.params[3] == type2('?d') # Operator preconditions (set of Literals) assert len(operator.preconds.literals) == 4 assert set(operator.preconds.literals) == { action_pred('?b'), pred1('?b'), pred3('?a', '?c', '?d'), Not(pred2('?c')) } # Operator effects (set of Literals) assert len(operator.effects.literals) == 3 assert set(operator.effects.literals) == { Anti(pred2('?d')), pred2('?c'), pred3('?b', '?d', '?c')} ## Check problem # Objects assert set(problem.objects) == {type1('a1'), type1('a2'), type1('b1'), type1('b2'), type1('b3'), type2('c1'), type2('c2'), type2('d1'), type2('d2'), type2('d3')} # Goal assert isinstance(problem.goal, LiteralConjunction) assert set(problem.goal.literals) == {pred2('c2'), pred3('b1', 'c1', 'd1')} # Init assert problem.initial_state == { pred1('b2'), pred2('c1'), pred3('a1', 'c1', 'd1'), pred3('a2', 'c2', 'd2'), action_pred('a1'), action_pred('a2'), action_pred('b1'), action_pred('b2')} print("Test passed.")
from transform.sokoban_game import SokobanGame from pddlgym.parser import PDDLProblemParser, PDDLDomainParser from transform.parse_func import parse_objects, parse_initial_state, parse_goal import os TAR_DIR = "transform/puzzles/hard" if __name__ == "__main__": cnt = 0 for file in sorted(os.listdir(TAR_DIR)): sok = SokobanGame() boards = sok.new_board(os.path.join(TAR_DIR, file)) for b in boards: domian_file = "/Users/yangchen/PycharmProjects/pddlgym/pddlgym/pddl/sokoban.pddl" problem_file = "/Users/yangchen/PycharmProjects/pddlgym/pddlgym/pddl/sokoban_test/task02.pddl" domain = PDDLDomainParser(domian_file) problem = PDDLProblemParser(problem_file, domain.domain_name, domain.types, domain.predicates, domain.actions, domain.constants) problem.objects = parse_objects(b, domain.types) problem.goal = parse_goal(b, domain.types, domain.predicates) problem.initial_state = parse_initial_state( b, domain.types, domain.predicates) with open( '/Users/yangchen/PycharmProjects/pddlgym/pddlgym/pddl/sokoban/{}.pddl' .format(cnt), 'w') as f: PDDLProblemParser.create_pddl_file(f, problem.objects, problem.initial_state, problem.problem_name,
def run_probabilistic_planning_demo(env, planner_name, verbose=False, num_epi=20, outdir='/tmp', fps=3): """Probabilistic planning via simple determinization. """ if outdir is None: outdir = "/tmp/{}".format(env_cls.__name__) if not os.path.exists(outdir): os.makedirs(outdir) if env._render: if env._problem_index_fixed: problem_idx = env._problem_idx video_path = os.path.join(outdir, 'planning_{}_{}_{}_demo.gif'.format( planner_name, env.spec.id, problem_idx)) else: video_path = os.path.join(outdir, 'planning_{}_{}_demo.gif'.format( planner_name, env.spec.id)) env = VideoWrapper(env, video_path, fps=fps) avg_reward = 0 for _ in range(num_epi): obs, debug_info = env.reset() domain = PDDLDomainParser(debug_info["domain_file"]) domain.determinize() domain.write("/tmp/domain.pddl") plan = run_planner("/tmp/domain.pddl", debug_info['problem_file'], planner_name) actions = [] for s in plan: a = parse_plan_step( s, env.domain.operators.values(), env.action_predicates, obs.objects, operators_as_actions=env.operators_as_actions ) actions.append(a) tot_reward = 0. for action in actions: if verbose: print("Obs:", obs) if verbose: print("Act:", action) obs, reward, done, _ = env.step(action) env.render() tot_reward += reward if verbose: print("Rew:", reward) if done: break if verbose: print("Final obs:", obs) print("Got total reward:", tot_reward) print() avg_reward += tot_reward/num_epi print("Average reward over {} episodes was {}".format(num_epi, avg_reward)) env.close() if verbose: input("press enter to continue to next problem") return tot_reward