From c3fb4788624595a664d59e97b8f468979d6d65f9 Mon Sep 17 00:00:00 2001 From: langfeng Date: Tue, 3 Feb 2026 20:11:19 +0800 Subject: [PATCH 1/6] remove redundant files & update readme --- README.md | 26 +- agent_system/environments/env_manager.py | 606 +-- .../env_package/alfworld/__init__.py | 2 - .../env_package/alfworld/alfworld/__init__.py | 1 - .../alfworld/alfworld/agents/README.md | 274 -- .../alfworld/alfworld/agents/__init__.py | 0 .../alfworld/agents/agent/__init__.py | 4 - .../alfworld/agents/agent/base_agent.py | 451 -- .../agents/agent/text_dagger_agent.py | 364 -- .../alfworld/agents/agent/text_dqn_agent.py | 946 ---- .../agents/agent/vision_dagger_agent.py | 344 -- .../alfworld/agents/config/rewards.json | 87 - .../alfworld/agents/controller/__init__.py | 4 - .../alfworld/agents/controller/base.py | 231 - .../alfworld/agents/controller/mrcnn.py | 557 --- .../alfworld/agents/controller/mrcnn_astar.py | 56 - .../alfworld/agents/controller/oracle.py | 340 -- .../agents/controller/oracle_astar.py | 54 - .../alfworld/agents/detector/__init__.py | 0 .../alfworld/agents/detector/coco_eval.py | 349 -- .../alfworld/agents/detector/coco_utils.py | 251 -- .../alfworld/agents/detector/engine.py | 108 - .../agents/detector/group_by_aspect_ratio.py | 187 - .../alfworld/agents/detector/mrcnn.py | 42 - .../alfworld/agents/detector/train.py | 177 - .../alfworld/agents/detector/transforms.py | 50 - .../alfworld/agents/detector/utils.py | 319 -- .../alfworld/agents/environment/__init__.py | 12 - .../agents/environment/alfred_hybrid.py | 59 - .../agents/environment/alfred_thor_env.py | 377 -- .../agents/environment/alfred_tw_env.py | 280 -- .../alfworld/alfworld/agents/eval/__init__.py | 3 - .../alfworld/agents/eval/evaluate_dagger.py | 170 - .../alfworld/agents/eval/evaluate_dqn.py | 146 - .../agents/eval/evaluate_vision_dagger.py | 144 - .../alfworld/agents/expert/__init__.py | 3 - .../agents/expert/handcoded_expert.py | 570 --- .../agents/expert/handcoded_expert_thor.py | 165 - .../agents/expert/handcoded_expert_tw.py | 128 - .../alfworld/agents/modules/__init__.py | 0 .../alfworld/agents/modules/generic.py | 298 -- .../alfworld/agents/modules/layers.py | 1622 ------- .../alfworld/agents/modules/memory.py | 337 -- .../alfworld/alfworld/agents/modules/model.py | 243 -- .../alfworld/agents/modules/segment_tree.py | 138 - .../alfworld/agents/utils/__init__.py | 0 .../alfworld/alfworld/agents/utils/misc.py | 306 -- .../alfworld/alfworld/data/README.md | 137 - .../alfworld/alfworld/data/alfred.pddl | 508 --- .../alfworld/alfworld/data/alfred.twl2 | 437 -- .../alfworld/alfworld/env/__init__.py | 0 .../alfworld/alfworld/env/reward.py | 258 -- .../alfworld/alfworld/env/tasks.py | 464 -- .../alfworld/alfworld/env/thor_env.py | 626 --- .../alfworld/alfworld/gen/README.md | 77 - .../alfworld/alfworld/gen/__init__.py | 0 .../alfworld/alfworld/gen/agents/__init__.py | 0 .../alfworld/gen/agents/agent_base.py | 60 - .../gen/agents/deterministic_planner_agent.py | 26 - .../alfworld/gen/agents/plan_agent.py | 94 - .../gen/agents/semantic_map_planner_agent.py | 72 - .../alfworld/alfworld/gen/constants.py | 1235 ------ .../alfworld/gen/ff_planner/README.md | 13 - .../alfworld/gen/ff_planner/expressions.c | 2623 ----------- .../alfworld/gen/ff_planner/expressions.h | 106 - .../alfworld/alfworld/gen/ff_planner/ff.h | 2044 --------- .../alfworld/gen/ff_planner/inst_easy.c | 1220 ------ .../alfworld/gen/ff_planner/inst_easy.h | 73 - .../alfworld/gen/ff_planner/inst_final.c | 2797 ------------ .../alfworld/gen/ff_planner/inst_final.h | 69 - .../alfworld/gen/ff_planner/inst_hard.c | 1306 ------ .../alfworld/gen/ff_planner/inst_hard.h | 71 - .../alfworld/gen/ff_planner/inst_pre.c | 3854 ----------------- .../alfworld/gen/ff_planner/inst_pre.h | 123 - .../alfworld/gen/ff_planner/lex-fct_pddl.l | 139 - .../alfworld/gen/ff_planner/lex-ops_pddl.l | 151 - .../alfworld/alfworld/gen/ff_planner/main.c | 1230 ------ .../alfworld/alfworld/gen/ff_planner/makefile | 89 - .../alfworld/alfworld/gen/ff_planner/memory.c | 1278 ------ .../alfworld/alfworld/gen/ff_planner/memory.h | 109 - .../alfworld/alfworld/gen/ff_planner/output.c | 1482 ------- .../alfworld/alfworld/gen/ff_planner/output.h | 68 - .../alfworld/alfworld/gen/ff_planner/parse.c | 1339 ------ .../alfworld/alfworld/gen/ff_planner/parse.h | 63 - .../alfworld/alfworld/gen/ff_planner/relax.c | 2756 ------------ .../alfworld/alfworld/gen/ff_planner/relax.h | 93 - .../alfworld/gen/ff_planner/run_sample.sh | 2 - .../ff_planner/samples/PutTask_domain.pddl | 152 - .../gen/ff_planner/samples/problem_0_0.pddl | 390 -- .../alfworld/gen/ff_planner/scan-fct_pddl.y | 918 ---- .../alfworld/gen/ff_planner/scan-ops_pddl.y | 1086 ----- .../alfworld/alfworld/gen/ff_planner/search.c | 2372 ---------- .../alfworld/alfworld/gen/ff_planner/search.h | 105 - .../alfworld/gen/game_states/__init__.py | 0 .../gen/game_states/game_state_base.py | 909 ---- .../gen/game_states/planned_game_state.py | 491 --- .../gen/game_states/task_game_state.py | 369 -- .../task_game_state_full_knowledge.py | 473 -- .../alfworld/alfworld/gen/goal_library.py | 633 --- .../alfworld/alfworld/gen/graph/__init__.py | 0 .../alfworld/alfworld/gen/graph/graph_obj.py | 427 -- .../gen/layouts/FloorPlan1-layout.npy | Bin 2192 -> 0 bytes .../gen/layouts/FloorPlan1-objects.json | 49 - .../gen/layouts/FloorPlan1-openable.json | 146 - .../gen/layouts/FloorPlan10-layout.npy | Bin 3376 -> 0 bytes .../gen/layouts/FloorPlan10-objects.json | 47 - .../gen/layouts/FloorPlan10-openable.json | 98 - .../gen/layouts/FloorPlan11-layout.npy | Bin 1200 -> 0 bytes .../gen/layouts/FloorPlan11-objects.json | 42 - .../gen/layouts/FloorPlan11-openable.json | 134 - .../gen/layouts/FloorPlan12-layout.npy | Bin 1392 -> 0 bytes .../gen/layouts/FloorPlan12-objects.json | 39 - .../gen/layouts/FloorPlan12-openable.json | 152 - .../gen/layouts/FloorPlan13-layout.npy | Bin 2944 -> 0 bytes .../gen/layouts/FloorPlan13-objects.json | 42 - .../gen/layouts/FloorPlan13-openable.json | 188 - .../gen/layouts/FloorPlan14-layout.npy | Bin 2016 -> 0 bytes .../gen/layouts/FloorPlan14-objects.json | 39 - .../gen/layouts/FloorPlan14-openable.json | 56 - .../gen/layouts/FloorPlan15-layout.npy | Bin 1664 -> 0 bytes .../gen/layouts/FloorPlan15-objects.json | 43 - .../gen/layouts/FloorPlan15-openable.json | 104 - .../gen/layouts/FloorPlan16-layout.npy | Bin 3296 -> 0 bytes .../gen/layouts/FloorPlan16-objects.json | 45 - .../gen/layouts/FloorPlan16-openable.json | 236 - .../gen/layouts/FloorPlan17-layout.npy | Bin 1248 -> 0 bytes .../gen/layouts/FloorPlan17-objects.json | 45 - .../gen/layouts/FloorPlan17-openable.json | 104 - .../gen/layouts/FloorPlan18-layout.npy | Bin 3680 -> 0 bytes .../gen/layouts/FloorPlan18-objects.json | 45 - .../gen/layouts/FloorPlan18-openable.json | 158 - .../gen/layouts/FloorPlan19-layout.npy | Bin 1248 -> 0 bytes .../gen/layouts/FloorPlan19-objects.json | 39 - .../gen/layouts/FloorPlan19-openable.json | 116 - .../gen/layouts/FloorPlan2-layout.npy | Bin 1968 -> 0 bytes .../gen/layouts/FloorPlan2-objects.json | 42 - .../gen/layouts/FloorPlan2-openable.json | 140 - .../gen/layouts/FloorPlan20-layout.npy | Bin 1408 -> 0 bytes .../gen/layouts/FloorPlan20-objects.json | 43 - .../gen/layouts/FloorPlan20-openable.json | 116 - .../gen/layouts/FloorPlan201-layout.npy | Bin 3152 -> 0 bytes .../gen/layouts/FloorPlan201-objects.json | 35 - .../gen/layouts/FloorPlan201-openable.json | 68 - .../gen/layouts/FloorPlan202-layout.npy | Bin 2416 -> 0 bytes .../gen/layouts/FloorPlan202-objects.json | 24 - .../gen/layouts/FloorPlan202-openable.json | 38 - .../gen/layouts/FloorPlan203-layout.npy | Bin 8096 -> 0 bytes .../gen/layouts/FloorPlan203-objects.json | 34 - .../gen/layouts/FloorPlan203-openable.json | 74 - .../gen/layouts/FloorPlan204-layout.npy | Bin 3552 -> 0 bytes .../gen/layouts/FloorPlan204-objects.json | 30 - .../gen/layouts/FloorPlan204-openable.json | 110 - .../gen/layouts/FloorPlan205-layout.npy | Bin 4096 -> 0 bytes .../gen/layouts/FloorPlan205-objects.json | 28 - .../gen/layouts/FloorPlan205-openable.json | 74 - .../gen/layouts/FloorPlan206-layout.npy | Bin 1968 -> 0 bytes .../gen/layouts/FloorPlan206-objects.json | 23 - .../gen/layouts/FloorPlan206-openable.json | 116 - .../gen/layouts/FloorPlan207-layout.npy | Bin 2448 -> 0 bytes .../gen/layouts/FloorPlan207-objects.json | 23 - .../gen/layouts/FloorPlan207-openable.json | 86 - .../gen/layouts/FloorPlan208-layout.npy | Bin 3536 -> 0 bytes .../gen/layouts/FloorPlan208-objects.json | 25 - .../gen/layouts/FloorPlan208-openable.json | 98 - .../gen/layouts/FloorPlan209-layout.npy | Bin 4992 -> 0 bytes .../gen/layouts/FloorPlan209-objects.json | 29 - .../gen/layouts/FloorPlan209-openable.json | 62 - .../gen/layouts/FloorPlan21-layout.npy | Bin 1808 -> 0 bytes .../gen/layouts/FloorPlan21-objects.json | 43 - .../gen/layouts/FloorPlan21-openable.json | 80 - .../gen/layouts/FloorPlan210-layout.npy | Bin 4416 -> 0 bytes .../gen/layouts/FloorPlan210-objects.json | 28 - .../gen/layouts/FloorPlan210-openable.json | 92 - .../gen/layouts/FloorPlan211-layout.npy | Bin 2128 -> 0 bytes .../gen/layouts/FloorPlan211-objects.json | 27 - .../gen/layouts/FloorPlan211-openable.json | 68 - .../gen/layouts/FloorPlan212-layout.npy | Bin 1792 -> 0 bytes .../gen/layouts/FloorPlan212-objects.json | 29 - .../gen/layouts/FloorPlan212-openable.json | 74 - .../gen/layouts/FloorPlan213-layout.npy | Bin 4800 -> 0 bytes .../gen/layouts/FloorPlan213-objects.json | 26 - .../gen/layouts/FloorPlan213-openable.json | 128 - .../gen/layouts/FloorPlan214-layout.npy | Bin 3104 -> 0 bytes .../gen/layouts/FloorPlan214-objects.json | 27 - .../gen/layouts/FloorPlan214-openable.json | 44 - .../gen/layouts/FloorPlan215-layout.npy | Bin 6160 -> 0 bytes .../gen/layouts/FloorPlan215-objects.json | 28 - .../gen/layouts/FloorPlan215-openable.json | 80 - .../gen/layouts/FloorPlan216-layout.npy | Bin 2528 -> 0 bytes .../gen/layouts/FloorPlan216-objects.json | 27 - .../gen/layouts/FloorPlan216-openable.json | 68 - .../gen/layouts/FloorPlan217-layout.npy | Bin 2576 -> 0 bytes .../gen/layouts/FloorPlan217-objects.json | 28 - .../gen/layouts/FloorPlan217-openable.json | 92 - .../gen/layouts/FloorPlan218-layout.npy | Bin 6848 -> 0 bytes .../gen/layouts/FloorPlan218-objects.json | 29 - .../gen/layouts/FloorPlan218-openable.json | 68 - .../gen/layouts/FloorPlan219-layout.npy | Bin 3536 -> 0 bytes .../gen/layouts/FloorPlan219-objects.json | 29 - .../gen/layouts/FloorPlan219-openable.json | 158 - .../gen/layouts/FloorPlan22-layout.npy | Bin 2304 -> 0 bytes .../gen/layouts/FloorPlan22-objects.json | 41 - .../gen/layouts/FloorPlan22-openable.json | 170 - .../gen/layouts/FloorPlan220-layout.npy | Bin 3920 -> 0 bytes .../gen/layouts/FloorPlan220-objects.json | 28 - .../gen/layouts/FloorPlan220-openable.json | 92 - .../gen/layouts/FloorPlan221-layout.npy | Bin 2016 -> 0 bytes .../gen/layouts/FloorPlan221-objects.json | 26 - .../gen/layouts/FloorPlan221-openable.json | 44 - .../gen/layouts/FloorPlan222-layout.npy | Bin 1824 -> 0 bytes .../gen/layouts/FloorPlan222-objects.json | 25 - .../gen/layouts/FloorPlan222-openable.json | 92 - .../gen/layouts/FloorPlan223-layout.npy | Bin 3632 -> 0 bytes .../gen/layouts/FloorPlan223-objects.json | 26 - .../gen/layouts/FloorPlan223-openable.json | 50 - .../gen/layouts/FloorPlan224-layout.npy | Bin 4496 -> 0 bytes .../gen/layouts/FloorPlan224-objects.json | 29 - .../gen/layouts/FloorPlan224-openable.json | 164 - .../gen/layouts/FloorPlan225-layout.npy | Bin 2592 -> 0 bytes .../gen/layouts/FloorPlan225-objects.json | 29 - .../gen/layouts/FloorPlan225-openable.json | 80 - .../gen/layouts/FloorPlan226-layout.npy | Bin 1392 -> 0 bytes .../gen/layouts/FloorPlan226-objects.json | 24 - .../gen/layouts/FloorPlan226-openable.json | 68 - .../gen/layouts/FloorPlan227-layout.npy | Bin 3312 -> 0 bytes .../gen/layouts/FloorPlan227-objects.json | 27 - .../gen/layouts/FloorPlan227-openable.json | 212 - .../gen/layouts/FloorPlan228-layout.npy | Bin 2688 -> 0 bytes .../gen/layouts/FloorPlan228-objects.json | 26 - .../gen/layouts/FloorPlan228-openable.json | 50 - .../gen/layouts/FloorPlan229-layout.npy | Bin 3456 -> 0 bytes .../gen/layouts/FloorPlan229-objects.json | 30 - .../gen/layouts/FloorPlan229-openable.json | 68 - .../gen/layouts/FloorPlan23-layout.npy | Bin 1664 -> 0 bytes .../gen/layouts/FloorPlan23-objects.json | 45 - .../gen/layouts/FloorPlan23-openable.json | 74 - .../gen/layouts/FloorPlan230-layout.npy | Bin 5872 -> 0 bytes .../gen/layouts/FloorPlan230-objects.json | 30 - .../gen/layouts/FloorPlan230-openable.json | 50 - .../gen/layouts/FloorPlan24-layout.npy | Bin 1104 -> 0 bytes .../gen/layouts/FloorPlan24-objects.json | 41 - .../gen/layouts/FloorPlan24-openable.json | 188 - .../gen/layouts/FloorPlan25-layout.npy | Bin 560 -> 0 bytes .../gen/layouts/FloorPlan25-objects.json | 40 - .../gen/layouts/FloorPlan25-openable.json | 104 - .../gen/layouts/FloorPlan26-layout.npy | Bin 1344 -> 0 bytes .../gen/layouts/FloorPlan26-objects.json | 39 - .../gen/layouts/FloorPlan26-openable.json | 92 - .../gen/layouts/FloorPlan27-layout.npy | Bin 816 -> 0 bytes .../gen/layouts/FloorPlan27-objects.json | 42 - .../gen/layouts/FloorPlan27-openable.json | 116 - .../gen/layouts/FloorPlan28-layout.npy | Bin 1744 -> 0 bytes .../gen/layouts/FloorPlan28-objects.json | 41 - .../gen/layouts/FloorPlan28-openable.json | 110 - .../gen/layouts/FloorPlan29-layout.npy | Bin 1168 -> 0 bytes .../gen/layouts/FloorPlan29-objects.json | 38 - .../gen/layouts/FloorPlan29-openable.json | 68 - .../gen/layouts/FloorPlan3-layout.npy | Bin 1792 -> 0 bytes .../gen/layouts/FloorPlan3-objects.json | 43 - .../gen/layouts/FloorPlan3-openable.json | 98 - .../gen/layouts/FloorPlan30-layout.npy | Bin 1072 -> 0 bytes .../gen/layouts/FloorPlan30-objects.json | 44 - .../gen/layouts/FloorPlan30-openable.json | 284 -- .../gen/layouts/FloorPlan301-layout.npy | Bin 1520 -> 0 bytes .../gen/layouts/FloorPlan301-objects.json | 33 - .../gen/layouts/FloorPlan301-openable.json | 98 - .../gen/layouts/FloorPlan302-layout.npy | Bin 848 -> 0 bytes .../gen/layouts/FloorPlan302-objects.json | 30 - .../gen/layouts/FloorPlan302-openable.json | 62 - .../gen/layouts/FloorPlan303-layout.npy | Bin 1424 -> 0 bytes .../gen/layouts/FloorPlan303-objects.json | 32 - .../gen/layouts/FloorPlan303-openable.json | 104 - .../gen/layouts/FloorPlan304-layout.npy | Bin 1872 -> 0 bytes .../gen/layouts/FloorPlan304-objects.json | 30 - .../gen/layouts/FloorPlan304-openable.json | 20 - .../gen/layouts/FloorPlan305-layout.npy | Bin 1488 -> 0 bytes .../gen/layouts/FloorPlan305-objects.json | 32 - .../gen/layouts/FloorPlan305-openable.json | 44 - .../gen/layouts/FloorPlan306-layout.npy | Bin 1616 -> 0 bytes .../gen/layouts/FloorPlan306-objects.json | 27 - .../gen/layouts/FloorPlan306-openable.json | 56 - .../gen/layouts/FloorPlan307-layout.npy | Bin 1552 -> 0 bytes .../gen/layouts/FloorPlan307-objects.json | 33 - .../gen/layouts/FloorPlan307-openable.json | 50 - .../gen/layouts/FloorPlan308-layout.npy | Bin 1696 -> 0 bytes .../gen/layouts/FloorPlan308-objects.json | 30 - .../gen/layouts/FloorPlan308-openable.json | 80 - .../gen/layouts/FloorPlan309-layout.npy | Bin 5920 -> 0 bytes .../gen/layouts/FloorPlan309-objects.json | 33 - .../gen/layouts/FloorPlan309-openable.json | 68 - .../gen/layouts/FloorPlan310-layout.npy | Bin 1200 -> 0 bytes .../gen/layouts/FloorPlan310-objects.json | 30 - .../gen/layouts/FloorPlan310-openable.json | 68 - .../gen/layouts/FloorPlan311-layout.npy | Bin 3728 -> 0 bytes .../gen/layouts/FloorPlan311-objects.json | 33 - .../gen/layouts/FloorPlan311-openable.json | 56 - .../gen/layouts/FloorPlan312-layout.npy | Bin 1616 -> 0 bytes .../gen/layouts/FloorPlan312-objects.json | 24 - .../gen/layouts/FloorPlan312-openable.json | 80 - .../gen/layouts/FloorPlan313-layout.npy | Bin 912 -> 0 bytes .../gen/layouts/FloorPlan313-objects.json | 32 - .../gen/layouts/FloorPlan313-openable.json | 68 - .../gen/layouts/FloorPlan314-layout.npy | Bin 1408 -> 0 bytes .../gen/layouts/FloorPlan314-objects.json | 26 - .../gen/layouts/FloorPlan314-openable.json | 50 - .../gen/layouts/FloorPlan315-layout.npy | Bin 1744 -> 0 bytes .../gen/layouts/FloorPlan315-objects.json | 26 - .../gen/layouts/FloorPlan315-openable.json | 104 - .../gen/layouts/FloorPlan316-layout.npy | Bin 1056 -> 0 bytes .../gen/layouts/FloorPlan316-objects.json | 28 - .../gen/layouts/FloorPlan316-openable.json | 32 - .../gen/layouts/FloorPlan317-layout.npy | Bin 2160 -> 0 bytes .../gen/layouts/FloorPlan317-objects.json | 30 - .../gen/layouts/FloorPlan317-openable.json | 98 - .../gen/layouts/FloorPlan318-layout.npy | Bin 1536 -> 0 bytes .../gen/layouts/FloorPlan318-objects.json | 29 - .../gen/layouts/FloorPlan318-openable.json | 110 - .../gen/layouts/FloorPlan319-layout.npy | Bin 1536 -> 0 bytes .../gen/layouts/FloorPlan319-objects.json | 28 - .../gen/layouts/FloorPlan319-openable.json | 122 - .../gen/layouts/FloorPlan320-layout.npy | Bin 1088 -> 0 bytes .../gen/layouts/FloorPlan320-objects.json | 25 - .../gen/layouts/FloorPlan320-openable.json | 50 - .../gen/layouts/FloorPlan321-layout.npy | Bin 1440 -> 0 bytes .../gen/layouts/FloorPlan321-objects.json | 26 - .../gen/layouts/FloorPlan321-openable.json | 44 - .../gen/layouts/FloorPlan322-layout.npy | Bin 1696 -> 0 bytes .../gen/layouts/FloorPlan322-objects.json | 28 - .../gen/layouts/FloorPlan322-openable.json | 80 - .../gen/layouts/FloorPlan323-layout.npy | Bin 3152 -> 0 bytes .../gen/layouts/FloorPlan323-objects.json | 28 - .../gen/layouts/FloorPlan323-openable.json | 110 - .../gen/layouts/FloorPlan324-layout.npy | Bin 1616 -> 0 bytes .../gen/layouts/FloorPlan324-objects.json | 26 - .../gen/layouts/FloorPlan324-openable.json | 98 - .../gen/layouts/FloorPlan325-layout.npy | Bin 3104 -> 0 bytes .../gen/layouts/FloorPlan325-objects.json | 26 - .../gen/layouts/FloorPlan325-openable.json | 146 - .../gen/layouts/FloorPlan326-layout.npy | Bin 1744 -> 0 bytes .../gen/layouts/FloorPlan326-objects.json | 33 - .../gen/layouts/FloorPlan326-openable.json | 122 - .../gen/layouts/FloorPlan327-layout.npy | Bin 1360 -> 0 bytes .../gen/layouts/FloorPlan327-objects.json | 28 - .../gen/layouts/FloorPlan327-openable.json | 92 - .../gen/layouts/FloorPlan328-layout.npy | Bin 1120 -> 0 bytes .../gen/layouts/FloorPlan328-objects.json | 29 - .../gen/layouts/FloorPlan328-openable.json | 44 - .../gen/layouts/FloorPlan329-layout.npy | Bin 1536 -> 0 bytes .../gen/layouts/FloorPlan329-objects.json | 26 - .../gen/layouts/FloorPlan329-openable.json | 32 - .../gen/layouts/FloorPlan330-layout.npy | Bin 2304 -> 0 bytes .../gen/layouts/FloorPlan330-objects.json | 30 - .../gen/layouts/FloorPlan330-openable.json | 128 - .../gen/layouts/FloorPlan4-layout.npy | Bin 1232 -> 0 bytes .../gen/layouts/FloorPlan4-objects.json | 41 - .../gen/layouts/FloorPlan4-openable.json | 92 - .../gen/layouts/FloorPlan401-layout.npy | Bin 1696 -> 0 bytes .../gen/layouts/FloorPlan401-objects.json | 31 - .../gen/layouts/FloorPlan401-openable.json | 50 - .../gen/layouts/FloorPlan402-layout.npy | Bin 1632 -> 0 bytes .../gen/layouts/FloorPlan402-objects.json | 32 - .../gen/layouts/FloorPlan402-openable.json | 92 - .../gen/layouts/FloorPlan403-layout.npy | Bin 1152 -> 0 bytes .../gen/layouts/FloorPlan403-objects.json | 32 - .../gen/layouts/FloorPlan403-openable.json | 56 - .../gen/layouts/FloorPlan404-layout.npy | Bin 928 -> 0 bytes .../gen/layouts/FloorPlan404-objects.json | 27 - .../gen/layouts/FloorPlan404-openable.json | 38 - .../gen/layouts/FloorPlan405-layout.npy | Bin 560 -> 0 bytes .../gen/layouts/FloorPlan405-objects.json | 27 - .../gen/layouts/FloorPlan405-openable.json | 56 - .../gen/layouts/FloorPlan406-layout.npy | Bin 1696 -> 0 bytes .../gen/layouts/FloorPlan406-objects.json | 27 - .../gen/layouts/FloorPlan406-openable.json | 44 - .../gen/layouts/FloorPlan407-layout.npy | Bin 656 -> 0 bytes .../gen/layouts/FloorPlan407-objects.json | 30 - .../gen/layouts/FloorPlan407-openable.json | 62 - .../gen/layouts/FloorPlan408-layout.npy | Bin 720 -> 0 bytes .../gen/layouts/FloorPlan408-objects.json | 27 - .../gen/layouts/FloorPlan408-openable.json | 62 - .../gen/layouts/FloorPlan409-layout.npy | Bin 752 -> 0 bytes .../gen/layouts/FloorPlan409-objects.json | 26 - .../gen/layouts/FloorPlan409-openable.json | 62 - .../gen/layouts/FloorPlan410-layout.npy | Bin 1408 -> 0 bytes .../gen/layouts/FloorPlan410-objects.json | 28 - .../gen/layouts/FloorPlan410-openable.json | 62 - .../gen/layouts/FloorPlan411-layout.npy | Bin 1200 -> 0 bytes .../gen/layouts/FloorPlan411-objects.json | 29 - .../gen/layouts/FloorPlan411-openable.json | 56 - .../gen/layouts/FloorPlan412-layout.npy | Bin 912 -> 0 bytes .../gen/layouts/FloorPlan412-objects.json | 28 - .../gen/layouts/FloorPlan412-openable.json | 44 - .../gen/layouts/FloorPlan413-layout.npy | Bin 1232 -> 0 bytes .../gen/layouts/FloorPlan413-objects.json | 31 - .../gen/layouts/FloorPlan413-openable.json | 68 - .../gen/layouts/FloorPlan414-layout.npy | Bin 928 -> 0 bytes .../gen/layouts/FloorPlan414-objects.json | 30 - .../gen/layouts/FloorPlan414-openable.json | 86 - .../gen/layouts/FloorPlan415-layout.npy | Bin 1040 -> 0 bytes .../gen/layouts/FloorPlan415-objects.json | 30 - .../gen/layouts/FloorPlan415-openable.json | 68 - .../gen/layouts/FloorPlan416-layout.npy | Bin 1248 -> 0 bytes .../gen/layouts/FloorPlan416-objects.json | 26 - .../gen/layouts/FloorPlan416-openable.json | 44 - .../gen/layouts/FloorPlan417-layout.npy | Bin 1056 -> 0 bytes .../gen/layouts/FloorPlan417-objects.json | 28 - .../gen/layouts/FloorPlan417-openable.json | 50 - .../gen/layouts/FloorPlan418-layout.npy | Bin 896 -> 0 bytes .../gen/layouts/FloorPlan418-objects.json | 27 - .../gen/layouts/FloorPlan418-openable.json | 32 - .../gen/layouts/FloorPlan419-layout.npy | Bin 624 -> 0 bytes .../gen/layouts/FloorPlan419-objects.json | 28 - .../gen/layouts/FloorPlan419-openable.json | 20 - .../gen/layouts/FloorPlan420-layout.npy | Bin 576 -> 0 bytes .../gen/layouts/FloorPlan420-objects.json | 28 - .../gen/layouts/FloorPlan420-openable.json | 32 - .../gen/layouts/FloorPlan421-layout.npy | Bin 624 -> 0 bytes .../gen/layouts/FloorPlan421-objects.json | 28 - .../gen/layouts/FloorPlan421-openable.json | 68 - .../gen/layouts/FloorPlan422-layout.npy | Bin 768 -> 0 bytes .../gen/layouts/FloorPlan422-objects.json | 31 - .../gen/layouts/FloorPlan422-openable.json | 68 - .../gen/layouts/FloorPlan423-layout.npy | Bin 1024 -> 0 bytes .../gen/layouts/FloorPlan423-objects.json | 31 - .../gen/layouts/FloorPlan423-openable.json | 80 - .../gen/layouts/FloorPlan424-layout.npy | Bin 736 -> 0 bytes .../gen/layouts/FloorPlan424-objects.json | 26 - .../gen/layouts/FloorPlan424-openable.json | 50 - .../gen/layouts/FloorPlan425-layout.npy | Bin 528 -> 0 bytes .../gen/layouts/FloorPlan425-objects.json | 29 - .../gen/layouts/FloorPlan425-openable.json | 38 - .../gen/layouts/FloorPlan426-layout.npy | Bin 928 -> 0 bytes .../gen/layouts/FloorPlan426-objects.json | 29 - .../gen/layouts/FloorPlan426-openable.json | 74 - .../gen/layouts/FloorPlan427-layout.npy | Bin 944 -> 0 bytes .../gen/layouts/FloorPlan427-objects.json | 30 - .../gen/layouts/FloorPlan427-openable.json | 68 - .../gen/layouts/FloorPlan428-layout.npy | Bin 1008 -> 0 bytes .../gen/layouts/FloorPlan428-objects.json | 27 - .../gen/layouts/FloorPlan428-openable.json | 50 - .../gen/layouts/FloorPlan429-layout.npy | Bin 1136 -> 0 bytes .../gen/layouts/FloorPlan429-objects.json | 28 - .../gen/layouts/FloorPlan429-openable.json | 26 - .../gen/layouts/FloorPlan430-layout.npy | Bin 1824 -> 0 bytes .../gen/layouts/FloorPlan430-objects.json | 35 - .../gen/layouts/FloorPlan430-openable.json | 62 - .../gen/layouts/FloorPlan5-layout.npy | Bin 1712 -> 0 bytes .../gen/layouts/FloorPlan5-objects.json | 45 - .../gen/layouts/FloorPlan5-openable.json | 194 - .../gen/layouts/FloorPlan6-layout.npy | Bin 2272 -> 0 bytes .../gen/layouts/FloorPlan6-objects.json | 41 - .../gen/layouts/FloorPlan6-openable.json | 164 - .../gen/layouts/FloorPlan7-layout.npy | Bin 4416 -> 0 bytes .../gen/layouts/FloorPlan7-objects.json | 47 - .../gen/layouts/FloorPlan7-openable.json | 152 - .../gen/layouts/FloorPlan8-layout.npy | Bin 2880 -> 0 bytes .../gen/layouts/FloorPlan8-objects.json | 45 - .../gen/layouts/FloorPlan8-openable.json | 200 - .../gen/layouts/FloorPlan9-layout.npy | Bin 1344 -> 0 bytes .../gen/layouts/FloorPlan9-objects.json | 41 - .../gen/layouts/FloorPlan9-openable.json | 284 -- .../layouts/precompute_layout_locations.py | 349 -- .../alfworld/alfworld/gen/planner/__init__.py | 0 .../domains/PutTaskExtended_domain.pddl | 302 -- .../gen/planner/ff_planner_handler.py | 252 -- .../alfworld/alfworld/gen/planner/pddl.pdf | Bin 196613 -> 0 bytes .../gen/scripts/generate_trajectories.py | 727 ---- .../alfworld/gen/scripts/replay_checks.py | 186 - .../alfworld/alfworld/gen/utils/__init__.py | 0 .../alfworld/alfworld/gen/utils/bb_util.py | 139 - .../gen/utils/dataset_management_util.py | 69 - .../alfworld/alfworld/gen/utils/game_util.py | 365 -- .../alfworld/alfworld/gen/utils/image_util.py | 59 - .../alfworld/alfworld/gen/utils/py_util.py | 84 - .../alfworld/gen/utils/replay_json.py | 52 - .../alfworld/alfworld/gen/utils/video_util.py | 11 - .../env_package/alfworld/alfworld/info.py | 15 - .../env_package/alfworld/alfworld/utils.py | 20 - .../alfworld/configs/config_thor.yaml | 145 - .../alfworld/configs/config_tw.yaml | 145 - .../environments/env_package/alfworld/envs.py | 191 - .../env_package/alfworld/projection.py | 47 - .../env_package/appworld/__init__.py | 2 - .../environments/env_package/appworld/envs.py | 237 - .../env_package/appworld/projection.py | 47 - .../env_package/gym_cards/__init__.py | 2 - .../env_package/gym_cards/envs.py | 165 - .../gym_cards/gym-cards/.gitignore | 160 - .../env_package/gym_cards/gym-cards/README.md | 151 - .../gym_cards/gym-cards/gym_cards/__init__.py | 29 - .../gym-cards/gym_cards/envs/__init__.py | 4 - .../gym-cards/gym_cards/envs/blackjack.py | 302 -- .../gym-cards/gym_cards/envs/ezpoints.py | 182 - .../gym_cards/envs/font/Minecraft.ttf | Bin 14488 -> 0 bytes .../gym-cards/gym_cards/envs/img/C2.png | Bin 88262 -> 0 bytes .../gym-cards/gym_cards/envs/img/C3.png | Bin 108456 -> 0 bytes .../gym-cards/gym_cards/envs/img/C4.png | Bin 114280 -> 0 bytes .../gym-cards/gym_cards/envs/img/C5.png | Bin 140951 -> 0 bytes .../gym-cards/gym_cards/envs/img/C6.png | Bin 164926 -> 0 bytes .../gym-cards/gym_cards/envs/img/C7.png | Bin 165722 -> 0 bytes .../gym-cards/gym_cards/envs/img/C8.png | Bin 201094 -> 0 bytes .../gym-cards/gym_cards/envs/img/C9.png | Bin 214555 -> 0 bytes .../gym-cards/gym_cards/envs/img/CA.png | Bin 68661 -> 0 bytes .../gym-cards/gym_cards/envs/img/CJ.png | Bin 1267135 -> 0 bytes .../gym-cards/gym_cards/envs/img/CK.png | Bin 1084649 -> 0 bytes .../gym-cards/gym_cards/envs/img/CQ.png | Bin 1159745 -> 0 bytes .../gym-cards/gym_cards/envs/img/CT.png | Bin 216949 -> 0 bytes .../gym-cards/gym_cards/envs/img/D2.png | Bin 70388 -> 0 bytes .../gym-cards/gym_cards/envs/img/D3.png | Bin 83142 -> 0 bytes .../gym-cards/gym_cards/envs/img/D4.png | Bin 82990 -> 0 bytes .../gym-cards/gym_cards/envs/img/D5.png | Bin 105096 -> 0 bytes .../gym-cards/gym_cards/envs/img/D6.png | Bin 122907 -> 0 bytes .../gym-cards/gym_cards/envs/img/D7.png | Bin 119274 -> 0 bytes .../gym-cards/gym_cards/envs/img/D8.png | Bin 148332 -> 0 bytes .../gym-cards/gym_cards/envs/img/D9.png | Bin 155794 -> 0 bytes .../gym-cards/gym_cards/envs/img/DA.png | Bin 56875 -> 0 bytes .../gym-cards/gym_cards/envs/img/DJ.png | Bin 1185239 -> 0 bytes .../gym-cards/gym_cards/envs/img/DK.png | Bin 1168385 -> 0 bytes .../gym-cards/gym_cards/envs/img/DQ.png | Bin 1052448 -> 0 bytes .../gym-cards/gym_cards/envs/img/DT.png | Bin 150839 -> 0 bytes .../gym-cards/gym_cards/envs/img/H2.png | Bin 74998 -> 0 bytes .../gym-cards/gym_cards/envs/img/H3.png | Bin 89807 -> 0 bytes .../gym-cards/gym_cards/envs/img/H4.png | Bin 91024 -> 0 bytes .../gym-cards/gym_cards/envs/img/H5.png | Bin 114862 -> 0 bytes .../gym-cards/gym_cards/envs/img/H6.png | Bin 133773 -> 0 bytes .../gym-cards/gym_cards/envs/img/H7.png | Bin 130378 -> 0 bytes .../gym-cards/gym_cards/envs/img/H8.png | Bin 160843 -> 0 bytes .../gym-cards/gym_cards/envs/img/H9.png | Bin 169472 -> 0 bytes .../gym-cards/gym_cards/envs/img/HA.png | Bin 60047 -> 0 bytes .../gym-cards/gym_cards/envs/img/HJ.png | Bin 1332525 -> 0 bytes .../gym-cards/gym_cards/envs/img/HK.png | Bin 1232445 -> 0 bytes .../gym-cards/gym_cards/envs/img/HQ.png | Bin 1183473 -> 0 bytes .../gym-cards/gym_cards/envs/img/HT.png | Bin 167289 -> 0 bytes .../gym-cards/gym_cards/envs/img/S2.png | Bin 82084 -> 0 bytes .../gym-cards/gym_cards/envs/img/S3.png | Bin 99256 -> 0 bytes .../gym-cards/gym_cards/envs/img/S4.png | Bin 102018 -> 0 bytes .../gym-cards/gym_cards/envs/img/S5.png | Bin 127529 -> 0 bytes .../gym-cards/gym_cards/envs/img/S6.png | Bin 148215 -> 0 bytes .../gym-cards/gym_cards/envs/img/S7.png | Bin 148546 -> 0 bytes .../gym-cards/gym_cards/envs/img/S8.png | Bin 180906 -> 0 bytes .../gym-cards/gym_cards/envs/img/S9.png | Bin 191887 -> 0 bytes .../gym-cards/gym_cards/envs/img/SA.png | Bin 65000 -> 0 bytes .../gym-cards/gym_cards/envs/img/SJ.png | Bin 1137993 -> 0 bytes .../gym-cards/gym_cards/envs/img/SK.png | Bin 1096302 -> 0 bytes .../gym-cards/gym_cards/envs/img/SQ.png | Bin 1118198 -> 0 bytes .../gym-cards/gym_cards/envs/img/ST.png | Bin 190697 -> 0 bytes .../gym-cards/gym_cards/envs/img/card.png | Bin 2429720 -> 0 bytes .../gym_cards/envs/img/pointgame_sample.png | Bin 25578 -> 0 bytes .../gym-cards/gym_cards/envs/numberline.py | 121 - .../gym-cards/gym_cards/envs/points.py | 203 - .../gym_cards/gym-cards/play_gymcards.ipynb | 287 -- .../play_gymcards_test_text_wrap.ipynb | 482 --- .../env_package/gym_cards/gym-cards/setup.py | 8 - .../gym_cards/gym-cards/text_wrapper.py | 89 - .../env_package/gym_cards/projection.py | 49 - .../env_package/sokoban/__init__.py | 2 - .../environments/env_package/sokoban/envs.py | 168 - .../env_package/sokoban/projection.py | 70 - .../env_package/sokoban/sokoban/__init__.py | 1 - .../env_package/sokoban/sokoban/base.py | 309 -- .../env_package/sokoban/sokoban/env.py | 156 - .../env_package/sokoban/sokoban/room_utils.py | 599 --- .../env_package/sokoban/sokoban/utils.py | 81 - .../env_package/webshop/__init__.py | 2 - .../environments/env_package/webshop/envs.py | 240 - .../env_package/webshop/projection.py | 49 - .../env_package/webshop/webshop/.gitignore | 18 - .../env_package/webshop/webshop/LICENSE.md | 21 - .../env_package/webshop/webshop/README.md | 130 - .../webshop/webshop/README_INSTALL_ARM-MAC.md | 82 - .../webshop/baseline_models/.gitignore | 125 - .../webshop/webshop/baseline_models/README.md | 77 - .../webshop/webshop/baseline_models/agent.py | 162 - .../webshop/webshop/baseline_models/env.py | 238 - .../baseline_models/generate_search.py | 34 - .../webshop/webshop/baseline_models/logger.py | 542 --- .../webshop/baseline_models/models/bert.py | 118 - .../webshop/baseline_models/models/modules.py | 156 - .../webshop/baseline_models/models/rnn.py | 121 - .../webshop/baseline_models/requirements.txt | 5 - .../webshop/webshop/baseline_models/test.py | 141 - .../baseline_models/train_choice_il.py | 629 --- .../webshop/baseline_models/train_rl.py | 249 -- .../baseline_models/train_search_il.py | 139 - .../env_package/webshop/webshop/conftest.py | 0 .../webshop/webshop/requirements.txt | 26 - .../webshop/webshop/requirements_arm.txt | 23 - .../webshop/webshop/run_web_agent_text_env.py | 32 - .../convert_product_file_format.py | 47 - .../webshop/search_engine/lucene_searcher.py | 15 - .../webshop/search_engine/run_indexing.sh | 31 - .../env_package/webshop/webshop/setup.sh | 79 - .../env_package/webshop/webshop/setup_arm.sh | 74 - .../webshop/webshop/transfer/README.md | 23 - .../webshop/webshop/transfer/__init__.py | 0 .../webshop/webshop/transfer/app.py | 315 -- .../webshop/webshop/transfer/predict_help.py | 457 -- .../webshop/webshop/transfer/webshop_lite.py | 102 - .../webshop/web_agent_site/__init__.py | 0 .../webshop/webshop/web_agent_site/app.py | 280 -- .../web_agent_site/attributes/annotate.py | 70 - .../attributes/generate_attrs.py | 171 - .../webshop/web_agent_site/engine/__init__.py | 0 .../webshop/web_agent_site/engine/engine.py | 362 -- .../webshop/web_agent_site/engine/goal.py | 269 -- .../web_agent_site/engine/normalize.py | 103 - .../webshop/web_agent_site/envs/__init__.py | 14 - .../webshop/web_agent_site/envs/chromedriver | Bin 16636712 -> 0 bytes .../web_agent_site/envs/web_agent_site_env.py | 217 - .../web_agent_site/envs/web_agent_text_env.py | 656 --- .../webshop/web_agent_site/models/__init__.py | 4 - .../webshop/web_agent_site/models/models.py | 55 - .../static/images/no-image-available.png | Bin 37283 -> 0 bytes .../webshop/web_agent_site/static/style.css | 200 - .../templates/attributes_page.html | 58 - .../templates/description_page.html | 43 - .../web_agent_site/templates/done_page.html | 50 - .../templates/features_page.html | 47 - .../web_agent_site/templates/item_page.html | 119 - .../templates/results_page.html | 89 - .../web_agent_site/templates/review_page.html | 59 - .../web_agent_site/templates/search_page.html | 34 - .../webshop/webshop/web_agent_site/utils.py | 48 - agent_system/environments/prompts/__init__.py | 5 - agent_system/environments/prompts/alfworld.py | 51 - agent_system/environments/prompts/appworld.py | 280 -- .../environments/prompts/gym_cards.py | 117 - agent_system/environments/prompts/sokoban.py | 83 - agent_system/environments/prompts/webshop.py | 65 - examples/multi_agent_trainer/run_math.sh | 8 +- examples/multi_agent_trainer/run_search.sh | 12 +- examples/search/retriever/retrieval_launch.sh | 2 +- requirements_sglang.txt | 10 +- setup.py | 23 +- 634 files changed, 44 insertions(+), 75987 deletions(-) delete mode 100644 agent_system/environments/env_package/alfworld/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/README.md delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/agent/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/agent/base_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dagger_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dqn_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/agent/vision_dagger_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/config/rewards.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/base.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn_astar.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle_astar.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_eval.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_utils.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/engine.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/group_by_aspect_ratio.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/mrcnn.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/train.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/transforms.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/detector/utils.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/environment/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_hybrid.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_thor_env.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_tw_env.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/eval/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dagger.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dqn.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_vision_dagger.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/expert/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_thor.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_tw.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/generic.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/layers.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/memory.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/model.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/modules/segment_tree.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/utils/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/agents/utils/misc.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/data/README.md delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/data/alfred.pddl delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/data/alfred.twl2 delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/env/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/env/reward.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/env/tasks.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/env/thor_env.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/README.md delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/agents/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/agents/agent_base.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/agents/deterministic_planner_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/agents/plan_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/agents/semantic_map_planner_agent.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/constants.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/README.md delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/ff.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-fct_pddl.l delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-ops_pddl.l delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/main.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/makefile delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/relax.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/relax.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/run_sample.sh delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/samples/PutTask_domain.pddl delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/samples/problem_0_0.pddl delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/scan-fct_pddl.y delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/scan-ops_pddl.y delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/search.c delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/search.h delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/game_states/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/game_states/game_state_base.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/game_states/planned_game_state.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/game_states/task_game_state.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/game_states/task_game_state_full_knowledge.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/goal_library.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/graph/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/graph/graph_obj.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan1-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan1-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan1-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan10-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan10-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan10-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan11-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan11-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan11-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan12-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan12-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan12-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan13-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan13-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan13-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan14-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan14-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan14-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan15-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan15-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan15-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan16-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan16-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan16-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan17-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan17-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan17-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan18-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan18-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan18-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan19-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan19-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan19-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan2-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan2-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan2-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan20-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan20-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan20-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan201-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan201-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan201-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan202-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan202-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan202-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan203-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan203-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan203-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan204-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan204-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan204-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan205-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan205-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan205-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan206-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan206-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan206-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan207-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan207-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan207-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan208-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan208-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan208-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan209-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan209-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan209-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan21-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan21-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan21-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan210-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan210-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan210-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan211-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan211-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan211-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan212-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan212-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan212-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan213-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan213-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan213-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan214-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan214-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan214-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan215-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan215-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan215-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan216-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan216-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan216-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan217-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan217-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan217-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan218-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan218-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan218-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan219-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan219-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan219-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan22-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan22-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan22-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan220-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan220-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan220-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan221-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan221-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan221-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan222-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan222-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan222-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan223-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan223-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan223-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan224-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan224-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan224-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan225-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan225-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan225-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan226-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan226-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan226-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan227-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan227-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan227-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan228-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan228-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan228-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan229-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan229-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan229-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan23-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan23-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan23-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan230-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan230-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan230-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan24-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan24-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan24-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan25-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan25-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan25-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan26-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan26-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan26-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan27-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan27-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan27-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan28-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan28-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan28-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan29-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan29-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan29-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan3-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan3-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan3-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan30-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan30-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan30-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan301-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan301-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan301-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan302-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan302-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan302-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan303-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan303-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan303-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan304-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan304-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan304-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan305-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan305-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan305-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan306-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan306-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan306-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan307-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan307-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan307-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan308-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan308-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan308-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan309-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan309-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan309-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan310-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan310-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan310-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan311-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan311-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan311-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan312-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan312-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan312-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan313-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan313-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan313-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan314-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan314-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan314-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan315-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan315-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan315-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan316-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan316-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan316-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan317-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan317-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan317-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan318-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan318-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan318-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan319-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan319-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan319-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan320-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan320-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan320-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan321-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan321-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan321-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan322-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan322-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan322-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan323-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan323-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan323-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan324-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan324-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan324-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan325-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan325-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan325-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan326-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan326-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan326-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan327-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan327-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan327-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan328-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan328-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan328-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan329-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan329-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan329-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan330-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan330-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan330-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan4-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan4-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan4-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan401-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan401-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan401-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan402-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan402-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan402-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan403-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan403-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan403-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan404-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan404-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan404-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan405-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan405-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan405-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan406-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan406-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan406-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan407-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan407-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan407-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan408-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan408-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan408-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan409-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan409-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan409-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan410-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan410-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan410-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan411-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan411-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan411-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan412-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan412-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan412-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan413-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan413-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan413-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan414-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan414-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan414-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan415-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan415-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan415-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan416-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan416-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan416-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan417-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan417-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan417-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan418-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan418-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan418-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan419-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan419-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan419-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan420-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan420-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan420-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan421-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan421-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan421-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan422-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan422-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan422-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan423-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan423-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan423-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan424-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan424-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan424-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan425-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan425-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan425-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan426-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan426-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan426-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan427-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan427-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan427-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan428-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan428-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan428-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan429-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan429-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan429-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan430-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan430-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan430-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan5-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan5-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan5-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan6-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan6-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan6-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan7-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan7-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan7-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan8-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan8-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan8-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan9-layout.npy delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan9-objects.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/FloorPlan9-openable.json delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/layouts/precompute_layout_locations.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/planner/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/planner/domains/PutTaskExtended_domain.pddl delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/planner/ff_planner_handler.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/planner/pddl.pdf delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/scripts/generate_trajectories.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/scripts/replay_checks.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/__init__.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/bb_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/dataset_management_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/game_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/image_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/py_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/replay_json.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/gen/utils/video_util.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/info.py delete mode 100644 agent_system/environments/env_package/alfworld/alfworld/utils.py delete mode 100644 agent_system/environments/env_package/alfworld/configs/config_thor.yaml delete mode 100644 agent_system/environments/env_package/alfworld/configs/config_tw.yaml delete mode 100644 agent_system/environments/env_package/alfworld/envs.py delete mode 100644 agent_system/environments/env_package/alfworld/projection.py delete mode 100644 agent_system/environments/env_package/appworld/__init__.py delete mode 100644 agent_system/environments/env_package/appworld/envs.py delete mode 100644 agent_system/environments/env_package/appworld/projection.py delete mode 100644 agent_system/environments/env_package/gym_cards/__init__.py delete mode 100644 agent_system/environments/env_package/gym_cards/envs.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/.gitignore delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/README.md delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/__init__.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/__init__.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/blackjack.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/ezpoints.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/font/Minecraft.ttf delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C2.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C3.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C4.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C5.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C6.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C7.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C8.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/C9.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/CA.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/CJ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/CK.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/CQ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/CT.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D2.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D3.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D4.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D5.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D6.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D7.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D8.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/D9.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/DA.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/DJ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/DK.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/DQ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/DT.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H2.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H3.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H4.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H5.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H6.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H7.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H8.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/H9.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/HA.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/HJ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/HK.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/HQ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/HT.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S2.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S3.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S4.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S5.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S6.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S7.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S8.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/S9.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/SA.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/SJ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/SK.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/SQ.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/ST.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/card.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/img/pointgame_sample.png delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/numberline.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/gym_cards/envs/points.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/play_gymcards.ipynb delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/play_gymcards_test_text_wrap.ipynb delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/setup.py delete mode 100644 agent_system/environments/env_package/gym_cards/gym-cards/text_wrapper.py delete mode 100644 agent_system/environments/env_package/gym_cards/projection.py delete mode 100644 agent_system/environments/env_package/sokoban/__init__.py delete mode 100644 agent_system/environments/env_package/sokoban/envs.py delete mode 100644 agent_system/environments/env_package/sokoban/projection.py delete mode 100644 agent_system/environments/env_package/sokoban/sokoban/__init__.py delete mode 100644 agent_system/environments/env_package/sokoban/sokoban/base.py delete mode 100644 agent_system/environments/env_package/sokoban/sokoban/env.py delete mode 100644 agent_system/environments/env_package/sokoban/sokoban/room_utils.py delete mode 100644 agent_system/environments/env_package/sokoban/sokoban/utils.py delete mode 100644 agent_system/environments/env_package/webshop/__init__.py delete mode 100644 agent_system/environments/env_package/webshop/envs.py delete mode 100644 agent_system/environments/env_package/webshop/projection.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/.gitignore delete mode 100644 agent_system/environments/env_package/webshop/webshop/LICENSE.md delete mode 100644 agent_system/environments/env_package/webshop/webshop/README.md delete mode 100644 agent_system/environments/env_package/webshop/webshop/README_INSTALL_ARM-MAC.md delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/.gitignore delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/README.md delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/agent.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/env.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/generate_search.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/logger.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/models/bert.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/models/modules.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/models/rnn.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/requirements.txt delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/test.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/train_choice_il.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/train_rl.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/baseline_models/train_search_il.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/conftest.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/requirements.txt delete mode 100644 agent_system/environments/env_package/webshop/webshop/requirements_arm.txt delete mode 100644 agent_system/environments/env_package/webshop/webshop/run_web_agent_text_env.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/search_engine/convert_product_file_format.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/search_engine/lucene_searcher.py delete mode 100755 agent_system/environments/env_package/webshop/webshop/search_engine/run_indexing.sh delete mode 100755 agent_system/environments/env_package/webshop/webshop/setup.sh delete mode 100644 agent_system/environments/env_package/webshop/webshop/setup_arm.sh delete mode 100644 agent_system/environments/env_package/webshop/webshop/transfer/README.md delete mode 100644 agent_system/environments/env_package/webshop/webshop/transfer/__init__.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/transfer/app.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/transfer/predict_help.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/transfer/webshop_lite.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/__init__.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/app.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/attributes/annotate.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/attributes/generate_attrs.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/engine/__init__.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/engine/engine.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/engine/goal.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/engine/normalize.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/envs/__init__.py delete mode 100755 agent_system/environments/env_package/webshop/webshop/web_agent_site/envs/chromedriver delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/envs/web_agent_site_env.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/envs/web_agent_text_env.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/models/__init__.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/models/models.py delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/static/images/no-image-available.png delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/static/style.css delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/attributes_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/description_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/done_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/features_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/item_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/results_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/review_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/templates/search_page.html delete mode 100644 agent_system/environments/env_package/webshop/webshop/web_agent_site/utils.py delete mode 100644 agent_system/environments/prompts/alfworld.py delete mode 100644 agent_system/environments/prompts/appworld.py delete mode 100644 agent_system/environments/prompts/gym_cards.py delete mode 100644 agent_system/environments/prompts/sokoban.py delete mode 100644 agent_system/environments/prompts/webshop.py diff --git a/README.md b/README.md index 6fea77bd..4b20f84a 100644 --- a/README.md +++ b/README.md @@ -45,8 +45,8 @@ Unlike single-agent approaches, `Dr.MAS` supports sophisticated multi-agent setu - [Install veRL](#install-verl) - [Install Supported Environments](#install-supported-environments) - [Run Examples](#run-examples) - - [Math](#math) - [Search](#search) + - [Math](#math) - [Usage Guide](#usage-guide) - [How to register Custom Agents](#how-to-register-custom-agents) - [How to Create Custom Orchestras](#how-to-create-custom-orchestras) @@ -100,25 +100,17 @@ A core assignment logic maps logical agents $(1, ..., K)$ to physical LLM worker conda create -n DrMAS python==3.12 -y conda activate DrMAS -pip3 install psutil -pip3 install torch==2.6.0 --index-url https://download.pytorch.org/whl/cu124 -pip3 install flash-attn==2.7.4.post1 --no-build-isolation +# pip3 install torch==2.8.0 --index-url https://download.pytorch.org/whl/cu126 +pip3 install -r requirements_sglang.txt +pip3 install flash-attn==2.7.4.post1 --no-build-isolation --no-cache-dir pip3 install -e . -pip3 install -r requirements_sglang.txt ``` ## Install Supported Environments -### 1. Math -Prepare the dataset: -```bash -cd repo_root/ -python examples/data_preprocess/drmas_math.py -``` - -### 2. Search +### 1. Search ```bash conda activate DrMAS cd ./agent_system/environments/env_package/search/third_party @@ -172,6 +164,14 @@ conda activate retriever bash examples/search/retriever/retrieval_launch.sh > retrieval_server.log ``` +### 2. Math +Prepare the dataset: +```bash +cd repo_root/ +python examples/data_preprocess/drmas_math.py +``` + + # Run Examples ## Math diff --git a/agent_system/environments/env_manager.py b/agent_system/environments/env_manager.py index 5275d1e0..a109f743 100644 --- a/agent_system/environments/env_manager.py +++ b/agent_system/environments/env_manager.py @@ -8,543 +8,6 @@ from agent_system.environments.base import EnvironmentManagerBase, to_numpy from agent_system.memory import SimpleMemory, SearchMemory -def parse_gamefile(infos): - gamefile = [] - for info in infos: - if 'extra.gamefile' in info: - gamefile.append(info['extra.gamefile']) - else: - gamefile.append(None) - return gamefile - -def set_gamefile(infos, gamefile): - for i in range(len(infos)): - if 'extra.gamefile' in infos[i]: - infos[i]['extra.gamefile'] = gamefile[i] - else: - infos[i]['extra.gamefile'] = None - return infos - - -class AlfWorldEnvironmentManager(EnvironmentManagerBase): - def __init__(self, envs, projection_f, config): - self.memory = SimpleMemory() - super().__init__(envs, projection_f, config) - - def reset(self, kwargs): - text_obs, image_obs, infos = self.envs.reset() - self.gamefile = parse_gamefile(infos) - # initialize the history buffer - self.memory.reset(batch_size = len(text_obs)) - self.tasks = [] - self.pre_text_obs = text_obs - self.extract_task(text_obs) - - full_text_obs = self.build_text_obs(text_obs, self.envs.get_admissible_commands, init=True) - return {'text': full_text_obs, 'image': image_obs, 'anchor': text_obs}, infos - - def step(self, text_actions: List[str]): - if not self.config.agent.multi_agent: - actions, valids = self.projection_f(text_actions, self.envs.get_admissible_commands) - else: - actions = text_actions - - text_obs, image_obs, rewards, dones, infos = self.envs.step(actions) - self.memory.store({'text_obs': self.pre_text_obs, 'action': actions}) - self.pre_text_obs = text_obs - - full_text_obs = self.build_text_obs(text_obs, self.envs.get_admissible_commands) - if infos[0].get("extra.gamefile") is None: - infos = set_gamefile(infos, self.gamefile) - - # add action_valid to infos - if not self.config.agent.multi_agent: - for i, info in enumerate(infos): - info['is_action_valid'] = to_numpy(valids[i]) - - next_observations = {'text': full_text_obs, 'image': image_obs, 'anchor': text_obs} - rewards = to_numpy(rewards) - dones = to_numpy(dones) - - return next_observations, rewards, dones, infos - - def extract_task(self, text_obs: List[str]): - for obs in text_obs: - task_start = obs.find('Your task is to: ') - - if task_start != -1: - self.tasks.append(obs[task_start + len('Your task is to: '):].strip()) - else: - raise ValueError("Task description not found in text observation.") - - - def build_text_obs(self, text_obs: List[str], admissible_actions: List[List[str]], init: bool = False) -> List[str]: - """ - This function builds the text observation for the agent. - """ - postprocess_text_obs = [] - if not init and self.config.env.history_length > 0: - memory_contexts, valid_lens = self.memory.fetch( - self.config.env.history_length, - obs_key="text_obs", - action_key="action") - - for i in range(len(text_obs)): - # exclude 'help' in admissible_actions[i] - reformatted_admissible_actions = "\n ".join(f"'{s}'" for s in admissible_actions[i] if s != 'help') - - if init or self.config.env.history_length <= 0: - if self.config.agent.multi_agent: - obs = ALFWORLD_MULTIAGENT_TEMPLATE_NO_HIS.format( - task_description=self.tasks[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - admissible_actions=reformatted_admissible_actions - ) - else: - obs = ALFWORLD_TEMPLATE_NO_HIS.format( - task_description=self.tasks[i], - current_observation=text_obs[i], - admissible_actions=reformatted_admissible_actions - ) - else: - if self.config.agent.multi_agent: - obs = ALFWORLD_MULTIAGENT_TEMPLATE.format( - task_description=self.tasks[i], - step_count=len(self.memory[i]), - memory="{memory}" if self.config.agent.use_agent_memory else memory_contexts[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - admissible_actions=reformatted_admissible_actions - ) - else: - obs = ALFWORLD_TEMPLATE.format( - task_description=self.tasks[i], - step_count=len(self.memory[i]), - history_length=valid_lens[i], - action_history=memory_contexts[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - admissible_actions=reformatted_admissible_actions - ) - - postprocess_text_obs.append(obs) - return postprocess_text_obs - - def _process_batch(self, batch_idx, total_batch_list, total_infos, success): - # Find the last entry with active masks - for i in reversed(range(len(total_batch_list[batch_idx]))): - batch_item = total_batch_list[batch_idx][i] - if batch_item['active_masks']: - info = total_infos[batch_idx][i] - won_value = float(info['won']) - success['success_rate'].append(won_value) - - # Process game file if it exists - gamefile = info.get("extra.gamefile") - if gamefile: - self._process_gamefile(gamefile, won_value, success) - return # Exit after finding the first active mask - - def _process_gamefile(self, gamefile, won_value, success): - tasks = [ - "pick_and_place", - "pick_two_obj_and_place", - "look_at_obj_in_light", - "pick_heat_then_place_in_recep", - "pick_cool_then_place_in_recep", - "pick_clean_then_place_in_recep", - ] - - for task in tasks: - if task in gamefile: - success[f"{task}_success_rate"].append(won_value) - break - - -class SokobanEnvironmentManager(EnvironmentManagerBase): - ACTION_LOOKUP = { - 0: "Still", - 1: "Up", - 2: "Down", - 3: "Left", - 4: "Right", - } - def __init__(self, envs, projection_f, config): - self.is_multi_modal = envs.mode == 'rgb_array' - self.memory = SimpleMemory() - super().__init__(envs, projection_f, config) - - def reset(self, kwargs): - obs, infos = self.envs.reset() - if self.is_multi_modal: - obs = np.array(obs, obs[0].dtype) - self.pre_text_obs = self.envs.render(mode='tiny_rgb_array') - observations = { - 'text': self.build_text_obs(infos, init=True), - 'image': obs, - 'anchor': obs - } - else: - self.pre_text_obs = obs - observations = { - 'text': self.build_text_obs(infos, obs, init=True), - 'image': None, - 'anchor': obs - } - self.memory.reset(batch_size = len(infos)) - return observations, infos - - def step(self, text_actions: List[str]): - if not self.config.agent.multi_agent: - actions, valids = self.projection_f(text_actions) - else: - actions = text_actions - - next_obs, rewards, dones, infos = self.envs.step(actions) - - if not self.config.agent.multi_agent: - for i, info in enumerate(infos): - info['is_action_valid'] = to_numpy(valids[i]) - - self.memory.store({'text_obs': self.pre_text_obs, 'action': [self.ACTION_LOOKUP[act] for act in actions]}) - if self.is_multi_modal: - next_obs = np.array(next_obs, next_obs[0].dtype) - self.pre_text_obs = self.envs.render(mode='tiny_rgb_array') - next_observations = { - 'text': self.build_text_obs(infos), - 'image': next_obs, - 'anchor': next_obs - } - else: - self.pre_text_obs = next_obs - next_observations = { - 'text': self.build_text_obs(infos, next_obs), - 'image': None, - 'anchor': next_obs - } - - rewards = to_numpy(rewards) - dones = to_numpy(dones) - - return next_observations, rewards, dones, infos - - def build_text_obs(self, infos, text_obs: List[str]=None, init: bool = False) -> List[str]: - """ - This function builds the text observation for the agent. - """ - postprocess_text_obs = [] - - if not init and self.config.env.history_length > 0: - memory_contexts, valid_lens = self.memory.fetch( - self.config.env.history_length, - obs_key="text_obs", - action_key="action") - - for i in range(len(infos)): - if init or self.config.env.history_length <= 0: - obs = SOKOBAN_VISUAL_TEMPLATE if self.is_multi_modal \ - else SOKOBAN_TEMPLATE_NO_HIS.format( - current_observation=text_obs[i], - ) - else: - if self.is_multi_modal: - obs = SOKOBAN_VISUAL_TEMPLATE - else: - obs = SOKOBAN_TEMPLATE.format( - step_count=len(self.memory[i]), - history_length=valid_lens[i], - action_history=memory_contexts[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - ) - postprocess_text_obs.append(obs) - - return postprocess_text_obs - - -class GymCardEnvironmentManager(EnvironmentManagerBase): - def __init__(self, envs, projection_f, config): - super().__init__(envs, projection_f, config) - - def reset(self, kwargs) -> Dict[str, Any]: - obs, infos = self.envs.reset() - # infos = [None] * self.envs.num_envs - observations = {'text': self.build_text_obs(infos), 'image': obs, 'anchor': obs.copy()} - - return observations, infos - - def step(self, text_actions: List[str]): - next_observations, rewards, dones, infos = super().step(text_actions) - - # add text observation to next_observations - next_observations['text'] = self.build_text_obs(infos) - next_observations['anchor'] = next_observations['image'].copy() - - return next_observations, rewards, dones, infos - - - def build_text_obs(self, infos: Tuple[Dict]=None) -> List[str]: - """ - This function builds the text observation for the agent. - """ - postprocess_text_obs = [] - for i in range(len(infos)): - if 'ezpoints' in self.config.env.env_name.lower(): - text_formula = ''.join(str(element) for element in infos[i]['Formula']) if infos[i] is not None else '' - obs = GYM_CARDS_EZPOINTS_TEMPLATE.format(text_formula=text_formula) - elif 'points24' in self.config.env.env_name.lower(): - text_formula = ''.join(str(element) for element in infos[i]['Formula']) if infos[i] is not None else '' - obs = GYM_CARDS_POINTS24_TEMPLATE.format(text_formula=text_formula) - elif 'numberline' in self.config.env.env_name.lower(): - obs = GYM_CARDS_NUMBERLINE_TEMPLATE - elif "blackjack" in self.config.env.env_name.lower(): - obs = GYM_CARDS_BLACKJACK_TEMPLATE - else: - raise ValueError(f"Unsupported environment: {self.config.env.env_name}") - postprocess_text_obs.append(obs) - return postprocess_text_obs - - -class WebshopEnvironmentManager(EnvironmentManagerBase): - def __init__(self, envs, projection_f, config): - self.memory = SimpleMemory() - super().__init__(envs, projection_f, config) - - def reset(self, kwargs) -> Dict[str, Any]: - obs, infos = self.envs.reset() - self.memory.reset(batch_size = len(infos)) - self.tasks = self.extract_task(obs) - obs = self.format_obs(obs) - # infos = [None] * self.envs.num_envs - observations = {'text': self.build_text_obs(obs, infos, init=True), - 'image': None, - 'anchor': obs.copy() - } - self.pre_text_obs = obs - return observations, infos - - def step(self, text_actions: List[str]): - if not self.config.agent.multi_agent: - actions, valids = self.projection_f(text_actions) - else: - actions = text_actions - - next_obs, rewards, dones, infos = self.envs.step(actions) - - next_obs = self.format_obs(next_obs) - - self.memory.store({'text_obs': self.pre_text_obs, 'action': actions}) - self.pre_text_obs = next_obs - - next_observations = { - 'text': self.build_text_obs(next_obs, infos), - 'image': None, - 'anchor': next_obs.copy() - } - - if not self.config.agent.multi_agent: - for i, info in enumerate(infos): - info['is_action_valid'] = to_numpy(valids[i]) - - rewards = to_numpy(rewards) - dones = to_numpy(dones) - - return next_observations, rewards, dones, infos - - def extract_task(self, text_obs: List[str]): - tasks = [] - for obs in text_obs: - parts = obs.split(" [SEP] ") - assert parts[1]=='Instruction:' - tasks.append(parts[2]) - return tasks - - def format_obs(self, text_obs): - postprocess_text_obs = [] - for i in range(len(text_obs)): - parts = text_obs[i].split(" [SEP] ") - # the index of self.tasks[i] in parts - try: - index = parts.index(self.tasks[i]) - reformatted_obs = " [SEP] ".join(f"'{p}'" for p in parts[index+1:]) - except: - reformatted_obs = text_obs[i] - - postprocess_text_obs.append(reformatted_obs) - - return postprocess_text_obs - - def format_avail_actions(self, avail): - actions = [] - - for key in avail.keys(): - if key not in ["has_search_bar", "clickables"]: - raise ValueError(f"Unknown key in available actions: {key}") - - if avail["has_search_bar"]: - actions.append("search[]") - - for txt in avail["clickables"]: - actions.append(f"click[{txt}]") - - return actions - - def build_text_obs(self, text_obs: List[str], infos: List[List[str]], init: bool = False) -> List[str]: - """ - This function builds the text observation for the agent. - """ - postprocess_text_obs = [] - if not init and self.config.env.history_length > 0: - memory_contexts, valid_lens = self.memory.fetch( - self.config.env.history_length, - obs_key="text_obs", - action_key="action") - - for i in range(len(text_obs)): - - available_actions = self.format_avail_actions(infos[i]['available_actions']) - reformatted_available_actions = "\n".join(f"'{s}'," for s in available_actions) - - if init or self.config.env.history_length <= 0: - if self.config.agent.multi_agent: - obs = WEBSHOP_MULTIAGENT_TEMPLATE_NO_HIS.format( - task_description=self.tasks[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - available_actions=reformatted_available_actions - ) - else: - obs = WEBSHOP_TEMPLATE_NO_HIS.format( - task_description=self.tasks[i], - current_observation=text_obs[i], - available_actions=reformatted_available_actions - ) - else: - if len(memory_contexts[i]) > 5000: - memory_contexts[i] = "... " + memory_contexts[i][-5000:] - - if self.config.agent.multi_agent: - obs = WEBSHOP_MULTIAGENT_TEMPLATE.format( - task_description=self.tasks[i], - step_count=len(self.memory[i]), - memory="{memory}" if self.config.agent.use_agent_memory else memory_contexts[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - available_actions=reformatted_available_actions - ) - else: - obs = WEBSHOP_TEMPLATE.format( - task_description=self.tasks[i], - step_count=len(self.memory[i]), - history_length=valid_lens[i], - action_history=memory_contexts[i], - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - available_actions=reformatted_available_actions - ) - - postprocess_text_obs.append(obs) - - return postprocess_text_obs - - def _process_batch(self, batch_idx, total_batch_list, total_infos, success): - for i in reversed(range(len(total_batch_list[batch_idx]))): - batch_item = total_batch_list[batch_idx][i] - if batch_item['active_masks']: - info = total_infos[batch_idx][i] - won_value = float(info['won']) - score_value = float(info['task_score']) - success['success_rate'].append(won_value) - success['webshop_task_score (not success_rate)'].append(score_value) - return - -class AppWorldEnvironmentManager(EnvironmentManagerBase): - def __init__(self, envs, projection_f, config): - self.memory = SimpleMemory() - super().__init__(envs, projection_f, config) - - def reset(self, kwargs): - text_obs, infos = self.envs.reset() - - self.supervisors = [info['supervisor'] for info in infos] - self.memory.reset(batch_size = len(text_obs)) - self.tasks = text_obs.copy() - self.pre_text_obs = text_obs - - full_text_obs = self.build_text_obs(text_obs, init=True) - return {'text': full_text_obs, 'image': None, 'anchor': text_obs}, infos - - def step(self, text_actions: List[str]): - if not self.config.agent.multi_agent: - actions, valids = self.projection_f(text_actions) - else: - actions = text_actions - - text_obs, rewards, dones, infos = self.envs.step(actions) - - self.memory.store({'text_obs': text_obs, 'action': actions}) - self.pre_text_obs = text_obs - - full_text_obs = self.build_text_obs(text_obs) - - if not self.config.agent.multi_agent: - for i, info in enumerate(infos): - info['is_action_valid'] = to_numpy(valids[i]) - - next_observations = {'text': full_text_obs, 'image': None, 'anchor': text_obs} - rewards = to_numpy(rewards) - dones = to_numpy(dones) - - return next_observations, rewards, dones, infos - - - def build_text_obs(self, text_obs: List[str], init: bool = False) -> List[str]: - """ - This function builds the text observation for the agent. - """ - postprocess_text_obs = [] - if init and self.supervisors is not None and self.config.env.history_length <= 0: - for i in range(len(text_obs)): - obs = APPWORLD_TEMPLATE_NO_HIS.format( - supervisor_first_name=self.supervisors[i]['first_name'], - supervisor_last_name=self.supervisors[i]['last_name'], - supervisor_email=self.supervisors[i]['email'], - supervisor_phone_number=self.supervisors[i]['phone_number'], - task_description=self.tasks[i], - ) - postprocess_text_obs.append(obs) - else: - for i in range(len(text_obs)): - # Get last `history_length` steps - recent_history = self.memory[i][-self.config.env.history_length:] - valid_history_length = len(recent_history) - start_index = len(self.memory[i]) - valid_history_length - action_history = "" - for j, record in enumerate(recent_history): - step_number = start_index + j + 1 - action = record["action"] - env_obs = record["text_obs"] - action_history += f"\nCode {step_number}: \n{action}\n\nResult {step_number}: \n{env_obs}\n" - - if len(action_history) > 10000: - action_history = "... " + action_history[-10000:] - - obs = APPWORLD_TEMPLATE.format( - supervisor_first_name=self.supervisors[i]['first_name'], - supervisor_last_name=self.supervisors[i]['last_name'], - supervisor_email=self.supervisors[i]['email'], - supervisor_phone_number=self.supervisors[i]['phone_number'], - task_description=self.tasks[i], - step_count=len(self.memory[i]), - history_length=valid_history_length, - action_history=action_history.strip(), - current_step=len(self.memory[i]) + 1, - current_observation=text_obs[i], - ) - postprocess_text_obs.append(obs) - return postprocess_text_obs - import time class SearchEnvironmentManager(EnvironmentManagerBase): @@ -746,74 +209,7 @@ def make_envs(config): # Get validation rollout n for pass@k and avg@k computation val_group_n = getattr(config.env.rollout, 'val_n', 1) - if "gym_cards" in config.env.env_name.lower(): - from agent_system.environments.env_package.gym_cards import build_gymcards_envs, gym_projection - _envs = build_gymcards_envs(env_name=config.env.env_name, seed=config.env.seed, env_num=config.data.train_batch_size, group_n=group_n, is_train=True) - _val_envs = build_gymcards_envs(env_name=config.env.env_name, seed=config.env.seed + 1000, env_num=config.data.val_batch_size, group_n=val_group_n, is_train=False) - - projection_f = partial(gym_projection, env_name=config.env.env_name) - envs = GymCardEnvironmentManager(_envs, projection_f, config) - val_envs = GymCardEnvironmentManager(_val_envs, projection_f, config) - return envs, val_envs - elif "alfworld" in config.env.env_name.lower(): - from agent_system.environments.env_package.alfworld import build_alfworld_envs, alfworld_projection - if config.env.env_name == 'alfworld/AlfredThorEnv': - alf_config_path = os.path.join(os.path.dirname(__file__), 'env_package/alfworld/configs/config_tw.yaml') - elif config.env.env_name == 'alfworld/AlfredTWEnv': - alf_config_path = os.path.join(os.path.dirname(__file__), 'env_package/alfworld/configs/config_tw.yaml') - else: - raise ValueError(f"Unsupported environment: {config.env.env_name}") - - env_kwargs = { - 'eval_dataset': 'eval_in_distribution', # 'eval_in_distribution' or 'eval_out_of_distribution' - } - _envs = build_alfworld_envs(alf_config_path, config.env.seed, config.data.train_batch_size, group_n, is_train=True, env_kwargs=env_kwargs) - _val_envs = build_alfworld_envs(alf_config_path, config.env.seed + 1000, config.data.val_batch_size, val_group_n, is_train=False, env_kwargs=env_kwargs) - - projection_f = partial(alfworld_projection) - envs = AlfWorldEnvironmentManager(_envs, projection_f, config) - val_envs = AlfWorldEnvironmentManager(_val_envs, projection_f, config) - return envs, val_envs - elif "sokoban" in config.env.env_name.lower(): - from agent_system.environments.env_package.sokoban import build_sokoban_envs, sokoban_projection - env_kwargs = { - 'dim_room': config.env.sokoban.dim_room, - 'num_boxes': config.env.sokoban.num_boxes, - 'max_steps': config.env.max_steps, - 'search_depth': config.env.sokoban.search_depth - } - _envs = build_sokoban_envs(config.env.seed, config.data.train_batch_size, group_n, mode=config.env.sokoban.mode, is_train=True, env_kwargs=env_kwargs) - _val_envs = build_sokoban_envs(config.env.seed + 1000, config.data.val_batch_size, val_group_n, mode=config.env.sokoban.mode, is_train=False, env_kwargs=env_kwargs) - - projection_f = partial(sokoban_projection) - envs = SokobanEnvironmentManager(_envs, projection_f, config) - val_envs = SokobanEnvironmentManager(_val_envs, projection_f, config) - return envs, val_envs - elif "webshop" in config.env.env_name.lower(): - from agent_system.environments.env_package.webshop import build_webshop_envs, webshop_projection - if config.env.webshop.use_small: - file_path = os.path.join(os.path.dirname(__file__), 'env_package/webshop/webshop/data/items_shuffle_1000.json') - attr_path = os.path.join(os.path.dirname(__file__), 'env_package/webshop/webshop/data/items_ins_v2_1000.json') - else: - file_path = os.path.join(os.path.dirname(__file__), 'env_package/webshop/webshop/data/items_shuffle.json') - attr_path = os.path.join(os.path.dirname(__file__), 'env_package/webshop/webshop/data/items_ins_v2.json') - env_kwargs = { - 'observation_mode': 'text', - 'num_products': None, - 'human_goals': config.env.webshop.human_goals, - 'file_path': file_path, - 'attr_path': attr_path - } - _envs = build_webshop_envs(seed=config.env.seed, env_num=config.data.train_batch_size, group_n=group_n, is_train=True, env_kwargs=env_kwargs) - _val_envs = build_webshop_envs(seed=config.env.seed + 1000, env_num=config.data.val_batch_size, group_n=val_group_n, is_train=False, env_kwargs=env_kwargs) - - projection_f = partial(webshop_projection) - envs = WebshopEnvironmentManager(_envs, projection_f, config) - val_envs = WebshopEnvironmentManager(_val_envs, projection_f, config) - import time - time.sleep((config.data.train_batch_size * group_n + config.data.val_batch_size) * 0.1) # wait for the envs to be ready - return envs, val_envs - elif "math" in config.env.env_name.lower(): + if "math" in config.env.env_name.lower(): from agent_system.environments.env_package.math import build_math_envs, math_projection _envs = build_math_envs(seed=config.env.seed, env_num=config.data.train_batch_size, group_n=group_n, is_train=True) _val_envs = build_math_envs(seed=config.env.seed + 1000, env_num=config.data.val_batch_size, group_n=val_group_n, is_train=False) diff --git a/agent_system/environments/env_package/alfworld/__init__.py b/agent_system/environments/env_package/alfworld/__init__.py deleted file mode 100644 index 8e7e0625..00000000 --- a/agent_system/environments/env_package/alfworld/__init__.py +++ /dev/null @@ -1,2 +0,0 @@ -from .projection import alfworld_projection -from .envs import build_alfworld_envs \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/__init__.py deleted file mode 100644 index cb4e3f23..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/__init__.py +++ /dev/null @@ -1 +0,0 @@ -from alfworld.info import * diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/README.md b/agent_system/environments/env_package/alfworld/alfworld/agents/README.md deleted file mode 100644 index b07e01f9..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/README.md +++ /dev/null @@ -1,274 +0,0 @@ -# Agents - -![](../../media/pipeline.png) - -## Training - -TextDAgger Training: -```bash -$ python scripts/train_dagger.py config/base_config.yaml -``` - -By default, you should be able to reproduce **BUTLERg** All Tasks results reported in [Table 2](https://arxiv.org/pdf/2010.03768.pdf). Run the [eval script](#evaluation) with `unstick_by_beam_search: True` to reproduce **BUTLER** evaluation results with a trained model. - -VisionDAgger Training (unimodal baseline): -```bash -$ python scripts/train_vision_dagger.py config/base_config.yaml -``` - -TextDQN Training (not reported in the paper): -```bash -$ python scripts/train_dqn.py config/base_config.yaml -``` - -Seq2Seq Training (no DAgger baseline): -```bash - -# collect dataset for offline training (not needed if python scripts/alfworld-download --extra) -# python scripts/collect_seq2seq_dataset.py config/base_config.yaml - -# train seq2seq model -$ python scripts/train_seq2seq.py config/base_config.yaml -``` - -Run `python -m visdom.server` and set `visdom: True` in the [config file](../../configs/base_config.yaml) to plot training and evaluation curves. - -## Config - -Modify [base_config.yaml](../../configs/base_config.yaml) to your needs. - -Dataset: -```yaml -dataset: - data_path: '$ALFWORLD_DATA/json_2.1.1/train' - eval_id_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_seen' # null/None to disable - eval_ood_data_path: '$ALFWORLD_DATA/json_2.1.1/valid_unseen' # null/None to disable - num_train_games: -1 # max training games (<=0 indicates full dataset) - num_eval_games: -1 # max evaluation games (<=0 indicates full dataset) -``` - -Environment: -```yaml -env: - type: 'AlfredTWEnv' # 'AlfredTWEnv' or 'AlfredThorEnv' or 'AlfredHybrid' - # regen_game_files: False # [Deprecated] Use script `alfworld-generate` instead. - domain_randomization: False # shuffle Textworld print order and object id nums - task_types: [1, 2, 3, 4, 5, 6] # task-type ids: 1 - Pick & Place, 2 - Examine in Light, 3 - Clean & Place, 4 - Heat & Place, 5 - Cool & Place, 6 - Pick Two & Place - expert_timeout_steps: 150 # max steps before timeout for expert to solve the task - expert_type: "handcoded" # 'handcoded' or 'downward'. Note: the downward planner is very slow for real-time use - goal_desc_human_anns_prob: 0.0 # prob of using human-annotated goal language instead of templated goals (1.0 indicates all human annotations from ALFRED) - - hybrid: - start_eps: 100000 # starting episode of hybrid training, tw-only training upto this point - thor_prob: 0.5 # prob of AlfredThorEnv during hybrid training - eval_mode: "tw" # 'tw' or 'thor' - env used for evaluation during hybrid training - - thor: - screen_width: 300 # width of THOR window - screen_height: 300 # height of THOR window - smooth_nav: False # smooth rotations, looks, and translations during navigation (very slow) - save_frames_to_disk: False # save frame PNGs to disk (useful for making videos of agent interactions) - save_frames_path: '../videos/' # path to save frame PNGs -``` - -Controller: -```yaml -controller: - type: 'oracle' # 'oracle' or 'oracle_astar' or 'mrcnn' or 'mrcnn_astar' (aka BUTLER) - debug: False - load_receps: True # load receptacle locations from precomputed dict (if available) -``` -`mrcnn_astar` corresponds to **BUTLER**. - -General: -```yaml -general: - random_seed: 42 - use_cuda: False # disable this when running on machine without cuda - visdom: False # plot training/eval curves, run with visdom server - task: 'alfred' - training_method: 'dagger' # 'dqn' or 'dagger' - save_path: '.' # path to save pytorch models - observation_pool_capacity: 3 # k-size queue, 0 indicates no observation - hide_init_receptacles: False # remove initial observation containing navigable receptacles - - training: - batch_size: 10 - max_episode: 50000 - smoothing_eps: 0.1 - optimizer: - learning_rate: 0.001 - clip_grad_norm: 5 - - evaluate: - run_eval: False - batch_size: 10 - env: - type: "AlfredTWEnv" - - checkpoint: - report_frequency: 1000 # report every N episode - experiment_tag: 'test' # name of experiment - load_pretrained: False # during test, enable this so that the agent load your pretrained model - load_from_tag: 'not loading anything' # name of pre-trained model to load in save_path - - model: - encoder_layers: 1 - decoder_layers: 1 - encoder_conv_num: 5 - block_hidden_dim: 64 - n_heads: 1 - dropout: 0.1 - block_dropout: 0.1 - recurrent: True -``` - -General DAgger: -```yaml -dagger: - action_space: "generation" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'exhaustive' (not working) - max_target_length: 20 # max token length for seq2seq generation - beam_width: 10 # 1 means greedy - generate_top_k: 5 - unstick_by_beam_search: False # use beam-search for failed actions, set True during evaluation - - training: - max_nb_steps_per_episode: 50 # terminate after this many steps - - fraction_assist: - fraction_assist_anneal_episodes: 50000 - fraction_assist_anneal_from: 1.0 - fraction_assist_anneal_to: 0.01 - - fraction_random: - fraction_random_anneal_episodes: 0 - fraction_random_anneal_from: 0.0 - fraction_random_anneal_to: 0.0 - - replay: - replay_memory_capacity: 500000 - update_per_k_game_steps: 5 - replay_batch_size: 64 - replay_sample_history_length: 4 - replay_sample_update_from: 2 -``` - -Vision DAgger: -```yaml -vision_dagger: - model_type: "resnet" # 'resnet' (whole image features) or 'maskrcnn_whole' (whole image MaskRCNN feats) or 'maskrcnn' (top k MaskRCNN detection feats) or 'no_vision' (zero vision input) - resnet_fc_dim: 64 - maskrcnn_top_k_boxes: 10 # top k box features - use_exploration_frame_feats: False # append feats from initial exploration (memory intensive!) - sequence_aggregation_method: "average" # 'sum' or 'average' or 'rnn' -``` - -General DQN: -```yaml -rl: - action_space: "admissible" # 'admissible' (candidates from text engine) or 'generation' (seq2seq-style generation) or 'beam_search_choice' or 'exhaustive' (not working) - max_target_length: 20 # max token length for seq2seq generation - beam_width: 10 # 1 means greedy - generate_top_k: 3 - - training: - max_nb_steps_per_episode: 50 # terminate after this many steps - learn_start_from_this_episode: 0 # delay updates until this epsiode - target_net_update_frequency: 500 # sync target net with online net per this many epochs - - replay: - accumulate_reward_from_final: True - count_reward_lambda: 0.0 # 0 to disable - novel_object_reward_lambda: 0.0 # 0 to disable - discount_gamma_game_reward: 0.9 - discount_gamma_count_reward: 0.5 - discount_gamma_novel_object_reward: 0.5 - replay_memory_capacity: 500000 # adjust this depending on your RAM size - replay_memory_priority_fraction: 0.5 - update_per_k_game_steps: 5 - replay_batch_size: 64 - multi_step: 3 - replay_sample_history_length: 4 - replay_sample_update_from: 2 - - epsilon_greedy: - noisy_net: False # if this is true, then epsilon greedy is disabled - epsilon_anneal_episodes: 1000 # -1 if not annealing - epsilon_anneal_from: 0.3 - epsilon_anneal_to: 0.1 -``` - -## Evaluation - -The training script evaluates every `report_frequency` episodes. But additionally, you can also independently evaluate pre-trained agents: - -```bash -$ python scripts/run_eval.py config/eval_config.yaml -``` - -Modify [eval_config.yaml](../../configs/eval_config.yaml) to your needs: -```yaml -general: -... - evaluate: - run_eval: True - batch_size: 3 # number of parallel eval threads - repeats: 1 # number of times to loop over eval games (we used 3 in paper experiments) - controllers: # different controllers to evaluate with - - 'oracle' - - 'mrcnn_astar' - envs: # different environments to evaluate in - - 'AlfredTWEnv' - - 'AlfredThorEnv' - eval_paths: # different splits to evaluate on - - '$ALFWORLD_DATA/json_2.1.1/valid_seen' - - '$ALFWORLD_DATA/json_2.1.1/valid_unseen' - eval_experiment_tag: "eval_run_001" # save results json with this prefix - - checkpoint: - report_frequency: 10 # report eval results every N episode - load_pretrained: True - load_from_tag: 'pretrained agent' # name of pre-trained model to load in save_path - -``` - -The script will sequentially evaluate all `envs`, `controllers`, and `eval_paths` in that nested order. - - -## Folder Structure - -``` -/configs - base_config.yaml (basic settings for all experiments) - eval_config.yaml (settings for batch evaluations) -/scripts - train_dagger.py (training script for TextDAgger agents) - train_vision_dagger.py (training script for VisionDAgger agents) - train_dqn.py (training script for TextDQN agents) - train_seq2seq.py (training script for TextSeq2seq agents) - run_eval.py (evaluation script for batch evals) - collect_seq2seq_dataset.py (data collection script for expert demonstrations) - train_mrcnn.py (training script for MaskRCNN state-estimator) -/alfworld - /agent - base_agent.py (base class for agents) - text_dagger_agent.py (TextDAgger agent used for BUTLER) - text_dqn_agent.py (TextDQN agent not reported in the paper) - vision_dagger_agent.py (VisionDAgger agent used for unimodal baselines) - /environment - alfred_tw_env.py (ALFRED TextWorld environment) - alfred_thor_env.py (ALFRED embodied environment with THOR) - alfred_hybrid.py (hybrid training manager) - /detector - mrcnn.py (MaskRCNN state-estimator) - /controller - base.py (base class for controllers) - oracle.py (GT object detections and teleport navigation) - oracle_astar.py (GT object detections and A* navigator) - mrcnn.py (MaskRCNN object detections and teleport navigation) - mrcnn_astar.py (MaskRCNN object detections and A* navigator aka BUTLER) - /eval - evaluate_dagger.py (evaluation loop for TextDAgger agents) - evaluate_vision_dagger.py (evaluation loop for VisionDAgger agents) - evaluate_dqn.py (evaluation loop for TextDQN agents) -``` diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/agent/__init__.py deleted file mode 100644 index 354f527b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from alfworld.agents.agent.base_agent import BaseAgent -from alfworld.agents.agent.text_dagger_agent import TextDAggerAgent -from alfworld.agents.agent.text_dqn_agent import TextDQNAgent -from alfworld.agents.agent.vision_dagger_agent import VisionDAggerAgent \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/base_agent.py b/agent_system/environments/env_package/alfworld/alfworld/agents/agent/base_agent.py deleted file mode 100644 index 2992b309..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/base_agent.py +++ /dev/null @@ -1,451 +0,0 @@ -import logging -import numpy as np - -try: - import torch - from transformers import DistilBertModel, DistilBertTokenizer -except ImportError: - raise ImportError("torch or transformers not found. Please install them via `pip install alfworld[full]`.") - -logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR) - -import alfworld.agents.modules.memory as memory -from alfworld.agents.modules.model import Policy -from alfworld.agents.modules.generic import to_np, to_pt, _words_to_ids, pad_sequences, preproc, max_len, ez_gather_dim_1, LinearSchedule, BeamSearchNode - - -class ObservationPool(object): - - def __init__(self, capacity=1): - if capacity == 0: - self.capacity = 1 - self.disable_observation = True - elif capacity > 0: - self.capacity = capacity - self.disable_observation = False - else: - raise NotImplementedError - - def identical_with_history(self, new_stuff, list_of_old_stuff): - for i in range(len(list_of_old_stuff)): - if new_stuff == list_of_old_stuff[i]: - return True - return False - - def push_batch(self, stuff): - assert len(stuff) == len(self.memory) - for i in range(len(stuff)): - self.push_one(i, stuff[i]) - - def push_one(self, which, stuff): - assert which < len(self.memory) - if len(self.memory[which]) == 0 and stuff.endswith("restart"): - return - if self.disable_observation: - if "[SEP]" in stuff: - action = stuff.split("[SEP]", 1)[-1].strip() - self.memory[which].append(action) - else: - if "Nothing happens" in stuff: - return - if not self.identical_with_history(stuff, self.memory[which]): - self.memory[which].append(stuff) - if len(self.memory[which]) > self.capacity: - self.memory[which] = self.memory[which][-self.capacity:] - - def push_first_sight(self, stuff): - assert len(stuff) == len(self.memory) - for i in range(len(stuff)): - self.first_sight.append(stuff[i]) - - def get(self, which=None): - if which is not None: - assert which < len(self.memory) - output = [self.first_sight[which]] - for idx in range(len(self.memory[which])): - output.append(self.memory[which][idx]) - return " [SEP] ".join(output) - - output = [] - for i in range(len(self.memory)): - output.append(self.get(which=i)) - return output - - def reset(self, batch_size): - self.memory = [] - self.first_sight = [] - for _ in range(batch_size): - self.memory.append([]) - - def __len__(self): - return len(self.memory) - - -class BaseAgent: - ''' - Base class for agents - ''' - - def __init__(self, config): - self.mode = "train" - self.config = config - print(self.config) - self.load_config() - - # bert tokenizer and model - self.tokenizer = DistilBertTokenizer.from_pretrained('distilbert-base-cased') - self.word2id = self.tokenizer.get_vocab() - self.word_vocab = {value:key for key, value in self.word2id.items()} - bert_model = DistilBertModel.from_pretrained('distilbert-base-cased') - bert_model.transformer = None - bert_model.encoder = None - for param in bert_model.parameters(): - param.requires_grad = False - - self.online_net = Policy(config=self.config, bert_model=bert_model, word_vocab_size=len(self.word2id)) - self.target_net = Policy(config=self.config, bert_model=bert_model, word_vocab_size=len(self.word2id)) - self.online_net.train() - self.target_net.train() - self.update_target_net() - for param in self.target_net.parameters(): - param.requires_grad = False - if self.use_cuda: - self.online_net.cuda() - self.target_net.cuda() - - # optimizer - self.optimizer = torch.optim.Adam(self.online_net.parameters(), lr=self.config['general']['training']['optimizer']['learning_rate']) - self.clip_grad_norm = self.config['general']['training']['optimizer']['clip_grad_norm'] - - # losses - self.cross_entropy_loss = torch.nn.CrossEntropyLoss() - - def load_config(self): - self.task = self.config['general']['task'] - self.observation_pool_capacity = self.config['general']['observation_pool_capacity'] - self.observation_pool = ObservationPool(capacity=self.observation_pool_capacity) - self.hide_init_receptacles = self.config['general']['hide_init_receptacles'] - self.training_method = self.config['general']['training_method'] - - self.init_learning_rate = self.config['general']['training']['optimizer']['learning_rate'] - self.clip_grad_norm = self.config['general']['training']['optimizer']['clip_grad_norm'] - self.batch_size = self.config['general']['training']['batch_size'] - self.max_episode = self.config['general']['training']['max_episode'] - self.smoothing_eps = self.config['general']['training']['smoothing_eps'] - - self.run_eval = self.config['general']['evaluate']['run_eval'] - self.eval_batch_size = self.config['general']['evaluate']['batch_size'] - - # Set the random seed manually for reproducibility. - self.random_seed = self.config['general']['random_seed'] - np.random.seed(self.random_seed) - torch.manual_seed(self.random_seed) - if torch.cuda.is_available(): - if not self.config['general']['use_cuda']: - print("WARNING: CUDA device detected but 'use_cuda: false' found in config.yaml") - self.use_cuda = False - else: - torch.backends.cudnn.deterministic = True - torch.cuda.manual_seed(self.random_seed) - self.use_cuda = True - else: - self.use_cuda = False - - self.experiment_tag = self.config['general']['checkpoint']['experiment_tag'] - self.report_frequency = self.config['general']['checkpoint']['report_frequency'] - self.load_pretrained = self.config['general']['checkpoint']['load_pretrained'] - self.load_from_tag = self.config['general']['checkpoint']['load_from_tag'] - - self.recurrent = self.config['general']['model']['recurrent'] - - # RL specific - # epsilon greedy - self.epsilon_anneal_episodes = self.config['rl']['epsilon_greedy']['epsilon_anneal_episodes'] - self.epsilon_anneal_from = self.config['rl']['epsilon_greedy']['epsilon_anneal_from'] - self.epsilon_anneal_to = self.config['rl']['epsilon_greedy']['epsilon_anneal_to'] - self.epsilon = self.epsilon_anneal_from - self.epsilon_scheduler = LinearSchedule(schedule_timesteps=self.epsilon_anneal_episodes, initial_p=self.epsilon_anneal_from, final_p=self.epsilon_anneal_to) - self.noisy_net = self.config['rl']['epsilon_greedy']['noisy_net'] - if self.noisy_net: - # disable epsilon greedy - self.epsilon_anneal_episodes = -1 - self.epsilon = 0.0 - - # replay buffer and updates - self.accumulate_reward_from_final = self.config['rl']['replay']['accumulate_reward_from_final'] - self.discount_gamma_game_reward = self.config['rl']['replay']['discount_gamma_game_reward'] - self.discount_gamma_count_reward = self.config['rl']['replay']['discount_gamma_count_reward'] - self.discount_gamma_novel_object_reward = self.config['rl']['replay']['discount_gamma_novel_object_reward'] - self.replay_batch_size = self.config['rl']['replay']['replay_batch_size'] - self.dqn_memory = memory.PrioritizedReplayMemory(self.config['rl']['replay']['replay_memory_capacity'], - priority_fraction=self.config['rl']['replay']['replay_memory_priority_fraction'], - discount_gamma_game_reward=self.discount_gamma_game_reward, - discount_gamma_count_reward=self.discount_gamma_count_reward, - discount_gamma_novel_object_reward=self.discount_gamma_novel_object_reward, - accumulate_reward_from_final=self.accumulate_reward_from_final) - self.update_per_k_game_steps = self.config['rl']['replay']['update_per_k_game_steps'] - self.multi_step = self.config['rl']['replay']['multi_step'] - self.count_reward_lambda = self.config['rl']['replay']['count_reward_lambda'] - self.novel_object_reward_lambda = self.config['rl']['replay']['novel_object_reward_lambda'] - self.rl_replay_sample_history_length = self.config['rl']['replay']['replay_sample_history_length'] - self.rl_replay_sample_update_from = self.config['rl']['replay']['replay_sample_update_from'] - - # rl train and eval - self.learn_start_from_this_episode = self.config['rl']['training']['learn_start_from_this_episode'] - self.target_net_update_frequency = self.config['rl']['training']['target_net_update_frequency'] - - # dagger - self.fraction_assist_anneal_episodes = self.config['dagger']['fraction_assist']['fraction_assist_anneal_episodes'] - self.fraction_assist_anneal_from = self.config['dagger']['fraction_assist']['fraction_assist_anneal_from'] - self.fraction_assist_anneal_to = self.config['dagger']['fraction_assist']['fraction_assist_anneal_to'] - self.fraction_assist = self.fraction_assist_anneal_from - self.fraction_assist_scheduler = LinearSchedule(schedule_timesteps=self.fraction_assist_anneal_episodes, initial_p=self.fraction_assist_anneal_from, final_p=self.fraction_assist_anneal_to) - - self.fraction_random_anneal_episodes = self.config['dagger']['fraction_random']['fraction_random_anneal_episodes'] - self.fraction_random_anneal_from = self.config['dagger']['fraction_random']['fraction_random_anneal_from'] - self.fraction_random_anneal_to = self.config['dagger']['fraction_random']['fraction_random_anneal_to'] - self.fraction_random = self.fraction_random_anneal_from - self.fraction_random_scheduler = LinearSchedule(schedule_timesteps=self.fraction_random_anneal_episodes, initial_p=self.fraction_random_anneal_from, final_p=self.fraction_random_anneal_to) - - self.dagger_memory = memory.DaggerReplayMemory(self.config['dagger']['replay']['replay_memory_capacity']) - self.dagger_update_per_k_game_steps = self.config['dagger']['replay']['update_per_k_game_steps'] - self.dagger_replay_batch_size = self.config['dagger']['replay']['replay_batch_size'] - self.dagger_replay_sample_history_length = self.config['dagger']['replay']['replay_sample_history_length'] - self.dagger_replay_sample_update_from = self.config['dagger']['replay']['replay_sample_update_from'] - - if self.training_method == "dagger": - self.max_target_length = self.config['dagger']['max_target_length'] - self.generate_top_k = self.config['dagger']['generate_top_k'] - self.beam_width = self.config['dagger']['beam_width'] - self.action_space = self.config['dagger']['action_space'] - self.max_nb_steps_per_episode = self.config['dagger']['training']['max_nb_steps_per_episode'] - self.unstick_by_beam_search = self.config['dagger']['unstick_by_beam_search'] - elif self.training_method == "dqn": - self.max_target_length = self.config['rl']['max_target_length'] - self.generate_top_k = self.config['rl']['generate_top_k'] - self.beam_width = self.config['rl']['beam_width'] - self.action_space = self.config['rl']['action_space'] - self.max_nb_steps_per_episode = self.config['rl']['training']['max_nb_steps_per_episode'] - self.unstick_by_beam_search = None - else: - raise NotImplementedError - - def train(self): - """ - Tell the agent that it's training phase. - """ - self.mode = "train" - self.online_net.train() - - def eval(self): - """ - Tell the agent that it's evaluation phase. - """ - self.mode = "eval" - self.online_net.eval() - - def update_target_net(self): - if self.target_net is not None: - self.target_net.load_state_dict(self.online_net.state_dict()) - - def reset_noise(self): - if self.noisy_net: - # Resets noisy weights in all linear layers (of online net only) - self.online_net.reset_noise() - - def load_pretrained_model(self, load_from): - """ - Load pretrained checkpoint from file. - - Arguments: - load_from: File name of the pretrained model checkpoint. - """ - print("loading model from %s\n" % (load_from)) - try: - if self.use_cuda: - pretrained_dict = torch.load(load_from) - else: - pretrained_dict = torch.load(load_from, map_location='cpu') - - model_dict = self.online_net.state_dict() - pretrained_dict = {k: v for k, v in pretrained_dict.items() if k in model_dict} - model_dict.update(pretrained_dict) - self.online_net.load_state_dict(model_dict) - print("The loaded parameters are:") - keys = [key for key in pretrained_dict] - print(", ".join(keys)) - print("--------------------------") - except: - print("Failed to load checkpoint...") - - def save_model_to_path(self, save_to): - torch.save(self.online_net.state_dict(), save_to) - print("Saved checkpoint to %s..." % (save_to)) - - def init(self, batch_size): - self.observation_pool.reset(batch_size) - - def get_word_input(self, input_strings): - word_id_list = [self.tokenizer.encode(item, add_special_tokens=False) for item in input_strings] - return self.get_word_input_from_ids(word_id_list) - - def get_word_input_from_ids(self, word_id_list): - input_word = pad_sequences(word_id_list, maxlen=max_len(word_id_list) + 3, dtype='int32') # 3 --> see layer.DepthwiseSeparableConv.padding - input_word = to_pt(input_word, self.use_cuda) - return input_word - - def get_action_candidate_representations(self, action_candidate_list, use_model="online"): - # in case there are too many candidates in certain data point, we compute their candidate representations by small batches - batch_size = len(action_candidate_list) - max_num_candidate = max_len(action_candidate_list) - res_representations = torch.zeros(batch_size, max_num_candidate, self.online_net.block_hidden_dim) - res_mask = torch.zeros(batch_size, max_num_candidate) - if self.use_cuda: - res_representations = res_representations.cuda() - res_mask = res_mask.cuda() - - squeezed_candidate_list, from_which_original_batch = [], [] - for b in range(batch_size): - squeezed_candidate_list += action_candidate_list[b] - for i in range(len(action_candidate_list[b])): - from_which_original_batch.append((b, i)) - - tmp_batch_size = 64 - n_tmp_batches = (len(squeezed_candidate_list) + tmp_batch_size - 1) // tmp_batch_size - for tmp_batch_id in range(n_tmp_batches): - tmp_batch_cand = squeezed_candidate_list[tmp_batch_id * tmp_batch_size: (tmp_batch_id + 1) * tmp_batch_size] # tmp_batch of candidates - tmp_batch_from = from_which_original_batch[tmp_batch_id * tmp_batch_size: (tmp_batch_id + 1) * tmp_batch_size] - - tmp_batch_cand_representation_sequence, tmp_batch_cand_mask = self.encode_text(tmp_batch_cand, use_model=use_model) # tmp_batch x num_word x hid, tmp_batch x num_word - - # masked mean the num_word dimension - _mask = torch.sum(tmp_batch_cand_mask, -1) # batch - tmp_batch_cand_representation = torch.sum(tmp_batch_cand_representation_sequence, -2) # batch x hid - tmp = torch.eq(_mask, 0).float() - if tmp_batch_cand_representation.is_cuda: - tmp = tmp.cuda() - _mask = _mask + tmp - tmp_batch_cand_representation = tmp_batch_cand_representation / _mask.unsqueeze(-1) # batch x hid - tmp_batch_cand_mask = tmp_batch_cand_mask.byte().any(-1).float() # batch - - for i in range(len(tmp_batch_from)): - res_representations[tmp_batch_from[i][0], tmp_batch_from[i][1], :] = tmp_batch_cand_representation[i] - res_mask[tmp_batch_from[i][0], tmp_batch_from[i][1]] = tmp_batch_cand_mask[i] - - return res_representations, res_mask - - def choose_model(self, use_model="online"): - if use_model == "online": - model = self.online_net - elif use_model == "target": - model = self.target_net - else: - raise NotImplementedError - return model - - def encode_text(self, observation_strings, use_model): - model = self.choose_model(use_model) - input_obs = self.get_word_input(observation_strings) - # encode - obs_encoding_sequence, obs_mask = model.encode_text(input_obs) - return obs_encoding_sequence, obs_mask - - def finish_of_episode(self, episode_no, batch_size): - # fraction_assist annealing - self.fraction_assist = self.fraction_assist_scheduler.value(episode_no) - self.fraction_assist = max(self.fraction_assist, 0.0) - - # fraction_random annealing - self.fraction_random = self.fraction_random_scheduler.value(episode_no) - self.fraction_random = max(self.fraction_random, 0.0) - - # Update target network - if (episode_no + batch_size) % self.target_net_update_frequency <= episode_no % self.target_net_update_frequency: - self.update_target_net() - # decay lambdas - if episode_no < self.learn_start_from_this_episode: - return - if episode_no < self.epsilon_anneal_episodes + self.learn_start_from_this_episode: - self.epsilon = self.epsilon_scheduler.value(episode_no - self.learn_start_from_this_episode) - self.epsilon = max(self.epsilon, 0.0) - - def preprocess_task(self, task_strings): - return [preproc(item) for item in task_strings] - - def preprocess_observation(self, observation_strings): - res = [] - for i in range(len(observation_strings)): - obs = observation_strings[i] - obs = preproc(obs) - # sort objects - if "you see" in obs: - # -= Welcome to TextWorld, ALFRED! =- You are in the middle of a room. Looking quickly around you, you see a armchair 2, a diningtable 1, a diningtable 2, a coffeetable 1, a armchair 1, a tvstand 1, a sidetable 2, a garbagecan 1, a sidetable 1, a sofa 1, a drawer 1, and a drawer 2. - before_you_see, after_you_see = obs.split("you see", 1) - before_you_see, after_you_see = before_you_see.strip(), after_you_see.strip() - before_you_see = " ".join([before_you_see, "you see"]) - object_list, after_period = after_you_see.split(".", 1) - object_list, after_period = object_list.strip(), after_period.strip() - after_period += "." - object_list = object_list.replace(", and ", ", ") - object_list = object_list.split(", ") - object_list = sorted(object_list) - if len(object_list) == 1: - object_string = object_list[0] - else: - object_string = ", ".join(object_list[:-1]) + ", and " + object_list[-1] - obs = " ".join([before_you_see, object_string]) + after_period - res.append(obs) - return res - - def preprocess_action_candidates(self, action_candidate_list): - batch_size = len(action_candidate_list) - preproced_action_candidate_list = [] - for b in range(batch_size): - ac = [preproc(item) for item in action_candidate_list[b]] - preproced_action_candidate_list.append(ac) - return preproced_action_candidate_list - - def preprocessing(self, observation_strings, action_candidate_list): - preproced_observation_strings = self.preprocess_observation(observation_strings) - preproced_action_candidate_list = self.preprocess_action_candidates(action_candidate_list) - return preproced_observation_strings, preproced_action_candidate_list - - def get_task_and_obs(self, observation_strings): - batch_size = len(observation_strings) - task_desc_strings, no_goal_observation_strings = [], [] - for b in range(batch_size): - task_desc = observation_strings[b].partition("Your task is to: ")[-1] - no_goal_obs_str = observation_strings[b].replace("Your task is to: %s" % task_desc, "") - if self.hide_init_receptacles: - no_goal_obs_str = no_goal_obs_str.partition("Looking quickly around you, you see")[0] - task_desc_strings.append(task_desc) - no_goal_observation_strings.append(no_goal_obs_str) - return task_desc_strings, no_goal_observation_strings - - def encode(self, observation_strings, use_model): - obs_enc_seq, obs_mask = self.encode_text(observation_strings, use_model=use_model) - return obs_enc_seq, obs_mask - - def action_scoring(self, action_candidate_list, h_obs, obs_mask, h_td, td_mask, previous_dynamics, use_model=None): - model = self.choose_model(use_model) - average_action_candidate_representations, action_candidate_mask = self.get_action_candidate_representations(action_candidate_list, use_model=use_model) # batch x num_cand x hid, batch x num_cand - aggregated_obs_representation = model.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = model.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = model.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else model.rnncell(averaged_representation) - else: - current_dynamics = None - - action_scores, action_masks = model.score_actions(average_action_candidate_representations, action_candidate_mask, - aggregated_obs_representation, obs_mask, current_dynamics) # batch x num_actions - return action_scores, action_masks, current_dynamics - - def beam_search_candidate_scoring(self, action_candidate_list, aggregated_obs_representation, obs_mask, current_dynamics, use_model=None): - model = self.choose_model(use_model) - average_action_candidate_representations, action_candidate_mask = self.get_action_candidate_representations(action_candidate_list, use_model=use_model) # batch x num_cand x hid, batch x num_cand - - action_scores, action_masks = model.score_actions(average_action_candidate_representations, action_candidate_mask, - aggregated_obs_representation, obs_mask, current_dynamics, fix_shared_components=True) # batch x num_actions - return action_scores, action_masks - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dagger_agent.py b/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dagger_agent.py deleted file mode 100644 index 9240a456..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dagger_agent.py +++ /dev/null @@ -1,364 +0,0 @@ -import copy -import operator -import logging -from queue import PriorityQueue - -import numpy as np -try: - import torch -except ImportError: - raise ImportError("torch not found. Please install them via `pip install alfworld[full]`.") -logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR) - -from alfworld.agents.agent import BaseAgent -import alfworld.agents.modules.memory as memory -from alfworld.agents.modules.generic import to_np, to_pt, _words_to_ids, pad_sequences, preproc, max_len, ez_gather_dim_1, LinearSchedule, BeamSearchNode -from alfworld.agents.modules.layers import NegativeLogLoss, masked_mean, compute_mask, GetGenerationQValue - - -class TextDAggerAgent(BaseAgent): - ''' - TextAgent trained with DAgger (Imitation Learning) - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - assert self.training_method == "dagger" - - def choose_softmax_action(self, action_rank, action_mask=None): - action_rank = action_rank - torch.min(action_rank, -1, keepdim=True)[0] + 1e-2 # minus the min value, so that all values are non-negative - if action_mask is not None: - assert action_mask.size() == action_rank.size(), (action_mask.size().shape, action_rank.size()) - action_rank = action_rank * action_mask - pred_softmax = torch.log_softmax(action_rank, dim=1) - action_indices = torch.argmax(pred_softmax, -1) # batch - return pred_softmax, to_np(action_indices) - - def update_dagger(self): - if self.recurrent: - return self.train_dagger_recurrent() - else: - return self.train_dagger() - - # without recurrency - def train_dagger(self): - - if len(self.dagger_memory) < self.dagger_replay_batch_size: - return None - transitions = self.dagger_memory.sample(self.dagger_replay_batch_size) - if transitions is None: - return None - batch = memory.dagger_transition(*zip(*transitions)) - - if self.action_space == "generation": - return self.command_generation_teacher_force(batch.observation_list, batch.task_list, batch.target_list) - elif self.action_space in ["admissible", "exhaustive"]: - return self.admissible_commands_teacher_force(batch.observation_list, batch.task_list, batch.action_candidate_list, batch.target_indices) - else: - raise NotImplementedError() - - def admissible_commands_teacher_force(self, observation_strings, task_desc_strings, action_candidate_list, target_indices): - expert_indicies = to_pt(np.array(target_indices), enable_cuda=self.use_cuda, type='long') - - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - - action_scores, _, _ = self.action_scoring(action_candidate_list, - h_obs, obs_mask, - h_td, td_mask, - None, - use_model="online") - - # softmax and cross-entropy - loss = self.cross_entropy_loss(action_scores, expert_indicies) - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(loss) - - def command_generation_teacher_force(self, observation_strings, task_desc_strings, target_strings): - input_target_strings = [" ".join(["[CLS]"] + item.split()) for item in target_strings] - output_target_strings = [" ".join(item.split() + ["[SEP]"]) for item in target_strings] - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - input_target = self.get_word_input(input_target_strings) - ground_truth = self.get_word_input(output_target_strings) # batch x target_length - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, None, input_obs) # batch x target_length x vocab - - batch_loss = NegativeLogLoss(pred * target_mask.unsqueeze(-1), ground_truth, target_mask, smoothing_eps=self.smoothing_eps) - loss = torch.mean(batch_loss) - - if loss is None: - return None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(loss) - - # with recurrency - def train_dagger_recurrent(self): - - if len(self.dagger_memory) < self.dagger_replay_batch_size: - return None - sequence_of_transitions, contains_first_step = self.dagger_memory.sample_sequence(self.dagger_replay_batch_size, self.dagger_replay_sample_history_length) - if sequence_of_transitions is None: - return None - - batches = [] - for transitions in sequence_of_transitions: - batch = memory.dagger_transition(*zip(*transitions)) - batches.append(batch) - - if self.action_space == "generation": - return self.command_generation_recurrent_teacher_force([batch.observation_list for batch in batches], [batch.task_list for batch in batches], [batch.target_list for batch in batches], contains_first_step) - elif self.action_space in ["admissible", "exhaustive"]: - return self.admissible_commands_recurrent_teacher_force([batch.observation_list for batch in batches], [batch.task_list for batch in batches], [batch.action_candidate_list for batch in batches], [batch.target_indices for batch in batches], contains_first_step) - else: - raise NotImplementedError() - - def admissible_commands_recurrent_teacher_force(self, seq_observation_strings, seq_task_desc_strings, seq_action_candidate_list, seq_target_indices, contains_first_step=False): - loss_list = [] - previous_dynamics = None - h_td, td_mask = self.encode(seq_task_desc_strings[0], use_model="online") - for step_no in range(self.dagger_replay_sample_history_length): - expert_indicies = to_pt(np.array(seq_target_indices[step_no]), enable_cuda=self.use_cuda, type='long') - h_obs, obs_mask = self.encode(seq_observation_strings[step_no], use_model="online") - action_scores, _, current_dynamics = self.action_scoring(seq_action_candidate_list[step_no], h_obs, obs_mask, h_td, td_mask, - previous_dynamics, use_model="online") - previous_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.dagger_replay_sample_update_from: - previous_dynamics = previous_dynamics.detach() - continue - - # softmax and cross-entropy - loss = self.cross_entropy_loss(action_scores, expert_indicies) - loss_list.append(loss) - loss = torch.stack(loss_list).mean() - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(loss) - - def command_generation_recurrent_teacher_force(self, seq_observation_strings, seq_task_desc_strings, seq_target_strings, contains_first_step=False): - loss_list = [] - previous_dynamics = None - h_td, td_mask = self.encode(seq_task_desc_strings[0], use_model="online") - for step_no in range(self.dagger_replay_sample_history_length): - input_target_strings = [" ".join(["[CLS]"] + item.split()) for item in seq_target_strings[step_no]] - output_target_strings = [" ".join(item.split() + ["[SEP]"]) for item in seq_target_strings[step_no]] - - input_obs = self.get_word_input(seq_observation_strings[step_no]) - h_obs, obs_mask = self.encode(seq_observation_strings[step_no], use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - - input_target = self.get_word_input(input_target_strings) - ground_truth = self.get_word_input(output_target_strings) # batch x target_length - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, current_dynamics, input_obs) # batch x target_length x vocab - - previous_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.dagger_replay_sample_update_from: - previous_dynamics = previous_dynamics.detach() - continue - - batch_loss = NegativeLogLoss(pred * target_mask.unsqueeze(-1), ground_truth, target_mask, smoothing_eps=self.smoothing_eps) - loss = torch.mean(batch_loss) - loss_list.append(loss) - - loss = torch.stack(loss_list).mean() - if loss is None: - return None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(loss) - - # free generation - def admissible_commands_greedy_generation(self, observation_strings, task_desc_strings, action_candidate_list, previous_dynamics): - - with torch.no_grad(): - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - action_scores, action_masks, current_dynamics = self.action_scoring(action_candidate_list, - h_obs, obs_mask, - h_td, td_mask, - previous_dynamics, - use_model="online") - - _, chosen_indices = self.choose_softmax_action(action_scores, action_masks) - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - return chosen_actions, chosen_indices, current_dynamics - - def command_generation_greedy_generation(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - batch_size = len(observation_strings) - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - else: - current_dynamics = None - - # greedy generation - input_target_list = [[self.word2id["[CLS]"]] for i in range(batch_size)] - eos = np.zeros(batch_size) - for _ in range(self.max_target_length): - - input_target = copy.deepcopy(input_target_list) - input_target = pad_sequences(input_target, maxlen=max_len(input_target)).astype('int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, current_dynamics, input_obs) # batch x target_length x vocab - # pointer softmax - pred = to_np(pred[:, -1]) # batch x vocab - pred = np.argmax(pred, -1) # batch - for b in range(batch_size): - new_stuff = [pred[b]] if eos[b] == 0 else [] - input_target_list[b] = input_target_list[b] + new_stuff - if pred[b] == self.word2id["[SEP]"]: - eos[b] = 1 - if np.sum(eos) == batch_size: - break - res = [self.tokenizer.decode(item) for item in input_target_list] - res = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in res] - return res, current_dynamics - - def command_generation_beam_search_generation(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - - batch_size = len(observation_strings) - beam_width = self.beam_width - if beam_width == 1: - res, current_dynamics = self.command_generation_greedy_generation(observation_strings, task_desc_strings, previous_dynamics) - res = [[item] for item in res] - return res, current_dynamics - generate_top_k = self.generate_top_k - res = [] - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - else: - current_dynamics = None - - for b in range(batch_size): - - # starts from CLS tokens - __input_target_list = [self.word2id["[CLS]"]] - __input_obs = input_obs[b: b + 1] # 1 x obs_len - __obs_mask = obs_mask[b: b + 1] # 1 x obs_len - __aggregated_obs_representation = aggregated_obs_representation[b: b + 1] # 1 x obs_len x hid - if current_dynamics is not None: - __current_dynamics = current_dynamics[b: b + 1] # 1 x hid - else: - __current_dynamics = None - ended_nodes = [] - - # starting node - previous node, input target, logp, length - node = BeamSearchNode(None, __input_target_list, 0, 1) - nodes_queue = PriorityQueue() - # start the queue - nodes_queue.put((node.val, node)) - queue_size = 1 - - while(True): - # give up when decoding takes too long - if queue_size > 2000: - break - - # fetch the best node - score, n = nodes_queue.get() - __input_target_list = n.input_target - - if (n.input_target[-1] == self.word2id["[SEP]"] or n.length >= self.max_target_length) and n.previous_node != None: - ended_nodes.append((score, n)) - # if we reached maximum # of sentences required - if len(ended_nodes) >= generate_top_k: - break - else: - continue - - input_target = pad_sequences([__input_target_list], dtype='int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) - # decode for one step using decoder - pred = self.online_net.decode(input_target, target_mask, __aggregated_obs_representation, __obs_mask, __current_dynamics, __input_obs) # 1 x target_length x vocab - pred = pred[0][-1].cpu() - gt_zero = torch.gt(pred, 0.0).float() # vocab - epsilon = torch.le(pred, 0.0).float() * 1e-8 # vocab - log_pred = torch.log(pred + epsilon) * gt_zero # vocab - - top_beam_width_log_probs, top_beam_width_indicies = torch.topk(log_pred, beam_width) - next_nodes = [] - - for new_k in range(beam_width): - pos = top_beam_width_indicies[new_k] - log_p = top_beam_width_log_probs[new_k].item() - node = BeamSearchNode(n, __input_target_list + [pos], n.log_prob + log_p, n.length + 1) - next_nodes.append((node.val, node)) - - # put them into queue - for i in range(len(next_nodes)): - score, nn = next_nodes[i] - nodes_queue.put((score, nn)) - # increase qsize - queue_size += len(next_nodes) - 1 - - # choose n best paths - if len(ended_nodes) == 0: - ended_nodes = [nodes_queue.get() for _ in range(generate_top_k)] - - utterances = [] - for score, n in sorted(ended_nodes, key=operator.itemgetter(0)): - utte = n.input_target - utte_string = self.tokenizer.decode(utte) - utterances.append(utte_string) - utterances = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in utterances] - res.append(utterances) - return res, current_dynamics - - # random generation - def admissible_commands_random_generation(self, action_candidate_list): - - chosen_actions, chosen_indicies = [], [] - for i in range(len(action_candidate_list)): - _action_idx = np.random.choice(len(action_candidate_list[i])) - chosen_indicies.append(_action_idx) - chosen_actions.append(action_candidate_list[i][_action_idx]) - return chosen_actions, chosen_indicies diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dqn_agent.py b/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dqn_agent.py deleted file mode 100644 index d6941f5e..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/text_dqn_agent.py +++ /dev/null @@ -1,946 +0,0 @@ -import copy -import operator -import logging -from queue import PriorityQueue - -import numpy as np - -try: - import torch - import torch.nn.functional as F -except ImportError: - raise ImportError("torch not found. Please install them via `pip install alfworld[full]`.") -logging.getLogger("transformers.tokenization_utils").setLevel(logging.ERROR) - -from alfworld.agents.agent import BaseAgent -from alfworld.agents.modules.generic import to_np, to_pt, _words_to_ids, pad_sequences, preproc, max_len, ez_gather_dim_1, LinearSchedule, BeamSearchNode -from alfworld.agents.modules.layers import NegativeLogLoss, masked_mean, compute_mask, GetGenerationQValue - - -class TextDQNAgent(BaseAgent): - ''' - TextAgent trained with DQN (Reinforcement Learning) - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - assert self.training_method == "dqn" - - def choose_random_action(self, action_rank, action_unpadded=None): - """ - Select an action randomly. - """ - batch_size = action_rank.size(0) - action_space_size = action_rank.size(1) - if action_unpadded is None: - indices = np.random.choice(action_space_size, batch_size) - else: - indices = [] - for j in range(batch_size): - indices.append(np.random.choice(len(action_unpadded[j]))) - indices = np.array(indices) - return indices - - def choose_maxQ_action(self, action_rank, action_mask=None): - """ - Generate an action by maximum q values. - """ - action_rank = action_rank - torch.min(action_rank, -1, keepdim=True)[0] + 1e-2 # minus the min value, so that all values are non-negative - if action_mask is not None: - assert action_mask.size() == action_rank.size(), (action_mask.size().shape, action_rank.size()) - action_rank = action_rank * action_mask - action_indices = torch.argmax(action_rank, -1) # batch - return to_np(action_indices) - - # choosing from list of admissible commands - def admissible_commands_act_greedy(self, observation_strings, task_desc_strings, action_candidate_list, previous_dynamics): - with torch.no_grad(): - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - action_scores, action_masks, current_dynamics = self.action_scoring(action_candidate_list, - h_obs, obs_mask, - h_td, td_mask, - previous_dynamics, - use_model="online") - action_indices_maxq = self.choose_maxQ_action(action_scores, action_masks) - chosen_indices = action_indices_maxq - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - - return chosen_actions, chosen_indices, current_dynamics - - def admissible_commands_act_random(self, observation_strings, task_desc_strings, action_candidate_list, previous_dynamics): - with torch.no_grad(): - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - action_scores, action_masks, current_dynamics = self.action_scoring(action_candidate_list, - h_obs, obs_mask, - h_td, td_mask, - previous_dynamics, - use_model="online") - action_indices_random = self.choose_random_action(action_scores, action_candidate_list) - - chosen_indices = action_indices_random - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - return chosen_actions, chosen_indices, current_dynamics - - def admissible_commands_act(self, observation_strings, task_desc_strings, action_candidate_list, previous_dynamics, random=False): - - with torch.no_grad(): - if self.mode == "eval": - return self.admissible_commands_act_greedy(observation_strings, task_desc_strings, action_candidate_list, previous_dynamics) - if random: - return self.admissible_commands_act_random(observation_strings, task_desc_strings, action_candidate_list, previous_dynamics) - batch_size = len(observation_strings) - - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - action_scores, action_masks, current_dynamics = self.action_scoring(action_candidate_list, - h_obs, obs_mask, - h_td, td_mask, - previous_dynamics, - use_model="online") - - action_indices_maxq = self.choose_maxQ_action(action_scores, action_masks) - action_indices_random = self.choose_random_action(action_scores, action_candidate_list) - - # random number for epsilon greedy - rand_num = np.random.uniform(low=0.0, high=1.0, size=(batch_size,)) - less_than_epsilon = (rand_num < self.epsilon).astype("float32") # batch - greater_than_epsilon = 1.0 - less_than_epsilon - - chosen_indices = less_than_epsilon * action_indices_random + greater_than_epsilon * action_indices_maxq - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - - return chosen_actions, chosen_indices, current_dynamics - - # choosing from output of beam search (without re-compute some intermediate representations) - def beam_search_choice_act_greedy(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - action_candidate_list, current_dynamics, obs_mask, aggregated_obs_representation = self.command_generation_by_beam_search(observation_strings, task_desc_strings, previous_dynamics) - action_scores, action_masks = self.beam_search_candidate_scoring(action_candidate_list, - aggregated_obs_representation, - obs_mask, - current_dynamics, - use_model="online") - action_indices_maxq = self.choose_maxQ_action(action_scores, action_masks) - chosen_indices = action_indices_maxq - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - - return chosen_actions, chosen_indices, current_dynamics, action_candidate_list - - def beam_search_choice_act_random(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - action_candidate_list, current_dynamics, obs_mask, aggregated_obs_representation = self.command_generation_by_beam_search(observation_strings, task_desc_strings, previous_dynamics) - action_scores, _ = self.beam_search_candidate_scoring(action_candidate_list, - aggregated_obs_representation, - obs_mask, - current_dynamics, - use_model="online") - action_indices_random = self.choose_random_action(action_scores, action_candidate_list) - - chosen_indices = action_indices_random - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - return chosen_actions, chosen_indices, current_dynamics, action_candidate_list - - def beam_search_choice_act(self, observation_strings, task_desc_strings, previous_dynamics, random=False): - with torch.no_grad(): - if self.mode == "eval": - return self.beam_search_choice_act_greedy(observation_strings, task_desc_strings, previous_dynamics) - if random: - return self.beam_search_choice_act_random(observation_strings, task_desc_strings, previous_dynamics) - batch_size = len(observation_strings) - action_candidate_list, current_dynamics, obs_mask, aggregated_obs_representation = self.command_generation_by_beam_search(observation_strings, task_desc_strings, previous_dynamics) - action_scores, action_masks = self.beam_search_candidate_scoring(action_candidate_list, - aggregated_obs_representation, - obs_mask, - current_dynamics, - use_model="online") - - action_indices_maxq = self.choose_maxQ_action(action_scores, action_masks) - action_indices_random = self.choose_random_action(action_scores, action_candidate_list) - - # random number for epsilon greedy - rand_num = np.random.uniform(low=0.0, high=1.0, size=(batch_size,)) - less_than_epsilon = (rand_num < self.epsilon).astype("float32") # batch - greater_than_epsilon = 1.0 - less_than_epsilon - - chosen_indices = less_than_epsilon * action_indices_random + greater_than_epsilon * action_indices_maxq - chosen_indices = chosen_indices.astype(int) - chosen_actions = [item[idx] for item, idx in zip(action_candidate_list, chosen_indices)] - - return chosen_actions, chosen_indices, current_dynamics, action_candidate_list - - # generating token by token - def command_generation_by_beam_search(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - batch_size = len(observation_strings) - beam_width = self.beam_width - generate_top_k = self.generate_top_k - chosen_actions = [] - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - else: - current_dynamics = None - - for b in range(batch_size): - # starts from CLS tokens - __input_target_list = [self.word2id["[CLS]"]] - __input_obs = input_obs[b: b + 1] # 1 x obs_len - __obs_mask = obs_mask[b: b + 1] # 1 x obs_len - __aggregated_obs_representation = aggregated_obs_representation[b: b + 1] # 1 x obs_len x hid - if current_dynamics is not None: - __current_dynamics = current_dynamics[b: b + 1] # 1 x hid - else: - __current_dynamics = None - ended_nodes = [] - - # starting node - previous node, input target, logp, length - node = BeamSearchNode(None, __input_target_list, 0, 1) - nodes_queue = PriorityQueue() - # start the queue - nodes_queue.put((node.val, node)) - queue_size = 1 - while(True): - # give up when decoding takes too long - if queue_size > 2000: - break - # fetch the best node - score, n = nodes_queue.get() - __input_target_list = n.input_target - - if (n.input_target[-1] == self.word2id["[SEP]"] or n.length >= self.max_target_length) and n.previous_node != None: - ended_nodes.append((score, n)) - # if we reached maximum # of sentences required - if len(ended_nodes) >= generate_top_k: - break - else: - continue - - input_target = pad_sequences([__input_target_list], dtype='int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) - # decode for one step using decoder - pred = self.online_net.decode(input_target, target_mask, __aggregated_obs_representation, __obs_mask, __current_dynamics, __input_obs) # 1 x target_length x vocab - pred = pred[0][-1].cpu() - gt_zero = torch.gt(pred, 0.0).float() # vocab - epsilon = torch.le(pred, 0.0).float() * 1e-8 # vocab - log_pred = torch.log(pred + epsilon) * gt_zero # vocab - - top_beam_width_log_probs, top_beam_width_indicies = torch.topk(log_pred, beam_width) - next_nodes = [] - - for new_k in range(beam_width): - pos = top_beam_width_indicies[new_k] - log_p = top_beam_width_log_probs[new_k].item() - node = BeamSearchNode(n, __input_target_list + [pos], n.log_prob + log_p, n.length + 1) - next_nodes.append((node.val, node)) - - # put them into queue - for i in range(len(next_nodes)): - score, nn = next_nodes[i] - nodes_queue.put((score, nn)) - # increase qsize - queue_size += len(next_nodes) - 1 - - # choose n best paths - if len(ended_nodes) == 0: - ended_nodes = [nodes_queue.get() for _ in range(generate_top_k)] - - utterances = [] - for score, n in sorted(ended_nodes, key=operator.itemgetter(0)): - utte = n.input_target - utte_string = self.tokenizer.decode(utte) - utterances.append(utte_string) - - utterances = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in utterances] - chosen_actions.append(utterances) - return chosen_actions, current_dynamics, obs_mask, aggregated_obs_representation - - def command_generation_act_greedy(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - batch_size = len(observation_strings) - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - else: - current_dynamics = None - - # greedy generation - input_target_list = [[self.word2id["[CLS]"]] for i in range(batch_size)] - eos = np.zeros(batch_size) - for _ in range(self.max_target_length): - - input_target = copy.deepcopy(input_target_list) - input_target = pad_sequences(input_target, maxlen=max_len(input_target)).astype('int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, current_dynamics, input_obs) # batch x target_length x vocab - # pointer softmax - pred = to_np(pred[:, -1]) # batch x vocab - pred = np.argmax(pred, -1) # batch - for b in range(batch_size): - new_stuff = [pred[b]] if eos[b] == 0 else [] - input_target_list[b] = input_target_list[b] + new_stuff - if pred[b] == self.word2id["[SEP]"]: - eos[b] = 1 - if np.sum(eos) == batch_size: - break - chosen_actions = [self.tokenizer.decode(item) for item in input_target_list] - chosen_actions = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in chosen_actions] - chosen_indices = [item[1:] for item in input_target_list] - for i in range(len(chosen_indices)): - if chosen_indices[i][-1] == self.word2id["[SEP]"]: - chosen_indices[i] = chosen_indices[i][:-1] - return chosen_actions, chosen_indices, current_dynamics - - def command_generation_act_random(self, observation_strings, task_desc_strings, previous_dynamics): - with torch.no_grad(): - - batch_size = len(observation_strings) - beam_width = self.beam_width - generate_top_k = self.generate_top_k - chosen_actions, chosen_indices = [], [] - - input_obs = self.get_word_input(observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - if self.recurrent: - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - else: - current_dynamics = None - - for b in range(batch_size): - # starts from CLS tokens - __input_target_list = [self.word2id["[CLS]"]] - __input_obs = input_obs[b: b + 1] # 1 x obs_len - __obs_mask = obs_mask[b: b + 1] # 1 x obs_len - __aggregated_obs_representation = aggregated_obs_representation[b: b + 1] # 1 x obs_len x hid - if current_dynamics is not None: - __current_dynamics = current_dynamics[b: b + 1] # 1 x hid - else: - __current_dynamics = None - ended_nodes = [] - # starting node - previous node, input target, logp, length - node = BeamSearchNode(None, __input_target_list, 0, 1) - nodes_queue = PriorityQueue() - # start the queue - nodes_queue.put((node.val, node)) - queue_size = 1 - - while(True): - # give up when decoding takes too long - if queue_size > 2000: - break - # fetch the best node - score, n = nodes_queue.get() - __input_target_list = n.input_target - - if (n.input_target[-1] == self.word2id["[SEP]"] or n.length >= self.max_target_length) and n.previous_node != None: - ended_nodes.append((score, n)) - # if we reached maximum # of sentences required - if len(ended_nodes) >= generate_top_k: - break - else: - continue - - input_target = pad_sequences([__input_target_list], dtype='int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) - # decode for one step using decoder - pred = self.online_net.decode(input_target, target_mask, __aggregated_obs_representation, __obs_mask, __current_dynamics, __input_obs) # 1 x target_length x vocab - pred = pred[0][-1].cpu() - gt_zero = torch.gt(pred, 0.0).float() # vocab - epsilon = torch.le(pred, 0.0).float() * 1e-8 # vocab - log_pred = torch.log(pred + epsilon) * gt_zero # vocab - - top_beam_width_log_probs, top_beam_width_indicies = torch.topk(log_pred, beam_width) - next_nodes = [] - - for new_k in range(beam_width): - pos = top_beam_width_indicies[new_k] - log_p = top_beam_width_log_probs[new_k].item() - node = BeamSearchNode(n, __input_target_list + [pos], n.log_prob + log_p, n.length + 1) - next_nodes.append((node.val, node)) - - # put them into queue - for i in range(len(next_nodes)): - score, nn = next_nodes[i] - nodes_queue.put((score, nn)) - # increase qsize - queue_size += len(next_nodes) - 1 - - # choose n best paths - if len(ended_nodes) == 0: - ended_nodes = [nodes_queue.get() for _ in range(generate_top_k)] - - indicies, utterances = [], [] - for score, n in sorted(ended_nodes, key=operator.itemgetter(0)): - utte = n.input_target - utte_string = self.tokenizer.decode(utte) - utterances.append(utte_string) - indicies.append(utte) - - utterances = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in utterances] - indicies = [item[1:] for item in indicies] - for i in range(len(indicies)): - if indicies[i][-1] == self.word2id["[SEP]"]: - indicies[i] = indicies[i][:-1] - - # sample one from all generated beams - rand_idx = np.random.choice(len(indicies)) - chosen_actions.append(utterances[rand_idx]) - chosen_indices.append(indicies[rand_idx]) - return chosen_actions, chosen_indices, current_dynamics - - def command_generation_act(self, observation_strings, task_desc_strings, previous_dynamics, random=False): - with torch.no_grad(): - if self.mode == "eval": - return self.command_generation_act_greedy(observation_strings, task_desc_strings, previous_dynamics) - if random: - return self.command_generation_act_random(observation_strings, task_desc_strings, previous_dynamics) - batch_size = len(observation_strings) - greedy_actions, greedy_indices, greedy_current_dynamics = self.command_generation_act_greedy(observation_strings, task_desc_strings, previous_dynamics) - - # random number for epsilon greedy - chosen_actions, chosen_indices, current_dynamics = [], [], [] - rand_num = np.random.uniform(low=0.0, high=1.0, size=(batch_size,)) - for b in range(batch_size): - if rand_num[b] < self.epsilon: - # random - random_actions, random_indices, random_current_dynamics = self.command_generation_act_random(observation_strings[b: b + 1], task_desc_strings[b: b + 1], None if previous_dynamics is None else previous_dynamics[b: b + 1]) - chosen_actions.append(random_actions[0]) - chosen_indices.append(random_indices[0]) - if self.recurrent: - current_dynamics.append(random_current_dynamics[0]) - else: - # greedy - chosen_actions.append(greedy_actions[b]) - chosen_indices.append(greedy_indices[b]) - if self.recurrent: - current_dynamics.append(greedy_current_dynamics[b]) - current_dynamics = torch.stack(current_dynamics, 0) if self.recurrent else None # batch x hidden - return chosen_actions, chosen_indices, current_dynamics - - # update: admissible commands - def get_dqn_loss_admissible_commands(self): - """ - Update neural model in agent. In this example we follow algorithm - of updating model in dqn with replay memory. - """ - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data = self.dqn_memory.get_batch(self.replay_batch_size, multi_step=self.multi_step) - if data is None: - return None, None - - obs_list, task_list, candidate_list, action_indices, rewards, next_obs_list, next_candidate_list, actual_ns = data - if self.use_cuda: - rewards = rewards.cuda() - - h_obs, obs_mask = self.encode(obs_list, use_model="online") - h_td, td_mask = self.encode(task_list, use_model="online") - action_scores, _, _ = self.action_scoring(candidate_list, - h_obs, obs_mask, - h_td, td_mask, - None, - use_model="online") - - # ps_a - action_indices = to_pt(action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - q_value = ez_gather_dim_1(action_scores, action_indices).squeeze(1) # batch - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - h_obs, obs_mask = self.encode(next_obs_list, use_model="online") - next_action_scores, next_action_masks, _ = self.action_scoring(next_candidate_list, - h_obs, obs_mask, - h_td.detach(), td_mask.detach(), - None, - use_model="online") - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - next_action_indices = self.choose_maxQ_action(next_action_scores, next_action_masks) # batch - next_action_indices = to_pt(next_action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - # pns # Probabilities p(s_t+n, ·; θtarget) - h_obs, obs_mask = self.encode(next_obs_list, use_model="target") - h_td_t, td_mask_t = self.encode(task_list, use_model="target") - next_action_scores, _, _ = self.action_scoring(next_candidate_list, - h_obs, obs_mask, - h_td_t, td_mask_t, - None, - use_model="target") - - # pns_a # Double-Q probabilities p(s_t+n, argmax_a[(z, p(s_t+n, a; θonline))]; θtarget) - next_q_value = ez_gather_dim_1(next_action_scores, next_action_indices).squeeze(1) # batch - discount = to_pt((np.ones_like(actual_ns) * self.discount_gamma_game_reward) ** actual_ns, self.use_cuda, type="float") - - rewards = rewards + next_q_value * discount # batch - loss = F.smooth_l1_loss(q_value, rewards) - return loss, q_value - - def get_drqn_loss_admissible_commands(self): - """ - Update neural model in agent. In this example we follow algorithm - of updating model in dqn with replay memory. - """ - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data, contains_first_step = self.dqn_memory.get_batch_of_sequences(self.replay_batch_size, sample_history_length=self.rl_replay_sample_history_length) - if data is None: - return None, None - - seq_obs, task, seq_candidates, seq_chosen_indices, seq_reward, seq_next_obs, seq_next_candidates = data - loss_list, q_value_list = [], [] - prev_dynamics = None - - h_td, td_mask = self.encode(task, use_model="online") - with torch.no_grad(): - h_td_t, td_mask_t = self.encode(task, use_model="target") - - for step_no in range(self.rl_replay_sample_history_length): - obs, candidates, chosen_indices, reward, next_obs, next_candidates = seq_obs[step_no], seq_candidates[step_no], seq_chosen_indices[step_no], seq_reward[step_no], seq_next_obs[step_no], seq_next_candidates[step_no] - if self.use_cuda: - reward = reward.cuda() - - h_obs, obs_mask = self.encode(obs, use_model="online") - action_scores, _, current_dynamics = self.action_scoring(candidates, h_obs, obs_mask, h_td, td_mask, - prev_dynamics, use_model="online") - # ps_a - chosen_indices = to_pt(chosen_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - q_value = ez_gather_dim_1(action_scores, chosen_indices).squeeze(1) # batch - - prev_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.rl_replay_sample_update_from: - q_value = q_value.detach() - prev_dynamics = prev_dynamics.detach() - continue - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - - h_obs, obs_mask = self.encode(next_obs, use_model="online") - next_action_scores, next_action_masks, _ = self.action_scoring(next_candidates, h_obs, obs_mask, h_td, td_mask, - prev_dynamics, use_model="online") - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - next_action_indices = self.choose_maxQ_action(next_action_scores, next_action_masks) # batch - next_action_indices = to_pt(next_action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - - # pns # Probabilities p(s_t+n, ·; θtarget) - h_obs, obs_mask = self.encode(next_obs, use_model="target") - next_action_scores, _, _ = self.action_scoring(next_candidates, h_obs, obs_mask, h_td_t, td_mask_t, - prev_dynamics, use_model="target") - - # pns_a # Double-Q probabilities p(s_t+n, argmax_a[(z, p(s_t+n, a; θonline))]; θtarget) - next_q_value = ez_gather_dim_1(next_action_scores, next_action_indices).squeeze(1) # batch - - reward = reward + next_q_value * self.discount_gamma_game_reward # batch - loss = F.smooth_l1_loss(q_value, reward) # 1 - loss_list.append(loss) - q_value_list.append(q_value) - - loss = torch.stack(loss_list).mean() - q_value = torch.stack(q_value_list).mean() - - return loss, q_value - - def update_dqn_admissible_commands(self): - # update neural model by replaying snapshots in replay memory - if self.recurrent: - dqn_loss, q_value = self.get_drqn_loss_admissible_commands() - else: - dqn_loss, q_value = self.get_dqn_loss_admissible_commands() - - if dqn_loss is None: - return None, None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - dqn_loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(torch.mean(dqn_loss)), to_np(torch.mean(q_value)) - - # update: beam search choice - def get_dqn_loss_beam_search_choice(self): - """ - Update neural model in agent. In this example we follow algorithm - of updating model in dqn with replay memory. - """ - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data = self.dqn_memory.get_batch(self.replay_batch_size, multi_step=self.multi_step) - if data is None: - return None, None - - obs_list, task_list, candidate_list, action_indices, rewards, next_obs_list, next_candidate_list, actual_ns = data - if self.use_cuda: - rewards = rewards.cuda() - - with torch.no_grad(): - h_obs, obs_mask = self.encode(obs_list, use_model="online") - h_td, td_mask = self.encode(task_list, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - action_scores, _ = self.beam_search_candidate_scoring(candidate_list, aggregated_obs_representation, obs_mask, None, use_model="online") - - # ps_a - action_indices = to_pt(action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - q_value = ez_gather_dim_1(action_scores, action_indices).squeeze(1) # batch - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - h_obs, obs_mask = self.encode(next_obs_list, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - next_action_scores, next_action_masks = self.beam_search_candidate_scoring(next_candidate_list, aggregated_obs_representation, obs_mask, None, use_model="online") - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - next_action_indices = self.choose_maxQ_action(next_action_scores, next_action_masks) # batch - next_action_indices = to_pt(next_action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - # pns # Probabilities p(s_t+n, ·; θtarget) - h_obs, obs_mask = self.encode(next_obs_list, use_model="target") - h_td_t, td_mask_t = self.encode(task_list, use_model="target") - aggregated_obs_representation = self.target_net.aggretate_information(h_obs, obs_mask, h_td_t, td_mask_t) # batch x obs_length x hid - next_action_scores, _ = self.beam_search_candidate_scoring(next_candidate_list, aggregated_obs_representation, obs_mask, None, use_model="target") - - # pns_a # Double-Q probabilities p(s_t+n, argmax_a[(z, p(s_t+n, a; θonline))]; θtarget) - next_q_value = ez_gather_dim_1(next_action_scores, next_action_indices).squeeze(1) # batch - discount = to_pt((np.ones_like(actual_ns) * self.discount_gamma_game_reward) ** actual_ns, self.use_cuda, type="float") - - rewards = rewards + next_q_value * discount # batch - loss = F.smooth_l1_loss(q_value, rewards) - return loss, q_value - - def get_drqn_loss_beam_search_choice(self): - """ - Update neural model in agent. In this example we follow algorithm - of updating model in dqn with replay memory. - """ - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data, contains_first_step = self.dqn_memory.get_batch_of_sequences(self.replay_batch_size, sample_history_length=self.rl_replay_sample_history_length) - if data is None: - return None, None - - seq_obs, task, seq_candidates, seq_chosen_indices, seq_reward, seq_next_obs, seq_next_candidates = data - loss_list, q_value_list = [], [] - prev_dynamics = None - - with torch.no_grad(): - h_td, td_mask = self.encode(task, use_model="online") - h_td_t, td_mask_t = self.encode(task, use_model="target") - - for step_no in range(self.rl_replay_sample_history_length): - obs, candidates, chosen_indices, reward, next_obs, next_candidates = seq_obs[step_no], seq_candidates[step_no], seq_chosen_indices[step_no], seq_reward[step_no], seq_next_obs[step_no], seq_next_candidates[step_no] - if self.use_cuda: - reward = reward.cuda() - - with torch.no_grad(): - h_obs, obs_mask = self.encode(obs, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, prev_dynamics) if prev_dynamics is not None else self.online_net.rnncell(averaged_representation) - action_scores, _ = self.beam_search_candidate_scoring(candidates, aggregated_obs_representation, obs_mask, current_dynamics, use_model="online") - # ps_a - chosen_indices = to_pt(chosen_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - q_value = ez_gather_dim_1(action_scores, chosen_indices).squeeze(1) # batch - - prev_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.rl_replay_sample_update_from: - q_value = q_value.detach() - prev_dynamics = prev_dynamics.detach() - continue - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - - h_obs, obs_mask = self.encode(next_obs, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - next_dynamics = self.online_net.rnncell(averaged_representation, current_dynamics) if current_dynamics is not None else self.online_net.rnncell(averaged_representation) - next_action_scores, next_action_masks = self.beam_search_candidate_scoring(next_candidates, aggregated_obs_representation, obs_mask, next_dynamics, use_model="online") - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - next_action_indices = self.choose_maxQ_action(next_action_scores, next_action_masks) # batch - next_action_indices = to_pt(next_action_indices, enable_cuda=self.use_cuda, type='long').unsqueeze(-1) - - # pns # Probabilities p(s_t+n, ·; θtarget) - h_obs, obs_mask = self.encode(next_obs, use_model="target") - aggregated_obs_representation = self.target_net.aggretate_information(h_obs, obs_mask, h_td_t, td_mask_t) # batch x obs_length x hid - averaged_representation = self.target_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - next_dynamics = self.target_net.rnncell(averaged_representation, current_dynamics) if current_dynamics is not None else self.target_net.rnncell(averaged_representation) - next_action_scores, _ = self.beam_search_candidate_scoring(next_candidates, aggregated_obs_representation, obs_mask, next_dynamics, use_model="target") - - # pns_a # Double-Q probabilities p(s_t+n, argmax_a[(z, p(s_t+n, a; θonline))]; θtarget) - next_q_value = ez_gather_dim_1(next_action_scores, next_action_indices).squeeze(1) # batch - - reward = reward + next_q_value * self.discount_gamma_game_reward # batch - loss = F.smooth_l1_loss(q_value, reward) # 1 - loss_list.append(loss) - q_value_list.append(q_value) - - loss = torch.stack(loss_list).mean() - q_value = torch.stack(q_value_list).mean() - - return loss, q_value - - def update_dqn_beam_search_choice(self): - # update neural model by replaying snapshots in replay memory - if self.recurrent: - dqn_loss, q_value = self.get_drqn_loss_beam_search_choice() - else: - dqn_loss, q_value = self.get_dqn_loss_beam_search_choice() - - if dqn_loss is None: - return None, None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - dqn_loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(torch.mean(dqn_loss)), to_np(torch.mean(q_value)) - - # update: command generation - def get_dqn_loss_command_generation(self): - """ - Update neural model in agent. In this example we follow algorithm - of updating model in dqn with replay memory. - """ - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data = self.dqn_memory.get_batch(self.replay_batch_size, multi_step=self.multi_step) - if data is None: - return None, None - - observation_strings, task_desc_strings, _, action_indices, rewards, next_observation_strings, _, actual_ns = data - batch_size = len(observation_strings) - if self.use_cuda: - rewards = rewards.cuda() - - input_target = [[self.word2id["[CLS]"]] + item for item in action_indices] - ground_truth = [item + [self.word2id["[SEP]"]] for item in action_indices] - input_target = self.get_word_input_from_ids(input_target) - ground_truth = self.get_word_input_from_ids(ground_truth) - - input_obs = self.get_word_input(observation_strings) - next_input_obs = self.get_word_input(next_observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, None, input_obs) # batch x target_length x vocab - q_value = GetGenerationQValue(pred * target_mask.unsqueeze(-1), ground_truth, target_mask) - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - next_h_obs, next_obs_mask = self.encode(next_observation_strings, use_model="online") - next_aggregated_obs_representation = self.online_net.aggretate_information(next_h_obs, next_obs_mask, h_td, td_mask) # batch x obs_length x hid - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - # greedy generation - input_target_list = [[self.word2id["[CLS]"]] for i in range(batch_size)] - eos = np.zeros(batch_size) - for _ in range(self.max_target_length): - input_target = copy.deepcopy(input_target_list) - input_target = pad_sequences(input_target, maxlen=max_len(input_target)).astype('int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, next_aggregated_obs_representation, next_obs_mask, None, next_input_obs) # batch x target_length x vocab - # pointer softmax - pred = to_np(pred[:, -1]) # batch x vocab - pred = np.argmax(pred, -1) # batch - for b in range(batch_size): - new_stuff = [pred[b]] if eos[b] == 0 else [] - input_target_list[b] = input_target_list[b] + new_stuff - if pred[b] == self.word2id["[SEP]"]: - eos[b] = 1 - if np.sum(eos) == batch_size: - break - chosen_indices = [item[1:] for item in input_target_list] - for i in range(len(chosen_indices)): - if chosen_indices[i][-1] == self.word2id["[SEP]"]: - chosen_indices[i] = chosen_indices[i][:-1] - - # pns # Probabilities p(s_t+n, ·; θtarget) - next_input_target = [[self.word2id["[CLS]"]] + item for item in chosen_indices] - next_ground_truth = [item + [self.word2id["[SEP]"]] for item in chosen_indices] - next_input_target = self.get_word_input_from_ids(next_input_target) - next_ground_truth = self.get_word_input_from_ids(next_ground_truth) - - next_h_obs, next_obs_mask = self.encode(next_observation_strings, use_model="target") - next_h_td, next_td_mask = self.encode(task_desc_strings, use_model="target") - next_aggregated_obs_representation = self.target_net.aggretate_information(next_h_obs, next_obs_mask, next_h_td, next_td_mask) # batch x obs_length x hid - - next_target_mask = compute_mask(next_input_target) # mask of ground truth should be the same - next_pred = self.target_net.decode(next_input_target, next_target_mask, next_aggregated_obs_representation, next_obs_mask, None, next_input_obs) # batch x target_length x vocab - next_q_value = GetGenerationQValue(next_pred * next_target_mask.unsqueeze(-1), next_ground_truth, next_target_mask) # batch - - discount = to_pt((np.ones_like(actual_ns) * self.discount_gamma_game_reward) ** actual_ns, self.use_cuda, type="float") - - rewards = rewards + next_q_value * discount # batch - loss = F.smooth_l1_loss(q_value, rewards) - return loss, q_value - - def get_drqn_loss_command_generation(self): - if len(self.dqn_memory) < self.replay_batch_size: - return None, None - data, contains_first_step = self.dqn_memory.get_batch_of_sequences(self.replay_batch_size, sample_history_length=self.rl_replay_sample_history_length) - if data is None: - return None, None - - seq_obs, task_desc_strings, _, seq_chosen_indices, seq_reward, seq_next_obs, _ = data - batch_size = len(seq_obs[0]) - loss_list, q_value_list = [], [] - previous_dynamics = None - - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - with torch.no_grad(): - h_td_t, td_mask_t = self.encode(task_desc_strings, use_model="target") - - for step_no in range(self.rl_replay_sample_history_length): - observation_strings, action_indices, reward, next_observation_strings = seq_obs[step_no], seq_chosen_indices[step_no], seq_reward[step_no], seq_next_obs[step_no] - if self.use_cuda: - reward = reward.cuda() - - input_target = [[self.word2id["[CLS]"]] + item for item in action_indices] - ground_truth = [item + [self.word2id["[SEP]"]] for item in action_indices] - input_target = self.get_word_input_from_ids(input_target) - ground_truth = self.get_word_input_from_ids(ground_truth) - - input_obs = self.get_word_input(observation_strings) - next_input_obs = self.get_word_input(next_observation_strings) - h_obs, obs_mask = self.encode(observation_strings, use_model="online") - aggregated_obs_representation = self.online_net.aggretate_information(h_obs, obs_mask, h_td, td_mask) # batch x obs_length x hid - - averaged_representation = self.online_net.masked_mean(aggregated_obs_representation, obs_mask) # batch x hid - current_dynamics = self.online_net.rnncell(averaged_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_representation) - - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, aggregated_obs_representation, obs_mask, current_dynamics, input_obs) # batch x target_length x vocab - q_value = GetGenerationQValue(pred * target_mask.unsqueeze(-1), ground_truth, target_mask) - - previous_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.rl_replay_sample_update_from: - q_value = q_value.detach() - previous_dynamics = previous_dynamics.detach() - continue - - with torch.no_grad(): - if self.noisy_net: - self.target_net.reset_noise() # Sample new target net noise - # pns Probabilities p(s_t+n, ·; θonline) - next_h_obs, next_obs_mask = self.encode(next_observation_strings, use_model="online") - next_aggregated_obs_representation = self.online_net.aggretate_information(next_h_obs, next_obs_mask, h_td, td_mask) # batch x obs_length x hid - next_averaged_representation = self.online_net.masked_mean(next_aggregated_obs_representation, next_obs_mask) # batch x hid - next_dynamics = self.online_net.rnncell(averaged_representation, current_dynamics) if current_dynamics is not None else self.online_net.rnncell(next_averaged_representation) - - # Perform argmax action selection using online network: argmax_a[(z, p(s_t+n, a; θonline))] - # greedy generation - input_target_list = [[self.word2id["[CLS]"]] for i in range(batch_size)] - eos = np.zeros(batch_size) - for _ in range(self.max_target_length): - input_target = copy.deepcopy(input_target_list) - input_target = pad_sequences(input_target, maxlen=max_len(input_target)).astype('int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.decode(input_target, target_mask, next_aggregated_obs_representation, next_obs_mask, next_dynamics, next_input_obs) # batch x target_length x vocab - # pointer softmax - pred = to_np(pred[:, -1]) # batch x vocab - pred = np.argmax(pred, -1) # batch - for b in range(batch_size): - new_stuff = [pred[b]] if eos[b] == 0 else [] - input_target_list[b] = input_target_list[b] + new_stuff - if pred[b] == self.word2id["[SEP]"]: - eos[b] = 1 - if np.sum(eos) == batch_size: - break - chosen_indices = [item[1:] for item in input_target_list] - for i in range(len(chosen_indices)): - if chosen_indices[i][-1] == self.word2id["[SEP]"]: - chosen_indices[i] = chosen_indices[i][:-1] - - # pns # Probabilities p(s_t+n, ·; θtarget) - next_input_target = [[self.word2id["[CLS]"]] + item for item in chosen_indices] - next_ground_truth = [item + [self.word2id["[SEP]"]] for item in chosen_indices] - next_input_target = self.get_word_input_from_ids(next_input_target) - next_ground_truth = self.get_word_input_from_ids(next_ground_truth) - - next_h_obs, next_obs_mask = self.encode(next_observation_strings, use_model="target") - next_aggregated_obs_representation = self.target_net.aggretate_information(next_h_obs, next_obs_mask, h_td_t, td_mask_t) # batch x obs_length x hid - next_averaged_representation = self.target_net.masked_mean(next_aggregated_obs_representation, next_obs_mask) # batch x hid - next_dynamics = self.target_net.rnncell(averaged_representation, current_dynamics) if current_dynamics is not None else self.target_net.rnncell(next_averaged_representation) - - next_target_mask = compute_mask(next_input_target) # mask of ground truth should be the same - next_pred = self.target_net.decode(next_input_target, next_target_mask, next_aggregated_obs_representation, next_obs_mask, next_dynamics, next_input_obs) # batch x target_length x vocab - next_q_value = GetGenerationQValue(next_pred * next_target_mask.unsqueeze(-1), next_ground_truth, next_target_mask) # batch - - reward = reward + next_q_value * self.discount_gamma_game_reward # batch - loss = F.smooth_l1_loss(q_value, reward) # 1 - loss_list.append(loss) - q_value_list.append(q_value) - - loss = torch.stack(loss_list).mean() - q_value = torch.stack(q_value_list).mean() - return loss, q_value - - def update_dqn_command_generation(self): - # update neural model by replaying snapshots in replay memory - if self.recurrent: - dqn_loss, q_value = self.get_drqn_loss_command_generation() - else: - dqn_loss, q_value = self.get_dqn_loss_command_generation() - - if dqn_loss is None: - return None, None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - dqn_loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(torch.mean(dqn_loss)), to_np(torch.mean(q_value)) - - def update_dqn(self): - if self.action_space == "generation": - return self.update_dqn_command_generation() - elif self.action_space == "beam_search_choice": - return self.update_dqn_beam_search_choice() - elif self.action_space in ["admissible", "exhaustive"]: - return self.update_dqn_admissible_commands() - else: - raise NotImplementedError() \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/vision_dagger_agent.py b/agent_system/environments/env_package/alfworld/alfworld/agents/agent/vision_dagger_agent.py deleted file mode 100644 index 0052bd08..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/agent/vision_dagger_agent.py +++ /dev/null @@ -1,344 +0,0 @@ -import copy - -import numpy as np -try: - import torch - import torch.nn.functional as F -except ImportError: - raise ImportError("torch not found. Please install them via `pip install alfworld[full]`.") - -import alfworld.agents -import alfworld.agents.modules.memory as memory -from alfworld.agents.agent import TextDAggerAgent -from alfworld.agents.modules.generic import to_np, to_pt, _words_to_ids, pad_sequences, preproc, max_len, ez_gather_dim_1, LinearSchedule -from alfworld.agents.modules.layers import NegativeLogLoss, masked_mean, compute_mask -from alfworld.agents.detector.mrcnn import load_pretrained_model - -import torchvision.transforms as T -from torchvision import models -from torchvision.ops import boxes as box_ops - - -class VisionDAggerAgent(TextDAggerAgent): - ''' - Vision Agent trained with DAgger - ''' - def __init__(self, config): - super().__init__(config) - - assert self.action_space == "generation" - - self.use_gpu = config['general']['use_cuda'] - self.transform = T.Compose([T.ToTensor()]) - - # choose vision model - self.vision_model_type = config['vision_dagger']['model_type'] - self.use_exploration_frame_feats = config['vision_dagger']['use_exploration_frame_feats'] - self.sequence_aggregation_method = config['vision_dagger']['sequence_aggregation_method'] - - # initialize model - if self.vision_model_type in {'resnet'}: - self.detector = models.resnet18(pretrained=True) - self.detector.eval() - if self.use_gpu: - self.detector.cuda() - elif self.vision_model_type in {'maskrcnn', 'maskrcnn_whole'}: - pretrained_model_path = config['mask_rcnn']['pretrained_model_path'] - self.mask_rcnn_top_k_boxes = self.config['vision_dagger']['maskrcnn_top_k_boxes'] - self.avg2dpool = torch.nn.AvgPool2d((13, 13)) - self.detector = load_pretrained_model(pretrained_model_path) - self.detector.roi_heads.register_forward_hook(self.box_features_hook) - self.detection_box_features = [] - self.fpn_pooled_features = [] - self.detector.eval() - if self.use_gpu: - self.detector.cuda() - elif self.vision_model_type in {"no_vision"}: - print("No Vision Agent") - else: - raise NotImplementedError() - - def box_features_hook(self, module, input, output): - ''' - hook for extracting features from MaskRCNN - ''' - - features, proposals, image_shapes, targets = input - - box_features = module.box_roi_pool(features, proposals, image_shapes) - box_features = module.box_head(box_features) - class_logits, box_regression = module.box_predictor(box_features) - - device = class_logits.device - num_classes = class_logits.shape[-1] - - boxes_per_image = [len(boxes_in_image) for boxes_in_image in proposals] - pred_boxes = module.box_coder.decode(box_regression, proposals) - - pred_scores = F.softmax(class_logits, -1) - - # split boxes and scores per image - pred_boxes = pred_boxes.split(boxes_per_image, 0) - pred_scores = pred_scores.split(boxes_per_image, 0) - - all_boxes = [] - all_scores = [] - all_labels = [] - all_keeps = [] - for boxes, scores, image_shape in zip(pred_boxes, pred_scores, image_shapes): - boxes = box_ops.clip_boxes_to_image(boxes, image_shape) - - # create labels for each prediction - labels = torch.arange(num_classes, device=device) - labels = labels.view(1, -1).expand_as(scores) - - # remove predictions with the background label - boxes = boxes[:, 1:] - scores = scores[:, 1:] - labels = labels[:, 1:] - - # batch everything, by making every class prediction be a separate instance - boxes = boxes.reshape(-1, 4) - scores = scores.flatten() - labels = labels.flatten() - - # remove low scoring boxes - inds = torch.nonzero(scores > module.score_thresh).squeeze(1) - boxes, scores, labels = boxes[inds], scores[inds], labels[inds] - - # remove empty boxes - keep = box_ops.remove_small_boxes(boxes, min_size=1e-2) - boxes, scores, labels = boxes[keep], scores[keep], labels[keep] - - # non-maximum suppression, independently done per class - keep = box_ops.batched_nms(boxes, scores, labels, module.nms_thresh) - # keep only topk scoring predictions - keep = keep[:self.mask_rcnn_top_k_boxes] - boxes, scores, labels = boxes[keep], scores[keep], labels[keep] - - all_boxes.append(boxes) - all_scores.append(scores) - all_labels.append(labels) - all_keeps.append(keep) - - box_features_per_image = [] - for keep in all_keeps: - box_features_per_image.append(box_features[keep]) - - self.detection_box_features = box_features_per_image - self.fpn_pooled_features = self.avg2dpool(features['pool']).squeeze(-1).squeeze(-1) - - # visual features for state representation - def extract_visual_features(self, images): - with torch.no_grad(): - if "resnet" in self.vision_model_type: - image_tensors = [self.transform(i).cuda() if self.use_gpu else self.transform() for i in images] - image_tensors = torch.stack(image_tensors, dim=0) - res_out = self.detector(image_tensors) - res_out_list = [res_out[i].unsqueeze(0) for i in range(res_out.shape[0])] - return res_out_list - elif "maskrcnn" in self.vision_model_type: - image_tensors = [self.transform(i).cuda() if self.use_gpu else self.transform(i) for i in images] - self.detector(image_tensors) # hook writes to self.detection_box_features - if "maskrcnn_whole" in self.vision_model_type: - return [i.unsqueeze(0) for i in self.fpn_pooled_features] - else: - return self.detection_box_features - elif "no_vision" in self.vision_model_type: - batch_size = len(images) - zeros = [torch.zeros((1, 1000)) for _ in range(batch_size)] - if self.use_gpu: - zeros = [z.cuda() for z in zeros] - return zeros - else: - raise NotImplementedError() - - # without recurrency - def train_dagger(self): - - if len(self.dagger_memory) < self.dagger_replay_batch_size: - return None - transitions = self.dagger_memory.sample(self.dagger_replay_batch_size) - if transitions is None: - return None - batch = memory.dagger_transition(*zip(*transitions)) - - if self.action_space == "generation": - return self.command_generation_teacher_force(batch.observation_list, batch.task_list, batch.target_list) - else: - raise NotImplementedError() - - # with recurrency - def train_dagger_recurrent(self): - - if len(self.dagger_memory) < self.dagger_replay_batch_size: - return None - sequence_of_transitions, contains_first_step = self.dagger_memory.sample_sequence(self.dagger_replay_batch_size, self.dagger_replay_sample_history_length) - if sequence_of_transitions is None: - return None - - batches = [] - for transitions in sequence_of_transitions: - batch = memory.dagger_transition(*zip(*transitions)) - batches.append(batch) - - if self.action_space == "generation": - return self.command_generation_recurrent_teacher_force([batch.observation_list for batch in batches], [batch.task_list for batch in batches], [batch.target_list for batch in batches], contains_first_step) - else: - raise NotImplementedError() - - def command_generation_teacher_force(self, observation_feats, task_desc_strings, target_strings): - input_target_strings = [" ".join(["[CLS]"] + item.split()) for item in target_strings] - output_target_strings = [" ".join(item.split() + ["[SEP]"]) for item in target_strings] - batch_size = len(observation_feats) - - aggregated_obs_feat = self.aggregate_feats_seq(observation_feats) - h_obs = self.online_net.vision_fc(aggregated_obs_feat) - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - h_td_mean = self.online_net.masked_mean(h_td, td_mask).unsqueeze(1) - h_obs = h_obs.to(h_td_mean.device) - vision_td = torch.cat((h_obs, h_td_mean), dim=1) # batch x k boxes x hi - vision_td_mask = torch.ones((batch_size, h_obs.shape[1]+h_td_mean.shape[1])).to(h_td_mean.device) - - input_target = self.get_word_input(input_target_strings) - ground_truth = self.get_word_input(output_target_strings) # batch x target_length - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.vision_decode(input_target, target_mask, vision_td, vision_td_mask, None) # batch x target_length x vocab - - batch_loss = NegativeLogLoss(pred * target_mask.unsqueeze(-1), ground_truth, target_mask, smoothing_eps=self.smoothing_eps) - loss = torch.mean(batch_loss) - - if loss is None: - return None, None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(pred), to_np(loss) - - def command_generation_recurrent_teacher_force(self, seq_observation_feats, seq_task_desc_strings, seq_target_strings, contains_first_step=False): - loss_list = [] - previous_dynamics = None - batch_size = len(seq_observation_feats[0]) - h_td, td_mask = self.encode(seq_task_desc_strings[0], use_model="online") - h_td_mean = self.online_net.masked_mean(h_td, td_mask).unsqueeze(1) - for step_no in range(self.dagger_replay_sample_history_length): - input_target_strings = [" ".join(["[CLS]"] + item.split()) for item in seq_target_strings[step_no]] - output_target_strings = [" ".join(item.split() + ["[SEP]"]) for item in seq_target_strings[step_no]] - - obs = [o.to(h_td.device) for o in seq_observation_feats[step_no]] - aggregated_obs_feat = self.aggregate_feats_seq(obs) - h_obs = self.online_net.vision_fc(aggregated_obs_feat) - vision_td = torch.cat((h_obs, h_td_mean), dim=1) # batch x k boxes x hid - vision_td_mask = torch.ones((batch_size, h_obs.shape[1]+h_td_mean.shape[1])).to(h_td_mean.device) - - averaged_vision_td_representation = self.online_net.masked_mean(vision_td, vision_td_mask) - current_dynamics = self.online_net.rnncell(averaged_vision_td_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_vision_td_representation) - - input_target = self.get_word_input(input_target_strings) - ground_truth = self.get_word_input(output_target_strings) # batch x target_length - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.vision_decode(input_target, target_mask, vision_td, vision_td_mask, current_dynamics) # batch x target_length x vocab - - previous_dynamics = current_dynamics - if (not contains_first_step) and step_no < self.dagger_replay_sample_update_from: - previous_dynamics = previous_dynamics.detach() - continue - - batch_loss = NegativeLogLoss(pred * target_mask.unsqueeze(-1), ground_truth, target_mask, smoothing_eps=self.smoothing_eps) - loss = torch.mean(batch_loss) - loss_list.append(loss) - - loss = torch.stack(loss_list).mean() - if loss is None: - return None - # Backpropagate - self.online_net.zero_grad() - self.optimizer.zero_grad() - loss.backward() - # `clip_grad_norm` helps prevent the exploding gradient problem in RNNs / LSTMs. - torch.nn.utils.clip_grad_norm_(self.online_net.parameters(), self.clip_grad_norm) - self.optimizer.step() # apply gradients - return to_np(loss) - - def command_generation_greedy_generation(self, observation_feats, task_desc_strings, previous_dynamics): - with torch.no_grad(): - batch_size = len(observation_feats) - - aggregated_obs_feat = self.aggregate_feats_seq(observation_feats) - h_obs = self.online_net.vision_fc(aggregated_obs_feat) - h_td, td_mask = self.encode(task_desc_strings, use_model="online") - h_td_mean = self.online_net.masked_mean(h_td, td_mask).unsqueeze(1) - h_obs = h_obs.to(h_td_mean.device) - vision_td = torch.cat((h_obs, h_td_mean), dim=1) # batch x k boxes x hid - vision_td_mask = torch.ones((batch_size, h_obs.shape[1]+h_td_mean.shape[1])).to(h_td_mean.device) - - if self.recurrent: - averaged_vision_td_representation = self.online_net.masked_mean(vision_td, vision_td_mask) - current_dynamics = self.online_net.rnncell(averaged_vision_td_representation, previous_dynamics) if previous_dynamics is not None else self.online_net.rnncell(averaged_vision_td_representation) - else: - current_dynamics = None - - # greedy generation - input_target_list = [[self.word2id["[CLS]"]] for i in range(batch_size)] - eos = np.zeros(batch_size) - for _ in range(self.max_target_length): - - input_target = copy.deepcopy(input_target_list) - input_target = pad_sequences(input_target, maxlen=max_len(input_target)).astype('int32') - input_target = to_pt(input_target, self.use_cuda) - target_mask = compute_mask(input_target) # mask of ground truth should be the same - pred = self.online_net.vision_decode(input_target, target_mask, vision_td, vision_td_mask, current_dynamics) # batch x target_length x vocab - # pointer softmax - pred = to_np(pred[:, -1]) # batch x vocab - pred = np.argmax(pred, -1) # batch - for b in range(batch_size): - new_stuff = [pred[b]] if eos[b] == 0 else [] - input_target_list[b] = input_target_list[b] + new_stuff - if pred[b] == self.word2id["[SEP]"]: - eos[b] = 1 - if np.sum(eos) == batch_size: - break - res = [self.tokenizer.decode(item) for item in input_target_list] - res = [item.replace("[CLS]", "").replace("[SEP]", "").strip() for item in res] - res = [item.replace(" in / on ", " in/on " ) for item in res] - return res, current_dynamics - - def get_vision_feat_mask(self, observation_feats): - batch_size = len(observation_feats) - num_vision_feats = [of.shape[0] for of in observation_feats] - max_feat_len = max(num_vision_feats) - mask = torch.zeros((batch_size, max_feat_len)) - for b, num_vision_feat in enumerate(num_vision_feats): - mask[b,:num_vision_feat] = 1 - return mask - - def extract_exploration_frame_feats(self, exploration_frames): - exploration_frame_feats = [] - for batch in exploration_frames: - ef_feats = [] - for image in batch: - ef_feats.append(self.extract_visual_features([image])[0]) - # cat_feats = torch.cat(ef_feats, dim=0) - max_feat_len = max([f.shape[0] for f in ef_feats]) - stacked_feats = self.online_net.vision_fc.pad_and_stack(ef_feats, max_feat_len=max_feat_len) - stacked_feats = stacked_feats.view(-1, self.online_net.vision_fc.in_features) - exploration_frame_feats.append(stacked_feats) - return exploration_frame_feats - - def aggregate_feats_seq(self, feats): - if self.sequence_aggregation_method == "sum": - return [f.sum(0).unsqueeze(0) for f in feats] - elif self.sequence_aggregation_method == "average": - return [f.mean(0).unsqueeze(0) for f in feats] - elif self.sequence_aggregation_method == "rnn": - max_feat_len = max([f.shape[0] for f in feats]) - feats_stack = self.online_net.vision_fc.pad_and_stack(feats, max_feat_len=max_feat_len) - feats_h, feats_c = self.online_net.vision_feat_seq_rnn(feats_stack) - aggregated_feats = feats_h[:,0,:].unsqueeze(1) - return [b for b in aggregated_feats] - else: - raise ValueError("sequence_aggregation_method must be sum, average or rnn") diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/config/rewards.json b/agent_system/environments/env_package/alfworld/alfworld/agents/config/rewards.json deleted file mode 100644 index e9f35e7b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/config/rewards.json +++ /dev/null @@ -1,87 +0,0 @@ -{ - "Generic": - { - "success": 2, - "failure": -0.05, - "step_penalty": -0.01, - "goal_reward": 5 - }, - "BaseAction": - { - "positive": 1, - "negative": 0, - "neutral": 0, - "invalid_action": -0.1 - }, - "GotoLocationAction": - { - "positive": 4, - "negative": 0, - "neutral": 0, - "invalid_action": -0.5, - "min_reach_distance": 3 - }, - "PickupObjectAction": - { - "positive": 2, - "negative": -1, - "neutral": 0, - "invalid_action": -0.1 - }, - "PutObjectAction": - { - "positive": 2, - "negative": -1, - "neutral": 0, - "invalid_action": -0.1 - }, - "OpenObjectAction": - { - "positive": 2, - "negative": -0.05, - "neutral": 0, - "invalid_action": -0.1 - }, - "CloseObjectAction": - { - "positive": 1, - "negative": 0, - "neutral": 0, - "invalid_action": -0.1 - }, - "ToggleObjectAction": - { - "positive": 1, - "negative": -1, - "neutral": 0, - "invalid_action": -0.1 - }, - "SliceObjectAction": - { - "positive": 1, - "negative": -4, - "neutral": 0, - "invalid_action": -0.1 - }, - "CleanObjectAction": - { - "positive": 2, - "negative": 0, - "neutral": 0, - "invalid_action": -0.1 - }, - "HeatObjectAction": - { - "positive": 2, - "negative": 0, - "neutral": 0, - "invalid_action": -0.1 - }, - "CoolObjectAction": - { - "positive": 2, - "negative": 0, - "neutral": 0, - "invalid_action": -0.1 - } -} \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/__init__.py deleted file mode 100644 index e59ba28b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/__init__.py +++ /dev/null @@ -1,4 +0,0 @@ -from alfworld.agents.controller.oracle import OracleAgent -from alfworld.agents.controller.oracle_astar import OracleAStarAgent -from alfworld.agents.controller.mrcnn import MaskRCNNAgent -from alfworld.agents.controller.mrcnn_astar import MaskRCNNAStarAgent \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/base.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/base.py deleted file mode 100644 index a1e6e6ed..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/base.py +++ /dev/null @@ -1,231 +0,0 @@ -import os -import sys -import json - -import copy -import random -import alfworld.gen.constants as constants -from alfworld.gen.utils.image_util import compress_mask, decompress_mask -from alfworld.agents.utils.misc import get_templated_task_desc, get_human_anns_task_desc, NumpyArrayEncoder -from enum import Enum - -class BaseAgent(object): - ''' - Base class for controllers - ''' - - # constants - RECEPTACLES = set(constants.RECEPTACLES) | {'Sink', 'Bathtub'} - OBJECTS = (set(constants.OBJECTS_WSLICED) - set(RECEPTACLES)) | set(constants.MOVABLE_RECEPTACLES) - OBJECTS -= {'Blinds', 'Boots', 'Cart', 'Chair', 'Curtains', 'Footstool', 'Mirror', 'LightSwtich', 'Painting', 'Poster', 'ShowerGlass', 'Window'} - STATIC_RECEPTACLES = set(RECEPTACLES) - set(constants.MOVABLE_RECEPTACLES) - - # action enum - class Action(Enum): - PASS = 0, - GOTO = 1, - PICK = 2, - PUT = 3, - OPEN = 4, - CLOSE = 5, - TOGGLE = 6, - HEAT = 7, - CLEAN = 8, - COOL = 9, - SLICE = 10, - INVENTORY = 11, - EXAMINE = 12, - LOOK = 13 - - def __init__(self, env, traj_data, traj_root, - load_receps=False, debug=False, - goal_desc_human_anns_prob=0.0, - recep_filename='receps.json', exhaustive_exploration=False): - self.env = env - self.traj_data = traj_data - self.debug = debug - self.traj_root = traj_root - self.load_receps = load_receps - self.recep_file = os.path.join(traj_root, recep_filename) - self.objects = {} - self.receptacles = {} - self.visible_objects = [] - self.exhaustive_exploration = exhaustive_exploration - self.goal_desc_human_anns_prob = goal_desc_human_anns_prob - - self.feedback = "" - self.curr_loc = {'action': "Pass"} - self.curr_recep = "nothing" - self.inventory = [] - self.intro = "" - self.frame_desc = "" - - self.init_scene(load_receps) - self.setup_navigator() - self.print_intro() - - # explore the scene to build receptacle map - def init_scene(self, load_receps): - if load_receps and os.path.isfile(self.recep_file): - with open(self.recep_file, 'r') as f: - self.receptacles = json.load(f) - for recep_id, recep in self.receptacles.items(): - if 'mask' in recep: - recep['mask'] = decompress_mask(recep['mask']) - else: - self.receptacles = {} - if self.exhaustive_exploration: - self.explore_scene_exhaustively() - else: - self.explore_scene() - - def get_object(self, name, obj_dict): - for id, obj in obj_dict.items(): - if obj['num_id'] == name: - return obj - return None - - def get_next_num_id(self, object_type, obj_dict): - return len([obj for _, obj in obj_dict.items() if obj['object_type'] == object_type]) + 1 - - def fix_and_comma_in_the_end(self, desc): - sc = desc.split(",") - if len(sc) > 2: - return ",".join(sc[:-2]) + ", and%s." % sc[-2] - elif len(sc) == 2: - return desc.rstrip(",") + "." - else: - return desc - - def explore_scene(self): - raise NotImplementedError() - - def explore_scene_exhaustively(self): - raise NotImplementedError() - - def get_admissible_commands(self): - raise NotImplementedError() - - def get_instance_seg(self): - raise NotImplementedError() - - def get_object_state(self, object_id): - raise NotImplementedError() - - # dump receptacle map to disk - def save_receps(self): - receptacles = copy.deepcopy(self.receptacles) - for recep_id, recep in receptacles.items(): - if 'mask' in recep: - recep['mask'] = compress_mask(recep['mask']) - with open(self.recep_file, 'w') as f: - json.dump(receptacles, f) #, cls=NumpyArrayEncoder) - - # display initial observation and task text - def print_intro(self): - self.feedback = "-= Welcome to TextWorld, ALFRED! =-\n\nYou are in the middle of a room. Looking quickly around you, you see " - recep_list = ["a %s," % (recep['num_id']) for id, recep in self.receptacles.items()] - self.feedback += self.fix_and_comma_in_the_end(" ".join(recep_list)) + "\n\n" - - if random.random() < self.goal_desc_human_anns_prob: - task = get_human_anns_task_desc(self.traj_data) - else: - task = get_templated_task_desc(self.traj_data) - - self.feedback += "Your task is to: %s" % task - - self.intro = str(self.feedback) - - # choose between different navigator available - def setup_navigator(self): - self.navigator = self.env # by default, directly teleport with THOR API - - def print_frame(self, recep, loc): - raise NotImplementedError() - - # display properties of an object - def print_object(self, object): - object_id, object_name = object['object_id'], object['num_id'] - - is_clean, is_cool, is_hot, is_sliced = self.get_object_state(object_id) - - # by default, nothing interesting about the object - feedback = "This is a normal %s" % object_name - - sliced_str = "sliced " if is_sliced else "" - if is_hot and is_cool and is_clean: - feedback = "This is a hot/cold and clean %s%s." % (sliced_str, object_name) # TODO: weird? - elif is_hot and is_clean: - feedback = "This is a hot and clean %s%s." % (sliced_str, object_name) - elif is_cool and is_clean: - feedback = "This is a cool and clean %s%s." % (sliced_str, object_name) - elif is_hot and is_cool: - feedback = "This is a hot/cold %s%s." % (sliced_str, object_name) - elif is_clean: - feedback = "This is a clean %s%s." % (sliced_str, object_name) - elif is_hot: - feedback = "This is a hot %s%s." % (sliced_str, object_name) - elif is_cool: - feedback = "This is a cool %s%s." % (sliced_str, object_name) - - return feedback - - # command parser - def parse_command(self, action_str): - - def get_triplet(astr, key): - astr = astr.replace(key, "").split() - obj, rel, tar = ' '.join(astr[:2]), astr[2], ' '.join(astr[-2:]) - return obj, rel, tar - - action_str = str(action_str).lower().strip() - - if "go to " in action_str: - tar = action_str.replace("go to ", "") - return {'action': self.Action.GOTO, 'tar': tar} - elif "take " in action_str: - obj, rel, tar = get_triplet(action_str, "take ") - return {'action': self.Action.PICK, 'obj': obj, 'rel': rel, 'tar': tar} - elif "put " in action_str: - obj, rel, tar = get_triplet(action_str, "put ") - return {'action': self.Action.PUT, 'obj': obj, 'rel': rel, 'tar': tar} - elif "open " in action_str: - tar = action_str.replace("open ", "") - return {'action': self.Action.OPEN, 'tar': tar} - elif "close " in action_str: - tar = action_str.replace("close ", "") - return {'action': self.Action.CLOSE, 'tar': tar} - elif "use " in action_str: - tar = action_str.replace("use ", "") - return {'action': self.Action.TOGGLE, 'tar': tar} - elif "heat " in action_str: - obj, rel, tar = get_triplet(action_str, "heat ") - return {'action': self.Action.HEAT, 'obj': obj, 'rel': rel, 'tar': tar} - elif "cool " in action_str: - obj, rel, tar = get_triplet(action_str, "cool ") - return {'action': self.Action.COOL, 'obj': obj, 'rel': rel, 'tar': tar} - elif "clean " in action_str: - obj, rel, tar = get_triplet(action_str, "clean ") - return {'action': self.Action.CLEAN, 'obj': obj, 'rel': rel, 'tar': tar} - elif "slice " in action_str: - obj, rel, tar = get_triplet(action_str, "slice ") - return {'action': self.Action.SLICE, 'obj': obj, 'rel': rel, 'tar': tar} - elif "inventory" in action_str: - return {'action': self.Action.INVENTORY} - elif "examine " in action_str: - tar = action_str.replace("examine ", "") - return {'action': self.Action.EXAMINE, 'tar': tar} - elif "look" in action_str: - return {'action': self.Action.LOOK} - else: - return {'action': self.Action.PASS} - - def navigate(self, teleport_loc): - return self.navigator.step(teleport_loc) - - def step(self, action_str): - self.feedback = "Nothing happens." - return self.feedback - - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn.py deleted file mode 100644 index 34066faf..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn.py +++ /dev/null @@ -1,557 +0,0 @@ -############ -# Reference: https://haochen23.github.io/2020/05/instance-segmentation-mask-rcnn.html#.XyiLqfhKg40 - -import os -import cv2 -import sys -import json -import re -import copy -import random -import traceback -from collections import Counter - -from PIL import Image -import numpy as np - -import alfworld.gen -import alfworld.gen.constants as constants - -from alfworld.agents.controller.base import BaseAgent -from alfworld.agents.utils.misc import extract_admissible_commands_with_heuristics - -try: - import torchvision.transforms as T -except ImportError: - raise ImportError("torchvision not found. Please install them via `pip install alfworld[full]`.") - -class MaskRCNNAgent(BaseAgent): - - def __init__(self, env, traj_data, traj_root, - pretrained_model=None, - load_receps=False, debug=False, - goal_desc_human_anns_prob=0.0, - classes=constants.OBJECTS_DETECTOR, - save_detections_to_disk=False, save_detections_path='./'): - - self.openable_points = self.get_openable_points(traj_data) - - # pre-trained MaskRCNN model - assert pretrained_model - self.mask_rcnn = pretrained_model - self.mask_rcnn.eval() - self.mask_rcnn.cuda() - self.transform = T.Compose([T.ToTensor()]) - self.classes = classes - - # object state tracking - self.cleaned_objects = set() - self.cooled_objects = set() - self.heated_objects = set() - - # recording settings - self.save_detections_to_disk = save_detections_to_disk - self.save_detections_path = save_detections_path - - super().__init__(env, traj_data, traj_root, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=goal_desc_human_anns_prob, - recep_filename='receps_mrcnn.json', exhaustive_exploration=False) - - def get_openable_points(self, traj_data): - scene_num = traj_data['scene']['scene_num'] - openable_json_file = os.path.join(alfworld.gen.__path__[0], 'layouts/FloorPlan%d-openable.json' % scene_num) - with open(openable_json_file, 'r') as f: - openable_points = json.load(f) - return openable_points - - # use pre-computed openable points from ALFRED to store receptacle locations - def explore_scene(self): - agent_height = self.env.last_event.metadata['agent']['position']['y'] - for object_id, point in self.openable_points.items(): - action = {'action': 'TeleportFull', - 'x': point[0], - 'y': agent_height, - 'z': point[1], - 'rotateOnTeleport': False, - 'rotation': point[2], - 'horizon': point[3]} - event = self.env.step(action) - - if event and event.metadata['lastActionSuccess']: - instance_segs = np.array(self.env.last_event.instance_segmentation_frame) - color_to_object_id = self.env.last_event.color_to_object_id - - # find unique instance segs - color_count = Counter() - for x in range(instance_segs.shape[0]): - for y in range(instance_segs.shape[1]): - color = instance_segs[x, y] - color_count[tuple(color)] += 1 - - for color, num_pixels in color_count.most_common(): - if color in color_to_object_id: - object_id = color_to_object_id[color] - object_type = object_id.split('|')[0] - if "Basin" in object_id: - object_type += "Basin" - - if object_type in self.STATIC_RECEPTACLES: - if object_id not in self.receptacles: - self.receptacles[object_id] = { - 'object_id': object_id, - 'object_type': object_type, - 'locs': action, - 'num_pixels': num_pixels, - 'mask': np.array(np.all(instance_segs == np.array(color), axis=-1), dtype=int), - 'num_id': "%s %d" % (object_type.lower(), self.get_next_num_id(object_type, self.receptacles)), - 'closed': True if object_type in constants.OPENABLE_CLASS_LIST else None - } - elif object_id in self.receptacles and num_pixels > self.receptacles[object_id]['num_pixels']: - self.receptacles[object_id]['locs'] = action # .append(action) - self.receptacles[object_id]['num_pixels'] = num_pixels - - # self.save_receps() - - # explore each scene exhaustively with grid-search - def explore_scene_exhaustively(self): - event = self.env.step(dict(action='GetReachablePositions', - gridSize=constants.AGENT_STEP_SIZE)) - - reachable_points = set() - for point in event.metadata['actionReturn']: - reachable_points.add((point['x'], point['z'])) - - agent_height = event.metadata['agent']['position']['y'] - - # teleport to points - for p_idx, point in enumerate(reachable_points): - if (p_idx+1) % 10 == 0: - print("Checking %d/%d..." % (p_idx+1, len(reachable_points))) - - action = {'action': 'TeleportFull', - 'x': point[0], - 'y': agent_height, - 'z': point[1]} - event = self.env.step(action) - - # look up and down - if event and event.metadata['lastActionSuccess']: - for horizon in [-30, 0, 30]: - action = {'action': 'TeleportFull', - 'x': point[0], - 'y': agent_height, - 'z': point[1], - 'rotateOnTeleport': True, - 'rotation': 0, - 'horizon': horizon} - event = self.env.step(action) - - # look around - if event and event.metadata['lastActionSuccess']: - for r in range(4): - rotation = 90 * r - action = {'action': 'TeleportFull', - 'x': point[0], - 'y': agent_height, - 'z': point[1], - 'rotateOnTeleport': True, - 'rotation': rotation, - 'horizon': horizon} - event = self.env.step(action) - - if event and event.metadata['lastActionSuccess']: - masks, boxes, pred_cls = self.get_instance_seg() - - for i in range(len(masks)): - object_id = "{}|{}".format(pred_cls[i], str(boxes[i])) - object_type = object_id.split('|')[0] - num_pixels = len(masks[i].nonzero()[0]) - if "Basin" in object_id: - object_type += "Basin" - if object_type in self.STATIC_RECEPTACLES: # and object_type == recep_class: - recep_id = object_id - if recep_id not in self.receptacles: - self.receptacles[recep_id] = { - 'object_id': recep_id, - 'object_type': object_type, - 'locs': action, - 'mask': masks[i] if masks[i].shape == (300, 300) else np.ones((300, 300)), - 'num_pixels': num_pixels, - 'num_id': "%s %d" % (object_type.lower(), self.get_next_num_id(object_type, self.receptacles)), - 'closed': True if object_type in constants.OPENABLE_CLASS_LIST else None - } - elif recep_id in self.receptacles and num_pixels > self.receptacles[recep_id]['num_pixels']: - self.receptacles[recep_id]['locs'] = action # .append(action) - self.receptacles[recep_id]['num_pixels'] = num_pixels - - # self.save_receps() - - # display a list of visible objects - def print_frame(self, recep, loc): - visible_objects = self.update_detection(recep, loc) - - visible_objects_with_articles = ["a %s," % vo for vo in visible_objects] - feedback = "" - if len(visible_objects) > 0: - feedback = "On the %s, you see %s" % (recep['num_id'], self.fix_and_comma_in_the_end(' '.join(visible_objects_with_articles))) - elif not recep['closed'] and len(visible_objects) == 0: - feedback = "On the %s, you see nothing." % (recep['num_id']) - - return visible_objects, feedback - - def update_detection(self, recep, loc): - masks, boxes, pred_cls = self.get_instance_seg() - # for each unique seg add to object dictionary if it's more visible than before - visible_objects = [] - self.objects = {} - for i in range(len(masks)): - object_id = "{}|{}".format(pred_cls[i], str(boxes[i])) - object_type = pred_cls[i] - num_pixels = len(masks[i].nonzero()[0]) - if object_type in self.OBJECTS: - if object_id not in self.objects: - num_id = "%s %d" % ( - object_type.lower() if "Sliced" not in object_id else "sliced-%s" % object_type.lower(), - self.get_next_num_id(object_type, self.objects)) - self.objects[object_id] = { - 'object_id': object_id, - 'object_type': object_type, - 'parent': recep['object_id'], - 'loc': loc, - 'mask': masks[i], - 'num_pixels': num_pixels, - 'num_id': num_id - } - elif object_id in self.objects and num_pixels > self.objects[object_id]['num_pixels']: - self.objects[object_id]['loc'] = loc - self.objects[object_id]['mask'] = masks[i] - self.objects[object_id]['num_pixels'] = num_pixels - - if self.objects[object_id]['num_id'] not in self.inventory: - visible_objects.append(self.objects[object_id]['num_id']) - return visible_objects - - def update_gt_receptacle_mask(self, recep): - instance_segs = self.env.last_event.instance_segmentation_frame - object_id_to_color = self.env.last_event.object_id_to_color - recep_id = recep['object_id'] - if recep_id in object_id_to_color: - recep_instance_color = object_id_to_color[recep_id] - recep['mask'] = np.array(np.all(instance_segs == np.array(recep_instance_color), axis=-1), dtype=int) - - def get_most_visible_object_of_type(self, otype, obj_dict): - max_pixels, best_view_obj = 0, None - for id, obj in obj_dict.items(): - if otype in obj['object_type'].lower(): - if obj['num_pixels'] > max_pixels: - best_view_obj = obj - max_pixels = obj['num_pixels'] - return best_view_obj - - def get_object_of_num_id(self, onum, obj_dict): - obj = None - for id, o in obj_dict.items(): - if onum == o['num_id']: - return o - return obj - - def get_coloured_mask(self, mask): - """ - random_colour_masks - parameters: - - image - predicted masks - method: - - the masks of each predicted object is given random colour for visualization - """ - colours = [[0, 255, 0],[0, 0, 255],[255, 0, 0],[0, 255, 255],[255, 255, 0],[255, 0, 255],[80, 70, 180],[250, 80, 190],[245, 145, 50],[70, 150, 250],[50, 190, 190]] - r = np.zeros_like(mask).astype(np.uint8) - g = np.zeros_like(mask).astype(np.uint8) - b = np.zeros_like(mask).astype(np.uint8) - r[mask == 1], g[mask == 1], b[mask == 1] = colours[random.randrange(0,10)] - coloured_mask = np.stack([r, g, b], axis=2) - return coloured_mask - - def get_maskrcnn_prediction(self, frame, confidence): - """ - get_prediction - parameters: - - img_path - path of the input image - - confidence - threshold to keep the prediction or not - method: - - Image is obtained from the image path - - the image is converted to image tensor using PyTorch's Transforms - - image is passed through the model to get the predictions - - masks, classes and bounding boxes are obtained from the model and soft masks are made binary(0 or 1) on masks - ie: eg. segment of cat is made 1 and rest of the image is made 0 - - """ - img = Image.fromarray(frame) - img = self.transform(img).cuda() - pred = self.mask_rcnn([img]) - pred_score = list(pred[0]['scores'].detach().cpu().numpy()) - pred_pruned = [pred_score.index(x) for x in pred_score if x>confidence] - - if len(pred_pruned) > 0: - pred_t = pred_pruned[-1] - masks = (pred[0]['masks']>0.5).squeeze().detach().cpu().numpy() - pred_class = [self.classes[i] for i in list(pred[0]['labels'].detach().cpu().numpy())] - pred_boxes = [[(i[0], i[1]), (i[2], i[3])] for i in list(pred[0]['boxes'].detach().cpu().numpy())] - masks = masks[:pred_t+1] - pred_boxes = pred_boxes[:pred_t+1] if len(pred_pruned) > 1 else pred_boxes - pred_class = pred_class[:pred_t+1] if len(pred_pruned) > 1 else pred_class - return masks, pred_boxes, pred_class - else: - return [], [], [] - - def get_instance_seg(self): - ''' - Ground-truth instance segemetations (with consistent object IDs) from THOR - ''' - - frame = self.env.last_event.frame[:,:,::-1] - masks, boxes, pred_cls = self.get_maskrcnn_prediction(frame, confidence=0.5) # TODO: add confidence to config file - - # visualize detections - if self.debug: - img = copy.deepcopy(frame) - for i in range(len(masks)): - rgb_mask = self.get_coloured_mask(masks[i]) - if rgb_mask.shape == img.shape: - img = cv2.addWeighted(img, 1, rgb_mask, 0.5, 0) - cv2.rectangle(img, boxes[i][0], boxes[i][1],color=(0, 255, 0), thickness=2) - cv2.putText(img, pred_cls[i], boxes[i][0], cv2.FONT_HERSHEY_SIMPLEX, 1, (0,255,0),thickness=2) - - cv2.imshow("MaskRCNN", img) - cv2.waitKey(1) - - if self.save_detections_to_disk: - if not os.path.exists(self.save_detections_path): - os.makedirs(self.save_detections_path) - for _ in range(10): # save 10 frames - img_idx = len(glob.glob(self.save_detections_path + '/*.png')) - cv2.imwrite(self.save_detections_path + '/%09d.png' % img_idx, img) - - return masks, boxes, pred_cls - - def get_object_state(self, object_id): - is_clean = object_id in self.cleaned_objects - is_hot = object_id in self.heated_objects - is_cool = object_id in self.cooled_objects - is_sliced = 'Sliced' in object_id - return is_clean, is_cool, is_hot, is_sliced - - def get_admissible_commands(self): - return extract_admissible_commands_with_heuristics(self.intro, self.frame_desc, self.feedback, - self.curr_recep, self.inventory) - - def interact(self, action, object_name): - # exception: pass actions - if action == 'Pass': - self.env.va_interact(action=action) - return self.env.last_event, None - - # extract context - object_type = object_name.split()[0] - recep, loc = self.get_object(self.curr_recep, self.receptacles), self.curr_loc - - # update MaskRCNN detections - _ = self.update_detection(recep, self.curr_loc) - self.update_gt_receptacle_mask(recep) - - # choose which dictionary to look at - recep_classes = [c.lower() for c in list(self.STATIC_RECEPTACLES)] - obj_dict = self.receptacles if object_type in recep_classes else self.objects - - # find the object with specific num id, if not, then find some object of same class - tar_object = self.get_object_of_num_id(object_name, obj_dict) - if not tar_object: - tar_object = self.get_most_visible_object_of_type(object_type, obj_dict) - - # use va_interact with ThorEnv - _, event, _, _, _ = self.env.va_interact(action=action, interact_mask=tar_object['mask']) - - return event, tar_object - - def step(self, action_str): - - event = None - self.feedback = "Nothing happens." - - try: - cmd = self.parse_command(action_str) - - if cmd['action'] == self.Action.GOTO: - target = cmd['tar'] - recep = self.get_object(target, self.receptacles) - if recep and recep['num_id'] == self.curr_recep: - return self.feedback - self.curr_loc = recep['locs'] - event = self.navigate(self.curr_loc) - self.curr_recep = target - self.visible_objects, self.feedback = self.print_frame(recep, self.curr_loc) - - # feedback conditions - if event and event.metadata['lastActionSuccess']: - loc_id = list(self.receptacles.keys()).index(recep['object_id']) - loc_feedback = "You arrive at loc %s. " % (loc_id) - state_feedback = "The {} is {}. ".format(self.curr_recep, "closed" if recep['closed'] else "open") if recep['closed'] is not None else "" - loc_state_feedback = loc_feedback + state_feedback - self.feedback = loc_state_feedback + self.feedback if "closed" not in state_feedback else loc_state_feedback - self.frame_desc = str(self.feedback) - - elif cmd['action'] == self.Action.PICK: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - if obj in self.visible_objects: - event, object = self.interact('PickupObject', obj) - if event and event.metadata['lastActionSuccess']: - self.inventory.append(object['num_id']) - self.feedback = "You pick up the %s from the %s." % (obj, tar) - - elif cmd['action'] == self.Action.PUT: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - event, recep = self.interact('PutObject', tar) - if event and event.metadata['lastActionSuccess']: - self.inventory.pop() - self.feedback = "You put the %s %s %s." % (obj, rel, tar) - - elif cmd['action'] == self.Action.OPEN: - target = cmd['tar'] - event, recep = self.interact('OpenObject', target) - if event and event.metadata['lastActionSuccess']: - self.receptacles[recep['object_id']]['closed'] = False - self.visible_objects, self.feedback = self.print_frame(recep, self.curr_loc) - action_feedback = "You open the %s. " % target - self.feedback = action_feedback + self.feedback - self.frame_desc = str(self.feedback) - - elif cmd['action'] == self.Action.CLOSE: - target = cmd['tar'] - event, recep = self.interact('CloseObject', target) - if event and event.metadata['lastActionSuccess']: - self.receptacles[recep['object_id']]['closed'] = True - self.feedback = "You close the %s." % target - _ = self.update_detection(recep, self.curr_loc) - - elif cmd['action'] == self.Action.TOGGLE: - target = cmd['tar'] - event, object = self.interact('ToggleObjectOn', target) - if event and event.metadata['lastActionSuccess']: - self.feedback = "The %s is on." % object['num_id'] - - elif cmd['action'] == self.Action.HEAT: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - - # open the microwave, heat the object, take the object, close the microwave - events = [] - event, microwave = self.interact('OpenObject', tar) - events.append(event) - event, microwave = self.interact('PutObject', tar) - events.append(event) - event, microwave = self.interact('CloseObject', tar) - events.append(event) - event, microwave = self.interact('ToggleObjectOn', tar) - events.append(event) - event, _ = self.interact('Pass', "") - events.append(event) - event, microwave = self.interact('ToggleObjectOff', tar) - events.append(event) - event, microwave = self.interact('OpenObject', tar) - events.append(event) - event, object = self.interact('PickupObject', obj) - events.append(event) - event, microwave = self.interact('CloseObject', tar) - events.append(event) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.heated_objects.add(object['object_id']) - self.feedback = "You heat the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.CLEAN: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - - # put the object in the sink, turn on the faucet, turn off the faucet, pickup the object - events = [] - event, sink = self.interact('PutObject', tar) - events.append(event) - event, faucet = self.interact('ToggleObjectOn', 'faucet') - events.append(event) - event, _ = self.interact('Pass', '') - events.append(event) - event, faucet = self.interact('ToggleObjectOff', 'faucet') - events.append(event) - event, object = self.interact('PickupObject', obj) - events.append(event) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.cleaned_objects.add(object['object_id']) - self.feedback = "You clean the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.COOL: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - - # open the fridge, put the object inside, close the fridge, open the fridge, pickup the object - events = [] - event, fridge = self.interact('OpenObject', 'fridge') - events.append(event) - event, fridge = self.interact('PutObject', 'fridge') - events.append(event) - event, fridge = self.interact('CloseObject', 'fridge') - events.append(event) - event, _ = self.interact('Pass', '') - events.append(event) - event, fridge = self.interact('OpenObject', 'fridge') - events.append(event) - event, object = self.interact('PickupObject', obj) - events.append(event) - event, fridge = self.interact('CloseObject', 'fridge') - events.append(event) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.cooled_objects.add(object['object_id']) - self.feedback = "You cool the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.SLICE: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - if len(self.inventory) > 0 and 'knife' in self.inventory[0]: - event, object = self.interact('SliceObject', obj) - if event and event.metadata['lastActionSuccess']: - self.feedback = "You slice %s with the %s" % (obj, tar) - - elif cmd['action'] == self.Action.INVENTORY: - if len(self.inventory) > 0: - self.feedback = "You are carrying: %s" % (self.inventory[0]) - else: - self.feedback = "You are not carrying anything." - - elif cmd['action'] == self.Action.EXAMINE: - target = cmd['tar'] - receptacle = self.get_object(target, self.receptacles) - object = self.get_object(target, self.objects) - - if receptacle: - self.visible_objects, self.feedback = self.print_frame(receptacle, self.curr_loc) - self.frame_desc = str(self.feedback) - elif object: - self.feedback = self.print_object(object) - - elif cmd['action'] == self.Action.LOOK: - if self.curr_recep == "nothing": - self.feedback = "You are in the middle of a room. Looking quickly around you, you see nothing." - else: - self.feedback = "You are facing the %s. Next to it, you see nothing." % self.curr_recep - - except: - if self.debug: - print(traceback.format_exc()) - - if event and not event.metadata['lastActionSuccess']: - self.feedback = "Nothing happens." - - if self.debug: - print(self.feedback) - return self.feedback - - - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn_astar.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn_astar.py deleted file mode 100644 index 9015bc97..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/mrcnn_astar.py +++ /dev/null @@ -1,56 +0,0 @@ -import json -import os -import alfworld.gen -import alfworld.gen.constants as constants -from alfworld.gen.game_states.task_game_state_full_knowledge import TaskGameStateFullKnowledge -from alfworld.gen.agents.deterministic_planner_agent import DeterministicPlannerAgent -from alfworld.gen.graph import graph_obj -from alfworld.agents.controller.mrcnn import MaskRCNNAgent - -class MaskRCNNAStarAgent(MaskRCNNAgent): - - def __init__(self, env, traj_data, traj_root, - pretrained_model=None, - load_receps=False, debug=False, - goal_desc_human_anns_prob=0.0, - classes=constants.OBJECTS_DETECTOR, - save_detections_to_disk=False, save_detections_path='./'): - - super().__init__(env, traj_data, traj_root, - pretrained_model=pretrained_model, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=goal_desc_human_anns_prob, - classes=classes, - save_detections_to_disk=save_detections_to_disk, save_detections_path=save_detections_path) - - def setup_navigator(self): - game_state = TaskGameStateFullKnowledge(self.env) - - # reset - game_state.receptacle_to_point = None - game_state.task_target = None - game_state.success = False - - # load nav graph - scene_num = self.traj_data['scene']['scene_num'] - game_state.gt_graph = graph_obj.Graph(use_gt=True, construct_graph=True, scene_id=scene_num) - game_state.gt_graph.clear() - - game_state.agent_height = self.env.last_event.metadata['agent']['position']['y'] - game_state.camera_height = game_state.agent_height + constants.CAMERA_HEIGHT_OFFSET - - points_source = os.path.join(alfworld.gen.__path__[0], 'layouts/FloorPlan%s-openable.json' % scene_num) - with open(points_source, 'r') as f: - openable_object_to_point = json.load(f) - game_state.openable_object_to_point = openable_object_to_point - - game_state.update_receptacle_nearest_points() # TODO: save to desk - game_state.planner.process_pool.terminate() - - self.navigator = DeterministicPlannerAgent(thread_id=0, game_state=game_state) - - - def navigate(self, teleport_loc): - self.navigator.pose = self.env.last_event.pose_discrete - self.navigator.step(teleport_loc) - return self.env.last_event \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle.py deleted file mode 100644 index 3865c697..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle.py +++ /dev/null @@ -1,340 +0,0 @@ -import os -import cv2 -import sys -import json -import re -import random -import traceback - -import numpy as np -from collections import Counter - -import alfworld.gen -import alfworld.gen.constants as constants -from alfworld.agents.controller.base import BaseAgent -from alfworld.agents.utils.misc import extract_admissible_commands_with_heuristics - - -class OracleAgent(BaseAgent): - - def __init__(self, env, traj_data, traj_root, - load_receps=False, debug=False, - goal_desc_human_anns_prob=0.0, - use_gt_relations=False): - self.openable_points = self.get_openable_points(traj_data) - self.use_gt_relations = use_gt_relations - self.exploration_frames = [] - super().__init__(env, traj_data, traj_root, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=goal_desc_human_anns_prob) - - def get_openable_points(self, traj_data): - scene_num = traj_data['scene']['scene_num'] - openable_json_file = os.path.join(alfworld.gen.__path__[0], 'layouts/FloorPlan%d-openable.json' % scene_num) - with open(openable_json_file, 'r') as f: - openable_points = json.load(f) - return openable_points - - def get_obj_cls_from_metadata(self, name): - objs = [obj for obj in self.env.last_event.metadata['objects'] if obj['visible'] and name in obj['objectType']] - return objs[0] if len(objs) > 0 else None - - def get_obj_id_from_metadata(self, object_id): - objs = [obj for obj in self.env.last_event.metadata['objects'] if object_id == obj['objectId']] - return objs[0] if len(objs) > 0 else None - - def get_num_interactable_objs(self, recep_id): - return len([obj for obj in self.env.last_event.metadata['objects'] if obj['visible'] and obj['parentReceptacles'] and recep_id in obj['parentReceptacles']]) - - def get_exploration_frames(self): - return self.exploration_frames - - # use pre-computed openable points from ALFRED to store receptacle locations - def explore_scene(self): - agent_height = self.env.last_event.metadata['agent']['position']['y'] - for object_id, point in self.openable_points.items(): - action = {'action': 'TeleportFull', - 'x': point[0], - 'y': agent_height, - 'z': point[1], - 'rotateOnTeleport': False, - 'rotation': point[2], - 'horizon': point[3]} - event = self.env.step(action) - - if event.metadata['lastActionSuccess']: - self.exploration_frames.append(np.array(self.env.last_event.frame[:,:,::-1])) - instance_segs = np.array(self.env.last_event.instance_segmentation_frame) - color_to_object_id = self.env.last_event.color_to_object_id - - # find unique instance segs - color_count = Counter() - for x in range(instance_segs.shape[0]): - for y in range(instance_segs.shape[1]): - color = instance_segs[y, x] - color_count[tuple(color)] += 1 - - for color, num_pixels in color_count.most_common(): - if color in color_to_object_id: - object_id = color_to_object_id[color] - object_type = object_id.split('|')[0] - if "Basin" in object_id: - object_type += "Basin" - - if object_type in self.STATIC_RECEPTACLES: - if object_id not in self.receptacles: - self.receptacles[object_id] = { - 'object_id': object_id, - 'object_type': object_type, - 'locs': action, - 'num_pixels': num_pixels, - 'num_id': "%s %d" % (object_type.lower(), self.get_next_num_id(object_type, self.receptacles)), - 'closed': True if object_type in constants.OPENABLE_CLASS_LIST else None - } - elif object_id in self.receptacles and num_pixels > self.receptacles[object_id]['num_pixels']: - self.receptacles[object_id]['locs'] = action # .append(action) - self.receptacles[object_id]['num_pixels'] = num_pixels - - # self.save_receps() - - # ground-truth instance segemetations (with consistent object IDs) from THOR - def get_instance_seg(self): - instance_segs = np.array(self.env.last_event.instance_segmentation_frame) - inst_color_to_object_id = self.env.last_event.color_to_object_id - - # find unique instance segs - inst_color_count = Counter() - for x in range(instance_segs.shape[0]): - for y in range(instance_segs.shape[1]): - color = instance_segs[y, x] - inst_color_count[tuple(color)] += 1 - return inst_color_count, inst_color_to_object_id - - # ground-truth object state info maintained by ThorEnv - def get_object_state(self, object_id): - is_clean = object_id in self.env.cleaned_objects - is_hot = object_id in self.env.heated_objects - is_cool = object_id in self.env.cooled_objects - is_sliced = 'Sliced' in object_id - return is_clean, is_cool, is_hot, is_sliced - - def get_admissible_commands(self): - return extract_admissible_commands_with_heuristics(self.intro, self.frame_desc, self.feedback, - self.curr_recep, self.inventory) - - def print_frame(self, recep, loc): - inst_color_count, inst_color_to_object_id = self.get_instance_seg() - recep_object_id = recep['object_id'] - - # for each unique seg add to object dictionary if it's more visible than before - visible_objects = [] - for color, num_pixels in inst_color_count.most_common(): - if color in inst_color_to_object_id: - object_id = inst_color_to_object_id[color] - object_type = object_id.split("|")[0] - object_metadata = self.get_obj_id_from_metadata(object_id) - is_obj_in_recep = (object_metadata and object_metadata['parentReceptacles'] and len(object_metadata['parentReceptacles']) > 0 and recep_object_id in object_metadata['parentReceptacles']) - if object_type in self.OBJECTS and object_metadata and (not self.use_gt_relations or is_obj_in_recep): - if object_id not in self.objects: - self.objects[object_id] = { - 'object_id': object_id, - 'object_type': object_type, - 'parent': recep['object_id'], - 'loc': loc, - 'num_pixels': num_pixels, - 'num_id': "%s %d" % (object_type.lower() if "Sliced" not in object_id else "sliced-%s" % object_type.lower(), - self.get_next_num_id(object_type, self.objects)) - } - elif object_id in self.objects and num_pixels > self.objects[object_id]['num_pixels']: - self.objects[object_id]['loc'] = loc - self.objects[object_id]['num_pixels'] = num_pixels - - if self.objects[object_id]['num_id'] not in self.inventory: - visible_objects.append(self.objects[object_id]['num_id']) - - visible_objects_with_articles = ["a %s," % vo for vo in visible_objects] - feedback = "" - if len(visible_objects) > 0: - feedback = "On the %s, you see %s" % (recep['num_id'], self.fix_and_comma_in_the_end(' '.join(visible_objects_with_articles))) - elif not recep['closed'] and len(visible_objects) == 0: - feedback = "On the %s, you see nothing." % (recep['num_id']) - - return visible_objects, feedback - - def step(self, action_str): - event = None - self.feedback = "Nothing happens." - - try: - cmd = self.parse_command(action_str) - - if cmd['action'] == self.Action.GOTO: - target = cmd['tar'] - recep = self.get_object(target, self.receptacles) - if recep and recep['num_id'] == self.curr_recep: - return self.feedback - self.curr_loc = recep['locs'] - event = self.navigate(self.curr_loc) - self.curr_recep = recep['num_id'] - self.visible_objects, self.feedback = self.print_frame(recep, self.curr_loc) - - # feedback conditions - loc_id = list(self.receptacles.keys()).index(recep['object_id']) - loc_feedback = "You arrive at loc %s. " % loc_id - state_feedback = "The {} is {}. ".format(self.curr_recep, "closed" if recep['closed'] else "open") if recep['closed'] is not None else "" - loc_state_feedback = loc_feedback + state_feedback - self.feedback = loc_state_feedback + self.feedback if "closed" not in state_feedback else loc_state_feedback - self.frame_desc = str(self.feedback) - - elif cmd['action'] == self.Action.PICK: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - if obj in self.visible_objects: - object = self.get_object(obj, self.objects) - event = self.env.step({'action': "PickupObject", - 'objectId': object['object_id'], - 'forceAction': True}) - - if event.metadata['lastActionSuccess']: - self.inventory.append(object['num_id']) - self.feedback = "You pick up the %s from the %s." % (obj, tar) - - elif cmd['action'] == self.Action.PUT: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - recep = self.get_object(tar, self.receptacles) - event = self.env.step({'action': "PutObject", - 'objectId': self.env.last_event.metadata['inventoryObjects'][0]['objectId'], - 'receptacleObjectId': recep['object_id'], - 'forceAction': True}) - if event.metadata['lastActionSuccess']: - self.inventory.pop() - self.feedback = "You put the %s %s the %s." % (obj, rel, tar) - - elif cmd['action'] == self.Action.OPEN: - target = cmd['tar'] - recep = self.get_object(target, self.receptacles) - event = self.env.step({'action': "OpenObject", - 'objectId': recep['object_id'], - 'forceAction': True}) - self.receptacles[recep['object_id']]['closed'] = False - self.visible_objects, self.feedback = self.print_frame(recep, self.curr_loc) - action_feedback = "You open the %s. The %s is open. " % (target, target) - self.feedback = action_feedback + self.feedback.replace("On the %s" % target, "In it") - self.frame_desc = str(self.feedback) - - elif cmd['action'] == self.Action.CLOSE: - target = cmd['tar'] - recep = self.get_object(target, self.receptacles) - event = self.env.step({'action': "CloseObject", - 'objectId': recep['object_id'], - 'forceAction': True}) - self.receptacles[recep['object_id']]['closed'] = True - self.feedback = "You close the %s." % target - - elif cmd['action'] == self.Action.TOGGLE: - target = cmd['tar'] - obj = self.get_object(target, self.objects) - event = self.env.step({'action': "ToggleObjectOn", - 'objectId': obj['object_id'], - 'forceAction': True}) - self.feedback = "You turn on the %s." % target - - elif cmd['action'] == self.Action.HEAT: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - obj_id = self.env.last_event.metadata['inventoryObjects'][0]['objectId'] - recep = self.get_object(tar, self.receptacles) - - # open the microwave, heat the object, take the object, close the microwave - events = [] - events.append(self.env.step({'action': 'OpenObject', 'objectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'PutObject', 'objectId': obj_id, 'receptacleObjectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'CloseObject', 'objectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'ToggleObjectOn', 'objectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'Pass'})) - events.append(self.env.step({'action': 'ToggleObjectOff', 'objectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'OpenObject', 'objectId': recep['object_id'], 'forceAction': True})) - events.append(self.env.step({'action': 'PickupObject', 'objectId': obj_id, 'forceAction': True})) - events.append(self.env.step({'action': 'CloseObject', 'objectId': recep['object_id'], 'forceAction': True})) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.feedback = "You heat the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.CLEAN: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - object = self.env.last_event.metadata['inventoryObjects'][0] - sink = self.get_obj_cls_from_metadata('BathtubBasin' if "bathtubbasin" in tar else "SinkBasin") - faucet = self.get_obj_cls_from_metadata('Faucet') - - # put the object in the sink, turn on the faucet, turn off the faucet, pickup the object - events = [] - events.append(self.env.step({'action': 'PutObject', 'objectId': object['objectId'], 'receptacleObjectId': sink['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'ToggleObjectOn', 'objectId': faucet['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'Pass'})) - events.append(self.env.step({'action': 'ToggleObjectOff', 'objectId': faucet['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'PickupObject', 'objectId': object['objectId'], 'forceAction': True})) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.feedback = "You clean the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.COOL: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - object = self.env.last_event.metadata['inventoryObjects'][0] - fridge = self.get_obj_cls_from_metadata('Fridge') - - # open the fridge, put the object inside, close the fridge, open the fridge, pickup the object - events = [] - events.append(self.env.step({'action': 'OpenObject', 'objectId': fridge['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'PutObject', 'objectId': object['objectId'], 'receptacleObjectId': fridge['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'CloseObject', 'objectId': fridge['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'Pass'})) - events.append(self.env.step({'action': 'OpenObject', 'objectId': fridge['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'PickupObject', 'objectId': object['objectId'], 'forceAction': True})) - events.append(self.env.step({'action': 'CloseObject', 'objectId': fridge['objectId'], 'forceAction': True})) - - if all(e.metadata['lastActionSuccess'] for e in events) and self.curr_recep == tar: - self.feedback = "You cool the %s using the %s." % (obj, tar) - - elif cmd['action'] == self.Action.SLICE: - obj, rel, tar = cmd['obj'], cmd['rel'], cmd['tar'] - object = self.get_object(obj, self.objects) - inventory_objects = self.env.last_event.metadata['inventoryObjects'] - if 'Knife' in inventory_objects[0]['objectType']: - event = self.env.step({'action': "SliceObject", - 'objectId': object['object_id']}) - self.feedback = "You slice %s with the %s" % (obj, tar) - - elif cmd['action'] == self.Action.INVENTORY: - if len(self.inventory) > 0: - self.feedback = "You are carrying: a %s" % (self.inventory[0]) - else: - self.feedback = "You are not carrying anything." - - elif cmd['action'] == self.Action.EXAMINE: - target = cmd['tar'] - receptacle = self.get_object(target, self.receptacles) - object = self.get_object(target, self.objects) - - if receptacle: - self.visible_objects, self.feedback = self.print_frame(receptacle, self.curr_loc) - self.frame_desc = str(self.feedback) - elif object: - self.feedback = self.print_object(object) - - elif cmd['action'] == self.Action.LOOK: - if self.curr_recep == "nothing": - self.feedback = "You are in the middle of a room. Looking quickly around you, you see nothing." - else: - self.feedback = "You are facing the %s. Next to it, you see nothing." % self.curr_recep - - except: - if self.debug: - print(traceback.format_exc()) - - if event and not event.metadata['lastActionSuccess']: - self.feedback = "Nothing happens." - if self.debug: - print(event.metadata['errorMessage']) - - if self.debug: - print(self.feedback) - return self.feedback - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle_astar.py b/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle_astar.py deleted file mode 100644 index 575f1c1e..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/controller/oracle_astar.py +++ /dev/null @@ -1,54 +0,0 @@ -import os -import json - -import alfworld.gen -import alfworld.gen.constants as constants -from alfworld.gen.game_states.task_game_state_full_knowledge import TaskGameStateFullKnowledge -from alfworld.gen.agents.deterministic_planner_agent import DeterministicPlannerAgent -from alfworld.gen.graph import graph_obj -from alfworld.agents.controller.oracle import OracleAgent - - -class OracleAStarAgent(OracleAgent): - - def __init__(self, env, traj_data, traj_root, - load_receps=False, debug=False, - goal_desc_human_anns_prob=0.0, - use_gt_relations=False): - - super().__init__(env, traj_data, traj_root, - load_receps=load_receps, debug=debug, - use_gt_relations=use_gt_relations, - goal_desc_human_anns_prob=goal_desc_human_anns_prob) - - def setup_navigator(self): - game_state = TaskGameStateFullKnowledge(self.env) - - # reset - game_state.receptacle_to_point = None - game_state.task_target = None - game_state.success = False - - # load nav graph - scene_num = self.traj_data['scene']['scene_num'] - game_state.gt_graph = graph_obj.Graph(use_gt=True, construct_graph=True, scene_id=scene_num) - game_state.gt_graph.clear() - - game_state.agent_height = self.env.last_event.metadata['agent']['position']['y'] - game_state.camera_height = game_state.agent_height + constants.CAMERA_HEIGHT_OFFSET - - points_source = os.path.join(alfworld.gen.__path__[0], 'layouts/FloorPlan%s-openable.json' % scene_num) - with open(points_source, 'r') as f: - openable_object_to_point = json.load(f) - game_state.openable_object_to_point = openable_object_to_point - - game_state.update_receptacle_nearest_points() # TODO: save to desk - game_state.planner.process_pool.terminate() - - self.navigator = DeterministicPlannerAgent(thread_id=0, game_state=game_state) - - - def navigate(self, teleport_loc): - self.navigator.pose = self.env.last_event.pose_discrete - self.navigator.step(teleport_loc) - return self.env.last_event \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_eval.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_eval.py deleted file mode 100644 index ecfee644..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_eval.py +++ /dev/null @@ -1,349 +0,0 @@ -import json -import tempfile - -import numpy as np -import copy -import time -import torch -import torch._six - -from pycocotools.cocoeval import COCOeval -from pycocotools.coco import COCO -import pycocotools.mask as mask_util - -from collections import defaultdict - -import alfworld.agents.detector.utils - - -class CocoEvaluator(object): - def __init__(self, coco_gt, iou_types): - assert isinstance(iou_types, (list, tuple)) - coco_gt = copy.deepcopy(coco_gt) - self.coco_gt = coco_gt - - self.iou_types = iou_types - self.coco_eval = {} - for iou_type in iou_types: - self.coco_eval[iou_type] = COCOeval(coco_gt, iouType=iou_type) - - self.img_ids = [] - self.eval_imgs = {k: [] for k in iou_types} - - def update(self, predictions): - img_ids = list(np.unique(list(predictions.keys()))) - self.img_ids.extend(img_ids) - - for iou_type in self.iou_types: - results = self.prepare(predictions, iou_type) - coco_dt = loadRes(self.coco_gt, results) if results else COCO() - coco_eval = self.coco_eval[iou_type] - - coco_eval.cocoDt = coco_dt - coco_eval.params.imgIds = list(img_ids) - img_ids, eval_imgs = evaluate(coco_eval) - - self.eval_imgs[iou_type].append(eval_imgs) - - def synchronize_between_processes(self): - for iou_type in self.iou_types: - self.eval_imgs[iou_type] = np.concatenate(self.eval_imgs[iou_type], 2) - create_common_coco_eval(self.coco_eval[iou_type], self.img_ids, self.eval_imgs[iou_type]) - - def accumulate(self): - for coco_eval in self.coco_eval.values(): - coco_eval.accumulate() - - def summarize(self): - for iou_type, coco_eval in self.coco_eval.items(): - print("IoU metric: {}".format(iou_type)) - coco_eval.summarize() - - def prepare(self, predictions, iou_type): - if iou_type == "bbox": - return self.prepare_for_coco_detection(predictions) - elif iou_type == "segm": - return self.prepare_for_coco_segmentation(predictions) - elif iou_type == "keypoints": - return self.prepare_for_coco_keypoint(predictions) - else: - raise ValueError("Unknown iou type {}".format(iou_type)) - - def prepare_for_coco_detection(self, predictions): - coco_results = [] - for original_id, prediction in predictions.items(): - if len(prediction) == 0: - continue - - boxes = prediction["boxes"] - boxes = convert_to_xywh(boxes).tolist() - scores = prediction["scores"].tolist() - labels = prediction["labels"].tolist() - - coco_results.extend( - [ - { - "image_id": original_id, - "category_id": labels[k], - "bbox": box, - "score": scores[k], - } - for k, box in enumerate(boxes) - ] - ) - return coco_results - - def prepare_for_coco_segmentation(self, predictions): - coco_results = [] - for original_id, prediction in predictions.items(): - if len(prediction) == 0: - continue - - scores = prediction["scores"] - labels = prediction["labels"] - masks = prediction["masks"] - - masks = masks > 0.5 - - scores = prediction["scores"].tolist() - labels = prediction["labels"].tolist() - - rles = [ - mask_util.encode(np.array(mask[0, :, :, np.newaxis], order="F"))[0] - for mask in masks - ] - for rle in rles: - rle["counts"] = rle["counts"].decode("utf-8") - - coco_results.extend( - [ - { - "image_id": original_id, - "category_id": labels[k], - "segmentation": rle, - "score": scores[k], - } - for k, rle in enumerate(rles) - ] - ) - return coco_results - - def prepare_for_coco_keypoint(self, predictions): - coco_results = [] - for original_id, prediction in predictions.items(): - if len(prediction) == 0: - continue - - boxes = prediction["boxes"] - boxes = convert_to_xywh(boxes).tolist() - scores = prediction["scores"].tolist() - labels = prediction["labels"].tolist() - keypoints = prediction["keypoints"] - keypoints = keypoints.flatten(start_dim=1).tolist() - - coco_results.extend( - [ - { - "image_id": original_id, - "category_id": labels[k], - 'keypoints': keypoint, - "score": scores[k], - } - for k, keypoint in enumerate(keypoints) - ] - ) - return coco_results - - -def convert_to_xywh(boxes): - xmin, ymin, xmax, ymax = boxes.unbind(1) - return torch.stack((xmin, ymin, xmax - xmin, ymax - ymin), dim=1) - - -def merge(img_ids, eval_imgs): - all_img_ids = utils.all_gather(img_ids) - all_eval_imgs = utils.all_gather(eval_imgs) - - merged_img_ids = [] - for p in all_img_ids: - merged_img_ids.extend(p) - - merged_eval_imgs = [] - for p in all_eval_imgs: - merged_eval_imgs.append(p) - - merged_img_ids = np.array(merged_img_ids) - merged_eval_imgs = np.concatenate(merged_eval_imgs, 2) - - # keep only unique (and in sorted order) images - merged_img_ids, idx = np.unique(merged_img_ids, return_index=True) - merged_eval_imgs = merged_eval_imgs[..., idx] - - return merged_img_ids, merged_eval_imgs - - -def create_common_coco_eval(coco_eval, img_ids, eval_imgs): - img_ids, eval_imgs = merge(img_ids, eval_imgs) - img_ids = list(img_ids) - eval_imgs = list(eval_imgs.flatten()) - - coco_eval.evalImgs = eval_imgs - coco_eval.params.imgIds = img_ids - coco_eval._paramsEval = copy.deepcopy(coco_eval.params) - - -################################################################# -# From pycocotools, just removed the prints and fixed -# a Python3 bug about unicode not defined -################################################################# - -# Ideally, pycocotools wouldn't have hard-coded prints -# so that we could avoid copy-pasting those two functions - -def createIndex(self): - # create index - # print('creating index...') - anns, cats, imgs = {}, {}, {} - imgToAnns, catToImgs = defaultdict(list), defaultdict(list) - if 'annotations' in self.dataset: - for ann in self.dataset['annotations']: - imgToAnns[ann['image_id']].append(ann) - anns[ann['id']] = ann - - if 'images' in self.dataset: - for img in self.dataset['images']: - imgs[img['id']] = img - - if 'categories' in self.dataset: - for cat in self.dataset['categories']: - cats[cat['id']] = cat - - if 'annotations' in self.dataset and 'categories' in self.dataset: - for ann in self.dataset['annotations']: - catToImgs[ann['category_id']].append(ann['image_id']) - - # print('index created!') - - # create class members - self.anns = anns - self.imgToAnns = imgToAnns - self.catToImgs = catToImgs - self.imgs = imgs - self.cats = cats - - -maskUtils = mask_util - - -def loadRes(self, resFile): - """ - Load result file and return a result api object. - :param resFile (str) : file name of result file - :return: res (obj) : result api object - """ - res = COCO() - res.dataset['images'] = [img for img in self.dataset['images']] - - # print('Loading and preparing results...') - # tic = time.time() - if isinstance(resFile, torch._six.string_classes): - anns = json.load(open(resFile)) - elif type(resFile) == np.ndarray: - anns = self.loadNumpyAnnotations(resFile) - else: - anns = resFile - assert type(anns) == list, 'results in not an array of objects' - annsImgIds = [ann['image_id'] for ann in anns] - assert set(annsImgIds) == (set(annsImgIds) & set(self.getImgIds())), \ - 'Results do not correspond to current coco set' - if 'caption' in anns[0]: - imgIds = set([img['id'] for img in res.dataset['images']]) & set([ann['image_id'] for ann in anns]) - res.dataset['images'] = [img for img in res.dataset['images'] if img['id'] in imgIds] - for id, ann in enumerate(anns): - ann['id'] = id + 1 - elif 'bbox' in anns[0] and not anns[0]['bbox'] == []: - res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) - for id, ann in enumerate(anns): - bb = ann['bbox'] - x1, x2, y1, y2 = [bb[0], bb[0] + bb[2], bb[1], bb[1] + bb[3]] - if 'segmentation' not in ann: - ann['segmentation'] = [[x1, y1, x1, y2, x2, y2, x2, y1]] - ann['area'] = bb[2] * bb[3] - ann['id'] = id + 1 - ann['iscrowd'] = 0 - elif 'segmentation' in anns[0]: - res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) - for id, ann in enumerate(anns): - # now only support compressed RLE format as segmentation results - ann['area'] = maskUtils.area(ann['segmentation']) - if 'bbox' not in ann: - ann['bbox'] = maskUtils.toBbox(ann['segmentation']) - ann['id'] = id + 1 - ann['iscrowd'] = 0 - elif 'keypoints' in anns[0]: - res.dataset['categories'] = copy.deepcopy(self.dataset['categories']) - for id, ann in enumerate(anns): - s = ann['keypoints'] - x = s[0::3] - y = s[1::3] - x0, x1, y0, y1 = np.min(x), np.max(x), np.min(y), np.max(y) - ann['area'] = (x1 - x0) * (y1 - y0) - ann['id'] = id + 1 - ann['bbox'] = [x0, y0, x1 - x0, y1 - y0] - # print('DONE (t={:0.2f}s)'.format(time.time()- tic)) - - res.dataset['annotations'] = anns - createIndex(res) - return res - - -def evaluate(self): - ''' - Run per image evaluation on given images and store results (a list of dict) in self.evalImgs - :return: None - ''' - # tic = time.time() - # print('Running per image evaluation...') - p = self.params - # add backward compatibility if useSegm is specified in params - if p.useSegm is not None: - p.iouType = 'segm' if p.useSegm == 1 else 'bbox' - print('useSegm (deprecated) is not None. Running {} evaluation'.format(p.iouType)) - # print('Evaluate annotation type *{}*'.format(p.iouType)) - p.imgIds = list(np.unique(p.imgIds)) - if p.useCats: - p.catIds = list(np.unique(p.catIds)) - p.maxDets = sorted(p.maxDets) - self.params = p - - self._prepare() - # loop through images, area range, max detection number - catIds = p.catIds if p.useCats else [-1] - - if p.iouType == 'segm' or p.iouType == 'bbox': - computeIoU = self.computeIoU - elif p.iouType == 'keypoints': - computeIoU = self.computeOks - self.ious = { - (imgId, catId): computeIoU(imgId, catId) - for imgId in p.imgIds - for catId in catIds} - - evaluateImg = self.evaluateImg - maxDet = p.maxDets[-1] - evalImgs = [ - evaluateImg(imgId, catId, areaRng, maxDet) - for catId in catIds - for areaRng in p.areaRng - for imgId in p.imgIds - ] - # this is NOT in the pycocotools code, but could be done outside - evalImgs = np.asarray(evalImgs).reshape(len(catIds), len(p.areaRng), len(p.imgIds)) - self._paramsEval = copy.deepcopy(self.params) - # toc = time.time() - # print('DONE (t={:0.2f}s).'.format(toc-tic)) - return p.imgIds, evalImgs - -################################################################# -# end of straight copy from pycocotools, just removing the prints -################################################################# diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_utils.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_utils.py deleted file mode 100644 index 2f2c904b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/coco_utils.py +++ /dev/null @@ -1,251 +0,0 @@ -import copy -import os -from PIL import Image - -import torch -import torch.utils.data -import torchvision - -from pycocotools import mask as coco_mask -from pycocotools.coco import COCO - -import alfworld.agents.detector.transforms as T - - -class FilterAndRemapCocoCategories(object): - def __init__(self, categories, remap=True): - self.categories = categories - self.remap = remap - - def __call__(self, image, target): - anno = target["annotations"] - anno = [obj for obj in anno if obj["category_id"] in self.categories] - if not self.remap: - target["annotations"] = anno - return image, target - anno = copy.deepcopy(anno) - for obj in anno: - obj["category_id"] = self.categories.index(obj["category_id"]) - target["annotations"] = anno - return image, target - - -def convert_coco_poly_to_mask(segmentations, height, width): - masks = [] - for polygons in segmentations: - rles = coco_mask.frPyObjects(polygons, height, width) - mask = coco_mask.decode(rles) - if len(mask.shape) < 3: - mask = mask[..., None] - mask = torch.as_tensor(mask, dtype=torch.uint8) - mask = mask.any(dim=2) - masks.append(mask) - if masks: - masks = torch.stack(masks, dim=0) - else: - masks = torch.zeros((0, height, width), dtype=torch.uint8) - return masks - - -class ConvertCocoPolysToMask(object): - def __call__(self, image, target): - w, h = image.size - - image_id = target["image_id"] - image_id = torch.tensor([image_id]) - - anno = target["annotations"] - - anno = [obj for obj in anno if obj['iscrowd'] == 0] - - boxes = [obj["bbox"] for obj in anno] - # guard against no boxes via resizing - boxes = torch.as_tensor(boxes, dtype=torch.float32).reshape(-1, 4) - boxes[:, 2:] += boxes[:, :2] - boxes[:, 0::2].clamp_(min=0, max=w) - boxes[:, 1::2].clamp_(min=0, max=h) - - classes = [obj["category_id"] for obj in anno] - classes = torch.tensor(classes, dtype=torch.int64) - - segmentations = [obj["segmentation"] for obj in anno] - masks = convert_coco_poly_to_mask(segmentations, h, w) - - keypoints = None - if anno and "keypoints" in anno[0]: - keypoints = [obj["keypoints"] for obj in anno] - keypoints = torch.as_tensor(keypoints, dtype=torch.float32) - num_keypoints = keypoints.shape[0] - if num_keypoints: - keypoints = keypoints.view(num_keypoints, -1, 3) - - keep = (boxes[:, 3] > boxes[:, 1]) & (boxes[:, 2] > boxes[:, 0]) - boxes = boxes[keep] - classes = classes[keep] - masks = masks[keep] - if keypoints is not None: - keypoints = keypoints[keep] - - target = {} - target["boxes"] = boxes - target["labels"] = classes - target["masks"] = masks - target["image_id"] = image_id - if keypoints is not None: - target["keypoints"] = keypoints - - # for conversion to coco api - area = torch.tensor([obj["area"] for obj in anno]) - iscrowd = torch.tensor([obj["iscrowd"] for obj in anno]) - target["area"] = area - target["iscrowd"] = iscrowd - - return image, target - - -def _coco_remove_images_without_annotations(dataset, cat_list=None): - def _has_only_empty_bbox(anno): - return all(any(o <= 1 for o in obj["bbox"][2:]) for obj in anno) - - def _count_visible_keypoints(anno): - return sum(sum(1 for v in ann["keypoints"][2::3] if v > 0) for ann in anno) - - min_keypoints_per_image = 10 - - def _has_valid_annotation(anno): - # if it's empty, there is no annotation - if len(anno) == 0: - return False - # if all boxes have close to zero area, there is no annotation - if _has_only_empty_bbox(anno): - return False - # keypoints task have a slight different critera for considering - # if an annotation is valid - if "keypoints" not in anno[0]: - return True - # for keypoint detection tasks, only consider valid images those - # containing at least min_keypoints_per_image - if _count_visible_keypoints(anno) >= min_keypoints_per_image: - return True - return False - - assert isinstance(dataset, torchvision.datasets.CocoDetection) - ids = [] - for ds_idx, img_id in enumerate(dataset.ids): - ann_ids = dataset.coco.getAnnIds(imgIds=img_id, iscrowd=None) - anno = dataset.coco.loadAnns(ann_ids) - if cat_list: - anno = [obj for obj in anno if obj["category_id"] in cat_list] - if _has_valid_annotation(anno): - ids.append(ds_idx) - - dataset = torch.utils.data.Subset(dataset, ids) - return dataset - - -def convert_to_coco_api(ds): - coco_ds = COCO() - ann_id = 0 - dataset = {'images': [], 'categories': [], 'annotations': []} - categories = set() - for img_idx in range(len(ds)): - # find better way to get target - # targets = ds.get_annotations(img_idx) - img, targets = ds[img_idx] - image_id = targets["image_id"].item() - img_dict = {} - img_dict['id'] = image_id - img_dict['height'] = img.shape[-2] - img_dict['width'] = img.shape[-1] - dataset['images'].append(img_dict) - bboxes = targets["boxes"] - bboxes[:, 2:] -= bboxes[:, :2] - bboxes = bboxes.tolist() - labels = targets['labels'].tolist() - areas = targets['area'].tolist() - iscrowd = targets['iscrowd'].tolist() - if 'masks' in targets: - masks = targets['masks'] - # make masks Fortran contiguous for coco_mask - masks = masks.permute(0, 2, 1).contiguous().permute(0, 2, 1) - if 'keypoints' in targets: - keypoints = targets['keypoints'] - keypoints = keypoints.reshape(keypoints.shape[0], -1).tolist() - num_objs = len(bboxes) - for i in range(num_objs): - ann = {} - ann['image_id'] = image_id - ann['bbox'] = bboxes[i] - ann['category_id'] = labels[i] - categories.add(labels[i]) - ann['area'] = areas[i] - ann['iscrowd'] = iscrowd[i] - ann['id'] = ann_id - if 'masks' in targets: - ann["segmentation"] = coco_mask.encode(masks[i].numpy()) - if 'keypoints' in targets: - ann['keypoints'] = keypoints[i] - ann['num_keypoints'] = sum(k != 0 for k in keypoints[i][2::3]) - dataset['annotations'].append(ann) - ann_id += 1 - dataset['categories'] = [{'id': i} for i in sorted(categories)] - coco_ds.dataset = dataset - coco_ds.createIndex() - return coco_ds - - -def get_coco_api_from_dataset(dataset): - for i in range(10): - if isinstance(dataset, torchvision.datasets.CocoDetection): - break - if isinstance(dataset, torch.utils.data.Subset): - dataset = dataset.dataset - if isinstance(dataset, torchvision.datasets.CocoDetection): - return dataset.coco - return convert_to_coco_api(dataset) - - -class CocoDetection(torchvision.datasets.CocoDetection): - def __init__(self, img_folder, ann_file, transforms): - super(CocoDetection, self).__init__(img_folder, ann_file) - self._transforms = transforms - - def __getitem__(self, idx): - img, target = super(CocoDetection, self).__getitem__(idx) - image_id = self.ids[idx] - target = dict(image_id=image_id, annotations=target) - if self._transforms is not None: - img, target = self._transforms(img, target) - return img, target - - -def get_coco(root, image_set, transforms, mode='instances'): - anno_file_template = "{}_{}2017.json" - PATHS = { - "train": ("train2017", os.path.join("annotations", anno_file_template.format(mode, "train"))), - "val": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))), - # "train": ("val2017", os.path.join("annotations", anno_file_template.format(mode, "val"))) - } - - t = [ConvertCocoPolysToMask()] - - if transforms is not None: - t.append(transforms) - transforms = T.Compose(t) - - img_folder, ann_file = PATHS[image_set] - img_folder = os.path.join(root, img_folder) - ann_file = os.path.join(root, ann_file) - - dataset = CocoDetection(img_folder, ann_file, transforms=transforms) - - if image_set == "train": - dataset = _coco_remove_images_without_annotations(dataset) - - # dataset = torch.utils.data.Subset(dataset, [i for i in range(500)]) - - return dataset - - -def get_coco_kp(root, image_set, transforms): - return get_coco(root, image_set, transforms, mode="person_keypoints") diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/engine.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/engine.py deleted file mode 100644 index e26dcfd0..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/engine.py +++ /dev/null @@ -1,108 +0,0 @@ -import math -import sys -import time -import torch - -import torchvision.models.detection.mask_rcnn - -from alfworld.agents.detector.coco_utils import get_coco_api_from_dataset -from alfworld.agents.detector.coco_eval import CocoEvaluator -import alfworld.agents.detector.utils as utils - - -def train_one_epoch(model, optimizer, data_loader, device, epoch, print_freq): - model.train() - metric_logger = utils.MetricLogger(delimiter=" ") - metric_logger.add_meter('lr', utils.SmoothedValue(window_size=1, fmt='{value:.6f}')) - header = 'Epoch: [{}]'.format(epoch) - - lr_scheduler = None - if epoch == 0: - warmup_factor = 1. / 1000 - warmup_iters = min(1000, len(data_loader) - 1) - - lr_scheduler = utils.warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor) - - for images, targets in metric_logger.log_every(data_loader, print_freq, header): - images = list(image.to(device) for image in images) - targets = [{k: v.to(device) for k, v in t.items()} for t in targets] - - loss_dict = model(images, targets) - - losses = sum(loss for loss in loss_dict.values()) - - # reduce losses over all GPUs for logging purposes - loss_dict_reduced = utils.reduce_dict(loss_dict) - losses_reduced = sum(loss for loss in loss_dict_reduced.values()) - - loss_value = losses_reduced.item() - - if not math.isfinite(loss_value): - print("Loss is {}, stopping training".format(loss_value)) - print(loss_dict_reduced) - sys.exit(1) - - optimizer.zero_grad() - losses.backward() - optimizer.step() - - if lr_scheduler is not None: - lr_scheduler.step() - - metric_logger.update(loss=losses_reduced, **loss_dict_reduced) - metric_logger.update(lr=optimizer.param_groups[0]["lr"]) - - -def _get_iou_types(model): - model_without_ddp = model - if isinstance(model, torch.nn.parallel.DistributedDataParallel): - model_without_ddp = model.module - iou_types = ["bbox"] - if isinstance(model_without_ddp, torchvision.models.detection.MaskRCNN): - iou_types.append("segm") - if isinstance(model_without_ddp, torchvision.models.detection.KeypointRCNN): - iou_types.append("keypoints") - return iou_types - - -@torch.no_grad() -def evaluate(model, data_loader, device): - n_threads = torch.get_num_threads() - # FIXME remove this and make paste_masks_in_image run on the GPU - torch.set_num_threads(1) - cpu_device = torch.device("cpu") - model.eval() - metric_logger = utils.MetricLogger(delimiter=" ") - header = 'Test:' - - coco = get_coco_api_from_dataset(data_loader.dataset) - iou_types = _get_iou_types(model) - coco_evaluator = CocoEvaluator(coco, iou_types) - - for image, targets in metric_logger.log_every(data_loader, 100, header): - image = list(img.to(device) for img in image) - targets = [{k: v.to(device) for k, v in t.items()} for t in targets] - - torch.cuda.synchronize() - model_time = time.time() - outputs = model(image) - - outputs = [{k: v.to(cpu_device) for k, v in t.items()} for t in outputs] - model_time = time.time() - model_time - - res = {target["image_id"].item(): output for target, output in zip(targets, outputs)} - evaluator_time = time.time() - coco_evaluator.update(res) - evaluator_time = time.time() - evaluator_time - metric_logger.update(model_time=model_time, evaluator_time=evaluator_time) - - # gather the stats from all processes - metric_logger.synchronize_between_processes() - print("Averaged stats:", metric_logger) - coco_evaluator.synchronize_between_processes() - - # accumulate predictions from all images - coco_evaluator.accumulate() - coco_evaluator.summarize() - torch.set_num_threads(n_threads) - return coco_evaluator diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/group_by_aspect_ratio.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/group_by_aspect_ratio.py deleted file mode 100644 index 572bf773..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/group_by_aspect_ratio.py +++ /dev/null @@ -1,187 +0,0 @@ -import bisect -from collections import defaultdict -import copy -import numpy as np - -import torch -import torch.utils.data -from torch.utils.data.sampler import BatchSampler, Sampler -from torch.utils.model_zoo import tqdm -import torchvision - -from PIL import Image - - -class GroupedBatchSampler(BatchSampler): - """ - Wraps another sampler to yield a mini-batch of indices. - It enforces that the batch only contain elements from the same group. - It also tries to provide mini-batches which follows an ordering which is - as close as possible to the ordering from the original sampler. - Arguments: - sampler (Sampler): Base sampler. - group_ids (list[int]): If the sampler produces indices in range [0, N), - `group_ids` must be a list of `N` ints which contains the group id of each sample. - The group ids must be a continuous set of integers starting from - 0, i.e. they must be in the range [0, num_groups). - batch_size (int): Size of mini-batch. - """ - def __init__(self, sampler, group_ids, batch_size): - if not isinstance(sampler, Sampler): - raise ValueError( - "sampler should be an instance of " - "torch.utils.data.Sampler, but got sampler={}".format(sampler) - ) - self.sampler = sampler - self.group_ids = group_ids - self.batch_size = batch_size - - def __iter__(self): - buffer_per_group = defaultdict(list) - samples_per_group = defaultdict(list) - - num_batches = 0 - for idx in self.sampler: - group_id = self.group_ids[idx] - buffer_per_group[group_id].append(idx) - samples_per_group[group_id].append(idx) - if len(buffer_per_group[group_id]) == self.batch_size: - yield buffer_per_group[group_id] - num_batches += 1 - del buffer_per_group[group_id] - assert len(buffer_per_group[group_id]) < self.batch_size - - # now we have run out of elements that satisfy - # the group criteria, let's return the remaining - # elements so that the size of the sampler is - # deterministic - expected_num_batches = len(self) - num_remaining = expected_num_batches - num_batches - if num_remaining > 0: - # for the remaining batches, take first the buffers with largest number - # of elements - for group_id, _ in sorted(buffer_per_group.items(), - key=lambda x: len(x[1]), reverse=True): - remaining = self.batch_size - len(buffer_per_group[group_id]) - buffer_per_group[group_id].extend( - samples_per_group[group_id][:remaining]) - assert len(buffer_per_group[group_id]) == self.batch_size - yield buffer_per_group[group_id] - num_remaining -= 1 - if num_remaining == 0: - break - assert num_remaining == 0 - - def __len__(self): - return len(self.sampler) // self.batch_size - - -def _compute_aspect_ratios_slow(dataset, indices=None): - print("Your dataset doesn't support the fast path for " - "computing the aspect ratios, so will iterate over " - "the full dataset and load every image instead. " - "This might take some time...") - if indices is None: - indices = range(len(dataset)) - - class SubsetSampler(Sampler): - def __init__(self, indices): - self.indices = indices - - def __iter__(self): - return iter(self.indices) - - def __len__(self): - return len(self.indices) - - sampler = SubsetSampler(indices) - data_loader = torch.utils.data.DataLoader( - dataset, batch_size=1, sampler=sampler, - num_workers=14, # you might want to increase it for faster processing - collate_fn=lambda x: x[0]) - aspect_ratios = [] - with tqdm(total=len(dataset)) as pbar: - for i, (img, _) in enumerate(data_loader): - pbar.update(1) - height, width = img.shape[-2:] - aspect_ratio = float(height) / float(width) - aspect_ratios.append(aspect_ratio) - return aspect_ratios - - -def _compute_aspect_ratios_custom_dataset(dataset, indices=None): - if indices is None: - indices = range(len(dataset)) - aspect_ratios = [] - for i in indices: - height, width = dataset.get_height_and_width(i) - aspect_ratio = float(height) / float(width) - aspect_ratios.append(aspect_ratio) - return aspect_ratios - - -def _compute_aspect_ratios_coco_dataset(dataset, indices=None): - if indices is None: - indices = range(len(dataset)) - aspect_ratios = [] - for i in indices: - img_info = dataset.coco.imgs[dataset.ids[i]] - aspect_ratio = float(img_info["height"]) / float(img_info["width"]) - aspect_ratios.append(aspect_ratio) - return aspect_ratios - - -def _compute_aspect_ratios_voc_dataset(dataset, indices=None): - if indices is None: - indices = range(len(dataset)) - aspect_ratios = [] - for i in indices: - # this doesn't load the data into memory, because PIL loads it lazily - width, height = Image.open(dataset.images[i]).size - aspect_ratio = float(height) / float(width) - aspect_ratios.append(aspect_ratio) - return aspect_ratios - - -def _compute_aspect_ratios_subset_dataset(dataset, indices=None): - if indices is None: - indices = range(len(dataset)) - - ds_indices = [dataset.indices[i] for i in indices] - return compute_aspect_ratios(dataset.dataset, ds_indices) - - -def compute_aspect_ratios(dataset, indices=None): - if hasattr(dataset, "get_height_and_width"): - return _compute_aspect_ratios_custom_dataset(dataset, indices) - - if isinstance(dataset, torchvision.datasets.CocoDetection): - return _compute_aspect_ratios_coco_dataset(dataset, indices) - - if isinstance(dataset, torchvision.datasets.VOCDetection): - return _compute_aspect_ratios_voc_dataset(dataset, indices) - - if isinstance(dataset, torch.utils.data.Subset): - return _compute_aspect_ratios_subset_dataset(dataset, indices) - - # slow path - return _compute_aspect_ratios_slow(dataset, indices) - - -def _quantize(x, bins): - bins = copy.deepcopy(bins) - bins = sorted(bins) - quantized = list(map(lambda y: bisect.bisect_right(bins, y), x)) - return quantized - - -def create_aspect_ratio_groups(dataset, k=0): - aspect_ratios = compute_aspect_ratios(dataset) - bins = (2 ** np.linspace(-1, 1, 2 * k + 1)).tolist() if k > 0 else [1.0] - groups = _quantize(aspect_ratios, bins) - # count number of elements per group - counts = np.unique(groups, return_counts=True)[1] - fbins = [0] + bins + [np.inf] - print("Using {} as bins for aspect ratio quantization".format(fbins)) - print("Count of instances per bin: {}".format(counts)) - return groups diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/mrcnn.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/mrcnn.py deleted file mode 100644 index 8c307eb9..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/mrcnn.py +++ /dev/null @@ -1,42 +0,0 @@ -import torch -import torchvision -from torchvision.models.detection.rpn import AnchorGenerator, RPNHead -from torchvision.models.detection.faster_rcnn import FastRCNNPredictor -from torchvision.models.detection.mask_rcnn import MaskRCNNPredictor - -import os -import sys -import alfworld.gen.constants as constants - - -def get_model_instance_segmentation(num_classes): - # load an instance segmentation model pre-trained pre-trained on COCO - model = torchvision.models.detection.maskrcnn_resnet50_fpn(pretrained=True) - - anchor_generator = AnchorGenerator( - sizes=tuple([(4, 8, 16, 32, 64, 128, 256, 512) for _ in range(5)]), - aspect_ratios=tuple([(0.25, 0.5, 1.0, 2.0) for _ in range(5)])) - model.rpn.anchor_generator = anchor_generator - - # 256 because that's the number of features that FPN returns - model.rpn.head = RPNHead(256, anchor_generator.num_anchors_per_location()[0]) - - # get number of input features for the classifier - in_features = model.roi_heads.box_predictor.cls_score.in_features - # replace the pre-trained head with a new one - model.roi_heads.box_predictor = FastRCNNPredictor(in_features, num_classes) - - # now get the number of input features for the mask classifier - in_features_mask = model.roi_heads.mask_predictor.conv5_mask.in_channels - hidden_layer = 256 - # and replace the mask predictor with a new one - model.roi_heads.mask_predictor = MaskRCNNPredictor(in_features_mask, - hidden_layer, - num_classes) - - return model - -def load_pretrained_model(path): - mask_rcnn = get_model_instance_segmentation(len(constants.OBJECTS_DETECTOR)+1) - mask_rcnn.load_state_dict(torch.load(path)) - return mask_rcnn \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/train.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/train.py deleted file mode 100644 index 190e7882..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/train.py +++ /dev/null @@ -1,177 +0,0 @@ -import datetime -import os -import time - -import torch -import torch.utils.data -from torch import nn -import torchvision -import torchvision.models.detection -import torchvision.models.detection.mask_rcnn - -from torchvision import transforms - -from alfworld.agents.detector.coco_utils import get_coco, get_coco_kp - -from alfworld.agents.detector.group_by_aspect_ratio import GroupedBatchSampler, create_aspect_ratio_groups -from alfworld.agents.detector.engine import train_one_epoch, evaluate - -import alfworld.agents.detector.utils as utils -import alfworld.agents.detector.transforms as T - - -def get_dataset(name, image_set, transform): - paths = { - "coco": ('/datasets01/COCO/022719/', get_coco, 91), - "coco_kp": ('/datasets01/COCO/022719/', get_coco_kp, 2) - } - p, ds_fn, num_classes = paths[name] - - ds = ds_fn(p, image_set=image_set, transforms=transform) - return ds, num_classes - - -def get_transform(train): - transforms = [] - transforms.append(T.ToTensor()) - if train: - transforms.append(T.RandomHorizontalFlip(0.5)) - return T.Compose(transforms) - - -def main(args): - utils.init_distributed_mode(args) - print(args) - - device = torch.device(args.device) - - # Data loading code - print("Loading data") - - dataset, num_classes = get_dataset(args.dataset, "train", get_transform(train=True)) - dataset_test, _ = get_dataset(args.dataset, "val", get_transform(train=False)) - - print("Creating data loaders") - if args.distributed: - train_sampler = torch.utils.data.distributed.DistributedSampler(dataset) - test_sampler = torch.utils.data.distributed.DistributedSampler(dataset_test) - else: - train_sampler = torch.utils.data.RandomSampler(dataset) - test_sampler = torch.utils.data.SequentialSampler(dataset_test) - - if args.aspect_ratio_group_factor >= 0: - group_ids = create_aspect_ratio_groups(dataset, k=args.aspect_ratio_group_factor) - train_batch_sampler = GroupedBatchSampler(train_sampler, group_ids, args.batch_size) - else: - train_batch_sampler = torch.utils.data.BatchSampler( - train_sampler, args.batch_size, drop_last=True) - - data_loader = torch.utils.data.DataLoader( - dataset, batch_sampler=train_batch_sampler, num_workers=args.workers, - collate_fn=utils.collate_fn) - - data_loader_test = torch.utils.data.DataLoader( - dataset_test, batch_size=1, - sampler=test_sampler, num_workers=args.workers, - collate_fn=utils.collate_fn) - - print("Creating model") - model = torchvision.models.detection.__dict__[args.model](num_classes=num_classes, - pretrained=args.pretrained) - model.to(device) - - model_without_ddp = model - if args.distributed: - model = torch.nn.parallel.DistributedDataParallel(model, device_ids=[args.gpu]) - model_without_ddp = model.module - - params = [p for p in model.parameters() if p.requires_grad] - optimizer = torch.optim.SGD( - params, lr=args.lr, momentum=args.momentum, weight_decay=args.weight_decay) - - # lr_scheduler = torch.optim.lr_scheduler.StepLR(optimizer, step_size=args.lr_step_size, gamma=args.lr_gamma) - lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(optimizer, milestones=args.lr_steps, gamma=args.lr_gamma) - - if args.resume: - checkpoint = torch.load(args.resume, map_location='cpu') - model_without_ddp.load_state_dict(checkpoint['model']) - optimizer.load_state_dict(checkpoint['optimizer']) - lr_scheduler.load_state_dict(checkpoint['lr_scheduler']) - - if args.test_only: - evaluate(model, data_loader_test, device=device) - return - - print("Start training") - start_time = time.time() - for epoch in range(args.epochs): - if args.distributed: - train_sampler.set_epoch(epoch) - train_one_epoch(model, optimizer, data_loader, device, epoch, args.print_freq) - lr_scheduler.step() - if args.output_dir: - utils.save_on_master({ - 'model': model_without_ddp.state_dict(), - 'optimizer': optimizer.state_dict(), - 'lr_scheduler': lr_scheduler.state_dict(), - 'args': args}, - os.path.join(args.output_dir, 'model_{}.pth'.format(epoch))) - - # evaluate after every epoch - evaluate(model, data_loader_test, device=device) - - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - print('Training time {}'.format(total_time_str)) - - -if __name__ == "__main__": - import argparse - parser = argparse.ArgumentParser(description='PyTorch Detection Training') - - parser.add_argument('--data-path', default='/datasets01/COCO/022719/', help='dataset') - parser.add_argument('--dataset', default='coco', help='dataset') - parser.add_argument('--model', default='maskrcnn_resnet50_fpn', help='model') - parser.add_argument('--device', default='cuda', help='device') - parser.add_argument('-b', '--batch-size', default=2, type=int) - parser.add_argument('--epochs', default=13, type=int, metavar='N', - help='number of total epochs to run') - parser.add_argument('-j', '--workers', default=4, type=int, metavar='N', - help='number of data loading workers (default: 16)') - parser.add_argument('--lr', default=0.02, type=float, help='initial learning rate') - parser.add_argument('--momentum', default=0.9, type=float, metavar='M', - help='momentum') - parser.add_argument('--wd', '--weight-decay', default=1e-4, type=float, - metavar='W', help='weight decay (default: 1e-4)', - dest='weight_decay') - parser.add_argument('--lr-step-size', default=8, type=int, help='decrease lr every step-size epochs') - parser.add_argument('--lr-steps', default=[8, 11], nargs='+', type=int, help='decrease lr every step-size epochs') - parser.add_argument('--lr-gamma', default=0.1, type=float, help='decrease lr by a factor of lr-gamma') - parser.add_argument('--print-freq', default=20, type=int, help='print frequency') - parser.add_argument('--output-dir', default='.', help='path where to save') - parser.add_argument('--resume', default='', help='resume from checkpoint') - parser.add_argument('--aspect-ratio-group-factor', default=0, type=int) - parser.add_argument( - "--test-only", - dest="test_only", - help="Only test the model", - action="store_true", - ) - parser.add_argument( - "--pretrained", - dest="pretrained", - help="Use pre-trained models from the modelzoo", - action="store_true", - ) - - # distributed training parameters - parser.add_argument('--world-size', default=1, type=int, - help='number of distributed processes') - parser.add_argument('--dist-url', default='env://', help='url used to set up distributed training') - - args = parser.parse_args() - - if args.output_dir: - utils.mkdir(args.output_dir) - - main(args) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/transforms.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/transforms.py deleted file mode 100644 index 73efc92b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/transforms.py +++ /dev/null @@ -1,50 +0,0 @@ -import random -import torch - -from torchvision.transforms import functional as F - - -def _flip_coco_person_keypoints(kps, width): - flip_inds = [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] - flipped_data = kps[:, flip_inds] - flipped_data[..., 0] = width - flipped_data[..., 0] - # Maintain COCO convention that if visibility == 0, then x, y = 0 - inds = flipped_data[..., 2] == 0 - flipped_data[inds] = 0 - return flipped_data - - -class Compose(object): - def __init__(self, transforms): - self.transforms = transforms - - def __call__(self, image, target): - for t in self.transforms: - image, target = t(image, target) - return image, target - - -class RandomHorizontalFlip(object): - def __init__(self, prob): - self.prob = prob - - def __call__(self, image, target): - if random.random() < self.prob: - height, width = image.shape[-2:] - image = image.flip(-1) - bbox = target["boxes"] - bbox[:, [0, 2]] = width - bbox[:, [2, 0]] - target["boxes"] = bbox - if "masks" in target: - target["masks"] = target["masks"].flip(-1) - if "keypoints" in target: - keypoints = target["keypoints"] - keypoints = _flip_coco_person_keypoints(keypoints, width) - target["keypoints"] = keypoints - return image, target - - -class ToTensor(object): - def __call__(self, image, target): - image = F.to_tensor(image) - return image, target diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/utils.py b/agent_system/environments/env_package/alfworld/alfworld/agents/detector/utils.py deleted file mode 100644 index 7b435859..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/detector/utils.py +++ /dev/null @@ -1,319 +0,0 @@ -from __future__ import print_function - -from collections import defaultdict, deque -import datetime -import pickle -import time - -import torch -import torch.distributed as dist - -import errno -import os - - -class SmoothedValue(object): - """Track a series of values and provide access to smoothed values over a - window or the global series average. - """ - - def __init__(self, window_size=20, fmt=None): - if fmt is None: - fmt = "{median:.4f} ({global_avg:.4f})" - self.deque = deque(maxlen=window_size) - self.total = 0.0 - self.count = 0 - self.fmt = fmt - - def update(self, value, n=1): - self.deque.append(value) - self.count += n - self.total += value * n - - def synchronize_between_processes(self): - """ - Warning: does not synchronize the deque! - """ - if not is_dist_avail_and_initialized(): - return - t = torch.tensor([self.count, self.total], dtype=torch.float64, device='cuda') - dist.barrier() - dist.all_reduce(t) - t = t.tolist() - self.count = int(t[0]) - self.total = t[1] - - @property - def median(self): - d = torch.tensor(list(self.deque)) - return d.median().item() - - @property - def avg(self): - d = torch.tensor(list(self.deque), dtype=torch.float32) - return d.mean().item() - - @property - def global_avg(self): - return self.total / self.count - - @property - def max(self): - return max(self.deque) - - @property - def value(self): - return self.deque[-1] - - def __str__(self): - return self.fmt.format( - median=self.median, - avg=self.avg, - global_avg=self.global_avg, - max=self.max, - value=self.value) - - -def all_gather(data): - """ - Run all_gather on arbitrary picklable data (not necessarily tensors) - Args: - data: any picklable object - Returns: - list[data]: list of data gathered from each rank - """ - world_size = get_world_size() - if world_size == 1: - return [data] - - # serialized to a Tensor - buffer = pickle.dumps(data) - storage = torch.ByteStorage.from_buffer(buffer) - tensor = torch.ByteTensor(storage).to("cuda") - - # obtain Tensor size of each rank - local_size = torch.tensor([tensor.numel()], device="cuda") - size_list = [torch.tensor([0], device="cuda") for _ in range(world_size)] - dist.all_gather(size_list, local_size) - size_list = [int(size.item()) for size in size_list] - max_size = max(size_list) - - # receiving Tensor from all ranks - # we pad the tensor because torch all_gather does not support - # gathering tensors of different shapes - tensor_list = [] - for _ in size_list: - tensor_list.append(torch.empty((max_size,), dtype=torch.uint8, device="cuda")) - if local_size != max_size: - padding = torch.empty(size=(max_size - local_size,), dtype=torch.uint8, device="cuda") - tensor = torch.cat((tensor, padding), dim=0) - dist.all_gather(tensor_list, tensor) - - data_list = [] - for size, tensor in zip(size_list, tensor_list): - buffer = tensor.cpu().numpy().tobytes()[:size] - data_list.append(pickle.loads(buffer)) - - return data_list - - -def reduce_dict(input_dict, average=True): - """ - Args: - input_dict (dict): all the values will be reduced - average (bool): whether to do average or sum - Reduce the values in the dictionary from all processes so that all processes - have the averaged results. Returns a dict with the same fields as - input_dict, after reduction. - """ - world_size = get_world_size() - if world_size < 2: - return input_dict - with torch.no_grad(): - names = [] - values = [] - # sort the keys so that they are consistent across processes - for k in sorted(input_dict.keys()): - names.append(k) - values.append(input_dict[k]) - values = torch.stack(values, dim=0) - dist.all_reduce(values) - if average: - values /= world_size - reduced_dict = {k: v for k, v in zip(names, values)} - return reduced_dict - - -class MetricLogger(object): - def __init__(self, delimiter="\t"): - self.meters = defaultdict(SmoothedValue) - self.delimiter = delimiter - - def update(self, **kwargs): - for k, v in kwargs.items(): - if isinstance(v, torch.Tensor): - v = v.item() - assert isinstance(v, (float, int)) - self.meters[k].update(v) - - def __getattr__(self, attr): - if attr in self.meters: - return self.meters[attr] - if attr in self.__dict__: - return self.__dict__[attr] - raise AttributeError("'{}' object has no attribute '{}'".format( - type(self).__name__, attr)) - - def __str__(self): - loss_str = [] - for name, meter in self.meters.items(): - loss_str.append( - "{}: {}".format(name, str(meter)) - ) - return self.delimiter.join(loss_str) - - def synchronize_between_processes(self): - for meter in self.meters.values(): - meter.synchronize_between_processes() - - def add_meter(self, name, meter): - self.meters[name] = meter - - def log_every(self, iterable, print_freq, header=None): - i = 0 - if not header: - header = '' - start_time = time.time() - end = time.time() - iter_time = SmoothedValue(fmt='{avg:.4f}') - data_time = SmoothedValue(fmt='{avg:.4f}') - space_fmt = ':' + str(len(str(len(iterable)))) + 'd' - log_msg = self.delimiter.join([ - header, - '[{0' + space_fmt + '}/{1}]', - 'eta: {eta}', - '{meters}', - 'time: {time}', - 'data: {data}', - 'max mem: {memory:.0f}' - ]) - MB = 1024.0 * 1024.0 - data = iter(iterable) - while True: - # for obj in iterable: - try: - obj = next(data) - data_time.update(time.time() - end) - yield obj - iter_time.update(time.time() - end) - if i % print_freq == 0 or i == len(iterable) - 1: - eta_seconds = iter_time.global_avg * (len(iterable) - i) - eta_string = str(datetime.timedelta(seconds=int(eta_seconds))) - print(log_msg.format( - i, len(iterable), eta=eta_string, - meters=str(self), - time=str(iter_time), data=str(data_time), - memory=torch.cuda.max_memory_allocated() / MB)) - i += 1 - end = time.time() - except StopIteration: - break - except Exception as e: - print(e) - total_time = time.time() - start_time - total_time_str = str(datetime.timedelta(seconds=int(total_time))) - print('{} Total time: {} ({:.4f} s / it)'.format( - header, total_time_str, total_time / len(iterable))) - - -def collate_fn(batch): - batch = list(filter(lambda x: x[0] is not None, batch)) - return tuple(zip(*batch)) - - -def warmup_lr_scheduler(optimizer, warmup_iters, warmup_factor): - - def f(x): - if x >= warmup_iters: - return 1 - alpha = float(x) / warmup_iters - return warmup_factor * (1 - alpha) + alpha - - return torch.optim.lr_scheduler.LambdaLR(optimizer, f) - - -def mkdir(path): - try: - os.makedirs(path) - except OSError as e: - if e.errno != errno.EEXIST: - raise - - -def setup_for_distributed(is_master): - """ - This function disables printing when not in master process - """ - import builtins as __builtin__ - builtin_print = __builtin__.print - - def print(*args, **kwargs): - force = kwargs.pop('force', False) - if is_master or force: - builtin_print(*args, **kwargs) - - __builtin__.print = print - - -def is_dist_avail_and_initialized(): - if not dist.is_available(): - return False - if not dist.is_initialized(): - return False - return True - - -def get_world_size(): - if not is_dist_avail_and_initialized(): - return 1 - return dist.get_world_size() - - -def get_rank(): - if not is_dist_avail_and_initialized(): - return 0 - return dist.get_rank() - - -def is_main_process(): - return get_rank() == 0 - - -def save_on_master(*args, **kwargs): - if is_main_process(): - torch.save(*args, **kwargs) - - -def init_distributed_mode(args): - if 'RANK' in os.environ and 'WORLD_SIZE' in os.environ: - args.rank = int(os.environ["RANK"]) - args.world_size = int(os.environ['WORLD_SIZE']) - args.gpu = int(os.environ['LOCAL_RANK']) - elif 'SLURM_PROCID' in os.environ: - args.rank = int(os.environ['SLURM_PROCID']) - args.gpu = args.rank % torch.cuda.device_count() - else: - print('Not using distributed mode') - args.distributed = False - return - - args.distributed = True - - torch.cuda.set_device(args.gpu) - args.dist_backend = 'nccl' - print('| distributed init (rank {}): {}'.format( - args.rank, args.dist_url), flush=True) - torch.distributed.init_process_group(backend=args.dist_backend, init_method=args.dist_url, - world_size=args.world_size, rank=args.rank) - torch.distributed.barrier() - setup_for_distributed(args.rank == 0) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/environment/__init__.py deleted file mode 100644 index 58784db7..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -def get_environment(env_type): - if env_type == 'AlfredTWEnv': - from agent_system.environments.env_package.alfworld.alfworld.agents.environment.alfred_tw_env import AlfredTWEnv - return AlfredTWEnv - elif env_type == 'AlfredThorEnv': - from agent_system.environments.env_package.alfworld.alfworld.agents.environment.alfred_thor_env import AlfredThorEnv - return AlfredThorEnv - elif env_type == 'AlfredHybrid': - from agent_system.environments.env_package.alfworld.alfworld.agents.environment.alfred_hybrid import AlfredHybrid - return AlfredHybrid - else: - raise NotImplementedError(f"Environment {env_type} is not implemented.") diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_hybrid.py b/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_hybrid.py deleted file mode 100644 index c7455578..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_hybrid.py +++ /dev/null @@ -1,59 +0,0 @@ -import random - -from alfworld.agents.environment.alfred_thor_env import AlfredThorEnv -from alfworld.agents.environment.alfred_tw_env import AlfredTWEnv - - -class AlfredHybrid(object): - ''' - Hybrid training manager for switching between AlfredTWEnv and AlfredThorEnv - ''' - - def __init__(self, config, train_eval="train"): - print("Setting up AlfredHybrid env") - self.hybrid_start_eps = config["env"]["hybrid"]["start_eps"] - self.hybrid_thor_prob = config["env"]["hybrid"]["thor_prob"] - - self.config = config - self.train_eval = train_eval - - self.curr_env = "tw" - self.eval_mode = config["env"]["hybrid"]["eval_mode"] - self.num_resets = 0 - - def choose_env(self): - if self.curr_env == "thor": - return self.thor - else: - return self.tw - - def init_env(self, batch_size): - alfred_tw_env = AlfredTWEnv(self.config, train_eval=self.train_eval) - alfred_thor_env = AlfredThorEnv(self.config, train_eval=self.train_eval) - - self.batch_size = batch_size - self.tw = alfred_tw_env.init_env(batch_size) - self.thor = alfred_thor_env.init_env(batch_size) - return self - - def seed(self, num): - env = self.choose_env() - return env.seed(num) - - def step(self, actions): - env = self.choose_env() - return env.step(actions) - - def reset(self): - if "eval" in self.train_eval: - assert(self.eval_mode in ['tw', 'thor']) - self.curr_env = self.eval_mode - else: - if self.num_resets >= self.hybrid_start_eps: - self.curr_env = "thor" if random.random() < self.hybrid_thor_prob else "tw" - else: - self.curr_env = "tw" - env = self.choose_env() - obs, infos = env.reset() - self.num_resets += self.batch_size - return obs, infos diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_thor_env.py b/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_thor_env.py deleted file mode 100644 index 01177c0b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_thor_env.py +++ /dev/null @@ -1,377 +0,0 @@ -import os -import json -import numpy as np - -import traceback -import threading -from queue import Queue -from threading import Thread -import random - -import alfworld.agents -from alfworld.agents.utils.misc import get_templated_task_desc -from alfworld.env.thor_env import ThorEnv -from alfworld.agents.expert import HandCodedThorAgent, HandCodedAgentTimeout -from alfworld.agents.detector.mrcnn import load_pretrained_model -from alfworld.agents.controller import OracleAgent, OracleAStarAgent, MaskRCNNAgent, MaskRCNNAStarAgent - - -TASK_TYPES = {1: "pick_and_place_simple", - 2: "look_at_obj_in_light", - 3: "pick_clean_then_place_in_recep", - 4: "pick_heat_then_place_in_recep", - 5: "pick_cool_then_place_in_recep", - 6: "pick_two_obj_and_place"} - - -class AlfredThorEnv(object): - ''' - Interface for Embodied (THOR) environment - ''' - - class Thor(threading.Thread): - def __init__(self, queue, train_eval="train"): - Thread.__init__(self) - self.action_queue = queue - self.mask_rcnn = None - self.env = None - self.train_eval = train_eval - self.controller_type = "oracle" - - def run(self): - while True: - action, reset, task_file = self.action_queue.get() - try: - if reset: - self.reset(task_file) - else: - self.step(action) - finally: - self.action_queue.task_done() - - def init_env(self, config): - self.config = config - - screen_height = config['env']['thor']['screen_height'] - screen_width = config['env']['thor']['screen_width'] - smooth_nav = config['env']['thor']['smooth_nav'] - save_frames_to_disk = config['env']['thor']['save_frames_to_disk'] - - if not self.env: - self.env = ThorEnv(player_screen_height=screen_height, - player_screen_width=screen_width, - smooth_nav=smooth_nav, - save_frames_to_disk=save_frames_to_disk) - self.controller_type = self.config['controller']['type'] - self._done = False - self._res = () - self._feedback = "" - self.expert = HandCodedThorAgent(self.env, max_steps=200) - self.prev_command = "" - self.load_mask_rcnn() - - def load_mask_rcnn(self): - # load pretrained MaskRCNN model if required - if 'mrcnn' in self.config['controller']['type'] and not self.mask_rcnn: - model_path = os.path.expandvars(self.config['mask_rcnn']['pretrained_model_path']) - self.mask_rcnn = load_pretrained_model(model_path) - - def set_task(self, task_file): - self.task_file = task_file - self.traj_root = os.path.dirname(task_file) - with open(task_file, 'r') as f: - self.traj_data = json.load(f) - - def reset(self, task_file): - assert self.env - assert self.controller_type - - self.set_task(task_file) - - # scene setup - scene_num = self.traj_data['scene']['scene_num'] - object_poses = self.traj_data['scene']['object_poses'] - dirty_and_empty = self.traj_data['scene']['dirty_and_empty'] - object_toggles = self.traj_data['scene']['object_toggles'] - scene_name = 'FloorPlan%d' % scene_num - self.env.reset(scene_name) - self.env.restore_scene(object_poses, object_toggles, dirty_and_empty) - - # recording - save_frames_path = self.config['env']['thor']['save_frames_path'] - self.env.save_frames_path = os.path.join(save_frames_path, self.traj_root.replace('../', '')) - - # initialize to start position - self.env.step(dict(self.traj_data['scene']['init_action'])) # print goal instr - task_desc = get_templated_task_desc(self.traj_data) - print("Task: %s" % task_desc) - # print("Task: %s" % (self.traj_data['turk_annotations']['anns'][0]['task_desc'])) - - # setup task for reward - class args: pass - args.reward_config = os.path.join(alfworld.agents.__path__[0], 'config/rewards.json') - self.env.set_task(self.traj_data, args, reward_type='dense') - - # set controller - self.controller_type = self.config['controller']['type'] - self.goal_desc_human_anns_prob = self.config['env']['goal_desc_human_anns_prob'] - load_receps = self.config['controller']['load_receps'] - debug = self.config['controller']['debug'] - - if self.controller_type == 'oracle': - self.controller = OracleAgent(self.env, self.traj_data, self.traj_root, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=self.goal_desc_human_anns_prob) - elif self.controller_type == 'oracle_astar': - self.controller = OracleAStarAgent(self.env, self.traj_data, self.traj_root, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=self.goal_desc_human_anns_prob) - elif self.controller_type == 'mrcnn': - self.controller = MaskRCNNAgent(self.env, self.traj_data, self.traj_root, - pretrained_model=self.mask_rcnn, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=self.goal_desc_human_anns_prob, - save_detections_to_disk=self.env.save_frames_to_disk, save_detections_path=self.env.save_frames_path) - elif self.controller_type == 'mrcnn_astar': - self.controller = MaskRCNNAStarAgent(self.env, self.traj_data, self.traj_root, - pretrained_model=self.mask_rcnn, - load_receps=load_receps, debug=debug, - goal_desc_human_anns_prob=self.goal_desc_human_anns_prob, - save_detections_to_disk=self.env.save_frames_to_disk, save_detections_path=self.env.save_frames_path) - else: - raise NotImplementedError() - - # zero steps - self.steps = 0 - - # reset expert state - self.expert.reset(task_file) - self.prev_command = "" - - # return intro text - self._feedback = self.controller.feedback - self._res = self.get_info() - - return self._feedback - - def step(self, action): - if not self._done: - # take action - self.prev_command = str(action) - self._feedback = self.controller.step(action) - self._res = self.get_info() - if self.env.save_frames_to_disk: - self.record_action(action) - self.steps += 1 - - def get_results(self): - return self._res - - def record_action(self, action): - txt_file = os.path.join(self.env.save_frames_path, 'action.txt') - with open(txt_file, 'a+') as f: - f.write("%s\r\n" % str(action)) - - def get_info(self): - won = self.env.get_goal_satisfied() - pcs = self.env.get_goal_conditions_met() - goal_condition_success_rate = pcs[0] / float(pcs[1]) - acs = self.controller.get_admissible_commands() - - # expert action - if self.train_eval == "train": - game_state = { - 'admissible_commands': acs, - 'feedback': self._feedback, - 'won': won - } - expert_actions = ["look"] - try: - if not self.prev_command: - self.expert.observe(game_state['feedback']) - else: - next_action = self.expert.act(game_state, 0, won, self.prev_command) - if next_action in acs: - expert_actions = [next_action] - except HandCodedAgentTimeout: - print("Expert Timeout") - except Exception as e: - print(e) - traceback.print_exc() - else: - expert_actions = [] - - training_method = self.config["general"]["training_method"] - if training_method == "dqn": - max_nb_steps_per_episode = self.config["rl"]["training"]["max_nb_steps_per_episode"] - elif training_method == "dagger": - max_nb_steps_per_episode = self.config["dagger"]["training"]["max_nb_steps_per_episode"] - else: - raise NotImplementedError - self._done = won or self.steps > max_nb_steps_per_episode - return (self._feedback, self._done, acs, won, goal_condition_success_rate, expert_actions) - - def get_last_frame(self): - return self.env.last_event.frame[:,:,::-1] - - def get_exploration_frames(self): - return self.controller.get_exploration_frames() - - def __init__(self, config, train_eval="train"): - print("Initialize AlfredThorEnv...") - self.config = config - self.train_eval = train_eval - self.random_seed = 123 - self.batch_size = 1 - self.envs = [] - self.action_queues = [] - self.get_env_paths() - - def close(self): - for env in self.envs: - env.env.stop() - - def seed(self, seed): - self.random_seed = seed - - def get_env_paths(self): - self.json_file_list = [] - - if self.train_eval == "train": - data_path = os.path.expandvars(self.config['dataset']['data_path']) - elif self.train_eval == "eval_in_distribution": - data_path = os.path.expandvars(self.config['dataset']['eval_id_data_path']) - elif self.train_eval == "eval_out_of_distribution": - data_path = os.path.expandvars(self.config['dataset']['eval_ood_data_path']) - else: - raise Exception("Invalid split. Must be either train or eval") - - # get task types - assert len(self.config['env']['task_types']) > 0 - task_types = [] - for tt_id in self.config['env']['task_types']: - if tt_id in TASK_TYPES: - task_types.append(TASK_TYPES[tt_id]) - - for root, dirs, files in os.walk(data_path, topdown=False): - if 'traj_data.json' in files: - # Skip movable and slice objects object tasks - if 'movable' in root or 'Sliced' in root: - continue - - # File paths - json_path = os.path.join(root, 'traj_data.json') - game_file_path = os.path.join(root, "game.tw-pddl") - - # Load trajectory file - with open(json_path, 'r') as f: - traj_data = json.load(f) - - # Check for any task_type constraints - if not traj_data['task_type'] in task_types: - continue - - self.json_file_list.append(json_path) - - # # Only add solvable games - # if os.path.exists(game_file_path): - # with open(game_file_path, 'r') as f: - # gamedata = json.load(f) - # - # if 'solvable' in gamedata and gamedata['solvable']: - # self.json_file_list.append(json_path) - - print("Overall we have %s games..." % (str(len(self.json_file_list)))) - self.num_games = len(self.json_file_list) - - if self.train_eval == "train": - num_train_games = self.config['dataset']['num_train_games'] if self.config['dataset']['num_train_games'] > 0 else len(self.json_file_list) - self.json_file_list = self.json_file_list[:num_train_games] - self.num_games = len(self.json_file_list) - print("Training with %d games" % (len(self.json_file_list))) - else: - num_eval_games = self.config['dataset']['num_eval_games'] if self.config['dataset']['num_eval_games'] > 0 else len(self.json_file_list) - self.json_file_list = self.json_file_list[:num_eval_games] - self.num_games = len(self.json_file_list) - print("Evaluating with %d games" % (len(self.json_file_list))) - - def init_env(self, batch_size): - self.get_env_paths() - self.batch_size = batch_size - self.action_queues = [] - self.task_order = [""] * self.batch_size - for n in range(self.batch_size): - queue = Queue() - env = self.Thor(queue, self.train_eval) - self.action_queues.append(queue) - self.envs.append(env) - env.daemon = True - env.start() - env.init_env(self.config) - return self - - def reset(self): - # set tasks - batch_size = self.batch_size - # reset envs - - if self.train_eval == 'train': - tasks = random.sample(self.json_file_list, k=batch_size) - else: - if len(self.json_file_list)-batch_size > batch_size: - tasks = [self.json_file_list.pop(random.randrange(len(self.json_file_list))) for _ in range(batch_size)] - else: - tasks = random.sample(self.json_file_list, k=batch_size) - self.get_env_paths() - - for n in range(batch_size): - self.action_queues[n].put((None, True, tasks[n])) - - obs, dones, infos = self.wait_and_get_info() - return obs, infos - - def step(self, actions): - ''' - executes actions in parallel and waits for all env to finish - ''' - - batch_size = self.batch_size - for n in range(batch_size): - self.action_queues[n].put((actions[n], False, "")) - - obs, dones, infos = self.wait_and_get_info() - return obs, None, dones, infos - - def wait_and_get_info(self): - obs, dones, admissible_commands, wons, gamefiles, expert_plans, gc_srs = [], [], [], [], [], [], [] - - # wait for all threads - for n in range(self.batch_size): - self.action_queues[n].join() - feedback, done, acs, won, gc_sr, expert_actions = self.envs[n].get_results() - obs.append(feedback) - dones.append(done) - admissible_commands.append(acs) - wons.append(won) - gc_srs.append(gc_sr) - gamefiles.append(self.envs[n].traj_root) - expert_plans.append(expert_actions) - - infos = {'admissible_commands': admissible_commands, - 'won': wons, - 'goal_condition_success_rate': gc_srs, - 'extra.gamefile': gamefiles, - 'extra.expert_plan': expert_plans} - return obs, dones, infos - - def get_frames(self): - images = [] - for n in range(self.batch_size): - images.append(self.envs[n].get_last_frame()) - return np.array(images) - - def get_exploration_frames(self): - images = [] - for n in range(self.batch_size): - images.append(self.envs[n].get_exploration_frames()) - return images diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_tw_env.py b/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_tw_env.py deleted file mode 100644 index 72ada5f7..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/environment/alfred_tw_env.py +++ /dev/null @@ -1,280 +0,0 @@ -import os -import json -import random - -from tqdm import tqdm -from termcolor import colored - -import textworld -import textworld.agents -import textworld.gym - -from alfworld.agents.utils.misc import Demangler, add_task_to_grammar -from alfworld.agents.expert import HandCodedTWAgent, HandCodedAgentTimeout - - -TASK_TYPES = {1: "pick_and_place_simple", - 2: "look_at_obj_in_light", - 3: "pick_clean_then_place_in_recep", - 4: "pick_heat_then_place_in_recep", - 5: "pick_cool_then_place_in_recep", - 6: "pick_two_obj_and_place"} - - -class AlfredDemangler(textworld.core.Wrapper): - - def __init__(self, *args, shuffle=False, **kwargs): - super().__init__(*args, **kwargs) - self.shuffle = shuffle - - def load(self, *args, **kwargs): - super().load(*args, **kwargs) - - demangler = Demangler(game_infos=self._entity_infos, shuffle=self.shuffle) - for info in self._entity_infos.values(): - info.name = demangler.demangle_alfred_name(info.id) - - -class AlfredInfos(textworld.core.Wrapper): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self._gamefile = None - - def load(self, *args, **kwargs): - super().load(*args, **kwargs) - self._gamefile = args[0] - - def reset(self, *args, **kwargs): - state = super().reset(*args, **kwargs) - state["extra.gamefile"] = self._gamefile - return state - - -# Enum for the supported types of AlfredExpert. -class AlfredExpertType: - HANDCODED = "handcoded" - PLANNER = "planner" - - -class AlfredExpert(textworld.core.Wrapper): - - def __init__(self, env=None, expert_type=AlfredExpertType.HANDCODED): - super().__init__(env=env) - - self.expert_type = expert_type - self.prev_command = "" - if expert_type not in (AlfredExpertType.HANDCODED, AlfredExpertType.PLANNER): - msg = "Unknown type of AlfredExpert: {}.\nExpecting either '{}' or '{}'." - msg = msg.format(expert_type, AlfredExpertType.HANDCODED, AlfredExpertType.PLANNER) - raise ValueError(msg) - - def _gather_infos(self): - # Compute expert plan. - if self.expert_type == AlfredExpertType.HANDCODED: - self.state["extra.expert_plan"] = ["look"] - try: - # initialization - if not self.prev_command: - self._handcoded_expert.observe(self.state["feedback"]) - else: - handcoded_expert_next_action = self._handcoded_expert.act(self.state, 0, self.state["won"], self.prev_command) - if handcoded_expert_next_action in self.state["admissible_commands"]: - self.state["extra.expert_plan"] = [handcoded_expert_next_action] - except HandCodedAgentTimeout: - raise Exception("Timeout") - elif self.expert_type == AlfredExpertType.PLANNER: - self.state["extra.expert_plan"] = self.state["policy_commands"] - else: - raise NotImplementedError("Unknown type of AlfredExpert: {}.".format(self.expert_type)) - - def load(self, gamefile): - super().load(gamefile) - self.gamefile = gamefile - self.request_infos.policy_commands = self.request_infos.policy_commands or (self.expert_type == AlfredExpertType.PLANNER) - self.request_infos.facts = self.request_infos.facts or (self.expert_type == AlfredExpertType.HANDCODED) - self._handcoded_expert = HandCodedTWAgent(max_steps=200) - - def step(self, command): - self.state, reward, done = super().step(command) - self.prev_command = str(command) - self._gather_infos() - return self.state, reward, done - - def reset(self): - self.state = super().reset() - self._handcoded_expert.reset(self.gamefile) - self.prev_command = "" - self._gather_infos() - return self.state - - -class AlfredTWEnv(object): - ''' - Interface for Textworld Env - ''' - - def __init__(self, config, train_eval="train"): - print("Initializing AlfredTWEnv...") - self.config = config - self.train_eval = train_eval - - if config["env"]["goal_desc_human_anns_prob"] > 0: - msg = ("Warning! Changing `goal_desc_human_anns_prob` should be done with" - " the script `alfworld-generate`. Ignoring it and loading games as they are.") - print(colored(msg, "yellow")) - - self.collect_game_files() - self.use_expert = False - print(f"use_expert = {self.use_expert}") - def collect_game_files(self, verbose=False): - def log(info): - if verbose: - print(info) - - self.game_files = [] - - if self.train_eval == "train": - data_path = os.path.expandvars(self.config['dataset']['data_path']) - elif self.train_eval == "eval_in_distribution": - data_path = os.path.expandvars(self.config['dataset']['eval_id_data_path']) - elif self.train_eval == "eval_out_of_distribution": - data_path = os.path.expandvars(self.config['dataset']['eval_ood_data_path']) - - log("Collecting solvable games...") - - # get task types - assert len(self.config['env']['task_types']) > 0 - task_types = [] - for tt_id in self.config['env']['task_types']: - if tt_id in TASK_TYPES: - task_types.append(TASK_TYPES[tt_id]) - - count = 0 - for root, dirs, files in tqdm(list(os.walk(data_path, topdown=False))): - if 'traj_data.json' in files: - count += 1 - - # Filenames - json_path = os.path.join(root, 'traj_data.json') - game_file_path = os.path.join(root, "game.tw-pddl") - - if 'movable' in root or 'Sliced' in root: - log("Movable & slice trajs not supported %s" % (root)) - continue - - # Get goal description - with open(json_path, 'r') as f: - traj_data = json.load(f) - - # Check for any task_type constraints - if not traj_data['task_type'] in task_types: - log("Skipping task type") - continue - - # Check if a game file exists - if not os.path.exists(game_file_path): - log(f"Skipping missing game! {game_file_path}") - continue - - with open(game_file_path, 'r') as f: - gamedata = json.load(f) - - # Check if previously checked if solvable - if 'solvable' not in gamedata: - print(f"-> Skipping missing solvable key! {game_file_path}") - continue - - if not gamedata['solvable']: - log("Skipping known %s, unsolvable game!" % game_file_path) - continue - - # Add to game file list - self.game_files.append(game_file_path) - - print(f"Overall we have {len(self.game_files)} games in split={self.train_eval}") - self.num_games = len(self.game_files) - - if self.train_eval == "train": - num_train_games = self.config['dataset']['num_train_games'] if self.config['dataset']['num_train_games'] > 0 else len(self.game_files) - self.game_files = self.game_files[:num_train_games] - self.num_games = len(self.game_files) - print("Training with %d games" % (len(self.game_files))) - else: - num_eval_games = self.config['dataset']['num_eval_games'] if self.config['dataset']['num_eval_games'] > 0 else len(self.game_files) - self.game_files = self.game_files[:num_eval_games] - self.num_games = len(self.game_files) - print("Evaluating with %d games" % (len(self.game_files))) - - def get_game_logic(self): - self.game_logic = { - "pddl_domain": open(os.path.expandvars(self.config['logic']['domain'])).read(), - "grammar": open(os.path.expandvars(self.config['logic']['grammar'])).read() - } - - # use expert to check the game is solvable - def is_solvable(self, env, game_file_path, - random_perturb=True, random_start=10, random_prob_after_state=0.15): - done = False - steps = 0 - trajectory = [] - try: - env.load(game_file_path) - game_state = env.reset() - if env.expert_type == AlfredExpertType.PLANNER: - return game_state["extra.expert_plan"] - - while not done: - expert_action = game_state['extra.expert_plan'][0] - random_action = random.choice(game_state.admissible_commands) - - command = expert_action - if random_perturb: - if steps <= random_start or random.random() < random_prob_after_state: - command = random_action - - game_state, _, done = env.step(command) - trajectory.append(command) - steps += 1 - except Exception as e: - print("Unsolvable: %s (%s)" % (str(e), game_file_path)) - return None - - return trajectory - - def init_env(self, batch_size): - domain_randomization = self.config["env"]["domain_randomization"] - if self.train_eval != "train": - domain_randomization = False - - alfred_demangler = AlfredDemangler(shuffle=domain_randomization) - wrappers = [alfred_demangler, AlfredInfos] - - # Register a new Gym environment. - request_infos = textworld.EnvInfos(won=True, admissible_commands=True, extras=["gamefile"]) - expert_type = self.config["env"]["expert_type"] - training_method = self.config["general"]["training_method"] - - if training_method == "dqn": - max_nb_steps_per_episode = self.config["rl"]["training"]["max_nb_steps_per_episode"] - elif training_method == "dagger": - max_nb_steps_per_episode = self.config["dagger"]["training"]["max_nb_steps_per_episode"] - if self.use_expert: - expert_plan = True if self.train_eval == "train" else False - else: - expert_plan = False - if expert_plan: - wrappers.append(AlfredExpert(expert_type)) - request_infos.extras.append("expert_plan") - - else: - raise NotImplementedError - - env_id = textworld.gym.register_games(self.game_files, request_infos, - batch_size=batch_size, - asynchronous=True, - max_episode_steps=max_nb_steps_per_episode, - wrappers=wrappers) - # Launch Gym environment. - env = textworld.gym.make(env_id) - return env diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/eval/__init__.py deleted file mode 100644 index 77fcf115..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from alfworld.agents.eval.evaluate_dagger import evaluate_dagger -from alfworld.agents.eval.evaluate_vision_dagger import evaluate_vision_dagger -from alfworld.agents.eval.evaluate_dqn import evaluate_dqn \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dagger.py b/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dagger.py deleted file mode 100644 index cfaa6731..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dagger.py +++ /dev/null @@ -1,170 +0,0 @@ -import copy -import numpy as np -import torch - -import os -import sys - -from alfworld.agents.utils.misc import extract_admissible_commands - - -def evaluate_dagger(env, agent, num_games, debug=False): - env.seed(42) - agent.eval() - episode_no = 0 - res_points, res_steps, res_gcs = [], [], [] - res_info = [] - with torch.no_grad(): - while(True): - if episode_no >= num_games: - break - obs, infos = env.reset() - game_names = infos["extra.gamefile"] - batch_size = len(obs) - if agent.unstick_by_beam_search: - smart = [{"not working": [], "to try": []} for _ in range(batch_size)] - - agent.init(batch_size) - previous_dynamics = None - - execute_actions = [] - prev_step_dones, prev_rewards = [], [] - for _ in range(batch_size): - execute_actions.append("restart") - prev_step_dones.append(0.0) - prev_rewards.append(0.0) - - observation_strings = list(obs) - task_desc_strings, observation_strings = agent.get_task_and_obs(observation_strings) - task_desc_strings = agent.preprocess_task(task_desc_strings) - observation_strings = agent.preprocess_observation(observation_strings) - first_sight_strings = copy.deepcopy(observation_strings) - agent.observation_pool.push_first_sight(first_sight_strings) - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - observation_strings = [item + " [SEP] " + a for item, a in zip(observation_strings, execute_actions)] # appending the chosen action at previous step into the observation - - still_running_mask = [] - sequence_game_points = [] - goal_condition_points = [] - print_actions = [] - report = agent.report_frequency > 0 and (episode_no % agent.report_frequency <= (episode_no - batch_size) % agent.report_frequency) - - if debug: - print(first_sight_strings[0]) - print(task_desc_strings[0]) - - for step_no in range(agent.max_nb_steps_per_episode): - # push obs into observation pool - agent.observation_pool.push_batch(observation_strings) - # get most recent k observations - most_recent_observation_strings = agent.observation_pool.get() - - # predict actions - if agent.action_space == "generation": - # heuristically unstick the agent from generating the same thing over and over again - prev_actions = copy.copy(execute_actions) - if agent.unstick_by_beam_search: - for i in range(batch_size): - if "Nothing happens" in observation_strings[i]: - smart[i]["not working"].append(execute_actions[i]) - - execute_actions, current_dynamics = agent.command_generation_greedy_generation(most_recent_observation_strings, task_desc_strings, previous_dynamics) - - # heuristically unstick the agent from generating the same thing over and over again - if agent.unstick_by_beam_search: - for i in range(batch_size): - if "Nothing happens" in observation_strings[i] and execute_actions[i] in smart[i]["not working"]: - if len(smart[i]["to try"]) == 0: - bs_actions, _ = agent.command_generation_beam_search_generation(most_recent_observation_strings[i: i + 1], task_desc_strings[i: i + 1], None if previous_dynamics is None else previous_dynamics[i: i + 1]) - bs_actions = bs_actions[0] - smart[i]["to try"] += bs_actions - - smart[i]["to try"] = [item for item in smart[i]["to try"] if item != prev_actions[i]] - if len(smart[i]["to try"]) > 0: - execute_actions[i] = smart[i]["to try"][0] - else: - smart[i] = {"not working": [], "to try": []} # reset - - elif agent.action_space in ["admissible", "exhaustive"]: - execute_actions, _, current_dynamics = agent.admissible_commands_greedy_generation(most_recent_observation_strings, task_desc_strings, action_candidate_list, previous_dynamics) - else: - raise NotImplementedError() - - obs, _, dones, infos = env.step(execute_actions) - scores = [float(item) for item in infos["won"]] - gcs =[float(item) for item in infos["goal_condition_success_rate"]] if "goal_condition_success_rate" in infos else [0.0]*batch_size - dones = [float(item) for item in dones] - - if debug: - print(execute_actions[0]) - print(obs[0]) - - observation_strings = list(obs) - observation_strings = agent.preprocess_observation(observation_strings) - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - observation_strings = [item + " [SEP] " + a for item, a in zip(observation_strings, execute_actions)] # appending the chosen action at previous step into the observation - previous_dynamics = current_dynamics - - if step_no == agent.max_nb_steps_per_episode - 1: - # terminate the game because DQN requires one extra step - dones = [1.0 for _ in dones] - - still_running = [1.0 - float(item) for item in prev_step_dones] # list of float - prev_step_dones = dones - step_rewards = [float(curr) - float(prev) for curr, prev in zip(scores, prev_rewards)] # list of float - prev_rewards = scores - sequence_game_points.append(step_rewards) - goal_condition_points.append(gcs) - still_running_mask.append(still_running) - print_actions.append(execute_actions[0] if still_running[0] else "--") - - # if all ended, break - if np.sum(still_running) == 0: - break - - game_steps = np.sum(np.array(still_running_mask), 0).tolist() # batch - game_points = np.max(np.array(sequence_game_points), 0).tolist() # batch - game_gcs = np.max(np.array(goal_condition_points), 0).tolist() # batch - for i in range(batch_size): - if len(res_points) >= num_games: - break - res_points.append(game_points[i]) - res_gcs.append(game_gcs[i]) - res_steps.append(game_steps[i]) - res_info.append("/".join(game_names[i].split("/")[-3:-1]) + ", score: " + str(game_points[i]) + ", step: " + str(game_steps[i])) - - # finish game - agent.finish_of_episode(episode_no, batch_size) - episode_no += batch_size - - if not report: - continue - print("Model: {:s} | Episode: {:3d} | {:s} | game points: {:2.3f} | game goal-condition points: {:2.3f} | game steps: {:2.3f}".format(agent.experiment_tag, episode_no, game_names[0], np.mean(res_points), np.mean(res_gcs), np.mean(res_steps))) - # print(game_id + ": " + " | ".join(print_actions)) - print(" | ".join(print_actions)) - - - average_points, average_gc_points, average_steps = np.mean(res_points), np.mean(res_gcs), np.mean(res_steps) - print("================================================") - print("eval game points: " + str(average_points) + ", eval game goal-condition points : " + str(average_gc_points) + ", eval game steps: " + str(average_steps)) - for item in res_info: - print(item) - - return { - 'average_points': average_points, - 'average_goal_condition_points': average_gc_points, - 'average_steps': average_steps, - 'res_points': res_points, - 'res_gcs': res_gcs, - 'res_steps': res_steps, - 'res_info': res_info - } - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dqn.py b/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dqn.py deleted file mode 100644 index 426b27b1..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_dqn.py +++ /dev/null @@ -1,146 +0,0 @@ -import copy -import numpy as np -import torch - -import os -import sys -from alfworld.agents.utils.misc import extract_admissible_commands - - -def evaluate_dqn(env, agent, num_games, debug=False): - env.seed(42) - agent.eval() - episode_no = 0 - res_points, res_gcs, res_steps = [], [], [] - res_info = [] - with torch.no_grad(): - while(True): - if episode_no >= num_games: - break - - obs, infos = env.reset() - game_names = infos["extra.gamefile"] - batch_size = len(obs) - - agent.init(batch_size) - previous_dynamics = None - - chosen_actions = [] - prev_step_dones, prev_rewards = [], [] - for _ in range(batch_size): - chosen_actions.append("restart") - prev_step_dones.append(0.0) - prev_rewards.append(0.0) - - observation_strings = list(obs) - task_desc_strings, observation_strings = agent.get_task_and_obs(observation_strings) - task_desc_strings = agent.preprocess_task(task_desc_strings) - observation_strings = agent.preprocess_observation(observation_strings) - first_sight_strings = copy.deepcopy(observation_strings) - agent.observation_pool.push_first_sight(first_sight_strings) - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - observation_strings = [item + " [SEP] " + a for item, a in zip(observation_strings, chosen_actions)] # appending the chosen action at previous step into the observation - - still_running_mask = [] - sequence_game_points = [] - goal_condition_points = [] - print_actions = [] - report = agent.report_frequency > 0 and (episode_no % agent.report_frequency <= (episode_no - batch_size) % agent.report_frequency) - - if debug: - print(first_sight_strings[0]) - print(task_desc_strings[0]) - - for step_no in range(agent.max_nb_steps_per_episode): - # push obs into observation pool - agent.observation_pool.push_batch(observation_strings) - # get most recent k observations - most_recent_observation_strings = agent.observation_pool.get() - - # predict actions - if agent.action_space == "generation": - chosen_actions, _, current_dynamics = agent.command_generation_act_greedy(most_recent_observation_strings, task_desc_strings, previous_dynamics) - elif agent.action_space == "beam_search_choice": - chosen_actions, _, current_dynamics, action_candidate_list = agent.beam_search_choice_act_greedy(most_recent_observation_strings, task_desc_strings, previous_dynamics) - elif agent.action_space in ["admissible", "exhaustive"]: - chosen_actions, _, current_dynamics = agent.admissible_commands_act_greedy(most_recent_observation_strings, task_desc_strings, action_candidate_list, previous_dynamics) - else: - raise NotImplementedError() - - obs, _, dones, infos = env.step(chosen_actions) - scores = [float(item) for item in infos["won"]] - dones = [float(item) for item in dones] - gcs = [float(item) for item in infos["goal_condition_success_rate"]] if "goal_condition_success_rate" in infos else [0.0]*batch_size - - if debug: - print(chosen_actions[0]) - print(obs[0]) - - observation_strings = list(obs) - observation_strings = agent.preprocess_observation(observation_strings) - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - observation_strings = [item + " [SEP] " + a for item, a in zip(observation_strings, chosen_actions)] # appending the chosen action at previous step into the observation - previous_dynamics = current_dynamics - - if step_no == agent.max_nb_steps_per_episode - 1: - # terminate the game because DQN requires one extra step - dones = [1.0 for _ in dones] - - still_running = [1.0 - float(item) for item in prev_step_dones] # list of float - prev_step_dones = dones - step_rewards = [float(curr) - float(prev) for curr, prev in zip(scores, prev_rewards)] # list of float - sequence_game_points.append(copy.copy(step_rewards)) - goal_condition_points.append(gcs) - prev_rewards = scores - still_running_mask.append(still_running) - print_actions.append(chosen_actions[0] if still_running[0] else "--") - - # if all ended, break - if np.sum(still_running) == 0: - break - - game_steps = np.sum(np.array(still_running_mask), 0).tolist() # batch - game_points = np.max(sequence_game_points, 0).tolist() # batch - game_gcs = np.max(np.array(goal_condition_points), 0).tolist() # batch - for i in range(batch_size): - if len(res_points) >= num_games: - break - res_points.append(game_points[i]) - res_gcs.append(game_gcs[i]) - res_steps.append(game_steps[i]) - res_info.append("/".join(game_names[i].split("/")[-3:-1]) + ", score: " + str(game_points[i]) + ", step: " + str(game_steps[i])) - - # finish game - agent.finish_of_episode(episode_no, batch_size) - episode_no += batch_size - - if not report: - continue - print("Episode: {:3d} | {:s} | game points: {:2.3f} | game goal-condition points: {:2.3f} | game steps: {:2.3f}".format(episode_no, game_names[0], np.mean(res_points), np.mean(res_gcs), np.mean(res_steps))) - # print(game_id + ": " + " | ".join(print_actions)) - print(" | ".join(print_actions)) - - average_points, average_gc_points, average_steps = np.mean(res_points), np.mean(res_gcs), np.mean(res_steps) - print("================================================") - print("eval game points: " + str(average_points) + ", eval game goal-condition points : " + str(average_gc_points) + ", eval game steps: " + str(average_steps)) - for item in res_info: - print(item) - - return { - 'average_points': average_points, - 'average_goal_condition_points': average_gc_points, - 'average_steps': average_steps, - 'res_points': res_points, - 'res_gcs': res_gcs, - 'res_steps': res_steps, - 'res_info': res_info - } - diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_vision_dagger.py b/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_vision_dagger.py deleted file mode 100644 index c18bca70..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/eval/evaluate_vision_dagger.py +++ /dev/null @@ -1,144 +0,0 @@ -import copy -import numpy as np -import torch - -import os -import sys -from alfworld.agents.utils.misc import extract_admissible_commands - - -def evaluate_vision_dagger(env, agent, num_games, debug=False): - env.seed(42) - agent.eval() - episode_no = 0 - res_points, res_steps, res_gcs = [], [], [] - res_info = [] - with torch.no_grad(): - while(True): - if episode_no >= num_games: - break - obs, infos = env.reset() - game_names = infos["extra.gamefile"] - batch_size = len(obs) - - agent.init(batch_size) - previous_dynamics = None - - execute_actions = [] - prev_step_dones, prev_rewards = [], [] - for _ in range(batch_size): - execute_actions.append("restart") - prev_step_dones.append(0.0) - prev_rewards.append(0.0) - - observation_strings = list(obs) - observation_strings = agent.preprocess_observation(observation_strings) - task_desc_strings, observation_strings = agent.get_task_and_obs(observation_strings) - first_sight_strings = copy.deepcopy(observation_strings) - agent.observation_pool.push_first_sight(first_sight_strings) - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - - # extract exploration frame features - if agent.use_exploration_frame_feats: - exploration_frames = env.get_exploration_frames() - exploration_frame_feats = agent.extract_exploration_frame_feats(exploration_frames) - - if debug: - print(first_sight_strings[0]) - print(task_desc_strings[0]) - - still_running_mask = [] - sequence_game_points = [] - goal_condition_points = [] - print_actions = [] - report = agent.report_frequency > 0 and (episode_no % agent.report_frequency <= (episode_no - batch_size) % agent.report_frequency) - - for step_no in range(agent.max_nb_steps_per_episode): - # get visual features - current_frames = env.get_frames() - observation_feats = agent.extract_visual_features(current_frames) - - # add exploration features if specified - if agent.use_exploration_frame_feats: - observation_feats = [torch.cat([ef, obs], dim=0) for ef, obs in zip(exploration_frame_feats, observation_feats)] - - # predict actions - if agent.action_space == "generation": - execute_actions, current_dynamics = agent.command_generation_greedy_generation(observation_feats, task_desc_strings, previous_dynamics) - else: - raise NotImplementedError() - - obs, _, dones, infos = env.step(execute_actions) - scores = [float(item) for item in infos["won"]] - gcs =[float(item) for item in infos["goal_condition_success_rate"]] if "goal_condition_success_rate" in infos else [0.0]*batch_size - dones = [float(item) for item in dones] - - if debug: - print(execute_actions[0]) - print(obs[0]) - - if agent.action_space == "exhaustive": - action_candidate_list = [extract_admissible_commands(intro, obs) for intro, obs in zip(first_sight_strings, observation_strings)] - else: - action_candidate_list = list(infos["admissible_commands"]) - action_candidate_list = agent.preprocess_action_candidates(action_candidate_list) - previous_dynamics = current_dynamics - - if step_no == agent.max_nb_steps_per_episode - 1: - # terminate the game because DQN requires one extra step - dones = [1.0 for _ in dones] - - still_running = [1.0 - float(item) for item in prev_step_dones] # list of float - prev_step_dones = dones - step_rewards = [float(curr) - float(prev) for curr, prev in zip(scores, prev_rewards)] # list of float - prev_rewards = scores - sequence_game_points.append(step_rewards) - goal_condition_points.append(gcs) - still_running_mask.append(still_running) - print_actions.append(execute_actions[0] if still_running[0] else "--") - - # if all ended, break - if np.sum(still_running) == 0: - break - - game_steps = np.sum(np.array(still_running_mask), 0).tolist() # batch - game_points = np.max(np.array(sequence_game_points), 0).tolist() # batch - game_gcs = np.max(np.array(goal_condition_points), 0).tolist() # batch - for i in range(batch_size): - if len(res_points) >= num_games: - break - res_points.append(game_points[i]) - res_gcs.append(game_gcs[i]) - res_steps.append(game_steps[i]) - res_info.append("/".join(game_names[i].split("/")[-3:-1]) + ", score: " + str(game_points[i]) + ", step: " + str(game_steps[i])) - - # finish game - agent.finish_of_episode(episode_no, batch_size) - episode_no += batch_size - - if not report: - continue - print("Model: {:s} | Episode: {:3d} | {:s} | game points: {:2.3f} | game goal-condition points: {:2.3f} | game steps: {:2.3f}".format(agent.experiment_tag, episode_no, game_names[0], np.mean(res_points), np.mean(res_gcs), np.mean(res_steps))) - # print(game_id + ": " + " | ".join(print_actions)) - print(" | ".join(print_actions)) - - - average_points, average_gc_points, average_steps = np.mean(res_points), np.mean(res_gcs), np.mean(res_steps) - print("================================================") - print("eval game points: " + str(average_points) + ", eval game goal-condition points : " + str(average_gc_points) + ", eval game steps: " + str(average_steps)) - for item in res_info: - print(item) - - return { - 'average_points': average_points, - 'average_goal_condition_points': average_gc_points, - 'average_steps': average_steps, - 'res_points': res_points, - 'res_gcs': res_gcs, - 'res_steps': res_steps, - 'res_info': res_info - } diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/expert/__init__.py deleted file mode 100644 index 110b7c57..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from alfworld.agents.expert.handcoded_expert import HandCodedAgentTimeout, HandCodedAgentFailed -from alfworld.agents.expert.handcoded_expert_tw import HandCodedTWAgent -from alfworld.agents.expert.handcoded_expert_thor import HandCodedThorAgent \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert.py b/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert.py deleted file mode 100644 index 9fa8c3d8..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert.py +++ /dev/null @@ -1,570 +0,0 @@ -import os -import re -import sys -import json -import random -from textworld import Agent - -import alfworld.gen.constants as constants - -class HandCodedAgentTimeout(NameError): - pass - -class HandCodedAgentFailed(NameError): - pass - -class BasePolicy(object): - - # Object and affordance priors - OBJECTS = constants.OBJECTS_SINGULAR - RECEPTACLES = [r.lower() for r in constants.RECEPTACLES] - OPENABLE_OBJECTS = [o.lower() for o in constants.OPENABLE_CLASS_LIST] - VAL_RECEPTACLE_OBJECTS = dict((r.lower(), [o.lower() for o in objs]) for r, objs in constants.VAL_RECEPTACLE_OBJECTS.items()) - OBJECT_TO_VAL_RECEPTACLE = dict((o, list()) for o in OBJECTS) - for o in constants.OBJECTS: - for r, os in constants.VAL_RECEPTACLE_OBJECTS.items(): - if o in os: - OBJECT_TO_VAL_RECEPTACLE[o.lower()].append(r.lower()) - - def __init__(self, task_params, max_steps=150): - self.max_steps = max_steps - self.task_params = task_params - self.subgoals = [ - {'action': "look", 'param': ""} - ] - # receptacle - self.receptacles = {} - self.visible_objects = {} - self.obj_cls_to_receptacle_map = {} - - # state memory - self.subgoal_idx = 0 - self.curr_recep = "" - self.checked_inside_curr_recep = False - self.receptacles_to_check = [] - self.inventory = [] - self.obs_at_recep = {} - self.got_inventory_from_recep = "" - self.action_backlog = [] - self.object_blacklist = [] - self.receptacle_whitelist = [] - self.steps = 0 - self.is_agent_holding_right_object = False - - def get_objects_and_classes(self, obs): - obj_str = re.split("you see", obs, flags=re.IGNORECASE)[-1].replace(" and a ", "").replace(" a ", "").split("Your task is to", 1)[0].strip(".,\n\r") - objects_with_ids = obj_str.split(",") - return dict((o, self.object_id_to_cls(o)) for o in objects_with_ids) - - def object_id_to_cls(self, object_hash, special_char=' '): - return object_hash.split(special_char)[0] - - def remove_num_ids(self, str): - return ' '.join(''.join(i for i in str if not i.isdigit()).split()) - - def get_list_of_objects_of_class(self, obj_cls, obj_dict): - return [name for name, cls in obj_dict.items() if cls == obj_cls] - - def get_next_subgoal(self): - subgoal = self.subgoals[self.subgoal_idx] - sub_action, sub_param = subgoal['action'], subgoal['param'] - objs_of_interest = self.get_list_of_objects_of_class(sub_param, self.visible_objects) - - # special case: check if bathbasin should be used instead of sinkbasin - if sub_param == 'sinkbasin' and not any('sinkbasin' in r for r in self.receptacles.values()): - sub_param = "bathtubbasin" - - return sub_action, sub_param, objs_of_interest - - def get_list_of_receptacles_to_search_for_object_cls(self, obj_cls): - obj_found_in_receps = self.OBJECT_TO_VAL_RECEPTACLE[obj_cls] - return [r_name for r_name, r_cls in self.receptacles.items() if r_cls in obj_found_in_receps] - - def get_list_of_receptacles_of_type(self, recep_cls): - return [r_name for r_name, r_cls in self.receptacles.items() if r_cls == recep_cls] - - def is_receptacle_openable(self, recep): - return recep and recep in self.receptacles and self.receptacles[recep] in self.OPENABLE_OBJECTS - - def is_already_at_receptacle(self, sub_param): - return (sub_param in self.obj_cls_to_receptacle_map and self.curr_recep == self.obj_cls_to_receptacle_map[sub_param]) or \ - (self.curr_recep in self.receptacles and self.receptacles[self.curr_recep] == sub_param) - - def is_blacklisted_object_in_visible_objects(self, visible_objects): - return len(list(set().union(visible_objects, self.object_blacklist))) > 0 - - def is_obj_cls_in_inventory(self, obj_cls): - return len(self.inventory) > 0 and obj_cls in self.object_id_to_cls(self.inventory[0]) - - def blacklist_obj(self, obj): - obj_cls = self.object_id_to_cls(obj) - if obj_cls in self.obj_cls_to_receptacle_map: - del self.obj_cls_to_receptacle_map[obj_cls] - if obj in self.visible_objects: - del self.visible_objects[obj] - if self.curr_recep in self.obs_at_recep: - self.obs_at_recep[self.curr_recep] = self.obs_at_recep[self.curr_recep].replace(obj, "") - - def check_subgoal_completion(self, game_state): - subgoal_idx = 0 - return subgoal_idx - - def get_facts(self, game_state): - facts = [f"{fact.name} " + " ".join(name.strip() for name in fact.names) for fact in game_state["facts"]] - return facts - - def get_state_info(self, game_state): - facts = self.get_facts(game_state) - facts_wo_num_ids = [self.remove_num_ids(f) for f in facts] - - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - return facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids - - def observe(self, obs): - if "Welcome" in obs: # intro text with receptacles - self.receptacles = self.get_objects_and_classes(obs) - else: - # get the objects which are visible in the current frame - if "you see nothing" in obs: - self.visible_objects = dict() - elif "you see" in obs: - if "You open the" in obs: - curr_recep = " ".join(obs.split("You open the", 1)[-1].split()[:2]).strip(",.") - elif "is open." in obs: - curr_recep = " ".join(obs.split("is open.", 1)[0].split()[-2:]).strip(",.") - else: - curr_recep = " ".join(obs.split("On the", 1)[-1].split()[:2]).strip(",.") - - self.visible_objects = self.get_objects_and_classes(obs) - self.obs_at_recep[curr_recep] = str(obs) - - # ignore blacklisted object - for obj in self.object_blacklist: - if obj in self.visible_objects: - del self.visible_objects[obj] - - # keep track of where all the objects are - for o_name, o_cls in self.visible_objects.items(): - self.obj_cls_to_receptacle_map[o_cls] = curr_recep - - def update_state_tracking(self, game_state, last_action): - obs = game_state['feedback'] - was_last_action_successful = "Nothing happens" not in obs - - if "go to" in last_action: - went_to_receptacle = last_action.replace("go to", "").strip() - self.curr_recep = str(went_to_receptacle) - if went_to_receptacle in self.receptacles_to_check: - self.receptacles_to_check.remove(went_to_receptacle) - self.checked_inside_curr_recep = (not self.is_receptacle_openable(self.curr_recep)) or "open" in obs - - if was_last_action_successful: - if "open" in last_action: - open_curr_recep_str = "open {}".format(self.curr_recep) - if open_curr_recep_str == last_action: - self.checked_inside_curr_recep = True - self.action_backlog.append("close {}".format(self.curr_recep)) - elif "close" in last_action: - close_curr_recep_str = "close {}".format(self.curr_recep) - if close_curr_recep_str == last_action: - if close_curr_recep_str in self.action_backlog: - self.action_backlog.remove(close_curr_recep_str) - elif "take" in last_action: - inv_obj = " ".join(last_action.split()[1:3]) - self.got_inventory_from_recep = " ".join(last_action.split()[-2:]) - self.inventory.append(inv_obj) - self.blacklist_obj(inv_obj) - elif "put" in last_action: - inv_obj = self.inventory.pop() - self.got_inventory_from_recep = "" - self.blacklist_obj(inv_obj) - if self.task_params['object_target'] in last_action: - self.object_blacklist.append(inv_obj) - - def act(self, game_state, last_action): - obs = game_state['feedback'] - self.steps += 1 - - # timeout - if self.steps > self.max_steps: - raise HandCodedAgentTimeout() - - # finished all subgoals but still didn't achieve the goal - elif self.subgoal_idx >= len(self.subgoals): - while len(self.action_backlog) > 0: - return self.action_backlog.pop() - raise HandCodedAgentFailed() - - # update state tracking - self.update_state_tracking(game_state, last_action) - - # update observations - self.observe(obs) - - # get subgoal - self.subgoal_idx = self.check_subgoal_completion(game_state) - sub_action, sub_param, objs_of_interest = self.get_next_subgoal() - - # FIND - if sub_action == 'find': - # done criteria - if len(objs_of_interest) > 0 or (self.is_already_at_receptacle(sub_param) and self.checked_inside_curr_recep) and (len(self.inventory) == 0 or (len(self.inventory) > 0 and self.is_agent_holding_right_object)): - self.receptacles_to_check = [] - self.action_backlog = [] - else: - # saw the obj class somewhere before - if sub_param in self.obj_cls_to_receptacle_map: - self.receptacles_to_check = [self.obj_cls_to_receptacle_map[sub_param]] - # use heuristic to determine which receptacle to check - elif len(self.receptacles_to_check) == 0: - if sub_param in self.RECEPTACLES: - self.receptacles_to_check = self.get_list_of_receptacles_of_type(sub_param) - else: - self.receptacles_to_check = self.get_list_of_receptacles_to_search_for_object_cls(sub_param) - - # in case priors don't work - self.receptacles_to_check = [r for r in list(self.receptacles.keys()) if r not in self.receptacles_to_check] + self.receptacles_to_check - - # still no idea where to look? look at all receptacles (necessary?) - if len(self.receptacles_to_check) == 0: - self.receptacles_to_check = list(self.receptacles.keys()) - - if self.curr_recep in self.receptacles_to_check and self.checked_inside_curr_recep: - self.receptacles_to_check.remove(self.curr_recep) - - # if holding something irrelavant, then discard it from where it was pickedup - if len(self.inventory) > 0 and not self.is_agent_holding_right_object: - if self.curr_recep == self.got_inventory_from_recep: - return "move {} to {}".format(self.inventory[0], self.got_inventory_from_recep) - else: - return "go to {}".format(self.got_inventory_from_recep) - - # open the current receptacle if you can - if (sub_param not in self.obj_cls_to_receptacle_map) and "closed" in obs and not self.checked_inside_curr_recep and last_action.split()[0] not in {'heat', 'cool', 'clean', 'slice'}: - return "open {}".format(self.curr_recep) - - # go to next receptacle - else: - if len(self.action_backlog) == 0: - receptacle_to_check = self.receptacles_to_check[-1] - return "go to {}".format(receptacle_to_check) - else: - return self.action_backlog.pop() - - # if find succeded, then no receptacles to check - self.receptacles_to_check = [] - - # GOTO - if sub_action == 'goto': - target_receps = self.get_list_of_receptacles_of_type(sub_param) - return "go to {}".format(target_receps[0]) - - # TAKE - if sub_action == 'take': - if "closed" in obs and not self.checked_inside_curr_recep and len(self.visible_objects) == 0: - return "open {}".format(self.curr_recep) - elif len(self.visible_objects) == 0 or not any(sub_param in o for o in self.visible_objects): - return "examine {}".format(self.curr_recep) - else: - obj = random.choice(objs_of_interest) - return "take {} from {}".format(obj, self.curr_recep) - - # PUT - if sub_action == 'put': - if "closed" in obs and not self.checked_inside_curr_recep: - return "open {}".format(self.curr_recep) - else: - obj = self.inventory[0] - return "move {} to {}".format(obj, self.curr_recep) - - # OPEN - if sub_action == 'open': - return "open {}".format(self.curr_recep) - - # CLOSE - if sub_action == 'close': - return "close {}".format(self.curr_recep) - - # HEAT - if sub_action == 'heat': - inv_obj = self.inventory[0] - return "heat {} with {}".format(inv_obj, self.curr_recep) - - # COOL - if sub_action == 'cool': - inv_obj = self.inventory[0] - return "cool {} with {}".format(inv_obj, self.curr_recep) - - # CLEAN - if sub_action == 'clean': - inv_obj = self.inventory[0] - return "clean {} with {}".format(inv_obj, self.curr_recep) - - # SLICE - if sub_action == 'slice': - if len(self.visible_objects) == 0: - return "examine {}".format(self.curr_recep) - else: - obj = random.choice(objs_of_interest) - knife_obj = self.inventory[0] - return "slice {} with {}".format(obj, knife_obj) - - # USE - if sub_action == 'use': - if len(self.visible_objects) == 0: - return "examine {}".format(self.curr_recep) - else: - obj = random.choice(objs_of_interest) - return "use {}".format(obj) - - # if holding something irrelavant, then discard it from where it was pickedup - if len(self.inventory) > 0 and not self.is_agent_holding_right_object: - if self.curr_recep == self.got_inventory_from_recep: - return "move {} to {}".format(self.inventory[0], self.got_inventory_from_recep) - else: - return "go to {}".format(self.got_inventory_from_recep) - - # examine objects on receptacles by default - if "closed" in obs: - return "open {}".format(self.curr_recep) - else: - examine_cmd = "examine {}".format(self.curr_recep) - return examine_cmd - - -class PickAndPlaceSimplePolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']} - ] - - def check_subgoal_completion(self, game_state): - obj, parent = self.task_params['object_target'], self.task_params['parent_target'] - at_right_recep, can_put_object, can_take_object, is_obj_in_obs = self.get_predicates(game_state, obj, parent) - - if self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-1 - elif self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-3 - else: - return 0 - - def get_predicates(self, game_state, obj, parent): - raise NotImplementedError() - - -class PickTwoObjAndPlacePolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']}, - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']} - ] - - def check_subgoal_completion(self, game_state): - obj, parent = self.task_params['object_target'], self.task_params['parent_target'] - at_right_recep, can_put_object, can_take_object, is_obj_in_obs, is_one_object_already_inside_receptacle, trying_to_take_the_same_object = self.get_predicates(game_state, obj, parent) - - if is_one_object_already_inside_receptacle and self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-1 - elif is_one_object_already_inside_receptacle and self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif is_one_object_already_inside_receptacle and not self.is_agent_holding_right_object and not trying_to_take_the_same_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-3 - elif is_one_object_already_inside_receptacle: - return len(self.subgoals)-4 - elif not is_one_object_already_inside_receptacle and self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-5 - elif not is_one_object_already_inside_receptacle and self.is_agent_holding_right_object: - return len(self.subgoals)-6 - elif not is_one_object_already_inside_receptacle and not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-7 - else: - return 0 - - def get_predicates(self, game_state, obj, parent): - raise NotImplementedError() - -class LookAtObjInLightPolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['toggle_target']}, - {'action': 'use', 'param': self.task_params['toggle_target']} - ] - - def check_subgoal_completion(self, game_state): - obj, toggle = self.task_params['object_target'], self.task_params['toggle_target'] - can_take_object, can_toggle_lamp, is_obj_in_obs = self.get_predicates(game_state, obj, toggle) - - if self.is_agent_holding_right_object and can_toggle_lamp: - return len(self.subgoals)-1 - elif self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-3 - else: - return 0 - - def get_predicates(self, game_state, obj, toggle): - raise NotImplementedError() - - -class PickHeatThenPlaceInRecepPolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'goto', 'param': 'microwave'}, - {'action': 'heat', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']} - ] - - def check_subgoal_completion(self, game_state): - obj, parent = self.task_params['object_target'], self.task_params['parent_target'] - at_right_recep, can_heat_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_hot = self.get_predicates(game_state, obj, parent) - - if is_the_object_agent_holding_hot and self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-1 - elif is_the_object_agent_holding_hot and self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif self.is_agent_holding_right_object and can_heat_object: - return len(self.subgoals)-3 - elif self.is_agent_holding_right_object: - return len(self.subgoals)-4 - elif not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-5 - else: - return 0 - - def get_predicates(self, game_state, obj, parent): - raise NotImplementedError() - - -class PickCoolThenPlaceInRecepPolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'goto', 'param': 'fridge'}, - {'action': 'cool', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']} - ] - - def check_subgoal_completion(self, game_state): - obj, parent = self.task_params['object_target'], self.task_params['parent_target'] - at_right_recep, can_cool_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_cool = self.get_predicates(game_state, obj, parent) - - if is_the_object_agent_holding_cool and self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-1 - elif is_the_object_agent_holding_cool and self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif self.is_agent_holding_right_object and can_cool_object: - return len(self.subgoals)-3 - elif self.is_agent_holding_right_object: - return len(self.subgoals)-4 - elif not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-5 - else: - return 0 - - def get_predicates(self, game_state, obj, parent): - raise NotImplementedError() - -class PickCleanThenPlaceInRecepPolicy(BasePolicy): - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - self.subgoals = [ - {'action': 'find', 'param': self.task_params['object_target']}, - {'action': 'take', 'param': self.task_params['object_target']}, - {'action': 'goto', 'param': 'sinkbasin'}, - {'action': 'clean', 'param': self.task_params['object_target']}, - {'action': 'find', 'param': self.task_params['parent_target']}, - {'action': 'put', 'param': self.task_params['parent_target']} - ] - self.is_agent_holding_right_object = False - - def check_subgoal_completion(self, game_state): - obj, parent = self.task_params['object_target'], self.task_params['parent_target'] - - at_right_recep, can_clean_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_isclean = self.get_predicates( - game_state, obj, parent) - - if is_the_object_agent_holding_isclean and self.is_agent_holding_right_object and can_put_object and at_right_recep: - return len(self.subgoals)-1 - elif is_the_object_agent_holding_isclean and self.is_agent_holding_right_object: - return len(self.subgoals)-2 - elif self.is_agent_holding_right_object and can_clean_object: - return len(self.subgoals)-3 - elif self.is_agent_holding_right_object: - return len(self.subgoals)-4 - elif not self.is_agent_holding_right_object and can_take_object and is_obj_in_obs: - return len(self.subgoals)-5 - else: - return 0 - - def get_predicates(self, game_state, obj, parent): - raise NotImplementedError() - -class HandCodedAgent(Agent): - """ Handcoded expert for solving tasks. Based on a set of heuristics to solve ALFRED tasks. - Not guaranteed to succeed or be optimal""" - - def __init__(self, max_steps=150): - self.max_steps = max_steps - - def get_task_policy(self, task_param): - task_type = task_param['task_type'] - task_class_str = task_type.replace("_", " ").title().replace(" ", '') + "Policy" - if task_class_str in globals(): - return globals()[task_class_str] - else: - raise Exception("Invalid Task Type: %s" % task_type) - - def reset(self, game="INVALID"): - traj_data_file = os.path.join(os.path.dirname(game), 'traj_data.json') - with open(traj_data_file, 'r') as f: - traj_data = json.load(f) - - self.task_params = {**traj_data['pddl_params'], - 'task_type': traj_data['task_type']} - self.task_params = dict((k, v.lower() if v in constants.OBJECTS else v) for k, v in self.task_params.items()) - - policy_class = self.get_task_policy(self.task_params) - self.policy = policy_class(self.task_params, max_steps=self.max_steps) - - def act(self, game_state, reward, done, last_action=''): - action = self.policy.act(game_state, last_action) - - if action == last_action or (last_action == "look" and action not in game_state['admissible_commands']): - return random.choice(game_state['admissible_commands']) - - return action - - def observe(self, obs): - self.policy.observe(obs) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_thor.py b/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_thor.py deleted file mode 100644 index e4718893..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_thor.py +++ /dev/null @@ -1,165 +0,0 @@ -import os -import sys -import json - -import alfworld.gen.constants as constants -from alfworld.agents.expert.handcoded_expert_tw import HandCodedTWAgent, PickAndPlaceSimplePolicy, PickTwoObjAndPlacePolicy, LookAtObjInLightPolicy, PickHeatThenPlaceInRecepPolicy, PickCoolThenPlaceInRecepPolicy, PickCleanThenPlaceInRecepPolicy - -class PickAndPlaceSimpleThorPolicy(PickAndPlaceSimplePolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, parent): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "put {} in/on {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_put_object, can_take_object, is_obj_in_obs - - -class PickTwoObjAndPlaceThorPolicy(PickTwoObjAndPlacePolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, parent): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - relevant_receptacles = [r.split("|")[0].lower() for o in metadata['objects'] if o['objectType'].lower() in obj and o['parentReceptacles'] for r in o['parentReceptacles'] if r is not None] - is_one_object_already_inside_receptacle = any(parent in r for r in relevant_receptacles) - trying_to_take_the_same_object = "take {} from {}".format(obj, parent) in admissible_commands_wo_num_ids - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "put {} in/on {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_put_object, can_take_object, is_obj_in_obs, is_one_object_already_inside_receptacle, trying_to_take_the_same_object - - -class LookAtObjInLightThorPolicy(LookAtObjInLightPolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, toggle): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - can_toggle_lamp = "use {}".format(toggle) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return can_take_object, can_toggle_lamp, is_obj_in_obs - - -class PickHeatThenPlaceInRecepThorPolicy(PickHeatThenPlaceInRecepPolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, parent): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - hot_objects = [o.split("|")[0].lower() for o in list(self.env.heated_objects) if o in [io['objectId'] for io in metadata['inventoryObjects']]] - is_the_object_agent_holding_hot = len(hot_objects) > 0 - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "put {} in/on {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - can_heat_object = "heat {} with {}".format(obj, "microwave") in admissible_commands_wo_num_ids - return at_right_recep, can_heat_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_hot - - -class PickCoolThenPlaceInRecepThorPolicy(PickCoolThenPlaceInRecepPolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, parent): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - cool_objects = [o.split("|")[0].lower() for o in list(self.env.cooled_objects) if o in [io['objectId'] for io in metadata['inventoryObjects']]] - is_the_object_agent_holding_cool = len(cool_objects) > 0 - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "put {} in/on {}".format(obj, parent) in admissible_commands_wo_num_ids - can_cool_object = "cool {} with {}".format(obj, "fridge") in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_cool_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_cool - - -class PickCleanThenPlaceInRecepThorPolicy(PickCleanThenPlaceInRecepPolicy): - - def __init__(self, task_params, env, max_steps): - super().__init__(task_params, max_steps=max_steps) - self.env = env - - def get_predicates(self, game_state, obj, parent): - admissible_commands = game_state['admissible_commands'] - admissible_commands_wo_num_ids = [self.remove_num_ids(ac) for ac in admissible_commands] - metadata = self.env.last_event.metadata - - self.is_agent_holding_right_object = any(obj in o for o in self.inventory) - clean_objects = [o.split("|")[0].lower() for o in list(self.env.cleaned_objects) if o in [io['objectId'] for io in metadata['inventoryObjects']]] - is_the_object_agent_holding_isclean = len(clean_objects) > 0 - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "put {} in/on {}".format(obj, parent) in admissible_commands_wo_num_ids - can_clean_object = "clean {} with {}".format(obj, "sinkbasin") in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_clean_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_isclean - - -class HandCodedThorAgent(HandCodedTWAgent): - """ THOR instance of handcoded expert. - Uses predicates from THOR metadata for making decisions.""" - - def __init__(self, env, max_steps=150): - self.env = env - super().__init__(max_steps=max_steps) - - def reset(self, game="INVALID"): - traj_data_file = os.path.join(game) - with open(traj_data_file, 'r') as f: - traj_data = json.load(f) - - self.task_params = {**traj_data['pddl_params'], - 'task_type': traj_data['task_type']} - self.task_params = dict((k, v.lower() if v in constants.OBJECTS else v) for k, v in self.task_params.items()) - - policy_class = self.get_task_policy(self.task_params) - self.policy = policy_class(self.task_params, self.env, max_steps=self.max_steps) - - def get_task_policy(self, task_param): - task_type = task_param['task_type'] - task_class_str = task_type.replace("_", " ").title().replace(" ", '') + "ThorPolicy" - if task_class_str in globals(): - return globals()[task_class_str] - else: - raise Exception("Invalid Task Type: %s" % task_type) \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_tw.py b/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_tw.py deleted file mode 100644 index da8bdc1e..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/expert/handcoded_expert_tw.py +++ /dev/null @@ -1,128 +0,0 @@ -import os -import sys - -from alfworld.agents.expert.handcoded_expert import HandCodedAgent, PickAndPlaceSimplePolicy, PickTwoObjAndPlacePolicy, LookAtObjInLightPolicy, PickHeatThenPlaceInRecepPolicy, PickCoolThenPlaceInRecepPolicy, PickCleanThenPlaceInRecepPolicy - -class PickAndPlaceSimpleTWPolicy(PickAndPlaceSimplePolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, parent): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "move {} to {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_put_object, can_take_object, is_obj_in_obs - - -class PickTwoObjAndPlaceTWPolicy(PickTwoObjAndPlacePolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, parent): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - in_recep_predicate = "inreceptacle {} {}".format(obj, parent) - is_one_object_already_inside_receptacle = in_recep_predicate in facts_wo_num_ids - in_receptacle_obj_ids = [" ".join(f.split()[1:3]) for f in facts if in_recep_predicate in self.remove_num_ids(f)] - in_receptacle_obj_id = in_receptacle_obj_ids[0] if len(in_receptacle_obj_ids) > 0 else "" - trying_to_take_the_same_object = any("take {}".format(in_receptacle_obj_id) in ac for ac in admissible_commands) - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "move {} to {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_put_object, can_take_object, is_obj_in_obs, is_one_object_already_inside_receptacle, trying_to_take_the_same_object - - -class LookAtObjInLightTWPolicy(LookAtObjInLightPolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, toggle): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - can_toggle_lamp = "use {}".format(toggle) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return can_take_object, can_toggle_lamp, is_obj_in_obs - - -class PickHeatThenPlaceInRecepTWPolicy(PickHeatThenPlaceInRecepPolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, parent): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - inventory = self.inventory - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - is_the_object_agent_holding_hot = "ishot {}".format(inventory[0]) in facts if len(inventory) > 0 else False - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "move {} to {}".format(obj, parent) in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - can_heat_object = "heat {} with {}".format(obj, "microwave") in admissible_commands_wo_num_ids - return at_right_recep, can_heat_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_hot - - -class PickCoolThenPlaceInRecepTWPolicy(PickCoolThenPlaceInRecepPolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, parent): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - inventory = self.inventory - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - is_the_object_agent_holding_cool = "iscool {}".format(inventory[0]) in facts if len(inventory) > 0 else False - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "move {} to {}".format(obj, parent) in admissible_commands_wo_num_ids - can_cool_object = "cool {} with {}".format(obj, "fridge") in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_cool_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_cool - - -class PickCleanThenPlaceInRecepTWPolicy(PickCleanThenPlaceInRecepPolicy): - - def __init__(self, task_params, max_steps): - super().__init__(task_params, max_steps=max_steps) - - def get_predicates(self, game_state, obj, parent): - facts, facts_wo_num_ids, admissible_commands, admissible_commands_wo_num_ids = self.get_state_info(game_state) - inventory = self.inventory - self.is_agent_holding_right_object = "holds agent {}".format(obj) in facts_wo_num_ids - is_the_object_agent_holding_isclean = "isclean {}".format(inventory[0]) in facts if len(inventory) > 0 else False - obs_at_curr_recep = self.obs_at_recep[self.curr_recep] if self.curr_recep in self.obs_at_recep else "" - is_obj_in_obs = "you see" in obs_at_curr_recep and " {} ".format(obj) in obs_at_curr_recep - at_right_recep = parent in self.curr_recep - can_put_object = "move {} to {}".format(obj, parent) in admissible_commands_wo_num_ids - can_clean_object = "clean {} with {}".format(obj, "sinkbasin") in admissible_commands_wo_num_ids - can_take_object = any("take {}".format(obj) in ac for ac in admissible_commands_wo_num_ids) - return at_right_recep, can_clean_object, can_put_object, can_take_object, is_obj_in_obs, is_the_object_agent_holding_isclean - - -class HandCodedTWAgent(HandCodedAgent): - """ Textworld instance of handcoded expert. - Uses predicates from Textworld Engine for making decisions.""" - - def __init__(self, max_steps=150): - super().__init__(max_steps=max_steps) - - def get_task_policy(self, task_param): - task_type = task_param['task_type'] - task_class_str = task_type.replace("_", " ").title().replace(" ", '') + "TWPolicy" - if task_class_str in globals(): - return globals()[task_class_str] - else: - raise Exception("Invalid Task Type: %s" % task_type) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/generic.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/generic.py deleted file mode 100644 index 8aa4647a..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/generic.py +++ /dev/null @@ -1,298 +0,0 @@ -import torch -import argparse -import os -import yaml -import numpy as np -import string -missing_words = set() - - -def to_np(x): - if isinstance(x, np.ndarray): - return x - return x.data.cpu().numpy() - - -def to_pt(np_matrix, enable_cuda=False, type='long'): - if type == 'long': - if enable_cuda: - return torch.autograd.Variable(torch.from_numpy(np_matrix).type(torch.LongTensor).cuda()) - else: - return torch.autograd.Variable(torch.from_numpy(np_matrix).type(torch.LongTensor)) - elif type == 'float': - if enable_cuda: - return torch.autograd.Variable(torch.from_numpy(np_matrix).type(torch.FloatTensor).cuda()) - else: - return torch.autograd.Variable(torch.from_numpy(np_matrix).type(torch.FloatTensor)) - - -def apply_f(inp, filter): - # inp is a list, after applying filter, shoudl return another list - res = filter(inp) - if not isinstance(res, tuple): - res = [res] - else: - res = list(res) - return res - - -def _words_to_ids(words, word2id): - ids = [] - for word in words: - ids.append(_word_to_id(word, word2id)) - return ids - - -def _word_to_id(word, word2id): - try: - return word2id[word] - except KeyError: - key = word + "_" + str(len(word2id)) - if key not in missing_words: - print("Warning... %s is not in vocab, vocab size is %d..." % (word, len(word2id))) - missing_words.add(key) - with open("missing_words.txt", 'a+') as outfile: - outfile.write(key + '\n') - outfile.flush() - return 1 - - -def max_len(list_of_list): - if len(list_of_list) == 0: - return 0 - return max(map(len, list_of_list)) - - -def pad_sequences(sequences, maxlen=None, dtype='int32', value=0.): - ''' - Partially borrowed from Keras - # Arguments - sequences: list of lists where each element is a sequence - maxlen: int, maximum length - dtype: type to cast the resulting sequence. - value: float, value to pad the sequences to the desired value. - # Returns - x: numpy array with dimensions (number_of_sequences, maxlen) - ''' - if isinstance(sequences, np.ndarray): - return sequences - lengths = [len(s) for s in sequences] - nb_samples = len(sequences) - if maxlen is None: - maxlen = np.max(lengths) - # take the sample shape from the first non empty sequence - # checking for consistency in the main loop below. - sample_shape = tuple() - for s in sequences: - if len(s) > 0: - sample_shape = np.asarray(s).shape[1:] - break - x = (np.ones((nb_samples, maxlen) + sample_shape) * value).astype(dtype) - for idx, s in enumerate(sequences): - if len(s) == 0: - continue # empty list was found - # pre truncating - trunc = s[-maxlen:] - # check `trunc` has expected shape - trunc = np.asarray(trunc, dtype=dtype) - if trunc.shape[1:] != sample_shape: - raise ValueError('Shape of sample %s of sequence at position %s is different from expected shape %s' % - (trunc.shape[1:], idx, sample_shape)) - # post padding - x[idx, :len(trunc)] = trunc - return x - - -def ez_gather_dim_1(input, index): - if len(input.size()) == len(index.size()): - return input.gather(1, index) - res = [] - for i in range(input.size(0)): - res.append(input[i][index[i][0]]) - return torch.stack(res, 0) - - -def preproc(s): - s = s.replace("\n", ' ') - # s = s.lower() - while(True): - if " " in s: - s = s.replace(" ", " ") - else: - break - s = s.strip() - if len(s) == 0: - return "nothing" - return s - - -class HistoryScoreCache: - - def __init__(self, capacity=1): - self.capacity = capacity - self.reset() - - def push(self, stuff): - """stuff is float.""" - if len(self.memory) < self.capacity: - self.memory.append(stuff) - else: - self.memory = self.memory[1:] + [stuff] - - def get_avg(self): - return np.mean(np.array(self.memory)) - - def reset(self): - self.memory = [] - - def __len__(self): - return len(self.memory) - - -class LinearSchedule(object): - """ - Linear interpolation between initial_p and final_p over - schedule_timesteps. After this many timesteps pass final_p is - returned. - :param schedule_timesteps: (int) Number of timesteps for which to linearly anneal initial_p to final_p - :param initial_p: (float) initial output value - :param final_p: (float) final output value - """ - - def __init__(self, schedule_timesteps, final_p, initial_p=1.0): - self.schedule_timesteps = schedule_timesteps - self.final_p = final_p - self.initial_p = initial_p - if schedule_timesteps < 0: - self.fixed = True - else: - self.schedule = np.linspace(initial_p, final_p, schedule_timesteps) - self.fixed = False - - def value(self, step): - if self.fixed: - return self.initial_p - if step < 0: - return self.initial_p - if step >= self.schedule_timesteps: - return self.final_p - else: - return self.schedule[step] - - -def load_config(): - parser = argparse.ArgumentParser() - parser.add_argument("config_file", help="path to config file") - parser.add_argument("-p", "--params", nargs="+", metavar="my.setting=value", default=[], - help="override params of the config file," - " e.g. -p 'training.gamma=0.95'") - args = parser.parse_args() - assert os.path.exists(args.config_file), "Invalid config file" - with open(args.config_file) as reader: - config = yaml.safe_load(reader) - # Parse overriden params. - for param in args.params: - fqn_key, value = param.split("=") - entry_to_change = config - keys = fqn_key.split(".") - for k in keys[:-1]: - entry_to_change = entry_to_change[k] - entry_to_change[keys[-1]] = value - # print(config) - return config - - -class EpisodicCountingMemory: - - def __init__(self): - self.reset() - - def push(self, stuff): - assert len(stuff) > 0 # batch size should be greater than 0 - if len(self.memory) == 0: - for _ in range(len(stuff)): - self.memory.append(set()) - - for b in range(len(stuff)): - key = stuff[b] - self.memory[b].add(key) - - def is_a_new_state(self, stuff): - assert len(stuff) > 0 # batch size should be greater than 0 - res = [] - for b in range(len(stuff)): - key = stuff[b] - res.append(float(key not in self.memory[b])) - return res - - def reset(self): - self.memory = [] - - def __len__(self): - return len(self.memory) - - -class ObjCentricEpisodicMemory: - - def __init__(self): - self.reset() - - def get_objects(self, str): - # TODO: replace with a more generic noun-phrase extractor - str_no_punc = str.translate(str.maketrans('', '', string.punctuation)) - words = str_no_punc.split() - objects = [] - for i,w in enumerate(words): - if w.isdigit() and i > 0: - object = words[i-1] + " " + w - objects.append(object) - return objects - - def push(self, stuff): - assert len(stuff) > 0 - if len(self.memory) == 0: - for _ in range(len(stuff)): - self.memory.append(set()) - - for b in range(len(stuff)): - key = stuff[b] - objects = self.get_objects(key) - for obj in objects: - self.memory[b].add(obj) - - def get_object_novelty_reward(self, stuff): - assert len(stuff) > 0 - res = [] - for b in range(len(stuff)): - key = stuff[b] - objects = self.get_objects(key) - if len(objects) > 0: - num_unseen_objects = len([obj for obj in objects if obj not in self.memory[b]]) - res.append(float(num_unseen_objects) / len(objects)) - else: - res.append(0.0) - return res - - def reset(self): - self.memory = [] - - -class BeamSearchNode(object): - def __init__(self, previous_node, input_target, log_prob, length): - - self.previous_node = previous_node - self.input_target = input_target - self.log_prob = log_prob - self.length = length - self.val = -self.log_prob / float(self.length - 1 + 1e-6) - - # defining comparators less_than and equals - def __lt__(self, other): - return self.val < other.val - - def __eq__(self, other): - if other is None: - return False - if not isinstance(other, BeamSearchNode): - return False - return self.val == other.val diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/layers.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/layers.py deleted file mode 100644 index 63f87ecd..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/layers.py +++ /dev/null @@ -1,1622 +0,0 @@ -import torch -import math -import numpy as np -import h5py -import torch.nn.functional as F - - -def compute_mask(x): - mask = torch.ne(x, 0).float() - if x.is_cuda: - mask = mask.cuda() - return mask - - -def to_one_hot(y_true, n_classes): - # y_true: batch x time - batch_size, length = y_true.size(0), y_true.size(1) - y_onehot = torch.FloatTensor(batch_size, length, n_classes) # batch x time x n_class - if y_true.is_cuda: - y_onehot = y_onehot.cuda() - y_onehot.zero_() - y_onehot = y_onehot.view(-1, y_onehot.size(-1)) # batch*time x n_class - y_true = y_true.view(-1, 1) # batch*time x 1 - y_onehot.scatter_(1, y_true, 1) # batch*time x n_class - return y_onehot.view(batch_size, length, -1) - - -def NegativeLogLoss(y_pred, y_true, mask=None, smoothing_eps=0.0): - """ - Shape: - - y_pred: batch x time x vocab - - y_true: batch x time - - mask: batch x time - """ - y_true_onehot = to_one_hot(y_true, y_pred.size(-1)) # batch x time x vocab - if smoothing_eps > 0.0: - y_true_onehot = y_true_onehot * (1.0 - smoothing_eps) + (1.0 - y_true_onehot) * smoothing_eps / (y_pred.size(-1) - 1) - P = y_true_onehot * y_pred # batch x time x vocab - P = torch.sum(P, dim=-1) # batch x time - gt_zero = torch.gt(P, 0.0).float() # batch x time - epsilon = torch.le(P, 0.0).float() * 1e-8 # batch x time - log_P = torch.log(P + epsilon) * gt_zero # batch x time - if mask is not None: - log_P = log_P * mask - output = -torch.sum(log_P, dim=1) # batch - return output - - -def GetGenerationQValue(y_pred, y_true, mask): - """ - Shape: - - y_pred: batch x time x vocab - - y_true: batch x time - - mask: batch x time - """ - y_true_onehot = to_one_hot(y_true, y_pred.size(-1)) # batch x time x vocab - P = y_true_onehot * y_pred # batch x time x vocab - P = torch.sum(P, dim=-1) # batch x time - - P = P * mask - mask_sum = torch.sum(mask, -1) # batch - tmp = torch.eq(mask_sum, 0).float() - if P.is_cuda: - tmp = tmp.cuda() - mask_sum = mask_sum + tmp - res = torch.sum(P, -1) # batch - res = res / mask_sum # batch - return res - - -def NLL(y_pred, y_true_onehot, mask=None): - """ - Shape: - - y_pred: batch x n_class - - y_true: batch x n_class - - mask: batch x n_class - """ - y_true_onehot = y_true_onehot.float() - P = y_true_onehot * y_pred # batch x n_class - gt_zero = torch.gt(P, 0.0).float() # batch x n_class - epsilon = torch.le(P, 0.0).float() * 1e-8 # batch x n_class - log_P = torch.log(P + epsilon) * gt_zero # batch x n_class - if mask is not None: - log_P = log_P * mask - output = -torch.sum(log_P, dim=1) # batch - return torch.mean(output) - - -def masked_softmax(x, m=None, axis=-1): - ''' - Softmax with mask (optional) - ''' - x = torch.clamp(x, min=-15.0, max=15.0) - if m is not None: - m = m.float() - x = x * m - e_x = torch.exp(x - torch.max(x, dim=axis, keepdim=True)[0]) - if m is not None: - e_x = e_x * m - softmax = e_x / (torch.sum(e_x, dim=axis, keepdim=True) + 1e-6) - return softmax - - -def masked_mean(x, m=None, dim=1): - """ - mean pooling when there're paddings - input: tensor: batch x time x h - mask: batch x time - output: tensor: batch x h - """ - if m is None: - return torch.mean(x, dim=dim) - x = x * m.unsqueeze(-1) - mask_sum = torch.sum(m, dim=-1) # batch - tmp = torch.eq(mask_sum, 0).float() - if x.is_cuda: - tmp = tmp.cuda() - mask_sum = mask_sum + tmp - res = torch.sum(x, dim=dim) # batch x h - res = res / mask_sum.unsqueeze(-1) - return res - - -def masked_ave_aggregator(x, mask): - """ - ave aggregator of the node embedding - input: tensor: batch x num_nodes x dim - mask: tensor: batch x num_nodes - - """ - mask_sum = torch.sum(mask, -1).unsqueeze(-1) # batch x 1 - mask = mask.unsqueeze(-1) # batch x num_nodes x 1 - mask = mask.expand(-1, -1, x.shape[-1]) # batch x num_nodes x dim - masked_x = x * mask # batch x num_nodes x dim - sum_masked_x = torch.sum(masked_x, 1) - ave_masked_x = sum_masked_x / mask_sum - return ave_masked_x - - -class LayerNorm(torch.nn.Module): - - def __init__(self, input_dim): - super(LayerNorm, self).__init__() - self.gamma = torch.nn.Parameter(torch.ones(input_dim)) - self.beta = torch.nn.Parameter(torch.zeros(input_dim)) - self.eps = 1e-6 - - def forward(self, x, mask=None): - # x: nbatch x hidden - # mask: nbatch - mean = x.mean(-1, keepdim=True) - std = torch.sqrt(x.var(dim=-1, keepdim=True) + self.eps) - output = self.gamma * (x - mean) / (std + self.eps) + self.beta - if mask is not None: - return output * mask.unsqueeze(-1) - else: - return output - - -class H5EmbeddingManager(object): - def __init__(self, h5_path): - f = h5py.File(h5_path, 'r') - self.W = np.array(f['embedding']) - print("embedding data type=%s, shape=%s" % (type(self.W), self.W.shape)) - self.id2word = f['words_flatten'][0].split('\n') - self.word2id = dict(zip(self.id2word, range(len(self.id2word)))) - - def __getitem__(self, item): - item_type = type(item) - if item_type is str: - index = self.word2id[item] - embs = self.W[index] - return embs - else: - raise RuntimeError("don't support type: %s" % type(item)) - - def word_embedding_initialize(self, words_list, dim_size=300, scale=0.1, oov_init='random'): - shape = (len(words_list), dim_size) - self.rng = np.random.RandomState(42) - if 'zero' == oov_init: - W2V = np.zeros(shape, dtype='float32') - elif 'one' == oov_init: - W2V = np.ones(shape, dtype='float32') - else: - W2V = self.rng.uniform(low=-scale, high=scale, size=shape).astype('float32') - W2V[0, :] = 0 - in_vocab = np.ones(shape[0], dtype=np.bool) - word_ids = [] - for i, word in enumerate(words_list): - if word in self.word2id: - word_ids.append(self.word2id[word]) - else: - in_vocab[i] = False - W2V[in_vocab] = self.W[np.array(word_ids, dtype='int32')][:, :dim_size] - return W2V - - -class Embedding(torch.nn.Module): - ''' - inputs: x: batch x ... - outputs:embedding: batch x ... x emb - mask: batch x ... - ''' - - def __init__(self, embedding_size, vocab_size, dropout_rate=0.0, trainable=True, id2word=None, - embedding_oov_init='random', load_pretrained=False, pretrained_embedding_path=None): - super(Embedding, self).__init__() - self.embedding_size = embedding_size - self.vocab_size = vocab_size - self.id2word = id2word - self.dropout_rate = dropout_rate - self.load_pretrained = load_pretrained - self.embedding_oov_init = embedding_oov_init - self.pretrained_embedding_path = pretrained_embedding_path - self.trainable = trainable - self.embedding_layer = torch.nn.Embedding(self.vocab_size, self.embedding_size, padding_idx=0) - self.init_weights() - - def init_weights(self): - init_embedding_matrix = self.embedding_init() - if self.embedding_layer.weight.is_cuda: - init_embedding_matrix = init_embedding_matrix.cuda() - self.embedding_layer.weight = torch.nn.Parameter(init_embedding_matrix) - if not self.trainable: - self.embedding_layer.weight.requires_grad = False - - def embedding_init(self): - # Embeddings - if self.load_pretrained is False: - word_embedding_init = np.random.uniform(low=-0.05, high=0.05, size=(self.vocab_size, self.embedding_size)) - word_embedding_init[0, :] = 0 - else: - embedding_initr = H5EmbeddingManager(self.pretrained_embedding_path) - word_embedding_init = embedding_initr.word_embedding_initialize(self.id2word, - dim_size=self.embedding_size, - oov_init=self.embedding_oov_init) - del embedding_initr - word_embedding_init = torch.from_numpy(word_embedding_init).float() - return word_embedding_init - - def compute_mask(self, x): - mask = torch.ne(x, 0).float() - if x.is_cuda: - mask = mask.cuda() - return mask - - def forward(self, x): - embeddings = self.embedding_layer(x) # batch x time x emb - embeddings = F.dropout(embeddings, p=self.dropout_rate, training=self.training) - mask = self.compute_mask(x) # batch x time - return embeddings, mask - - -class FastUniLSTM(torch.nn.Module): - """ - Adapted from https://github.com/facebookresearch/DrQA/ - now supports: different rnn size for each layer - all zero rows in batch (from time distributed layer, by reshaping certain dimension) - """ - - def __init__(self, ninp, nhids, dropout_between_rnn_layers=0.): - super(FastUniLSTM, self).__init__() - self.ninp = ninp - self.nhids = nhids - self.nlayers = len(self.nhids) - self.dropout_between_rnn_layers = dropout_between_rnn_layers - self.stack_rnns() - - def stack_rnns(self): - rnns = [torch.nn.LSTM(self.ninp if i == 0 else self.nhids[i - 1], - self.nhids[i], - num_layers=1, - bidirectional=False) for i in range(self.nlayers)] - self.rnns = torch.nn.ModuleList(rnns) - - def forward(self, x, mask): - - def pad_(tensor, n): - if n > 0: - zero_pad = torch.autograd.Variable(torch.zeros((n,) + tensor.size()[1:])) - if x.is_cuda: - zero_pad = zero_pad.cuda() - tensor = torch.cat([tensor, zero_pad]) - return tensor - - """ - inputs: x: batch x time x inp - mask: batch x time - output: encoding: batch x time x hidden[-1] - """ - # Compute sorted sequence lengths - batch_size = x.size(0) - lengths = mask.data.eq(1).long().sum(1) # .squeeze() - _, idx_sort = torch.sort(lengths, dim=0, descending=True) - _, idx_unsort = torch.sort(idx_sort, dim=0) - - lengths = list(lengths[idx_sort]) - idx_sort = torch.autograd.Variable(idx_sort) - idx_unsort = torch.autograd.Variable(idx_unsort) - - # Sort x - x = x.index_select(0, idx_sort) - - # remove non-zero rows, and remember how many zeros - n_nonzero = np.count_nonzero(lengths) - n_zero = batch_size - n_nonzero - if n_zero != 0: - lengths = lengths[:n_nonzero] - x = x[:n_nonzero] - - # Transpose batch and sequence dims - x = x.transpose(0, 1) - - # Pack it up - rnn_input = torch.nn.utils.rnn.pack_padded_sequence(x, lengths) - - # Encode all layers - outputs = [rnn_input] - for i in range(self.nlayers): - rnn_input = outputs[-1] - - # dropout between rnn layers - if self.dropout_between_rnn_layers > 0: - dropout_input = F.dropout(rnn_input.data, - p=self.dropout_between_rnn_layers, - training=self.training) - rnn_input = torch.nn.utils.rnn.PackedSequence(dropout_input, - rnn_input.batch_sizes) - seq, last = self.rnns[i](rnn_input) - outputs.append(seq) - if i == self.nlayers - 1: - # last layer - last_state = last[0] # (num_layers * num_directions, batch, hidden_size) - last_state = last_state[0] # batch x hidden_size - - # Unpack everything - for i, o in enumerate(outputs[1:], 1): - outputs[i] = torch.nn.utils.rnn.pad_packed_sequence(o)[0] - output = outputs[-1] - - # Transpose and unsort - output = output.transpose(0, 1) # batch x time x enc - - # re-padding - output = pad_(output, n_zero) - last_state = pad_(last_state, n_zero) - - output = output.index_select(0, idx_unsort) - last_state = last_state.index_select(0, idx_unsort) - - # Pad up to original batch sequence length - if output.size(1) != mask.size(1): - padding = torch.zeros(output.size(0), - mask.size(1) - output.size(1), - output.size(2)).type(output.data.type()) - output = torch.cat([output, torch.autograd.Variable(padding)], 1) - - output = output.contiguous() * mask.unsqueeze(-1) - return output, last_state, mask - - -class FastBiLSTM(torch.nn.Module): - """ - Adapted from https://github.com/facebookresearch/DrQA/ - now supports: different rnn size for each layer - all zero rows in batch (from time distributed layer, by reshaping certain dimension) - """ - - def __init__(self, ninp, nhids, dropout_between_rnn_layers=0.): - super(FastBiLSTM, self).__init__() - self.ninp = ninp - self.nhids = [h // 2 for h in nhids] - self.nlayers = len(self.nhids) - self.dropout_between_rnn_layers = dropout_between_rnn_layers - self.stack_rnns() - - def stack_rnns(self): - rnns = [torch.nn.LSTM(self.ninp if i == 0 else self.nhids[i - 1] * 2, - self.nhids[i], - num_layers=1, - bidirectional=True) for i in range(self.nlayers)] - self.rnns = torch.nn.ModuleList(rnns) - - def forward(self, x, mask): - - def pad_(tensor, n): - if n > 0: - zero_pad = torch.autograd.Variable(torch.zeros((n,) + tensor.size()[1:])) - if x.is_cuda: - zero_pad = zero_pad.cuda() - tensor = torch.cat([tensor, zero_pad]) - return tensor - - """ - inputs: x: batch x time x inp - mask: batch x time - output: encoding: batch x time x hidden[-1] - """ - # Compute sorted sequence lengths - batch_size = x.size(0) - lengths = mask.data.eq(1).long().sum(1) # .squeeze() - _, idx_sort = torch.sort(lengths, dim=0, descending=True) - _, idx_unsort = torch.sort(idx_sort, dim=0) - - lengths = list(lengths[idx_sort]) - idx_sort = torch.autograd.Variable(idx_sort) - idx_unsort = torch.autograd.Variable(idx_unsort) - - # Sort x - x = x.index_select(0, idx_sort) - - # remove non-zero rows, and remember how many zeros - n_nonzero = np.count_nonzero(lengths) - n_zero = batch_size - n_nonzero - if n_zero != 0: - lengths = lengths[:n_nonzero] - x = x[:n_nonzero] - - # Transpose batch and sequence dims - x = x.transpose(0, 1) - - # Pack it up - rnn_input = torch.nn.utils.rnn.pack_padded_sequence(x, lengths) - - # Encode all layers - outputs = [rnn_input] - for i in range(self.nlayers): - rnn_input = outputs[-1] - - # dropout between rnn layers - if self.dropout_between_rnn_layers > 0: - dropout_input = F.dropout(rnn_input.data, - p=self.dropout_between_rnn_layers, - training=self.training) - rnn_input = torch.nn.utils.rnn.PackedSequence(dropout_input, - rnn_input.batch_sizes) - seq, last = self.rnns[i](rnn_input) - outputs.append(seq) - if i == self.nlayers - 1: - # last layer - last_state = last[0] # (num_layers * num_directions, batch, hidden_size) - last_state = torch.cat([last_state[0], last_state[1]], 1) # batch x hid_f+hid_b - - # Unpack everything - for i, o in enumerate(outputs[1:], 1): - outputs[i] = torch.nn.utils.rnn.pad_packed_sequence(o)[0] - output = outputs[-1] - - # Transpose and unsort - output = output.transpose(0, 1) # batch x time x enc - - # re-padding - output = pad_(output, n_zero) - last_state = pad_(last_state, n_zero) - - output = output.index_select(0, idx_unsort) - last_state = last_state.index_select(0, idx_unsort) - - # Pad up to original batch sequence length - if output.size(1) != mask.size(1): - padding = torch.zeros(output.size(0), - mask.size(1) - output.size(1), - output.size(2)).type(output.data.type()) - output = torch.cat([output, torch.autograd.Variable(padding)], 1) - - output = output.contiguous() * mask.unsqueeze(-1) - return output, last_state, mask - - -class LSTMCell(torch.nn.Module): - - """A basic LSTM cell.""" - - def __init__(self, input_size, hidden_size, use_bias=True): - """ - Most parts are copied from torch.nn.LSTMCell. - """ - - super(LSTMCell, self).__init__() - self.input_size = input_size - self.hidden_size = hidden_size - self.use_bias = use_bias - self.pre_act_linear = torch.nn.Linear(input_size + hidden_size, 4 * hidden_size, bias=False) - if use_bias: - self.bias_f = torch.nn.Parameter(torch.FloatTensor(hidden_size)) - self.bias_iog = torch.nn.Parameter(torch.FloatTensor(3 * hidden_size)) - else: - self.register_parameter('bias', None) - self.reset_parameters() - - def reset_parameters(self): - torch.nn.init.xavier_uniform_(self.pre_act_linear.weight.data) - if self.use_bias: - self.bias_f.data.fill_(1.0) - self.bias_iog.data.fill_(0.0) - - def get_init_hidden(self, bsz, use_cuda): - h_0 = torch.autograd.Variable(torch.FloatTensor(bsz, self.hidden_size).zero_()) - c_0 = torch.autograd.Variable(torch.FloatTensor(bsz, self.hidden_size).zero_()) - if use_cuda: - h_0, c_0 = h_0.cuda(), c_0.cuda() - return h_0, c_0 - - def forward(self, input_, mask_=None, h_0=None, c_0=None): - """ - Args: - input_: A (batch, input_size) tensor containing input features. - mask_: (batch) - hx: A tuple (h_0, c_0), which contains the initial hidden - and cell state, where the size of both states is - (batch, hidden_size). - Returns: - h_1, c_1: Tensors containing the next hidden and cell state. - """ - if h_0 is None or c_0 is None: - h_init, c_init = self.get_init_hidden(input_.size(0), use_cuda=input_.is_cuda) - if h_0 is None: - h_0 = h_init - if c_0 is None: - c_0 = c_init - - if mask_ is None: - mask_ = torch.ones_like(torch.sum(input_, -1)) - if input_.is_cuda: - mask_ = mask_.cuda() - - pre_act = self.pre_act_linear(torch.cat([input_, h_0], -1)) # batch x 4*hid - if self.use_bias: - pre_act = pre_act + torch.cat([self.bias_f, self.bias_iog]).unsqueeze(0) - f, i, o, g = torch.split(pre_act, split_size_or_sections=self.hidden_size, dim=1) - expand_mask_ = mask_.unsqueeze(1) # batch x 1 - c_1 = torch.sigmoid(f) * c_0 + torch.sigmoid(i) * torch.tanh(g) - c_1 = c_1 * expand_mask_ + c_0 * (1 - expand_mask_) - h_1 = torch.sigmoid(o) * torch.tanh(c_1) - h_1 = h_1 * expand_mask_ + h_0 * (1 - expand_mask_) - return h_1, c_1 - - def __repr__(self): - s = '{name}({input_size}, {hidden_size})' - return s.format(name=self.__class__.__name__, **self.__dict__) - - -class MatchLSTMAttention(torch.nn.Module): - ''' - input: p: batch x inp_p - p_mask: batch - q: batch x time x inp_q - q_mask: batch x time - h_tm1: batch x out - depth: int - output: z: batch x inp_p+inp_q - ''' - - def __init__(self, input_p_dim, input_q_dim, output_dim): - super(MatchLSTMAttention, self).__init__() - self.input_p_dim = input_p_dim - self.input_q_dim = input_q_dim - self.output_dim = output_dim - self.nlayers = len(self.output_dim) - - W_p_r = [torch.nn.Linear(self.output_dim[i] + (self.input_p_dim if i == 0 else self.output_dim[i - 1]), self.output_dim[i]) for i in range(self.nlayers)] - W_q = [torch.nn.Linear(self.input_q_dim, self.output_dim[i]) for i in range(self.nlayers)] - w = [torch.nn.Parameter(torch.FloatTensor(self.output_dim[i])) for i in range(self.nlayers)] - match_b = [torch.nn.Parameter(torch.FloatTensor(1)) for i in range(self.nlayers)] - - self.W_p_r = torch.nn.ModuleList(W_p_r) - self.W_q = torch.nn.ModuleList(W_q) - self.w = torch.nn.ParameterList(w) - self.match_b = torch.nn.ParameterList(match_b) - self.init_weights() - - def init_weights(self): - for i in range(self.nlayers): - torch.nn.init.xavier_uniform_(self.W_p_r[i].weight.data) - torch.nn.init.xavier_uniform_(self.W_q[i].weight.data) - self.W_p_r[i].bias.data.fill_(0) - self.W_q[i].bias.data.fill_(0) - torch.nn.init.normal_(self.w[i].data, mean=0, std=0.05) - self.match_b[i].data.fill_(1.0) - - def forward(self, input_p, mask_p, input_q, mask_q, h_tm1, depth): - G_p_r = self.W_p_r[depth](torch.cat([input_p, h_tm1], -1)).unsqueeze(1) # batch x None x out - G_q = self.W_q[depth](input_q) # batch x time x out - G = torch.tanh(G_p_r + G_q) # batch x time x out - alpha = torch.matmul(G, self.w[depth]) # batch x time - alpha = alpha + self.match_b[depth].unsqueeze(0) # batch x time - alpha = masked_softmax(alpha, mask_q, axis=-1) # batch x time - alpha = alpha.unsqueeze(1) # batch x 1 x time - # batch x time x input_q, batch x 1 x time - z = torch.bmm(alpha, input_q) # batch x 1 x input_q - z = z.squeeze(1) # batch x input_q - z = torch.cat([input_p, z], 1) # batch x input_p+input_q - return z - - -class StackedMatchLSTM(torch.nn.Module): - ''' - inputs: p: batch x time x inp_p - mask_p: batch x time - q: batch x time x inp_q - mask_q: batch x time - outputs: - encoding: batch x time x h - Dropout types: - dropout_between_rnn_layers -- if multi layer rnns - dropout_in_rnn_weights -- rnn weight dropout - ''' - - def __init__(self, input_p_dim, input_q_dim, nhids, attention_layer, - dropout_between_rnn_layers=0.): - super(StackedMatchLSTM, self).__init__() - self.nhids = nhids - self.input_p_dim = input_p_dim - self.input_q_dim = input_q_dim - self.attention_layer = attention_layer - self.dropout_between_rnn_layers = dropout_between_rnn_layers - self.nlayers = len(self.nhids) - self.stack_rnns() - - def stack_rnns(self): - rnns = [LSTMCell((self.input_p_dim + self.input_q_dim) if i == 0 else (self.nhids[i - 1] + self.input_q_dim), self.nhids[i], use_bias=True) - for i in range(self.nlayers)] - self.rnns = torch.nn.ModuleList(rnns) - - def get_init_hidden(self, bsz, use_cuda): - weight = next(self.parameters()).data - if use_cuda: - return [[(torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()).cuda(), - torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()).cuda())] - for i in range(self.nlayers)] - else: - return [[(torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()), - torch.autograd.Variable(weight.new(bsz, self.nhids[i]).zero_()))] - for i in range(self.nlayers)] - - def forward(self, input_p, mask_p, input_q, mask_q): - batch_size = input_p.size(0) - state_stp = self.get_init_hidden(batch_size, use_cuda=input_p.is_cuda) - - for d, rnn in enumerate(self.rnns): - for t in range(input_p.size(1)): - input_mask = mask_p[:, t] - if d == 0: - # 0th layer - curr_input = input_p[:, t] - else: - curr_input = state_stp[d - 1][t][0] - # apply dropout layer-to-layer - drop_input = F.dropout(curr_input, p=self.dropout_between_rnn_layers, training=self.training) if d > 0 else curr_input - previous_h, previous_c = state_stp[d][t] - drop_input = self.attention_layer(drop_input, input_mask, input_q, mask_q, h_tm1=previous_h, depth=d) - new_h, new_c = rnn(drop_input, input_mask, previous_h, previous_c) - state_stp[d].append((new_h, new_c)) - - states = [h[0] for h in state_stp[-1][1:]] # list of batch x hid - states = torch.stack(states, 1) # batch x time x hid - return states - - -class BiMatchLSTM(torch.nn.Module): - ''' - inputs: p: batch x time_p x emb - mask_p: batch x time_p - q: batch x time_q x emb - mask_q: batch x time_q - outputs:encoding: batch x time_p x hid - last state: batch x hid - Dropout types: - dropouth -- dropout on hidden-to-hidden connections - ''' - - def __init__(self, input_p_dim, input_q_dim, nhids, dropout_between_rnn_layers=0.): - super(BiMatchLSTM, self).__init__() - self.nhids = nhids - self.input_p_dim = input_p_dim - self.input_q_dim = input_q_dim - self.attention_layer = MatchLSTMAttention(input_p_dim, input_q_dim, - output_dim=[hid // 2 for hid in self.nhids]) - - self.forward_rnn = StackedMatchLSTM(input_p_dim=self.input_p_dim, - input_q_dim=self.input_q_dim, - nhids=[hid // 2 for hid in self.nhids], - attention_layer=self.attention_layer, - dropout_between_rnn_layers=dropout_between_rnn_layers) - - self.backward_rnn = StackedMatchLSTM(input_p_dim=self.input_p_dim, - input_q_dim=self.input_q_dim, - nhids=[hid // 2 for hid in self.nhids], - attention_layer=self.attention_layer, - dropout_between_rnn_layers=dropout_between_rnn_layers) - - def forward(self, input_p, mask_p, input_q, mask_q): - # forward pass - forward_states = self.forward_rnn(input_p, mask_p, input_q, mask_q) - forward_last_state = forward_states[:, -1] # batch x hid/2 - - # backward pass - input_p_inverted = torch.flip(input_p, dims=[1]) # batch x time x p_dim (backward) - mask_p_inverted = torch.flip(mask_p, dims=[1]) # batch x time (backward) - backward_states = self.backward_rnn(input_p_inverted, mask_p_inverted, input_q, mask_q) - backward_last_state = backward_states[:, -1] # batch x hid/2 - backward_states = torch.flip(backward_states, dims=[1]) # batch x time x hid/2 - - concat_states = torch.cat([forward_states, backward_states], -1) # batch x time x hid - concat_states = concat_states * mask_p.unsqueeze(-1) # batch x time x hid - concat_last_state = torch.cat([forward_last_state, backward_last_state], -1) # batch x hid - - return concat_states, concat_last_state - - -class ActionScorerAttention(torch.nn.Module): - - def __init__(self, input_q_dim, output_dim, noisy_net=False): - super(ActionScorerAttention, self).__init__() - self.input_q_dim = input_q_dim - self.output_dim = output_dim - self.noisy_net = noisy_net - - if self.noisy_net: - self.W_a = NoisyLinear(self.input_q_dim, self.output_dim) - else: - self.W_a = torch.nn.Linear(self.input_q_dim, self.output_dim) - self.init_weights() - - def init_weights(self): - if not self.noisy_net: - torch.nn.init.xavier_uniform_(self.W_a.weight.data, gain=1) - self.W_a.bias.data.fill_(0) - - def forward(self, H_q): - # H_q: batch x inp_q - Fk_prime = self.W_a(H_q) # batch x out - Fk_prime = torch.sigmoid(Fk_prime) # batch x out - return Fk_prime - - def reset_noise(self): - if self.noisy_net: - self.W_a.reset_noise() - - -class ActionScorerAttentionAdvantage(torch.nn.Module): - - def __init__(self, input_seq_dim, input_q_dim, output_dim, noisy_net=False): - super(ActionScorerAttentionAdvantage, self).__init__() - self.input_seq_dim = input_seq_dim - self.input_q_dim = input_q_dim - self.output_dim = output_dim - self.noisy_net = noisy_net - - if self.noisy_net: - self.V = NoisyLinear(self.input_seq_dim, self.output_dim) - self.W_a = NoisyLinear(self.input_q_dim, self.output_dim) - else: - self.V = torch.nn.Linear(self.input_seq_dim, self.output_dim) - self.W_a = torch.nn.Linear(self.input_q_dim, self.output_dim) - self.v = torch.nn.Parameter(torch.FloatTensor(self.output_dim)) - self.init_weights() - - def init_weights(self): - if not self.noisy_net: - torch.nn.init.xavier_uniform_(self.V.weight.data, gain=1) - torch.nn.init.xavier_uniform_(self.W_a.weight.data, gain=1) - self.V.bias.data.fill_(0) - self.W_a.bias.data.fill_(0) - torch.nn.init.normal_(self.v.data, mean=0, std=0.05) - - def forward(self, H_r, mask_r, H_q): - # H_r: batch x time x input_seq_dim - # mask_r: batch x time - # H_q: batch x inp_q - batch_size, time = H_r.size(0), H_r.size(1) - Fk = self.V(H_r.view(-1, H_r.size(2))) # batch*time x out - Fk_prime = self.W_a(H_q) # batch x out - Fk = Fk.view(batch_size, time, -1) # batch x time x out - Fk = torch.sigmoid(Fk + Fk_prime.unsqueeze(1)) # batch x time x out - Fk = Fk * mask_r.unsqueeze(-1) # batch x time x out - return Fk - - def reset_noise(self): - if self.noisy_net: - self.V.reset_noise() - self.W_a.reset_noise() - - -class BoundaryDecoderAttention(torch.nn.Module): - - def __init__(self, input_dim, output_dim, noisy_net=False): - super(BoundaryDecoderAttention, self).__init__() - self.input_dim = input_dim - self.output_dim = output_dim - self.noisy_net = noisy_net - - if self.noisy_net: - self.V = NoisyLinear(self.input_dim, self.output_dim) - self.W_a = NoisyLinear(self.output_dim, self.output_dim) - else: - self.V = torch.nn.Linear(self.input_dim, self.output_dim) - self.W_a = torch.nn.Linear(self.output_dim, self.output_dim) - self.v = torch.nn.Parameter(torch.FloatTensor(self.output_dim)) - self.c = torch.nn.Parameter(torch.FloatTensor(1)) - self.init_weights() - - def init_weights(self): - if not self.noisy_net: - torch.nn.init.xavier_uniform_(self.V.weight.data) - torch.nn.init.xavier_uniform_(self.W_a.weight.data) - self.V.bias.data.fill_(0) - self.W_a.bias.data.fill_(0) - torch.nn.init.normal_(self.v.data, mean=0, std=0.05) - self.c.data.fill_(1.0) - - def forward(self, H_r, mask_r, h_tm1): - # H_r: batch x time x inp - # mask_r: batch x time - # h_tm1: batch x out - batch_size, time = H_r.size(0), H_r.size(1) - Fk = self.V(H_r.view(-1, H_r.size(2))) # batch*time x out - Fk_prime = self.W_a(h_tm1) # batch x out - Fk = Fk.view(batch_size, time, -1) # batch x time x out - Fk = torch.tanh(Fk + Fk_prime.unsqueeze(1)) # batch x time x out - - beta = torch.matmul(Fk, self.v) # batch x time - beta = beta + self.c.unsqueeze(0) # batch x time - beta = masked_softmax(beta, mask_r, axis=-1) # batch x time - z = torch.bmm(beta.view(beta.size(0), 1, beta.size(1)), H_r) # batch x 1 x inp - z = z.view(z.size(0), -1) # batch x inp - return z, beta - - def reset_noise(self): - if self.noisy_net: - self.V.reset_noise() - self.W_a.reset_noise() - - -class BoundaryDecoder(torch.nn.Module): - ''' - input: encoded stories: batch x time x input_dim - story mask: batch x time - init states: batch x hid - encoded question: batch x input_dim_q - ''' - - def __init__(self, input_dim, hidden_dim, noisy_net=False): - super(BoundaryDecoder, self).__init__() - self.input_dim = input_dim - self.hidden_dim = hidden_dim - self.noisy_net = noisy_net - self.attention_layer = BoundaryDecoderAttention(input_dim=input_dim, - output_dim=hidden_dim, - noisy_net=self.noisy_net) - - self.rnn = LSTMCell(self.input_dim, self.hidden_dim, use_bias=True) - - def forward(self, x, x_mask, h_0): - - state_stp = [(h_0, h_0)] - beta_list = [] - mask = torch.autograd.Variable(torch.ones(x.size(0))) # fake mask - mask = mask.cuda() if x.is_cuda else mask - for t in range(2): - previous_h, previous_c = state_stp[t] - curr_input, beta = self.attention_layer(x, x_mask, h_tm1=previous_h) - new_h, new_c = self.rnn(curr_input, mask, previous_h, previous_c) - state_stp.append((new_h, new_c)) - beta_list.append(beta) - - # beta list: list of batch x time - res = torch.stack(beta_list, 2) # batch x time x 2 - res = res * x_mask.unsqueeze(2) # batch x time x 2 - return res - - def reset_noise(self): - if self.noisy_net: - self.attention_layer.reset_noise() - - -class NoisyLinear(torch.nn.Module): - # Factorised NoisyLinear layer with bias - def __init__(self, in_features, out_features, std_init=0.5): - super(NoisyLinear, self).__init__() - self.in_features = in_features - self.out_features = out_features - self.std_init = std_init - self.weight_mu = torch.nn.Parameter(torch.empty(out_features, in_features)) - self.weight_sigma = torch.nn.Parameter(torch.empty(out_features, in_features)) - self.register_buffer('weight_epsilon', torch.empty(out_features, in_features)) - self.bias_mu = torch.nn.Parameter(torch.empty(out_features)) - self.bias_sigma = torch.nn.Parameter(torch.empty(out_features)) - self.register_buffer('bias_epsilon', torch.empty(out_features)) - self.reset_parameters() - self.reset_noise() - - def reset_parameters(self): - mu_range = 1 / math.sqrt(self.in_features) - self.weight_mu.data.uniform_(-mu_range, mu_range) - self.weight_sigma.data.fill_(self.std_init / math.sqrt(self.in_features)) - self.bias_mu.data.uniform_(-mu_range, mu_range) - self.bias_sigma.data.fill_(self.std_init / math.sqrt(self.out_features)) - - def _scale_noise(self, size): - x = torch.randn(size) - return x.sign().mul_(x.abs().sqrt_()) - - def reset_noise(self): - epsilon_in = self._scale_noise(self.in_features) - epsilon_out = self._scale_noise(self.out_features) - self.weight_epsilon.copy_(epsilon_out.ger(epsilon_in)) - self.bias_epsilon.copy_(epsilon_out) - - def forward(self, input): - if self.training: - return F.linear(input, self.weight_mu + self.weight_sigma * self.weight_epsilon, self.bias_mu + self.bias_sigma * self.bias_epsilon) - else: - return F.linear(input, self.weight_mu, self.bias_mu) - - -################################# qanet - -def PosEncoder(x, min_timescale=1.0, max_timescale=1.0e4): - length = x.size(1) - channels = x.size(2) - signal = get_timing_signal(length, channels, min_timescale, max_timescale) - return x + (signal.cuda() if x.is_cuda else signal) - - -def get_timing_signal(length, channels, min_timescale=1.0, max_timescale=1.0e4): - position = torch.arange(length).type(torch.float32) - num_timescales = channels // 2 - log_timescale_increment = (math.log(float(max_timescale) / float(min_timescale)) / (float(num_timescales)-1)) - inv_timescales = min_timescale * torch.exp( - torch.arange(num_timescales).type(torch.float32) * -log_timescale_increment) - scaled_time = position.unsqueeze(1) * inv_timescales.unsqueeze(0) - signal = torch.cat([torch.sin(scaled_time), torch.cos(scaled_time)], dim = 1) - m = torch.nn.ZeroPad2d((0, (channels % 2), 0, 0)) - signal = m(signal) - signal = signal.view(1, length, channels) - return signal - - -class DepthwiseSeparableConv(torch.nn.Module): - def __init__(self, in_ch, out_ch, k, bias=True): - super().__init__() - self.depthwise_conv = torch.nn.Conv1d(in_channels=in_ch, out_channels=in_ch, kernel_size=k, groups=in_ch, padding=k // 2, bias=False) - self.pointwise_conv = torch.nn.Conv1d(in_channels=in_ch, out_channels=out_ch, kernel_size=1, padding=0, bias=bias) - - def forward(self, x, mask): - # x: batch x length x h - # mask: batch x length - x = x.transpose(1, 2) - res = self.depthwise_conv(x) * mask.unsqueeze(1) - res = torch.relu(self.pointwise_conv(res)) * mask.unsqueeze(1) - res = res.transpose(1, 2) - return res - - -class SimpleSelfAttention(torch.nn.Module): - def __init__(self, hidden_size): - super(SimpleSelfAttention, self).__init__() - self.hidden_size = hidden_size - self.att_weights = torch.nn.Parameter(torch.Tensor(hidden_size, 1), requires_grad=True) - torch.nn.init.xavier_uniform(self.att_weights.data) - - def forward(self, input, mask): - batch_size = input.size(0) - # apply attention layer - weights = torch.bmm(input, self.att_weights.unsqueeze(0).repeat(batch_size, 1, 1)).squeeze(-1) - attentions = masked_softmax(weights, mask) - # apply attention weights - weighted = torch.mul(input, attentions.unsqueeze(-1).expand_as(input)) - return weighted, attentions - - -class ScaledDotProductAttention(torch.nn.Module): - ''' Scaled Dot-Product Attention ''' - - def __init__(self, temperature, attn_dropout=0.1): - super().__init__() - self.temperature = temperature - self.dropout = torch.nn.Dropout(attn_dropout) - - def forward(self, q, k, v, mask): - attn = torch.bmm(q, k.transpose(1, 2)) - attn = attn / self.temperature - attn = masked_softmax(attn, mask, 2) - attn = self.dropout(attn) - output = torch.bmm(attn, v) - return output, attn - - -class SelfAttention(torch.nn.Module): - ''' From Multi-Head Attention module - https://github.com/jadore801120/attention-is-all-you-need-pytorch''' - - def __init__(self, block_hidden_dim, n_head, dropout=0.1): - super().__init__() - - self.n_head = n_head - self.block_hidden_dim = block_hidden_dim - self.w_qs = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False) - self.w_ks = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False) - self.w_vs = torch.nn.Linear(block_hidden_dim, n_head * block_hidden_dim, bias=False) - torch.nn.init.normal_(self.w_qs.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2))) - torch.nn.init.normal_(self.w_ks.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2))) - torch.nn.init.normal_(self.w_vs.weight, mean=0, std=np.sqrt(2.0 / (block_hidden_dim * 2))) - self.attention = ScaledDotProductAttention(temperature=np.power(block_hidden_dim, 0.5)) - self.fc = torch.nn.Linear(n_head * block_hidden_dim, block_hidden_dim) - self.layer_norm = torch.nn.LayerNorm(self.block_hidden_dim) - torch.nn.init.xavier_normal_(self.fc.weight) - self.dropout = torch.nn.Dropout(dropout) - - def forward(self, q, mask, k, v): - # q: batch x len_q x hid - # k: batch x len_k x hid - # v: batch x len_v x hid - # mask: batch x len_q x len_k - batch_size, len_q = q.size(0), q.size(1) - len_k, len_v = k.size(1), v.size(1) - assert mask.size(1) == len_q - assert mask.size(2) == len_k - residual = q - - q = self.w_qs(q).view(batch_size, len_q, self.n_head, self.block_hidden_dim) - k = self.w_ks(k).view(batch_size, len_k, self.n_head, self.block_hidden_dim) - v = self.w_vs(v).view(batch_size, len_v, self.n_head, self.block_hidden_dim) - - q = q.permute(2, 0, 1, 3).contiguous().view(-1, len_q, self.block_hidden_dim) # (n*b) x lq x dk - k = k.permute(2, 0, 1, 3).contiguous().view(-1, len_k, self.block_hidden_dim) # (n*b) x lk x dk - v = v.permute(2, 0, 1, 3).contiguous().view(-1, len_v, self.block_hidden_dim) # (n*b) x lv x dv - - mask = mask.repeat(self.n_head, 1, 1) # (n*b) x .. x .. - output, attn = self.attention(q, k, v, mask=mask) - - output = output.view(self.n_head, batch_size, len_q, self.block_hidden_dim) - output = output.permute(1, 2, 0, 3).contiguous().view(batch_size, len_q, -1) # b x lq x (n*dv) - output = self.dropout(self.fc(output)) - output = self.layer_norm(output + residual) - - return output, attn - - -class EncoderBlock(torch.nn.Module): - def __init__(self, conv_num, ch_num, k, block_hidden_dim, n_head, dropout): - super().__init__() - self.dropout = dropout - self.convs = torch.nn.ModuleList([DepthwiseSeparableConv(ch_num, ch_num, k) for _ in range(conv_num)]) - self.self_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.FFN_1 = torch.nn.Linear(ch_num, ch_num) - self.FFN_2 = torch.nn.Linear(ch_num, ch_num) - self.norm_C = torch.nn.ModuleList([torch.nn.LayerNorm(block_hidden_dim) for _ in range(conv_num)]) - self.norm_1 = torch.nn.LayerNorm(block_hidden_dim) - self.norm_2 = torch.nn.LayerNorm(block_hidden_dim) - self.conv_num = conv_num - - def forward(self, x, mask, squared_mask, l, blks): - total_layers = (self.conv_num + 2) * blks - # conv layers - out = PosEncoder(x) - out = out * mask.unsqueeze(-1) - for i, conv in enumerate(self.convs): - res = out - out = self.norm_C[i](out) - if (i) % 2 == 0: - out = F.dropout(out, p=self.dropout, training=self.training) - out = conv(out, mask) - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - out = out * mask.unsqueeze(-1) - l += 1 - res = out - out = self.norm_1(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # self attention - out, _ = self.self_att(out, squared_mask, out, out) - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - out = out * mask.unsqueeze(-1) - l += 1 - res = out - out = self.norm_2(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # fully connected layers - out = self.FFN_1(out) - out = torch.relu(out) - out = self.FFN_2(out) - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - out = out * mask.unsqueeze(-1) - l += 1 - return out - - def layer_dropout(self, inputs, residual, dropout): - if self.training == True: - pred = torch.empty(1).uniform_(0, 1) < dropout - if pred: - return residual - else: - return F.dropout(inputs, dropout, training=self.training) + residual - else: - return inputs + residual - - -class DecoderBlock(torch.nn.Module): - def __init__(self, ch_num, k, block_hidden_dim, n_head, dropout): - super().__init__() - self.dropout = dropout - self.self_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.obs_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.FFN_0 = torch.nn.Linear(block_hidden_dim, block_hidden_dim) - self.FFN_1 = torch.nn.Linear(ch_num, ch_num) - self.FFN_2 = torch.nn.Linear(ch_num, ch_num) - self.norm_1 = torch.nn.LayerNorm(block_hidden_dim) - self.norm_2 = torch.nn.LayerNorm(block_hidden_dim) - - def forward(self, x, mask, self_att_mask, obs_enc_representations, obs_mask, l, blks): - total_layers = blks * 3 - # conv layers - out = PosEncoder(x) - res = out - # self attention - out, _ = self.self_att(out, self_att_mask, out, out) - out_self = out * mask.unsqueeze(-1) - out = self.layer_dropout(out_self, res, self.dropout * float(l) / total_layers) - l += 1 - res = out - out = self.norm_1(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # attention with encoder outputs - out_obs, obs_attention = self.obs_att(out, obs_mask, obs_enc_representations, obs_enc_representations) - - out = self.FFN_0(out_obs) - out = torch.relu(out) - out = out * mask.unsqueeze(-1) - - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - l += 1 - res = out - out = self.norm_2(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # Fully connected layers - out = self.FFN_1(out) - out = torch.relu(out) - out = self.FFN_2(out) - out = out * mask.unsqueeze(-1) - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - l += 1 - return out, out_self, out_obs, obs_attention - - def layer_dropout(self, inputs, residual, dropout): - if self.training == True: - pred = torch.empty(1).uniform_(0, 1) < dropout - if pred: - return residual - else: - return F.dropout(inputs, dropout, training=self.training) + residual - else: - return inputs + residual - - -class DecoderBlockForObsGen(torch.nn.Module): - def __init__(self, ch_num, k, block_hidden_dim, n_head, dropout): - super().__init__() - self.dropout = dropout - self.self_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.obs_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.node_att = SelfAttention(block_hidden_dim, n_head, dropout) - self.FFN_0 = torch.nn.Linear(block_hidden_dim * 2, block_hidden_dim) - self.FFN_1 = torch.nn.Linear(ch_num, ch_num) - self.FFN_2 = torch.nn.Linear(ch_num, ch_num) - self.norm_1 = torch.nn.LayerNorm(block_hidden_dim) - self.norm_2 = torch.nn.LayerNorm(block_hidden_dim) - - def forward(self, x, mask, self_att_mask, prev_action_enc_representations, prev_action_mask, node_enc_representations, node_mask, l, blks): - total_layers = blks * 3 - # conv layers - out = PosEncoder(x) - res = out - # self attention - out, _ = self.self_att(out, self_att_mask, out, out) - out_self = out * mask.unsqueeze(-1) - out = self.layer_dropout(out_self, res, self.dropout * float(l) / total_layers) - l += 1 - res = out - out = self.norm_1(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # attention with encoder outputs - out_obs, obs_attention = self.obs_att(out, prev_action_mask, prev_action_enc_representations, prev_action_enc_representations) - out_node, _ = self.node_att(out, node_mask, node_enc_representations, node_enc_representations) - - out = torch.cat([out_obs, out_node], -1) - out = self.FFN_0(out) - out = torch.relu(out) - out = out * mask.unsqueeze(-1) - - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - l += 1 - res = out - out = self.norm_2(out) - out = F.dropout(out, p=self.dropout, training=self.training) - # Fully connected layers - out = self.FFN_1(out) - out = torch.relu(out) - out = self.FFN_2(out) - out = out * mask.unsqueeze(-1) - out = self.layer_dropout(out, res, self.dropout * float(l) / total_layers) - l += 1 - return out, out_self #, out_obs, obs_attention - - def layer_dropout(self, inputs, residual, dropout): - if self.training == True: - pred = torch.empty(1).uniform_(0, 1) < dropout - if pred: - return residual - else: - return F.dropout(inputs, dropout, training=self.training) + residual - else: - return inputs + residual - - -class CQAttention(torch.nn.Module): - def __init__(self, block_hidden_dim, dropout=0): - super().__init__() - self.dropout = dropout - w4C = torch.empty(block_hidden_dim, 1) - w4Q = torch.empty(block_hidden_dim, 1) - w4mlu = torch.empty(1, 1, block_hidden_dim) - torch.nn.init.xavier_uniform_(w4C) - torch.nn.init.xavier_uniform_(w4Q) - torch.nn.init.xavier_uniform_(w4mlu) - self.w4C = torch.nn.Parameter(w4C) - self.w4Q = torch.nn.Parameter(w4Q) - self.w4mlu = torch.nn.Parameter(w4mlu) - - bias = torch.empty(1) - torch.nn.init.constant_(bias, 0) - self.bias = torch.nn.Parameter(bias) - - def forward(self, C, Q, Cmask, Qmask): - S = self.trilinear_for_attention(C, Q, Cmask, Qmask) - Cmask = Cmask.unsqueeze(-1) - Qmask = Qmask.unsqueeze(1) - S1 = masked_softmax(S, Qmask, axis=2) - S2 = masked_softmax(S, Cmask, axis=1) - S1 = S1 * Qmask * Cmask - S2 = S2 * Qmask * Cmask - A = torch.bmm(S1, Q) - B = torch.bmm(torch.bmm(S1, S2.transpose(1, 2)), C) - out = torch.cat([C, A, torch.mul(C, A), torch.mul(C, B)], dim=2) - return out - - def trilinear_for_attention(self, C, Q, Cmask, Qmask): - C = F.dropout(C, p=self.dropout, training=self.training) - Q = F.dropout(Q, p=self.dropout, training=self.training) - max_q_len = Q.size(-2) - max_context_len = C.size(-2) - subres0 = torch.matmul(C, self.w4C).expand([-1, -1, max_q_len]) - subres1 = torch.matmul(Q, self.w4Q).transpose(1, 2).expand([-1, max_context_len, -1]) - subres2 = torch.matmul(C * self.w4mlu, Q.transpose(1, 2)) - res = subres0 + subres1 + subres2 - res += self.bias - res = res * Qmask.unsqueeze(1) * Cmask.unsqueeze(-1) - return res - - -class AnswerPointer(torch.nn.Module): - def __init__(self, block_hidden_dim, noisy_net=False): - super().__init__() - self.noisy_net = noisy_net - if self.noisy_net: - self.w_head_1 = NoisyLinear(block_hidden_dim * 2, block_hidden_dim) - self.w_tail_1 = NoisyLinear(block_hidden_dim * 2, block_hidden_dim) - self.w_head_2 = NoisyLinear(block_hidden_dim, 1) - self.w_tail_2 = NoisyLinear(block_hidden_dim, 1) - # self.w_head_2 = NoisyLinear(block_hidden_dim * 2, 1) - # self.w_tail_2 = NoisyLinear(block_hidden_dim * 2, 1) - else: - self.w_head_1 = torch.nn.Linear(block_hidden_dim * 2, block_hidden_dim) - self.w_tail_1 = torch.nn.Linear(block_hidden_dim * 2, block_hidden_dim) - self.w_head_2 = torch.nn.Linear(block_hidden_dim, 1) - self.w_tail_2 = torch.nn.Linear(block_hidden_dim, 1) - # self.w_head_2 = torch.nn.Linear(block_hidden_dim * 2, 1) - # self.w_tail_2 = torch.nn.Linear(block_hidden_dim * 2, 1) - - def forward(self, M1, M2, M3, mask): - X_head = torch.cat([M1, M2], dim=-1) - X_tail = torch.cat([M1, M3], dim=-1) - X_head = torch.relu(self.w_head_1(X_head)) - X_tail = torch.relu(self.w_tail_1(X_tail)) - Y_head = masked_softmax(self.w_head_2(X_head).squeeze(), mask, axis=1) - Y_tail = masked_softmax(self.w_tail_2(X_tail).squeeze(), mask, axis=1) - return torch.stack([Y_head, Y_tail], -1) - - def reset_noise(self): - if self.noisy_net: - self.w_head_1.reset_noise() - self.w_tail_1.reset_noise() - self.w_head_2.reset_noise() - self.w_tail_2.reset_noise() - - -class Highway(torch.nn.Module): - def __init__(self, layer_num, size, dropout=0): - super().__init__() - self.n = layer_num - self.dropout = dropout - self.linear = torch.nn.ModuleList([torch.nn.Linear(size, size) for _ in range(self.n)]) - self.gate = torch.nn.ModuleList([torch.nn.Linear(size, size) for _ in range(self.n)]) - - def forward(self, x): - #x: shape [batch_size, length, hidden_size] - for i in range(self.n): - gate = torch.sigmoid(self.gate[i](x)) - nonlinear = self.linear[i](x) - nonlinear = F.dropout(nonlinear, p=self.dropout, training=self.training) - x = gate * nonlinear + (1 - gate) * x - return x - - -class MergeEmbeddings(torch.nn.Module): - def __init__(self, block_hidden_dim, word_emb_dim, char_emb_dim, dropout=0): - super().__init__() - self.conv2d = torch.nn.Conv2d(char_emb_dim, block_hidden_dim, kernel_size = (1, 5), padding=0, bias=True) - torch.nn.init.kaiming_normal_(self.conv2d.weight, nonlinearity='relu') - - self.linear = torch.nn.Linear(word_emb_dim + block_hidden_dim, block_hidden_dim, bias=False) - self.high = Highway(2, size=block_hidden_dim, dropout=dropout) - - def forward(self, word_emb, char_emb, mask=None): - char_emb = char_emb.permute(0, 3, 1, 2) # batch x emb x time x nchar - char_emb = self.conv2d(char_emb) # batch x block_hidden_dim x time x nchar-5+1 - if mask is not None: - char_emb = char_emb * mask.unsqueeze(1).unsqueeze(-1) - char_emb = F.relu(char_emb) # batch x block_hidden_dim x time x nchar-5+1 - char_emb, _ = torch.max(char_emb, dim=3) # batch x emb x time - char_emb = char_emb.permute(0, 2, 1) # batch x time x emb - emb = torch.cat([char_emb, word_emb], dim=2) - emb = self.linear(emb) - emb = self.high(emb) - if mask is not None: - emb = emb * mask.unsqueeze(-1) - return emb - - -class GraphConvolution(torch.nn.Module): - """ - Simple GCN layer, similar to https://arxiv.org/abs/1609.02907 - """ - - def __init__(self, in_features, out_features, bias=True): - super(GraphConvolution, self).__init__() - self.in_features = in_features - self.out_features = out_features - self.weight = torch.nn.Linear(self.in_features, self.out_features, bias=False) - if bias: - self.bias = torch.nn.Parameter(torch.FloatTensor(out_features)) - else: - self.register_parameter('bias', None) - self.reset_parameters() - - def reset_parameters(self): - torch.nn.init.xavier_uniform_(self.weight.weight.data) - if self.bias is not None: - self.bias.data.fill_(0) - - def forward(self, input, adj): - # input: batch x num_entity x in_dim - # adj: batch x num_entity x num_entity - support = self.weight(input) # batch x num_entity x out_dim - output = torch.bmm(adj, support) # batch x num_entity x out_dim - if self.bias is not None: - return output + self.bias - else: - return output - - def __repr__(self): - return self.__class__.__name__ + ' (' \ - + str(self.in_features) + ' -> ' \ - + str(self.out_features) + ')' - - -class StackedGraphConvolution(torch.nn.Module): - ''' - input: entity features: batch x num_entity x input_dim - adjacency matrix: batch x num_entity x num_entity - ''' - - def __init__(self, input_dim, hidden_dims, dropout_rate=0.0): - super(StackedGraphConvolution, self).__init__() - self.input_dim = input_dim - self.hidden_dims = hidden_dims - self.dropout_rate = dropout_rate - self.nlayers = len(self.hidden_dims) - self.stack_rnns() - - def stack_rnns(self): - gcns = [GraphConvolution(self.input_dim if i == 0 else self.hidden_dims[i - 1], self.hidden_dims[i]) - for i in range(self.nlayers)] - self.gcns = torch.nn.ModuleList(gcns) - - def forward(self, x, adj): - for i in range(self.nlayers): - res = self.gcns[i](x, adj) # batch x num_nodes x hid - x = F.relu(res) - x = F.dropout(x, self.dropout_rate, training=self.training) - - return res - - -class PointerSoftmax(torch.nn.Module): - def __init__(self, input_dim, hidden_dim): - super().__init__() - self.pointer_softmax_context = torch.nn.Linear(input_dim, hidden_dim) - self.pointer_softmax_target = torch.nn.Linear(input_dim, hidden_dim) - self.pointer_softmax_squash = torch.nn.Linear(hidden_dim, 1) - - def forward(self, target_target_representations, target_source_representations, trg_decoder_output, target_mask, target_source_attention, source_mask, input_source): - # target_target_representations: batch x target_len x hid - # target_source_representations: batch x target_len x hid - # trg_decoder_output: batch x target len x vocab - # target mask: batch x target len - # target_source_attention: batch x target len x source len - # source mask: batch x source len - # input source: batch x source len - batch_size = target_source_attention.size(0) - target_len = target_source_attention.size(1) - source_len = target_source_attention.size(2) - - switch = self.pointer_softmax_context(target_source_representations) # batch x trg_len x hid - switch = switch + self.pointer_softmax_target(target_target_representations) # batch x trg_len x hid - switch = torch.tanh(switch) - switch = switch * target_mask.unsqueeze(-1) - switch = self.pointer_softmax_squash(switch).squeeze(-1) # batch x trg_len - switch = torch.sigmoid(switch) - switch = switch * target_mask # batch x target len - switch = switch.unsqueeze(-1) # batch x target len x 1 - - target_source_attention = target_source_attention * source_mask.unsqueeze(1) - from_vocab = trg_decoder_output # batch x target len x vocab - from_source = torch.autograd.Variable(torch.zeros(batch_size * target_len, from_vocab.size(-1))) # batch x target len x vocab - if from_vocab.is_cuda: - from_source = from_source.cuda() - input_source = input_source.unsqueeze(1).expand(batch_size, target_len, source_len) - input_source = input_source.contiguous().view(batch_size * target_len, -1) # batch*target_len x source_len - from_source = from_source.scatter_add_(1, input_source, target_source_attention.view(batch_size * target_len, -1)) - from_source = from_source.view(batch_size, target_len, -1) # batch x target_len x vocab - merged = switch * from_vocab + (1.0 - switch) * from_source # batch x target_len x vocab - merged = merged * target_mask.unsqueeze(-1) - return merged - - -class RelationalGraphConvolution(torch.nn.Module): - """ - Simple R-GCN layer, modified from theano/keras implementation from https://github.com/tkipf/relational-gcn - We also consider relation representation here (relation labels matter) - """ - - def __init__(self, entity_input_dim, relation_input_dim, num_relations, out_dim, bias=True, num_bases=0): - super(RelationalGraphConvolution, self).__init__() - self.entity_input_dim = entity_input_dim - self.relation_input_dim = relation_input_dim - self.out_dim = out_dim - self.num_relations = num_relations - self.num_bases = num_bases - - if self.num_bases > 0: - self.bottleneck_layer = torch.nn.Linear((self.entity_input_dim + self.relation_input_dim) * self.num_relations, self.num_bases, bias = False) - self.weight = torch.nn.Linear(self.num_bases, self.out_dim, bias=False) - else: - self.weight = torch.nn.Linear((self.entity_input_dim + self.relation_input_dim) * self.num_relations, self.out_dim, bias=False) - if bias: - self.bias = torch.nn.Parameter(torch.FloatTensor(self.out_dim)) - else: - self.register_parameter('bias', None) - self.reset_parameters() - - def reset_parameters(self): - torch.nn.init.xavier_uniform_(self.weight.weight.data) - if self.bias is not None: - self.bias.data.fill_(0) - - def forward(self, node_features, relation_features, adj): - # node_features: batch x num_entity x in_dim - # relation_features: batch x num_relation x in_dim - # adj: batch x num_relations x num_entity x num_entity - supports = [] - for relation_idx in range(self.num_relations): - _r_features = relation_features[:, relation_idx: relation_idx + 1] # batch x 1 x in_dim - _r_features = _r_features.repeat(1, node_features.size(1), 1) # batch x num_entity x in_dim - supports.append(torch.bmm(adj[:, relation_idx], torch.cat([node_features, _r_features], dim=-1))) # batch x num_entity x in_dim+in_dim - supports = torch.cat(supports, dim=-1) # batch x num_entity x (in_dim+in_dim)*num_relations - if self.num_bases > 0: - supports = self.bottleneck_layer(supports) - output = self.weight(supports) # batch x num_entity x out_dim - - if self.bias is not None: - return output + self.bias - else: - return output - - -class StackedRelationalGraphConvolution(torch.nn.Module): - ''' - input: entity features: batch x num_entity x input_dim - relation features: batch x num_relations x input_dim - adjacency matrix: batch x num_relations x num_entity x num_entity - ''' - - def __init__(self, entity_input_dim, relation_input_dim, num_relations, hidden_dims, num_bases, use_highway_connections=False, dropout_rate=0.0, real_valued_graph=False): - super(StackedRelationalGraphConvolution, self).__init__() - self.entity_input_dim = entity_input_dim - self.relation_input_dim = relation_input_dim - self.hidden_dims = hidden_dims - self.num_relations = num_relations - self.dropout_rate = dropout_rate - self.num_bases = num_bases - self.real_valued_graph = real_valued_graph - self.nlayers = len(self.hidden_dims) - self.stack_gcns() - self.use_highway_connections = use_highway_connections - if self.use_highway_connections: - self.stack_highway_connections() - - def stack_highway_connections(self): - highways = [torch.nn.Linear(self.hidden_dims[i], self.hidden_dims[i]) for i in range(self.nlayers)] - self.highways = torch.nn.ModuleList(highways) - self.input_linear = torch.nn.Linear(self.entity_input_dim, self.hidden_dims[0]) - - def stack_gcns(self): - gcns = [RelationalGraphConvolution(self.entity_input_dim if i == 0 else self.hidden_dims[i - 1], self.relation_input_dim, self.num_relations, self.hidden_dims[i], num_bases=self.num_bases) - for i in range(self.nlayers)] - self.gcns = torch.nn.ModuleList(gcns) - - def forward(self, node_features, relation_features, adj): - x = node_features - for i in range(self.nlayers): - if self.use_highway_connections: - if i == 0: - prev = self.input_linear(x) - else: - prev = x.clone() - x = self.gcns[i](x, relation_features, adj) # batch x num_nodes x hid - if self.real_valued_graph: - x = torch.sigmoid(x) - else: - x = F.relu(x) - x = F.dropout(x, self.dropout_rate, training=self.training) - if self.use_highway_connections: - gate = torch.sigmoid(self.highways[i](x)) - x = gate * x + (1 - gate) * prev - return x - - -class DGIDiscriminator(torch.nn.Module): - def __init__(self, n_h): - super(DGIDiscriminator, self).__init__() - self.f_k = torch.nn.Bilinear(n_h, n_h, 1) - for m in self.modules(): - self.weights_init(m) - - def weights_init(self, m): - if isinstance(m, torch.nn.Bilinear): - torch.nn.init.xavier_uniform_(m.weight.data) - if m.bias is not None: - m.bias.data.fill_(0.0) - - def forward(self, c, h_pl, h_mi, s_bias1=None, s_bias2=None): - c_x = torch.unsqueeze(c, 1) - c_x = c_x.expand_as(h_pl) - c_x = c_x.contiguous() - - sc_1 = torch.squeeze(self.f_k(h_pl, c_x), 2) - sc_2 = torch.squeeze(self.f_k(h_mi, c_x), 2) - - if s_bias1 is not None: - sc_1 += s_bias1 - if s_bias2 is not None: - sc_2 += s_bias2 - - logits = torch.cat((sc_1, sc_2), 1) - - return logits - - -class ObservationDiscriminator(torch.nn.Module): - def __init__(self, n_h): - super(ObservationDiscriminator, self).__init__() - self.f_k = torch.nn.Bilinear(2 * n_h, n_h, 1) - for m in self.modules(): - self.weights_init(m) - - def weights_init(self, m): - if isinstance(m, torch.nn.Bilinear): - torch.nn.init.xavier_uniform_(m.weight.data) - if m.bias is not None: - m.bias.data.fill_(0.0) - - def forward(self, c, h_p, p_mask, h_n, n_mask, s_bias1=None, s_bias2=None): - masked_ave_hp = masked_mean(h_p, p_mask) - masked_ave_hn = masked_mean(h_n, n_mask) - - sc_1 = self.f_k(c, masked_ave_hp) - sc_2 = self.f_k(c, masked_ave_hn) - - logits = torch.cat([sc_1, sc_2], dim=0) - return logits - - -class BoxFeaturesFC(torch.nn.Module): - def __init__(self, in_features=1024, out_features=64): - super(BoxFeaturesFC, self).__init__() - self.in_features = in_features - self.out_features = out_features - self.linear1 = torch.nn.Linear(in_features=self.in_features, out_features=256) - self.linear2 = torch.nn.Linear(in_features=256, out_features=self.out_features) - - def pad_and_stack(self, obs, max_feat_len=None): - if not max_feat_len: - max_feat_len = max([o.shape[0] for o in obs]) - padded = [F.pad(input=o, pad=(0, 0, 0, max_feat_len-o.shape[0]), mode='constant', value=0) for o in obs] - return torch.stack(padded, dim=0) - - def forward(self, x): - x = self.pad_and_stack(x) - x = self.linear1(x) - x = self.linear2(x) - return x \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/memory.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/memory.py deleted file mode 100644 index 86cb1eb3..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/memory.py +++ /dev/null @@ -1,337 +0,0 @@ -# part of the code are from https://github.com/hill-a/stable-baselines/ -import random -from collections import namedtuple -import numpy as np -import torch - - -# a snapshot of state to be stored in replay memory -Transition = namedtuple('Transition', ('observation_list', 'task_list', 'action_candidate_list', 'chosen_indices', 'reward', 'count_reward', 'novel_object_reward')) -# a snapshot of state to be stored in replay memory for question answering -dagger_transition = namedtuple('dagger_transition', ('observation_list', 'task_list', 'action_candidate_list', 'target_list', 'target_indices')) - - -class PrioritizedReplayMemory(object): - - def __init__(self, capacity=100000, priority_fraction=0.0, - discount_gamma_game_reward=1.0, discount_gamma_count_reward=0.0, discount_gamma_novel_object_reward=0.0, - accumulate_reward_from_final=False): - # prioritized replay memory - self.priority_fraction = priority_fraction - self.alpha_capacity = int(capacity * priority_fraction) - self.beta_capacity = capacity - self.alpha_capacity - self.alpha_memory, self.beta_memory = [], [] - self.alpha_rewards, self.beta_rewards = [], [] - self.accumulate_reward_from_final = accumulate_reward_from_final - self.discount_gamma_game_reward = discount_gamma_game_reward - self.discount_gamma_count_reward = discount_gamma_count_reward - self.discount_gamma_novel_object_reward = discount_gamma_novel_object_reward - - def push(self, is_prior, reward, t): - """Saves a transition.""" - if self.priority_fraction == 0.0: - is_prior = False - trajectory = [] - for i in range(len(t)): - trajectory.append(Transition(t[i][0], t[i][1], t[i][2], t[i][3], t[i][4], t[i][5], t[i][6])) - if is_prior: - self.alpha_memory.append(trajectory) - self.alpha_rewards.append(reward) - if len(self.alpha_memory) > self.alpha_capacity: - remove_id = np.random.randint(self.alpha_capacity) - self.alpha_memory = self.alpha_memory[:remove_id] + self.alpha_memory[remove_id + 1:] - self.alpha_rewards = self.alpha_rewards[:remove_id] + self.alpha_rewards[remove_id + 1:] - else: - self.beta_memory.append(trajectory) - self.beta_rewards.append(reward) - if len(self.beta_memory) > self.beta_capacity: - remove_id = np.random.randint(self.beta_capacity) - self.beta_memory = self.beta_memory[:remove_id] + self.beta_memory[remove_id + 1:] - self.beta_rewards = self.beta_rewards[:remove_id] + self.beta_rewards[remove_id + 1:] - - def _get_single_transition(self, n, which_memory): - if len(which_memory) == 0: - return None - assert n > 0 - trajectory_id = np.random.randint(len(which_memory)) - trajectory = which_memory[trajectory_id] - - if len(trajectory) <= n: - return None - head = np.random.randint(0, len(trajectory) - n) - final = len(trajectory) - 1 - - # all good - obs = trajectory[head].observation_list - task = trajectory[head].task_list - candidates = trajectory[head].action_candidate_list - chosen_indices = trajectory[head].chosen_indices - - next_obs = trajectory[head + n].observation_list - next_candidates = trajectory[head + n].action_candidate_list - - # 1 2 [3] 4 5 (6) 7 8 9f - how_long = final - head + 1 if self.accumulate_reward_from_final else n + 1 - accumulated_rewards = [self.discount_gamma_game_reward ** i * trajectory[head + i].reward for i in range(how_long)] - accumulated_rewards = accumulated_rewards[:n + 1] - game_reward = torch.sum(torch.stack(accumulated_rewards)) - - accumulated_count_rewards = [self.discount_gamma_count_reward ** i * trajectory[head + i].count_reward for i in range(n + 1)] - accumulated_count_rewards = accumulated_count_rewards[:n + 1] - count_reward = torch.sum(torch.stack(accumulated_count_rewards)) - - accumulated_novel_object_rewards = [self.discount_gamma_novel_object_reward ** i * trajectory[head + i].novel_object_reward for i in range(n + 1)] - accumulated_novel_object_rewards = accumulated_novel_object_rewards[:n + 1] - novel_object_reward = torch.sum(torch.stack(accumulated_novel_object_rewards)) - - return (obs, task, candidates, chosen_indices, game_reward + count_reward + novel_object_reward, next_obs, next_candidates, n) - - def _get_batch(self, n_list, which_memory): - res = [] - for i in range(len(n_list)): - output = self._get_single_transition(n_list[i], which_memory) - if output is None: - continue - res.append(output) - if len(res) == 0: - return None - return res - - def get_batch(self, batch_size, multi_step=1): - from_alpha = min(int(self.priority_fraction * batch_size), len(self.alpha_memory)) - from_beta = min(batch_size - from_alpha, len(self.beta_memory)) - res = [] - if from_alpha == 0: - res_alpha = None - else: - res_alpha = self._get_batch(np.random.randint(1, multi_step + 1, size=from_alpha), self.alpha_memory) - if from_beta == 0: - res_beta = None - else: - res_beta = self._get_batch(np.random.randint(1, multi_step + 1, size=from_beta), self.beta_memory) - if res_alpha is None and res_beta is None: - return None - if res_alpha is not None: - res += res_alpha - if res_beta is not None: - res += res_beta - random.shuffle(res) - - obs_list, task_list, action_candidate_list, chosen_indices_list, reward_list, actual_n_list = [], [], [], [], [], [] - next_obs_list, next_action_candidate_list = [], [] - - for item in res: - obs, task, candidates, chosen_indices, reward, next_obs, next_candidates, n = item - obs_list.append(obs) - task_list.append(task) - action_candidate_list.append(candidates) - chosen_indices_list.append(chosen_indices) - reward_list.append(reward) - next_obs_list.append(next_obs) - next_action_candidate_list.append(next_candidates) - actual_n_list.append(n) - - chosen_indices_list = np.array(chosen_indices_list) # batch - reward_list = torch.stack(reward_list, 0) # batch - actual_n_list = np.array(actual_n_list) - - return [obs_list, task_list, action_candidate_list, chosen_indices_list, reward_list, next_obs_list, next_action_candidate_list, actual_n_list] - - def _get_single_sequence_transition(self, which_memory, sample_history_length, contains_first_step): - if len(which_memory) == 0: - return None - assert sample_history_length > 1 - trajectory_id = np.random.randint(len(which_memory)) - trajectory = which_memory[trajectory_id] - - if len(trajectory) <= sample_history_length: - return None - - # 0 1 2 3 4 5 6 7 - if contains_first_step: - head = 0 - else: - if 1 >= len(trajectory) - sample_history_length: - return None - head = np.random.randint(1, len(trajectory) - sample_history_length) - # tail = head + sample_history_length - 1 - final = len(trajectory) - 1 - - seq_obs, seq_candidates, seq_chosen_indices, seq_reward, seq_next_obs, seq_next_candidates = [], [], [], [], [], [] - task = trajectory[head].task_list - for j in range(sample_history_length): - seq_obs.append(trajectory[head + j].observation_list) - seq_candidates.append(trajectory[head + j].action_candidate_list) - seq_chosen_indices.append(trajectory[head + j].chosen_indices) - seq_next_obs.append(trajectory[head + j + 1].observation_list) - seq_next_candidates.append(trajectory[head + j + 1].action_candidate_list) - - how_long = final - (head + j) + 1 if self.accumulate_reward_from_final else 1 - accumulated_rewards = [self.discount_gamma_game_reward ** i * trajectory[head + j + i].reward for i in range(how_long)] - accumulated_rewards = accumulated_rewards[:1] - game_reward = torch.sum(torch.stack(accumulated_rewards)) - - accumulated_count_rewards = [self.discount_gamma_count_reward ** i * trajectory[head + j + i].count_reward for i in range(how_long)] - accumulated_count_rewards = accumulated_count_rewards[:1] - count_reward = torch.sum(torch.stack(accumulated_count_rewards)) - - accumulated_novel_object_rewards = [self.discount_gamma_novel_object_reward ** i * trajectory[head + j + i].novel_object_reward for i in range(how_long)] - accumulated_novel_object_rewards = accumulated_novel_object_rewards[:1] - novel_object_reward = torch.sum(torch.stack(accumulated_novel_object_rewards)) - seq_reward.append(game_reward + count_reward + novel_object_reward) - - return [seq_obs, seq_candidates, seq_chosen_indices, seq_reward, seq_next_obs, seq_next_candidates, task] - - def _get_batch_of_sequences(self, which_memory, batch_size, sample_history_length, contains_first_step): - assert sample_history_length > 1 - - obs, task, candidates, chosen_indices, reward, next_obs, next_candidates = [], [], [], [], [], [], [] - for _ in range(sample_history_length): - obs.append([]) - candidates.append([]) - chosen_indices.append([]) - reward.append([]) - next_obs.append([]) - next_candidates.append([]) - - # obs, candidate, chosen_indices, graph_triplets, reward, next_obs, next_candidate, next_graph_triplets - for _ in range(batch_size): - t = self._get_single_sequence_transition(which_memory, sample_history_length, contains_first_step) - if t is None: - continue - task.append(t[6]) - for step in range(sample_history_length): - obs[step].append(t[0][step]) - candidates[step].append(t[1][step]) - chosen_indices[step].append(t[2][step]) - reward[step].append(t[3][step]) - next_obs[step].append(t[4][step]) - next_candidates[step].append(t[5][step]) - - if len(task) == 0: - return None - - return [obs, task, candidates, chosen_indices, reward, next_obs, next_candidates] - - def get_batch_of_sequences(self, batch_size, sample_history_length): - - from_alpha = min(int(self.priority_fraction * batch_size), len(self.alpha_memory)) - from_beta = min(batch_size - from_alpha, len(self.beta_memory)) - - random_number = np.random.uniform(low=0.0, high=1.0, size=(1,)) - contains_first_step = random_number[0] < 0.05 # hard coded here. So 5% of the sampled batches will have first step - - if from_alpha == 0: - res_alpha = None - else: - res_alpha = self._get_batch_of_sequences(self.alpha_memory, from_alpha, sample_history_length, contains_first_step) - if from_beta == 0: - res_beta = None - else: - res_beta = self._get_batch_of_sequences(self.beta_memory, from_beta, sample_history_length, contains_first_step) - if res_alpha is None and res_beta is None: - return None - - obs, task, candidates, chosen_indices, reward, next_obs, next_candidates = [], [], [], [], [], [], [] - for _ in range(sample_history_length): - obs.append([]) - candidates.append([]) - chosen_indices.append([]) - reward.append([]) - next_obs.append([]) - next_candidates.append([]) - - if res_alpha is not None: - __obs, __task, __candidates, __chosen_indices, __reward, __next_obs, __next_candidates = res_alpha - task += __task - for i in range(sample_history_length): - obs[i] += __obs[i] - candidates[i] += __candidates[i] - chosen_indices[i] += __chosen_indices[i] - reward[i] += __reward[i] - next_obs[i] += __next_obs[i] - next_candidates[i] += __next_candidates[i] - - if res_beta is not None: - __obs, __task, __candidates, __chosen_indices, __reward, __next_obs, __next_candidates = res_beta - task += __task - for i in range(sample_history_length): - obs[i] += __obs[i] - candidates[i] += __candidates[i] - chosen_indices[i] += __chosen_indices[i] - reward[i] += __reward[i] - next_obs[i] += __next_obs[i] - next_candidates[i] += __next_candidates[i] - - for i in range(sample_history_length): - reward[i] = torch.stack(reward[i], 0) # batch - chosen_indices[i] = np.array(chosen_indices[i]) # batch - - return [obs, task, candidates, chosen_indices, reward, next_obs, next_candidates], contains_first_step - - def get_avg_rewards(self): - if len(self.alpha_rewards) == 0 and len(self.beta_rewards) == 0 : - return 0.0 - return np.mean(self.alpha_rewards + self.beta_rewards) - - def __len__(self): - return len(self.alpha_memory) + len(self.beta_memory) - - -class DaggerReplayMemory(object): - - def __init__(self, capacity=100000): - # replay memory - self.capacity = capacity - self.memory = [] - - def push(self, t): - """Saves a transition.""" - - trajectory = [] - for i in range(len(t)): - trajectory.append(dagger_transition(t[i][0], t[i][1], t[i][2], t[i][3], t[i][4])) - self.memory.append(trajectory) - if len(self.memory) > self.capacity: - remove_id = np.random.randint(self.capacity) - self.memory = self.memory[:remove_id] + self.memory[remove_id + 1:] - - def sample(self, batch_size): - how_many = min(batch_size, len(self.memory)) - res = [] - for _ in range(how_many): - trajectory_id = np.random.randint(len(self.memory)) - trajectory = self.memory[trajectory_id] - head = np.random.randint(0, len(trajectory)) - res.append(trajectory[head]) - return res - - def sample_sequence(self, batch_size, sample_history_length): - assert sample_history_length > 1 - how_many = min(batch_size, len(self.memory)) - res = [] - for _ in range(sample_history_length): - res.append([]) - - random_number = np.random.uniform(low=0.0, high=1.0, size=(1,)) - contains_first_step = random_number[0] < 0.05 # hard coded here. So 5% of the sampled batches will have first step - - for _ in range(how_many): - trajectory_id = np.random.randint(len(self.memory)) - trajectory = self.memory[trajectory_id] - if len(trajectory) < sample_history_length: - continue - if contains_first_step: - head = 0 - else: - if 1 >= len(trajectory) - sample_history_length + 1: - continue - head = np.random.randint(1, len(trajectory) - sample_history_length + 1) - for i in range(sample_history_length): - res[i].append(trajectory[head + i]) - if len(res) == 0: - return None, None - return res, contains_first_step - - def __len__(self): - return len(self.memory) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/model.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/model.py deleted file mode 100644 index 92c7a5b8..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/model.py +++ /dev/null @@ -1,243 +0,0 @@ -import os -import copy -import logging -import numpy as np - -import torch -from alfworld.agents.modules.layers import EncoderBlock, DecoderBlock, NoisyLinear, CQAttention, compute_mask, PointerSoftmax, masked_softmax, SelfAttention, BoxFeaturesFC -BERT_EMBEDDING_SIZE = 768 - -logger = logging.getLogger(__name__) - - -class Policy(torch.nn.Module): - model_name = 'policy' - - def __init__(self, config, bert_model, word_vocab_size): - super(Policy, self).__init__() - self.config = config - self.bert_model = bert_model - self.word_vocab_size = word_vocab_size - self.read_config() - self._def_layers() - # self.print_parameters() - - def print_parameters(self): - amount = 0 - for p in self.parameters(): - amount += np.prod(p.size()) - print("total number of parameters: %s" % (amount)) - parameters = filter(lambda p: p.requires_grad, self.parameters()) - amount = 0 - for p in parameters: - amount += np.prod(p.size()) - print("number of trainable parameters: %s" % (amount)) - - def read_config(self): - # model config - model_config = self.config['general']['model'] - self.encoder_layers = model_config['encoder_layers'] - self.encoder_conv_num = model_config['encoder_conv_num'] - self.block_hidden_dim = model_config['block_hidden_dim'] - self.n_heads = model_config['n_heads'] - self.block_dropout = model_config['block_dropout'] - self.dropout = model_config['dropout'] - self.decoder_layers = model_config['decoder_layers'] - self.recurrent = model_config['recurrent'] - - self.noisy_net = self.config['rl']['epsilon_greedy']['noisy_net'] - - self.resnet_fc_dim = self.config['vision_dagger']['resnet_fc_dim'] - self.vision_model_type = self.config['vision_dagger']['model_type'] - if self.vision_model_type == "maskrcnn_whole": - self.vision_input_dim = 256 - elif self.vision_model_type == "maskrcnn": - self.vision_input_dim = 1024 - else: - self.vision_input_dim = 1000 - - - def _def_layers(self): - - self.word_embedding_prj = torch.nn.Linear(BERT_EMBEDDING_SIZE, self.block_hidden_dim, bias=False) - self.encoder = torch.nn.ModuleList([EncoderBlock(conv_num=self.encoder_conv_num, ch_num=self.block_hidden_dim, k=5, block_hidden_dim=self.block_hidden_dim, n_head=self.n_heads, dropout=self.block_dropout) for _ in range(self.encoder_layers)]) - - self.aggregation_attention = CQAttention(block_hidden_dim=self.block_hidden_dim, dropout=self.dropout) - self.aggregation_attention_proj = torch.nn.Linear(self.block_hidden_dim * 4, self.block_hidden_dim) - - if self.recurrent: - self.rnncell = torch.nn.GRUCell(self.block_hidden_dim, self.block_hidden_dim) - self.dynamics_aggregation = torch.nn.Linear(self.block_hidden_dim * 2, self.block_hidden_dim) - else: - self.rnncell, self.dynamics_aggregation = None, None - - self.decoder = torch.nn.ModuleList([DecoderBlock(ch_num=self.block_hidden_dim, k=5, block_hidden_dim=self.block_hidden_dim, n_head=self.n_heads, dropout=self.block_dropout) for _ in range(self.decoder_layers)]) - self.decoding_to_embedding = torch.nn.Linear(self.block_hidden_dim, BERT_EMBEDDING_SIZE) - self.embedding_to_words = torch.nn.Linear(BERT_EMBEDDING_SIZE, self.word_vocab_size, bias=False) - self.embedding_to_words.weight = self.bert_model.embeddings.word_embeddings.weight - self.embedding_to_words.weight.requires_grad = False - self.pointer_softmax = PointerSoftmax(input_dim=self.block_hidden_dim, hidden_dim=self.block_hidden_dim) - - linear_function = NoisyLinear if self.noisy_net else torch.nn.Linear - self.action_scorer_linear_1 = linear_function(self.block_hidden_dim * 2, self.block_hidden_dim) # [candidate_rep, obs_att] - self.action_scorer_linear_2 = linear_function(self.block_hidden_dim, 1) - self.action_scorer_extra_self_attention = SelfAttention(self.block_hidden_dim, self.n_heads, self.dropout) - self.action_scorer_extra_linear = linear_function(self.block_hidden_dim, self.block_hidden_dim) - - # vision modules - self.vision_fc = BoxFeaturesFC(in_features=self.vision_input_dim, out_features=self.resnet_fc_dim) - self.vision_feat_seq_rnn = torch.nn.GRU(self.vision_input_dim, int(self.vision_input_dim/2), 1, bidirectional=True) - - def get_bert_embeddings(self, _input_words, _input_masks): - # _input_words: batch x time - # _input_masks: batch x time - if _input_words.size(1) > 512: # exceeds the length limit of pre-trained bert max_position_embeddings - # hack - seg_length = 500 - outputs = [] - num_batch = (_input_words.size(1) + seg_length - 1) // seg_length - for i in range(num_batch): - batch_input = _input_words[:, i * seg_length: (i + 1) * seg_length] - batch_mask = _input_masks[:, i * seg_length: (i + 1) * seg_length] - out = self.get_bert_embeddings(batch_input, batch_mask) - outputs.append(out) - return torch.cat(outputs, 1) - - with torch.no_grad(): - res = self.bert_model.embeddings(_input_words) - res = res * _input_masks.unsqueeze(-1) - return res - - def embed(self, input_words, input_word_masks): - word_embeddings = self.get_bert_embeddings(input_words, input_word_masks) # batch x time x emb - word_embeddings = word_embeddings * input_word_masks.unsqueeze(-1) # batch x time x hid - word_embeddings = self.word_embedding_prj(word_embeddings) - word_embeddings = word_embeddings * input_word_masks.unsqueeze(-1) # batch x time x hid - return word_embeddings - - def encode_text(self, input_word_ids): - # input_word_ids: batch x seq_len - # text embedding / encoding - input_word_masks = compute_mask(input_word_ids) - embeddings = self.embed(input_word_ids, input_word_masks) # batch x seq_len x emb - squared_mask = torch.bmm(input_word_masks.unsqueeze(-1), input_word_masks.unsqueeze(1)) # batch x seq_len x seq_len - encoding_sequence = embeddings - for i in range(self.encoder_layers): - encoding_sequence = self.encoder[i](encoding_sequence, input_word_masks, squared_mask, i * (self.encoder_conv_num + 2) + 1, self.encoder_layers) # batch x time x enc - return encoding_sequence, input_word_masks - - def aggretate_information(self, h_obs, obs_mask, h_td, td_mask): - aggregated_obs_representation = self.aggregation_attention(h_obs, h_td, obs_mask, td_mask) # batch x obs_length x 4*hid - aggregated_obs_representation = self.aggregation_attention_proj(aggregated_obs_representation) # batch x obs_length x hid - aggregated_obs_representation = torch.tanh(aggregated_obs_representation) - aggregated_obs_representation = aggregated_obs_representation * obs_mask.unsqueeze(-1) - return aggregated_obs_representation - - def score_actions(self, candidate_representations, cand_mask, h_obs, obs_mask, current_dynamics, fix_shared_components=False): - # candidate_representations: batch x num_candidate x hid - # cand_mask: batch x num_candidate - batch_size, num_candidate = candidate_representations.size(0), candidate_representations.size(1) - aggregated_obs_representation = self.masked_mean(h_obs, obs_mask) # batch x hid - if self.recurrent: - aggregated_obs_representation = self.dynamics_aggregation(torch.cat([aggregated_obs_representation, current_dynamics], -1)) - aggregated_obs_representation = torch.relu(aggregated_obs_representation) # batch x hid - - # if action space is "beam_saerch_choice" - if fix_shared_components: - aggregated_obs_representation = aggregated_obs_representation.detach() - candidate_representations = candidate_representations.detach() - - # only text - new_h_expanded = torch.stack([aggregated_obs_representation] * num_candidate, 1).view(batch_size, num_candidate, aggregated_obs_representation.size(-1)) - output = self.action_scorer_linear_1(torch.cat([candidate_representations, new_h_expanded], -1)) # batch x num_candidate x hid - output = torch.relu(output) - output = output * cand_mask.unsqueeze(-1) - - if fix_shared_components: - # use some extra trainable parameters to increase the model's capacity - cand_mask_squared = torch.bmm(cand_mask.unsqueeze(-1), cand_mask.unsqueeze(1)) # batch x num_candidate x num_candidate - output, _ = self.action_scorer_extra_self_attention(output, cand_mask_squared, output, output) # batch x num_candidate x hid - output = self.action_scorer_extra_linear(output) # batch x num_candidate x hid - output = torch.relu(output) - output = output * cand_mask.unsqueeze(-1) - - output = self.action_scorer_linear_2(output).squeeze(-1) # batch x num_candidate - output = output * cand_mask - - return output, cand_mask - - def get_subsequent_mask(self, seq): - ''' For masking out the subsequent info. ''' - _, length = seq.size() - subsequent_mask = torch.triu(torch.ones((length, length)), diagonal=1).float() - subsequent_mask = 1.0 - subsequent_mask - if seq.is_cuda: - subsequent_mask = subsequent_mask.cuda() - subsequent_mask = subsequent_mask.unsqueeze(0) # 1 x time x time - return subsequent_mask - - def decode(self, input_target_word_ids, input_target_word_masks, h_obs, obs_mask, current_dynamics, input_obs): - trg_mask = input_target_word_masks - trg_embeddings = self.embed(input_target_word_ids, input_target_word_masks) # batch x target_len x emb - - trg_mask_square = torch.bmm(trg_mask.unsqueeze(-1), trg_mask.unsqueeze(1)) # batch x target_len x target_len - trg_mask_square = trg_mask_square * self.get_subsequent_mask(input_target_word_ids) # batch x target_len x target_len - obs_mask_square = torch.bmm(trg_mask.unsqueeze(-1), obs_mask.unsqueeze(1)) # batch x target_len x obs_len - - if self.recurrent: - current_dynamics_expanded = torch.stack([current_dynamics] * h_obs.size(1), 1) # batch x source_len x hid - h_obs = self.dynamics_aggregation(torch.cat([h_obs, current_dynamics_expanded], -1)) # batch x source_len x hid - h_obs = torch.relu(h_obs) # batch x source_len x hid - - trg_decoder_output = trg_embeddings - for i in range(self.decoder_layers): - trg_decoder_output, target_target_representations, target_source_representations, target_source_attention = self.decoder[i](trg_decoder_output, trg_mask, trg_mask_square, h_obs, obs_mask_square, i * 3 + 1, self.decoder_layers) # batch x time x hid - - trg_decoder_output = self.decoding_to_embedding(trg_decoder_output) # batch x time x emb - trg_decoder_output = torch.tanh(trg_decoder_output) - trg_decoder_output = self.embedding_to_words(trg_decoder_output) # batch x time x n_vocab - trg_decoder_output = masked_softmax(trg_decoder_output, m=trg_mask.unsqueeze(-1), axis=-1) - output = self.pointer_softmax(target_target_representations, target_source_representations, trg_decoder_output, trg_mask, target_source_attention, obs_mask, input_obs) - - return output - - def vision_decode(self, input_target_word_ids, input_target_word_masks, h_obs, obs_mask, current_dynamics): - trg_mask = input_target_word_masks - trg_embeddings = self.embed(input_target_word_ids, input_target_word_masks) # batch x target_len x emb - - trg_mask_square = torch.bmm(trg_mask.unsqueeze(-1), trg_mask.unsqueeze(1)) # batch x target_len x target_len - trg_mask_square = trg_mask_square * self.get_subsequent_mask(input_target_word_ids) # batch x target_len x target_len - obs_mask_square = torch.bmm(trg_mask.unsqueeze(-1), obs_mask.unsqueeze(1)) # batch x target_len x obs_len - - if self.recurrent: - current_dynamics_expanded = torch.stack([current_dynamics] * h_obs.size(1), 1) # batch x source_len x hid - h_obs = self.dynamics_aggregation(torch.cat([h_obs, current_dynamics_expanded], -1)) # batch x source_len x hid - h_obs = torch.relu(h_obs) # batch x source_len x hid - - trg_decoder_output = trg_embeddings - for i in range(self.decoder_layers): - trg_decoder_output, target_target_representations, target_source_representations, target_source_attention = self.decoder[i](trg_decoder_output, trg_mask, trg_mask_square, h_obs, obs_mask_square, i * 3 + 1, self.decoder_layers) # batch x time x hid - - trg_decoder_output = self.decoding_to_embedding(trg_decoder_output) # batch x time x emb - trg_decoder_output = torch.tanh(trg_decoder_output) - trg_decoder_output = self.embedding_to_words(trg_decoder_output) # batch x time x n_vocab - trg_decoder_output = masked_softmax(trg_decoder_output, m=trg_mask.unsqueeze(-1), axis=-1) - - return trg_decoder_output - - def masked_mean(self, h_obs, obs_mask): - # h_obs: batch x obs_length x hid - # obs_mask: batch x obs_length - _mask = torch.sum(obs_mask, -1) # batch - obs_representations = torch.sum(h_obs, -2) # batch x hid - tmp = torch.eq(_mask, 0).float() - if obs_representations.is_cuda: - tmp = tmp.cuda() - _mask = _mask + tmp - obs_representations = obs_representations / _mask.unsqueeze(-1) # batch x hid - return obs_representations - - def reset_noise(self): - if self.noisy_net: - self.action_scorer_linear_1.reset_noise() - self.action_scorer_linear_2.reset_noise() diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/segment_tree.py b/agent_system/environments/env_package/alfworld/alfworld/agents/modules/segment_tree.py deleted file mode 100644 index e6999f1f..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/modules/segment_tree.py +++ /dev/null @@ -1,138 +0,0 @@ -# code from https://github.com/hill-a/stable-baselines/ -import operator - - -class SegmentTree(object): - def __init__(self, capacity, operation, neutral_element): - """ - Build a Segment Tree data structure. - - https://en.wikipedia.org/wiki/Segment_tree - - Can be used as regular array, but with two - important differences: - - a) setting item's value is slightly slower. - It is O(lg capacity) instead of O(1). - b) user has access to an efficient ( O(log segment size) ) - `reduce` operation which reduces `operation` over - a contiguous subsequence of items in the array. - - :param capacity: (int) Total size of the array - must be a power of two. - :param operation: (lambda (Any, Any): Any) operation for combining elements (eg. sum, max) must form a - mathematical group together with the set of possible values for array elements (i.e. be associative) - :param neutral_element: (Any) neutral element for the operation above. eg. float('-inf') for max and 0 for sum. - """ - assert capacity > 0 and capacity & (capacity - 1) == 0, "capacity must be positive and a power of 2." - self._capacity = capacity - self._value = [neutral_element for _ in range(2 * capacity)] - self._operation = operation - - def _reduce_helper(self, start, end, node, node_start, node_end): - if start == node_start and end == node_end: - return self._value[node] - mid = (node_start + node_end) // 2 - if end <= mid: - return self._reduce_helper(start, end, 2 * node, node_start, mid) - else: - if mid + 1 <= start: - return self._reduce_helper(start, end, 2 * node + 1, mid + 1, node_end) - else: - return self._operation( - self._reduce_helper(start, mid, 2 * node, node_start, mid), - self._reduce_helper(mid + 1, end, 2 * node + 1, mid + 1, node_end) - ) - - def reduce(self, start=0, end=None): - """ - Returns result of applying `self.operation` - to a contiguous subsequence of the array. - - self.operation(arr[start], operation(arr[start+1], operation(... arr[end]))) - - :param start: (int) beginning of the subsequence - :param end: (int) end of the subsequences - :return: (Any) result of reducing self.operation over the specified range of array elements. - """ - if end is None: - end = self._capacity - if end < 0: - end += self._capacity - end -= 1 - return self._reduce_helper(start, end, 1, 0, self._capacity - 1) - - def __setitem__(self, idx, val): - # index of the leaf - idx += self._capacity - self._value[idx] = val - idx //= 2 - while idx >= 1: - self._value[idx] = self._operation( - self._value[2 * idx], - self._value[2 * idx + 1] - ) - idx //= 2 - - def __getitem__(self, idx): - assert 0 <= idx < self._capacity - return self._value[self._capacity + idx] - - -class SumSegmentTree(SegmentTree): - def __init__(self, capacity): - super(SumSegmentTree, self).__init__( - capacity=capacity, - operation=operator.add, - neutral_element=0.0 - ) - - def sum(self, start=0, end=None): - """ - Returns arr[start] + ... + arr[end] - - :param start: (int) start position of the reduction (must be >= 0) - :param end: (int) end position of the reduction (must be < len(arr), can be None for len(arr) - 1) - :return: (Any) reduction of SumSegmentTree - """ - return super(SumSegmentTree, self).reduce(start, end) - - def find_prefixsum_idx(self, prefixsum): - """ - Find the highest index `i` in the array such that - sum(arr[0] + arr[1] + ... + arr[i - i]) <= prefixsum - - if array values are probabilities, this function - allows to sample indexes according to the discrete - probability efficiently. - - :param prefixsum: (float) upperbound on the sum of array prefix - :return: (int) highest index satisfying the prefixsum constraint - """ - assert 0 <= prefixsum <= self.sum() + 1e-5 - idx = 1 - while idx < self._capacity: # while non-leaf - if self._value[2 * idx] > prefixsum: - idx = 2 * idx - else: - prefixsum -= self._value[2 * idx] - idx = 2 * idx + 1 - return idx - self._capacity - - -class MinSegmentTree(SegmentTree): - def __init__(self, capacity): - super(MinSegmentTree, self).__init__( - capacity=capacity, - operation=min, - neutral_element=float('inf') - ) - - def min(self, start=0, end=None): - """ - Returns min(arr[start], ..., arr[end]) - - :param start: (int) start position of the reduction (must be >= 0) - :param end: (int) end position of the reduction (must be < len(arr), can be None for len(arr) - 1) - :return: (Any) reduction of MinSegmentTree - """ - return super(MinSegmentTree, self).reduce(start, end) diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/utils/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/agents/utils/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/agents/utils/misc.py b/agent_system/environments/env_package/alfworld/alfworld/agents/utils/misc.py deleted file mode 100644 index 3d0297e6..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/agents/utils/misc.py +++ /dev/null @@ -1,306 +0,0 @@ -import hashlib -import random -import string - -from collections import Counter -from textworld.logic import Proposition, Variable - -import os -import sys -import alfworld.gen.goal_library as glib -import alfworld.gen.constants as constants - -import numpy as np -from json import JSONEncoder - - -class Demangler(object): - - def __init__(self, obj_dict=None, game_infos=None, shuffle=False): - if obj_dict is None: - self.obj_count = Counter() - else: - self.obj_count = obj_dict - - self.obj_names = {} - if game_infos: - ids = sorted([info.id for info in game_infos.values()]) - if shuffle: - random.shuffle(ids) - - # count the number of instances - for id in ids: - splits = id.split("_bar_", 1) - if len(splits) > 1: - name, rest = splits - if "basin" in id: - name += "basin" - self.obj_count[name] += 1 - - # make list of num ids for each object (shuffle the ids if required) - obj_num_ids = {} - for obj, count in self.obj_count.most_common(): - num_ids = list(range(count+1)[1:]) # start from index 1 - obj_num_ids[obj] = num_ids - - # assign unique num id for each object based on precomputed list - for id in ids: - text = id - text = text.replace("_bar_", "|") - text = text.replace("_minus_", "-") - text = text.replace("_plus_", "+") - text = text.replace("_dot_", ".") - text = text.replace("_comma_", ",") - - splits = text.split("|", 1) - if len(splits) == 1: - self.obj_names[id] = {'name': text, 'id': 0} - else: - name, rest = splits - if "basin" in id: - name += "basin" - self.obj_names[id] = {'name': name, 'id': obj_num_ids[name].pop()} - - def demangle_alfred_name(self, text): - assert(text in self.obj_names) - name, id = self.obj_names[text].values() - id = str(id) if id > 0 else "" - res = "{} {}".format(name, id) - return res - - -class NumpyArrayEncoder(JSONEncoder): - def default(self, obj): - if isinstance(obj, np.ndarray): - return obj.tolist() - return JSONEncoder.default(self, obj) - - -def get_templated_task_desc(traj_data): - - pddl_params = traj_data['pddl_params'] - goal_str = traj_data['task_type'] - if pddl_params['object_sliced']: - goal_str += "_slice" - - template = random.choice(glib.gdict[goal_str]['templates']) - obj = pddl_params['object_target'].lower() - recep = pddl_params['parent_target'].lower() - toggle = pddl_params['toggle_target'].lower() - mrecep = pddl_params['mrecep_target'].lower() - filled_in_str = template.format(obj=obj, recep=recep, toggle=toggle, mrecep=mrecep) - return filled_in_str - - -def clean_alfred_facts(facts): - # TODO: fix this? - demangler = Demangler() - - def _clean_fact(fact: Proposition): - args = [Variable(demangler.demangle_alfred_name(arg.name), arg.type) for arg in fact.arguments] - return Proposition(fact.name, args) - - facts = [_clean_fact(fact) for fact in facts if not fact.name.startswith("new-axiom@")] - return facts - - -def add_task_to_grammar(grammar_str, traj_data, goal_desc_human_anns_prob=0.0, rng=random): - if rng.random() < goal_desc_human_anns_prob: - task_desc = get_human_anns_task_desc(traj_data, rng) - else: - task_desc = get_templated_task_desc(traj_data) - return grammar_str.replace("UNKNOWN GOAL", task_desc) - - -def get_human_anns_task_desc(traj_data, rng=random): - return rng.choice(traj_data['turk_annotations']['anns'])['task_desc'] - - -def parse_objects(desc): - ''' - extract objects after "you see" and before "your task is to:" - ''' - # TODO: replace with a noun-phrase extractor - objs = [] - if "you see" in desc.lower(): - obj_str = desc.lower().replace(" and", ",") - obj_str = obj_str.split("you see ", 1)[1] - obj_str = obj_str.partition("your task is to:")[0] - for s in obj_str.split(","): - item = s.translate(str.maketrans('', '', string.punctuation)) - item = item.strip().replace("a ", "") - if item: - objs.append(item) - return objs - - -def extract_admissible_commands_with_heuristics(intro, frame_desc, feedback, - curr_recep, inventory): - ''' - Heavily engineered admissible commands extraction. Lots of commonsense and heuristics used to prune list. - ''' - - at_recep = str(curr_recep) if curr_recep != "nothing" else "" - at_recep_type = at_recep.split()[0] if at_recep else "" - in_inv = str(inventory[0]).lower() if len(inventory) > 0 else "" - - OPENABLE_RECEPTACLES = [r.lower() for r in constants.OPENABLE_CLASS_LIST] - - assert intro # intro should be non-empty - - admissible_commands = [] - templates = [ - "go to {recep}", - "open {recep}", - "close {recep}", - "take {obj} from {recep}", - "move {obj} to {recep}", - "use {lamp}", - "heat {obj} with {microwave}", - "cool {obj} with {fridge}", - "clean {obj} with {cleaner}", - "slice {obj} with {knife}", - "inventory", - "look", - "help", - "examine {obj}", - "examine {recep}" - ] - - # parse interactable and navigable objects - receps = parse_objects(intro) - objects = parse_objects(frame_desc) if frame_desc else [] - lamps = [obj for obj in objects if 'lamp' in obj] - microwaves = [obj for obj in receps if 'microwave' in obj] - cleaners = [obj for obj in receps if 'sink' in obj or 'bathtub' in obj] - fridges = [obj for obj in receps if 'fridge' in obj] - knives = [obj for obj in receps if 'knife' in obj] - - # populate templates - for t in templates: - if 'take {obj} from {recep}' in t: - if at_recep and not in_inv: - for obj in objects: - if 'desklamp' not in obj and 'floorlamp' not in obj: - admissible_commands.append(t.format(recep=at_recep, obj=obj)) - elif 'move {obj} to {recep}' in t: - if in_inv and at_recep: - admissible_commands.append(t.format(recep=at_recep, obj=in_inv)) - elif '{obj}' in t and '{microwave}' in t: - if 'microwave' in at_recep and in_inv: - for microwave in microwaves: - admissible_commands.append(t.format(microwave=microwave, obj=in_inv)) - elif '{obj}' in t and '{fridge}' in t: - if 'fridge' in at_recep and in_inv: - for fridge in fridges: - admissible_commands.append(t.format(fridge=fridge, obj=in_inv)) - elif '{obj}' in t and '{cleaner}' in t: - if ('sink' in at_recep or 'bathtub' in at_recep) and in_inv: - for cleaner in cleaners: - admissible_commands.append(t.format(cleaner=cleaner, obj=in_inv)) - elif '{obj}' in t and '{knife}' in t: - if 'knife' in in_inv: - for knife in knives: - for obj in objects: - admissible_commands.append(t.format(knife=knife, obj=obj)) - elif 'open {recep}' in t: - if at_recep: - if at_recep_type in OPENABLE_RECEPTACLES: # and ("is closed" in feedback or "You close" in feedback): - admissible_commands.append(t.format(recep=at_recep)) - elif 'close {recep}' in t: - if at_recep: - if at_recep_type in OPENABLE_RECEPTACLES: # and "is open" in feedback: - admissible_commands.append(t.format(recep=at_recep)) - elif 'examine {recep}' in t: - if at_recep: - admissible_commands.append(t.format(recep=at_recep)) - elif 'examine {obj}' in t: - if in_inv: - admissible_commands.append(t.format(obj=in_inv)) - elif 'go to {recep}' in t: - for recep in receps: - if recep != at_recep: - admissible_commands.append(t.format(recep=recep)) - elif '{recep}' in t: - for recep in receps: - admissible_commands.append(t.format(recep=recep)) - elif '{obj}' in t: - for obj in objects: - admissible_commands.append(t.format(obj=obj)) - elif '{lamp}' in t: - for lamp in lamps: - admissible_commands.append(t.format(lamp=lamp)) - else: - admissible_commands.append(t) - - return admissible_commands - - -def extract_admissible_commands(intro, frame_desc): - ''' - exhaustive list of admissible commands - ''' - - admissible_commands = [] - templates = [ - "go to {recep}", - "open {recep}", - "close {recep}", - "take {obj} from {recep}", - "move {obj} to {recep}", - "use {lamp}", - "heat {obj} with {microwave}", - "cool {obj} with {fridge}", - "clean {obj} with {cleaner}", - "slice {obj} with {knife}", - "inventory", - "look", - "help", - "examine {obj}", - "examine {recep}" - ] - - # parse interactable and navigable objects - receps = parse_objects(intro) - objects = parse_objects(frame_desc) if frame_desc else [] - lamps = [obj for obj in objects if 'lamp' in obj] - microwaves = [obj for obj in receps if 'microwave' in obj] - cleaners = [obj for obj in receps if 'sink' in obj or 'bathtub' in obj] - fridges = [obj for obj in receps if 'fridge' in obj] - knives = [obj for obj in receps if 'knife' in obj] - - # populate templates - for t in templates: - if '{recep}' in t and '{obj}' in t: - for recep in receps: - for obj in objects: - admissible_commands.append(t.format(recep=recep, obj=obj)) - elif '{obj}' in t and '{microwave}' in t: - for microwave in microwaves: - for obj in objects: - admissible_commands.append(t.format(microwave=microwave, obj=obj)) - elif '{obj}' in t and '{fridge}' in t: - for fridge in fridges: - for obj in objects: - admissible_commands.append(t.format(fridge=fridge, obj=obj)) - elif '{obj}' in t and '{cleaner}' in t: - for cleaner in cleaners: - for obj in objects: - admissible_commands.append(t.format(cleaner=cleaner, obj=obj)) - elif '{obj}' in t and '{knife}' in t: - for knife in knives: - for obj in objects: - admissible_commands.append(t.format(knife=knife, obj=obj)) - elif '{recep}' in t: - for recep in receps: - admissible_commands.append(t.format(recep=recep)) - elif '{obj}' in t: - for obj in objects: - admissible_commands.append(t.format(obj=obj)) - elif '{lamp}' in t: - for lamp in lamps: - admissible_commands.append(t.format(lamp=lamp)) - else: - admissible_commands.append(t) - - return admissible_commands diff --git a/agent_system/environments/env_package/alfworld/alfworld/data/README.md b/agent_system/environments/env_package/alfworld/alfworld/data/README.md deleted file mode 100644 index 490e78d1..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/data/README.md +++ /dev/null @@ -1,137 +0,0 @@ -# Dataset - -The ALFWorld dataset contains 3,553 training games, 140 seen and 134 unseen validation games. - -## Download - -Download PDDL, Game Files and pre-trained MaskRCNN model: - -```bash -python scripts/alfworld-download -``` - -Additional Seq2Seq data and pre-trained BUTLER checkpoints (All Tasks): - -```bash -python scripts/alfworld-download --extra -``` - -## File Structure - -``` -$ALFWORLD_DATA/json_2.1.1/train/task_type-object-movableReceptacle-receptacle-sceneNum/trial_ID/ (trajectory root) -$ALFWORLD_DATA/json_2.1.1/train/task_type-object-movableReceptacle-receptacle-sceneNum/trial_ID/traj_data.json (trajectory metadata) -$ALFWORLD_DATA/json_2.1.1/train/task_type-object-movableReceptacle-receptacle-sceneNum/trial_ID/initial_state.pddl (PDDL description of the initial state) -$ALFWORLD_DATA/json_2.1.1/train/task_type-object-movableReceptacle-receptacle-sceneNum/trial_ID/game.tw-pddl (textworld game file) -``` - -## JSON Structure - -Dictionary structure of `traj_data.json`: - -Task Info: -``` -['task_id'] = "trial_00003_T20190312_234237" (unique trajectory ID) -['task_type'] = "pick_heat_then_place_in_recep" (one of 7 task types) -['pddl_params'] = {'object_target': "AlarmClock", (object) - 'parent_target': "DeskLamp", (receptacle) - 'mrecep_target': "", (movable receptacle) - "toggle_target": "", (toggle object) - "object_sliced": false} (should the object be sliced?) -``` - -Scene Info: -``` -['scene'] = {'floor_plan': "FloorPlan7", (THOR scene name) - 'scene_num' : 7, (THOR scene number) - 'random_seed': 3810970210, (seed for initializing object placements) - 'init_action' : , (called to set the starting position of the agent) - 'object_poses': , (initial 6DOF poses of objects in the scene) - 'object_toggles': } (initial states of togglable objects) -``` - -Language Annotations: -``` -['turk_annotations']['anns'] = - [{'task_desc': "Examine a clock using the light of a lamp.", (goal instruction) - 'high_descs': ["Turn to the left and move forward to the window ledge.", (list of step-by-step instructions) - "Pick up the alarm clock on the table", ...], (indexes aligned with high_idx) - 'votes': [1, 1, 1] (AMTurk languauge quality votes) - }, - ...] -``` - -Expert Demonstration: -``` -['plan'] = {'high_pddl': - ..., - ["high_idx": 4, (high-level subgoal index) - "discrete_action": - {"action": "PutObject", (discrete high-level action) - "args": ["bread", "microwave"], (discrete params) - "planner_action": ], (PDDL action) - ...], - - 'low_actions': - ..., - ["high_idx": 1, (high-level subgoal index) - "discrete_action": - {"action": "PickupObject", (discrete low-level action) - "args": - {"bbox": [180, 346, 332, 421]} (bounding box for interact action) - "mask": [0, 0, ... 1, 1]}, (compressed pixel mask for interact action) - "api_action": ], (THOR API command for replay) - ...], - } -``` - -Images: -``` -['images'] = [{"low_idx": 0, (low-level action index) - "high_idx": 0, (high-level action index) - "image_name": "000000000.jpg"} (image filename) - ...] -``` - -## Data & Generation - -#### PDDL states from ALFRED - -To generate `initial_state.pddl` from ALFRED `traj_data.json` files: - -```bash -python scripts/augment_pddl_states.py --data_path $ALFWORLD_DATA/json_2.1.1/train -``` - -#### Adding additional attributes to TextWorld games - -1. Use [augment_pddl_states.py](../../scripts/augment_pddl_states.py#L254) to dump additional attributes and properties from THOR into `initial_state.pddl`. -2. Use [alfworld-generate](../../scripts/alfworld-generate) to generate `game.tw-pddl` files from the new `initial_state.pddl`s. This will use the expert to check if the text game is solvable and then dump a game file used by the text-engine. -3. Modify the demangler in [`misc.py`](../../alfworld/agents/utils/misc.py#L64) to display the attribute in Textworld, or modify the grammar in [`alfred.twl2`](https://github.com/alfworld/alfworld/blob/master/data/textworld_data/logic/alfred.twl2) to your needs. - -#### Generating TextWorld games that use human goal annotations. - -```bash -alfworld-generate --data_path $ALFWORLD_DATA/json_2.1.1 --save_path custom_dataset/ --goal_desc_human_anns_prob 1 -``` - -## Mask-RCNN Detector - -#### Generating MaskRCNN training images from ALFRED - -To generate image and instance-segmentation pairs from ALFRED training scenes: - -```bash -python scripts/augment_trajectories.py --data_path $ALFWORLD_DATA/json_2.1.1/train --save_path $ALFWORLD_DATA/raw_images --num_threads 4 -``` - -#### Fine-tuning MaskRCNN - -To fine-tune a COCO-trained MaskRCNN model: - -```bash -python scripts/train_mrcnn.py --data_path $ALFWORLD_DATA/raw_images --save_path $ALFWORLD_DATA/mrcnn --balance_scenes --object_types objects --batch_size 32 -``` - -#### Pre-trained Models -The default pre-trained model provided in the repo is trained on 73 object classes without receptacles. We also provide [other models](https://github.com/alfworld/alfworld/releases/tag/0.2.2) for receptacles (32 receptacle classes) and all objects (105 classes). These pre-trained models are named `mrcnn_*`. diff --git a/agent_system/environments/env_package/alfworld/alfworld/data/alfred.pddl b/agent_system/environments/env_package/alfworld/alfworld/data/alfred.pddl deleted file mode 100644 index 9c0d8126..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/data/alfred.pddl +++ /dev/null @@ -1,508 +0,0 @@ -;; Specification in PDDL of the Alfred domain -;; Intended to be used with Fast Downward which supports PDDL 2.2 level 1 plus the :action-costs requirement from PDDL 3.1. - -(define (domain alfred) - (:requirements - :adl - :action-costs - :typing - ) - (:types - agent - location - receptacle - object - rtype - otype - ) - - - (:predicates - (atLocation ?a - agent ?l - location) ; true if the agent is at the location - (receptacleAtLocation ?r - receptacle ?l - location) ; true if the receptacle is at the location (constant) - (objectAtLocation ?o - object ?l - location) ; true if the object is at the location - (openable ?r - receptacle) ; true if a receptacle is openable - (opened ?r - receptacle) ; true if a receptacle is opened - (inReceptacle ?o - object ?r - receptacle) ; object ?o is in receptacle ?r - (isReceptacleObject ?o - object) ; true if the object can have things put inside it - (inReceptacleObject ?innerObject - object ?outerObject - object) ; object ?innerObject is inside object ?outerObject - (isReceptacleObjectFull ?o - object) ; true if the receptacle object contains something - (wasInReceptacle ?o - object ?r - receptacle) ; object ?o was or is in receptacle ?r now or some time in the past - (checked ?r - receptacle) ; whether the receptacle has been looked inside/visited - (examined ?l - location) ; TODO - (receptacleType ?r - receptacle ?t - rtype) ; the type of receptacle (Cabinet vs Cabinet|01|2...) - (canContain ?rt - rtype ?ot - otype) ; true if receptacle can hold object - (objectType ?o - object ?t - otype) ; the type of object (Apple vs Apple|01|2...) - (holds ?a - agent ?o - object) ; object ?o is held by agent ?a - (holdsAny ?a - agent) ; agent ?a holds an object - (holdsAnyReceptacleObject ?a - agent) ; agent ?a holds a receptacle object - (full ?r - receptacle) ; true if the receptacle has no remaining space - (isClean ?o - object) ; true if the object has been clean in sink - (cleanable ?o - object) ; true if the object can be placed in a sink - (isHot ?o - object) ; true if the object has been heated up - (heatable ?o - object) ; true if the object can be heated up in a microwave - (isCool ?o - object) ; true if the object has been cooled - (coolable ?o - object) ; true if the object can be cooled in the fridge - (pickupable ?o - object) ; true if the object can be picked up - (moveable ?o - object) ; true if the object can be moved - (toggleable ?o - object) ; true if the object can be turned on/off - (isOn ?o - object) ; true if the object is on - (isToggled ?o - object) ; true if the object has been toggled - (sliceable ?o - object) ; true if the object can be sliced - (isSliced ?o - object) ; true if the object is sliced - ) - - (:functions - (distance ?from ?to) - (total-cost) - number - ) - -;; All actions are specified such that the final arguments are the ones used -;; for performing actions in Unity. - - -(:action look - :parameters (?a - agent ?l - location) - :precondition - (and - (atLocation ?a ?l) - ) - :effect - (and - (checked ?l) - ) -) - -(:action inventory - :parameters (?a - agent) - :precondition - () - :effect - (and - (checked ?a) - ) -) - -(:action examineReceptacle - :parameters (?a - agent ?r - receptacle) - :precondition - (and - (exists (?l - location) - (and - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - ) - ) - ) - :effect - (and - (checked ?r) - ) -) - -(:action examineObject - :parameters (?a - agent ?o - object) - :precondition - (or - ;(exists (?l - location) - ; (and - ; (atLocation ?a ?l) - ; (objectAtLocation ?o ?l) - ; ) - ;) - (exists (?l - location, ?r - receptacle) - (and - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - ; (objectAtLocation ?o ?l) - (inReceptacle ?o ?r) - (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable. - ) - ) - (holds ?a ?o) - ) - :effect - (and - (checked ?o) - ) -) - -;; agent goes to receptacle - (:action GotoLocation - :parameters (?a - agent ?lStart - location ?lEnd - location ?r - receptacle) - :precondition (and - (atLocation ?a ?lStart) - (receptacleAtLocation ?r ?lEnd) - ;(exists (?r - receptacle) (receptacleAtLocation ?r ?lEnd)) - ) - :effect (and - (not (atLocation ?a ?lStart)) - (atLocation ?a ?lEnd) - ; (forall (?r - receptacle) - ; (when (and (receptacleAtLocation ?r ?lEnd) - ; (or (not (openable ?r)) (opened ?r))) - ; (checked ?r) - ; ) - ; ) - ; (increase (total-cost) (distance ?lStart ?lEnd)) - (increase (total-cost) 1) - ) - ) - -;; agent opens receptacle - (:action OpenObject - :parameters (?a - agent ?l - location ?r - receptacle) - :precondition (and - (openable ?r) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (not (opened ?r)) - ) - :effect (and - (opened ?r) - (checked ?r) - (increase (total-cost) 1) - ) - ) -;; agent closes receptacle - (:action CloseObject - :parameters (?a - agent ?l - location ?r - receptacle) - :precondition (and - (openable ?r) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (opened ?r) - ) - :effect (and - (not (opened ?r)) - (increase (total-cost) 1) - ) - - ) - - ;; agent picks up object from a receptacle - (:action PickupObject - :parameters (?a - agent ?l - location ?o - object ?r - receptacle) - :precondition - (and - (pickupable ?o) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - ; (objectAtLocation ?o ?l) - (inReceptacle ?o ?r) - (not (holdsAny ?a)) ; agent's hands are empty. - ;(not (holdsAnyReceptacleObject ?a)) - (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable. - ;(not (isReceptacleObject ?o)) - ) - :effect - (and - (not (inReceptacle ?o ?r)) - (holds ?a ?o) - (holdsAny ?a) - (not (objectAtLocation ?o ?l)) - ;(not (full ?r)) - (increase (total-cost) 1) - ) - ) - - -; ;; agent picks up object from a receptacle -; (:action PickupObjectFromReceptacleObject -; :parameters (?a - agent ?l - location ?o - object ?outerR - object ?r - receptacle) -; :precondition -; (and -; (atLocation ?a ?l) -; (receptacleAtLocation ?r ?l) -; (inReceptacle ?o ?r) -; (pickupable ?o) -; (not (holdsAny ?a)) ; agent's hands are empty. -; (not (holdsAnyReceptacleObject ?a)) -; (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable. -; (not (isReceptacleObject ?o)) -; (isReceptacleObject ?outerR) -; (inReceptacleObject ?o ?outerR) -; ) -; :effect -; (and -; (not (inReceptacle ?o ?r)) -; (holds ?a ?o) -; (holdsAny ?a) -; (not (objectAtLocation ?o ?l)) -; (not (full ?r)) -; (increase (total-cost) 1) -; -; (not (inReceptacleObject ?o ?outerR)) -; (not (isReceptacleObjectFull ?outerR)) -; ) -; ) -; -; ;; agent picks up object from a receptacle -; (:action PickupEmptyReceptacleObject -; :parameters (?a - agent ?l - location ?o - object ?r - receptacle) -; :precondition -; (and -; (atLocation ?a ?l) -; (receptacleAtLocation ?r ?l) -; ; (objectAtLocation ?o ?l) -; (inReceptacle ?o ?r) -; (pickupable ?o) -; (not (holdsAny ?a)) ; agent's hands are empty. -; (not (holdsAnyReceptacleObject ?a)) -; (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable. -; (isReceptacleObject ?o) -; (not (isReceptacleObjectFull ?o)) -; ) -; :effect -; (and -; (not (inReceptacle ?o ?r)) -; (holds ?a ?o) -; (holdsAny ?a) -; (not (objectAtLocation ?o ?l)) -; (not (full ?r)) -; (increase (total-cost) 1) -; (holdsAnyReceptacleObject ?a) -; ) -; ) -; -; ;; agent picks up object from a receptacle -; (:action PickupFullReceptacleObject -; :parameters (?a - agent ?l - location ?o - object ?outerR - object ?r - receptacle) -; :precondition -; (and -; (atLocation ?a ?l) -; (receptacleAtLocation ?r ?l) -; (inReceptacle ?outerR ?r) -; (pickupable ?outerR) -; (not (holdsAny ?a)) ; agent's hands are empty. -; (not (holdsAnyReceptacleObject ?a)) -; (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable. -; (not (isReceptacleObject ?o)) -; (isReceptacleObject ?outerR) -; (inReceptacleObject ?o ?outerR) -; ) -; :effect -; (and -; (not (inReceptacle ?o ?r)) -; (not (inReceptacle ?outerR ?r)) -; (holds ?a ?outerR) -; (holdsAny ?a) -; (not (objectAtLocation ?o ?l)) -; (not (objectAtLocation ?outerR ?l)) -; (not (full ?r)) -; (increase (total-cost) 1) -; (holdsAnyReceptacleObject ?a) -; ) -; ) - - -;; agent puts down an object - (:action PutObject - :parameters (?a - agent ?l - location ?o - object ?r - receptacle ?ot - otype ?rt - rtype) - :precondition (and - (holds ?a ?o) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable - ;(not (full ?r)) - (objectType ?o ?ot) - (receptacleType ?r ?rt) - (canContain ?rt ?ot) - ;(not (holdsAnyReceptacleObject ?a)) - ) - :effect (and - (inReceptacle ?o ?r) - (objectAtLocation ?o ?l) - ;(full ?r) - (not (holds ?a ?o)) - (not (holdsAny ?a)) - (increase (total-cost) 1) - ) - ) - -;;; agent puts down an object -; (:action PutObjectInReceptacleObject -; :parameters (?a - agent ?l - location ?ot - otype ?o - object ?outerO - object ?outerR - receptacle) -; :precondition (and -; (atLocation ?a ?l) -; (objectAtLocation ?outerO ?l) -; (isReceptacleObject ?outerO) -; (not (isReceptacleObject ?o)) -; (objectType ?o ?ot) -; (holds ?a ?o) -; (not (holdsAnyReceptacleObject ?a)) -; (inReceptacle ?outerO ?outerR) -; (not (isReceptacleObjectFull ?outerO)) -; ) -; :effect (and -; (inReceptacleObject ?o ?outerO) -; (inReceptacle ?o ?outerR) -; (not (holds ?a ?o)) -; (not (holdsAny ?a)) -; (objectAtLocation ?o ?l) -; (isReceptacleObjectFull ?outerO) -; (increase (total-cost) 1) -; ) -; ) -; -;;; agent puts down an object -; (:action PutEmptyReceptacleObjectinReceptacle -; :parameters (?a - agent ?l - location ?ot - otype ?o - object ?r - receptacle) -; :precondition (and -; (atLocation ?a ?l) -; (receptacleAtLocation ?r ?l) -; (or (not (openable ?r)) (opened ?r)) ; receptacle is opened if it is openable -; (not (full ?r)) -; (objectType ?o ?ot) -; (holds ?a ?o) -; (holdsAnyReceptacleObject ?a) -; (isReceptacleObject ?o) -; (not (isReceptacleObjectFull ?o)) -; ) -; :effect (and -; (inReceptacle ?o ?r) -; (objectAtLocation ?o ?l) -; (full ?r) -; (not (holds ?a ?o)) -; (not (holdsAny ?a)) -; (not (holdsAnyReceptacleObject ?a)) -; (increase (total-cost) 1) -; ) -; ) -; -;;; agent puts down a receptacle object in a receptacle -; (:action PutFullReceptacleObjectInReceptacle -; :parameters (?a - agent ?l - location ?ot - otype ?innerO - object ?outerO - object ?r - receptacle) ; ?rt - rtype) -; :precondition (and -; (atLocation ?a ?l) -; (receptacleAtLocation ?r ?l) -; (objectType ?outerO ?ot) -; (holds ?a ?outerO) -; (holdsAnyReceptacleObject ?a) -; (isReceptacleObject ?outerO) -; (isReceptacleObjectFull ?outerO) -; (inReceptacleObject ?innerO ?outerO) -; ) -; :effect (and -; (not (holdsAny ?a)) -; (not (holdsAnyReceptacleObject ?a)) -; (objectAtLocation ?outerO ?l) -; (objectAtLocation ?innerO ?l) -; (inReceptacle ?outerO ?r) -; (inReceptacle ?innerO ?r) -; (not (holds ?a ?outerO)) -; (increase (total-cost) 1) -; ) -; ) - -;; agent cleans some object - (:action CleanObject - :parameters (?a - agent ?l - location ?r - receptacle ?o - object) - :precondition (and - (cleanable ?o) - (or - ;(receptacleType ?r SinkType) - (receptacleType ?r SinkBasinType) - ) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (holds ?a ?o) - ) - :effect (and - (increase (total-cost) 5) - (isClean ?o) - ) - ) - - -;; agent heats-up some object - (:action HeatObject - :parameters (?a - agent ?l - location ?r - receptacle ?o - object) - :precondition (and - (heatable ?o) - (or - (receptacleType ?r MicrowaveType) - ) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (holds ?a ?o) - ) - :effect (and - (increase (total-cost) 5) - (isHot ?o) - (not (isCool ?o)) - ) - ) - -;; agent cools some object - (:action CoolObject - :parameters (?a - agent ?l - location ?r - receptacle ?o - object) - :precondition (and - (coolable ?o) - (or - (receptacleType ?r FridgeType) - ) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (holds ?a ?o) - ) - :effect (and - (increase (total-cost) 5) - (isCool ?o) - (not (isHot ?o)) - ) - ) - - -;; agent toggle object - (:action ToggleObject - :parameters (?a - agent ?l - location ?o - object ?r - receptacle) - :precondition (and - (toggleable ?o) - (atLocation ?a ?l) - (receptacleAtLocation ?r ?l) - (inReceptacle ?o ?r) - ) - :effect (and - (increase (total-cost) 5) - (when (isOn ?o) - (not (isOn ?o))) - (when (not (isOn ?o)) - (isOn ?o)) - (isToggled ?o) - ) - ) - - -;; agent slices some object with a knife - (:action SliceObject - :parameters (?a - agent ?l - location ?co - object ?ko - object) - :precondition - (and - (sliceable ?co) - (or - (objectType ?ko KnifeType) - (objectType ?ko ButterKnifeType) - ) - (atLocation ?a ?l) - (objectAtLocation ?co ?l) - (holds ?a ?ko) - ) - :effect (and - (increase (total-cost) 5) - (isSliced ?co) - ) - ) - - -(:action help - :parameters (?a - agent) - :precondition - () - :effect - (and - (checked ?a) - ) -) - -) diff --git a/agent_system/environments/env_package/alfworld/alfworld/data/alfred.twl2 b/agent_system/environments/env_package/alfworld/alfworld/data/alfred.twl2 deleted file mode 100644 index 47a7c9f5..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/data/alfred.twl2 +++ /dev/null @@ -1,437 +0,0 @@ -grammar :: """ - { - "intro": [ - { - "rhs": "-= Welcome to TextWorld, ALFRED! =-\n\n#look.feedback#\n\n#task#" - } - ], - - "notImplemented": [ - { - "rhs": "TODO" - } - ], - - "task": [ - { - "rhs": "Your task is to: UNKNOWN GOAL." - } - ], - - "GotoLocation.feedback": [ - { - "rhs": "You arrive at {r.name}. #examineReceptacle.feedback#" - } - ], - - "OpenObject.feedback": [ - { - "rhs": "You open the {r.name}. #examineReceptacle.feedback#" - } - ], - - "CloseObject.feedback": [ - { - "rhs": "You close the {r.name}." - } - ], - - "PickupObject.feedback": [ - { - "rhs": "You pick up the {o.name} from the {r.name}." - } - ], - - "PickupObjectFromReceptacleObject.feedback": [ - { - "rhs": "PickupObjectFromReceptacleObject: You pick up the {o.name}." - } - ], - - "PickupEmptyReceptacleObject.feedback": [ - { - "rhs": "PickupEmptyReceptacleObject: You pick up the {o.name}." - } - ], - - "PickupFullReceptacleObject.feedback": [ - { - "rhs": "PickupFullReceptacleObject: You pick up the {outerr.name}." - } - ], - - "PutObject.feedback": [ - { - "rhs": "You move the {o.name} to the {r.name}." - } - ], - - "PutObjectInReceptacleObject.feedback": [ - { - "rhs": "PutObjectInReceptacleObject: You put the {o.name} in the {outero.name}." - } - ], - - "PutEmptyReceptacleObjectinReceptacle.feedback": [ - { - "rhs": "PutEmptyReceptacleObjectinReceptacle: You put the {o.name} in the {r.name}." - } - ], - - "PutFullReceptacleObjectInReceptacle.feedback": [ - { - "rhs": "PutFullReceptacleObjectInReceptacle: You put the {outero.name} in the {r.name}." - } - ], - - "inventory.feedback": [ - { - "condition": "holdsany(a:agent)", - "rhs": "You are carrying: [{o.indefinite + ' ' + o.name | holds(a:agent, o:object)}]." - }, - { - "rhs": "You are not carrying anything." - } - ], - - "examineReceptacle.feedback": [ - { - "condition": "openable(r:receptacle) & opened(r:receptacle)", - "rhs": "The {r.name} is open. In it, you see [{o.indefinite + ' ' + o.name | inreceptacle(o:object, r:receptacle)}]." - }, - { - "condition": "openable(r:receptacle)", - "rhs": "The {r.name} is closed." - }, - { - "rhs": "On the {r.name}, you see [{o.indefinite + ' ' + o.name | inreceptacle(o:object, r:receptacle)}]." - } - ], - - "examineObject.feedback": [ - { - "condition": "isreceptacleobject(o:object)", - "rhs": "This is a normal {o.name}. In it, you see [{o2.indefinite + ' ' + o2.name | inreceptacleobject(o2:object, o:object)}]." - }, - { - "condition": "isclean(o:object) & ishot(o:object) & issliced(o:object)", - "rhs": "This is a hot and clean sliced {o.name}." - }, - { - "condition": "isclean(o:object) & iscool(o:object) & issliced(o:object)", - "rhs": "This is a cool and clean sliced {o.name}." - }, - { - "condition": "isclean(o:object) & issliced(o:object)", - "rhs": "This is a clean sliced {o.name}." - }, - { - "condition": "ishot(o:object) & issliced(o:object)", - "rhs": "This is a hot sliced {o.name}." - }, - { - "condition": "iscool(o:object) & issliced(o:object)", - "rhs": "This is a cool sliced {o.name}." - }, - { - "condition": "isclean(o:object) & ishot(o:object)", - "rhs": "This is a hot and clean {o.name}." - }, - { - "condition": "isclean(o:object) & iscool(o:object)", - "rhs": "This is a cool and clean {o.name}." - }, - { - "condition": "ishot(o:object)", - "rhs": "This is a hot {o.name}." - }, - { - "condition": "isclean(o:object)", - "rhs": "This is a clean {o.name}." - }, - { - "condition": "iscool(o:object)", - "rhs": "This is a cold {o.name}." - }, - { - "condition": "toggleable(o:object) & istoggled(o:object)", - "rhs": "This {o.name} is on." - }, - { - "condition": "toggleable(o:object) & not_istoggled(o:object)", - "rhs": "This {o.name} is off." - }, - { - "condition": "sliceable(o:object) & issliced(o:object)", - "rhs": "This is a sliced {o.name}." - }, - { - "rhs": "There's nothing special about {o.name}." - } - ] - } -"""; - -action GotoLocation { - template :: "go to [{r.name | receptacleatlocation(r:receptacle, lend:location)}]"; - feedback :: "#GotoLocation.feedback#"; -} - -action OpenObject { - template :: "open {r}"; - feedback :: "#OpenObject.feedback#"; -} - -action CloseObject { - template :: "close {r}"; - feedback :: "#CloseObject.feedback#"; -} - -action PickupObject { - template :: "take {o} from {r}"; - feedback :: "#PickupObject.feedback#"; -} - -action PickupObjectFromReceptacleObject { - template :: "take {o} from {r}"; - feedback :: "#PickupObjectFromReceptacleObject.feedback#"; -} - -action PickupEmptyReceptacleObject { - template :: "take {o} from {r}"; - feedback :: "#PickupEmptyReceptacleObject.feedback#"; -} - -action PickupFullReceptacleObject { - template :: "take {outerr} from {r}"; - feedback :: "#PickupFullReceptacleObject.feedback#"; -} - -action PutObject { - template :: "move {o} to {r}"; - feedback :: "#PutObject.feedback#"; -} - -action PutObjectInReceptacleObject { - template :: "put {o} into {outero}"; - feedback :: "#PutObjectInReceptacleObject.feedback#"; -} - -action PutEmptyReceptacleObjectinReceptacle { - template :: "move {o} to {r}"; - feedback :: "#PutEmptyReceptacleObjectinReceptacle.feedback#"; -} - -action PutFullReceptacleObjectInReceptacle { - template :: "put {outero} in {r}"; - feedback :: "#PutFullReceptacleObjectInReceptacle.feedback#"; -} - -action inventory { - template :: "inventory"; - feedback :: "#inventory.feedback#"; -} - -action examineReceptacle { - template :: "examine {r}"; - feedback :: "#examineReceptacle.feedback#"; -} - -action examineObject { - template :: "examine {o}"; - feedback :: "#examineObject.feedback#"; -} - -action ToggleObject { - template :: "use {o}"; - feedback :: "#toggleObject.feedback#"; - - grammar :: """ - { - "toggleObject.feedback": [ - { - "condition": "toggleable(o:object) & istoggled(o:object)", - "rhs": "You turn on the {o.name}." - }, - { - "condition": "toggleable(o:object)", - "rhs": "You turn off the {o.name}." - }, - { - "rhs": "You don't see any switch on the {o.name}." - } - ] - } - """; -} - -action HeatObject { - template :: "heat {o} with {r}"; - feedback :: "#heatObject.feedback#"; - - grammar :: """ - { - "heatObject.feedback": [ - { - "rhs": "You heat the {o.name} using the {r.name}." - } - ] - } - """; -} - -action CleanObject { - template :: "clean {o} with {r}"; - feedback :: "#cleanObject.feedback#"; - - grammar :: """ - { - "cleanObject.feedback": [ - { - "rhs": "You clean the {o.name} using the {r.name}." - } - ] - } - """; -} - -action CoolObject { - template :: "cool {o} with {r}"; - feedback :: "#coolObject.feedback#"; - - grammar :: """ - { - "coolObject.feedback": [ - { - "rhs": "You cool the {o.name} using the {r.name}." - } - ] - } - """; -} - -action SliceObject { - template :: "slice {co} with {ko}"; - feedback :: "#sliceObject.feedback#"; - - grammar :: """ - { - "sliceObject.feedback": [ - { - "rhs": "You sliced the {co.name} with the {ko.name}." - } - ] - } - """; -} - -action look { - template :: "look"; - feedback :: "#look.feedback#"; - - grammar :: """ - { - "look.feedback": [ - { - "condition": "atlocation(a:agent, l:location) & receptacleatlocation(r:receptacle, l:location)", - "rhs": "#look-variations#. Next to it, you see #list_objects_on_the_floor#." - }, - { - "rhs": "You are in the middle of a room. Looking quickly around you, you see #list_appliances#." - } - ], - - "look-variations": [ - { - "rhs": "You are facing the [{r.name | atlocation(a:agent, l:location) & receptacleatlocation(r:receptacle, l:location)}]" - } - ], - - "list_objects_on_the_floor": [ - { - "condition": "atlocation(a:agent, l:location) & objectatlocation(o:object, l:location) & receptacleatlocation(r:receptacle, l:location) & not_inreceptacle(o:object, r:receptacle)", - "rhs": "[{#overview(o)# | atlocation(a:agent, l:location) & objectatlocation(o:object, l:location) & receptacleatlocation(r:receptacle, l:location) & not_inreceptacle(o:object, r:receptacle)}]" - }, - { - "rhs": "nothing" - } - ], - - "list_appliances": [ - { - "condition": "receptacleatlocation(r:receptacle, l:location)", - "rhs": "[{#overview(r)# | receptacleatlocation(r:receptacle, l:location)}]" - }, - { - "rhs": "nothing" - } - ], - - "overview(o, r)": [ - { - "rhs": "{o.indefinite} {o.name} (in/on the {r.name})}" - } - ], - - "overview(o)": [ - { - "rhs": "{o.indefinite} {o.name}" - } - ], - "overview(r)": [ - { - "rhs": "{r.indefinite} {r.name or r.id}" - } - ], - "overview_with_state(r)": [ - { - "rhs": "{r.indefinite} {r.name or r.id}#overview_state(r)#" - } - ], - "overview_state(r)": [ - { - "condition": "openable(r:receptacle) & opened(r:receptacle)", - "rhs": " (it is open)" - }, - { - "condition": "openable(r:receptacle)", - "rhs": " (it is closed)" - }, - { - "rhs": "" - } - ], - - "list_empty": [ - { - "rhs": "nothing" - } - ], - "list_separator": [ - { - "rhs": ", " - } - ], - "list_last_separator": [ - { - "rhs": ", and " - } - ] - } - """; -} - -action help { - template :: "help"; - feedback :: "#help.feedback#"; - - grammar :: """ - { - "help.feedback": [ - { - "rhs": "\nAvailable commands:\n look: look around your current location\n inventory: check your current inventory\n go to (receptacle): move to a receptacle\n open (receptacle): open a receptacle\n close (receptacle): close a receptacle\n take (object) from (receptacle): take an object from a receptacle\n move (object) to (receptacle): place an object in or on a receptacle\n examine (something): examine a receptacle or an object\n use (object): use an object\n heat (object) with (receptacle): heat an object using a receptacle\n clean (object) with (receptacle): clean an object using a receptacle\n cool (object) with (receptacle): cool an object using a receptacle\n slice (object) with (object): slice an object using a sharp object\n" - } - ] - } - """; -} diff --git a/agent_system/environments/env_package/alfworld/alfworld/env/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/env/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/env/reward.py b/agent_system/environments/env_package/alfworld/alfworld/env/reward.py deleted file mode 100644 index 0a4ddcd1..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/env/reward.py +++ /dev/null @@ -1,258 +0,0 @@ -from alfworld.gen.utils.game_util import get_object - -class BaseAction(object): - ''' - base class for API actions - ''' - - def __init__(self, gt_graph, env, rewards, strict=True): - self.gt_graph = gt_graph # for navigation - self.env = env - self.rewards = rewards - self.strict = strict - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - reward, done = self.rewards['neutral'], True - return reward, done - - -class GotoLocationAction(BaseAction): - ''' - MoveAhead, Rotate, Lookup - ''' - - valid_actions = {'MoveAhead', 'RotateLeft', 'RotateRight', 'LookUp', 'LookDown', 'Teleport', 'TeleportFull'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - curr_pose = state.pose_discrete - prev_pose = prev_state.pose_discrete - tar_pose = tuple([int(i) for i in subgoal['location'].split('|')[1:]]) - - prev_actions, _ = self.gt_graph.get_shortest_path(prev_pose, tar_pose) - curr_actions, _ = self.gt_graph.get_shortest_path(curr_pose, tar_pose) - - prev_distance = len(prev_actions) - curr_distance = len(curr_actions) - reward = (prev_distance - curr_distance) * 0.2 # distance reward factor? - - # [DEPRECATED] Old criteria which requires the next subgoal object to be visible - # Consider navigation a success if we can see the target object in the next step from here. - # assert len(expert_plan) > goal_idx + 1 - # next_subgoal = expert_plan[goal_idx + 1]['planner_action'] - # next_goal_object = get_object(next_subgoal['objectId'], state.metadata) - # done = (next_goal_object['visible'] and curr_distance < self.rewards['min_reach_distance']) - - done = curr_distance < self.rewards['min_reach_distance'] - - if done: - reward += self.rewards['positive'] - - return reward, done - - -class PickupObjectAction(BaseAction): - ''' - PickupObject - ''' - - valid_actions = {'PickupObject', 'OpenObject', 'CloseObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - inventory_objects = state.metadata['inventoryObjects'] - if len(inventory_objects): - inv_object_id = state.metadata['inventoryObjects'][0]['objectId'] - goal_object_id = subgoal['objectId'] - reward, done = (self.rewards['positive'], True) if inv_object_id == goal_object_id else (self.rewards['negative'], False) - return reward, done - - -class PutObjectAction(BaseAction): - ''' - PutObject - ''' - - valid_actions = {'PutObject', 'OpenObject', 'CloseObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - target_object_id = subgoal['objectId'] - recep_object = get_object(subgoal['receptacleObjectId'], state.metadata) - if recep_object is not None: - is_target_in_recep = target_object_id in recep_object['receptacleObjectIds'] - reward, done = (self.rewards['positive'], True) if is_target_in_recep else (self.rewards['negative'], False) - return reward, done - - -class OpenObjectAction(BaseAction): - ''' - OpenObject - ''' - - valid_actions = {'OpenObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - target_recep = get_object(subgoal['objectId'], state.metadata) - if target_recep is not None: - is_target_open = target_recep['isOpen'] - reward, done = (self.rewards['positive'], True) if is_target_open else (self.rewards['negative'], False) - return reward, done - - -class CloseObjectAction(BaseAction): - ''' - CloseObject - ''' - - valid_actions = {'CloseObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['negative'], False - target_recep = get_object(subgoal['objectId'], state.metadata) - if target_recep is not None: - is_target_closed = not target_recep['isOpen'] - reward, done = (self.rewards['positive'], True) if is_target_closed else (self.rewards['negative'], False) - return reward, done - - -class ToggleObjectAction(BaseAction): - ''' - ToggleObjectOn, ToggleObjectOff - ''' - - valid_actions = {'ToggleObjectOn', 'ToggleObjectOff'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - target_toggle = get_object(subgoal['objectId'], state.metadata) - if target_toggle is not None: - is_target_toggled = target_toggle['isToggled'] - reward, done = (self.rewards['positive'], True) if is_target_toggled else (self.rewards['negative'], False) - return reward, done - - -class SliceObjectAction(BaseAction): - ''' - SliceObject - ''' - - valid_actions = {'SliceObject', 'OpenObject', 'CloseObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - target_object = get_object(subgoal['objectId'], state.metadata) - if target_object is not None: - is_target_sliced = target_object['isSliced'] - reward, done = (self.rewards['positive'], True) if is_target_sliced else (self.rewards['negative'], False) - return reward, done - - -class CleanObjectAction(BaseAction): - ''' - CleanObject - ''' - - valid_actions = {'PutObject', 'PickupObject', 'ToggleObjectOn', 'ToggleObjectOff'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - subgoal = expert_plan[goal_idx]['planner_action'] - reward, done = self.rewards['neutral'], False - clean_object = get_object(subgoal['cleanObjectId'], state.metadata) - if clean_object is not None: - is_obj_clean = clean_object['objectId'] in self.env.cleaned_objects - reward, done = (self.rewards['positive'], True) if is_obj_clean else (self.rewards['negative'], False) - return reward, done - - -class HeatObjectAction(BaseAction): - ''' - HeatObject - ''' - - valid_actions = {'OpenObject', 'CloseObject', 'PickupObject', 'PutObject', 'ToggleObjectOn', 'ToggleObjectOff'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - reward, done = self.rewards['neutral'], False - next_put_goal_idx = goal_idx+2 # (+1) GotoLocation -> (+2) PutObject (get the objectId from the PutObject action) - if next_put_goal_idx < len(expert_plan): - heat_object_id = expert_plan[next_put_goal_idx]['planner_action']['objectId'] - heat_object = get_object(heat_object_id, state.metadata) - is_obj_hot = heat_object['objectId'] in self.env.heated_objects - reward, done = (self.rewards['positive'], True) if is_obj_hot else (self.rewards['negative'], False) - return reward, done - - -class CoolObjectAction(BaseAction): - ''' - CoolObject - ''' - - valid_actions = {'OpenObject', 'CloseObject', 'PickupObject', 'PutObject'} - - def get_reward(self, state, prev_state, expert_plan, goal_idx): - if state.metadata['lastAction'] not in self.valid_actions: - reward, done = self.rewards['invalid_action'], False - return reward, done - - reward, done = self.rewards['neutral'], False - next_put_goal_idx = goal_idx+2 # (+1) GotoLocation -> (+2) PutObject (get the objectId from the PutObject action) - if next_put_goal_idx < len(expert_plan): - cool_object_id = expert_plan[next_put_goal_idx]['planner_action']['objectId'] - cool_object = get_object(cool_object_id, state.metadata) - is_obj_cool = cool_object['objectId'] in self.env.cooled_objects - reward, done = (self.rewards['positive'], True) if is_obj_cool else (self.rewards['negative'], False) - return reward, done - - -def get_action(action_type, gt_graph, env, reward_config, strict): - action_type_str = action_type + "Action" - - if action_type_str in globals(): - action = globals()[action_type_str] - return action(gt_graph, env, reward_config[action_type_str], strict) - else: - raise Exception("Invalid action_type %s" % action_type_str) \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/env/tasks.py b/agent_system/environments/env_package/alfworld/alfworld/env/tasks.py deleted file mode 100644 index 478d5dae..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/env/tasks.py +++ /dev/null @@ -1,464 +0,0 @@ -import json -import numpy as np -from alfworld.gen.graph import graph_obj -from alfworld.gen.utils.game_util import get_objects_with_name_and_prop -from alfworld.env.reward import get_action - - -class BaseTask(object): - ''' - base class for tasks - ''' - - def __init__(self, traj, env, args, reward_type='sparse', max_episode_length=2000): - # settings - self.traj = traj - self.env = env - self.args = args - self.task_type = self.traj['task_type'] - self.max_episode_length = max_episode_length - self.reward_type = reward_type - self.step_num = 0 - self.num_subgoals = len(self.traj['plan']['high_pddl']) - 1 # ignore end noop - self.goal_finished = False - - # internal states - self.goal_idx = 0 - self.finished = -1 - - # load navigation graph - self.gt_graph = None - self.load_nav_graph() - - # reward config - self.reward_config = None - self.load_reward_config(args.reward_config) - self.strict = 'strict' in reward_type - - # prev state - self.prev_state = self.env.last_event - - def load_reward_config(self, config_file): - ''' - load json file with reward values - ''' - with open(config_file, 'r') as rc: - reward_config = json.load(rc) - self.reward_config = reward_config - - def load_nav_graph(self): - ''' - build navigation grid graph - ''' - floor_plan = self.traj['scene']['floor_plan'] - scene_num = self.traj['scene']['scene_num'] - self.gt_graph = graph_obj.Graph(use_gt=True, construct_graph=True, scene_id=scene_num) - - def goal_satisfied(self, state): - ''' - check if the overall task goal was satisfied. - ''' - raise NotImplementedError - - def transition_reward(self, state): - ''' - immediate reward given the current state - ''' - reward = 0 - - # goal completed - if self.goal_finished: - done = True - return reward, done - - # get subgoal and action - expert_plan = self.traj['plan']['high_pddl'] - action_type = expert_plan[self.goal_idx]['planner_action']['action'] - - # subgoal reward - if "dense" in self.reward_type: - action = get_action(action_type, self.gt_graph, self.env, self.reward_config, self.strict) - sg_reward, sg_done = action.get_reward(state, self.prev_state, expert_plan, self.goal_idx) - reward += sg_reward - if sg_done: - self.finished += 1 - if self.goal_idx + 1 < self.num_subgoals: - self.goal_idx += 1 - - # end task reward - goal_finished = self.goal_satisfied(state) - if goal_finished: - reward += self.reward_config['Generic']['goal_reward'] - self.goal_finished = True - - # success reward - if "success" in self.reward_type and self.env.last_event.metadata['lastActionSuccess']: - reward += self.reward_config['Generic']['success'] - - # failure reward - if "failure" in self.reward_type and not self.env.last_event.metadata['lastActionSuccess']: - reward += self.reward_config['Generic']['failure'] - - # step penalty - if self.step_num > len(self.traj['plan']['low_actions']): - reward += self.reward_config['Generic']['step_penalty'] - - # save event - self.prev_state = self.env.last_event - - # step and check if max_episode_length reached - self.step_num += 1 - done = self.goal_idx >= self.num_subgoals or self.step_num >= self.max_episode_length - return reward, done - - def reset(self): - ''' - Reset internal states - ''' - self.goal_idx = 0 - self.finished = -1 - self.step_num = 0 - self.goal_finished = False - - def get_subgoal_idx(self): - return self.finished - - def get_target(self, var): - ''' - returns the object type of a task param - ''' - return self.traj['pddl_params'][var] if self.traj['pddl_params'][var] is not None else None - - def get_targets(self): - ''' - returns a dictionary of all targets for the task - ''' - targets = { - 'object': self.get_target('object_target'), - 'parent': self.get_target('parent_target'), - 'toggle': self.get_target('toggle_target'), - 'mrecep': self.get_target('mrecep_target'), - } - - # slice exception - if 'object_sliced' in self.traj['pddl_params'] and self.traj['pddl_params']['object_sliced']: - targets['object'] += 'Sliced' # Change, e.g., "Apple" -> "AppleSliced" as pickup target. - - return targets - - -class PickAndPlaceSimpleTask(BaseTask): - ''' - pick_and_place task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class is inside any receptacle of 'parent' class - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 1 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - - # check if object needs to be sliced - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - if np.any([np.any([p['objectId'] in r['receptacleObjectIds'] - for r in receptacles if r['receptacleObjectIds'] is not None]) - for p in pickupables]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -class PickTwoObjAndPlaceTask(BaseTask): - ''' - pick_two_obj_and_place task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if two objects of 'object' class are in any receptacle of 'parent' class - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 2 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - - # check if object needs to be sliced - if 'Sliced' in targets['object']: - ts += 2 - s += min(len([p for p in pickupables if 'Sliced' in p['objectId']]), 2) - - # placing each object counts as a goal_condition - s += min(np.max([sum([1 if r['receptacleObjectIds'] is not None - and p['objectId'] in r['receptacleObjectIds'] else 0 - for p in pickupables]) - for r in receptacles]), 2) - return s, ts - - def reset(self): - super().reset() - - -class LookAtObjInLightTask(BaseTask): - ''' - look_at_obj_in_light task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class is being held in front of 'toggle' object that is turned on - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 2 - s = 0 - - targets = self.get_targets() - toggleables = get_objects_with_name_and_prop(targets['toggle'], 'toggleable', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - inventory_objects = state.metadata['inventoryObjects'] - - # check if object needs to be sliced - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - # check if the right object is in hand - if len(inventory_objects) > 0 and inventory_objects[0]['objectId'] in [p['objectId'] for p in pickupables]: - s += 1 - # check if the lamp is visible and turned on - if np.any([t['isToggled'] and t['visible'] for t in toggleables]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -class PickHeatThenPlaceInRecepTask(BaseTask): - ''' - pick_heat_then_place_in_recep task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class inside receptacle of 'parent' class is hot - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 3 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - - # check if object needs to be sliced - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - objs_in_place = [p['objectId'] for p in pickupables for r in receptacles - if r['receptacleObjectIds'] is not None and p['objectId'] in r['receptacleObjectIds']] - objs_heated = [p['objectId'] for p in pickupables if p['objectId'] in self.env.heated_objects] - - # check if object is in the receptacle - if len(objs_in_place) > 0: - s += 1 - # check if some object was heated - if len(objs_heated) > 0: - s += 1 - # check if the object is both in the receptacle and hot - if np.any([obj_id in objs_heated for obj_id in objs_in_place]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -class PickCoolThenPlaceInRecepTask(BaseTask): - ''' - pick_cool_then_place_in_recep task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class inside receptacle of 'parent' class is cold - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 3 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - objs_in_place = [p['objectId'] for p in pickupables for r in receptacles - if r['receptacleObjectIds'] is not None and p['objectId'] in r['receptacleObjectIds']] - objs_cooled = [p['objectId'] for p in pickupables if p['objectId'] in self.env.cooled_objects] - - # check if object is in the receptacle - if len(objs_in_place) > 0: - s += 1 - # check if some object was cooled - if len(objs_cooled) > 0: - s += 1 - # check if the object is both in the receptacle and cold - if np.any([obj_id in objs_cooled for obj_id in objs_in_place]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -class PickCleanThenPlaceInRecepTask(BaseTask): - ''' - pick_clean_then_place_in_recep task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class inside receptacle of 'parent' class is clean - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 3 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - objs_in_place = [p['objectId'] for p in pickupables for r in receptacles - if r['receptacleObjectIds'] is not None and p['objectId'] in r['receptacleObjectIds']] - objs_cleaned = [p['objectId'] for p in pickupables if p['objectId'] in self.env.cleaned_objects] - - # check if object is in the receptacle - if len(objs_in_place) > 0: - s += 1 - # check if some object was cleaned - if len(objs_cleaned) > 0: - s += 1 - # check if the object is both in the receptacle and clean - if np.any([obj_id in objs_cleaned for obj_id in objs_in_place]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -class PickAndPlaceWithMovableRecepTask(BaseTask): - ''' - pick_and_place_with_movable_recep task - ''' - - def __init__(self, *args, **kwargs): - super().__init__(*args, **kwargs) - - def goal_satisfied(self, state): - # check if any object of 'object' class is inside any movable receptacle of 'mrecep' class at receptacle of 'parent' class - pcs = self.goal_conditions_met(state) - return pcs[0] == pcs[1] - - def goal_conditions_met(self, state): - ts = 3 - s = 0 - - targets = self.get_targets() - receptacles = get_objects_with_name_and_prop(targets['parent'], 'receptacle', state.metadata) - pickupables = get_objects_with_name_and_prop(targets['object'], 'pickupable', state.metadata) - movables = get_objects_with_name_and_prop(targets['mrecep'], 'pickupable', state.metadata) - - # check if object needs to be sliced - if 'Sliced' in targets['object']: - ts += 1 - if len([p for p in pickupables if 'Sliced' in p['objectId']]) >= 1: - s += 1 - - pickup_in_place = [p for p in pickupables for m in movables - if 'receptacleObjectIds' in p and m['receptacleObjectIds'] is not None - and p['objectId'] in m['receptacleObjectIds']] - movable_in_place = [m for m in movables for r in receptacles - if 'receptacleObjectIds' in r and r['receptacleObjectIds'] is not None - and m['objectId'] in r['receptacleObjectIds']] - # check if the object is in the final receptacle - if len(pickup_in_place) > 0: - s += 1 - # check if the movable receptacle is in the final receptacle - if len(movable_in_place) > 0: - s += 1 - # check if both the object and movable receptacle stack is in the final receptacle - if np.any([np.any([p['objectId'] in m['receptacleObjectIds'] for p in pickupables]) and - np.any([r['objectId'] in m['parentReceptacles'] for r in receptacles]) for m in movables - if m['parentReceptacles'] is not None and m['receptacleObjectIds'] is not None]): - s += 1 - - return s, ts - - def reset(self): - super().reset() - - -def get_task(task_type, traj, env, args, reward_type='sparse', max_episode_length=2000): - task_class_str = task_type.replace('_', ' ').title().replace(' ', '') + "Task" - - if task_class_str in globals(): - task = globals()[task_class_str] - return task(traj, env, args, reward_type=reward_type, max_episode_length=max_episode_length) - else: - raise Exception("Invalid task_type %s" % task_class_str) \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/env/thor_env.py b/agent_system/environments/env_package/alfworld/alfworld/env/thor_env.py deleted file mode 100644 index 4e3ad4e4..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/env/thor_env.py +++ /dev/null @@ -1,626 +0,0 @@ -import copy -import os -import glob -import numpy as np -from collections import Counter, OrderedDict - -try: - from ai2thor.controller import Controller - import cv2 -except ImportError: - raise ImportError("ai2thor or cv2 not found. Please install them via `pip install alfworld[vis]`.") - -import alfworld.gen.constants as constants -from alfworld.env.tasks import get_task -import alfworld.gen.utils.image_util as image_util -from alfworld.gen.utils import game_util -from alfworld.gen.utils.game_util import get_objects_of_type, get_obj_of_type_closest_to_obj - - -DEFAULT_RENDER_SETTINGS = {'renderImage': True, - 'renderDepthImage': False, - 'renderClassImage': False, - 'renderObjectImage': False, - } - -class ThorEnv(Controller): - ''' - an extension of ai2thor.controller.Controller for ALFRED tasks - ''' - def __init__(self, x_display=constants.X_DISPLAY, - player_screen_height=constants.DETECTION_SCREEN_HEIGHT, - player_screen_width=constants.DETECTION_SCREEN_WIDTH, - quality='MediumCloseFitShadows', - build_path=constants.BUILD_PATH, - save_frames_to_disk=False, - save_frames_path="./", - smooth_nav=False): - - self.smooth_nav = smooth_nav - super().__init__(quality=quality) - self.local_executable_path = build_path - self.start(x_display=x_display, - player_screen_height=player_screen_height, - player_screen_width=player_screen_width) - self.task = None - - # internal states - self.cleaned_objects = set() - self.cooled_objects = set() - self.heated_objects = set() - - # save frames settings - self.save_frames_to_disk = save_frames_to_disk - self.save_frames_path = save_frames_path - - print("ThorEnv started.") - - def reset(self, scene_name_or_num, - grid_size=constants.AGENT_STEP_SIZE / constants.RECORD_SMOOTHING_FACTOR, - camera_y=constants.CAMERA_HEIGHT_OFFSET, - render_image=constants.RENDER_IMAGE, - render_depth_image=constants.RENDER_DEPTH_IMAGE, - render_class_image=constants.RENDER_CLASS_IMAGE, - render_object_image=constants.RENDER_OBJECT_IMAGE, - visibility_distance=constants.VISIBILITY_DISTANCE): - ''' - reset scene and task states - ''' - print("Resetting ThorEnv") - - if type(scene_name_or_num) == str: - scene_name = scene_name_or_num - else: - scene_name = 'FloorPlan%d' % scene_name_or_num - - super().reset(scene_name) - event = super().step(dict( - action='Initialize', - gridSize=grid_size, - cameraY=camera_y, - renderImage=render_image, - renderDepthImage=render_depth_image, - renderClassImage=render_class_image, - renderObjectImage=render_object_image, - visibility_distance=visibility_distance, - makeAgentsVisible=False, - )) - - # reset task if specified - if self.task is not None: - self.task.reset() - - # clear object state changes - self.reset_states() - - return event - - def reset_states(self): - ''' - clear state changes - ''' - self.cleaned_objects = set() - self.cooled_objects = set() - self.heated_objects = set() - - def restore_scene(self, object_poses, object_toggles, dirty_and_empty): - ''' - restore object locations and states - ''' - super().step(dict( - action='Initialize', - gridSize=constants.AGENT_STEP_SIZE / constants.RECORD_SMOOTHING_FACTOR, - cameraY=constants.CAMERA_HEIGHT_OFFSET, - renderImage=constants.RENDER_IMAGE, - renderDepthImage=constants.RENDER_DEPTH_IMAGE, - renderClassImage=constants.RENDER_CLASS_IMAGE, - renderObjectImage=constants.RENDER_OBJECT_IMAGE, - visibility_distance=constants.VISIBILITY_DISTANCE, - makeAgentsVisible=False, - )) - if len(object_toggles) > 0: - super().step((dict(action='SetObjectToggles', objectToggles=object_toggles))) - - if dirty_and_empty: - super().step(dict(action='SetStateOfAllObjects', - StateChange="CanBeDirty", - forceAction=True)) - super().step(dict(action='SetStateOfAllObjects', - StateChange="CanBeFilled", - forceAction=False)) - super().step((dict(action='SetObjectPoses', objectPoses=object_poses))) - - def set_task(self, traj, args, reward_type='sparse', max_episode_length=2000): - ''' - set the current task type (one of 7 tasks) - ''' - task_type = traj['task_type'] - self.task = get_task(task_type, traj, self, args, reward_type=reward_type, max_episode_length=max_episode_length) - - def step(self, action, smooth_nav=False): - ''' - overrides ai2thor.controller.Controller.step() for smooth navigation and goal_condition updates - ''' - if smooth_nav or self.smooth_nav: - if "MoveAhead" in action['action']: - event = self.smooth_move_ahead(action) - elif "Rotate" in action['action']: - event = self.smooth_rotate(action) - elif "Look" in action['action']: - event = self.smooth_look(action) - else: - event = super().step(action) - else: - if "LookUp" in action['action']: - event = self.look_angle(-constants.AGENT_HORIZON_ADJ) - elif "LookDown" in action['action']: - event = self.look_angle(constants.AGENT_HORIZON_ADJ) - else: - event = super().step(action) - - if self.save_frames_to_disk: - self.save_frames(event) - event = self.update_states(action) - self.check_post_conditions(action) - return event - - def save_frames(self, event): - def save_png(e): - if not os.path.exists(self.save_frames_path): - os.makedirs(self.save_frames_path) - rgb_image = e.frame[:,:,::-1] - img_idx = len(glob.glob(self.save_frames_path + '/*.png')) - cv2.imwrite(self.save_frames_path + '/%09d.png' % img_idx, rgb_image) - - if type(event) is list: - for e in event: - save_png(e) - else: - save_png(event) - - def check_post_conditions(self, action): - ''' - handle special action post-conditions - ''' - if action['action'] == 'ToggleObjectOn': - self.check_clean(action['objectId']) - - def update_states(self, action): - ''' - extra updates to metadata after step - ''' - # add 'cleaned' to all object that were washed in the sink - event = self.last_event - if event.metadata['lastActionSuccess']: - # clean - if action['action'] == 'ToggleObjectOn' and "Faucet" in action['objectId']: - sink_basin = get_obj_of_type_closest_to_obj('SinkBasin', action['objectId'], event.metadata) - cleaned_object_ids = sink_basin['receptacleObjectIds'] - self.cleaned_objects = self.cleaned_objects | set(cleaned_object_ids) if cleaned_object_ids is not None else set() - # heat - if action['action'] == 'ToggleObjectOn' and "Microwave" in action['objectId']: - microwave = get_objects_of_type('Microwave', event.metadata)[0] - heated_object_ids = microwave['receptacleObjectIds'] - self.heated_objects = self.heated_objects | set(heated_object_ids) if heated_object_ids is not None else set() - # cool - if action['action'] == 'CloseObject' and "Fridge" in action['objectId']: - fridge = get_objects_of_type('Fridge', event.metadata)[0] - cooled_object_ids = fridge['receptacleObjectIds'] - self.cooled_objects = self.cooled_objects | set(cooled_object_ids) if cooled_object_ids is not None else set() - - return event - - def get_transition_reward(self): - if self.task is None: - raise Exception("WARNING: no task setup for transition_reward") - else: - return self.task.transition_reward(self.last_event) - - def get_goal_satisfied(self): - if self.task is None: - raise Exception("WARNING: no task setup for goal_satisfied") - else: - return self.task.goal_satisfied(self.last_event) - - def get_goal_conditions_met(self): - if self.task is None: - raise Exception("WARNING: no task setup for goal_satisfied") - else: - return self.task.goal_conditions_met(self.last_event) - - def get_subgoal_idx(self): - if self.task is None: - raise Exception("WARNING: no task setup for subgoal_idx") - else: - return self.task.get_subgoal_idx() - - def noop(self): - ''' - do nothing - ''' - super().step(dict(action='Pass')) - - def smooth_move_ahead(self, action, render_settings=None): - ''' - smoother MoveAhead - ''' - if render_settings is None: - render_settings = DEFAULT_RENDER_SETTINGS - smoothing_factor = constants.RECORD_SMOOTHING_FACTOR - new_action = copy.deepcopy(action) - new_action['moveMagnitude'] = constants.AGENT_STEP_SIZE / smoothing_factor - - new_action['renderImage'] = render_settings['renderImage'] - new_action['renderClassImage'] = render_settings['renderClassImage'] - new_action['renderObjectImage'] = render_settings['renderObjectImage'] - new_action['renderDepthImage'] = render_settings['renderDepthImage'] - - events = [] - for xx in range(smoothing_factor - 1): - event = super().step(new_action) - if event.metadata['lastActionSuccess']: - events.append(event) - - event = super().step(new_action) - if event.metadata['lastActionSuccess']: - events.append(event) - return events - - def smooth_rotate(self, action, render_settings=None): - ''' - smoother RotateLeft and RotateRight - ''' - if render_settings is None: - render_settings = DEFAULT_RENDER_SETTINGS - event = self.last_event - horizon = np.round(event.metadata['agent']['cameraHorizon'], 4) - position = event.metadata['agent']['position'] - rotation = event.metadata['agent']['rotation'] - start_rotation = rotation['y'] - if action['action'] == 'RotateLeft': - end_rotation = (start_rotation - 90) - else: - end_rotation = (start_rotation + 90) - - events = [] - for xx in np.arange(.1, 1.0001, .1): - if xx < 1: - teleport_action = { - 'action': 'TeleportFull', - 'rotation': np.round(start_rotation * (1 - xx) + end_rotation * xx, 3), - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': horizon, - 'tempRenderChange': True, - 'renderNormalsImage': False, - 'renderImage': render_settings['renderImage'], - 'renderClassImage': render_settings['renderClassImage'], - 'renderObjectImage': render_settings['renderObjectImage'], - 'renderDepthImage': render_settings['renderDepthImage'], - } - event = super().step(teleport_action) - else: - teleport_action = { - 'action': 'TeleportFull', - 'rotation': np.round(start_rotation * (1 - xx) + end_rotation * xx, 3), - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': horizon, - } - event = super().step(teleport_action) - - if event.metadata['lastActionSuccess']: - events.append(event) - return events - - def smooth_look(self, action, render_settings=None): - ''' - smoother LookUp and LookDown - ''' - if render_settings is None: - render_settings = DEFAULT_RENDER_SETTINGS - event = self.last_event - start_horizon = event.metadata['agent']['cameraHorizon'] - rotation = np.round(event.metadata['agent']['rotation']['y'], 4) - end_horizon = start_horizon + constants.AGENT_HORIZON_ADJ * (1 - 2 * int(action['action'] == 'LookUp')) - position = event.metadata['agent']['position'] - - events = [] - for xx in np.arange(.1, 1.0001, .1): - if xx < 1: - teleport_action = { - 'action': 'TeleportFull', - 'rotation': rotation, - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': np.round(start_horizon * (1 - xx) + end_horizon * xx, 3), - 'tempRenderChange': True, - 'renderNormalsImage': False, - 'renderImage': render_settings['renderImage'], - 'renderClassImage': render_settings['renderClassImage'], - 'renderObjectImage': render_settings['renderObjectImage'], - 'renderDepthImage': render_settings['renderDepthImage'], - } - event = super().step(teleport_action) - else: - teleport_action = { - 'action': 'TeleportFull', - 'rotation': rotation, - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': np.round(start_horizon * (1 - xx) + end_horizon * xx, 3), - } - event = super().step(teleport_action) - - if event.metadata['lastActionSuccess']: - events.append(event) - return events - - def look_angle(self, angle, render_settings=None): - ''' - look at a specific angle - ''' - if render_settings is None: - render_settings = DEFAULT_RENDER_SETTINGS - event = self.last_event - start_horizon = event.metadata['agent']['cameraHorizon'] - rotation = np.round(event.metadata['agent']['rotation']['y'], 4) - end_horizon = start_horizon + angle - position = event.metadata['agent']['position'] - - teleport_action = { - 'action': 'TeleportFull', - 'rotation': rotation, - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': np.round(end_horizon, 3), - 'tempRenderChange': True, - 'renderNormalsImage': False, - 'renderImage': render_settings['renderImage'], - 'renderClassImage': render_settings['renderClassImage'], - 'renderObjectImage': render_settings['renderObjectImage'], - 'renderDepthImage': render_settings['renderDepthImage'], - } - event = super().step(teleport_action) - return event - - def rotate_angle(self, angle, render_settings=None): - ''' - rotate at a specific angle - ''' - if render_settings is None: - render_settings = DEFAULT_RENDER_SETTINGS - event = self.last_event - horizon = np.round(event.metadata['agent']['cameraHorizon'], 4) - position = event.metadata['agent']['position'] - rotation = event.metadata['agent']['rotation'] - start_rotation = rotation['y'] - end_rotation = start_rotation + angle - - teleport_action = { - 'action': 'TeleportFull', - 'rotation': np.round(end_rotation, 3), - 'x': position['x'], - 'z': position['z'], - 'y': position['y'], - 'horizon': horizon, - 'tempRenderChange': True, - 'renderNormalsImage': False, - 'renderImage': render_settings['renderImage'], - 'renderClassImage': render_settings['renderClassImage'], - 'renderObjectImage': render_settings['renderObjectImage'], - 'renderDepthImage': render_settings['renderDepthImage'], - } - event = super().step(teleport_action) - return event - - def to_thor_api_exec(self, action, object_id="", smooth_nav=False): - # TODO: parametrized navigation commands - - if "RotateLeft" in action: - action = dict(action="RotateLeft", - forceAction=True) - event = self.step(action, smooth_nav=smooth_nav) - elif "RotateRight" in action: - action = dict(action="RotateRight", - forceAction=True) - event = self.step(action, smooth_nav=smooth_nav) - elif "MoveAhead" in action: - action = dict(action="MoveAhead", - forceAction=True) - event = self.step(action, smooth_nav=smooth_nav) - elif "LookUp" in action: - action = dict(action="LookUp", - forceAction=True) - event = self.step(action, smooth_nav=smooth_nav) - elif "LookDown" in action: - action = dict(action="LookDown", - forceAction=True) - event = self.step(action, smooth_nav=smooth_nav) - elif "OpenObject" in action: - action = dict(action="OpenObject", - objectId=object_id, - moveMagnitude=1.0) - event = self.step(action) - elif "CloseObject" in action: - action = dict(action="CloseObject", - objectId=object_id, - forceAction=True) - event = self.step(action) - elif "PickupObject" in action: - action = dict(action="PickupObject", - objectId=object_id) - event = self.step(action) - elif "PutObject" in action: - inventory_object_id = self.last_event.metadata['inventoryObjects'][0]['objectId'] - action = dict(action="PutObject", - objectId=inventory_object_id, - receptacleObjectId=object_id, - forceAction=True, - placeStationary=True) - event = self.step(action) - elif "ToggleObjectOn" in action: - action = dict(action="ToggleObjectOn", - objectId=object_id) - event = self.step(action) - - elif "ToggleObjectOff" in action: - action = dict(action="ToggleObjectOff", - objectId=object_id) - event = self.step(action) - elif "SliceObject" in action: - # check if agent is holding knife in hand - inventory_objects = self.last_event.metadata['inventoryObjects'] - if len(inventory_objects) == 0 or 'Knife' not in inventory_objects[0]['objectType']: - raise Exception("Agent should be holding a knife before slicing.") - - action = dict(action="SliceObject", - objectId=object_id) - event = self.step(action) - else: - raise Exception("Invalid action. Conversion to THOR API failed! (action='" + str(action) + "')") - - return event, action - - def check_clean(self, object_id): - ''' - Handle special case when Faucet is toggled on. - In this case, we need to execute a `CleanAction` in the simulator on every object in the corresponding - basin. This is to clean everything in the sink rather than just things touching the stream. - ''' - event = self.last_event - if event.metadata['lastActionSuccess'] and 'Faucet' in object_id: - # Need to delay one frame to let `isDirty` update on stream-affected. - event = self.step({'action': 'Pass'}) - sink_basin_obj = game_util.get_obj_of_type_closest_to_obj("SinkBasin", object_id, event.metadata) - for in_sink_obj_id in sink_basin_obj['receptacleObjectIds']: - if (game_util.get_object(in_sink_obj_id, event.metadata)['dirtyable'] - and game_util.get_object(in_sink_obj_id, event.metadata)['isDirty']): - event = self.step({'action': 'CleanObject', 'objectId': in_sink_obj_id}) - return event - - def prune_by_any_interaction(self, instances_ids): - ''' - ignores any object that is not interactable in anyway - ''' - pruned_instance_ids = [] - for obj in self.last_event.metadata['objects']: - obj_id = obj['objectId'] - if obj_id in instances_ids: - if obj['pickupable'] or obj['receptacle'] or obj['openable'] or obj['toggleable'] or obj['sliceable']: - pruned_instance_ids.append(obj_id) - - ordered_instance_ids = [id for id in instances_ids if id in pruned_instance_ids] - return ordered_instance_ids - - def va_interact(self, action, interact_mask=None, smooth_nav=True, mask_px_sample=1, debug=False): - ''' - interact mask based action call - ''' - - all_ids = [] - - if type(interact_mask) is str and interact_mask == "NULL": - raise Exception("NULL mask.") - elif interact_mask is not None: - # ground-truth instance segmentation mask from THOR - instance_segs = np.array(self.last_event.instance_segmentation_frame) - color_to_object_id = self.last_event.color_to_object_id - - # get object_id for each 1-pixel in the interact_mask - nz_rows, nz_cols = np.nonzero(interact_mask) - instance_counter = Counter() - for i in range(0, len(nz_rows), mask_px_sample): - x, y = nz_rows[i], nz_cols[i] - instance = tuple(instance_segs[x, y]) - instance_counter[instance] += 1 - if debug: - print("action_box", "instance_counter", instance_counter) - - # iou scores for all instances - iou_scores = {} - for color_id, intersection_count in instance_counter.most_common(): - union_count = np.sum(np.logical_or(np.all(instance_segs == color_id, axis=2), interact_mask.astype(bool))) - iou_scores[color_id] = intersection_count / float(union_count) - iou_sorted_instance_ids = list(OrderedDict(sorted(iou_scores.items(), key=lambda x: x[1], reverse=True))) - - # get the most common object ids ignoring the object-in-hand - inv_obj = self.last_event.metadata['inventoryObjects'][0]['objectId'] \ - if len(self.last_event.metadata['inventoryObjects']) > 0 else None - all_ids = [color_to_object_id[color_id] for color_id in iou_sorted_instance_ids - if color_id in color_to_object_id and color_to_object_id[color_id] != inv_obj] - - # print all ids - if debug: - print("action_box", "all_ids", all_ids) - - # print instance_ids - instance_ids = [inst_id for inst_id in all_ids if inst_id is not None] - if debug: - print("action_box", "instance_ids", instance_ids) - - # prune invalid instances like floors, walls, etc. - instance_ids = self.prune_by_any_interaction(instance_ids) - - # cv2 imshows to show image, segmentation mask, interact mask - if debug: - print("action_box", "instance_ids", instance_ids) - instance_seg = copy.copy(instance_segs) - instance_seg[:, :, :] = interact_mask[:, :, np.newaxis] == 1 - instance_seg *= 255 - - cv2.imshow('seg', instance_segs) - cv2.imshow('mask', instance_seg) - cv2.imshow('full', self.last_event.frame[:,:,::-1]) - cv2.waitKey(0) - - if len(instance_ids) == 0: - err = "Bad interact mask. Couldn't locate target object" - success = False - return success, None, None, err, None - - target_instance_id = instance_ids[0] - else: - target_instance_id = "" - - if debug: - print("taking action: " + str(action) + " on target_instance_id " + str(target_instance_id)) - try: - event, api_action = self.to_thor_api_exec(action, target_instance_id, smooth_nav) - except Exception as err: - success = False - return success, None, None, err, None - - if not event.metadata['lastActionSuccess']: - if interact_mask is not None and debug: - print("Failed to execute action!", action, target_instance_id) - print("all_ids inside BBox: " + str(all_ids)) - instance_seg = copy.copy(instance_segs) - instance_seg[:, :, :] = interact_mask[:, :, np.newaxis] == 1 - cv2.imshow('seg', instance_segs) - cv2.imshow('mask', instance_seg) - cv2.imshow('full', self.last_event.frame[:,:,::-1]) - cv2.waitKey(0) - print(event.metadata['errorMessage']) - success = False - return success, event, target_instance_id, event.metadata['errorMessage'], api_action - - success = True - return success, event, target_instance_id, '', api_action - - @staticmethod - def bbox_to_mask(bbox): - return image_util.bbox_to_mask(bbox) - - @staticmethod - def point_to_mask(point): - return image_util.point_to_mask(point) - - @staticmethod - def decompress_mask(compressed_mask): - return image_util.decompress_mask(compressed_mask) diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/README.md b/agent_system/environments/env_package/alfworld/alfworld/gen/README.md deleted file mode 100644 index 607e80b9..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/README.md +++ /dev/null @@ -1,77 +0,0 @@ -# Data Generation - -We also provide code for generating PDDL-based expert demonstrations. This can be used to extend the training data, albiet without human language annotations. - -## Installation - -Get dependencies and compile the planner: -```bash -$ sudo apt-get install ffmpeg flex bison - -$ cd $ALFRED_ROOT/gen/ff_planner -$ make -``` - -## Generation - -To spawn multiple generation threads: - -```bash -$ cd $ALFRED_ROOT/gen -$ python scripts/generate_trajectories.py --save_path data/new_trajs --in_parallel --debug --num_threads 2 -``` - -This will sample tasks based on the sampling mechanism described in the paper. You might notice a lot of failed executions, which are automatically discarded by the script. - -**Note:** The first time you run the generation script, use `--num_threads 1` to allow the script to download the THOR binary. - -## Replay Checks - -In parallel with generation, replay saved trajectories to check if they are reproducable: - -```bash -$ python scripts/replay_checks.py --data_path data/new_trajs --in_parallel -``` -This will ensure that the interaction masks and expert actions can be deterministically executed in THOR. - -## Data Augmentation - -Currently, the dataset only provides 300x300 RGB images. However, each trajectory can be replayed to save any additional info available from the simulator. See the [augment_trajectories.py](scripts/augment_trajectories.py) script as an example for saving 600x600 RGB, depth and instance segmentation masks from the existing dataset: - -```bash -python scripts/augment_trajectories.py --data_path data/json_2.1.0 --num_threads 2 --smooth_nav --time_delays -``` - -![](../media/aug.png) - -Note that these files consume a lot of storage space. - -## PDDL Tasks - -The goals for the planner are specified in [goal_library.py](goal_library.py). Here is a simple pick-and-place PDDL goal definition: - -``` -# basic pick and place (e.g: "put the apple in the microwave") -gdict["pick_and_place_simple"] = ''' - (:goal - (and - ;; make sure all the cabinets and doors are closed in the end - (forall (?re # receptacle) - (not (opened ?re)) - ) - - ;; make sure some object {obj} exists inside some receptacle {recep} - (exists (?r # receptacle) - (exists (?o # object) - (and - (inReceptacle ?o ?r) - (objectType ?o {obj}Type) - (receptacleType ?r {recep}Type) - ) - ) - ) - ) - ) -) -``` - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/gen/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/__init__.py b/agent_system/environments/env_package/alfworld/alfworld/gen/agents/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/agent_base.py b/agent_system/environments/env_package/alfworld/alfworld/gen/agents/agent_base.py deleted file mode 100644 index 34cb3f72..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/agent_base.py +++ /dev/null @@ -1,60 +0,0 @@ -import copy -import time -import numpy as np - - -class AgentBase(object): - def __init__(self, thread_id=0, game_state=None): - assert(game_state is not None) - self.game_state = game_state - self.thread_id = thread_id - self.timers = np.zeros((2, 2)) - self.total_frame_count = 0 - self.current_frame_count = 0 - self.gt_graph = None - self.bounds = None - self.pose = None - self.terminal = False - self.num_invalid_actions = 0 - self.total_num_invalid_actions = 0 - - def setup_problem(self, game_state_problem_args, scene=None, objs=None): - self.game_state.setup_problem(**game_state_problem_args, scene=scene, objs=objs) - - def reset(self, game_state_reset_args, scene=None, objs=None): - self.game_state.reset(**game_state_reset_args, scene=scene, objs=objs) - - self.timers = np.zeros((2, 2)) - self.current_frame_count = 0 - self.gt_graph = None - self.bounds = None - self.pose = None - self.terminal = False - self.num_invalid_actions = 0 - - self.total_frame_count += 1 - self.gt_graph = self.game_state.gt_graph - self.bounds = self.game_state.bounds - self.pose = self.game_state.pose - - def step(self, action): - self.total_frame_count += 1 - self.current_frame_count += 1 - t_start = time.time() - self.game_state.step(action) - if not self.game_state.event.metadata['lastActionSuccess']: - self.num_invalid_actions += 1 - self.total_num_invalid_actions += 1 - self.timers[0, 0] += time.time() - t_start - self.timers[0, 1] += 1 - if self.timers[0, 1] % 100 == 0: - print('game state step time %.3f' % (self.timers[0, 0] / self.timers[0, 1])) - self.timers[0, :] = 0 - self.pose = self.game_state.pose - - def get_action(self, action_ind): - action = copy.deepcopy(self.game_state.action_space[action_ind]) - if action['action'] == 'End': - # Remove other arguments - action = {'action': 'End'} - return action diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/deterministic_planner_agent.py b/agent_system/environments/env_package/alfworld/alfworld/gen/agents/deterministic_planner_agent.py deleted file mode 100644 index 198d60ec..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/deterministic_planner_agent.py +++ /dev/null @@ -1,26 +0,0 @@ -from alfworld.gen.agents.semantic_map_planner_agent import SemanticMapPlannerAgent - - -class DeterministicPlannerAgent(SemanticMapPlannerAgent): - def __init__(self, thread_id=0, game_state=None): - super(DeterministicPlannerAgent, self).__init__(thread_id, game_state) - self.action_sequence = None - self.question = None - - def reset(self, seed=None, info=None, scene=None, objs=None): - info = super(DeterministicPlannerAgent, self).reset(seed, info, scene=scene, objs=objs) - self.action_sequence = ['Plan', 'End'] - return info - - def step(self, action, executing_plan=True): - if not executing_plan: - self.action_sequence = self.action_sequence[1:] - super(DeterministicPlannerAgent, self).step(action) - - def get_action(self, action_ind=None): - assert(action_ind is None) - return {'action': self.action_sequence[0]} - - def get_reward(self): - return 0, self.terminal - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/plan_agent.py b/agent_system/environments/env_package/alfworld/alfworld/gen/agents/plan_agent.py deleted file mode 100644 index 8dc0ca15..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/plan_agent.py +++ /dev/null @@ -1,94 +0,0 @@ -import alfworld.gen.constants as constants -from alfworld.gen.agents.agent_base import AgentBase -from alfworld.gen.game_states.planned_game_state import PlannedGameState -from alfworld.gen.utils import game_util - - -class PlanAgent(AgentBase): - def __init__(self, thread_id=0, game_state=None, controller_agent=None): - super(PlanAgent, self).__init__(thread_id, game_state) - assert(isinstance(game_state, PlannedGameState)) - self.controller_agent = controller_agent - self.planned = False - - def reset(self): - self.planned = False - - def execute_plan(self): - step_count = 0 - self.planned = True - self.controller_agent.planning = True - if constants.OPEN_LOOP: - plan = self.game_state.get_current_plan(force_update=True) - - if plan[0]['action'] == 'End': - raise ValueError('Empty plan is successful, no work to do') - - elif len(plan) == 0 or len(plan) > constants.PLANNER_MAX_STEPS: - print ("Planning failed. Possibly because the goal was already satisfied") - raise ValueError("Symbolic Planning Failed") - - for idx, plan_action in enumerate(plan): - self.save_plan(plan, idx) - - if plan_action['action'] == 'GotoLocation': - plan_action = self.game_state.get_teleport_action(plan_action) - elif plan_action['action'] == 'End': - break - self.controller_agent.step(plan_action, executing_plan=True) - step_count += 1 - if self.controller_agent.current_frame_count >= constants.MAX_EPISODE_LENGTH: - break - else: - past_plans = [] - plan = self.game_state.get_current_plan(force_update=True) - - if plan[0]['action'] == 'End': - raise ValueError('Empty plan is successful, no work to do') - elif len(plan) == 0 or len(plan) > constants.PLANNER_MAX_STEPS: - print("Symbolic Planning Failed") - raise ValueError("Symbolic Planning Failed") - - plan_action = plan[0] - if constants.USE_DETERMINISTIC_CONTROLLER: - # Don't fail right away, just rotate a few times. - rotations = 0 - while rotations < 4 and (plan_action is None or plan_action['action'] == 'End'): - action = {'action': 'RotateLeft'} - self.controller_agent.step(action, executing_plan=True) - rotations += 1 - plan = self.game_state.get_current_plan(force_update=True) - plan_action = plan[0] - - while not(plan_action is None or plan_action['action'] == 'End'): - self.controller_agent.step(self.game_state.get_plan_action(plan_action), executing_plan=True) - - # save data - self.save_plan(plan, 0) - - step_count += 1 - past_plans.append(plan) - if len(past_plans) > 5: - past_plans = past_plans[-5:] - plan = self.game_state.get_current_plan(force_update=True) - if plan[0]['action'] == 'End': - break - if (step_count >= constants.MAX_PLANNER_STEP_COUNT or - self.controller_agent.current_frame_count >= constants.MAX_EPISODE_LENGTH): - # Too many steps, plan may be looping. - break - if len(plan) > 1 and any([plan == past_plan for past_plan in past_plans]): - plan_action = plan[0] - self.controller_agent.step(self.game_state.get_plan_action(plan_action), executing_plan=True) - step_count += 1 - plan = plan[1:] - plan_action = plan[0] - - self.controller_agent.planning = False - - def save_plan(self, plan, idx=0): - plan_action = plan[idx] - constants.data_dict['plan']['high_pddl'].append({"high_idx": len(constants.data_dict['plan']['high_pddl']), - "planner_action": plan_action, - "discrete_action": game_util.get_discrete_hl_action(plan, idx)}) - constants.data_dict['template']['high_descs'].append(game_util.get_templated_action_str(plan, idx)) diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/semantic_map_planner_agent.py b/agent_system/environments/env_package/alfworld/alfworld/gen/agents/semantic_map_planner_agent.py deleted file mode 100644 index 2594f1dd..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/agents/semantic_map_planner_agent.py +++ /dev/null @@ -1,72 +0,0 @@ -import glob -import cv2 -import alfworld.gen.constants as constants -from alfworld.gen.agents.agent_base import AgentBase -from alfworld.gen.agents.plan_agent import PlanAgent -from alfworld.gen.game_states.planned_game_state import PlannedGameState - - -class SemanticMapPlannerAgent(AgentBase): - def __init__(self, thread_id=0, game_state=None): - assert(isinstance(game_state, PlannedGameState)) - super(SemanticMapPlannerAgent, self).__init__(thread_id, game_state) - - self.plan_agent = PlanAgent(thread_id, game_state, self) - self.planning = False - - def reset(self, seed=None, info=None, scene=None, objs=None): - self.planning = False - info = self.game_state.get_setup_info(info, scene=scene)[0] - super(SemanticMapPlannerAgent, self).reset({'seed': seed, 'info': info}, scene=scene, objs=objs) - if self.plan_agent is not None: - self.plan_agent.reset() - return info - - def setup_problem(self, game_state_problem_args, scene=None, objs=None): - super(SemanticMapPlannerAgent, self).setup_problem(game_state_problem_args, scene=scene, objs=objs) - self.pose = self.game_state.pose - - def get_reward(self): - raise NotImplementedError - - def step(self, action, executing_plan=False): - if action['action'] == 'End': - self.current_frame_count += 1 - self.total_frame_count += 1 - self.terminal = True - - if constants.RECORD_VIDEO_IMAGES: - im_ind = len(glob.glob(constants.save_path + '/*.png')) - for _ in range(10): - cv2.imwrite(constants.save_path + '/%09d.png' % im_ind, - self.game_state.s_t[:, :, ::-1]) - im_ind += 1 - else: - if 'Teleport' in action['action']: - start_pose = self.pose - end_angle = action['horizon'] - end_pose = (int(action['x'] / constants.AGENT_STEP_SIZE), - int(action['z'] / constants.AGENT_STEP_SIZE), - int(action['rotation'] / 90), - int(end_angle)) - - self.game_state.gt_graph.navigate_to_goal(self.game_state, start_pose, end_pose) - self.pose = self.game_state.pose - elif action['action'] == 'Plan': - self.plan_agent.execute_plan() - if not constants.EVAL: - self.current_frame_count += 1 - self.total_frame_count += 1 - elif action['action'] == 'Scan': - self.game_state.step(action) - if not constants.EVAL: - self.current_frame_count += 1 - self.total_frame_count += 1 - elif action['action'] == 'Explore': - if not constants.EVAL: - self.current_frame_count += 1 - self.total_frame_count += 1 - else: - super(SemanticMapPlannerAgent, self).step(action) - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/constants.py b/agent_system/environments/env_package/alfworld/alfworld/gen/constants.py deleted file mode 100644 index 4233c102..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/constants.py +++ /dev/null @@ -1,1235 +0,0 @@ -from collections import OrderedDict -import os - -######################################################################################################################## -# General Settings - -DEBUG = True -EVAL = False -LOG_FILE = 'logs_gen' - -RECORD_VIDEO_IMAGES = True -RECORD_SMOOTHING_FACTOR = 1 -DATA_SAVE_PATH = "dataset/new_trajectories" - -OPEN_LOOP = True -FULL_OBSERVABLE_STATE = True - -######################################################################################################################## -# Generation Ablations - -MAX_NUM_OF_OBJ_INSTANCES = 3 # when randomly initializing the scene, create duplicate instance up to this number -PICKUP_REPEAT_MAX = 4 # how many of the target pickup object to generate in [1, MAX] (randomly chosen) -RECEPTACLE_SPARSE_POINTS = 50 # increment for how many points to leave free for sparsely populated receptacles -RECEPTACLE_EMPTY_POINTS = 200 # increment for how many points to leave free for empty receptacles - -MIN_VISIBLE_RATIO = 0.0011 # minimum area ratio (with respect to image size) of visible object -PLANNER_MAX_STEPS = 100 # if the generated plan is more than these steps, discard the traj -MAX_EPISODE_LENGTH = 1000 # maximum number of API steps allowed per trajectory - -FORCED_SAMPLING = False # set True for debugging instead of proper sampling -PRUNE_UNREACHABLE_POINTS = False # prune navigation points that were deemed unreachable by the proprocessing script - -######################################################################################################################## -# Goals - -GOALS = ["pick_and_place_simple", - "pick_two_obj_and_place", - "look_at_obj_in_light", - "pick_clean_then_place_in_recep", - "pick_heat_then_place_in_recep", - "pick_cool_then_place_in_recep", - "pick_and_place_with_movable_recep"] - -GOALS_VALID = {"pick_and_place_simple": {"Kitchen", "LivingRoom", "Bathroom", "Bedroom"}, - "pick_two_obj_and_place": {"Kitchen", "LivingRoom", "Bathroom", "Bedroom"}, - "look_at_obj_in_light": {"LivingRoom", "Bedroom"}, - "pick_clean_then_place_in_recep": {"Kitchen", "Bathroom"}, - "pick_heat_then_place_in_recep": {"Kitchen"}, - "pick_cool_then_place_in_recep": {"Kitchen"}, - "pick_and_place_with_movable_recep": {"Kitchen", "LivingRoom", "Bedroom"}} - -pddl_goal_type = "pick_and_place_simple" # default goal type - -######################################################################################################################## -# Video Settings - -# filler frame IDs -BEFORE = 0 -MIDDLE = 1 -AFTER = 2 - -# number of image frames to save before and after executing the specified action -SAVE_FRAME_BEFORE_AND_AFTER_COUNTS = { - 'OpenObject': [2, 0, 2], - 'CloseObject': [2, 0, 2], - 'PickupObject': [5, 0, 10], - 'PutObject': [5, 0, 10], - 'CleanObject': [3, 0, 5], - 'HeatObject': [3, 0, 5], - 'CoolObject': [3, 30, 5], - 'ToggleObjectOn': [3, 0, 15], - 'ToggleObjectOff': [1, 0, 5], - 'SliceObject': [3, 0, 7] -} - -# FPS -VIDEO_FRAME_RATE = 5 - -######################################################################################################################## -# Data & Storage - -save_path = DATA_SAVE_PATH -data_dict = OrderedDict() # dictionary for storing trajectory data to be dumped - -######################################################################################################################## -# Unity Hyperparameters - -BUILD_PATH = None -X_DISPLAY = None - -AGENT_STEP_SIZE = 0.25 -AGENT_HORIZON_ADJ = 15 -AGENT_ROTATE_ADJ = 90 -CAMERA_HEIGHT_OFFSET = 0.75 -VISIBILITY_DISTANCE = 1.5 -HORIZON_GRANULARITY = 15 - -RENDER_IMAGE = True -RENDER_DEPTH_IMAGE = True -RENDER_CLASS_IMAGE = True -RENDER_OBJECT_IMAGE = True - -MAX_DEPTH = 5000 -STEPS_AHEAD = 5 -SCENE_PADDING = STEPS_AHEAD * 3 -SCREEN_WIDTH = DETECTION_SCREEN_WIDTH = 300 -SCREEN_HEIGHT = DETECTION_SCREEN_HEIGHT = 300 -MIN_VISIBLE_PIXELS = 10 - -# (400) / (600*600) ~ 0.13% area of image -# int(MIN_VISIBLE_RATIO * float(DETECTION_SCREEN_WIDTH) * float(DETECTION_SCREEN_HEIGHT)) -# MIN_VISIBLE_PIXELS = int(MIN_VISIBLE_RATIO * float(DETECTION_SCREEN_WIDTH) * float( -# DETECTION_SCREEN_HEIGHT)) # (400) / (600*600) ~ 0.13% area of image - -######################################################################################################################## -# Scenes and Objects - -TRAIN_SCENE_NUMBERS = list(range(7, 31)) # Train Kitchens (24/30) -TRAIN_SCENE_NUMBERS.extend(list(range(207, 231))) # Train Living Rooms (24/30) -TRAIN_SCENE_NUMBERS.extend(list(range(307, 331))) # Train Bedrooms (24/30) -TRAIN_SCENE_NUMBERS.extend(list(range(407, 431))) # Train Bathrooms (24/30) - -TEST_SCENE_NUMBERS = list(range(1, 7)) # Test Kitchens (6/30) -TEST_SCENE_NUMBERS.extend(list(range(201, 207))) # Test Living Rooms (6/30) -TEST_SCENE_NUMBERS.extend(list(range(301, 307))) # Test Bedrooms (6/30) -TEST_SCENE_NUMBERS.extend(list(range(401, 407))) # Test Bathrooms (6/30) - -SCENE_NUMBERS = TRAIN_SCENE_NUMBERS + TEST_SCENE_NUMBERS - -# Scene types. -SCENE_TYPE = {"Kitchen": range(1, 31), - "LivingRoom": range(201, 231), - "Bedroom": range(301, 331), - "Bathroom": range(401, 431)} - -OBJECTS = [ - 'AlarmClock', - 'Apple', - 'ArmChair', - 'BaseballBat', - 'BasketBall', - 'Bathtub', - 'BathtubBasin', - 'Bed', - 'Blinds', - 'Book', - 'Boots', - 'Bowl', - 'Box', - 'Bread', - 'ButterKnife', - 'Cabinet', - 'Candle', - 'Cart', - 'CD', - 'CellPhone', - 'Chair', - 'Cloth', - 'CoffeeMachine', - 'CounterTop', - 'CreditCard', - 'Cup', - 'Curtains', - 'Desk', - 'DeskLamp', - 'DishSponge', - 'Drawer', - 'Dresser', - 'Egg', - 'FloorLamp', - 'Footstool', - 'Fork', - 'Fridge', - 'GarbageCan', - 'Glassbottle', - 'HandTowel', - 'HandTowelHolder', - 'HousePlant', - 'Kettle', - 'KeyChain', - 'Knife', - 'Ladle', - 'Laptop', - 'LaundryHamper', - 'LaundryHamperLid', - 'Lettuce', - 'LightSwitch', - 'Microwave', - 'Mirror', - 'Mug', - 'Newspaper', - 'Ottoman', - 'Painting', - 'Pan', - 'PaperTowel', - 'PaperTowelRoll', - 'Pen', - 'Pencil', - 'PepperShaker', - 'Pillow', - 'Plate', - 'Plunger', - 'Poster', - 'Pot', - 'Potato', - 'RemoteControl', - 'Safe', - 'SaltShaker', - 'ScrubBrush', - 'Shelf', - 'ShowerDoor', - 'ShowerGlass', - 'Sink', - 'SinkBasin', - 'SoapBar', - 'SoapBottle', - 'Sofa', - 'Spatula', - 'Spoon', - 'SprayBottle', - 'Statue', - 'StoveBurner', - 'StoveKnob', - 'DiningTable', - 'CoffeeTable', - 'SideTable', - 'TeddyBear', - 'Television', - 'TennisRacket', - 'TissueBox', - 'Toaster', - 'Toilet', - 'ToiletPaper', - 'ToiletPaperHanger', - 'ToiletPaperRoll', - 'Tomato', - 'Towel', - 'TowelHolder', - 'TVStand', - 'Vase', - 'Watch', - 'WateringCan', - 'Window', - 'WineBottle', -] - -OBJECTS_WSLICED = sorted(OBJECTS + - ['AppleSliced', 'BreadSliced', 'LettuceSliced', 'PotatoSliced', 'TomatoSliced'] + - ['Faucet']) - -OBJECTS_LOWER_TO_UPPER = {obj.lower(): obj for obj in OBJECTS} - -OBJECTS_SINGULAR = [ - 'alarmclock', - 'apple', - 'armchair', - 'baseballbat', - 'basketball', - 'bathtub', - 'bathtubbasin', - 'bed', - 'blinds', - 'book', - 'boots', - 'bowl', - 'box', - 'bread', - 'butterknife', - 'cabinet', - 'candle', - 'cart', - 'cd', - 'cellphone', - 'chair', - 'cloth', - 'coffeemachine', - 'countertop', - 'creditcard', - 'cup', - 'curtains', - 'desk', - 'desklamp', - 'dishsponge', - 'drawer', - 'dresser', - 'egg', - 'floorlamp', - 'footstool', - 'fork', - 'fridge', - 'garbagecan', - 'glassbottle', - 'handtowel', - 'handtowelholder', - 'houseplant', - 'kettle', - 'keychain', - 'knife', - 'ladle', - 'laptop', - 'laundryhamper', - 'laundryhamperlid', - 'lettuce', - 'lightswitch', - 'microwave', - 'mirror', - 'mug', - 'newspaper', - 'ottoman', - 'painting', - 'pan', - 'papertowel', - 'papertowelroll', - 'pen', - 'pencil', - 'peppershaker', - 'pillow', - 'plate', - 'plunger', - 'poster', - 'pot', - 'potato', - 'remotecontrol', - 'safe', - 'saltshaker', - 'scrubbrush', - 'shelf', - 'showerdoor', - 'showerglass', - 'sink', - 'sinkbasin', - 'soapbar', - 'soapbottle', - 'sofa', - 'spatula', - 'spoon', - 'spraybottle', - 'statue', - 'stoveburner', - 'stoveknob', - 'diningtable', - 'coffeetable', - 'sidetable' - 'teddybear', - 'television', - 'tennisracket', - 'tissuebox', - 'toaster', - 'toilet', - 'toiletpaper', - 'toiletpaperhanger', - 'toiletpaperroll', - 'tomato', - 'towel', - 'towelholder', - 'tvstand', - 'vase', - 'watch', - 'wateringcan', - 'window', - 'winebottle', -] - -OBJECTS_PLURAL = [ - 'alarmclocks', - 'apples', - 'armchairs', - 'baseballbats', - 'basketballs', - 'bathtubs', - 'bathtubbasins', - 'beds', - 'blinds', - 'books', - 'boots', - 'bottles', - 'bowls', - 'boxes', - 'bread', - 'butterknives', - 'cabinets', - 'candles', - 'carts', - 'cds', - 'cellphones', - 'chairs', - 'cloths', - 'coffeemachines', - 'countertops', - 'creditcards', - 'cups', - 'curtains', - 'desks', - 'desklamps', - 'dishsponges', - 'drawers', - 'dressers', - 'eggs', - 'floorlamps', - 'footstools', - 'forks', - 'fridges', - 'garbagecans', - 'glassbottles', - 'handtowels', - 'handtowelholders', - 'houseplants', - 'kettles', - 'keychains', - 'knives', - 'ladles', - 'laptops', - 'laundryhampers', - 'laundryhamperlids', - 'lettuces', - 'lightswitches', - 'microwaves', - 'mirrors', - 'mugs', - 'newspapers', - 'ottomans', - 'paintings', - 'pans', - 'papertowels', - 'papertowelrolls', - 'pens', - 'pencils', - 'peppershakers', - 'pillows', - 'plates', - 'plungers', - 'posters', - 'pots', - 'potatoes', - 'remotecontrollers', - 'safes', - 'saltshakers', - 'scrubbrushes', - 'shelves', - 'showerdoors', - 'showerglassess', - 'sinks', - 'sinkbasins', - 'soapbars', - 'soapbottles', - 'sofas', - 'spatulas', - 'spoons', - 'spraybottles', - 'statues', - 'stoveburners', - 'stoveknobs', - 'diningtables', - 'coffeetables', - 'sidetable', - 'teddybears', - 'televisions', - 'tennisrackets', - 'tissueboxes', - 'toasters', - 'toilets', - 'toiletpapers', - 'toiletpaperhangers', - 'toiletpaperrolls', - 'tomatoes', - 'towels', - 'towelholders', - 'tvstands', - 'vases', - 'watches', - 'wateringcans', - 'windows', - 'winebottles', -] - -MOVABLE_RECEPTACLES = [ - 'Bowl', - 'Box', - 'Cup', - 'Mug', - 'Plate', - 'Pan', - 'Pot', -] - -MOVABLE_RECEPTACLES_SET = set(MOVABLE_RECEPTACLES) -OBJECTS_SET = set(OBJECTS) | MOVABLE_RECEPTACLES_SET - -OBJECT_CLASS_TO_ID = {obj: ii for (ii, obj) in enumerate(OBJECTS)} - -RECEPTACLES = { - 'BathtubBasin', - 'Bowl', - 'Cup', - 'Drawer', - 'Mug', - 'Plate', - 'Shelf', - 'SinkBasin', - 'Box', - 'Cabinet', - 'CoffeeMachine', - 'CounterTop', - 'Fridge', - 'GarbageCan', - 'HandTowelHolder', - 'Microwave', - 'PaintingHanger', - 'Pan', - 'Pot', - 'StoveBurner', - 'DiningTable', - 'CoffeeTable', - 'SideTable', - 'ToiletPaperHanger', - 'TowelHolder', - 'Safe', - 'BathtubBasin', - 'ArmChair', - 'Toilet', - 'Sofa', - 'Ottoman', - 'Dresser', - 'LaundryHamper', - 'Desk', - 'Bed', - 'Cart', - 'TVStand', - 'Toaster', - } - -NON_RECEPTACLES = OBJECTS_SET - RECEPTACLES - -NUM_RECEPTACLES = len(RECEPTACLES) -NUM_CLASSES = len(OBJECTS) - -# For generating questions -QUESTION_OBJECT_CLASS_LIST = [ - 'Spoon', - 'Potato', - 'Fork', - 'Plate', - 'Egg', - 'Tomato', - 'Bowl', - 'Lettuce', - 'Apple', - 'Knife', - 'Container', - 'Bread', - 'Mug', -] - -VAL_RECEPTACLE_OBJECTS = { - 'Pot': {'Apple', - 'AppleSliced', - 'ButterKnife', - 'DishSponge', - 'Egg', - 'Fork', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Potato', - 'PotatoSliced', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced'}, - 'Pan': {'Apple', - 'AppleSliced', - 'ButterKnife', - 'DishSponge', - 'Egg', - 'Fork', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Potato', - 'PotatoSliced', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced'}, - 'Bowl': {'Apple', - 'AppleSliced', - 'ButterKnife', - 'DishSponge', - 'Egg', - 'Fork', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Potato', - 'PotatoSliced', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'DishSponge', - 'KeyChain', - 'Mug', - 'PaperTowel', - 'Pen', - 'Pencil', - 'RemoteControl', - 'Watch'}, - 'CoffeeMachine': {'Mug'}, - 'Microwave': {'Apple', - 'AppleSliced', - 'Bowl', - 'Bread', - 'BreadSliced', - 'Cup', - 'Egg', - 'Glassbottle', - 'Mug', - 'Plate', - 'Potato', - 'PotatoSliced', - 'Tomato', - 'TomatoSliced'}, - 'StoveBurner': {'Kettle', - 'Pan', - 'Pot'}, - 'Fridge': {'Apple', - 'AppleSliced', - 'Bowl', - 'Bread', - 'BreadSliced', - 'Cup', - 'Egg', - 'Glassbottle', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Pan', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'Tomato', - 'TomatoSliced', - 'WineBottle'}, - 'Mug': {'ButterKnife', - 'Fork', - 'Knife', - 'Pen', - 'Pencil', - 'Spoon', - 'KeyChain', - 'Watch'}, - 'Plate': {'Apple', - 'AppleSliced', - 'ButterKnife', - 'DishSponge', - 'Egg', - 'Fork', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Potato', - 'PotatoSliced', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced', - 'AlarmClock', - 'Book', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'DishSponge', - 'Glassbottle', - 'KeyChain', - 'Mug', - 'PaperTowel', - 'Pen', - 'Pencil', - 'TissueBox', - 'Watch'}, - 'Cup': {'ButterKnife', - 'Fork', - 'Spoon'}, - 'Sofa': {'BasketBall', - 'Book', - 'Box', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'KeyChain', - 'Laptop', - 'Newspaper', - 'Pillow', - 'RemoteControl'}, - 'ArmChair': {'BasketBall', - 'Book', - 'Box', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'KeyChain', - 'Laptop', - 'Newspaper', - 'Pillow', - 'RemoteControl'}, - 'Box': {'AlarmClock', - 'Book', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'DishSponge', - 'Glassbottle', - 'KeyChain', - 'Mug', - 'PaperTowel', - 'Pen', - 'Pencil', - 'RemoteControl', - 'Statue', - 'TissueBox', - 'Vase', - 'Watch'}, - 'Ottoman': {'BasketBall', - 'Book', - 'Box', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'KeyChain', - 'Laptop', - 'Newspaper', - 'Pillow', - 'RemoteControl'}, - 'Dresser': {'AlarmClock', - 'BasketBall', - 'Book', - 'Bowl', - 'Box', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'Cup', - 'Glassbottle', - 'KeyChain', - 'Laptop', - 'Mug', - 'Newspaper', - 'Pen', - 'Pencil', - 'Plate', - 'RemoteControl', - 'SprayBottle', - 'Statue', - 'TennisRacket', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Vase', - 'Watch', - 'WateringCan', - 'WineBottle'}, - 'LaundryHamper': {'Cloth'}, - 'Desk': {'AlarmClock', - 'BasketBall', - 'Book', - 'Bowl', - 'Box', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'Cup', - 'Glassbottle', - 'KeyChain', - 'Laptop', - 'Mug', - 'Newspaper', - 'Pen', - 'Pencil', - 'Plate', - 'RemoteControl', - 'SoapBottle', - 'SprayBottle', - 'Statue', - 'TennisRacket', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Vase', - 'Watch', - 'WateringCan', - 'WineBottle'}, - 'Bed': {'BaseballBat', - 'BasketBall', - 'Book', - 'CellPhone', - 'Laptop', - 'Newspaper', - 'Pillow', - 'TennisRacket'}, - 'Toilet': {'Candle', - 'Cloth', - 'DishSponge', - 'Newspaper', - 'PaperTowel', - 'SoapBar', - 'SoapBottle', - 'SprayBottle', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'HandTowel'}, - 'ToiletPaperHanger': {'ToiletPaper', - 'ToiletPaperRoll'}, - 'TowelHolder': {'Towel'}, - 'HandTowelHolder': {'HandTowel'}, - 'Cart': {'Candle', - 'Cloth', - 'DishSponge', - 'Mug', - 'PaperTowel', - 'Plunger', - 'SoapBar', - 'SoapBottle', - 'SprayBottle', - 'Statue', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Vase', - 'HandTowel'}, - 'BathtubBasin': {'Cloth', - 'DishSponge', - 'SoapBar', - 'HandTowel'}, - 'SinkBasin': {'Apple', - 'AppleSliced', - 'Bowl', - 'ButterKnife', - 'Cloth', - 'Cup', - 'DishSponge', - 'Egg', - 'Glassbottle', - 'Fork', - 'Kettle', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Pan', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'SoapBar', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced', - 'HandTowel'}, - 'Cabinet': {'Book', - 'Bowl', - 'Box', - 'Candle', - 'CD', - 'Cloth', - 'Cup', - 'DishSponge', - 'Glassbottle', - 'Kettle', - 'Ladle', - 'Mug', - 'Newspaper', - 'Pan', - 'PepperShaker', - 'Plate', - 'Plunger', - 'Pot', - 'SaltShaker', - 'SoapBar', - 'SoapBottle', - 'SprayBottle', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Vase', - 'WateringCan', - 'WineBottle', - 'HandTowel'}, - 'TableTop': {'AlarmClock', - 'Apple', - 'AppleSliced', - 'BaseballBat', - 'BasketBall', - 'Book', - 'Bowl', - 'Box', - 'Bread', - 'BreadSliced', - 'ButterKnife', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'Cup', - 'DishSponge', - 'Glassbottle', - 'Egg', - 'Fork', - 'Kettle', - 'KeyChain', - 'Knife', - 'Ladle', - 'Laptop', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Newspaper', - 'Pan', - 'PaperTowel', - 'Pen', - 'Pencil', - 'PepperShaker', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'RemoteControl', - 'SaltShaker', - 'SoapBar', - 'SoapBottle', - 'Spatula', - 'Spoon', - 'SprayBottle', - 'Statue', - 'TennisRacket', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Tomato', - 'TomatoSliced', - 'Vase', - 'Watch', - 'WateringCan', - 'WineBottle', - 'HandTowel'}, - 'CounterTop': {'AlarmClock', - 'Apple', - 'AppleSliced', - 'BaseballBat', - 'BasketBall', - 'Book', - 'Bowl', - 'Box', - 'Bread', - 'BreadSliced', - 'ButterKnife', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'Cup', - 'DishSponge', - 'Egg', - 'Glassbottle', - 'Fork', - 'Kettle', - 'KeyChain', - 'Knife', - 'Ladle', - 'Laptop', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Newspaper', - 'Pan', - 'PaperTowel', - 'Pen', - 'Pencil', - 'PepperShaker', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'RemoteControl', - 'SaltShaker', - 'SoapBar', - 'SoapBottle', - 'Spatula', - 'Spoon', - 'SprayBottle', - 'Statue', - 'TennisRacket', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Tomato', - 'TomatoSliced', - 'Vase', - 'Watch', - 'WateringCan', - 'WineBottle', - 'HandTowel'}, - 'Shelf': {'AlarmClock', - 'Book', - 'Bowl', - 'Box', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'Cup', - 'DishSponge', - 'Glassbottle', - 'Kettle', - 'KeyChain', - 'Mug', - 'Newspaper', - 'PaperTowel', - 'Pen', - 'Pencil', - 'PepperShaker', - 'Plate', - 'Pot', - 'RemoteControl', - 'SaltShaker', - 'SoapBar', - 'SoapBottle', - 'SprayBottle', - 'Statue', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Vase', - 'Watch', - 'WateringCan', - 'WineBottle', - 'HandTowel'}, - 'Drawer': {'Book', - 'ButterKnife', - 'Candle', - 'CD', - 'CellPhone', - 'Cloth', - 'CreditCard', - 'DishSponge', - 'Fork', - 'KeyChain', - 'Knife', - 'Ladle', - 'Newspaper', - 'Pen', - 'Pencil', - 'PepperShaker', - 'RemoteControl', - 'SaltShaker', - 'SoapBar', - 'SoapBottle', - 'Spatula', - 'Spoon', - 'SprayBottle', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Watch', - 'WateringCan', - 'HandTowel'}, - 'GarbageCan': {'Apple', - 'AppleSliced', - 'Bread', - 'BreadSliced', - 'CD', - 'Cloth', - 'DishSponge', - 'Egg', - 'Lettuce', - 'LettuceSliced', - 'Newspaper', - 'PaperTowel', - 'Pen', - 'Pencil', - 'Potato', - 'PotatoSliced', - 'SoapBar', - 'SoapBottle', - 'SprayBottle', - 'TissueBox', - 'ToiletPaper', - 'ToiletPaperRoll', - 'Tomato', - 'TomatoSliced', - 'WineBottle', - 'HandTowel'}, - 'Safe': {'CD', - 'CellPhone', - 'CreditCard', - 'KeyChain', - 'Statue', - 'Vase', - 'Watch'}, - 'TVStand': {'TissueBox'}, - 'Toaster': {'BreadSliced'}, -} -VAL_RECEPTACLE_OBJECTS['DiningTable'] = VAL_RECEPTACLE_OBJECTS['TableTop'] -VAL_RECEPTACLE_OBJECTS['CoffeeTable'] = VAL_RECEPTACLE_OBJECTS['TableTop'] -VAL_RECEPTACLE_OBJECTS['SideTable'] = VAL_RECEPTACLE_OBJECTS['TableTop'] -del VAL_RECEPTACLE_OBJECTS['TableTop'] - -NON_RECEPTACLES_SET = (OBJECTS_SET - set(VAL_RECEPTACLE_OBJECTS.keys())) | set(MOVABLE_RECEPTACLES) - -VAL_ACTION_OBJECTS = { - 'Heatable': {'Apple', - 'AppleSliced', - 'Bread', - 'BreadSliced', - 'Cup', - 'Egg', - 'Mug', - 'Plate', - 'Potato', - 'PotatoSliced', - 'Tomato', - 'TomatoSliced'}, - 'Coolable': {'Apple', - 'AppleSliced', - 'Bowl', - 'Bread', - 'BreadSliced', - 'Cup', - 'Egg', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Pan', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'Tomato', - 'TomatoSliced', - 'WineBottle'}, - 'Cleanable': {'Apple', - 'AppleSliced', - 'Bowl', - 'ButterKnife', - 'Cloth', - 'Cup', - 'DishSponge', - 'Egg', - 'Fork', - 'Kettle', - 'Knife', - 'Ladle', - 'Lettuce', - 'LettuceSliced', - 'Mug', - 'Pan', - 'Plate', - 'Pot', - 'Potato', - 'PotatoSliced', - 'SoapBar', - 'Spatula', - 'Spoon', - 'Tomato', - 'TomatoSliced'}, - 'Toggleable': {'DeskLamp', - 'FloorLamp'}, - 'Sliceable': {'Apple', - 'Bread', - 'Egg', - 'Lettuce', - 'Potato', - 'Tomato'} -} - - -RECEPTACLES_SB = set(RECEPTACLES) | {'Sink', 'Bathtub'} -OBJECTS_DETECTOR = (set(OBJECTS_WSLICED) - set(RECEPTACLES_SB)) | set(MOVABLE_RECEPTACLES) -OBJECTS_DETECTOR -= {'Blinds', 'Boots', 'Cart', 'Chair', 'Curtains', 'Footstool', 'Mirror', 'LightSwtich', 'Painting', 'Poster', 'ShowerGlass', 'Window'} -STATIC_RECEPTACLES = set(RECEPTACLES_SB) - set(MOVABLE_RECEPTACLES) - -OBJECTS_DETECTOR = sorted(list(OBJECTS_DETECTOR)) -STATIC_RECEPTACLES = sorted(list(STATIC_RECEPTACLES)) -ALL_DETECTOR = sorted(list(set(OBJECTS_DETECTOR) | set(STATIC_RECEPTACLES))) - -# object parents -OBJ_PARENTS = {obj: obj for obj in OBJECTS} -OBJ_PARENTS['AppleSliced'] = 'Apple' -OBJ_PARENTS['BreadSliced'] = 'Bread' -OBJ_PARENTS['LettuceSliced'] = 'Lettuce' -OBJ_PARENTS['PotatoSliced'] = 'Potato' -OBJ_PARENTS['TomatoSliced'] = 'Tomato' - -# force a different horizon view for objects of (type, location). If the location is None, force this horizon for all -# objects of that type. -FORCED_HORIZON_OBJS = { - ('FloorLamp', None): 0, - ('Fridge', 18): 30, - ('Toilet', None): 15, -} - -# openable objects with fixed states for transport. -FORCED_OPEN_STATE_ON_PICKUP = { - 'Laptop': False, -} - -# list of openable classes. -OPENABLE_CLASS_LIST = ['Fridge', 'Cabinet', 'Microwave', 'Drawer', 'Safe', 'Box'] -OPENABLE_CLASS_SET = set(OPENABLE_CLASS_LIST) - -######################################################################################################################## \ No newline at end of file diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/README.md b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/README.md deleted file mode 100644 index 81bc18c0..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# Metric FF Planner -Credit: https://fai.cs.uni-saarland.de/hoffmann/metric-ff.html. -Specifically this uses the Metric-FF Version 2.1 (https://fai.cs.uni-saarland.de/hoffmann/ff/Metric-FF-v2.1.tgz). - -Note that the code here is not exactly the same as the one you can download from that website. -Their code had issues that threw segfaults which I was able to fix for this project. -It is possible that my changes caused some other issues that I am unaware of. - -To compile: -```bash -$ cd -$ make -``` diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.c deleted file mode 100644 index 8fb8d240..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.c +++ /dev/null @@ -1,2623 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - -/*********************************************************************** - * File: expressions.c - * Description: functions for handling numerical expressions - * - * - general utilities: - * comparisons between numbers etc. - * - * - LNF compilation: - * normalization of expressions - * translation of subtractions - * - * - LNF post-processing: - * summarization of effects - * encoding of non-minimal LNFs - * - * Author: Joerg Hoffmann 2001 - * - *********************************************************************/ - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - - - - - - - - - - - - - - - -/******************************************************* - * SIMPLE UTILITIES - *******************************************************/ - - - - - - - - - - - - - - - - -Bool number_comparison_holds( Comparator c, float l, float r ) - -{ - - switch ( c ) { - case LE: - if ( l < r ) return TRUE; - break; - case LEQ: - if ( l <= r ) return TRUE; - break; - case EQ: - if ( l == r ) return TRUE; - break; - case GEQ: - if ( l >= r ) return TRUE; - break; - case GE: - if ( l > r ) return TRUE; - break; - case IGUAL: - /* technical for non-required fluents - */ - return TRUE; - default: - printf("\n\nillegal comparator %d in number comp holds", c); - exit( 1 ); - } - - return FALSE; - -} - - - - - - - - - - - - - - - - - - - - - -/******************************************************* - * MACHINERY FOR LNF TRANSFORMATION!!!!!! - *******************************************************/ - - - - - - - - - - - - - - - - - - - - - - - - -Bool transform_to_LNF( void ) - -{ - - if ( !is_linear_task() ) { - return FALSE; - } - - normalize_expressions(); - if ( gcmd_line.display_info == 121 ) { - printf("\n\nnormalized expressions representation is:\n\n"); - print_lnf_representation(); - } - - translate_subtractions(); - if ( gcmd_line.display_info == 122 ) { - printf("\n\nLNF : translated subtractions representation is:\n\n"); - print_lnf_representation(); - } - - /* LNF computed. start post-processing. - */ - - /* do same-cond effects etc. summarization here so as to have - * as tight as possible an encoded LNF representation. - */ - summarize_effects(); - if ( gcmd_line.display_info == 123 ) { - printf("\n\nLNF - summarized effects representation is:\n\n"); - print_lnf_representation(); - } - - encode_lfns_as_artificial_fluents(); - /* optimization is translated into minimizing - * effect costs... here, determine the cost that - * each effect has. - * - * returns TRUE if a non-trivial optimization expression - * could be established. - */ - if ( setup_effect_costs() ) { - if ( gcmd_line.display_info > 1 ) { - printf("\nmetric established (normalized to minimize): "); - print_LnfExpNode( &glnf_metric ); - } - goptimization_established = TRUE; - } - if ( gcmd_line.display_info == 124 ) { - printf("\n\nencoded LNF representation is:\n\n"); - print_lnf_representation(); - } - - return TRUE; - -} - - - -/* simple syntax check - */ -Bool is_linear_task( void ) - -{ - - Action *a; - ActionEffect *e; - int i, j; - - for ( a = gactions; a; a = a->next ) { - /* preconds - */ - for ( i = 0; i < a->num_numeric_preconds; i++ ) { - if ( !is_linear_expression( a->numeric_preconds_lh[i] ) ) { - return FALSE; - } - if ( !is_linear_expression( a->numeric_preconds_rh[i] ) ) { - return FALSE; - } - } - - /* effects - */ - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - for ( j = 0; j < e->num_numeric_conditions; j++ ) { - if ( !is_linear_expression( e->numeric_conditions_lh[j] ) ) { - return FALSE; - } - if ( !is_linear_expression( e->numeric_conditions_rh[j] ) ) { - return FALSE; - } - } - - if ( e->illegal ) { - /* we don't care whether that one's ok or not- - * it won't be applied anyway. - */ - continue; - } - - for ( j = 0; j < e->num_numeric_effects; j++ ) { - if ( e->numeric_effects_neft[j] != INCREASE && - e->numeric_effects_neft[j] != DECREASE && - e->numeric_effects_neft[j] != ASSIGN ) { - return FALSE; - } - if ( !is_linear_expression( e->numeric_effects_rh[j] ) ) { - return FALSE; - } - } - } - } - - /* goal condition also... - */ - for ( i = 0; i < gnum_numeric_goal; i++ ) { - if ( !is_linear_expression( gnumeric_goal_lh[i] ) ) { - return FALSE; - } - if ( !is_linear_expression( gnumeric_goal_rh[i] ) ) { - return FALSE; - } - } - - if ( gmetric != NULL ) { - if ( !is_linear_expression( gmetric ) ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: metric is no linear expression. defaulting to plan length."); - } - free_ExpNode( gmetric ); - gmetric = NULL; - } - } - - return TRUE; - -} - - - -Bool is_linear_expression( ExpNode *n ) - -{ - - switch ( n->connective ) { - case MU: - if ( !is_linear_expression( n->leftson ) || - !is_linear_expression( n->rightson ) ) { - return FALSE; - } - if ( n->leftson->connective != NUMBER && - n->rightson->connective != NUMBER ) { - return FALSE; - } - break; - case DI: - if ( !is_linear_expression( n->leftson ) || - n->rightson->connective != NUMBER ) { - return FALSE; - } - break; - case AD: - case SU: - if ( !is_linear_expression( n->leftson ) || - !is_linear_expression( n->rightson ) ) { - return FALSE; - } - break; - case MINUS: - if ( !is_linear_expression( n->son ) ) { - return FALSE; - } - break; - case NUMBER: - case FHEAD: - break; - default: - printf("\n\nis linear exp: wrong specifier %d", - n->connective); - exit( 1 ); - } - - return TRUE; - -} - - - -void print_lnf_representation( void ) - -{ - - int i; - Action *a; - - for ( i = 0; i < gnum_operators; i++ ) { - printf("\n\n------------------operator %s-----------\n\n", goperators[i]->name); - for ( a = gactions; a; a = a->next ) { - if ( ( !a->norm_operator && - !a->pseudo_action ) || - ( a->norm_operator && - a->norm_operator->operator != goperators[i] ) || - ( a->pseudo_action && - a->pseudo_action->operator != goperators[i] ) ) { - continue; - } - print_lnf_Action( a ); - } - } - printf("\n\n--------------------GOAL REACHED ops-----------\n\n"); - for ( a = gactions; a; a = a->next ) { - if ( !a->norm_operator && - !a->pseudo_action ) { - print_lnf_Action( a ); - } - } - - printf("\n\ninitial state is:\n\n"); - print_State( ginitial_state ); - - printf("\n\ngoal is:\n\n"); - for ( i = 0; i < gnum_logic_goal; i++ ) { - print_ft_name( glogic_goal[i] ); - printf("\n"); - } - for ( i = 0; i < gnum_lnf_goal; i++ ) { - switch ( glnf_goal_comp[i] ) { - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator in lnf goal %d\n\n", glnf_goal_comp[i]); - exit( 1 ); - } - print_LnfExpNode( glnf_goal_lh[i] ); - printf(" %f", glnf_goal_rh[i]); - printf(")\n"); - } - - if ( gmetric ) { - printf("\n\nmetric is (minimize) (constant part skipped):\n"); - print_LnfExpNode( &glnf_metric ); - } else { - printf("\n\nmetric: none, i.e. plan length\n"); - } - -} - - - - - - - - - - - - - - - - - - -/******************************************************* - * SUBPART I: NORMALIZE THE EXPRESSIONS - *******************************************************/ - - - - - - - - - - - - - - - - - -/* local globals. - */ - -Comparator lcomp; - -int lF[MAX_LNF_F]; -float lC[MAX_LNF_F]; -int lnum_F; - -float lc; - - - - - - - - - - - -void normalize_expressions( void ) - -{ - - Action *a, *p, *t; - ActionEffect *e; - int i, j, k; - Bool eq; - LnfExpNode *lnf; - - /* first, pre-normalize all the expressions, i.e. translate - * divisions, and push muliplications downwards. - */ - for ( i = 0; i < gnum_numeric_goal; i++ ) { - if ( !translate_divisions( &(gnumeric_goal_lh[i]) ) ) { - printf("\n\nff: division by zero in goal. no plan will solve it.\n\n"); - exit( 1 ); - } - push_multiplications_down( &(gnumeric_goal_lh[i]) ); - if ( !translate_divisions( &(gnumeric_goal_rh[i]) ) ) { - printf("\n\nff: division by zero in goal. no plan will solve it.\n\n"); - exit( 1 ); - } - push_multiplications_down( &(gnumeric_goal_rh[i]) ); - } - - a = gactions; p = NULL; - while ( a ) { - for ( i = 0; i < a->num_numeric_preconds; i++ ) { - if ( !translate_divisions( &(a->numeric_preconds_lh[i]) ) ) break; - push_multiplications_down( &(a->numeric_preconds_lh[i]) ); - if ( !translate_divisions( &(a->numeric_preconds_rh[i]) ) ) break; - push_multiplications_down( &(a->numeric_preconds_rh[i]) ); - } - if ( i < a->num_numeric_preconds ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: division by zero in precond of "); - print_Action_name( a ); - printf(". skipping action."); - } - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - continue; - } - - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - - for ( j = 0; j < e->num_numeric_conditions; j++ ) { - if ( !translate_divisions( &(e->numeric_conditions_lh[j]) ) ) break; - push_multiplications_down( &(e->numeric_conditions_lh[j]) ); - if ( !translate_divisions( &(e->numeric_conditions_rh[j]) ) ) break; - push_multiplications_down( &(e->numeric_conditions_rh[j]) ); - } - if ( j < e->num_numeric_conditions ) break; - - if ( e->illegal ) { - continue; - } - - for ( j = 0; j < e->num_numeric_effects; j++ ) { - if ( !translate_divisions( &(e->numeric_effects_rh[j]) ) ) break; - push_multiplications_down( &(e->numeric_effects_rh[j]) ); - } - if ( j < e->num_numeric_effects ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: division by zero in effect rh of "); - print_Action_name( a ); - printf(". marking effect as illegal."); - } - e->illegal = TRUE; - } - } - if ( i < a->num_effects ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: division by zero in effect cond of "); - print_Action_name( a ); - printf(". skipping action."); - } - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - continue; - } - - p = a; - a = a->next; - } - if ( gmetric != NULL ) { - if ( !translate_divisions( &gmetric ) ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: division by zero in metric. replaced with plan length."); - } - free_ExpNode( gmetric ); - gmetric = NULL; - } - push_multiplications_down( &gmetric ); - } - - /* now, collect the normalized representations of all expressions. - */ - for ( a = gactions; a; a = a->next ) { - /* preconds - */ - a->lnf_preconds_comp = ( Comparator * ) calloc( MAX_LNF_COMPS, sizeof( Comparator ) ); - a->lnf_preconds_lh = ( LnfExpNode_pointer * ) calloc( MAX_LNF_COMPS, sizeof( LnfExpNode_pointer ) ); - a->lnf_preconds_rh = ( float * ) calloc( MAX_LNF_COMPS, sizeof( float ) ); - a->num_lnf_preconds = 0; - for ( i = 0; i < a->num_numeric_preconds; i++ ) { - if ( a->num_lnf_preconds == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - eq = FALSE; - if ( a->numeric_preconds_comp[i] == EQ ) { - eq = TRUE; - a->numeric_preconds_comp[i] = LEQ; - } - put_comp_into_normalized_locals( a->numeric_preconds_comp[i], - a->numeric_preconds_lh[i], - a->numeric_preconds_rh[i] ); - a->lnf_preconds_comp[a->num_lnf_preconds] = lcomp; - a->lnf_preconds_lh[a->num_lnf_preconds] = new_LnfExpNode(); - lnf = a->lnf_preconds_lh[a->num_lnf_preconds]; - for ( j = 0; j < lnum_F; j++ ) { - if ( lC[j] == 0 ) continue; - if ( lC[j] > 0 ) { - lnf->pF[lnf->num_pF] = lF[j]; - lnf->pC[lnf->num_pF++] = lC[j]; - } else { - lnf->nF[lnf->num_nF] = lF[j]; - lnf->nC[lnf->num_nF++] = (-1) * lC[j]; - } - } - a->lnf_preconds_rh[a->num_lnf_preconds] = lc; - a->num_lnf_preconds++; - if ( eq ) { - if ( a->num_lnf_preconds == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - a->numeric_preconds_comp[i] = EQ; - put_comp_into_normalized_locals( GEQ, - a->numeric_preconds_lh[i], - a->numeric_preconds_rh[i] ); - a->lnf_preconds_comp[a->num_lnf_preconds] = lcomp; - a->lnf_preconds_lh[a->num_lnf_preconds] = new_LnfExpNode(); - lnf = a->lnf_preconds_lh[a->num_lnf_preconds]; - for ( j = 0; j < lnum_F; j++ ) { - if ( lC[j] == 0 ) continue; - if ( lC[j] > 0 ) { - lnf->pF[lnf->num_pF] = lF[j]; - lnf->pC[lnf->num_pF++] = lC[j]; - } else { - lnf->nF[lnf->num_nF] = lF[j]; - lnf->nC[lnf->num_nF++] = (-1) * lC[j]; - } - } - a->lnf_preconds_rh[a->num_lnf_preconds] = lc; - a->num_lnf_preconds++; - } - } - - /* effects - */ - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - - e->lnf_conditions_comp = ( Comparator * ) calloc( MAX_LNF_COMPS, sizeof( Comparator ) ); - e->lnf_conditions_lh = ( LnfExpNode_pointer * ) calloc( MAX_LNF_COMPS, sizeof( LnfExpNode_pointer ) ); - e->lnf_conditions_rh = ( float * ) calloc( MAX_LNF_COMPS, sizeof( float ) ); - e->num_lnf_conditions = 0; - for ( j = 0; j < e->num_numeric_conditions; j++ ) { - if ( e->num_lnf_conditions == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - eq = FALSE; - if ( e->numeric_conditions_comp[j] == EQ ) { - eq = TRUE; - e->numeric_conditions_comp[j] = LEQ; - } - put_comp_into_normalized_locals( e->numeric_conditions_comp[j], - e->numeric_conditions_lh[j], - e->numeric_conditions_rh[j] ); - e->lnf_conditions_comp[e->num_lnf_conditions] = lcomp; - e->lnf_conditions_lh[e->num_lnf_conditions] = new_LnfExpNode(); - lnf = e->lnf_conditions_lh[e->num_lnf_conditions]; - for ( k = 0; k < lnum_F; k++ ) { - if ( lC[k] == 0 ) continue; - if ( lC[k] > 0 ) { - lnf->pF[lnf->num_pF] = lF[k]; - lnf->pC[lnf->num_pF++] = lC[k]; - } else { - lnf->nF[lnf->num_nF] = lF[k]; - lnf->nC[lnf->num_nF++] = (-1) * lC[k]; - } - } - e->lnf_conditions_rh[e->num_lnf_conditions] = lc; - e->num_lnf_conditions++; - if ( eq ) { - if ( e->num_lnf_conditions == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - e->numeric_conditions_comp[j] = EQ; - put_comp_into_normalized_locals( GEQ, - e->numeric_conditions_lh[j], - e->numeric_conditions_rh[j] ); - e->lnf_conditions_comp[e->num_lnf_conditions] = lcomp; - e->lnf_conditions_lh[e->num_lnf_conditions] = new_LnfExpNode(); - lnf = e->lnf_conditions_lh[e->num_lnf_conditions]; - for ( k = 0; k < lnum_F; k++ ) { - if ( lC[k] == 0 ) continue; - if ( lC[k] > 0 ) { - lnf->pF[lnf->num_pF] = lF[k]; - lnf->pC[lnf->num_pF++] = lC[k]; - } else { - lnf->nF[lnf->num_nF] = lF[k]; - lnf->nC[lnf->num_nF++] = (-1) * lC[k]; - } - } - e->lnf_conditions_rh[e->num_lnf_conditions] = lc; - e->num_lnf_conditions++; - } - } - - if ( e->illegal ) { - /* we do have the LNF to know whether the effect appears. - * if it does, then this one is illegal anyway, remembered - * in inst final due to undefined fl access. - * - * if it is LEGAL, then all fluents we're gonna find and - * collect below are relevant!!! - */ - continue; - } - - e->lnf_effects_neft = ( NumericEffectType * ) calloc( MAX_LNF_EFFS, sizeof( NumericEffectType ) ); - e->lnf_effects_fl = ( int * ) calloc( MAX_LNF_EFFS, sizeof( int ) ); - e->lnf_effects_rh = ( LnfExpNode_pointer * ) calloc( MAX_LNF_EFFS, sizeof( LnfExpNode_pointer ) ); - e->num_lnf_effects = 0; - for ( j = 0; j < e->num_numeric_effects; j++ ) { - if ( e->num_lnf_effects == MAX_LNF_EFFS ) { - printf("\n\nincrease MAX_LNF_EFFS! currently %d\n\n", MAX_LNF_EFFS); - exit( 1 ); - } - e->lnf_effects_neft[e->num_lnf_effects] = e->numeric_effects_neft[j]; - e->lnf_effects_fl[e->num_lnf_effects] = e->numeric_effects_fl[j]; - lnum_F = 0; - lc = 0; - if ( e->lnf_effects_neft[e->num_lnf_effects] == DECREASE ) { - collect_normalized_locals( e->numeric_effects_rh[j], FALSE ); - e->lnf_effects_neft[e->num_lnf_effects] = INCREASE; - } else { - collect_normalized_locals( e->numeric_effects_rh[j], TRUE ); - } - e->lnf_effects_rh[e->num_lnf_effects] = new_LnfExpNode(); - lnf = e->lnf_effects_rh[e->num_lnf_effects]; - for ( k = 0; k < lnum_F; k++ ) { - if ( lC[k] == 0 ) continue; - if ( lC[k] > 0 ) { - lnf->pF[lnf->num_pF] = lF[k]; - lnf->pC[lnf->num_pF++] = lC[k]; - } else { - lnf->nF[lnf->num_nF] = lF[k]; - lnf->nC[lnf->num_nF++] = (-1) * lC[k]; - } - } - e->lnf_effects_rh[e->num_lnf_effects]->c = lc; - e->num_lnf_effects++; - } - } - } - - /* goal condition also... - */ - glnf_goal_comp = ( Comparator * ) calloc( MAX_LNF_COMPS, sizeof( Comparator ) ); - glnf_goal_lh = ( LnfExpNode_pointer * ) calloc( MAX_LNF_COMPS, sizeof( LnfExpNode_pointer ) ); - glnf_goal_rh = ( float * ) calloc( MAX_LNF_COMPS, sizeof( float ) ); - gnum_lnf_goal = 0; - for ( i = 0; i < gnum_numeric_goal; i++ ) { - if ( gnum_lnf_goal == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - eq = FALSE; - if ( gnumeric_goal_comp[i] == EQ ) { - eq = TRUE; - gnumeric_goal_comp[i] = LEQ; - } - put_comp_into_normalized_locals( gnumeric_goal_comp[i], - gnumeric_goal_lh[i], - gnumeric_goal_rh[i] ); - glnf_goal_comp[gnum_lnf_goal] = lcomp; - glnf_goal_lh[gnum_lnf_goal] = new_LnfExpNode(); - lnf = glnf_goal_lh[gnum_lnf_goal]; - for ( j = 0; j < lnum_F; j++ ) { - if ( lC[j] == 0 ) continue; - if ( lC[j] > 0 ) { - lnf->pF[lnf->num_pF] = lF[j]; - lnf->pC[lnf->num_pF++] = lC[j]; - } else { - lnf->nF[lnf->num_nF] = lF[j]; - lnf->nC[lnf->num_nF++] = (-1) * lC[j]; - } - } - glnf_goal_rh[gnum_lnf_goal] = lc; - gnum_lnf_goal++; - if ( eq ) { - if ( gnum_lnf_goal == MAX_LNF_COMPS ) { - printf("\n\nincrease MAX_LNF_COMPS! currently %d\n\n", MAX_LNF_COMPS); - exit( 1 ); - } - gnumeric_goal_comp[i] = EQ; - put_comp_into_normalized_locals( GEQ, - gnumeric_goal_lh[i], - gnumeric_goal_rh[i] ); - glnf_goal_comp[gnum_lnf_goal] = lcomp; - glnf_goal_lh[gnum_lnf_goal] = new_LnfExpNode(); - lnf = glnf_goal_lh[gnum_lnf_goal]; - for ( j = 0; j < lnum_F; j++ ) { - if ( lC[j] == 0 ) continue; - if ( lC[j] > 0 ) { - lnf->pF[lnf->num_pF] = lF[j]; - lnf->pC[lnf->num_pF++] = lC[j]; - } else { - lnf->nF[lnf->num_nF] = lF[j]; - lnf->nC[lnf->num_nF++] = (-1) * lC[j]; - } - } - glnf_goal_rh[gnum_lnf_goal] = lc; - gnum_lnf_goal++; - } - } - /* metric... - */ - lnum_F = 0; - lc = 0; - glnf_metric.num_pF = 0; - glnf_metric.num_nF = 0; - glnf_metric.c = 0; - collect_normalized_locals( gmetric, TRUE ); - lnf = &glnf_metric; - for ( j = 0; j < lnum_F; j++ ) { - if ( lC[j] == 0 ) continue; - if ( lC[j] > 0 ) { - lnf->pF[lnf->num_pF] = lF[j]; - lnf->pC[lnf->num_pF++] = lC[j]; - } else { - lnf->nF[lnf->num_nF] = lF[j]; - lnf->nC[lnf->num_nF++] = (-1) * lC[j]; - } - } - - -} - - - -Bool translate_divisions( ExpNode **n ) - -{ - - ExpNode *tmp; - - /* "dirty": also normalize multiplications so that the constant - * is always on the left hand side --- - * simplifies function below a lot. - */ - switch ( (*n)->connective ) { - case DI: - /* rightson is number due to syntax check. - */ - if ( (*n)->rightson->value == 0 ) { - /* what needs to be done we can only decide further up. - */ - printf("\nwarning: division by zero."); - return FALSE; - } - if ( !translate_divisions( &((*n)->leftson) ) ) return FALSE; - (*n)->connective = MU; - (*n)->rightson->value = 1 / (*n)->rightson->value; - tmp = (*n)->rightson; - (*n)->rightson = (*n)->leftson; - (*n)->leftson = tmp; - break; - case MU: - if ( !translate_divisions( &((*n)->leftson) ) ) return FALSE; - if ( !translate_divisions( &((*n)->rightson) ) ) return FALSE; - if ( (*n)->rightson->connective == NUMBER ) { - tmp = (*n)->rightson; - (*n)->rightson = (*n)->leftson; - (*n)->leftson = tmp; - } - break; - case AD: - case SU: - if ( !translate_divisions( &((*n)->leftson) ) ) return FALSE; - if ( !translate_divisions( &((*n)->rightson) ) ) return FALSE; - break; - case MINUS: - if ( !translate_divisions( &((*n)->son) ) ) return FALSE; - break; - case NUMBER: - case FHEAD: - break; - default: - printf("\n\ntranslate divisions: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - - return TRUE; - -} - - - -void push_multiplications_down( ExpNode **n ) - -{ - - ExpNode *tmp1, *tmp2; - - switch ( (*n)->connective ) { - case MU: - /* due to syntax check, at least one of sons is number, - * - * due to above, it's the left one. - * NOTE that this invariant is kept true troughout the - * modifications done here. - */ - if ( (*n)->rightson->connective == NUMBER ) { - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - free_ExpNode( (*n)->rightson ); - (*n)->leftson = NULL; - (*n)->rightson = NULL; - break; - } - if ( (*n)->rightson->connective == FHEAD ) { - (*n)->connective = FHEAD; - (*n)->fl = (*n)->rightson->fl; - (*n)->c = (*n)->leftson->value; - free_ExpNode( (*n)->leftson ); - free_ExpNode( (*n)->rightson ); - (*n)->leftson = NULL; - (*n)->rightson = NULL; - break; - } - if ( (*n)->rightson->connective == MINUS ) { - (*n)->connective = MINUS; - (*n)->son = (*n)->rightson; - (*n)->son->connective = MU; - (*n)->son->leftson = (*n)->leftson; - (*n)->son->rightson = (*n)->rightson->son; - (*n)->rightson = NULL; - (*n)->leftson = NULL; - (*n)->son->son = NULL; - push_multiplications_down( &((*n)->son) ); - break; - } - if ( (*n)->rightson->connective == MU ) { - (*n)->leftson->value *= (*n)->rightson->leftson->value; - tmp1 = (*n)->rightson->rightson; - (*n)->rightson->rightson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = tmp1; - push_multiplications_down( n ); - break; - } - - /* rigthson is either AD or SU - */ - tmp1 = new_ExpNode( NUMBER ); - tmp2 = new_ExpNode( NUMBER ); - tmp1->value = (*n)->leftson->value; - tmp2->value = (*n)->leftson->value; - - (*n)->connective = (*n)->rightson->connective; - (*n)->leftson->connective = MU; - (*n)->rightson->connective = MU; - (*n)->leftson->leftson = tmp1; - (*n)->leftson->rightson = (*n)->rightson->leftson; - (*n)->rightson->leftson = tmp2; - - push_multiplications_down( &((*n)->leftson) ); - push_multiplications_down( &((*n)->rightson) ); - break; - case AD: - case SU: - push_multiplications_down( &((*n)->leftson) ); - push_multiplications_down( &((*n)->rightson) ); - break; - case MINUS: - push_multiplications_down( &((*n)->son) ); - break; - case NUMBER: - case FHEAD: - break; - default: - printf("\n\ntranslate divisions: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - -} - - - -void put_comp_into_normalized_locals( Comparator comp, - ExpNode *lh, - ExpNode *rh ) - -{ - - ExpNode *tmp; - - tmp = new_ExpNode( SU ); - - /* initialisation of normalized locals - */ - lnum_F = 0; - lc = 0; - - lcomp = comp; - - /* if comparison is LE or LEQ, then subtract - * left hand side from right hand side to obtain - * new left hand side. - */ - if ( lcomp == LE ) { - tmp->leftson = rh; - tmp->rightson = lh; - collect_normalized_locals( tmp, TRUE ); - lcomp = GE; - /* "subtract" the constant to get it to the right hand - * side. - */ - lc *= (-1); - free( tmp ); - return; - } - if ( lcomp == LEQ ) { - tmp->leftson = rh; - tmp->rightson = lh; - collect_normalized_locals( tmp, TRUE ); - lcomp = GEQ; - lc *= (-1); - free( tmp ); - return; - } - - /* otherwise, subtract right hand side from left hand side. - */ - tmp->leftson = lh; - tmp->rightson = rh; - collect_normalized_locals( tmp, TRUE ); - lc *= (-1); - free( tmp ); - -} - - - -void collect_normalized_locals( ExpNode *n, Bool positive ) - -{ - - Bool negative = positive ? FALSE : TRUE; - int i; - - if ( !n ) return; - - switch ( n->connective ) { - case AD: - collect_normalized_locals( n->leftson, positive ); - collect_normalized_locals( n->rightson, positive ); - break; - case SU: - collect_normalized_locals( n->leftson, positive ); - collect_normalized_locals( n->rightson, negative ); - break; - case MINUS: - collect_normalized_locals( n->son, negative ); - break; - case NUMBER: - if ( positive ) { - lc += n->value; - } else { - lc -= n->value; - } - break; - case FHEAD: - if ( n->fl < 0 && n->fl != -2 ) { - printf("\n\ncollecting non-relevant fluent for LNF!!\n\n"); - exit( 1 ); - } - for ( i = 0; i < lnum_F; i++ ) { - if ( lF[i] == n->fl ) break; - } - if ( i < lnum_F ) { - lC[i] += positive ? n->c : ((-1) * n->c); - } else { - if ( lnum_F == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - lF[lnum_F] = n->fl; - lC[lnum_F] = positive ? n->c : ((-1) * n->c); - lnum_F++; - } - break; - default: - printf("\n\ncollect_normalized_locals: wrong specifier %d", - n->connective); - exit( 1 ); - } - -} - - - - - - - - - - - - - - - - - - - - - -/******************************************************* - * SUBPART II: TRANSLATE THE SUBTRACTIONS - *******************************************************/ - - - - - - - - - - - - - - - -/* local globals. - */ - -int lminus_fluent[MAX_RELEVANT_FLUENTS]; - - - - - - - - - - - - -void translate_subtractions( void ) - -{ - - int i, fl; - - /* minus_fluent[fl] gives the number of the fluent that - * takes on the negative value to fl, or -1 if there is - * no such fluent. - */ - for ( i = 0; i < MAX_RELEVANT_FLUENTS; i++ ) { - lminus_fluent[i] = -1; - } - - while ( TRUE ) { - /* ex fl \in nF for pre, cond, eff or goal? - */ - if ( !ex_fl_in_nF_of_pre_cond_eff_goal( &fl ) ) { - /* no --> we are finished. - */ - break; - } - if ( fl < 0 ) { - if ( fl != -2 ) { - printf("\n\nnon-relevant fluent in non-illegal part!\n\n"); - exit( 1 ); - } else { - printf("\n\nwarning: total-time occurs negatively in metric. no optimization done.\n\n"); - glnf_metric.num_pF = 0; - glnf_metric.num_nF = 0; - continue; - } - } - /* set the new number and name, incrementing - * gnum_relevant_fluents, and setting - * minus_fluent value for both directions. - */ - introduce_minus_fluent( fl ); - /* replace all occurences in effects and conds and goals - */ - replace_fl_in_nF_with_minus_fl( fl ); - /* set the initial value of the new fluent - */ - set_minus_fl_initial( fl ); - /* adjust the effects accordingly - */ - introduce_minus_fl_effects( fl ); - } - -} - - - -Bool ex_fl_in_nF_of_pre_cond_eff_goal( int *fl ) - -{ - - Action *a; - ActionEffect *e; - int i, j; - - for ( i = 0; i < gnum_lnf_goal; i++ ) { - if ( glnf_goal_lh[i]->num_nF > 0 ) { - *fl = glnf_goal_lh[i]->nF[0]; - return TRUE; - } - } - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_lnf_preconds; i++ ) { - if ( a->lnf_preconds_lh[i]->num_nF > 0 ) { - *fl = a->lnf_preconds_lh[i]->nF[0]; - return TRUE; - } - } - - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - - for ( j = 0; j < e->num_lnf_conditions; j++ ) { - if ( e->lnf_conditions_lh[j]->num_nF > 0 ) { - *fl = e->lnf_conditions_lh[j]->nF[0]; - return TRUE; - } - } - - if ( e->illegal ) { - /* we don't care if there's something in here that - * wants to be translated. - */ - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_rh[j]->num_nF > 0 ) { - *fl = e->lnf_effects_rh[j]->nF[0]; - return TRUE; - } - } - } - } - - /* no need to throw costs away, even if we're not explicitly asked to - * minimize them - */ - if ( (1 || gcost_minimizing) && glnf_metric.num_nF > 0 ) { - *fl = glnf_metric.nF[0]; - return TRUE; - } - - return FALSE; - -} - - - -void introduce_minus_fluent( int fl ) - -{ - - if ( gnum_relevant_fluents == MAX_RELEVANT_FLUENTS ) { - printf("\ntoo many relevant fluents! increase MAX_RELEVANT_FLUENTS (currently %d)\n\n", - MAX_RELEVANT_FLUENTS); - exit( 1 ); - } - grelevant_fluents[gnum_relevant_fluents].function = -1; - grelevant_fluents_name[gnum_relevant_fluents] = - ( char * ) calloc( MAX_LENGTH, sizeof( char ) ); - strcpy( grelevant_fluents_name[gnum_relevant_fluents], "MINUS-" ); - strcat( grelevant_fluents_name[gnum_relevant_fluents], - grelevant_fluents_name[fl] ); - lminus_fluent[fl] = gnum_relevant_fluents; - lminus_fluent[gnum_relevant_fluents] = fl; - gnum_relevant_fluents++; - -} - - - -void replace_fl_in_nF_with_minus_fl( int fl ) - -{ - - Action *a; - ActionEffect *e; - int i, j, k, l; - - for ( i = 0; i < gnum_lnf_goal; i++ ) { - for ( j = 0; j < glnf_goal_lh[i]->num_nF; j++ ) { - if ( glnf_goal_lh[i]->nF[j] == fl ) break; - } - if ( j == glnf_goal_lh[i]->num_nF ) continue; - /* now the jth fluent in subtraction is our translated one. - * - * first, put minus-fl into pF. Can't already be there - * because we have only just introduced it. - */ - if ( glnf_goal_lh[i]->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - glnf_goal_lh[i]->pF[glnf_goal_lh[i]->num_pF] = lminus_fluent[fl]; - glnf_goal_lh[i]->pC[glnf_goal_lh[i]->num_pF++] = glnf_goal_lh[i]->nC[j]; - /* now remove fl from nF. - */ - for ( k = j; k < glnf_goal_lh[i]->num_nF - 1; k++ ) { - glnf_goal_lh[i]->nF[k] = glnf_goal_lh[i]->nF[k+1]; - glnf_goal_lh[i]->nC[k] = glnf_goal_lh[i]->nC[k+1]; - } - glnf_goal_lh[i]->num_nF--; - } - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_lnf_preconds; i++ ) { - for ( j = 0; j < a->lnf_preconds_lh[i]->num_nF; j++ ) { - if ( a->lnf_preconds_lh[i]->nF[j] == fl ) break; - } - if ( j == a->lnf_preconds_lh[i]->num_nF ) continue; - if ( a->lnf_preconds_lh[i]->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - a->lnf_preconds_lh[i]->pF[a->lnf_preconds_lh[i]->num_pF] = lminus_fluent[fl]; - a->lnf_preconds_lh[i]->pC[a->lnf_preconds_lh[i]->num_pF++] = a->lnf_preconds_lh[i]->nC[j]; - for ( k = j; k < a->lnf_preconds_lh[i]->num_nF - 1; k++ ) { - a->lnf_preconds_lh[i]->nF[k] = a->lnf_preconds_lh[i]->nF[k+1]; - a->lnf_preconds_lh[i]->nC[k] = a->lnf_preconds_lh[i]->nC[k+1]; - } - a->lnf_preconds_lh[i]->num_nF--; - } - - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - - for ( j = 0; j < e->num_lnf_conditions; j++ ) { - for ( k = 0; k < e->lnf_conditions_lh[j]->num_nF; k++ ) { - if ( e->lnf_conditions_lh[j]->nF[k] == fl ) break; - } - if ( k == e->lnf_conditions_lh[j]->num_nF ) continue; - if ( e->lnf_conditions_lh[j]->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - e->lnf_conditions_lh[j]->pF[e->lnf_conditions_lh[j]->num_pF] = lminus_fluent[fl]; - e->lnf_conditions_lh[j]->pC[e->lnf_conditions_lh[j]->num_pF++] = e->lnf_conditions_lh[j]->nC[k]; - for ( l = k; l < e->lnf_conditions_lh[j]->num_nF - 1; l++ ) { - e->lnf_conditions_lh[j]->nF[l] = e->lnf_conditions_lh[j]->nF[l+1]; - e->lnf_conditions_lh[j]->nC[l] = e->lnf_conditions_lh[j]->nC[l+1]; - } - e->lnf_conditions_lh[j]->num_nF--; - } - - if ( e->illegal ) { - /* like before, we don't care about effects that access - * irrelevant fluents - */ - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - for ( k = 0; k < e->lnf_effects_rh[j]->num_nF; k++ ) { - if ( e->lnf_effects_rh[j]->nF[k] == fl ) break; - } - if ( k == e->lnf_effects_rh[j]->num_nF ) continue; - if ( e->lnf_effects_rh[j]->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - e->lnf_effects_rh[j]->pF[e->lnf_effects_rh[j]->num_pF] = lminus_fluent[fl]; - e->lnf_effects_rh[j]->pC[e->lnf_effects_rh[j]->num_pF++] = e->lnf_effects_rh[j]->nC[k]; - for ( l = k; l < e->lnf_effects_rh[j]->num_nF - 1; l++ ) { - e->lnf_effects_rh[j]->nF[l] = e->lnf_effects_rh[j]->nF[l+1]; - e->lnf_effects_rh[j]->nC[l] = e->lnf_effects_rh[j]->nC[l+1]; - } - e->lnf_effects_rh[j]->num_nF--; - } - } - } - - for ( j = 0; j < glnf_metric.num_nF; j++ ) { - if ( glnf_metric.nF[j] == fl ) break; - } - if ( j < glnf_metric.num_nF ) { - if ( glnf_metric.num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - glnf_metric.pF[glnf_metric.num_pF] = lminus_fluent[fl]; - glnf_metric.pC[glnf_metric.num_pF++] = glnf_metric.nC[j]; - for ( k = j; k < glnf_metric.num_nF - 1; k++ ) { - glnf_metric.nF[k] = glnf_metric.nF[k+1]; - glnf_metric.nC[k] = glnf_metric.nC[k+1]; - } - glnf_metric.num_nF--; - } - -} - - - -void set_minus_fl_initial( int fl ) - -{ - - if ( ginitial_state.f_D[fl] ) { - ginitial_state.f_D[lminus_fluent[fl]] = TRUE; - ginitial_state.f_V[lminus_fluent[fl]] = (-1) * ginitial_state.f_V[fl]; - } - -} - - - -void introduce_minus_fl_effects( int fl ) - -{ - - Action *a; - ActionEffect *e; - int i, j, k, pf, nf; - LnfExpNode *len; - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - if ( e->illegal ) { - /* no need to translate illegal effects. - */ - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_fl[j] != fl ) { - continue; - } - /* here is an effect that affects our fl. - * introduce inverse effect for minus_fl, - * making use of all minus-fl's that are already - * there. - */ - if ( e->num_lnf_effects == MAX_LNF_EFFS ) { - printf("\n\nincrease MAX_LNF_EFFS! currently %d\n\n", MAX_LNF_EFFS); - exit( 1 ); - } - e->lnf_effects_neft[e->num_lnf_effects] = e->lnf_effects_neft[j]; - e->lnf_effects_fl[e->num_lnf_effects] = lminus_fluent[fl]; - e->lnf_effects_rh[e->num_lnf_effects] = new_LnfExpNode(); - len = e->lnf_effects_rh[e->num_lnf_effects]; - /* now the most "difficult" part: setup the inverted pF and nF - * informations. - * - * NOTE: as fluent occurences are unique in original ef, - * so will they be in new ef. (no len contains both - * a fluent and its minus-fluent) - * --> invariant is or should be that the absolute - * fluents occur at most once in |pF| \cup |nF|. - * holds in the beginning. only thing we do is - * we exchange in that set for some fluents the - * positive with the negative version, so the - * invariant is in fact preserved. - */ - for ( k = 0; k < e->lnf_effects_rh[j]->num_pF; k++ ) { - pf = e->lnf_effects_rh[j]->pF[k]; - if ( lminus_fluent[pf] == -1 ) { - /* not translated yet --> insert it into nF - */ - if ( len->num_nF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - len->nF[len->num_nF] = pf; - len->nC[len->num_nF++] = e->lnf_effects_rh[j]->pC[k]; - } else { - /* else, insert minus-pf into pF - */ - if ( len->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - len->pF[len->num_pF] = lminus_fluent[pf]; - len->pC[len->num_pF++] = e->lnf_effects_rh[j]->pC[k]; - } - } - for ( k = 0; k < e->lnf_effects_rh[j]->num_nF; k++ ) { - nf = e->lnf_effects_rh[j]->nF[k]; - /* insert all of those into pF - */ - if ( len->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - len->pF[len->num_pF] = nf; - len->pC[len->num_pF++] = e->lnf_effects_rh[j]->nC[k]; - } - /* the constant must of course be inverted. - */ - len->c = (-1) * e->lnf_effects_rh[j]->c; - e->num_lnf_effects++; - } - } - } - -} - - - - - - - - - - - - - - - - - - -/************************************************************* - * LNF POST-PROCESSING I: SUMMARIZE EFFECTS. - *************************************************************/ - - - - - - - - - - - - - - - - - - - -int *lA, *lD; -int lnum_A, lnum_D; - - - - - - -void summarize_effects( void ) - -{ - - Action *a; - ActionEffect *e, *e_; - int i, j, k, l; - - lA = ( int * ) calloc( gnum_relevant_facts, sizeof( int ) ); - lD = ( int * ) calloc( gnum_relevant_facts, sizeof( int ) ); - - for ( a = gactions; a; a = a->next ) { - i = 0; - while ( i < a->num_effects ) { - e = &(a->effects[i]); - if ( e->removed ) { - /* this one's already handled. - */ - i++; - continue; - } - - /* first, merge the effect's own effects together. logical: - */ - lnum_A = 0; - for ( j = 0; j < e->num_adds; j++ ) { - for ( k = 0; k < lnum_A; k++ ) { - if ( lA[k] == e->adds[j] ) break; - } - if ( k < lnum_A ) continue; - lA[lnum_A++] = e->adds[j]; - } - lnum_D = 0; - for ( j = 0; j < e->num_dels; j++ ) { - for ( k = 0; k < lnum_D; k++ ) { - if ( lD[k] == e->dels[j] ) break; - } - if ( k < lnum_D ) continue; - lD[lnum_D++] = e->dels[j]; - } - /* numerical: - */ - j = 0; - while ( j < e->num_lnf_effects ) { - /* merge all effects increasing the same fluent into - * effect j, and remove them. - */ - k = j + 1; - while ( k < e->num_lnf_effects ) { - if ( e->lnf_effects_fl[k] != e->lnf_effects_fl[j] ) { - k++; - continue; - } - if ( e->lnf_effects_neft[j] == ASSIGN ) { - if ( e->lnf_effects_neft[k] != ASSIGN || - !same_lnfs( e->lnf_effects_rh[j], e->lnf_effects_rh[k] ) ) { - e->illegal = TRUE; - break; - } - } else { - if ( e->lnf_effects_neft[k] == ASSIGN ) { - e->illegal = TRUE; - break; - } - merge_lnfs( e->lnf_effects_rh[j], e->lnf_effects_rh[k] ); - } - /* we also get here if we have two identical assigns. - */ - free( e->lnf_effects_rh[k] ); - for ( l = k; l < e->num_lnf_effects - 1; l++ ) { - e->lnf_effects_neft[l] = e->lnf_effects_neft[l+1]; - e->lnf_effects_fl[l] = e->lnf_effects_fl[l+1]; - e->lnf_effects_rh[l] = e->lnf_effects_rh[l+1]; - } - e->num_lnf_effects--; - } - if ( k < e->num_lnf_effects ) { - /* illegal combination - */ - break; - } - j++; - } - - /* now merge all effects after i with same condition - * into that. - */ - j = i + 1; - while ( j < a->num_effects ) { - e_ = &(a->effects[j]); - if ( e_->removed ) { - j++; - continue; - } - - if ( !same_condition( e, e_ ) ) { - j++; - continue; - } - /* no matter what happens, we can get rid of effect e_ - */ - e_->removed = TRUE; - - /* illegality is inherited in both directions. - */ - if ( e_->illegal ) { - e->illegal = TRUE; - } - if ( e->illegal ) { - /* just for docu; it is removed anyway. - */ - e_->illegal = TRUE; - } - - if ( !e->illegal ) { - /* the combined effect appears to be legal. merge it. - */ - merge_effects( e, e_ ); - if ( e->illegal ) { - /* e might have become illegal. again, docu this. - */ - e_->illegal = TRUE; - } - } - - j++; - } - - /* now put the updated A and D info into e. - * - * have to be careful: it might be that there are - * now too many facts and we need to re-allocate - * e's capabilities. - */ - if ( lnum_A > e->num_adds ) { - free( e->adds ); - e->adds = ( int * ) calloc( lnum_A, sizeof( int ) ); - } - for ( j = 0; j < lnum_A; j++ ) { - e->adds[j] = lA[j]; - } - e->num_adds = lnum_A; - if ( lnum_D > e->num_dels ) { - free( e->dels ); - e->dels = ( int * ) calloc( lnum_D, sizeof( int ) ); - } - for ( j = 0; j < lnum_D; j++ ) { - e->dels[j] = lD[j]; - } - e->num_dels = lnum_D; - - /* increment current effects counter. - */ - i++; - } - } - -} - - - -Bool same_condition( ActionEffect *e, ActionEffect *e_ ) - -{ - - int i, j; - - if ( e->num_conditions != e_->num_conditions || - e->num_lnf_conditions != e_->num_lnf_conditions ) return FALSE; - - for ( i = 0; i < e->num_conditions; i++ ) { - for ( j = 0; j < e_->num_conditions; j++ ) { - if ( e->conditions[i] == e_->conditions[j] ) break; - } - if ( j == e_->num_conditions ) break; - } - if ( i < e->num_conditions ) return FALSE; - - for ( i = 0; i < e->num_lnf_conditions; i++ ) { - for ( j = 0; j < e_->num_lnf_conditions; j++ ) { - if ( e_->lnf_conditions_comp[j] != e->lnf_conditions_comp[i] ) continue; - if ( e_->lnf_conditions_rh[j] != e->lnf_conditions_rh[i] ) continue; - if ( !same_lnfs( e_->lnf_conditions_lh[j], e->lnf_conditions_lh[i] ) ) continue; - break; - } - if ( j == e_->num_lnf_conditions ) break; - } - if ( i < e->num_lnf_conditions ) return FALSE; - - return TRUE; - -} - - - -Bool same_lnfs( LnfExpNode *l, LnfExpNode *r ) - -{ - - int i, j; - - if ( l->num_pF != r->num_pF || - l->c != r->c ) return FALSE; - - for ( i = 0; i < l->num_pF; i++ ) { - for ( j = 0; j < r->num_pF; j++ ) { - if ( l->pF[i] != r->pF[j] ) continue; - if ( l->pC[i] != r->pC[j] ) { - /* same fluent with different weighting. - */ - return FALSE; - } - break; - } - if ( j == r->num_pF ) break; - } - if ( i < l->num_pF ) return FALSE; - - return TRUE; - -} - - - -void merge_effects( ActionEffect *e, ActionEffect *e_ ) - -{ - - int i, j; - - /* we don't care whether adds and dels intersect: - * they're allowed to by semantics. - */ - for ( i = 0; i < e_->num_adds; i++ ) { - for ( j = 0; j < lnum_A; j++ ) { - if ( lA[j] == e_->adds[i] ) break; - } - if ( j < lnum_A ) continue; - lA[lnum_A++] = e_->adds[i]; - } - for ( i = 0; i < e_->num_dels; i++ ) { - for ( j = 0; j < lnum_D; j++ ) { - if ( lD[j] == e_->dels[i] ) break; - } - if ( j < lnum_D ) continue; - lD[lnum_D++] = e_->dels[i]; - } - - for ( i = 0; i < e_->num_lnf_effects; i++ ) { - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_fl[j] == e_->lnf_effects_fl[i] ) break; - } - if ( j == e->num_lnf_effects ) { - /* new affected fluent! - */ - if ( e->num_lnf_effects == MAX_LNF_EFFS ) { - printf("\n\nincrease MAX_LNF_EFFS! currently %d\n\n", MAX_LNF_EFFS); - exit( 1 ); - } - e->lnf_effects_neft[e->num_lnf_effects] = e_->lnf_effects_neft[i]; - e->lnf_effects_fl[e->num_lnf_effects] = e_->lnf_effects_fl[i]; - /* we can also simply take the pointer: e_ is only marked as removed, - * but not freed. - */ - e->lnf_effects_rh[e->num_lnf_effects] = e_->lnf_effects_rh[i]; - e->num_lnf_effects++; - } else { - if ( e->lnf_effects_neft[j] == ASSIGN ) { - if ( e_->lnf_effects_neft[i] != ASSIGN || - !same_lnfs( e->lnf_effects_rh[j], e_->lnf_effects_rh[i] ) ) { - e->illegal = TRUE; - return; - } - /* identical assigns. nothing needs to be done. - */ - } else { - if ( e_->lnf_effects_neft[i] == ASSIGN ) { - e->illegal = TRUE; - return; - } - merge_lnfs( e->lnf_effects_rh[j], e_->lnf_effects_rh[i] ); - } - } - } - -} - - - -/* merge both LNFs into the left one. - * (only pF needed as both are already - * fully transformed) - */ -void merge_lnfs( LnfExpNode *l, LnfExpNode *r ) - -{ - - int i, j, k; - - for ( i = 0; i < r->num_pF; i++ ) { - - for ( j = 0; j < l->num_pF; j++ ) { - if ( r->pF[i] == l->pF[j] ) break; - } - if ( j < l->num_pF ) { - /* got that one in dest LNF already - */ - l->pC[j] += r->pC[i]; - continue; - } - - if ( lminus_fluent[r->pF[i]] != -1 ) { - /* this one was already translated. let's see - * if its counterpart is in the left lnf. - */ - for ( j = 0; j < l->num_pF; j++ ) { - if ( lminus_fluent[r->pF[i]] == l->pF[j] ) break; - } - if ( j < l->num_pF ) { - /* for this, we got the inverse one! - */ - l->pC[j] -= r->pC[i]; - if ( l->pC[j] < 0 ) { - l->pF[j] = r->pF[i]; - l->pC[j] *= (-1); - } - if ( l->pC[j] == 0 ) { - /* remove this entirely. - */ - for ( k = j; k < l->num_pF - 1; k++ ) { - l->pF[k] = l->pF[k+1]; - l->pC[k] = l->pC[k+1]; - } - l->num_pF--; - } - continue; - } - } - - /* we got neither that nor its counterpart. - */ - if ( l->num_pF == MAX_LNF_F ) { - printf("\n\nincrease MAX_LNF_F! currently %d\n\n", MAX_LNF_F); - exit( 1 ); - } - l->pF[l->num_pF] = r->pF[i]; - l->pC[l->num_pF++] = r->pC[i]; - } - - - l->c += r->c; - -} - - - - - - - - - - - - - - - - - - - - - - -/************************************************************* - * LNF POST-PROCESSING II: ENCODE NON-MINIMAL LNFs. - *************************************************************/ - - - - - - - - - - - - - - - - - - - - - - - -void encode_lfns_as_artificial_fluents( void ) - -{ - - int i; - - /* for the artificial new ones, this will be set - * to the respective LNF. - */ - for ( i = 0; i < MAX_RELEVANT_FLUENTS; i++ ) { - grelevant_fluents_lnf[i] = NULL; - } - - while ( TRUE ) { - /* ex non-minimal lnf in pre, cond, eff, or goal? - * - * (i.e., lnf != fl + c) - */ - if ( !ex_non_minimal_lnf_in_pre_cond_goal_eff() ) { - /* no --> we are finished. - */ - break; - } - /* otherwise, the respective LNF, without the - * constant part, is set up in - * lF...; (local global borrowed from above); - * - * introduce a new artificial fluent for that - * LNF - */ - introduce_artificial_fluent(); - /* replace all occurences in pres, conds, effs, and goals - */ - replace_non_minimal_lnf_with_artificial_fl(); - } - -} - - - -Bool ex_non_minimal_lnf_in_pre_cond_goal_eff( void ) - -{ - - Action *a; - ActionEffect *e; - int i, j, k; - - for ( i = 0; i < gnum_lnf_goal; i++ ) { - if ( glnf_goal_lh[i]->num_pF > 1 || - (glnf_goal_lh[i]->num_pF == 1 && glnf_goal_lh[i]->pC[0] != 1) ) { - for ( j = 0; j < glnf_goal_lh[i]->num_pF; j++ ) { - lF[j] = glnf_goal_lh[i]->pF[j]; - lC[j] = glnf_goal_lh[i]->pC[j]; - } - lnum_F = glnf_goal_lh[i]->num_pF; - return TRUE; - } - } - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_lnf_preconds; i++ ) { - if ( a->lnf_preconds_lh[i]->num_pF > 1 || - (a->lnf_preconds_lh[i]->num_pF == 1 && a->lnf_preconds_lh[i]->pC[0] != 1) ) { - for ( j = 0; j < a->lnf_preconds_lh[i]->num_pF; j++ ) { - lF[j] = a->lnf_preconds_lh[i]->pF[j]; - lC[j] = a->lnf_preconds_lh[i]->pC[j]; - } - lnum_F = a->lnf_preconds_lh[i]->num_pF; - return TRUE; - } - } - - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - if ( e->removed ) { - /* these will not be included into conn: - * merged into somewhere else. - */ - continue; - } - - for ( j = 0; j < e->num_lnf_conditions; j++ ) { - if ( e->lnf_conditions_lh[j]->num_pF > 1 || - (e->lnf_conditions_lh[j]->num_pF == 1 && e->lnf_conditions_lh[j]->pC[0] != 1) ) { - for ( k = 0; k < e->lnf_conditions_lh[j]->num_pF; k++ ) { - lF[k] = e->lnf_conditions_lh[j]->pF[k]; - lC[k] = e->lnf_conditions_lh[j]->pC[k]; - } - lnum_F = e->lnf_conditions_lh[j]->num_pF; - return TRUE; - } - } - - if ( e->illegal ) { - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_rh[j]->num_pF > 1 || - (e->lnf_effects_rh[j]->num_pF == 1 && e->lnf_effects_rh[j]->pC[0] != 1) ) { - for ( k = 0; k < e->lnf_effects_rh[j]->num_pF; k++ ) { - lF[k] = e->lnf_effects_rh[j]->pF[k]; - lC[k] = e->lnf_effects_rh[j]->pC[k]; - } - lnum_F = e->lnf_effects_rh[j]->num_pF; - return TRUE; - } - } - } - } - - return FALSE; - -} - - - -void introduce_artificial_fluent( void ) - -{ - - int i; - - if ( gnum_relevant_fluents == MAX_RELEVANT_FLUENTS ) { - printf("\ntoo many relevant fluents! increase MAX_RELEVANT_FLUENTS (currently %d)\n\n", - MAX_RELEVANT_FLUENTS); - exit( 1 ); - } - grelevant_fluents[gnum_relevant_fluents].function = -1; - - /* no name --> is inferred in this case from _lnf - */ - - grelevant_fluents_lnf[gnum_relevant_fluents] = new_LnfExpNode(); - for ( i = 0; i < lnum_F; i++ ) { - grelevant_fluents_lnf[gnum_relevant_fluents]->pF[i] = lF[i]; - grelevant_fluents_lnf[gnum_relevant_fluents]->pC[i] = lC[i]; - } - grelevant_fluents_lnf[gnum_relevant_fluents]->num_pF = lnum_F; - - gnum_relevant_fluents++; - -} - - - -void replace_non_minimal_lnf_with_artificial_fl( void ) - -{ - - Action *a; - ActionEffect *e; - int i, j; - - for ( i = 0; i < gnum_lnf_goal; i++ ) { - if ( !is_artificial_fluent( glnf_goal_lh[i] ) ) { - continue; - } - /* the pF here is the pF we are currently replacing. - */ - glnf_goal_lh[i]->pF[0] = gnum_relevant_fluents - 1; - glnf_goal_lh[i]->pC[0] = 1; - glnf_goal_lh[i]->num_pF = 1; - } - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_lnf_preconds; i++ ) { - if ( !is_artificial_fluent( a->lnf_preconds_lh[i] ) ) { - continue; - } - a->lnf_preconds_lh[i]->pF[0] = gnum_relevant_fluents - 1; - a->lnf_preconds_lh[i]->pC[0] = 1; - a->lnf_preconds_lh[i]->num_pF = 1; - } - - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - if ( e->removed ) { - /* these will not be included into conn: - * merged into somewhere else. - */ - continue; - } - - for ( j = 0; j < e->num_lnf_conditions; j++ ) { - if ( !is_artificial_fluent( e->lnf_conditions_lh[j] ) ) { - continue; - } - e->lnf_conditions_lh[j]->pF[0] = gnum_relevant_fluents - 1; - e->lnf_conditions_lh[j]->pC[0] = 1; - e->lnf_conditions_lh[j]->num_pF = 1; - } - - if ( e->illegal ) { - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( !is_artificial_fluent( e->lnf_effects_rh[j] ) ) { - continue; - } - e->lnf_effects_rh[j]->pF[0] = gnum_relevant_fluents - 1; - e->lnf_effects_rh[j]->pC[0] = 1; - e->lnf_effects_rh[j]->num_pF = 1; - } - } - } - -} - - - -Bool is_artificial_fluent( LnfExpNode *n ) - -{ - - int i, j; - - if ( n->num_nF != 0 ) { - printf("\n\nchecking non-empty nF for multiple fl!\n\n"); - exit( 1 ); - } - - if ( n->num_pF != lnum_F ) { - return FALSE; - } - - for ( i = 0; i < lnum_F; i++ ) { - for ( j = 0; j < n->num_pF; j++ ) { - if ( n->pF[j] != lF[i] ) continue; - if ( n->pC[j] != lC[i] ) { - /* wrong constant multiplier! - */ - return FALSE; - } - break; - } - if ( j == n->num_pF ) { - /* didn't find this fluent i in here. - */ - return FALSE; - } - } - - return TRUE; - -} - - - - - - - - - - - - - - - - - - -/************************************************************* - * AT LAST: PREPARATIONS FOR METRIC FUNCTION - *************************************************************/ - - - - - - - - - - - - - - - - - - -Bool setup_effect_costs( void ) - -{ - - Action *a; - ActionEffect *e; - int i, j, k, fl; - Bool non_zero = FALSE; - - if ( glnf_metric.num_pF == 0 ) { - /* no metric, or previously failed - */ - if ( gcmd_line.display_info ) { - printf("\nno metric specified."); - } - return FALSE; - } - - /* also in here: check if all parts of metric are defined - * if not, then they won't ever be because we do not allow - * assigners anyway. - * - * also, setup gtt total-time multipl. - * currently needed since in h fn effect cists are summed up - * --> may count the same action more than once, if we insert the - * timing cost into the effect cost. - * - * ... this is AWKWARD... probably would be better to simply - * associate costs always (including relaxed plans) - * only with ACTIONS! - */ - gtt = 0; - for ( i = 0; i < glnf_metric.num_pF; i++ ) { - if ( glnf_metric.pF[i] == -2 ) { - gtt = glnf_metric.pC[i]; - continue; - } - if ( !ginitial_state.f_D[glnf_metric.pF[i]] ) break; - } - if ( i < glnf_metric.num_pF ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: metric undefined initially. no optimization done."); - } - return FALSE; - } - - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - e->cost = 0; - - if ( e->removed || - e->illegal ) { - continue; - } - - for ( j = 0; j < e->num_lnf_effects; j++ ) { - fl = e->lnf_effects_fl[j]; - for ( k = 0; k < glnf_metric.num_pF; k++ ) { - if ( fl == glnf_metric.pF[k] ) break; - } - if ( k == glnf_metric.num_pF ) continue; - - if ( e->lnf_effects_rh[j]->num_pF > 0 ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: non-constant effect on metric. no optimization done."); - } - return FALSE; - } - if ( e->lnf_effects_neft[j] != INCREASE ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: assign on metric. no optimization done."); - } - return FALSE; - } - if ( e->lnf_effects_rh[j]->c < 0 ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: change on metric in wrong direction. no optimization done."); - } - return FALSE; - } - - e->cost += glnf_metric.pC[k] * e->lnf_effects_rh[j]->c; - if ( e->cost > 0 ) { - non_zero = TRUE; - } - } - } - } - - if ( !non_zero ) { - if ( gtt == 0 ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: trivial metric, all costs 0. no optimization done."); - } - return FALSE; - } - } - - return TRUE; - -} - - - - - - - - - - - - - - - - - - - - - -/************************************************************* - * AT VERY LAST: ACYCLIC := EFFS, AND STATIC FL RELEVANCE - *************************************************************/ - - - - - - - - - - - - - - - - - - - - - - - -void check_assigncycles( void ) - -{ - - int i, j, k, c = 0; - - gassign_influence = ( Bool ** ) calloc( gnum_real_fl_conn, sizeof( Bool* ) ); - gTassign_influence = ( Bool ** ) calloc( gnum_real_fl_conn, sizeof( Bool* ) ); - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - gassign_influence[i] = ( Bool * ) calloc( gnum_real_fl_conn, sizeof( Bool ) ); - gTassign_influence[i] = ( Bool * ) calloc( gnum_real_fl_conn, sizeof( Bool ) ); - } - - if ( gcmd_line.display_info > 1 ) { - printf("\n\nchecking for cyclic := effects"); - } - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - gassign_influence[i][j] = i_influences_j( i, j ); - gTassign_influence[i][j] = i_influences_j( i, j ); - } - } - /* compute transitive closure on dependencies - */ - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - if ( gTassign_influence[i][j] ) { - for ( k = 0; k < gnum_real_fl_conn; k++ ) { - if ( gTassign_influence[j][k] ) { - gTassign_influence[i][k] = TRUE; - } - } - } - } - } - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - if ( gTassign_influence[i][i] ) { - printf("\nnumerical variable "); - print_fl_name( i ); - printf(" lies on := propagation cycle!"); - c++; - } - } - if ( c > 0 ) { - printf("\nexit. (mneed computation not possible, RPG termination unclear)"); - printf("\n (questions to Joerg Hoffmann)\n\n"); - exit( 1 ); - } else { - if ( gcmd_line.display_info > 1 ) { - printf(" --- OK."); - } - } - -} - - - -Bool i_influences_j( int fi, int fj ) - -{ - - int i, j, fl_; - - for ( i = 0; i < gfl_conn[fj].num_AS; i++ ) { - fl_ = gfl_conn[fj].AS_fl_[i]; - if ( fl_ < 0 ) continue; - if ( fl_ == fi ) return TRUE; - if ( !gfl_conn[fl_].artificial ) continue; - for ( j = 0; j < gfl_conn[fl_].num_lnf; j++ ) { - if ( gfl_conn[fl_].lnf_F[j] == fi ) return TRUE; - } - } - - return FALSE; - -} - - - -void determine_fl_relevance( void ) - -{ - - int i, j, k, fl, fl_, ef, pc, g; - Bool **influenced_by; - - /* this here contains transfers from i to j i.e. if - * i is relevant then j is too - */ - influenced_by = ( Bool ** ) calloc( gnum_real_fl_conn, sizeof( Bool* ) ); - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - influenced_by[i] = ( Bool * ) calloc( gnum_real_fl_conn, sizeof( Bool ) ); - } - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - influenced_by[i][j] = ( gassign_influence[j][i] || - i_inc_influences_j( j, i ) ); - } - } - /* transitive closure so we'll have direct access below. - */ - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - if ( influenced_by[i][j] ) { - for ( k = 0; k < gnum_real_fl_conn; k++ ) { - if ( influenced_by[j][k] ) { - influenced_by[i][k] = TRUE; - } - } - } - } - } - - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - gfl_conn[i].relevant = FALSE; - } - /* relevance originates in effect preconds and goals. - */ - for ( ef = 0; ef < gnum_ef_conn; ef++ ) { - for ( pc = 0; pc < gef_conn[ef].num_f_PC; pc++ ) { - /* constraint here is gef_conn[ef].f_PC_fl[pc] >= [>] gef_conn[ef].f_PC_c[pc] - * where lh side can be lnf expression. - */ - fl = gef_conn[ef].f_PC_fl[pc]; - if ( fl < 0 ) { - printf("\nnegative constr lh??\n\n"); - exit( 1 ); - } - if ( !gfl_conn[fl].artificial ) { - gfl_conn[fl].relevant = TRUE; - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - if ( influenced_by[fl][i] ) gfl_conn[i].relevant = TRUE; - } - } else { - for ( i = 0; i < gfl_conn[fl].num_lnf; i++ ) { - fl_ = gfl_conn[fl].lnf_F[i]; - gfl_conn[fl_].relevant = TRUE; - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - if ( influenced_by[fl_][j] ) gfl_conn[j].relevant = TRUE; - } - } - } - } - } - for ( g = 0; g < gnum_fnumeric_goal; g++ ) { - /* constraint here is gfnumeric_goal_fl[g] >= [>] gfnumeric_goal_c[g] - * where lh side can be lnf expression. - */ - fl = gfnumeric_goal_fl[g]; - if ( fl < 0 ) { - printf("\nnegative constr lh??\n\n"); - exit( 1 ); - } - if ( !gfl_conn[fl].artificial ) { - gfl_conn[fl].relevant = TRUE; - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - if ( influenced_by[fl][i] ) gfl_conn[i].relevant = TRUE; - } - } else { - for ( i = 0; i < gfl_conn[fl].num_lnf; i++ ) { - fl_ = gfl_conn[fl].lnf_F[i]; - gfl_conn[fl_].relevant = TRUE; - for ( j = 0; j < gnum_real_fl_conn; j++ ) { - if ( influenced_by[fl_][j] ) gfl_conn[j].relevant = TRUE; - } - } - } - } - - if ( 0 ) { - for ( i = 0; i < gnum_real_fl_conn; i++ ) { - printf("\n"); print_fl_name( i ); - printf (" --- relevant: %d", gfl_conn[i].relevant); - } - } - -} - - - -Bool i_inc_influences_j( int fi, int fj ) - -{ - - int i, j, fl_; - - for ( i = 0; i < gfl_conn[fj].num_IN; i++ ) { - fl_ = gfl_conn[fj].IN_fl_[i]; - if ( fl_ < 0 ) continue; - if ( fl_ == fi ) return TRUE; - if ( !gfl_conn[fl_].artificial ) continue; - for ( j = 0; j < gfl_conn[fl_].num_lnf; j++ ) { - if ( gfl_conn[fl_].lnf_F[j] == fi ) return TRUE; - } - } - - return FALSE; - -} - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.h deleted file mode 100644 index 3546f2ac..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/expressions.h +++ /dev/null @@ -1,106 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - - -/********************************************************************* - * File: expressions.h - * Description: headers for handling numerical expressions - * - * Author: Joerg Hoffmann 2001 - * - *********************************************************************/ - - - - - - - - - - - - - - -#ifndef _EXPRESSIONS_H -#define _EXPRESSIONS_H - - - - -Bool number_comparison_holds( Comparator c, float l, float r ); - - - -Bool transform_to_LNF( void ); -Bool is_linear_task( void ); -Bool is_linear_expression( ExpNode *n ); -void print_lnf_representation( void ); - - - -void normalize_expressions( void ); -Bool translate_divisions( ExpNode **n ); -void push_multiplications_down( ExpNode **n ); -void put_comp_into_normalized_locals( Comparator comp, - ExpNode *lh, - ExpNode *rh ); -void collect_normalized_locals( ExpNode *n, Bool positive ); - - - -void translate_subtractions( void ); -Bool ex_fl_in_nF_of_pre_cond_eff_goal( int *fl ); -void introduce_minus_fluent( int fl ); -void replace_fl_in_nF_with_minus_fl( int fl ); -void set_minus_fl_initial( int fl ); -void introduce_minus_fl_effects( int fl ); - - - -void summarize_effects( void ); -Bool same_condition( ActionEffect *e, ActionEffect *e_ ); -Bool same_lnfs( LnfExpNode *l, LnfExpNode *r ); -void merge_effects( ActionEffect *e, ActionEffect *e_ ); -void merge_lnfs( LnfExpNode *l, LnfExpNode *r ); - - - -void encode_lfns_as_artificial_fluents( void ); -Bool ex_non_minimal_lnf_in_pre_cond_goal_eff( void ); -void introduce_artificial_fluent( void ); -void replace_non_minimal_lnf_with_artificial_fl( void ); -Bool is_artificial_fluent( LnfExpNode *n ); - - - -Bool setup_effect_costs( void ); - - - -void check_assigncycles( void ); -Bool i_influences_j( int fi, int fj ); -void determine_fl_relevance( void ); -Bool i_inc_influences_j( int fi, int fj ); - - - -#endif /* _EXPRESSIONS_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/ff.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/ff.h deleted file mode 100644 index d244df7a..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/ff.h +++ /dev/null @@ -1,2044 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - -/********************************************************************* - * File: ff.h - * Description: Types and structures for the Metric-FastForward planner. - * Enhanced version with derived predicates and A*-epsilon - * - * --------- PDDL2.1 level 2 :: VERSION v 1.0 -------------- - * - * Author: Joerg Hoffmann 2012 - * Contact: hoffmann@cs.uni-saarland.de - * - *********************************************************************/ - - - - - - - - -#ifndef __FF_H -#define __FF_H - - - - - - -#include -#include -#include -#include -#include -#include -#include - - - - - - - - - -/* - * ------------------------------------ DEFINES ---------------------------- - */ - - - - - - - - - - - -/*********************** - * MEANINGLESS HELPERS * - ***********************/ - - - - -/* strcmp returns 0 if two strings are equal, which is not nice */ -#define SAME 0 - - - - - - - - - -/**************** - * PARSING ETC. * - ****************/ - - - - - - - - - -/* various defines used in parsing - */ -#define HIDDEN_STR "#" -#define AXIOM_STR "AXIOM" -#define NAME_STR "name\0" -#define VARIABLE_STR "variable\0" -#define STANDARD_TYPE "OBJECT\0" -#define EITHER_STR "EITHER" - - - - - - - - - -/*************************** - * SOME ARBITRARY SETTINGS * - ***************************/ - - - - - - - -/* maximal string length - */ -#define MAX_LENGTH 256 - - -/* marks border between connected items - */ -#define CONNECTOR "~" - - -/* size of goals_at array in 1P extraction - */ -#define RELAXED_STEPS_DEFAULT 25 - - -/* size of hash table for repeated states checking - * during EHC breadth first search - */ -#define EHC_HASH_SIZE 8192 -#define EHC_HASH_BITS 8191 - - -/* size of hash table for repeated states checking - * in plan construction - */ -#define PLAN_HASH_SIZE 1024 -#define PLAN_HASH_BITS 1023 - - -/* size of hash table for repeated states checking - * during BFS search - */ -#define BFS_HASH_SIZE 65536 -#define BFS_HASH_BITS 65535 - - -/* cut random values of facts off modulo this value, - * to make state sums fit into a single integer - */ -#define BIG_INT 1500000 - - -/* max number of different fluents in one list of LNF - */ -#define MAX_LNF_F 25 - - -/* max number of comps in one cond / precond / goal - */ -#define MAX_LNF_COMPS 100 - - -/* max number of lnf effects in one action effect - */ -#define MAX_LNF_EFFS 50 - - - - - - - -/************************ - * INSTANTIATION LIMITS * - ************************/ - - - - - - - - -#define MAX_CONSTANTS 2000 -#define MAX_PREDICATES 50 -#define MAX_FUNCTIONS 50 -#define MAX_TYPES 50 -#define MAX_ARITY 5 -#define MAX_VARS 15 - - -#define MAX_TYPE 2000 - - -#define MAX_OPERATORS 50000 - - -/* in DNF: AND with OR - sons - collect 'hitting set': - * one son of each OR node. - * - * this here is initial max number of such son s that can be collected - * (grows dynamically, if required) - */ -#define MAX_HITTING_SET_DEFAULT 1000 - - -#define MAX_TYPE_INTERSECTIONS 10 - - -#define MAX_RELEVANT_FACTS 150000 -#define MAX_RELEVANT_FLUENTS 1000 - - - - - - -/****************************************** - * DOMAIN STRUCTURE AND SEARCHING LIMITS * - ******************************************/ - - - - - - -#define MAX_STATE 800 - - -#define MAX_PLAN_LENGTH 500 - - - - - - -/**************** - * CODE DEFINES * - ****************/ - - - - - - - - - -/* not a real 'code' define; used in relax and search to encode - * infinite level number / plan length - */ -#ifndef INFINITY -#define INFINITY -1 -#endif - - - - - - - -/* define boolean types if not allready defined - */ -#ifndef Bool -typedef unsigned char Bool; -#ifndef TRUE /* we assume that FALSE is also not defined */ -#define TRUE 1 -#define FALSE 0 -#endif /* TRUE */ -#endif /* Bool */ - - -/* code a param number into a negative number and vice versa - */ -#define ENCODE_VAR( val ) (val * (-1)) - 1 -#define DECODE_VAR( val ) (val + 1) * (-1) - -#define GET_CONSTANT( val, pointer ) ( val >= 0 ) ? val : pointer->inst_table[DECODE_VAR( val )] - - -/* Check allocated memory - */ -#define CHECK_PTR(p) if (NULL == (p)) { \ - fprintf(stdout, "\n\aNO MEMORY in file %s:%d\n\n", __FILE__, __LINE__); \ - exit(1);} - - -/* add elapsed time from main local time vars to specified val - */ -#define TIME( val ) val += ( float ) ( ( end.tms_utime - start.tms_utime + \ - end.tms_stime - start.tms_stime ) / 100.0 ) - - - - - - - - - - - - -/* - * ------------------------------ DATA STRUCTURES ---------------------------- - */ - - - - - - - - - - - -/******************* - * GENERAL HELPERS * - *******************/ - - - - - - - - -/* all command switches - */ -struct _command_line { - - char path[MAX_LENGTH]; - char ops_file_name[MAX_LENGTH]; - char fct_file_name[MAX_LENGTH]; - int display_info; - int debug; - - int search_config; - Bool cost_rplans; - - int w; - - float cost_bound; - -}; - - -typedef char *Token; - - - - - - - - - - - - -/*********** - * PARSING * - ***********/ - - - - - - - - - - -/* A list of strings - */ -typedef struct _TokenList { - - char *item; - struct _TokenList *next; - -} TokenList; - - - -/* list of string lists - */ -typedef struct _FactList { - - TokenList *item; - struct _FactList *next; - -} FactList; - - - -/* structure to store typed-list-of /, - * as they are declared in PDDL files - */ -typedef struct _TypedList { - - char *name; - - /* each item in this list is the name of a type which - * our type is the union of (EITHER - types ...) - * - * usually, this will default to a single-item TokenList. - */ - TokenList *type; - /* after first sweep, this will contain the number in type table - */ - int n; - - struct _TypedList *next; - -} TypedList; - - - -/* only needed to parse in the predicates and their arg - * definitions - */ -typedef struct _TypedListList { - - char *predicate; - - TypedList *args; - - struct _TypedListList *next; - -} TypedListList; - - - -typedef enum _ExpConnective{FHEAD = 1000, - NUMBER, - MINUS, - AD, - SU, - MU, - DI} ExpConnective; - - - -typedef struct _ParseExpNode { - - ExpConnective connective; - - /* NULL anywhere except when node is FHEAD or NUMBER - * (in which case it is fn name ... resp. number (int or float) as string - */ - TokenList *atom; - - /* both NULL in FHEAD; - * in MINUS, left is son and right is NULL - * else (binary operators), left and right operand - */ - struct _ParseExpNode *leftson, *rightson; - -} ParseExpNode; - - - -/* This type indicates whether a node in the pddl tree stands for - * an atomic expression, a junctor or a quantor. - */ -typedef enum _Connective{TRU = 2000, - FAL, - ATOM, - COMP, - NEF, - NOT, - AND, - OR, - ALL, - EX, - WHEN} Connective; - - - -typedef enum _Comparator{IGUAL = 3000, /* technical if conds are array comp exp, resp float */ - LE, - LEQ, - EQ, - GEQ, - GE} Comparator; - - - - -typedef enum _NumericEffectType{ASSIGN = 4000, - SCALE_UP, - SCALE_DOWN, - INCREASE, - DECREASE} NumericEffectType; - - - - -/* - * This is a node in the tree to parse PDDL files - */ -typedef struct _PlNode { - - /* type of the node - */ - Connective connective; - - /* only for parsing: the var args in quantifiers - */ - TypedList *parse_vars; - - /* AND, OR, NOT, WHEN, - * COMP, NEF => NULL - * ALL, EX => the quantified variable with its type - * ATOM => the atom as predicate->param1->param2->... - */ - TokenList *atom; - /* all except COMP, NEF => NULL - * COMP, NEF => left hand, right hand - */ - Comparator comp; - NumericEffectType neft; - ParseExpNode *lh, *rh; - - /* (a) for AND, OR this is the list of sons(a AND b AND c...), - * (b) for the rest this is the son, e.g. a subtree that is negated - * (c) for WHEN, the first son is the condition and the next son - * is the effect - */ - struct _PlNode *sons; - - /* if you have a list of sons, they are connected by next - */ - struct _PlNode *next; - -} PlNode; - - -/* - * This resembles an uninstantiated PDDL operator - */ -typedef struct _PlOperator { - - char *name; - Bool axiom; - - /* only important for PDDL where :VARS may be added to the param list - * which must be hidden when writing the plan to an output file - */ - int number_of_real_params; - - /* the params, as they are declared in domain file - */ - TypedList *parse_params; - - /* params is a list of variable/type pairs, such that: - * factlist->item = [variable] -> [type] - */ - FactList *params; - PlNode *preconds; - PlNode *effects; - - struct _PlOperator *next; - -} PlOperator; - - - - - - - - - - - - - - - -/***************** - * INSTANTIATION * - *****************/ - - - - - - - - - -/* helpers - */ - -typedef int TypeArray[MAX_TYPE_INTERSECTIONS]; - -typedef int *int_pointer; - - - - -/* first step structures: parsing & preprocessing - */ - -typedef struct _Fact { - - int predicate, args[MAX_ARITY]; - -} Fact; - - - -typedef struct _Fluent { - - int function, args[MAX_ARITY]; - -} Fluent; - - - -typedef struct _FluentValue { - - Fluent fluent; - float value; - -} FluentValue; - - - -typedef struct _Facts { - - Fact *fact; - - struct _Facts *next; - -} Facts; - - - -typedef struct _FluentValues { - - Fluent fluent; - float value; - - struct _FluentValues *next; - -} FluentValues; - - - -typedef struct _ExpNode { - - ExpConnective connective; - - /* in FHEAD nodes, pre-processing - */ - Fluent *fluent; - /* in FHEAD nodes after pre-processes have finished. - * (internal number of relevant fluent, or -1 if not - * relevant) - */ - int fl; - /* helper for LNF: if that fl is multiplied, this is the - * respective constant after pre-normalization. - */ - float c; - - /* in NUMBER nodes - */ - float value; - - /* in MINUS nodes - */ - struct _ExpNode *son; - - /* in all others - */ - struct _ExpNode *leftson, *rightson; - -} ExpNode, *ExpNode_pointer; - - - -typedef struct _WffNode { - - Connective connective; - - /* in ALL/EX s - */ - int var, var_type; - char *var_name; - - /* in AND/OR s - */ - struct _WffNode *sons; - /* sons are doubly connected linear list - */ - struct _WffNode *next; - struct _WffNode *prev; - - /* in ATOMs - */ - Fact *fact; - /* after translation: mark NOT-p s for efficiency - */ - int NOT_p; - - /* in ALL/EX/NOT - */ - struct _WffNode *son; - - /* in COMP - */ - Comparator comp; - ExpNode *lh, *rh; - - /* for expansion speedup - */ - Bool visited; - - /* no WHEN s here... use Pl Connectives anyway for simplicity - */ - -} WffNode, *WffNode_pointer; - - - -typedef struct _Literal { - - Bool negated; - - Fact fact; - - struct _Literal *next; - struct _Literal *prev; - -} Literal; - - - -typedef struct _NumericEffect { - - Fluent fluent; - NumericEffectType neft; - - ExpNode *rh; - - struct _NumericEffect *next; - struct _NumericEffect *prev; - -} NumericEffect; - - - -typedef struct _Effect { - - int num_vars, var_types[MAX_VARS]; - char *var_names[MAX_VARS]; - - WffNode *conditions; - - Literal *effects; - NumericEffect *numeric_effects; - - struct _Effect *next; - struct _Effect *prev; - -} Effect; - - - -typedef struct _Operator { - - char *name, *var_names[MAX_VARS]; - int number_of_real_params; - Bool axiom; - - int num_vars, var_types[MAX_VARS]; - Bool removed[MAX_VARS]; - - WffNode *preconds; - - Effect *effects; - - Bool hard; - -} Operator, *Operator_pointer; - - - - - - -/* second step: structures that keep already normalized - * operators - */ - - - - -typedef struct _NormEffect { - - int num_vars, var_types[MAX_VARS]; - int inst_table[MAX_VARS]; - - Fact *conditions; - int num_conditions; - - Fact *adds; - int num_adds; - Fact *dels; - int num_dels; - - /* numerical parts: not yet normalized any further; seems that - * normalizing requires certain additional structures + - * transformation, and that these will better be done when - * the representation is fully instantiated already. - */ - Comparator *numeric_conditions_comp; - ExpNode_pointer *numeric_conditions_lh, *numeric_conditions_rh; - int num_numeric_conditions; - - NumericEffectType *numeric_effects_neft; - Fluent *numeric_effects_fluent; - ExpNode_pointer *numeric_effects_rh; - int num_numeric_effects; - - struct _NormEffect *prev; - struct _NormEffect *next; - -} NormEffect; - - - -typedef struct _NormOperator { - - Operator *operator; - - int num_vars, var_types[MAX_VARS]; - int inst_table[MAX_VARS]; - int removed_vars[MAX_VARS], num_removed_vars, type_removed_vars[MAX_VARS]; - - Fact *preconds; - int num_preconds; - /* numeric precondition still full scale represented, see above - */ - Comparator *numeric_preconds_comp; - ExpNode_pointer *numeric_preconds_lh, *numeric_preconds_rh; - int num_numeric_preconds; - - NormEffect *effects; - - Bool out; - -} NormOperator, *NormOperator_pointer; - - - -/* minimal info for a fully instantiated easy operator; - * yields one action when expanded - */ -typedef struct _EasyTemplate { - - NormOperator *op; - int inst_table[MAX_VARS]; - - struct _EasyTemplate *prev; - struct _EasyTemplate *next; - -} EasyTemplate; - - - - - - -/* structures for hard ops - */ - - - - - -/* intermediate step: structure for keeping hard ops - * with normalized precondition, but arbitrary - * effect conditions - */ -typedef struct _MixedOperator { - - Operator *operator; - - int inst_table[MAX_VARS]; - - Fact *preconds; - int num_preconds; - /* numeric part, pre-normalized - */ - Comparator *numeric_preconds_comp; - ExpNode_pointer *numeric_preconds_lh, *numeric_preconds_rh; - int num_numeric_preconds; - - Effect *effects; - - struct _MixedOperator *next; - -} MixedOperator; - - - -/* last hard step: everything is action - like, except that - * facts are not yet integer coded - */ - - - -typedef struct _PseudoActionEffect { - - Fact *conditions; - int num_conditions; - - Fact *adds; - int num_adds; - Fact *dels; - int num_dels; - - - /* and the numeric parts again... - */ - Comparator *numeric_conditions_comp; - ExpNode_pointer *numeric_conditions_lh, *numeric_conditions_rh; - int num_numeric_conditions; - - NumericEffectType *numeric_effects_neft; - Fluent *numeric_effects_fluent; - ExpNode_pointer *numeric_effects_rh; - int num_numeric_effects; - - struct _PseudoActionEffect *next; - -} PseudoActionEffect; - - - -typedef struct _PseudoAction { - - Operator *operator; - - int inst_table[MAX_VARS]; - - Fact *preconds; - int num_preconds; - /* numeric part, pre-normalized - */ - Comparator *numeric_preconds_comp; - ExpNode_pointer *numeric_preconds_lh, *numeric_preconds_rh; - int num_numeric_preconds; - - PseudoActionEffect *effects; - int num_effects; - -} PseudoAction, *PseudoAction_pointer; - - - - -/* final domain representation structure - */ - - - -typedef struct _LnfExpNode { - - int pF[MAX_LNF_F]; - float pC[MAX_LNF_F]; - int num_pF; - - int nF[MAX_LNF_F]; - float nC[MAX_LNF_F]; - int num_nF; - - float c; - -} LnfExpNode, *LnfExpNode_pointer; - - - -typedef struct _ActionEffect { - - int *conditions; - int num_conditions; - - int *adds; - int num_adds; - int *dels; - int num_dels; - - /* and the numeric parts again; fluents all as fl ints; - * - * normalization for cond as below for pre; - * norm. for effects by restriction of types (?), - * right hand side float (?) - */ - Comparator *numeric_conditions_comp; - ExpNode_pointer *numeric_conditions_lh, *numeric_conditions_rh; - int num_numeric_conditions; - - NumericEffectType *numeric_effects_neft; - int *numeric_effects_fl; - ExpNode_pointer *numeric_effects_rh; - int num_numeric_effects; - - /* LNF - */ - Comparator *lnf_conditions_comp; - LnfExpNode_pointer *lnf_conditions_lh; - float *lnf_conditions_rh; - int num_lnf_conditions; - - NumericEffectType *lnf_effects_neft; - int *lnf_effects_fl; - LnfExpNode_pointer *lnf_effects_rh; - int num_lnf_effects; - - /* this is true iff the numerical part of the effects affects or accesses - * an undefined fluent (i.e. in numeric_effects_fl or numeric_effects_rh ) - * --- then, if the effect appears, the action is - * illegal. - */ - Bool illegal; - - /* helper - */ - Bool removed; - - float cost; - -} ActionEffect; - - - -typedef struct _Action { - - NormOperator *norm_operator; - PseudoAction *pseudo_action; - Bool axiom; - - char *name; - int num_name_vars; - int name_inst_table[MAX_VARS]; - - int inst_table[MAX_VARS]; - - int *preconds; - int num_preconds; - /* numeric part, in general format, with fluents encoded as fl ints - * - * also, will (?) be transformed to lh fl, rh float; then, expnodes as - * fast accessible as specialised structures. - */ - Comparator *numeric_preconds_comp; - ExpNode_pointer *numeric_preconds_lh, *numeric_preconds_rh; - int num_numeric_preconds; - - /* LNF - */ - Comparator *lnf_preconds_comp; - LnfExpNode_pointer *lnf_preconds_lh; - float *lnf_preconds_rh; - int num_lnf_preconds; - - ActionEffect *effects; - int num_effects; - - struct _Action *next; - -} Action; - - - - - - - - - - - -/***************************************************** - * BASIC OP AND FT STRUCTURES FOR CONNECTIVITY GRAPH * - *****************************************************/ - - - - - - - - - - - -typedef struct _OpConn { - - /* to get name - */ - Action *action; - Bool axiom; - - /* effects - */ - int *E; - int num_E; - - /* member for applicable actions extraction - */ - Bool is_in_A; - Bool is_in_A_axioms; - - /* members for 1Ph - H(S) extraction - */ - int is_used; - Bool is_in_H; - - /* this is a bit imprecise since actually, in this - * framework here, the cost of the action may depend on - * which conditional effects actually apply. - * ... anyway, this makes things much easier for the case - * where there aren't any effect conditions. all cost handling - * is now based on this..!! - */ - float cost; - -} OpConn; - - - -typedef struct _EfConn { - - int op; - - /* true if access to always undefined fluent, or - * conflicting assignments. - * - * if that is the case then nothing except condition is set: - * the effect is completely ignored except that - * it renders the op unapplicable when its condition - * is true. - */ - Bool illegal; - - /* this one means we found in conn that it is useless (empty) - */ - Bool removed; - - /* this is the cost; can be non-zero if a metric was specified - * and established - */ - float cost; - - int *PC; - int num_PC; - /* numeric part - */ - Comparator *f_PC_comp; /* either GEQ or GE */ - int *f_PC_fl; - float *f_PC_c; - int num_f_PC; - /* array indexed by fl number, to fast know whether - * new fluent value is high enough - */ - Comparator *f_PC_direct_comp; - float *f_PC_direct_c; - - /* logic effects - */ - int *A; - int num_A; - int *D; - int num_D; - /* and the numeric ones; fl_ is the encoding of the LNF - * on the right hand side, without constant part - * (special treatment for that as it's supposed - * to be the most common thing!!) - */ - int *IN_fl; - int *IN_fl_; - float *IN_c; - int num_IN; - - int *AS_fl; - int *AS_fl_; - float *AS_c; - int num_AS; - - /* implied effects - */ - int *I; - int num_I; - - /* members for relaxed fixpoint computation - */ - int level;/* first "cost level" where ef appears */ - float RPGcost;/* max_{p prec} cost(p)+cost(op(ef)) */ - - Bool in_E; - int num_active_PCs; - Bool ch; - - /* RPG - */ - int num_active_f_PCs; - - /* 1P; an effect can be selected several times - * for increasing a fluent. - */ - int in_plan; - -} EfConn; - - - -typedef struct _FtConn { - - /* effects it is union conds, pres element of - */ - int *PC; - int num_PC; - - /* efs that add or del it - */ - int *A; - int num_A; - - int *D; - int num_D; - - /* members for orderings preprocessing - */ - int *False; - int num_False; - - /* members for relaxed fixpoint computation - */ - int level;/* first "cost level" where ft appears */ - float RPGcost;/* min_{e adder} cost(e) */ - Bool in_F; - - /* members for 1Ph extraction - */ - int is_goal; - int is_true; - Bool ch; - - /* search - */ - int rand;/* for hashing */ - - /* is this the effect of an axiom? - * needed to quickly filter out derived facts, in state - * transitions! - */ - Bool axiom_added; - -} FtConn; - - - -typedef struct _FlConn { - - /* effects it is union conds, pres required - */ - int *PC; - int num_PC; - - /* efs that inc, ass it and by which encoded fluents and constants - */ - int *IN; - int *IN_fl_; - float *IN_c; - int num_IN; - - int *AS; - int *AS_fl_; - float *AS_c;/* see above */ - int num_AS; - - /* is it an artificial fluent? - */ - Bool artificial; - /* if so, then this here is the linear equation - * it stands for - */ - int *lnf_F; - float *lnf_C; - int num_lnf; - - - /* the termination criterion for RPG building is based on mneed, see - * JAIR article for definition; - * - * as the name suggests, we use the bool to indicate that this one is not - * needed at all - */ - Bool mneed_is_minusinfty; - float mneed; - /* see JAIR; shortcut for never needed at all. - */ - Bool relevant; - - /* the following are members handled within heuristic algorithms. - */ - - /* this are arrays saying what the max value at - * the levels in the RPG is, resp. whether the value - * can be defined there at all, resp. what the increasers - * at that level have added. - */ - Bool *def; - float *level; - - /* for handling assigners in RPG: is an assigner in there yet, - * and if so what is their max value? - */ - Bool curr_assigned; - float curr_max_assigned; - - int rand;/* for hashing */ - -} FlConn; - - - - - - - - - - - - -/**************************** - * STRUCTURES FOR SEARCHING * - ****************************/ - - - - - - - - - -typedef struct _State { - - int *F; - int num_F; - - Bool *f_D; - float *f_V; - -} State, *State_pointer; - - - -typedef struct _EhcNode { - - State S; - - int op; - int depth; - - struct _EhcNode *father; - struct _EhcNode *next; - -} EhcNode; - - - -typedef struct _EhcHashEntry { - - int sum; - - EhcNode *ehc_node; - - struct _EhcHashEntry *next; - -} EhcHashEntry, *EhcHashEntry_pointer; - - - -typedef struct _PlanHashEntry { - - int sum; - State S; - - /* step is number of op that is EXECUTED in S; - * -1 means that this state is no longer contained in plan - */ - int step; - struct _PlanHashEntry *next_step; - - struct _PlanHashEntry *next; - -} PlanHashEntry, *PlanHashEntry_pointer; - - - -typedef struct _BfsNode { - - State S; - int op; - - /* number of steps from ini state to here - */ - int ini_distance; - - /* number of steps in relaxed plan for this state - */ - int goal_distance; - - /* g-value and h-value, ie summed-up cost to here, - * summed-up cost in rplan for here. - * used in all optimization configs - */ - float g; - float h; - - /* f-value. in weighted A*, f=g+w*h; in A*epsilon, f=g+h - */ - float f; - - /* The applicable actions -- may be only the helpful ones, - * in case helpful actions are used! - */ - int *A; - int num_A; - - struct _BfsNode *father; - - struct _BfsNode *next; - struct _BfsNode *prev; - -} BfsNode; - - - -typedef struct _BfsHashEntry { - - int sum; - - BfsNode *bfs_node; - - struct _BfsHashEntry *next; - -} BfsHashEntry, *BfsHashEntry_pointer; - - - - - - - - - - - - - -/* - * -------------------------------- MAIN FN HEADERS ---------------------------- - */ - - - - - - - - - - - - - - - - - -void output_planner_info( void ); -void ff_usage( void ); -Bool process_command_line( int argc, char *argv[] ); - - - - - - - - - -/* - * ----------------------------- GLOBAL VARIABLES ---------------------------- - */ - - - - - - - - - - - - -/******************* - * GENERAL HELPERS * - *******************/ - - - - - - - - - - -/* used to time the different stages of the planner - */ -extern float gtempl_time, greach_time, grelev_time, gconn_time; -extern float gLNF_time, gsearch_time; - -/* the command line inputs - */ -extern struct _command_line gcmd_line; - -/* number of states that got heuristically evaluated - */ -extern int gevaluated_states; - -/* maximal depth of breadth first search - */ -extern int gmax_search_depth; - - - - - - - - - -/*********** - * PARSING * - ***********/ - - - - - - - - - - - -/* used for pddl parsing, flex only allows global variables - */ -extern int gbracket_count; -extern char *gproblem_name; - -/* The current input line number - */ -extern int lineno; - -/* The current input filename - */ -extern char *gact_filename; - -/* The pddl domain name - */ -extern char *gdomain_name; - -/* loaded, uninstantiated operators - */ -extern PlOperator *gloaded_ops; - -/* stores initials as fact_list - */ -extern PlNode *gorig_initial_facts; - -/* not yet preprocessed goal facts - */ -extern PlNode *gorig_goal_facts; - -/* the types, as defined in the domain file - */ -extern TypedList *gparse_types; - -/* the constants, as defined in domain file - */ -extern TypedList *gparse_constants; - -/* the predicates and their arg types, as defined in the domain file - */ -extern TypedListList *gparse_predicates; - -/* the functions and their arg types, as defined in the domain file - */ -extern TypedListList *gparse_functions; - -/* the objects, declared in the problem file - */ -extern TypedList *gparse_objects; - -/* the metric - */ -extern Token gparse_optimization; -extern ParseExpNode *gparse_metric; - - -/* connection to instantiation ( except ops, goal, initial ) - */ - -/* all typed objects - */ -extern FactList *gorig_constant_list; - -/* the predicates and their types - */ -extern FactList *gpredicates_and_types; - -/* the functions and their types - */ -extern FactList *gfunctions_and_types; - - - - - - - - - - - - - - -/***************** - * INSTANTIATING * - *****************/ - - - - - - - - - - -/* global arrays of constant names, - * type names (with their constants), - * predicate names, - * predicate aritys, - * defined types of predicate args - */ -extern Token gconstants[MAX_CONSTANTS]; -extern int gnum_constants; -extern Token gtype_names[MAX_TYPES]; -extern int gtype_consts[MAX_TYPES][MAX_TYPE]; -extern Bool gis_member[MAX_CONSTANTS][MAX_TYPES]; -extern int gmember_nr[MAX_CONSTANTS][MAX_TYPES];/* nr of object within a type */ -extern int gtype_size[MAX_TYPES]; -extern int gnum_types; -extern Token gpredicates[MAX_PREDICATES]; -extern int garity[MAX_PREDICATES]; -extern Bool gaxiom_added[MAX_PREDICATES]; -extern int gpredicates_args_type[MAX_PREDICATES][MAX_ARITY]; -extern int gnum_predicates; -extern Token gfunctions[MAX_FUNCTIONS]; -extern int gf_arity[MAX_FUNCTIONS]; -extern int gfunctions_args_type[MAX_FUNCTIONS][MAX_ARITY]; -extern int gnum_functions; - - - - -/* the domain in first step integer representation - */ -extern Operator_pointer goperators[MAX_OPERATORS]; -extern int gnum_operators; -extern Fact *gfull_initial; -extern int gnum_full_initial; -extern FluentValue *gfull_fluents_initial; -extern int gnum_full_fluents_initial; -extern WffNode *ggoal; - -extern ExpNode *gmetric; - - - -/* stores inertia - information: is any occurence of the predicate - * added / deleted in the uninstantiated ops ? - */ -extern Bool gis_added[MAX_PREDICATES]; -extern Bool gis_deleted[MAX_PREDICATES]; - -/* for functions we *might* want to say, symmetrically, whether it is - * increased resp. decreased at all. - * - * that is, however, somewhat involved because the right hand - * sides can be arbirtray expressions, so we have no guarantee - * that increasing really does adds to a functions value... - * - * thus (for the time being), we settle for "is the function changed at all?" - */ -extern Bool gis_changed[MAX_FUNCTIONS]; - - - -/* splitted initial state: - * initial non static facts, - * initial static facts, divided into predicates - * (will be two dimensional array, allocated directly before need) - */ -extern Facts *ginitial; -extern int gnum_initial; -extern Fact **ginitial_predicate; -extern int *gnum_initial_predicate; - -/* same thing for functions - */ -extern FluentValues *gf_initial; -extern int gnum_f_initial; -extern FluentValue **ginitial_function; -extern int *gnum_initial_function; - - - -/* the type numbers corresponding to any unary inertia - */ -extern int gtype_to_predicate[MAX_PREDICATES]; -extern int gpredicate_to_type[MAX_TYPES]; - -/* (ordered) numbers of types that new type is intersection of - */ -extern TypeArray gintersected_types[MAX_TYPES]; -extern int gnum_intersected_types[MAX_TYPES]; - - - -/* splitted domain: hard n easy ops - */ -extern Operator_pointer *ghard_operators; -extern int gnum_hard_operators; -extern NormOperator_pointer *geasy_operators; -extern int gnum_easy_operators; - - - -/* so called Templates for easy ops: possible inertia constrained - * instantiation constants - */ -extern EasyTemplate *geasy_templates; -extern int gnum_easy_templates; - - - -/* first step for hard ops: create mixed operators, with conjunctive - * precondition and arbitrary effects - */ -extern MixedOperator *ghard_mixed_operators; -extern int gnum_hard_mixed_operators; - - - -/* hard ''templates'' : pseudo actions - */ -extern PseudoAction_pointer *ghard_templates; -extern int gnum_hard_templates; - - - -/* store the final "relevant facts" - */ -extern Fact grelevant_facts[MAX_RELEVANT_FACTS]; -extern int gnum_relevant_facts; -extern int gnum_pp_facts; -/* store the "relevant fluents" - */ -extern Fluent grelevant_fluents[MAX_RELEVANT_FLUENTS]; -extern int gnum_relevant_fluents; -extern Token grelevant_fluents_name[MAX_RELEVANT_FLUENTS]; -/* this is NULL for normal, and the LNF for - * artificial fluents. - */ -extern LnfExpNode_pointer grelevant_fluents_lnf[MAX_RELEVANT_FLUENTS]; - - - -/* the final actions and problem representation - */ -extern Action *gactions; -extern int gnum_actions; -extern State ginitial_state; -extern int *glogic_goal; -extern int gnum_logic_goal; -extern Comparator *gnumeric_goal_comp; -extern ExpNode_pointer *gnumeric_goal_lh, *gnumeric_goal_rh; -extern int gnum_numeric_goal; - - - -/* to avoid memory leaks; too complicated to identify - * the exact state of the action to throw away (during construction), - * memory gain not worth the implementation effort. - */ -extern Action *gtrash_actions; - - - -/* additional lnf step between finalized inst and - * conn graph - */ -extern Comparator *glnf_goal_comp; -extern LnfExpNode_pointer *glnf_goal_lh; -extern float *glnf_goal_rh; -extern int gnum_lnf_goal; - -extern LnfExpNode glnf_metric; -extern Bool goptimization_established; - - - -/********************** - * CONNECTIVITY GRAPH * - **********************/ - - - - - -/* one ops (actions) array ... - */ -extern OpConn *gop_conn; -extern int gnum_op_conn; - - - -/* one effects array ... - */ -extern EfConn *gef_conn; -extern int gnum_ef_conn; - - - -/* one facts array. - */ -extern FtConn *gft_conn; -extern int gnum_ft_conn; - - - -/* and: one fluents array. - */ -extern FlConn *gfl_conn; -extern int gnum_fl_conn; -extern int gnum_real_fl_conn;/* number of non-artificial ones */ - - - -/* final goal is also transformed one more step. - */ -extern int *gflogic_goal; -extern int gnum_flogic_goal; -extern Comparator *gfnumeric_goal_comp; -extern int *gfnumeric_goal_fl; -extern float *gfnumeric_goal_c; -extern int gnum_fnumeric_goal; - -/* direct access (by relevant fluents) - */ -extern Comparator *gfnumeric_goal_direct_comp; -extern float *gfnumeric_goal_direct_c; - - - - - - - - - - - - - -/******************* - * SEARCHING NEEDS * - *******************/ - - - - - - - - - - - - -/* applicable actions - */ -extern int *gA;/* non-axioms */ -extern int gnum_A; -extern int *gA_axioms; /* axioms */ -extern int gnum_A_axioms; - - - -/* communication from extract 1.P. to search engine: - * 1P action choice - */ -extern int *gH; -extern int gnum_H; -/* added cost of relaxed plan - */ -extern float gh_cost; -/* hmax value - */ -extern float ghmax; - - - -/* to store plan - */ -extern int gplan_ops[MAX_PLAN_LENGTH]; -extern int gnum_plan_ops; - - - -/* stores the states that the current plan goes through - */ -extern State gplan_states[MAX_PLAN_LENGTH + 1]; - - - -/* dirty: multiplic. of total-time in final metric LNF - */ -extern float gtt; - - - - - - -/* the mneed structures - * - * assign propagation pairs i, j, and transitive such pairs. - */ -extern Bool **gassign_influence; -extern Bool **gTassign_influence; - - - -/* the real var input to the mneed computation. - */ -extern Bool *gmneed_start_D; -extern float *gmneed_start_V; - - - -/* does this contain conditional effects? - * (if it does then the state hashing has to be made more - * cautiously) - */ -extern Bool gconditional_effects; - - -/* easier to question: are we optimizing or no? - */ -extern Bool gcost_minimizing; - - -/* stores current A* weight: this is initially given by user, - * but changes during anytime search. - */ -extern float gw; -/* this is the minimum weight, ie we'll stop once the weight update - * does/would yield a value <= this. - * if no such minim weight is given, this will be -1 - */ -extern float gmin_w; - - -/* this one says whether or not we are actually using - * cost-minimizing rplans. - * this will be the case by default if we're running cost- - * minimizing searches. it can be switched off by a flag; - * it is automatically switched off in case there are - * numeric preconditions/goals: for this case, - * cost-minimizing rplans are not implemented (a numeric prec - * may cause an action to come in "later" on in the RPG although - * its logical pres are easy. in that case, any new effects will - * have a smaller RPGcost value than facts we already have waiting. - * in other words, the "Dijsktra" nature breaks. - * - * ... I suppose there may be a generic solution to this that - * can handle numeric precs/goals. Doesn't seem important enough - * to bother. - */ -extern Bool gcost_rplans; - - -#endif diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.c deleted file mode 100644 index db6c1681..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.c +++ /dev/null @@ -1,1220 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - - -/********************************************************************* - * File: inst_easy.c - * Description: functions for multiplying easy operators. - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - -#include "inst_pre.h" -#include "inst_easy.h" - - - - - - - - -void build_easy_action_templates( void ) - -{ - - int i, j; - NormOperator *o; - EasyTemplate *t; - - cleanup_easy_domain(); - - if ( gcmd_line.display_info == 110 ) { - printf("\n\ncleaned up easy operators are:\n"); - for ( i = 0; i < gnum_easy_operators; i++ ) { - print_NormOperator( geasy_operators[i] ); - } - fflush( stdout ); - } - - encode_easy_unaries_as_types(); - - if ( gcmd_line.display_info == 111 ) { - printf("\n\nunaries encoded easy operators are:\n"); - for ( i = 0; i < gnum_easy_operators; i++ ) { - print_NormOperator( geasy_operators[i] ); - } - fflush( stdout ); - } - - multiply_easy_effect_parameters(); - - if ( gcmd_line.display_info == 112 ) { - printf("\n\neffects multiplied easy operators are:\n"); - for ( i = 0; i < gnum_easy_operators; i++ ) { - print_NormOperator( geasy_operators[i] ); - } - fflush( stdout ); - } - - multiply_easy_op_parameters(); - - if ( gcmd_line.display_info == 113 ) { - printf("\n\ninertia free easy operators are:"); - for ( i = 0; i < gnum_easy_operators; i++ ) { - print_NormOperator( geasy_operators[i] ); - } - printf("\n\n"); - fflush( stdout ); - } - - if ( gcmd_line.display_info == 114 ) { - printf("\n\neasy operator templates are:\n"); - - for ( i = 0; i < gnum_easy_operators; i++ ) { - o = geasy_operators[i]; - - printf("\n\n-----------operator %s:-----------", o->operator->name); - for ( t = geasy_templates; t; t = t->next ) { - if ( t->op != o ) { - continue; - } - printf("\ninst: "); - for ( j = 0; j < o->num_vars; j++ ) { - if ( t->inst_table[j] < 0 ) { - printf("\nuninstantiated param in template! debug me, please\n\n"); - exit( 1 ); - } - printf("x%d = %s", j, gconstants[t->inst_table[j]]); - if ( j < o->num_vars - 1 ) { - printf(", "); - } - } - } - } - fflush( stdout ); - } - -} - - - - - - - - - - - -/********************************* - * EASY DOMAIN CLEANUP FUNCTIONs * - *********************************/ - - - - - - - - - - - -void cleanup_easy_domain( void ) - -{ - - int i, i1, i2, i3, i4, a; - NormOperator *o; - NormEffect *e; - - /* most likely ( for sure ? ) we do not need this function call here, - * as empty types are recognised in translation already. - * - * however, who knows .. ? doesn't need any real computation time anyway. - * - * function DOES make sense after unaries encoding, as artificial types - * might well be empty. - */ - handle_empty_easy_parameters(); - - /* remove identical preconds and effects; - * VERY unlikely that such will get down to here, after all - * the formula preprocessing, but possible (?) in principle. - * takes no computation time. - * - * also, remove effect conditions that are contained in the - * preconditions. - */ - for ( i = 0; i < gnum_easy_operators; i++ ) { - o = geasy_operators[i]; - - i1 = 0; - while ( i1 < o->num_preconds-1 ) { - i2 = i1+1; - while ( i2 < o->num_preconds ) { - if ( identical_fact( &(o->preconds[i1]), &(o->preconds[i2]) ) ) { - for ( i3 = i2; i3 < o->num_preconds-1; i3++ ) { - o->preconds[i3].predicate = o->preconds[i3+1].predicate; - for ( i4 = 0; i4 < garity[o->preconds[i3].predicate]; i4++ ) { - o->preconds[i3].args[i4] = o->preconds[i3+1].args[i4]; - } - } - o->num_preconds--; - } else { - i2++; - } - } - i1++; - } - - for ( e = o->effects; e; e = e->next ) { - i1 = 0; - while ( i1 < e->num_conditions-1 ) { - i2 = i1+1; - while ( i2 < e->num_conditions ) { - if ( identical_fact( &(e->conditions[i1]), &(e->conditions[i2]) ) ) { - for ( i3 = i2; i3 < e->num_conditions-1; i3++ ) { - e->conditions[i3].predicate = e->conditions[i3+1].predicate; - /* here, we can still have equalities. nowhere else. - */ - a = ( e->conditions[i3].predicate < 0 ) ? - 2 : garity[e->conditions[i3].predicate]; - for ( i4 = 0; i4 < a; i4++ ) { - e->conditions[i3].args[i4] = e->conditions[i3+1].args[i4]; - } - } - e->num_conditions--; - } else { - i2++; - } - } - i1++; - } - - i1 = 0; - while ( i1 < e->num_conditions ) { - for ( i2 = 0; i2 < o->num_preconds; i2++ ) { - if ( identical_fact( &(e->conditions[i1]), &(o->preconds[i2]) ) ) { - break; - } - } - if ( i2 == o->num_preconds ) { - i1++; - continue; - } - for ( i2 = i1; i2 < e->num_conditions-1; i2++ ) { - e->conditions[i2].predicate = e->conditions[i2+1].predicate; - for ( i3 = 0; i3 < garity[e->conditions[i2].predicate]; i3++ ) { - e->conditions[i2].args[i3] = e->conditions[i2+1].args[i3]; - } - } - e->num_conditions--; - } - - i1 = 0; - while ( i1 < e->num_adds-1 ) { - i2 = i1+1; - while ( i2 < e->num_adds ) { - if ( identical_fact( &(e->adds[i1]), &(e->adds[i2]) ) ) { - for ( i3 = i2; i3 < e->num_adds-1; i3++ ) { - e->adds[i3].predicate = e->adds[i3+1].predicate; - for ( i4 = 0; i4 < garity[e->adds[i3].predicate]; i4++ ) { - e->adds[i3].args[i4] = e->adds[i3+1].args[i4]; - } - } - e->num_adds--; - } else { - i2++; - } - } - i1++; - } - - i1 = 0; - while ( i1 < e->num_dels-1 ) { - i2 = i1+1; - while ( i2 < e->num_dels ) { - if ( identical_fact( &(e->dels[i1]), &(e->dels[i2]) ) ) { - for ( i3 = i2; i3 < e->num_dels-1; i3++ ) { - e->dels[i3].predicate = e->dels[i3+1].predicate; - for ( i4 = 0; i4 < garity[e->dels[i3].predicate]; i4++ ) { - e->dels[i3].args[i4] = e->dels[i3+1].args[i4]; - } - } - e->num_dels--; - } else { - i2++; - } - } - i1++; - } - } - } - -} - - - -Bool identical_fact( Fact *f1, Fact *f2 ) - -{ - - int i, a; - - if ( f1->predicate != f2->predicate ) { - return FALSE; - } - - a = ( f1->predicate < 0 ) ? 2 : garity[f1->predicate]; - - for ( i = 0; i < a; i++ ) { - if ( f1->args[i] != f2->args[i] ) { - return FALSE; - } - } - - return TRUE; - -} - - - -/* this one needs ONLY be used after unaries encoding, as all empty types - * are already recognised during translation, except the artificial ones, - * of course. - */ -void handle_empty_easy_parameters( void ) - -{ - - int i, j, k; - NormOperator *o; - NormEffect *e, *tmp; - - i = 0; - while ( i < gnum_easy_operators ) { - o = geasy_operators[i]; - - for ( j = 0; j < o->num_vars; j++ ) { - if ( gtype_size[o->var_types[j]] == 0 ) { - break; - } - } - if ( j < o->num_vars ) { - free_NormOperator( o ); - for ( k = i; k < gnum_easy_operators - 1; k++ ) { - geasy_operators[k] = geasy_operators[k+1]; - } - gnum_easy_operators--; - } else { - i++; - } - } - - for ( i = 0; i < gnum_easy_operators; i++ ) { - o = geasy_operators[i]; - - e = o->effects; - while ( e ) { - for ( j = 0; j < e->num_vars; j++ ) { - if ( gtype_size[e->var_types[j]] == 0 ) { - break; - } - } - if ( j < e->num_vars ) { - if ( e->prev ) { - e->prev->next = e->next; - } else { - o->effects = e->next; - } - if ( e->next ) { - e->next->prev = e->prev; - } - tmp = e->next; - free_single_NormEffect( e ); - e = tmp; - } else { - e = e->next; - } - } - } - -} - - - - - - - - - - -/**************************** - * UNARY INERTIA INTO TYPES * - ****************************/ - - - - - - - - - - - - -void encode_easy_unaries_as_types( void ) - -{ - - NormOperator *o; - int i1, i, j, k, l, new_T, p, a; - TypeArray T; - int num_T; - NormEffect *e; - int intersected_type, var; - - for ( i1 = 0; i1 < gnum_easy_operators; i1++ ) { - o = geasy_operators[i1]; - - for ( i = 0; i < o->num_vars; i++ ) { - - T[0] = o->var_types[i]; - num_T = 1; - - j = 0; - while ( j < o->num_preconds ) { - p = o->preconds[j].predicate; - if ( ( (new_T = gtype_to_predicate[p]) != -1 ) && - ( o->preconds[j].args[0] == ENCODE_VAR( i ) ) ) { - if ( num_T == MAX_TYPE_INTERSECTIONS ) { - printf("\nincrease MAX_TYPE_INTERSECTIONS (currently %d)\n\n", - MAX_TYPE_INTERSECTIONS); - exit( 1 ); - } - /* insert new type number into ordered array T; - * ---- all type numbers in T are different: - * new nr. is of inferred type - can't be type declared for param - * precondition facts occur at most once - doubles are removed - * during cleanup - */ - for ( k = 0; k < num_T; k++ ) { - if ( new_T < T[k] ) { - break; - } - } - for ( l = num_T; l > k; l-- ) { - T[l] = T[l-1]; - } - T[k] = new_T; - num_T++; - /* now remove superfluous precondition - */ - for ( k = j; k < o->num_preconds-1; k++ ) { - o->preconds[k].predicate = o->preconds[k+1].predicate; - for ( l = 0; l < garity[o->preconds[k].predicate]; l++ ) { - o->preconds[k].args[l] = o->preconds[k+1].args[l]; - } - } - o->num_preconds--; - } else { - j++; - } - } - - /* if we did not hit any unary inertia concerning this parameter - * in the preconds, skip parameter and go to next one - */ - if ( num_T == 1 ) { - continue; - } - - /* now we have the ordered array of types to intersect for param i - * of op o in array T of size num_T; - * if there already is this intersected type, set type of this - * param to its number, otherwise create the new intersected type. - */ - if ( (intersected_type = find_intersected_type( T, num_T )) != -1 ) { - /* type already there - */ - o->var_types[i] = intersected_type; - continue; - } - - /* create new type - */ - o->var_types[i] = create_intersected_type( T, num_T ); - } - - for ( e = o->effects; e; e = e->next ) { - for ( i = 0; i < e->num_vars; i++ ) { - T[0] = e->var_types[i]; - var = o->num_vars + i; - num_T = 1; - j = 0; - while ( j < e->num_conditions ) { - p = e->conditions[j].predicate; - if ( p < 0 ) { - j++; - continue; - } - if ( ( (new_T = gtype_to_predicate[p]) != -1 ) && - ( e->conditions[j].args[0] == ENCODE_VAR( var ) ) ) { - if ( num_T == MAX_TYPE_INTERSECTIONS ) { - printf("\nincrease MAX_TYPE_INTERSECTIONS (currently %d)\n\n", - MAX_TYPE_INTERSECTIONS); - exit( 1 ); - } - for ( k = 0; k < num_T; k++ ) { - if ( new_T < T[k] ) { - break; - } - } - for ( l = num_T; l > k; l-- ) { - T[l] = T[l-1]; - } - T[k] = new_T; - num_T++; - for ( k = j; k < e->num_conditions-1; k++ ) { - e->conditions[k].predicate = e->conditions[k+1].predicate; - a = ( e->conditions[k].predicate < 0 ) ? - 2 : garity[e->conditions[k].predicate]; - for ( l = 0; l < a; l++ ) { - e->conditions[k].args[l] = e->conditions[k+1].args[l]; - } - } - e->num_conditions--; - } else { - j++; - } - } - if ( num_T == 1 ) { - continue; - } - if ( (intersected_type = find_intersected_type( T, num_T )) != -1 ) { - e->var_types[i] = intersected_type; - continue; - } - e->var_types[i] = create_intersected_type( T, num_T ); - } - } - } - - handle_empty_easy_parameters(); - -} - - - -int create_intersected_type( TypeArray T, int num_T ) - -{ - - int i, j, k, intersected_type; - - if ( gnum_types == MAX_TYPES ) { - printf("\ntoo many (inferred and intersected) types! increase MAX_TYPES (currently %d)\n\n", - MAX_TYPES); - exit( 1 ); - } - gtype_names[gnum_types] = NULL; - gtype_size[gnum_types] = 0; - for ( i = 0; i < MAX_CONSTANTS; i++ ) { - gis_member[i][gnum_types] = FALSE; - } - for ( i = 0; i < num_T; i++ ) { - gintersected_types[gnum_types][i] = T[i]; - } - gnum_intersected_types[gnum_types] = num_T; - intersected_type = gnum_types; - gnum_types++; - - for ( j = 0; j < gtype_size[T[0]]; j++ ) { - for ( k = 1; k < num_T; k++ ) { - if ( !gis_member[gtype_consts[T[0]][j]][T[k]] ) { - break; - } - } - if ( k < num_T ) { - continue; - } - /* add constant to new type - */ - if ( gtype_size[intersected_type] == MAX_TYPE ) { - printf("\ntoo many consts in intersected type! increase MAX_TYPE (currently %d)\n\n", - MAX_TYPE); - exit( 1 ); - } - gtype_consts[intersected_type][gtype_size[intersected_type]++] = gtype_consts[T[0]][j]; - gis_member[gtype_consts[T[0]][j]][intersected_type] = TRUE; - } - - /* now verify if the intersected type equals one of the types that we intersected. - * this is the case, iff one of the types in T has the same size as intersected_type - */ - for ( j = 0; j < num_T; j++ ) { - if ( gtype_size[intersected_type] != gtype_size[T[j]] ) { - continue; - } - /* type T[j] contains exactly the constants that we need! - * - * remove intersected type from table! - */ - gtype_size[intersected_type] = 0; - for ( k = 0; k < MAX_CONSTANTS; k++ ) { - gis_member[k][intersected_type] = FALSE; - } - gnum_intersected_types[intersected_type] = -1; - gnum_types--; - intersected_type = T[j]; - break; - } - - return intersected_type; - -} - - - -int find_intersected_type( TypeArray T, int num_T ) - -{ - - int i, j; - - for ( i = 0; i < gnum_types; i++ ) { - if ( gnum_intersected_types[i] == -1 ) { - continue; - } - - if ( gnum_intersected_types[i] != num_T ) { - continue; - } - - for ( j = 0; j < num_T; j++ ) { - if ( T[j] != gintersected_types[i][j] ) { - break; - } - } - if ( j < num_T ) { - continue; - } - - return i; - } - - return -1; - -} - - - - - - - - - - - - - - -/****************************** - * MULTIPLY EFFECT PARAMETERS * - ******************************/ - - - - - - - - - - - - -/* local globals for multiplying - */ - -int linertia_conds[MAX_VARS]; -int lnum_inertia_conds; - -int lmultiply_parameters[MAX_VARS]; -int lnum_multiply_parameters; - -NormOperator *lo; -NormEffect *le; - -NormEffect *lres; - - - - - - -void multiply_easy_effect_parameters( void ) - -{ - - int i, j, k, l, p, par; - NormEffect *e; - - for ( i = 0; i < gnum_easy_operators; i++ ) { - lo = geasy_operators[i]; - - lres = NULL; - for ( e = lo->effects; e; e = e->next ) { - le = e; - - lnum_inertia_conds = 0; - for ( j = 0; j < e->num_conditions; j++ ) { - for ( k = 0; k < garity[e->conditions[j].predicate]; k++ ) { - if ( e->conditions[j].args[k] < 0 && - DECODE_VAR( e->conditions[j].args[k] ) < lo->num_vars ) { - break; - } - } - if ( k < garity[e->conditions[j].predicate] ) { - /* only consider inertia constraining effect parameters - */ - continue; - } - if ( !gis_added[e->conditions[j].predicate] && - !gis_deleted[e->conditions[j].predicate] ) { - linertia_conds[lnum_inertia_conds++] = j; - } - } - - lnum_multiply_parameters = 0; - for ( j = 0; j < e->num_vars; j++ ) { - par = lo->num_vars + j; - for ( k = 0; k < lnum_inertia_conds; k++ ) { - p = e->conditions[linertia_conds[k]].predicate; - for ( l = 0; l < garity[p]; l++ ) { - if ( e->conditions[linertia_conds[k]].args[l] == - ENCODE_VAR( par ) ) { - break; - } - } - if ( l < garity[p] ) { - break; - } - } - if ( k < lnum_inertia_conds ) { - continue; - } - lmultiply_parameters[lnum_multiply_parameters++] = j; - } - - unify_easy_inertia_conditions( 0 ); - } - free_NormEffect( lo->effects ); - lo->effects = lres; - } - -} - - - -void unify_easy_inertia_conditions( int curr_inertia ) - -{ - - int p, i, j, af, hh; - int args[MAX_VARS]; - int affected_params[MAX_VARS]; - int num_affected_params = 0; - - if ( curr_inertia == lnum_inertia_conds ) { - multiply_easy_non_constrained_effect_parameters( 0 ); - return; - } - - p = le->conditions[linertia_conds[curr_inertia]].predicate; - for ( i = 0; i < garity[p]; i++ ) { - args[i] = le->conditions[linertia_conds[curr_inertia]].args[i]; - if ( args[i] < 0 ) { - hh = DECODE_VAR( args[i] ); - hh -= lo->num_vars; - if ( le->inst_table[hh] != -1 ) { - args[i] = le->inst_table[hh]; - } else { - affected_params[num_affected_params++] = hh; - } - } - } - - for ( i = 0; i < gnum_initial_predicate[p]; i++ ) { - af = 0; - for ( j = 0; j < garity[p]; j++ ) { - if ( args[j] >= 0 ) { - if ( args[j] != ginitial_predicate[p][i].args[j] ) { - break; - } else { - continue; - } - } - le->inst_table[affected_params[af++]] = ginitial_predicate[p][i].args[j]; - } - if ( j < garity[p] ) { - continue; - } - - unify_easy_inertia_conditions( curr_inertia + 1 ); - } - - for ( i = 0; i < num_affected_params; i++ ) { - le->inst_table[affected_params[i]] = -1; - } - -} - - - -void multiply_easy_non_constrained_effect_parameters( int curr_parameter ) - -{ - - int t, n, i, j, k, p, par; - NormEffect *tmp; - Bool rem; - - if ( curr_parameter == lnum_multiply_parameters ) { - /* create new effect, adjusting conds to inst, and - * partially instantiating effects; - * - * add result to lres - */ - tmp = new_NormEffect2( le ); - - /* instantiate param occurences - */ - for ( i = 0; i < le->num_vars; i++ ) { - par = lo->num_vars + i; - - /* numerical part - */ - for ( j = 0; j < tmp->num_numeric_conditions; j++ ) { - replace_var_with_const_in_exp( &(tmp->numeric_conditions_lh[j]), - par, le->inst_table[i] ); - } - for ( j = 0; j < tmp->num_numeric_conditions; j++ ) { - replace_var_with_const_in_exp( &(tmp->numeric_conditions_rh[j]), - par, le->inst_table[i] ); - } - /* was that already enough to get numbers? if yes, - * see whether comparison holds or not. - */ - j = 0; - while ( j < tmp->num_numeric_conditions ) { - if ( tmp->numeric_conditions_lh[j]->connective == NUMBER && - tmp->numeric_conditions_rh[j]->connective == NUMBER ) { - if ( number_comparison_holds( tmp->numeric_conditions_comp[j], - tmp->numeric_conditions_lh[j]->value, - tmp->numeric_conditions_rh[j]->value ) ) { - free_ExpNode( tmp->numeric_conditions_lh[j] ); - free_ExpNode( tmp->numeric_conditions_rh[j] ); - for ( k = j; k < tmp->num_numeric_conditions-1; k++ ) { - tmp->numeric_conditions_comp[k] = tmp->numeric_conditions_comp[k+1]; - tmp->numeric_conditions_lh[k] = tmp->numeric_conditions_lh[k+1]; - tmp->numeric_conditions_rh[k] = tmp->numeric_conditions_rh[k+1]; - } - tmp->num_numeric_conditions--; - } else { - free_NormEffect( tmp ); - return; - } - } else { - j++; - } - } - for ( j = 0; j < tmp->num_numeric_effects; j++ ) { - for ( k = 0; k < gf_arity[tmp->numeric_effects_fluent[j].function]; k++ ) { - if ( tmp->numeric_effects_fluent[j].args[k] == ENCODE_VAR( par ) ) { - tmp->numeric_effects_fluent[j].args[k] = le->inst_table[i]; - } - } - } - for ( j = 0; j < tmp->num_numeric_effects; j++ ) { - replace_var_with_const_in_exp( &(tmp->numeric_effects_rh[j]), - par, le->inst_table[i] ); - } - - /* logical part - */ - for ( j = 0; j < tmp->num_conditions; j++ ) { - for ( k = 0; k < garity[tmp->conditions[j].predicate]; k++ ) { - if ( tmp->conditions[j].args[k] == ENCODE_VAR( par ) ) { - tmp->conditions[j].args[k] = le->inst_table[i]; - } - } - } - for ( j = 0; j < tmp->num_adds; j++ ) { - for ( k = 0; k < garity[tmp->adds[j].predicate]; k++ ) { - if ( tmp->adds[j].args[k] == ENCODE_VAR( par ) ) { - tmp->adds[j].args[k] = le->inst_table[i]; - } - } - } - for ( j = 0; j < tmp->num_dels; j++ ) { - for ( k = 0; k < garity[tmp->dels[j].predicate]; k++ ) { - if ( tmp->dels[j].args[k] == ENCODE_VAR( par ) ) { - tmp->dels[j].args[k] = le->inst_table[i]; - } - } - } - } - /* adjust conditions - */ - i = 0; - while ( i < tmp->num_conditions ) { - rem = FALSE; - p = tmp->conditions[i].predicate; - if ( !gis_added[p] && - !gis_deleted[p] ) { - for ( j = 0; j < garity[p]; j++ ) { - if ( tmp->conditions[i].args[j] < 0 && - DECODE_VAR( tmp->conditions[i].args[j] < lo->num_vars ) ) { - break; - } - } - if ( j == garity[p] ) { - /* inertia that constrain only effect params have been unified, - * are therefore TRUE - */ - rem = TRUE; - } - } - if ( rem ) { - for ( j = i; j < tmp->num_conditions - 1; j++ ) { - tmp->conditions[j].predicate = tmp->conditions[j+1].predicate; - for ( k = 0; k < garity[tmp->conditions[j+1].predicate]; k++ ) { - tmp->conditions[j].args[k] = tmp->conditions[j+1].args[k]; - } - } - tmp->num_conditions--; - } else { - i++; - } - } - /* add result to lres - */ - if ( lres ) { - lres->prev = tmp; - } - tmp->next = lres; - lres = tmp; - return; - } - - t = le->var_types[lmultiply_parameters[curr_parameter]]; - n = gtype_size[t]; - - for ( i = 0; i < n; i++ ) { - le->inst_table[lmultiply_parameters[curr_parameter]] = gtype_consts[t][i]; - multiply_easy_non_constrained_effect_parameters( curr_parameter + 1 ); - } - - le->inst_table[lmultiply_parameters[curr_parameter]] = -1; - -} - - - - - - - - - - - - - - - - - - - -/************************** - * MULTIPLY OP PARAMETERS * - **************************/ - - - - - - - - - - - - - - -/* Bool bla; */ - - - - -void multiply_easy_op_parameters( void ) - -{ - - int i, j, k, l, p; - NormOperator *o; - - geasy_templates = NULL; - gnum_easy_templates = 0; - - for ( i = 0; i < gnum_easy_operators; i++ ) { - lo = geasy_operators[i]; -/* if ( strcmp(lo->operator->name, "PORT445_WIN2000") == 0 ) { */ -/* printf("\nmultiply easy OP: %s", lo->operator->name); */ -/* bla = TRUE; */ -/* } else { */ -/* bla = FALSE; */ -/* } */ - - lnum_inertia_conds = 0; - for ( j = 0; j < lo->num_preconds; j++ ) { - if ( !gis_added[lo->preconds[j].predicate] && - !gis_deleted[lo->preconds[j].predicate] ) { - linertia_conds[lnum_inertia_conds++] = j; -/* if ( bla ) { */ -/* printf("\n:inertia cond: %d (pred %s)", j, gpredicates[lo->preconds[j].predicate]); */ -/* fflush(stdout); */ -/* } */ - } - } - - - lnum_multiply_parameters = 0; - for ( j = 0; j < lo->num_vars; j++ ) { - for ( k = 0; k < lnum_inertia_conds; k++ ) { - p = lo->preconds[linertia_conds[k]].predicate; - for ( l = 0; l < garity[p]; l++ ) { - if ( lo->preconds[linertia_conds[k]].args[l] == - ENCODE_VAR( j ) ) { - break; - } - } - if ( l < garity[p] ) { - break; - } - } - if ( k < lnum_inertia_conds ) { - continue; - } -/* if ( bla ) { */ -/* printf("\nmultiply parameter: %d", j); */ -/* fflush(stdout); */ -/* } */ - lmultiply_parameters[lnum_multiply_parameters++] = j; - } - - unify_easy_inertia_preconds( 0 ); - } - - /* now remove inertia preconditions from operator schemata - */ - for ( i = 0; i < gnum_easy_operators; i++ ) { - o = geasy_operators[i]; - - j = 0; - while ( j < o->num_preconds ) { - if ( !gis_added[o->preconds[j].predicate] && - !gis_deleted[o->preconds[j].predicate] ) { - for ( k = j; k < o->num_preconds - 1; k++ ) { - o->preconds[k].predicate = o->preconds[k+1].predicate; - for ( l = 0; l < garity[o->preconds[k].predicate]; l++ ) { - o->preconds[k].args[l] = o->preconds[k+1].args[l]; - } - } - o->num_preconds--; - } else { - j++; - } - } - } - -} - - - -void unify_easy_inertia_preconds( int curr_inertia ) - -{ - - int p, i, j, af, hh; - int args[MAX_VARS]; - int affected_params[MAX_VARS]; - int num_affected_params = 0; - - if ( curr_inertia == lnum_inertia_conds ) { - multiply_easy_non_constrained_op_parameters( 0 ); - return; - } - - p = lo->preconds[linertia_conds[curr_inertia]].predicate; - for ( i = 0; i < garity[p]; i++ ) { - args[i] = lo->preconds[linertia_conds[curr_inertia]].args[i]; - if ( args[i] < 0 ) { - hh = DECODE_VAR( args[i] ); - if ( lo->inst_table[hh] != -1 ) { - args[i] = lo->inst_table[hh]; - } else { - affected_params[num_affected_params++] = hh; - } - } - } - - for ( i = 0; i < gnum_initial_predicate[p]; i++ ) { - af = 0; - for ( j = 0; j < garity[p]; j++ ) { - if ( args[j] >= 0 ) { - if ( args[j] != ginitial_predicate[p][i].args[j] ) { - break; - } else { - continue; - } - } - /* check whether that constant has the correct type for that - * parameter (can be not fulfilled due to encoding of unary inertia - */ - if ( !gis_member[ginitial_predicate[p][i].args[j]][lo->var_types[affected_params[af]]] ) { - break; - } - /* legal constant; set op parameter instantiation to it - */ - lo->inst_table[affected_params[af++]] = ginitial_predicate[p][i].args[j]; - } - if ( j < garity[p] ) { - continue; - } - - unify_easy_inertia_preconds( curr_inertia + 1 ); - } - - for ( i = 0; i < num_affected_params; i++ ) { - lo->inst_table[affected_params[i]] = -1; - } - -} - - - -void multiply_easy_non_constrained_op_parameters( int curr_parameter ) - -{ - - EasyTemplate *tmp; - int i, j, t, n; - -/* if ( bla ) { */ -/* printf("\nEntry multiply!"); */ -/* fflush(stdout); */ -/* } */ - - if ( curr_parameter == lnum_multiply_parameters ) { - tmp = new_EasyTemplate( lo ); - for ( i = 0; i < lo->num_vars; i++ ) { - tmp->inst_table[i] = lo->inst_table[i]; - } - tmp->next = geasy_templates; - if ( geasy_templates ) { - geasy_templates->prev = tmp; - } - geasy_templates = tmp; - gnum_easy_templates++; - return; - } - - if ( curr_parameter == lnum_multiply_parameters - 1 ) { -/* if ( bla ) { */ -/* printf("\nEntry 1 missing!"); */ -/* fflush(stdout); */ -/* } */ - t = lo->var_types[lmultiply_parameters[curr_parameter]]; - n = gtype_size[t]; - for ( i = 0; i < n; i++ ) { - lo->inst_table[lmultiply_parameters[curr_parameter]] = gtype_consts[t][i]; - -/* if ( bla ) { */ -/* printf("\nmaking instance (numvars %d):", lo->num_vars); */ -/* fflush(stdout); */ -/* } */ - tmp = new_EasyTemplate( lo ); - for ( j = 0; j < lo->num_vars; j++ ) { - tmp->inst_table[j] = lo->inst_table[j]; -/* if ( bla ) { */ -/* printf("%s (ID %d), ", gconstants[tmp->inst_table[j]], tmp->inst_table[j]); */ -/* fflush(stdout); */ -/* } */ - } - tmp->next = geasy_templates; - if ( geasy_templates ) { - geasy_templates->prev = tmp; - } - geasy_templates = tmp; - gnum_easy_templates++; - } - - lo->inst_table[lmultiply_parameters[curr_parameter]] = -1; - - return; - } - - t = lo->var_types[lmultiply_parameters[curr_parameter]]; - n = gtype_size[t]; - for ( i = 0; i < n; i++ ) { - lo->inst_table[lmultiply_parameters[curr_parameter]] = gtype_consts[t][i]; - - multiply_easy_non_constrained_op_parameters( curr_parameter + 1 ); - } - - lo->inst_table[lmultiply_parameters[curr_parameter]] = -1; - -} diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.h deleted file mode 100644 index 1bc6eb1d..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_easy.h +++ /dev/null @@ -1,73 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - - - - -/********************************************************************* - * File: inst_easy.h - * Description: headers for multiplying easy operators. - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - -#ifndef _INST_EASY_H -#define _INST_EASY_H - - - -void build_easy_action_templates( void ); - - - -void cleanup_easy_domain( void ); -Bool identical_fact( Fact *f1, Fact *f2 ); -void handle_empty_easy_parameters( void ); - - - -void encode_easy_unaries_as_types( void ); -int create_intersected_type( TypeArray T, int num_T ); -int find_intersected_type( TypeArray T, int num_T ); - - - -void multiply_easy_effect_parameters( void ); -void unify_easy_inertia_conditions( int curr_inertia ); -void multiply_easy_non_constrained_effect_parameters( int curr_parameter ); - - - -void multiply_easy_op_parameters( void ); -void unify_easy_inertia_preconds( int curr_inertia ); -void multiply_easy_non_constrained_op_parameters( int curr_parameter ); - - - -#endif /* _INST_EASY_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.c deleted file mode 100644 index 3f51a89e..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.c +++ /dev/null @@ -1,2797 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - -/********************************************************************* - * File: inst_final.c - * Description: final domain representation functions - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - -#include "inst_pre.h" -#include "inst_final.h" - - - - - - - - - - - - - - -/******************************** - * POSSIBLY TRUE FACTS ANALYSIS * - ********************************/ - - - - - - - - -/* local globals for this part - */ - -int_pointer lpos[MAX_PREDICATES]; -int_pointer lneg[MAX_PREDICATES]; -int_pointer luse[MAX_PREDICATES]; -int_pointer lindex[MAX_PREDICATES]; - -int lp; -int largs[MAX_VARS]; - - - -/* for collecting poss. defined fluents - */ -int_pointer lf_def[MAX_FUNCTIONS]; -int_pointer lf_index[MAX_FUNCTIONS]; - -int lf; -int lf_args[MAX_VARS]; - - - - - - -void perform_reachability_analysis( void ) - -{ - - int size, i, j, k, adr, num, pargtype; - Bool fixpoint; - Facts *f; - NormOperator *no; - EasyTemplate *t1, *t2; - NormEffect *ne; - Action *tmp, *a; - Bool *had_hard_template; - PseudoAction *pa; - PseudoActionEffect *pae; - - gactions = NULL; - gnum_actions = 0; - - for ( i = 0; i < gnum_predicates; i++ ) { - size = 1; - for ( j = 0; j < garity[i]; j++ ) { - pargtype = gpredicates_args_type[i][j]; - size *= gtype_size[pargtype]; - } - - lpos[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - lneg[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - luse[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - lindex[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - - for ( j = 0; j < size; j++ ) { - lpos[i][j] = 0; - lneg[i][j] = 1;/* all facts but initials are poss. negative */ - luse[i][j] = 0; - lindex[i][j] = -1; - } - } - - had_hard_template = ( Bool * ) calloc( gnum_hard_templates, sizeof( Bool ) ); - for ( i = 0; i < gnum_hard_templates; i++ ) { - had_hard_template[i] = FALSE; - } - - /* mark initial facts as possibly positive, not poss. negative - */ - for ( i = 0; i < gnum_predicates; i++ ) { - lp = i; - for ( j = 0; j < gnum_initial_predicate[i]; j++ ) { - for ( k = 0; k < garity[i]; k++ ) { - largs[k] = ginitial_predicate[i][j].args[k]; - } - adr = fact_adress(); - lpos[lp][adr] = 1; - lneg[lp][adr] = 0; - } - } - - /* compute fixpoint - */ - fixpoint = FALSE; - while ( !fixpoint ) { - fixpoint = TRUE; - - /* assign next layer of easy templates to possibly positive fixpoint - */ - t1 = geasy_templates; - while ( t1 ) { - no = t1->op; - for ( i = 0; i < no->num_preconds; i++ ) { - lp = no->preconds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( no->preconds[i].args[j] >= 0 ) ? - no->preconds[i].args[j] : t1->inst_table[DECODE_VAR( no->preconds[i].args[j] )]; - } - if ( !lpos[lp][fact_adress()] ) { - break; - } - } - - if ( i < no->num_preconds ) { - t1 = t1->next; - continue; - } - - num = 0; - for ( ne = no->effects; ne; ne = ne->next ) { - num++; - /* currently, simply ignore effect conditions and assume - * they will all be made true eventually. - */ - for ( i = 0; i < ne->num_adds; i++ ) { - lp = ne->adds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( ne->adds[i].args[j] >= 0 ) ? - ne->adds[i].args[j] : t1->inst_table[DECODE_VAR( ne->adds[i].args[j] )]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) { - /* new relevant fact! (added non initial) - */ - lpos[lp][adr] = 1; - lneg[lp][adr] = 1; - luse[lp][adr] = 1; - if ( gnum_relevant_facts == MAX_RELEVANT_FACTS ) { - printf("\ntoo many relevant facts! increase MAX_RELEVANT_FACTS (currently %d)\n\n", - MAX_RELEVANT_FACTS); - exit( 1 ); - } - grelevant_facts[gnum_relevant_facts].predicate = lp; - for ( j = 0; j < garity[lp]; j++ ) { - grelevant_facts[gnum_relevant_facts].args[j] = largs[j]; - } - lindex[lp][adr] = gnum_relevant_facts; - gnum_relevant_facts++; - fixpoint = FALSE; - } - } - } - - tmp = new_Action(); - tmp->norm_operator = no; - tmp->axiom = no->operator->axiom; - for ( i = 0; i < no->num_vars; i++ ) { - tmp->inst_table[i] = t1->inst_table[i]; - } - tmp->name = no->operator->name; - tmp->num_name_vars = no->operator->number_of_real_params; - make_name_inst_table_from_NormOperator( tmp, no, t1 ); - tmp->next = gactions; - tmp->num_effects = num; - gactions = tmp; - gnum_actions++; - - t2 = t1->next; - if ( t1->next ) { - t1->next->prev = t1->prev; - } - if ( t1->prev ) { - t1->prev->next = t1->next; - } else { - geasy_templates = t1->next; - } - free_single_EasyTemplate( t1 ); - t1 = t2; - } - - /* now assign all hard templates that have not been transformed - * to actions yet. - */ - for ( i = 0; i < gnum_hard_templates; i++ ) { - if ( had_hard_template[i] ) { - continue; - } - pa = ghard_templates[i]; - - for ( j = 0; j < pa->num_preconds; j++ ) { - lp = pa->preconds[j].predicate; - for ( k = 0; k < garity[lp]; k++ ) { - largs[k] = pa->preconds[j].args[k]; - } - if ( !lpos[lp][fact_adress()] ) { - break; - } - } - - if ( j < pa->num_preconds ) { - continue; - } - - for ( pae = pa->effects; pae; pae = pae->next ) { - /* currently, simply ignore effect conditions and assume - * they will all be made true eventually. - */ - for ( j = 0; j < pae->num_adds; j++ ) { - lp = pae->adds[j].predicate; - for ( k = 0; k < garity[lp]; k++ ) { - largs[k] = pae->adds[j].args[k]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) { - /* new relevant fact! (added non initial) - */ - lpos[lp][adr] = 1; - lneg[lp][adr] = 1; - luse[lp][adr] = 1; - if ( gnum_relevant_facts == MAX_RELEVANT_FACTS ) { - printf("\ntoo many relevant facts! increase MAX_RELEVANT_FACTS (currently %d)\n\n", - MAX_RELEVANT_FACTS); - exit( 1 ); - } - grelevant_facts[gnum_relevant_facts].predicate = lp; - for ( k = 0; k < garity[lp]; k++ ) { - grelevant_facts[gnum_relevant_facts].args[k] = largs[k]; - } - lindex[lp][adr] = gnum_relevant_facts; - gnum_relevant_facts++; - fixpoint = FALSE; - } - } - } - - tmp = new_Action(); - tmp->pseudo_action = pa; - tmp->axiom = pa->operator->axiom; - for ( j = 0; j < pa->operator->num_vars; j++ ) { - tmp->inst_table[j] = pa->inst_table[j]; - } - tmp->name = pa->operator->name; - tmp->num_name_vars = pa->operator->number_of_real_params; - make_name_inst_table_from_PseudoAction( tmp, pa ); - tmp->next = gactions; - tmp->num_effects = pa->num_effects; - gactions = tmp; - gnum_actions++; - - had_hard_template[i] = TRUE; - } - } - - free( had_hard_template ); - - gnum_pp_facts = gnum_initial + gnum_relevant_facts; - - if ( gcmd_line.display_info == 118 ) { - printf("\nreachability analysys came up with:"); - - printf("\n\npossibly positive facts:"); - for ( f = ginitial; f; f = f->next ) { - printf("\n"); - print_Fact( f->fact ); - } - for ( i = 0; i < gnum_relevant_facts; i++ ) { - printf("\n"); - print_Fact( &(grelevant_facts[i]) ); - } - - printf("\n\nthis yields these %d action templates:", gnum_actions); - for ( i = 0; i < gnum_operators; i++ ) { - printf("\n\noperator %s:", goperators[i]->name); - for ( a = gactions; a; a = a->next ) { - if ( ( a->norm_operator && - a->norm_operator->operator != goperators[i] ) || - ( a->pseudo_action && - a->pseudo_action->operator != goperators[i] ) ) { - continue; - } - printf("\ntemplate: "); - if ( a->axiom ) printf("(axiom) "); - for ( j = 0; j < goperators[i]->number_of_real_params; j++ ) { - printf("%s", gconstants[a->name_inst_table[j]]); - if ( j < goperators[i]->num_vars-1 ) { - printf(" "); - } - } - } - } - printf("\n\n"); - } - -} - - - -/* bit complicated to avoid memory explosion when high arity predicates take - * num_obs ^ arity space. take space for individual arg types only; - * must consider pred args in smallest - to - largest - type order to make - * mapping injective. - */ -int fact_adress( void ) - -{ - - int r = 0, b = 1, i, j, min, minj; - Bool done[MAX_ARITY]; - - for ( i = 0; i < garity[lp]; i++ ) { - done[i] = FALSE; - } - - for ( i = 0; i < garity[lp]; i++ ) { - min = -1; - minj = -1; - for ( j = 0; j < garity[lp]; j++ ) { - if ( !done[j] ) { - if ( min == -1 || - gtype_size[gpredicates_args_type[lp][j]] < min ) { - min = gtype_size[gpredicates_args_type[lp][j]]; - minj = j; - } - } - } - if ( minj == -1 || min == -1 ) { - printf("\n\nmin or minj not made in fact adress?\n\n"); - exit( 1 ); - } - /* now minj is remaining arg with lowest type size min - */ - /* need number **within type** here! */ - r += b * gmember_nr[largs[minj]][gpredicates_args_type[lp][minj]]; - b *= min; - done[minj] = TRUE; - } - - return r; - -} - - - -int fluent_adress( void ) - -{ - - int r = 0, b = 1, i; - - for ( i = gf_arity[lf] - 1; i > -1; i-- ) { - r += b * lf_args[i]; - b *= gnum_constants; - } - - return r; - -} - - - -void make_name_inst_table_from_NormOperator( Action *a, NormOperator *o, EasyTemplate *t ) - -{ - - int i, r = 0, m = 0; - - for ( i = 0; i < o->operator->number_of_real_params; i++ ) { - if ( o->num_removed_vars > r && - o->removed_vars[r] == i ) { - /* this var has been removed in NormOp; - * insert type constraint constant - * - * at least one there, as empty typed pars ops are removed - */ - a->name_inst_table[i] = gtype_consts[o->type_removed_vars[r]][0]; - r++; - } else { - /* this par corresponds to par m in NormOp - */ - a->name_inst_table[i] = t->inst_table[m]; - m++; - } - } - -} - - - -void make_name_inst_table_from_PseudoAction( Action *a, PseudoAction *pa ) - -{ - - int i; - - for ( i = 0; i < pa->operator->number_of_real_params; i++ ) { - a->name_inst_table[i] = pa->inst_table[i]; - } - -} - - - - - - - - - - - - - - - - - - -/*********************************************************** - * RELEVANCE ANALYSIS AND FINAL DOMAIN AND PROBLEM CLEANUP * - ***********************************************************/ - - - - - - - - - -/* counts effects for later allocation - */ -int lnum_effects; - - - - - - - - - -void collect_relevant_facts_and_fluents( void ) - -{ - - Action *a; - NormOperator *no; - NormEffect *ne; - int i, j, adr, size; - PseudoAction *pa; - PseudoActionEffect *pae; - FluentValues *fvs; - - /* facts: mark all deleted facts; such facts, that are also pos, are relevant. - */ - for ( a = gactions; a; a = a->next ) { - if ( a->norm_operator ) { - no = a->norm_operator; - - for ( ne = no->effects; ne; ne = ne->next ) { - for ( i = 0; i < ne->num_dels; i++ ) { - lp = ne->dels[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( ne->dels[i].args[j] >= 0 ) ? - ne->dels[i].args[j] : a->inst_table[DECODE_VAR( ne->dels[i].args[j] )]; - } - adr = fact_adress(); - - lneg[lp][adr] = 1; - if ( lpos[lp][adr] && - !luse[lp][adr] ) { - luse[lp][adr] = 1; - lindex[lp][adr] = gnum_relevant_facts; - if ( gnum_relevant_facts == MAX_RELEVANT_FACTS ) { - printf("\nincrease MAX_RELEVANT_FACTS! (current value: %d)\n\n", - MAX_RELEVANT_FACTS); - exit( 1 ); - } - grelevant_facts[gnum_relevant_facts].predicate = lp; - for ( j = 0; j < garity[lp]; j++ ) { - grelevant_facts[gnum_relevant_facts].args[j] = largs[j]; - } - lindex[lp][adr] = gnum_relevant_facts; - gnum_relevant_facts++; - } - } - } - } else { - pa = a->pseudo_action; - - for ( pae = pa->effects; pae; pae = pae->next ) { - for ( i = 0; i < pae->num_dels; i++ ) { - lp = pae->dels[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = pae->dels[i].args[j]; - } - adr = fact_adress(); - - lneg[lp][adr] = 1; - if ( lpos[lp][adr] && - !luse[lp][adr] ) { - luse[lp][adr] = 1; - lindex[lp][adr] = gnum_relevant_facts; - if ( gnum_relevant_facts == MAX_RELEVANT_FACTS ) { - printf("\nincrease MAX_RELEVANT_FACTS! (current value: %d)\n\n", - MAX_RELEVANT_FACTS); - exit( 1 ); - } - grelevant_facts[gnum_relevant_facts].predicate = lp; - for ( j = 0; j < garity[lp]; j++ ) { - grelevant_facts[gnum_relevant_facts].args[j] = largs[j]; - } - lindex[lp][adr] = gnum_relevant_facts; - gnum_relevant_facts++; - } - } - } - } - } - /* fluents: collect all that are defined in initial state, plus - * all that are assigned to by an effect of an action - * (i.e. preconds poss. pos. due to reachability) - * - * first initialise fast access structures - */ - for ( i = 0; i < gnum_functions; i++ ) { - size = 1; - for ( j = 0; j < gf_arity[i]; j++ ) { - size *= gnum_constants; - } - lf_def[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - lf_index[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - for ( j = 0; j < size; j++ ) { - lf_def[i][j] = 0; - lf_index[i][j] = -1; - } - } - /* from initial state, only those that are not static. - */ - for ( fvs = gf_initial; fvs; fvs = fvs->next ) { - lf = fvs->fluent.function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = fvs->fluent.args[j]; - } - adr = fluent_adress(); - if ( !lf_def[lf][adr] ) { - lf_def[lf][adr] = 1; - if ( gnum_relevant_fluents == MAX_RELEVANT_FLUENTS ) { - printf("\ntoo many relevant fluents! increase MAX_RELEVANT_FLUENTS (currently %d)\n\n", - MAX_RELEVANT_FLUENTS); - exit( 1 ); - } - grelevant_fluents[gnum_relevant_fluents].function = lf; - grelevant_fluents_name[gnum_relevant_fluents] = - ( char * ) calloc( MAX_LENGTH, sizeof( char ) ); - strcpy( grelevant_fluents_name[gnum_relevant_fluents], gfunctions[lf] ); - for ( j = 0; j < gf_arity[lf]; j++ ) { - grelevant_fluents[gnum_relevant_fluents].args[j] = lf_args[j]; - strcat( grelevant_fluents_name[gnum_relevant_fluents], "_" ); - strcat( grelevant_fluents_name[gnum_relevant_fluents], gconstants[lf_args[j]] ); - } - lf_index[lf][adr] = gnum_relevant_fluents; - gnum_relevant_fluents++; - } else { - printf("\n\nfluent "); - print_Fluent( &(fvs->fluent) ); - printf(" defined twice in initial state! check input files\n\n"); - exit( 1 ); - } - } - /* from actions, all assigns (are non-static anyway) - */ - for ( a = gactions; a; a = a->next ) { - if ( a->norm_operator ) { - no = a->norm_operator; - for ( ne = no->effects; ne; ne = ne->next ) { - for ( i = 0; i < ne->num_numeric_effects; i++ ) { - if ( ne->numeric_effects_neft[i] != ASSIGN ) continue; - lf = ne->numeric_effects_fluent[i].function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = ( ne->numeric_effects_fluent[i].args[j] >= 0 ) ? - ne->numeric_effects_fluent[i].args[j] : - a->inst_table[DECODE_VAR( ne->numeric_effects_fluent[i].args[j] )]; - } - adr = fluent_adress(); - if ( !lf_def[lf][adr] ) { - lf_def[lf][adr] = 1; - if ( gnum_relevant_fluents == MAX_RELEVANT_FLUENTS ) { - printf("\ntoo many relevant fluents! increase MAX_RELEVANT_FLUENTS (currently %d)\n\n", - MAX_RELEVANT_FLUENTS); - exit( 1 ); - } - grelevant_fluents[gnum_relevant_fluents].function = lf; - grelevant_fluents_name[gnum_relevant_fluents] = - ( char * ) calloc( MAX_LENGTH, sizeof( char ) ); - strcpy( grelevant_fluents_name[gnum_relevant_fluents], gfunctions[lf] ); - for ( j = 0; j < gf_arity[lf]; j++ ) { - grelevant_fluents[gnum_relevant_fluents].args[j] = lf_args[j]; - strcat( grelevant_fluents_name[gnum_relevant_fluents], "_" ); - strcat( grelevant_fluents_name[gnum_relevant_fluents], gconstants[lf_args[j]] ); - } - lf_index[lf][adr] = gnum_relevant_fluents; - gnum_relevant_fluents++; - } - } - } - } else { - pa = a->pseudo_action; - for ( pae = pa->effects; pae; pae = pae->next ) { - for ( i = 0; i < pae->num_numeric_effects; i++ ) { - if ( pae->numeric_effects_neft[i] != ASSIGN ) continue; - lf = pae->numeric_effects_fluent[i].function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = ( pae->numeric_effects_fluent[i].args[j] >= 0 ) ? - pae->numeric_effects_fluent[i].args[j] : - a->inst_table[DECODE_VAR( pae->numeric_effects_fluent[i].args[j] )]; - } - adr = fluent_adress(); - if ( !lf_def[lf][adr] ) { - lf_def[lf][adr] = 1; - if ( gnum_relevant_fluents == MAX_RELEVANT_FLUENTS ) { - printf("\ntoo many relevant fluents! increase MAX_RELEVANT_FLUENTS (currently %d)\n\n", - MAX_RELEVANT_FLUENTS); - exit( 1 ); - } - grelevant_fluents[gnum_relevant_fluents].function = lf; - grelevant_fluents_name[gnum_relevant_fluents] = - ( char * ) calloc( MAX_LENGTH, sizeof( char ) ); - strcpy( grelevant_fluents_name[gnum_relevant_fluents], gfunctions[lf] ); - for ( j = 0; j < gf_arity[lf]; j++ ) { - grelevant_fluents[gnum_relevant_fluents].args[j] = lf_args[j]; - strcat( grelevant_fluents_name[gnum_relevant_fluents], "_" ); - strcat( grelevant_fluents_name[gnum_relevant_fluents], gconstants[lf_args[j]] ); - } - lf_index[lf][adr] = gnum_relevant_fluents; - gnum_relevant_fluents++; - } - } - } - } - } - - if ( gcmd_line.display_info == 119 ) { - printf("\n\nfacts selected as relevant:"); - for ( i = 0; i < gnum_relevant_facts; i++ ) { - printf("\n%d: ", i); - print_Fact( &(grelevant_facts[i]) ); - } - printf("\n\nfluents selected as relevant:"); - for ( i = 0; i < gnum_relevant_fluents; i++ ) { - printf("\n%d: ", i); - print_Fluent( &(grelevant_fluents[i]) ); - } - printf("\n\n"); - } - - lnum_effects = 0; - - create_final_goal_state(); - create_final_initial_state(); - create_final_actions(); - - if ( gmetric != NULL ) { - if ( !set_relevants_in_exp( &gmetric ) ) { - if ( gcmd_line.display_info ) { - printf("\nwarning: undefined fluent used in optimization expression. defaulting to plan length"); - } - free_ExpNode( gmetric ); - gmetric = NULL; - } - } - - if ( gcmd_line.display_info == 120 ) { - printf("\n\nfinal domain representation is:\n\n"); - - for ( i = 0; i < gnum_operators; i++ ) { - printf("\n\n------------------operator %s-----------\n\n", goperators[i]->name); - for ( a = gactions; a; a = a->next ) { - if ( ( !a->norm_operator && - !a->pseudo_action ) || - ( a->norm_operator && - a->norm_operator->operator != goperators[i] ) || - ( a->pseudo_action && - a->pseudo_action->operator != goperators[i] ) ) { - continue; - } - print_Action( a ); - } - } - printf("\n\n--------------------GOAL REACHED ops-----------\n\n"); - for ( a = gactions; a; a = a->next ) { - if ( !a->norm_operator && - !a->pseudo_action ) { - print_Action( a ); - } - } - - printf("\n\nfinal initial state is:\n\n"); - print_State( ginitial_state ); - - printf("\n\nfinal goal is:\n\n"); - for ( i = 0; i < gnum_logic_goal; i++ ) { - print_ft_name( glogic_goal[i] ); - printf("\n"); - } - for ( i = 0; i < gnum_numeric_goal; i++ ) { - switch ( gnumeric_goal_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator in gnumeric_goal %d\n\n", gnumeric_goal_comp[i]); - exit( 1 ); - } - print_ExpNode( gnumeric_goal_lh[i] ); - print_ExpNode( gnumeric_goal_rh[i] ); - printf(")\n"); - } - - if ( gmetric ) { - printf("\n\nmetric is (minimize):\n"); - print_ExpNode( gmetric ); - } else { - printf("\n\nmetric: none, i.e. plan length\n"); - } - } - -} - - - -void create_final_goal_state( void ) - -{ - - WffNode *w, *ww; - int m, mn, i, adr; - Action *tmp; - - if ( !set_relevants_in_wff( &ggoal ) ) { - printf("\n\nff: goal accesses a fluent that will never have a defined value. Problem unsolvable.\n\n"); - exit( 1 ); - } - cleanup_wff( &ggoal ); - - if ( ggoal->connective == TRU ) { - printf("\nff: goal can be simplified to TRUE. The empty plan solves it\n\n"); - gnum_plan_ops = 0; - exit( 1 ); - } - if ( ggoal->connective == FAL ) { - printf("\nff: goal can be simplified to FALSE. No plan will solve it\n\n"); - exit( 1 ); - } - - switch ( ggoal->connective ) { - case OR: - if ( gnum_relevant_facts == MAX_RELEVANT_FACTS ) { - printf("\nincrease MAX_RELEVANT_FACTS! (current value: %d)\n\n", - MAX_RELEVANT_FACTS); - exit( 1 ); - } - grelevant_facts[gnum_relevant_facts].predicate = -3; - gnum_relevant_facts++; - for ( w = ggoal->sons; w; w = w->next ) { - tmp = new_Action(); - if ( w->connective == AND ) { - m = 0; mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) m++; - if ( ww->connective == COMP ) mn++; - } - tmp->preconds = ( int * ) calloc( m, sizeof( int ) ); - tmp->numeric_preconds_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp->num_preconds = m; - tmp->num_numeric_preconds = mn; - m = 0; mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) { - lp = ww->fact->predicate; - for ( i = 0; i < garity[lp]; i++ ) { - largs[i] = ww->fact->args[i]; - } - adr = fact_adress(); - tmp->preconds[m] = lindex[lp][adr]; - m++; - } - if ( ww->connective == COMP ) { - tmp->numeric_preconds_comp[mn] = ww->comp; - tmp->numeric_preconds_lh[mn] = copy_Exp( ww->lh ); - tmp->numeric_preconds_rh[mn] = copy_Exp( ww->rh ); - mn++; - } - } - } else { - if ( w->connective == ATOM ) { - tmp->preconds = ( int * ) calloc( 1, sizeof( int ) ); - tmp->num_preconds = 1; - lp = w->fact->predicate; - for ( i = 0; i < garity[lp]; i++ ) { - largs[i] = w->fact->args[i]; - } - adr = fact_adress(); - tmp->preconds[0] = lindex[lp][adr]; - } - if ( w->connective == COMP ) { - tmp->numeric_preconds_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp->numeric_preconds_comp[0] = w->comp; - tmp->numeric_preconds_lh[0] = copy_Exp( w->lh ); - tmp->numeric_preconds_rh[0] = copy_Exp( w->rh ); - tmp->num_numeric_preconds = 1; - } - } - tmp->effects = ( ActionEffect * ) calloc( 1, sizeof( ActionEffect ) ); - tmp->num_effects = 1; - tmp->effects[0].conditions = NULL; - tmp->effects[0].num_conditions = 0; - tmp->effects[0].dels = NULL; - tmp->effects[0].num_dels = 0; - tmp->effects[0].adds = ( int * ) calloc( 1, sizeof( int ) ); - tmp->effects[0].adds[0] = gnum_relevant_facts - 1; - tmp->effects[0].num_adds = 1; - tmp->effects[0].numeric_conditions_comp = NULL; - tmp->effects[0].numeric_conditions_lh = NULL; - tmp->effects[0].numeric_conditions_rh = NULL; - tmp->effects[0].num_numeric_conditions = 0; - tmp->effects[0].numeric_effects_neft = NULL; - tmp->effects[0].numeric_effects_fl = NULL; - tmp->effects[0].numeric_effects_rh = NULL; - tmp->effects[0].num_numeric_effects = 0; - - tmp->next = gactions; - gactions = tmp; - gnum_actions++; - lnum_effects++; - } - glogic_goal = ( int * ) calloc( 1, sizeof( int ) ); - glogic_goal[0] = gnum_relevant_facts - 1; - gnum_logic_goal = 1; - break; - case AND: - m = 0; mn = 0; - for ( w = ggoal->sons; w; w = w->next ) { - if ( w->connective == ATOM ) m++; - if ( w->connective == COMP ) mn++; - } - glogic_goal = ( int * ) calloc( m, sizeof( int ) ); - gnumeric_goal_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - gnumeric_goal_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - gnumeric_goal_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - gnum_logic_goal = m; - gnum_numeric_goal = mn; - m = 0; mn = 0; - for ( w = ggoal->sons; w; w = w->next ) { - if ( w->connective == ATOM ) { - lp = w->fact->predicate; - for ( i = 0; i < garity[lp]; i++ ) { - largs[i] = w->fact->args[i]; - } - adr = fact_adress(); - glogic_goal[m] = lindex[lp][adr]; - m++; - } - if ( w->connective == COMP ) { - gnumeric_goal_comp[mn] = w->comp; - gnumeric_goal_lh[mn] = copy_Exp( w->lh ); - gnumeric_goal_rh[mn] = copy_Exp( w->rh ); - mn++; - } - } - break; - case ATOM: - glogic_goal = ( int * ) calloc( 1, sizeof( int ) ); - gnum_logic_goal = 1; - lp = ggoal->fact->predicate; - for ( i = 0; i < garity[lp]; i++ ) { - largs[i] = ggoal->fact->args[i]; - } - adr = fact_adress(); - glogic_goal[0] = lindex[lp][adr]; - break; - case COMP: - gnumeric_goal_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - gnumeric_goal_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - gnumeric_goal_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - gnum_numeric_goal = 1; - gnumeric_goal_comp[0] = ggoal->comp; - gnumeric_goal_lh[0] = copy_Exp( ggoal->lh ); - gnumeric_goal_rh[0] = copy_Exp( ggoal->rh ); - break; - default: - printf("\n\nwon't get here: non COMP,ATOM,AND,OR in fully simplified goal\n\n"); - exit( 1 ); - } - -} - - - -Bool set_relevants_in_wff( WffNode **w ) - -{ - - WffNode *i; - int j, adr; - - switch ( (*w)->connective ) { - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - if ( !set_relevants_in_wff( &i ) ) { - return FALSE; - } - } - break; - case ATOM: - /* no equalities, as fully instantiated - */ - lp = (*w)->fact->predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = (*w)->fact->args[j]; - } - adr = fact_adress(); - - if ( !lneg[lp][adr] ) { - (*w)->connective = TRU; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - if ( !lpos[lp][adr] ) { - (*w)->connective = FAL; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - break; - case COMP: - if ( !set_relevants_in_exp( &((*w)->lh) ) || - !set_relevants_in_exp( &((*w)->rh) ) ) { - return FALSE; - } - break; - default: - printf("\n\nwon't get here: non ATOM,OR,AND in goal set relevants\n\n"); - exit( 1 ); - } - - return TRUE; - -} - - - -Bool set_relevants_in_exp( ExpNode **n ) - -{ - - int j, adr; - - /* can probably (for sure) forget about the simplification - * stuff here because it's been done before. - * - * igual.... - */ - switch ( (*n)->connective ) { - case AD: - if ( !set_relevants_in_exp( &((*n)->leftson) ) ) return FALSE; - if ( !set_relevants_in_exp( &((*n)->rightson) ) ) return FALSE; - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value + (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case SU: - if ( !set_relevants_in_exp( &((*n)->leftson) ) ) return FALSE; - if ( !set_relevants_in_exp( &((*n)->rightson) ) ) return FALSE; - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value - (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MU: - if ( !set_relevants_in_exp( &((*n)->leftson) ) ) return FALSE; - if ( !set_relevants_in_exp( &((*n)->rightson) ) ) return FALSE; - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case DI: - if ( !set_relevants_in_exp( &((*n)->leftson) ) ) return FALSE; - if ( !set_relevants_in_exp( &((*n)->rightson) ) ) return FALSE; - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - if ( (*n)->rightson->value == 0 ) { - /* kind of unclean: simply leave that in here; - * we will later determine the right thing - * to do with it. - */ - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value / (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MINUS: - if ( !set_relevants_in_exp( &((*n)->son) ) ) return FALSE; - if ( (*n)->son->connective != NUMBER ) break; - (*n)->connective = NUMBER; - (*n)->value = ((float) (-1)) * (*n)->son->value; - free_ExpNode( (*n)->son ); - (*n)->son = NULL; - break; - case NUMBER: - break; - case FHEAD: - lf = (*n)->fluent->function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = (*n)->fluent->args[j]; - } - adr = fluent_adress(); - (*n)->fl = lf_index[lf][adr]; - free( (*n)->fluent ); - (*n)->fluent = NULL; - if ( lf_index[lf][adr] == -1 ) { - if ( lf == 0 ) { - /* ATTENTION!! FUNCTION 0 IS TOTAL-TIME WHICH IS *ONLY* USED - * IN OPTIMIZATION EXPRESSION. GETS A SPECIAL TREATMENT - * IN THE RESPECTIVE FUNCTION IN SEARCH.C!!!! - * - * we remember it as fluent -2!! - */ - (*n)->fl = -2; - } else { - return FALSE; - } - } - break; - default: - printf("\n\nset relevants in expnode: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - - return TRUE; - -} - - - -void create_final_initial_state( void ) - -{ - - Facts *f; - int i, adr, fl; - FluentValues *fvs; - - i = 0; -/* for ( f = ginitial; f; f = f->next ) i++; */ - /* we need space for transformation fluents to come! - * - * ALSO, we may need space for derived facts!!! - */ - make_state( &ginitial_state, gnum_relevant_facts + 1, MAX_RELEVANT_FLUENTS ); - - for ( f = ginitial; f; f = f->next ) { - lp = f->fact->predicate; - for ( i = 0; i < garity[lp]; i++ ) { - largs[i] = f->fact->args[i]; - } - adr = fact_adress(); - if ( !lneg[lp][adr] ) {/* non deleted ini */ - continue; - } - ginitial_state.F[ginitial_state.num_F++] = lindex[lp][adr]; - } - - for ( fvs = gf_initial; fvs; fvs = fvs->next ) { - lf = fvs->fluent.function; - for ( i = 0; i < gf_arity[lf]; i++ ) { - lf_args[i] = fvs->fluent.args[i]; - } - adr = fluent_adress(); - fl = lf_index[lf][adr]; - ginitial_state.f_D[fl] = TRUE; - ginitial_state.f_V[fl] = fvs->value; - } - -} - - - -void create_final_actions( void ) - -{ - - Action *a, *p, *t; - NormOperator *no; - NormEffect *ne; - int i, j, adr; - PseudoAction *pa; - PseudoActionEffect *pae; - ActionEffect *aa; - Bool false_cond; - - a = gactions; p = NULL; - while ( a ) { - if ( a->norm_operator ) { - /* action comes from an easy template NormOp - */ - no = a->norm_operator; - - if ( no->num_preconds > 0 ) { - a->preconds = ( int * ) calloc( no->num_preconds, sizeof( int ) ); - } - a->num_preconds = 0; - for ( i = 0; i < no->num_preconds; i++ ) { - lp = no->preconds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( no->preconds[i].args[j] >= 0 ) ? - no->preconds[i].args[j] : a->inst_table[DECODE_VAR( no->preconds[i].args[j] )]; - } - adr = fact_adress(); - /* preconds are lpos in all cases due to reachability analysis - */ - if ( !lneg[lp][adr] ) { - continue; - } - a->preconds[a->num_preconds++] = lindex[lp][adr]; - } - - /**************************NUMERIC PRECOND*************************/ - if ( no->num_numeric_preconds > 0 ) { - a->numeric_preconds_comp = ( Comparator * ) - calloc( no->num_numeric_preconds, sizeof( Comparator ) ); - a->numeric_preconds_lh = ( ExpNode_pointer * ) - calloc( no->num_numeric_preconds, sizeof( ExpNode_pointer ) ); - a->numeric_preconds_rh = ( ExpNode_pointer * ) - calloc( no->num_numeric_preconds, sizeof( ExpNode_pointer ) ); - a->num_numeric_preconds = 0; - } - for ( i = 0; i < no->num_numeric_preconds; i++ ) { - a->numeric_preconds_comp[a->num_numeric_preconds] = no->numeric_preconds_comp[i]; - a->numeric_preconds_lh[a->num_numeric_preconds] = copy_Exp( no->numeric_preconds_lh[i] ); - instantiate_exp_by_action( &(a->numeric_preconds_lh[a->num_numeric_preconds]), a ); - if ( !set_relevants_in_exp( &(a->numeric_preconds_lh[a->num_numeric_preconds]) ) ) break; - a->numeric_preconds_rh[a->num_numeric_preconds] = copy_Exp( no->numeric_preconds_rh[i] ); - instantiate_exp_by_action( &(a->numeric_preconds_rh[a->num_numeric_preconds]), a ); - if ( !set_relevants_in_exp( &(a->numeric_preconds_rh[a->num_numeric_preconds]) ) ) break; - if ( a->numeric_preconds_lh[a->num_numeric_preconds]->connective == NUMBER && - a->numeric_preconds_rh[a->num_numeric_preconds]->connective == NUMBER ) { - /* trivial numeric precond - */ - if ( number_comparison_holds( a->numeric_preconds_comp[a->num_numeric_preconds], - a->numeric_preconds_lh[a->num_numeric_preconds]->value, - a->numeric_preconds_rh[a->num_numeric_preconds]->value ) ) { - /* true precond -> throw precond away. by not incrementing number of such. - */ - free_ExpNode( a->numeric_preconds_lh[a->num_numeric_preconds] ); - free_ExpNode( a->numeric_preconds_rh[a->num_numeric_preconds] ); - continue; - } else { - /* false precond -> throw action away. - */ - break; - } - } - a->num_numeric_preconds++; - } - if ( i < no->num_numeric_preconds ) { - /* a precond accesses an undefined fluent, or is false -> remove action! - */ - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - continue; - } - /**************************NUMERIC PRECOND-END*************************/ - - /* and now for the effects - */ - if ( a->num_effects > 0 ) { - a->effects = ( ActionEffect * ) calloc( a->num_effects, sizeof( ActionEffect ) ); - for ( i = 0; i < a->num_effects; i++ ) { - a->effects[i].illegal = FALSE; - a->effects[i].removed = FALSE; - } - } - a->num_effects = 0; - for ( ne = no->effects; ne; ne = ne->next ) { - aa = &(a->effects[a->num_effects]); - - if ( ne->num_conditions > 0 ) { - aa->conditions = ( int * ) calloc( ne->num_conditions, sizeof( int ) ); - } - aa->num_conditions = 0; - for ( i = 0; i < ne->num_conditions; i++ ) { - lp = ne->conditions[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( ne->conditions[i].args[j] >= 0 ) ? - ne->conditions[i].args[j] : a->inst_table[DECODE_VAR( ne->conditions[i].args[j] )]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) {/* condition not reachable: skip effect */ - break; - } - if ( !lneg[lp][adr] ) {/* condition always true: skip it */ - continue; - } - aa->conditions[aa->num_conditions++] = lindex[lp][adr]; - } - if ( i < ne->num_conditions ) {/* found unreachable condition: free condition space */ - free( aa->conditions ); - continue; - } - - /**************************NUMERIC COND*************************/ - if ( ne->num_numeric_conditions > 0 ) { - aa->numeric_conditions_comp = ( Comparator * ) - calloc( ne->num_numeric_conditions, sizeof( Comparator ) ); - aa->numeric_conditions_lh = ( ExpNode_pointer * ) - calloc( ne->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - aa->numeric_conditions_rh = ( ExpNode_pointer * ) - calloc( ne->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - for ( i = 0; i < ne->num_numeric_conditions; i++ ) { - aa->numeric_conditions_lh[i] = NULL; - aa->numeric_conditions_rh[i] = NULL; - } - aa->num_numeric_conditions = 0; - } - false_cond = FALSE; - for ( i = 0; i < ne->num_numeric_conditions; i++ ) { - aa->numeric_conditions_comp[aa->num_numeric_conditions] = ne->numeric_conditions_comp[i]; - aa->numeric_conditions_lh[aa->num_numeric_conditions] = copy_Exp( ne->numeric_conditions_lh[i] ); - instantiate_exp_by_action( &(aa->numeric_conditions_lh[aa->num_numeric_conditions]), a ); - if ( !set_relevants_in_exp( &(aa->numeric_conditions_lh[aa->num_numeric_conditions]) ) ) break; - aa->numeric_conditions_rh[aa->num_numeric_conditions] = copy_Exp( ne->numeric_conditions_rh[i] ); - instantiate_exp_by_action( &(aa->numeric_conditions_rh[aa->num_numeric_conditions]), a ); - if ( !set_relevants_in_exp( &(aa->numeric_conditions_rh[aa->num_numeric_conditions]) ) ) break; - if ( aa->numeric_conditions_lh[aa->num_numeric_conditions]->connective == NUMBER && - aa->numeric_conditions_rh[aa->num_numeric_conditions]->connective == NUMBER ) { - /* trivial numeric condition - */ - if ( number_comparison_holds( aa->numeric_conditions_comp[aa->num_numeric_conditions], - aa->numeric_conditions_lh[aa->num_numeric_conditions]->value, - aa->numeric_conditions_rh[aa->num_numeric_conditions]->value ) ) { - /* true cond -> throw cond away. by not incrementing number of such. - */ - free_ExpNode( aa->numeric_conditions_lh[aa->num_numeric_conditions] ); - free_ExpNode( aa->numeric_conditions_rh[aa->num_numeric_conditions] ); - aa->numeric_conditions_lh[aa->num_numeric_conditions] = NULL; - aa->numeric_conditions_rh[aa->num_numeric_conditions] = NULL; - continue; - } else { - /* false cond -> throw effect away. - */ - false_cond = TRUE; - break; - } - } - aa->num_numeric_conditions++; - } - if ( i < ne->num_numeric_conditions ) { - if ( false_cond ) { - /* false numeric cond: free what's been done so far, and skip effect - */ - for ( i = 0; i <= aa->num_numeric_conditions; i++ ) { - free_ExpNode( aa->numeric_conditions_lh[i] ); - free_ExpNode( aa->numeric_conditions_rh[i] ); - } - free( aa->numeric_conditions_comp ); - free( aa->numeric_conditions_lh ); - free( aa->numeric_conditions_rh ); - continue;/* next effect, without incrementing action counter */ - } else { - /* numeric effect uses undefined fluent in condition --> - * THROW WHOLE ACTION AWAY! done by breaking out of the - * effects loop, which will be catched below overall - * effect handling. - */ - break; - } - } - /**************************NUMERIC COND - END*************************/ - - /* now create the add and del effects. - */ - if ( ne->num_adds > 0 ) { - aa->adds = ( int * ) calloc( ne->num_adds, sizeof( int ) ); - } - aa->num_adds = 0; - for ( i = 0; i < ne->num_adds; i++ ) { - lp = ne->adds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( ne->adds[i].args[j] >= 0 ) ? - ne->adds[i].args[j] : a->inst_table[DECODE_VAR( ne->adds[i].args[j] )]; - } - adr = fact_adress(); - if ( !lneg[lp][adr] ) {/* effect always true: skip it */ - continue; - } - aa->adds[aa->num_adds++] = lindex[lp][adr]; - } - - if ( ne->num_dels > 0 ) { - aa->dels = ( int * ) calloc( ne->num_dels, sizeof( int ) ); - } - aa->num_dels = 0; - for ( i = 0; i < ne->num_dels; i++ ) { - lp = ne->dels[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = ( ne->dels[i].args[j] >= 0 ) ? - ne->dels[i].args[j] : a->inst_table[DECODE_VAR( ne->dels[i].args[j] )]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) {/* effect always false: skip it */ - continue; - } - /* NO CHECK FOR ADD \CAP DEL!!!!! -> ALLOWED BY SEMANTICS!!! - */ - aa->dels[aa->num_dels++] = lindex[lp][adr]; - } - if ( i < ne->num_dels ) break; - - /**************************NUMERIC EFFECTS*************************/ - if ( ne->num_numeric_effects > 0 ) { - aa->numeric_effects_neft = ( NumericEffectType * ) - calloc( ne->num_numeric_effects, sizeof( NumericEffectType ) ); - aa->numeric_effects_fl = ( int * ) - calloc( ne->num_numeric_effects, sizeof( int ) ); - aa->numeric_effects_rh = ( ExpNode_pointer * ) - calloc( ne->num_numeric_effects, sizeof( ExpNode_pointer ) ); - aa->num_numeric_effects = 0; - } - for ( i = 0; i < ne->num_numeric_effects; i++ ) { - aa->numeric_effects_neft[aa->num_numeric_effects] = ne->numeric_effects_neft[i]; - lf = ne->numeric_effects_fluent[i].function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = ( ne->numeric_effects_fluent[i].args[j] >= 0 ) ? - ne->numeric_effects_fluent[i].args[j] : - a->inst_table[DECODE_VAR( ne->numeric_effects_fluent[i].args[j] )]; - } - adr = fluent_adress(); - /* if it's -1, simply let it in --- if that effect appears, then - * action is illegal, otherwise not. - */ - aa->numeric_effects_fl[i] = lf_index[lf][adr]; - if ( lf_index[lf][adr] == -1 ) aa->illegal = TRUE; - aa->numeric_effects_rh[aa->num_numeric_effects] = copy_Exp( ne->numeric_effects_rh[i] ); - instantiate_exp_by_action( &(aa->numeric_effects_rh[aa->num_numeric_effects]), a ); - if ( !set_relevants_in_exp( &(aa->numeric_effects_rh[aa->num_numeric_effects]) ) ) { - aa->illegal = TRUE; - } - if ( aa->illegal && - aa->num_conditions == 0 && - aa->num_numeric_conditions == 0 ) { - break; - } - /* that's it ???????????????? - !! - */ - aa->num_numeric_effects++; - } - if ( i < ne->num_numeric_effects ) { - /* an unconditional illegal effekt - */ - break; - } - /**************************NUMERIC EFFECTS - END*************************/ - - /* this effect is OK. go to next one in NormOp. - */ - a->num_effects++; - lnum_effects++; - } - if ( ne ) { - /* we get here if one effect was faulty - */ - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - } else { - p = a; - a = a->next; - } - continue; - } - /**********************************second half: hard operators --> pseudo actions******************/ - if ( a->pseudo_action ) { - /* action is result of a PseudoAction - */ - pa = a->pseudo_action; - if ( pa->num_preconds > 0 ) { - a->preconds = ( int * ) calloc( pa->num_preconds, sizeof( int ) ); - } - a->num_preconds = 0; - for ( i = 0; i < pa->num_preconds; i++ ) { - lp = pa->preconds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = pa->preconds[i].args[j]; - } - adr = fact_adress(); - /* preconds are lpos in all cases due to reachability analysis - */ - if ( !lneg[lp][adr] ) { - continue; - } - a->preconds[a->num_preconds++] = lindex[lp][adr]; - } - - /**************************NUMERIC PRECOND*************************/ - if ( pa->num_numeric_preconds > 0 ) { - a->numeric_preconds_comp = ( Comparator * ) - calloc( pa->num_numeric_preconds, sizeof( Comparator ) ); - a->numeric_preconds_lh = ( ExpNode_pointer * ) - calloc( pa->num_numeric_preconds, sizeof( ExpNode_pointer ) ); - a->numeric_preconds_rh = ( ExpNode_pointer * ) - calloc( pa->num_numeric_preconds, sizeof( ExpNode_pointer ) ); - a->num_numeric_preconds = 0; - } - for ( i = 0; i < pa->num_numeric_preconds; i++ ) { - a->numeric_preconds_comp[a->num_numeric_preconds] = pa->numeric_preconds_comp[i]; - a->numeric_preconds_lh[a->num_numeric_preconds] = copy_Exp( pa->numeric_preconds_lh[i] ); - if ( !set_relevants_in_exp( &(a->numeric_preconds_lh[a->num_numeric_preconds]) ) ) break; - a->numeric_preconds_rh[a->num_numeric_preconds] = copy_Exp( pa->numeric_preconds_rh[i] ); - if ( !set_relevants_in_exp( &(a->numeric_preconds_rh[a->num_numeric_preconds]) ) ) break; - a->num_numeric_preconds++; - } - if ( i < pa->num_numeric_preconds ) { - /* a precond accesses an undefined fluent -> remove action! - */ - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - continue; - } - /**************************NUMERIC PRECOND-END*************************/ - - /* and now for the effects - */ - if ( a->num_effects > 0 ) { - a->effects = ( ActionEffect * ) calloc( a->num_effects, sizeof( ActionEffect ) ); - for ( i = 0; i < a->num_effects; i++ ) { - a->effects[i].illegal = FALSE; - a->effects[i].removed = FALSE; - } - } - a->num_effects = 0; - for ( pae = pa->effects; pae; pae = pae->next ) { - aa = &(a->effects[a->num_effects]); - - if ( pae->num_conditions > 0 ) { - aa->conditions = ( int * ) calloc( pae->num_conditions, sizeof( int ) ); - } - aa->num_conditions = 0; - for ( i = 0; i < pae->num_conditions; i++ ) { - lp = pae->conditions[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = pae->conditions[i].args[j]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) {/* condition not reachable: skip effect */ - break; - } - if ( !lneg[lp][adr] ) {/* condition always true: skip it */ - continue; - } - aa->conditions[aa->num_conditions++] = lindex[lp][adr]; - } - if ( i < pae->num_conditions ) {/* found unreachable condition: free condition space */ - free( aa->conditions ); - continue; - } - - /**************************NUMERIC COND*************************/ - if ( pae->num_numeric_conditions > 0 ) { - aa->numeric_conditions_comp = ( Comparator * ) - calloc( pae->num_numeric_conditions, sizeof( Comparator ) ); - aa->numeric_conditions_lh = ( ExpNode_pointer * ) - calloc( pae->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - aa->numeric_conditions_rh = ( ExpNode_pointer * ) - calloc( pae->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - for ( i = 0; i < pae->num_numeric_conditions; i++ ) { - aa->numeric_conditions_lh[i] = NULL; - aa->numeric_conditions_rh[i] = NULL; - } - aa->num_numeric_conditions = 0; - } - for ( i = 0; i < pae->num_numeric_conditions; i++ ) { - aa->numeric_conditions_comp[aa->num_numeric_conditions] = pae->numeric_conditions_comp[i]; - aa->numeric_conditions_lh[aa->num_numeric_conditions] = copy_Exp( pae->numeric_conditions_lh[i] ); - if ( !set_relevants_in_exp( &(aa->numeric_conditions_lh[aa->num_numeric_conditions]) ) ) break; - aa->numeric_conditions_rh[aa->num_numeric_conditions] = copy_Exp( pae->numeric_conditions_rh[i] ); - if ( !set_relevants_in_exp( &(aa->numeric_conditions_rh[aa->num_numeric_conditions]) ) ) break; - aa->num_numeric_conditions++; - } - if ( i < pae->num_numeric_conditions ) { - /* numeric effect uses undefined fluent in condition --> - * THROW WHOLE ACTION AWAY! done by breaking out of the - * effects loop, which will be catched below overall - * effect handling. - */ - break; - } - /**************************NUMERIC COND - END*************************/ - - /* now create the add and del effects. - */ - if ( pae->num_adds > 0 ) { - aa->adds = ( int * ) calloc( pae->num_adds, sizeof( int ) ); - } - aa->num_adds = 0; - for ( i = 0; i < pae->num_adds; i++ ) { - lp = pae->adds[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = pae->adds[i].args[j]; - } - adr = fact_adress(); - if ( !lneg[lp][adr] ) {/* effect always true: skip it */ - continue; - } - aa->adds[aa->num_adds++] = lindex[lp][adr]; - } - - if ( pae->num_dels > 0 ) { - aa->dels = ( int * ) calloc( pae->num_dels, sizeof( int ) ); - } - aa->num_dels = 0; - for ( i = 0; i < pae->num_dels; i++ ) { - lp = pae->dels[i].predicate; - for ( j = 0; j < garity[lp]; j++ ) { - largs[j] = pae->dels[i].args[j]; - } - adr = fact_adress(); - if ( !lpos[lp][adr] ) {/* effect always false: skip it */ - continue; - } - aa->dels[aa->num_dels++] = lindex[lp][adr]; - } - if ( i < pae->num_dels ) break; - - /**************************NUMERIC EFFECTS*************************/ - if ( pae->num_numeric_effects > 0 ) { - aa->numeric_effects_neft = ( NumericEffectType * ) - calloc( pae->num_numeric_effects, sizeof( NumericEffectType ) ); - aa->numeric_effects_fl = ( int * ) - calloc( pae->num_numeric_effects, sizeof( int ) ); - aa->numeric_effects_rh = ( ExpNode_pointer * ) - calloc( pae->num_numeric_effects, sizeof( ExpNode_pointer ) ); - aa->num_numeric_effects = 0; - } - for ( i = 0; i < pae->num_numeric_effects; i++ ) { - aa->numeric_effects_neft[aa->num_numeric_effects] = pae->numeric_effects_neft[i]; - lf = pae->numeric_effects_fluent[i].function; - for ( j = 0; j < gf_arity[lf]; j++ ) { - lf_args[j] = pae->numeric_effects_fluent[i].args[j]; - if ( lf_args[j] < 0 ) { - printf("\n\nuninstantiated affected fluent in final actions! debug me.\n\n"); - exit( 1 ); - } - } - adr = fluent_adress(); - /* if it's -1, simply let it in --- if that effect appears, then - * action is illegal, otherwise not. - */ - aa->numeric_effects_fl[i] = lf_index[lf][adr]; - if ( lf_index[lf][adr] == -1 ) aa->illegal = TRUE; - aa->numeric_effects_rh[aa->num_numeric_effects] = copy_Exp( pae->numeric_effects_rh[i] ); - if ( !set_relevants_in_exp( &(aa->numeric_effects_rh[aa->num_numeric_effects]) ) ) { - aa->illegal = TRUE; - } - if ( aa->illegal && - aa->num_conditions == 0 && - aa->num_numeric_conditions == 0 ) { - break; - } - /* that's it ???????????????? - !! - */ - aa->num_numeric_effects++; - } - if ( i < pae->num_numeric_effects ) { - /* an unconditional illegal effekt - */ - break; - } - /**************************NUMERIC EFFECTS - END*************************/ - - /* this effect is OK. go to next one in PseudoAction. - */ - a->num_effects++; - lnum_effects++; - } - if ( pae ) { - /* we get here if one effect was faulty - */ - gnum_actions--; - if ( p ) { - p->next = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } else { - gactions = a->next; - t = a; - a = a->next; - t->next = gtrash_actions; - gtrash_actions = t; - } - } else { - p = a; - a = a->next; - } - continue; - }/* end of if clause for PseudoAction */ - /* if action was neither normop, nor pseudo action determined, - * then it is an artificial action due to disjunctive goal - * conditions. - * - * these are already in final form. - */ - p = a; - a = a->next; - }/* endfor all actions ! */ - -} - - - -void instantiate_exp_by_action( ExpNode **n, Action *a ) - -{ - - int j, f, k, h; - Bool ok; - - switch ( (*n)->connective ) { - case AD: - instantiate_exp_by_action( &((*n)->leftson), a ); - instantiate_exp_by_action( &((*n)->rightson), a ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value + (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case SU: - instantiate_exp_by_action( &((*n)->leftson), a ); - instantiate_exp_by_action( &((*n)->rightson), a ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value - (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MU: - instantiate_exp_by_action( &((*n)->leftson), a ); - instantiate_exp_by_action( &((*n)->rightson), a ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case DI: - instantiate_exp_by_action( &((*n)->leftson), a ); - instantiate_exp_by_action( &((*n)->rightson), a ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - if ( (*n)->rightson->value == 0 ) { - /* kind of unclean: simply leave that in here; - * we will later determine the right thing - * to do with it. - */ - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value / (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MINUS: - instantiate_exp_by_action( &((*n)->son), a ); - if ( (*n)->son->connective != NUMBER ) break; - (*n)->connective = NUMBER; - (*n)->value = ((float) (-1)) * (*n)->son->value; - free_ExpNode( (*n)->son ); - (*n)->son = NULL; - break; - case NUMBER: - break; - case FHEAD: - f = (*n)->fluent->function; - ok = TRUE; - for ( j = 0; j < gf_arity[f]; j++ ) { - h = ( (*n)->fluent->args[j] < 0 ) ? - a->inst_table[DECODE_VAR( (*n)->fluent->args[j] )] : (*n)->fluent->args[j]; - if ( h < 0 ) { - ok = FALSE; - } else { - (*n)->fluent->args[j] = h; - } - } - if ( !ok ) { - printf("\n\nnon-instantiated fluent in final actiona! debug me!!\n\n"); - exit( 1 ); - } - if ( gis_changed[f] ) break; - for ( j = 0; j < gnum_initial_function[f]; j++ ) { - for ( k = 0; k < gf_arity[f]; k++ ) { - if ( ginitial_function[f][j].fluent.args[k] != - (*n)->fluent->args[k] ) break; - } - if ( k < gf_arity[f] ) continue; - (*n)->connective = NUMBER; - (*n)->value = ginitial_function[f][j].value; - break; - } - break; - default: - printf("\n\ninst. exp by action: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - -} - - - - - - - - - - - - - - - - - - - - -/************************************************** - * CONNECTIVITY GRAPH. ULTRA CLEAN REPRESENTATION * - **************************************************/ - - - - - - - - - - - - - - - - - - - - -void build_connectivity_graph( void ) - -{ - - int i, j, k, l, n_op, n_ef, fl, ef, ef_, m; - float val; - Action *a; - ActionEffect *e; - - gnum_ft_conn = gnum_relevant_facts; - gnum_fl_conn = gnum_relevant_fluents; - gnum_op_conn = gnum_actions; - gft_conn = ( FtConn * ) calloc( gnum_ft_conn, sizeof( FtConn ) ); - gfl_conn = ( FlConn * ) calloc( gnum_fl_conn, sizeof( FlConn ) ); - gop_conn = ( OpConn * ) calloc( gnum_op_conn, sizeof( OpConn ) ); - gef_conn = ( EfConn * ) calloc( lnum_effects, sizeof( EfConn ) ); - gnum_ef_conn = 0; - - for ( i = 0; i < gnum_ft_conn; i++ ) { - gft_conn[i].num_PC = 0; - gft_conn[i].num_A = 0; - gft_conn[i].num_D = 0; - - gft_conn[i].axiom_added = FALSE; - - gft_conn[i].rand = random() % BIG_INT; - } - - gnum_real_fl_conn = 0; - for ( i = 0; i < gnum_fl_conn; i++ ) { - gfl_conn[i].num_PC = 0; - gfl_conn[i].num_IN = 0; - gfl_conn[i].num_AS = 0; - - if ( grelevant_fluents_lnf[i] == NULL ) { - gfl_conn[i].artificial = FALSE; - gnum_real_fl_conn++; - gfl_conn[i].rand = random() % BIG_INT; - } else { - /* once we're in here we'll stay as all artificial - * fluents are appended to the end. - */ - gfl_conn[i].artificial = TRUE; - gfl_conn[i].lnf_F = ( int * ) - calloc( grelevant_fluents_lnf[i]->num_pF, sizeof( int ) ); - gfl_conn[i].lnf_C = ( float * ) - calloc( grelevant_fluents_lnf[i]->num_pF, sizeof( float ) ); - for ( j = 0; j < grelevant_fluents_lnf[i]->num_pF; j++ ) { - gfl_conn[i].lnf_F[j] = grelevant_fluents_lnf[i]->pF[j]; - gfl_conn[i].lnf_C[j] = grelevant_fluents_lnf[i]->pC[j]; - } - gfl_conn[i].num_lnf = grelevant_fluents_lnf[i]->num_pF; - } - } - - - /* why not do this here? - */ - gmneed_start_D = ( Bool * ) calloc( gnum_real_fl_conn, sizeof( Bool ) ); - gmneed_start_V = ( float * ) calloc( gnum_real_fl_conn, sizeof( float ) ); - - - for ( i = 0; i < gnum_op_conn; i++ ) { - gop_conn[i].num_E = 0; - } - - for ( i = 0; i < lnum_effects; i++ ) { - gef_conn[i].num_PC = 0; - gef_conn[i].num_f_PC = 0; - gef_conn[i].num_A = 0; - gef_conn[i].num_D = 0; - gef_conn[i].num_I = 0; - gef_conn[i].num_IN = 0; - gef_conn[i].num_AS = 0; - - gef_conn[i].illegal = FALSE; - gef_conn[i].removed = FALSE; - } - - - /* determine if there are conditional effects. - */ - gconditional_effects = FALSE; - for ( a = gactions; a; a = a->next ) { - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - if ( e->num_conditions > 0 ) { - break; - } - if ( e->num_lnf_conditions > 0 ) { - break; - } - } - if ( i < a->num_effects ) break; - } - if ( a ) { - printf("\n\ntask contains conditional effects. turning off state domination.\n\n"); - gconditional_effects = TRUE; - } - - n_op = 0; - n_ef = 0; - for ( a = gactions; a; a = a->next ) { - gop_conn[n_op].action = a; - gop_conn[n_op].axiom = a->axiom; - if ( a->num_effects == 0 ) { - continue; - } - - gop_conn[n_op].E = ( int * ) calloc( a->num_effects, sizeof( int ) ); - for ( i = 0; i < a->num_effects; i++ ) { - e = &(a->effects[i]); - gef_conn[n_ef].cost = e->cost; - if ( e->removed ) { - /* this one disappeared through summarization - */ - continue; - } - gop_conn[n_op].E[gop_conn[n_op].num_E++] = n_ef; - gef_conn[n_ef].op = n_op; - if ( e->illegal ) { - gef_conn[n_ef].illegal = TRUE; - } - - /*****************************CONDS********************************/ - gef_conn[n_ef].PC = ( int * ) - calloc( e->num_conditions + a->num_preconds, sizeof( int ) ); - for ( j = 0; j < a->num_preconds; j++ ) { - for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { - if ( gef_conn[n_ef].PC[k] == a->preconds[j] ) break; - } - if ( k < gef_conn[n_ef].num_PC ) continue; - gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = a->preconds[j]; - } - for ( j = 0; j < e->num_conditions; j++ ) { - for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { - if ( gef_conn[n_ef].PC[k] == e->conditions[j] ) break; - } - if ( k < gef_conn[n_ef].num_PC ) continue; - gef_conn[n_ef].PC[gef_conn[n_ef].num_PC++] = e->conditions[j]; - } - /* similar thing for numeric conditions. - */ - gef_conn[n_ef].f_PC_comp = ( Comparator * ) - calloc( e->num_lnf_conditions + a->num_lnf_preconds, sizeof( Comparator ) ); - gef_conn[n_ef].f_PC_fl = ( int * ) - calloc( e->num_lnf_conditions + a->num_lnf_preconds, sizeof( int ) ); - gef_conn[n_ef].f_PC_c = ( float * ) - calloc( e->num_lnf_conditions + a->num_lnf_preconds, sizeof( float ) ); - gef_conn[n_ef].f_PC_direct_comp = ( Comparator * ) calloc( gnum_fl_conn, sizeof( Comparator ) ); - for ( j = 0; j < gnum_fl_conn; j++ ) { - gef_conn[n_ef].f_PC_direct_comp[j] = IGUAL; - } - gef_conn[n_ef].f_PC_direct_c = ( float * ) calloc( gnum_fl_conn, sizeof( float ) ); - for ( j = 0; j < a->num_lnf_preconds; j++ ) { - if ( a->lnf_preconds_lh[j]->num_pF != 1 ) { - printf("\n\nnon 1 card. in comp lh final pre copyover.\n\n"); - exit( 1 ); - } - for ( k = 0; k < gef_conn[n_ef].num_f_PC; k++ ) { - if ( gef_conn[n_ef].f_PC_fl[k] == a->lnf_preconds_lh[j]->pF[0] ) break; - } - if ( k < gef_conn[n_ef].num_f_PC ) { - if ( a->lnf_preconds_rh[j] < gef_conn[n_ef].f_PC_c[k] ) { - /* weaker cond - */ - continue; - } - if ( a->lnf_preconds_rh[j] > gef_conn[n_ef].f_PC_c[k] ) { - /* stronger cond - */ - gef_conn[n_ef].f_PC_c[k] = a->lnf_preconds_rh[j]; - gef_conn[n_ef].f_PC_comp[k] = a->lnf_preconds_comp[j]; - continue; - } - if ( a->lnf_preconds_comp[j] == GE ) { - /* we might need to strengthen our comp - */ - gef_conn[n_ef].f_PC_comp[k] = GE; - } - } else { - gef_conn[n_ef].f_PC_comp[gef_conn[n_ef].num_f_PC] = a->lnf_preconds_comp[j]; - gef_conn[n_ef].f_PC_fl[gef_conn[n_ef].num_f_PC] = a->lnf_preconds_lh[j]->pF[0]; - gef_conn[n_ef].f_PC_c[gef_conn[n_ef].num_f_PC++] = a->lnf_preconds_rh[j]; - } - } - for ( j = 0; j < e->num_lnf_conditions; j++ ) { - if ( e->lnf_conditions_lh[j]->num_pF != 1 ) { - printf("\n\nnon 1 card. in comp lh final cond copyover.\n\n"); - exit( 1 ); - } - for ( k = 0; k < gef_conn[n_ef].num_f_PC; k++ ) { - if ( gef_conn[n_ef].f_PC_fl[k] == e->lnf_conditions_lh[j]->pF[0] ) break; - } - if ( k < gef_conn[n_ef].num_f_PC ) { - if ( e->lnf_conditions_rh[j] < gef_conn[n_ef].f_PC_c[k] ) { - continue; - } - if ( e->lnf_conditions_rh[j] > gef_conn[n_ef].f_PC_c[k] ) { - gef_conn[n_ef].f_PC_c[k] = e->lnf_conditions_rh[j]; - gef_conn[n_ef].f_PC_comp[k] = e->lnf_conditions_comp[j]; - continue; - } - if ( e->lnf_conditions_comp[j] == GE ) { - gef_conn[n_ef].f_PC_comp[k] = GE; - } - } else { - gef_conn[n_ef].f_PC_comp[gef_conn[n_ef].num_f_PC] = e->lnf_conditions_comp[j]; - gef_conn[n_ef].f_PC_fl[gef_conn[n_ef].num_f_PC] = e->lnf_conditions_lh[j]->pF[0]; - gef_conn[n_ef].f_PC_c[gef_conn[n_ef].num_f_PC++] = e->lnf_conditions_rh[j]; - } - } - /* now arrange the direct access structures from that. - */ - for ( j = 0; j < gef_conn[n_ef].num_f_PC; j++ ) { - gef_conn[n_ef].f_PC_direct_comp[gef_conn[n_ef].f_PC_fl[j]] = gef_conn[n_ef].f_PC_comp[j]; - gef_conn[n_ef].f_PC_direct_c[gef_conn[n_ef].f_PC_fl[j]] = gef_conn[n_ef].f_PC_c[j]; - } - /*****************************CONDS - END********************************/ - - - if ( e->illegal ) { - /* we don't care about the effects if they're illegal - - * all we care about is whether the condition is true or not. - */ - n_ef++; - gnum_ef_conn++; - continue; - } - /*****************************EFFECTS********************************/ - gef_conn[n_ef].A = ( int * ) calloc( e->num_adds, sizeof( int ) ); - gef_conn[n_ef].D = ( int * ) calloc( e->num_dels, sizeof( int ) ); - gef_conn[n_ef].IN_fl = ( int * ) calloc( e->num_lnf_effects, sizeof( int ) ); - gef_conn[n_ef].IN_fl_ = ( int * ) calloc( e->num_lnf_effects, sizeof( int ) ); - gef_conn[n_ef].IN_c = ( float * ) calloc( e->num_lnf_effects, sizeof( float ) ); - gef_conn[n_ef].AS_fl = ( int * ) calloc( e->num_lnf_effects, sizeof( int ) ); - gef_conn[n_ef].AS_fl_ = ( int * ) calloc( e->num_lnf_effects, sizeof( int ) ); - gef_conn[n_ef].AS_c = ( float * ) calloc( e->num_lnf_effects, sizeof( float ) ); - - /* duplicates removed in summarize already. - * - * but don't include adds that are in the conds. - * --- those are true anyway. - * - * and don't include dels that are in the adds - * --- those will be re-added anyway. - * - * NOTE: it is important that we use the *original* add list - * not the already reduced one, for the delete check! - * otherwise it may be that a delete that's in the add - * and also in the cond stays in! - * - * IT IS ALSO IMPORTANT THAT WE DO BOTH!!!, i.e. if we do - * the ads reduction then we *must* also do the dels - * reduction to avoid that things are deleted that - * would otherwise have been re-added. - */ - for ( j = 0; j < e->num_adds; j++ ) { - for ( k = 0; k < gef_conn[n_ef].num_PC; k++ ) { - if ( gef_conn[n_ef].PC[k] == e->adds[j] ) break; - } - if ( k < gef_conn[n_ef].num_PC ) continue; - gef_conn[n_ef].A[gef_conn[n_ef].num_A++] = e->adds[j]; - } - for ( j = 0; j < e->num_dels; j++ ) { - for ( k = 0; k < e->num_adds; k++ ) { - if ( e->adds[k] == e->dels[j] ) break; - } - if ( k < e->num_adds ) continue; - gef_conn[n_ef].D[gef_conn[n_ef].num_D++] = e->dels[j]; - } - - /* numeric part - */ - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_neft[j] != INCREASE ) continue; - gef_conn[n_ef].IN_fl[gef_conn[n_ef].num_IN] = e->lnf_effects_fl[j]; - if ( e->lnf_effects_rh[j]->num_pF == 1 ) { - if ( e->lnf_effects_rh[j]->pF[0] < 0 ) { - printf("\n\nnon-relevant fluent in final copying to conn.\n\n"); - exit( 1 ); - } - gef_conn[n_ef].IN_fl_[gef_conn[n_ef].num_IN] = e->lnf_effects_rh[j]->pF[0]; - } else { - if ( e->lnf_effects_rh[j]->num_pF != 0 ) { - printf("\n\nnon-1 or 0 number of fl_ in copying to conn\n\n"); - exit( 1 ); - } - gef_conn[n_ef].IN_fl_[gef_conn[n_ef].num_IN] = -1; - } - gef_conn[n_ef].IN_c[gef_conn[n_ef].num_IN++] = e->lnf_effects_rh[j]->c; - } - /* now remove increasers by nothing. - */ - j = 0; - while ( j < gef_conn[n_ef].num_IN ) { - if ( gef_conn[n_ef].IN_fl_[j] != -1 || - gef_conn[n_ef].IN_c[j] != 0 ) { - j++; - continue; - } - for ( k = j; k < gef_conn[n_ef].num_IN - 1; k++ ) { - gef_conn[n_ef].IN_fl[k] = gef_conn[n_ef].IN_fl[k+1]; - gef_conn[n_ef].IN_fl_[k] = gef_conn[n_ef].IN_fl_[k+1]; - gef_conn[n_ef].IN_c[k] = gef_conn[n_ef].IN_c[k+1]; - } - gef_conn[n_ef].num_IN--; - } - /* now: the assigners... - */ - for ( j = 0; j < e->num_lnf_effects; j++ ) { - if ( e->lnf_effects_neft[j] != ASSIGN ) continue; - gef_conn[n_ef].AS_fl[gef_conn[n_ef].num_AS] = e->lnf_effects_fl[j]; - if ( e->lnf_effects_rh[j]->num_pF == 1 ) { - if ( e->lnf_effects_rh[j]->pF[0] < 0 ) { - printf("\n\nnon-relevant fluent in final copying to conn.\n\n"); - exit( 1 ); - } - gef_conn[n_ef].AS_fl_[gef_conn[n_ef].num_AS] = e->lnf_effects_rh[j]->pF[0]; - } else { - if ( e->lnf_effects_rh[j]->num_pF != 0 ) { - printf("\n\nnon-1 or 0 number of fl_ in copying to conn\n\n"); - exit( 1 ); - } - gef_conn[n_ef].AS_fl_[gef_conn[n_ef].num_AS] = -1; - } - gef_conn[n_ef].AS_c[gef_conn[n_ef].num_AS++] = e->lnf_effects_rh[j]->c; - } - /*****************************EFFECTS - END********************************/ - - n_ef++; - gnum_ef_conn++; - }/* end all a->effects */ - - - /*****************************EMPTY EFFECTS********************************/ - if ( gop_conn[n_op].num_E >= 1 ) { - /* CHECK EMPTY EFFECTS! - * - * two step process --- first, remove all effects that are entirely empty. - * second, check if all remaining effects are illegal - * or only delete: - * in that case, the op will never do any good so we - * remove all its effects. - */ - i = 0; - while ( i < gop_conn[n_op].num_E ) { - /* illegal effects *must* stay in!!! - */ - if ( gef_conn[gop_conn[n_op].E[i]].illegal ) { - i++; - continue; - } - if ( gef_conn[gop_conn[n_op].E[i]].num_A != 0 || - gef_conn[gop_conn[n_op].E[i]].num_D != 0 || - gef_conn[gop_conn[n_op].E[i]].num_IN != 0 || - gef_conn[gop_conn[n_op].E[i]].num_AS != 0 ) { - i++; - continue; - } - /* we keep it in the gef_conn (seems easier), - * but mark it as removed, which will exclude it from everything. - */ - gef_conn[gop_conn[n_op].E[i]].removed = TRUE; - for ( j = i; j < gop_conn[n_op].num_E - 1; j++ ) { - gop_conn[n_op].E[j] = gop_conn[n_op].E[j+1]; - } - gop_conn[n_op].num_E--; - } - - m = 0; - for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { - if ( gef_conn[gop_conn[n_op].E[i]].illegal ) { - m++; - continue; - } - if ( gef_conn[gop_conn[n_op].E[i]].num_A == 0 && - gef_conn[gop_conn[n_op].E[i]].num_IN == 0 && - gef_conn[gop_conn[n_op].E[i]].num_AS == 0 ) { - m++; - } - } - if ( m == gop_conn[n_op].num_E ) { - /* all remaining effects illegal or solely-deleters. - */ - for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { - gef_conn[gop_conn[n_op].E[i]].removed = TRUE; - } - gop_conn[n_op].num_E = 0; - } - } - /*****************************EMPTY EFFECTS - END********************************/ - - - /*****************************IMPLIED EFFECTS********************************/ - if ( gop_conn[n_op].num_E > 1 ) { - for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { - ef = gop_conn[n_op].E[i]; - gef_conn[ef].I = ( int * ) calloc( gop_conn[n_op].num_E, sizeof( int ) ); - gef_conn[ef].num_I = 0; - } - for ( i = 0; i < gop_conn[n_op].num_E - 1; i++ ) { - ef = gop_conn[n_op].E[i]; - for ( j = i+1; j < gop_conn[n_op].num_E; j++ ) { - ef_ = gop_conn[n_op].E[j]; - /* ef ==> ef_ ? */ - for ( k = 0; k < gef_conn[ef_].num_PC; k++ ) { - for ( l = 0; l < gef_conn[ef].num_PC; l++ ) { - if ( gef_conn[ef].PC[l] == gef_conn[ef_].PC[k] ) break; - } - if ( l == gef_conn[ef].num_PC ) break; - } - if ( k == gef_conn[ef_].num_PC ) { - for ( k = 0; k < gnum_fl_conn; k++ ) { - if ( gef_conn[ef_].f_PC_direct_comp[k] == IGUAL ) continue; - if ( gef_conn[ef].f_PC_direct_comp[k] == IGUAL || - gef_conn[ef].f_PC_direct_c[k] < gef_conn[ef_].f_PC_direct_c[k] || - ( gef_conn[ef].f_PC_direct_c[k] == gef_conn[ef_].f_PC_direct_c[k] && - gef_conn[ef].f_PC_direct_comp[k] == GEQ && - gef_conn[ef_].f_PC_direct_comp[k] == GE ) ) break; - } - if ( k == gnum_fl_conn ) { - gef_conn[ef].I[gef_conn[ef].num_I++] = ef_; - } - } - /* ef_ ==> ef ? */ - for ( k = 0; k < gef_conn[ef].num_PC; k++ ) { - for ( l = 0; l < gef_conn[ef_].num_PC; l++ ) { - if ( gef_conn[ef_].PC[l] == gef_conn[ef].PC[k] ) break; - } - if ( l == gef_conn[ef_].num_PC ) break; - } - if ( k == gef_conn[ef].num_PC ) { - for ( k = 0; k < gnum_fl_conn; k++ ) { - if ( gef_conn[ef].f_PC_direct_comp[k] == IGUAL ) continue; - if ( gef_conn[ef_].f_PC_direct_comp[k] == IGUAL || - gef_conn[ef_].f_PC_direct_c[k] < gef_conn[ef].f_PC_direct_c[k] || - ( gef_conn[ef_].f_PC_direct_c[k] == gef_conn[ef].f_PC_direct_c[k] && - gef_conn[ef_].f_PC_direct_comp[k] == GEQ && - gef_conn[ef].f_PC_direct_comp[k] == GE ) ) break; - } - if ( k == gnum_fl_conn ) { - gef_conn[ef_].I[gef_conn[ef_].num_I++] = ef; - } - } - } - } - } - /*****************************IMPLIED EFFECTS - END********************************/ - - /* op cost is sum of eff costs + gtt*1: - * [gtt is multiplicator of TOTAL-TIME in final metric; if no - * total-time part in metric, it is 0] - * ie eff-costs plus the cost for the time taken by 1 more step. - */ - gop_conn[n_op].cost = gtt; - if ( gop_conn[n_op].num_E > 0 ) { - for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { - ef = gop_conn[n_op].E[i]; - if ( gef_conn[ef].illegal ) { - continue; - } - if ( gef_conn[ef].removed ) { - continue; - } - gop_conn[n_op].cost += gef_conn[ef].cost; - } - } - - /* first sweep: only count the space we need for the fact arrays ! - */ - if ( gop_conn[n_op].num_E > 0 ) { - for ( i = 0; i < gop_conn[n_op].num_E; i++ ) { - ef = gop_conn[n_op].E[i]; - for ( j = 0; j < gef_conn[ef].num_PC; j++ ) { - gft_conn[gef_conn[ef].PC[j]].num_PC++; - } - for ( j = 0; j < gef_conn[ef].num_A; j++ ) { - gft_conn[gef_conn[ef].A[j]].num_A++; - if ( gop_conn[n_op].axiom ) { - gft_conn[gef_conn[ef].A[j]].axiom_added = TRUE; - } - } - for ( j = 0; j < gef_conn[ef].num_D; j++ ) { - gft_conn[gef_conn[ef].D[j]].num_D++; - } - /* similar increments for flconn - */ - for ( j = 0; j < gef_conn[ef].num_f_PC; j++ ) { - gfl_conn[gef_conn[ef].f_PC_fl[j]].num_PC++; - } - for ( j = 0; j < gef_conn[ef].num_IN; j++ ) { - gfl_conn[gef_conn[ef].IN_fl[j]].num_IN++; - } - for ( j = 0; j < gef_conn[ef].num_AS; j++ ) { - gfl_conn[gef_conn[ef].AS_fl[j]].num_AS++; - } - } - } - - - n_op++; - } - - /*****************************FLCONN********************************/ - for ( i = 0; i < gnum_ft_conn; i++ ) { - if ( gft_conn[i].num_PC > 0 ) { - gft_conn[i].PC = ( int * ) calloc( gft_conn[i].num_PC, sizeof( int ) ); - } - gft_conn[i].num_PC = 0; - if ( gft_conn[i].num_A > 0 ) { - gft_conn[i].A = ( int * ) calloc( gft_conn[i].num_A, sizeof( int ) ); - } - gft_conn[i].num_A = 0; - if ( gft_conn[i].num_D > 0 ) { - gft_conn[i].D = ( int * ) calloc( gft_conn[i].num_D, sizeof( int ) ); - } - gft_conn[i].num_D = 0; - } - for ( i = 0; i < gnum_ef_conn; i++ ) { - if ( gef_conn[i].removed ) continue; - for ( j = 0; j < gef_conn[i].num_PC; j++ ) { - gft_conn[gef_conn[i].PC[j]].PC[gft_conn[gef_conn[i].PC[j]].num_PC++] = i; - } - for ( j = 0; j < gef_conn[i].num_A; j++ ) { - gft_conn[gef_conn[i].A[j]].A[gft_conn[gef_conn[i].A[j]].num_A++] = i; - } - for ( j = 0; j < gef_conn[i].num_D; j++ ) { - gft_conn[gef_conn[i].D[j]].D[gft_conn[gef_conn[i].D[j]].num_D++] = i; - } - } - /*****************************FTCONN - END********************************/ - - - /*****************************FLCONN********************************/ - /* similar thing for flconn - */ - for ( i = 0; i < gnum_fl_conn; i++ ) { - if ( gfl_conn[i].num_PC > 0 ) { - gfl_conn[i].PC = ( int * ) calloc( gfl_conn[i].num_PC, sizeof( int ) ); - } - gfl_conn[i].num_PC = 0; - if ( gfl_conn[i].num_IN > 0 ) { - gfl_conn[i].IN = ( int * ) calloc( gfl_conn[i].num_IN, sizeof( int ) ); - gfl_conn[i].IN_fl_ = ( int * ) calloc( gfl_conn[i].num_IN, sizeof( int ) ); - gfl_conn[i].IN_c = ( float * ) calloc( gfl_conn[i].num_IN, sizeof( float ) ); - } - gfl_conn[i].num_IN = 0; - if ( gfl_conn[i].num_AS > 0 ) { - gfl_conn[i].AS = ( int * ) calloc( gfl_conn[i].num_AS, sizeof( int ) ); - gfl_conn[i].AS_fl_ = ( int * ) calloc( gfl_conn[i].num_AS, sizeof( int ) ); - gfl_conn[i].AS_c = ( float * ) calloc( gfl_conn[i].num_AS, sizeof( float ) ); - } - gfl_conn[i].num_AS = 0; - } - for ( i = 0; i < gnum_ef_conn; i++ ) { - if ( gef_conn[i].removed ) continue; - /* PCs - */ - for ( j = 0; j < gef_conn[i].num_f_PC; j++ ) { - fl = gef_conn[i].f_PC_fl[j]; - gfl_conn[fl].PC[gfl_conn[fl].num_PC++] = i; - } - /* insert increasers by decreasing amount --> - * "best" - at least for constant part - are first! - */ - for ( j = 0; j < gef_conn[i].num_IN; j++ ) { - fl = gef_conn[i].IN_fl[j]; - val = gef_conn[i].IN_c[j]; - for ( k = 0; k < gfl_conn[fl].num_IN; k++ ) { - if ( gfl_conn[fl].IN_c[k] < val ) break; - } - for ( l = gfl_conn[fl].num_IN; l > k; l-- ) { - gfl_conn[fl].IN[l] = gfl_conn[fl].IN[l-1]; - gfl_conn[fl].IN_fl_[l] = gfl_conn[fl].IN_fl_[l-1]; - gfl_conn[fl].IN_c[l] = gfl_conn[fl].IN_c[l-1]; - } - gfl_conn[fl].IN[k] = i; - gfl_conn[fl].IN_fl_[k] = gef_conn[i].IN_fl_[j];/* the rh fluent */ - gfl_conn[fl].IN_c[k] = val; - gfl_conn[fl].num_IN++; - } - /* insert assigners by decreasing amount --> - * "best" - at least for constant part - are first! - */ - for ( j = 0; j < gef_conn[i].num_AS; j++ ) { - fl = gef_conn[i].AS_fl[j]; - val = gef_conn[i].AS_c[j]; - for ( k = 0; k < gfl_conn[fl].num_AS; k++ ) { - if ( gfl_conn[fl].AS_c[k] < val ) break; - } - for ( l = gfl_conn[fl].num_AS; l > k; l-- ) { - gfl_conn[fl].AS[l] = gfl_conn[fl].AS[l-1]; - gfl_conn[fl].AS_fl_[l] = gfl_conn[fl].AS_fl_[l-1]; - gfl_conn[fl].AS_c[l] = gfl_conn[fl].AS_c[l-1]; - } - gfl_conn[fl].AS[k] = i; - gfl_conn[fl].AS_fl_[k] = gef_conn[i].AS_fl_[j];/* the rh fluent */ - gfl_conn[fl].AS_c[k] = val; - gfl_conn[fl].num_AS++; - } - } - /*****************************FLCONN - END********************************/ - - - /*****************************GOAL********************************/ - gflogic_goal = ( int * ) calloc( gnum_logic_goal, sizeof( int ) ); - for ( j = 0; j < gnum_logic_goal; j++ ) { - for ( k = 0; k < gnum_flogic_goal; k++ ) { - if ( gflogic_goal[k] == glogic_goal[j] ) break; - } - if ( k < gnum_flogic_goal ) continue; - gflogic_goal[gnum_flogic_goal++] = glogic_goal[j]; - } - /* numeric part - */ - gfnumeric_goal_comp = ( Comparator * ) calloc( gnum_lnf_goal, sizeof( Comparator ) ); - gfnumeric_goal_fl = ( int * ) calloc( gnum_lnf_goal, sizeof( int ) ); - gfnumeric_goal_c = ( float * ) calloc( gnum_lnf_goal, sizeof( float ) ); - for ( j = 0; j < gnum_lnf_goal; j++ ) { - if ( glnf_goal_lh[j]->num_pF != 1 ) { - printf("\n\nnon 1 card. in comp lh final goal copyover.\n\n"); - exit( 1 ); - } - for ( k = 0; k < gnum_fnumeric_goal; k++ ) { - if ( gfnumeric_goal_fl[k] == glnf_goal_lh[j]->pF[0] ) break; - } - if ( k < gnum_fnumeric_goal ) { - if ( glnf_goal_rh[j] < gfnumeric_goal_c[k] ) continue; - if ( glnf_goal_rh[j] > gfnumeric_goal_c[k] ) { - gfnumeric_goal_comp[k] = glnf_goal_comp[j]; - gfnumeric_goal_c[k] = glnf_goal_rh[j]; - continue; - } - if ( glnf_goal_comp[j] == GE ) { - gfnumeric_goal_comp[k] = GE; - } - } else { - gfnumeric_goal_comp[gnum_fnumeric_goal] = glnf_goal_comp[j]; - gfnumeric_goal_fl[gnum_fnumeric_goal] = glnf_goal_lh[j]->pF[0]; - gfnumeric_goal_c[gnum_fnumeric_goal++] = glnf_goal_rh[j]; - } - } - gfnumeric_goal_direct_comp = ( Comparator * ) calloc( gnum_fl_conn, sizeof( Comparator ) ); - for ( j = 0; j < gnum_fl_conn; j++ ) { - gfnumeric_goal_direct_comp[j] = IGUAL; - } - gfnumeric_goal_direct_c = ( float * ) calloc( gnum_fl_conn, sizeof( float ) ); - for ( k = 0; k < gnum_fnumeric_goal; k++ ) { - gfnumeric_goal_direct_comp[gfnumeric_goal_fl[k]] = gfnumeric_goal_comp[k]; - gfnumeric_goal_direct_c[gfnumeric_goal_fl[k]] = gfnumeric_goal_c[k]; - } - /*****************************GOAL - END********************************/ - - - - /******************** - * safety: if there are numeric precs/goals, need to turn - * cost-minimizing rplans off!!! - * (see comments with def of gcost_rplans - */ - for ( i = 0; i < gnum_ef_conn; i++ ) { - if ( gcost_rplans && gef_conn[i].num_f_PC > 0 ) { - printf("\nwarning: numeric precondition. turning cost-minimizing relaxed plans OFF."); - gcost_rplans = FALSE; - break; - } - } - if ( gcost_rplans && gnum_fnumeric_goal > 0 ) { - printf("\nwarning: numeric goal. turning cost-minimizing relaxed plans OFF."); - gcost_rplans = FALSE; - } - - - - - if ( gcmd_line.display_info == 125 ) { - printf("\n\ncreated connectivity graph as follows:"); - - printf("\n\n------------------OP ARRAY:-----------------------"); - for ( i = 0; i < gnum_op_conn; i++ ) { - printf("\n\nOP %d: ", i); - if ( gop_conn[i].axiom ) printf("(axiom) "); - print_op_name( i ); - printf(" cost %f", gop_conn[i].cost); - printf("\n----------EFFS:"); - for ( j = 0; j < gop_conn[i].num_E; j++ ) { - printf("\neffect %d", gop_conn[i].E[j]); - } - } - - printf("\n\n-------------------EFFECT ARRAY:----------------------"); - for ( i = 0; i < gnum_ef_conn; i++ ) { - printf("\n\neffect %d of op %d cost %f: ", i, gef_conn[i].op, gef_conn[i].cost); - print_op_name( gef_conn[i].op ); - if ( gef_conn[i].illegal ) printf(" ******ILLEGAL************************"); - if ( gef_conn[i].removed ) printf(" ******REMOVED************************"); - printf("\n----------PCS:"); - for ( j = 0; j < gef_conn[i].num_PC; j++ ) { - printf("\n"); - print_ft_name( gef_conn[i].PC[j] ); - } - printf("\n----------f_PCS:"); - for ( j = 0; j < gef_conn[i].num_f_PC; j++ ) { - printf("\n"); - print_fl_name( gef_conn[i].f_PC_fl[j] ); - if ( gef_conn[i].f_PC_comp[j] == GEQ ) { - printf(" >= "); - } else { - printf(" > "); - } - printf("%f", gef_conn[i].f_PC_c[j]); - } - printf("\nDIRECT: "); - for ( j = 0; j < gnum_fl_conn; j++ ) { - if ( gef_conn[i].f_PC_direct_comp[j] == IGUAL ) { - printf("IGUAL | "); - } - if ( gef_conn[i].f_PC_direct_comp[j] == GEQ ) { - printf(">= %f | ", gef_conn[i].f_PC_direct_c[j]); - } - if ( gef_conn[i].f_PC_direct_comp[j] == GE ) { - printf("> %f | ", gef_conn[i].f_PC_direct_c[j]); - } - } - if ( gef_conn[i].illegal ) continue; - printf("\n----------ADDS:"); - for ( j = 0; j < gef_conn[i].num_A; j++ ) { - printf("\n"); - print_ft_name( gef_conn[i].A[j] ); - } - printf("\n----------DELS:"); - for ( j = 0; j < gef_conn[i].num_D; j++ ) { - printf("\n"); - print_ft_name( gef_conn[i].D[j] ); - } - printf("\n----------INCREASE:"); - for ( j = 0; j < gef_conn[i].num_IN; j++ ) { - printf("\n"); - print_fl_name( gef_conn[i].IN_fl[j] ); - printf(" by "); - if ( gef_conn[i].IN_fl_[j] >= 0 ) { - print_fl_name( gef_conn[i].IN_fl_[j] ); - printf(" + %f", gef_conn[i].IN_c[j]); - } else { - printf("%f", gef_conn[i].IN_c[j]); - } - } - printf("\n----------ASSIGN:"); - for ( j = 0; j < gef_conn[i].num_AS; j++ ) { - printf("\n"); - print_fl_name( gef_conn[i].AS_fl[j] ); - printf(" to "); - if ( gef_conn[i].AS_fl_[j] >= 0 ) { - print_fl_name( gef_conn[i].AS_fl_[j] ); - printf(" + %f", gef_conn[i].AS_c[j]); - } else { - printf("%f", gef_conn[i].AS_c[j]); - } - } - printf("\n----------IMPLIEDS:"); - for ( j = 0; j < gef_conn[i].num_I; j++ ) { - printf("\nimplied effect %d of op %d: ", - gef_conn[i].I[j], gef_conn[gef_conn[i].I[j]].op); - print_op_name( gef_conn[gef_conn[i].I[j]].op ); - } - } - - printf("\n\n----------------------FT ARRAY:-----------------------------"); - for ( i = 0; i < gnum_ft_conn; i++ ) { - printf("\n\nFT: "); - print_ft_name( i ); - printf(" rand: %d", gft_conn[i].rand); - printf(" --------- AXIOM ADDED %d", gft_conn[i].axiom_added); - printf("\n----------PRE COND OF:"); - for ( j = 0; j < gft_conn[i].num_PC; j++ ) { - printf("\neffect %d", gft_conn[i].PC[j]); - printf(" - op "); print_op_name( gef_conn[gft_conn[i].PC[j]].op ); - } - printf("\n----------ADD BY:"); - for ( j = 0; j < gft_conn[i].num_A; j++ ) { - printf("\neffect %d", gft_conn[i].A[j]); - printf(" - op "); print_op_name( gef_conn[gft_conn[i].A[j]].op ); - } - printf("\n----------DEL BY:"); - for ( j = 0; j < gft_conn[i].num_D; j++ ) { - printf("\neffect %d", gft_conn[i].D[j]); - printf(" - op "); print_op_name( gef_conn[gft_conn[i].D[j]].op ); - } - } - - printf("\n\n----------------------FLUENT ARRAY:-----------------------------"); - for ( i = 0; i < gnum_fl_conn; i++ ) { - printf("\n\nFL: "); - print_fl_name( i ); - printf("\n----------PRE COND OF:"); - for ( j = 0; j < gfl_conn[i].num_PC; j++ ) { - printf("\neffect %d", gfl_conn[i].PC[j]); - printf(" - op "); print_op_name( gef_conn[gfl_conn[i].PC[j]].op ); - } - printf("\n----------INCREASED BY:"); - for ( j = 0; j < gfl_conn[i].num_IN; j++ ) { - if ( gfl_conn[i].IN_fl_[j] == -1 ) { - printf("\neffect %d --- %f", gfl_conn[i].IN[j], gfl_conn[i].IN_c[j]); - printf(" --- op "); print_op_name( gef_conn[gfl_conn[i].IN[j]].op ); - } else { - printf("\neffect %d --- ", gfl_conn[i].IN[j]); - print_fl_name( gfl_conn[i].IN_fl_[j] ); - printf(" + %f", gfl_conn[i].IN_c[j]); - printf(" --- op "); print_op_name( gef_conn[gfl_conn[i].IN[j]].op ); - } - } - printf("\n----------ASSIGNED BY:"); - for ( j = 0; j < gfl_conn[i].num_AS; j++ ) { - if ( gfl_conn[i].AS_fl_[j] == -1 ) { - printf("\neffect %d --- %f", gfl_conn[i].AS[j], gfl_conn[i].AS_c[j]); - printf(" --- op "); print_op_name( gef_conn[gfl_conn[i].AS[j]].op ); - } else { - printf("\neffect %d --- ", gfl_conn[i].AS[j]); - print_fl_name( gfl_conn[i].AS_fl_[j] ); - printf(" + %f", gfl_conn[i].AS_c[j]); - printf(" --- op "); print_op_name( gef_conn[gfl_conn[i].AS[j]].op ); - } - } - if ( gfl_conn[i].artificial ) { - printf("\n----------ARTIFICIAL FOR:"); - for ( j = 0; j < gfl_conn[i].num_lnf; j++ ) { - printf(" %f*", gfl_conn[i].lnf_C[j]); - print_fl_name( gfl_conn[i].lnf_F[j] ); - if ( j < gfl_conn[i].num_lnf - 1 ) { - printf(" +"); - } - } - } else { - printf("\n----------REAL"); - } - } - - printf("\n\n----------------------GOAL:-----------------------------"); - for ( j = 0; j < gnum_flogic_goal; j++ ) { - printf("\n"); - print_ft_name( gflogic_goal[j] ); - } - for ( j = 0; j < gnum_fnumeric_goal; j++ ) { - printf("\n"); - print_fl_name( gfnumeric_goal_fl[j] ); - if ( gfnumeric_goal_comp[j] == GEQ ) { - printf(" >= "); - } else { - printf(" > "); - } - printf("%f", gfnumeric_goal_c[j]); - } - printf("\nDIRECT: "); - for ( j = 0; j < gnum_fl_conn; j++ ) { - if ( gfnumeric_goal_direct_comp[j] == IGUAL ) { - printf("IGUAL | "); - } - if ( gfnumeric_goal_direct_comp[j] == GEQ ) { - printf(">= %f | ", gfnumeric_goal_direct_c[j]); - } - if ( gfnumeric_goal_direct_comp[j] == GE ) { - printf("> %f | ", gfnumeric_goal_direct_c[j]); - } - } - - printf("\n\n"); - } - -} - - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.h deleted file mode 100644 index ab42b609..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_final.h +++ /dev/null @@ -1,69 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - -/********************************************************************* - * File: inst_final.h - * Description: headers for final domain representation functions - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - -#ifndef _INST_FINAL_H -#define _INST_FINAL_H - - - -void perform_reachability_analysis( void ); -int fact_adress( void ); -void make_name_inst_table_from_NormOperator( Action *a, NormOperator *o, EasyTemplate *t ); -void make_name_inst_table_from_PseudoAction( Action *a, PseudoAction *pa ); - - - -void collect_relevant_facts_and_fluents( void ); -void create_final_goal_state( void ); -Bool set_relevants_in_wff( WffNode **w ); -Bool set_relevants_in_exp( ExpNode **n ); -void create_final_initial_state( void ); -void create_final_actions( void ); -void instantiate_exp_by_action( ExpNode **n, Action *a ); - - - -void build_connectivity_graph( void ); - - - -void summarize_effects( void ); -Bool same_condition( ActionEffect *e, ActionEffect *e_ ); -Bool same_lnfs( LnfExpNode *l, LnfExpNode *r ); -void merge_effects( ActionEffect *e, ActionEffect *e_ ); - - - -#endif /* _INST_FINAL_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.c deleted file mode 100644 index 54f63d75..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.c +++ /dev/null @@ -1,1306 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - - -/********************************************************************* - * File: inst_hard.c - * Description: functions for multiplying hard operators. - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - -#include "inst_pre.h" -#include "inst_hard.h" - - - - - - - - - - - -/* used in multiplying routines - */ -int linst_table[MAX_VARS]; -int_pointer lini[MAX_PREDICATES]; - - - - - - - - -void build_hard_action_templates( void ) - -{ - - int i, j, size, adr; - MixedOperator *o; - - /* remove unused params; empty types are already recognised during - * domain translation; have to be handled after (or while) - * unaries encoding (if done), though. - */ - cleanup_hard_domain(); - - if ( gcmd_line.display_info == 115 ) { - printf("\n\ncleaned up hard domain representation is:\n\n"); - for ( i = 0; i < gnum_hard_operators; i++ ) { - print_Operator( ghard_operators[i] ); - } - fflush( stdout ); - } - - /* create local table of instantiated facts that occur in the - * initial state. for fast finding out if fact is in ini or not. - */ - for ( i = 0; i < gnum_predicates; i++ ) { - size = 1; - for ( j = 0; j < garity[i]; j++ ) { - size *= gnum_constants; - } - lini[i] = ( int_pointer ) calloc( size, sizeof( int ) ); - for ( j = 0; j < size; j++ ) { - lini[i][j] = 0; - } - for ( j = 0; j < gnum_initial_predicate[i]; j++ ) { - adr = instantiated_fact_adress( &ginitial_predicate[i][j] ); - lini[i][adr]++; - } - } - - - /* create mixed op for each param combination - */ - multiply_hard_op_parameters(); - - if ( gcmd_line.display_info == 116 ) { - printf("\n\nmixed hard domain representation is:\n\n"); - for ( o = ghard_mixed_operators; o; o = o->next ) { - print_MixedOperator( o ); - } - fflush( stdout ); - } - - /* create pseudo op for each mixed op - */ - multiply_hard_effect_parameters(); - - if ( gcmd_line.display_info == 117 ) { - printf("\n\npseudo hard domain representation is:\n\n"); - for ( i = 0; i < gnum_hard_templates; i++ ) { - print_PseudoAction( ghard_templates[i] ); - } - fflush( stdout ); - } - - -} - - - - - - - - - - - - -/**************** - * CLEANUP CODE * - ****************/ - - - - - - - - - - - - -void cleanup_hard_domain( void ) - -{ - - int i, j, k, par; - Operator *o; - Effect *e; - - /* so far, only unused parameters removal - */ - - for ( i = 0; i < gnum_hard_operators; i++ ) { - o = ghard_operators[i]; - - j = 0; - while ( j < o->num_vars ) { - if ( var_used_in_wff( ENCODE_VAR( j ), o->preconds ) ) { - j++; - continue; - } - - for ( e = o->effects; e; e = e->next ) { - if ( var_used_in_wff( ENCODE_VAR( j ), e->conditions ) ) { - break; - } - if ( var_used_in_literals( ENCODE_VAR( j ), e->effects ) ) { - break; - } - if ( var_used_in_numeric_effects( ENCODE_VAR( j ), e->numeric_effects ) ) { - break; - } - } - if ( e ) { - j++; - continue; - } - - o->removed[j] = TRUE; - j++; - } - - for ( e = o->effects; e; e = e->next ) { - j = 0; - while ( j < e->num_vars ) { - par = o->num_vars + j; - if ( var_used_in_wff( ENCODE_VAR( par ), e->conditions ) ) { - j++; - continue; - } - if ( var_used_in_literals( ENCODE_VAR( par ), e->effects ) ) { - j++; - continue; - } - if ( var_used_in_numeric_effects( ENCODE_VAR( par ), e->numeric_effects ) ) { - j++; - continue; - } - - if ( e->var_names[j] ) { - free( e->var_names[j] ); - } - for ( k = j; k < e->num_vars - 1; k++ ) { - e->var_names[k] = e->var_names[k+1]; - e->var_names[k] = e->var_names[k+1]; - } - e->num_vars--; - decrement_inferior_vars( par, e->conditions ); - decrement_inferior_vars_in_literals( par, e->effects ); - decrement_inferior_vars_in_numeric_effects( par, e->numeric_effects ); - } - } - } - -} - - - -Bool var_used_in_literals( int code_var, Literal *ef ) - -{ - - Literal *l; - int i; - - for ( l = ef; l; l = l->next ) { - for ( i = 0; i < garity[l->fact.predicate]; i++ ) { - if ( l->fact.args[i] == code_var ) { - return TRUE; - } - } - } - - return FALSE; - -} - - - -Bool var_used_in_numeric_effects( int code_var, NumericEffect *ef ) - -{ - - NumericEffect *l; - int i; - - for ( l = ef; l; l = l->next ) { - for ( i = 0; i < gf_arity[l->fluent.function]; i++ ) { - if ( l->fluent.args[i] == code_var ) { - return TRUE; - } - } - if ( var_used_in_exp( code_var, l->rh ) ) { - return TRUE; - } - } - - return FALSE; - -} - - - -void decrement_inferior_vars_in_literals( int var, Literal *ef ) - -{ - - Literal *l; - int i; - - for ( l = ef; l; l = l->next ) { - for ( i = 0; i < garity[l->fact.predicate]; i++ ) { - if ( l->fact.args[i] >= 0 ) { - continue; - } - if ( DECODE_VAR( l->fact.args[i] ) > var ) { - l->fact.args[i]++; - } - } - } - -} - - - -void decrement_inferior_vars_in_numeric_effects( int var, NumericEffect *ef ) - -{ - - NumericEffect *l; - int i; - - for ( l = ef; l; l = l->next ) { - for ( i = 0; i < gf_arity[l->fluent.function]; i++ ) { - if ( l->fluent.args[i] >= 0 ) { - continue; - } - if ( DECODE_VAR( l->fluent.args[i] ) > var ) { - l->fluent.args[i]++; - } - } - decrement_inferior_vars_in_exp( var, l->rh ); - } - -} - - - - - - - - - - - - - - -/****************************** - * CODE THAT BUILDS MIXED OPS * - ******************************/ - - - - - - - - - - - - - - -void multiply_hard_op_parameters( void ) - -{ - - int i; - - ghard_mixed_operators = NULL; - - for ( i = 0; i < MAX_VARS; i++ ) { - linst_table[i] = -1; - } - - for ( i = 0; i < gnum_hard_operators; i++ ) { - create_hard_mixed_operators( ghard_operators[i], 0 ); - } - -} - - - -void create_hard_mixed_operators( Operator *o, int curr_var ) - -{ - - int t, i, m, mn; - WffNode *tmp1, *w, *ww; - MixedOperator *tmp2; - - if ( curr_var < o->num_vars ) { - if ( o->removed[curr_var] ) { - /* param doesn't matter -- select any appropriate type constant - * at least one there; otherwise, op would not have been translated. - */ - linst_table[curr_var] = gtype_consts[o->var_types[curr_var]][0]; - create_hard_mixed_operators( o, curr_var + 1 ); - linst_table[curr_var] = -1; - return; - } - - t = o->var_types[curr_var]; - for ( i = 0; i < gtype_size[t]; i++ ) { - linst_table[curr_var] = gtype_consts[t][i]; - - create_hard_mixed_operators( o, curr_var + 1 ); - - linst_table[curr_var] = -1; - } - return; - } - - - tmp1 = instantiate_wff( o->preconds ); - - if ( tmp1->connective == FAL ) { - free_WffNode( tmp1 ); - return; - } - - dnf( &tmp1 ); - cleanup_wff( &tmp1 ); - - if ( tmp1->connective == FAL ) { - free_WffNode( tmp1 ); - return; - } - - /* only debugging, REMOVE LATER - */ - if ( is_dnf( tmp1 ) == -1 ) { - printf("\n\nILLEGAL DNF %s AFTER INSTANTIATION\n\n", o->name); - print_Wff( tmp1, 0 ); - exit( 1 ); - } - - switch ( tmp1->connective ) { - case OR: - for ( w = tmp1->sons; w; w = w->next ) { - tmp2 = new_MixedOperator( o ); - for ( i = 0; i < o->num_vars; i++ ) { - tmp2->inst_table[i] = linst_table[i]; - } - if ( w->connective == AND ) { - m = 0; - mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) m++; - if ( ww->connective == COMP ) mn++; - } - tmp2->preconds = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp2->numeric_preconds_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp2->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->num_preconds = m; - tmp2->num_numeric_preconds = mn; - m = 0; mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) { - tmp2->preconds[m].predicate = ww->fact->predicate; - for ( i = 0; i < garity[ww->fact->predicate]; i++ ) { - tmp2->preconds[m].args[i] = ww->fact->args[i]; - } - m++; - } - if ( ww->connective == COMP ) { - tmp2->numeric_preconds_comp[mn] = ww->comp; - tmp2->numeric_preconds_lh[mn] = copy_Exp( ww->lh ); - tmp2->numeric_preconds_rh[mn] = copy_Exp( ww->rh ); - mn++; - } - } - } else { - if ( w->connective == ATOM ) { - tmp2->preconds = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp2->num_preconds = 1; - tmp2->preconds[0].predicate = w->fact->predicate; - for ( i = 0; i < garity[w->fact->predicate]; i++ ) { - tmp2->preconds[0].args[i] = w->fact->args[i]; - } - } - if ( w->connective == COMP ) { - tmp2->numeric_preconds_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp2->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_comp[0] = w->comp; - tmp2->numeric_preconds_lh[0] = copy_Exp( w->lh ); - tmp2->numeric_preconds_rh[0] = copy_Exp( w->rh ); - tmp2->num_numeric_preconds = 1; - } - } - tmp2->effects = instantiate_Effect( o->effects ); - tmp2->next = ghard_mixed_operators; - ghard_mixed_operators = tmp2; - gnum_hard_mixed_operators++; - } - break; - case AND: - tmp2 = new_MixedOperator( o ); - for ( i = 0; i < o->num_vars; i++ ) { - tmp2->inst_table[i] = linst_table[i]; - } - m = 0; - mn = 0; - for ( w = tmp1->sons; w; w = w->next ) { - if ( w->connective == ATOM ) m++; - if ( w->connective == COMP ) mn++; - } - tmp2->preconds = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp2->numeric_preconds_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp2->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->num_preconds = m; - tmp2->num_numeric_preconds = mn; - m = 0; mn = 0; - for ( w = tmp1->sons; w; w = w->next ) { - if ( w->connective == ATOM ) { - tmp2->preconds[m].predicate = w->fact->predicate; - for ( i = 0; i < garity[w->fact->predicate]; i++ ) { - tmp2->preconds[m].args[i] = w->fact->args[i]; - } - m++; - } - if ( w->connective == COMP ) { - tmp2->numeric_preconds_comp[mn] = w->comp; - tmp2->numeric_preconds_lh[mn] = copy_Exp( w->lh ); - tmp2->numeric_preconds_rh[mn] = copy_Exp( w->rh ); - mn++; - } - } - tmp2->effects = instantiate_Effect( o->effects ); - tmp2->next = ghard_mixed_operators; - ghard_mixed_operators = tmp2; - gnum_hard_mixed_operators++; - break; - case ATOM: - tmp2 = new_MixedOperator( o ); - for ( i = 0; i < o->num_vars; i++ ) { - tmp2->inst_table[i] = linst_table[i]; - } - tmp2->preconds = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp2->num_preconds = 1; - tmp2->preconds[0].predicate = tmp1->fact->predicate; - for ( i = 0; i < garity[tmp1->fact->predicate]; i++ ) { - tmp2->preconds[0].args[i] = tmp1->fact->args[i]; - } - tmp2->effects = instantiate_Effect( o->effects ); - tmp2->next = ghard_mixed_operators; - ghard_mixed_operators = tmp2; - gnum_hard_mixed_operators++; - break; - case COMP: - tmp2 = new_MixedOperator( o ); - for ( i = 0; i < o->num_vars; i++ ) { - tmp2->inst_table[i] = linst_table[i]; - } - tmp2->numeric_preconds_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp2->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_preconds_comp[0] = tmp1->comp; - tmp2->numeric_preconds_lh[0] = copy_Exp( tmp1->lh ); - tmp2->numeric_preconds_rh[0] = copy_Exp( tmp1->rh ); - tmp2->num_numeric_preconds = 1; - tmp2->effects = instantiate_Effect( o->effects ); - tmp2->next = ghard_mixed_operators; - ghard_mixed_operators = tmp2; - gnum_hard_mixed_operators++; - break; - case TRU: - tmp2 = new_MixedOperator( o ); - for ( i = 0; i < o->num_vars; i++ ) { - tmp2->inst_table[i] = linst_table[i]; - } - tmp2->effects = instantiate_Effect( o->effects ); - tmp2->next = ghard_mixed_operators; - ghard_mixed_operators = tmp2; - gnum_hard_mixed_operators++; - break; - default: - printf("\n\nillegal connective %d in parsing DNF precond.\n\n", - tmp1->connective); - exit( 1 ); - } - - free_WffNode( tmp1 ); - -} - - - -Effect *instantiate_Effect( Effect *e ) - -{ - - Effect *res = NULL, *tmp, *i; - Literal *tt, *l; - NumericEffect *ne, *ttt; - int j; - - for ( i = e; i; i = i->next ) { - tmp = new_Effect(); - - for ( j = 0; j < i->num_vars; j++ ) { - tmp->var_types[j] = i->var_types[j]; - } - tmp->num_vars = i->num_vars; - - tmp->conditions = instantiate_wff( i->conditions ); - - if ( tmp->conditions->connective == FAL ) { - free_partial_Effect( tmp ); - continue; - } - - for ( l = i->effects; l; l = l->next ) { - tt = new_Literal(); - tt->negated = l->negated; - tt->fact.predicate = l->fact.predicate; - for ( j = 0; j < garity[tt->fact.predicate]; j++ ) { - tt->fact.args[j] = l->fact.args[j]; - if ( tt->fact.args[j] < 0 && - linst_table[DECODE_VAR( tt->fact.args[j] )] != -1 ) { - tt->fact.args[j] = linst_table[DECODE_VAR( tt->fact.args[j] )]; - } - } - tt->next = tmp->effects; - if ( tmp->effects ) { - tmp->effects->prev = tt; - } - tmp->effects = tt; - } - - for ( ne = i->numeric_effects; ne; ne = ne->next ) { - ttt = new_NumericEffect(); - ttt->neft = ne->neft; - ttt->fluent.function = ne->fluent.function; - for ( j = 0; j < gf_arity[ttt->fluent.function]; j++ ) { - ttt->fluent.args[j] = ne->fluent.args[j]; - if ( ttt->fluent.args[j] < 0 && - linst_table[DECODE_VAR( ttt->fluent.args[j] )] != -1 ) { - ttt->fluent.args[j] = linst_table[DECODE_VAR( ttt->fluent.args[j] )]; - } - } - ttt->rh = copy_Exp( ne->rh ); - instantiate_exp( &(ttt->rh) ); - ttt->next = tmp->numeric_effects; - if ( tmp->numeric_effects ) { - tmp->numeric_effects->prev = ttt; - } - tmp->numeric_effects = ttt; - } - - tmp->next = res; - if ( res ) { - res->prev = tmp; - } - res = tmp; - } - - return res; - -} - - - -WffNode *instantiate_wff( WffNode *w ) - -{ - - WffNode *res = NULL, *tmp, *i; - int j, m, h; - Bool ok, ct; - - switch ( w->connective ) { - case AND: - m = 0; - i = w->sons; - while ( i ) { - tmp = instantiate_wff( i ); - if ( tmp->connective == FAL ) { - free_WffNode( res ); - return tmp; - } - if ( tmp->connective == TRU ) { - free( tmp ); - i = i->next; - continue; - } - tmp->next = res; - if ( res ) { - res->prev = tmp; - } - res = tmp; - i = i->next; - m++; - } - if ( m == 0 ) { - res = new_WffNode( TRU ); - break; - } - if ( m == 1 ) { - break; - } - tmp = new_WffNode( AND ); - tmp->sons = res; - res = tmp; - break; - case OR: - m = 0; - i = w->sons; - while ( i ) { - tmp = instantiate_wff( i ); - if ( tmp->connective == TRU ) { - free_WffNode( res ); - return tmp; - } - if ( tmp->connective == FAL ) { - free( tmp ); - i = i->next; - continue; - } - tmp->next = res; - if ( res ) { - res->prev = tmp; - } - res = tmp; - i = i->next; - m++; - } - if ( m == 0 ) { - res = new_WffNode( FAL ); - break; - } - if ( m == 1 ) { - break; - } - tmp = new_WffNode( OR ); - tmp->sons = res; - res = tmp; - break; - case ATOM: - res = new_WffNode( ATOM ); - res->fact = new_Fact(); - res->fact->predicate = w->fact->predicate; - ok = TRUE; - for ( j = 0; j < garity[res->fact->predicate]; j++ ) { - h = ( w->fact->args[j] < 0 ) ? - linst_table[DECODE_VAR( w->fact->args[j] )] : w->fact->args[j]; - if ( h < 0 ) { - ok = FALSE; - res->fact->args[j] = w->fact->args[j]; - } else { - res->fact->args[j] = h; - } - } - if ( !ok ) {/* contains ef params */ - break; - } - if ( !full_possibly_negative( res->fact ) ) { - free( res->fact ); - res->fact = NULL; - res->connective = TRU; - break; - } - if ( !full_possibly_positive( res->fact ) ) { - free( res->fact ); - res->fact = NULL; - res->connective = FAL; - break; - } - break; - case COMP: - res = new_WffNode( COMP ); - res->comp = w->comp; - res->lh = copy_Exp( w->lh ); - res->rh = copy_Exp( w->rh ); - instantiate_exp( &(res->lh) ); - instantiate_exp( &(res->rh) ); - if ( res->lh->connective != NUMBER || - res->rh->connective != NUMBER ) { - /* logical simplification only possible if both parts are numbers - */ - break; - } - ct = number_comparison_holds( res->comp, res->lh->value, res->rh->value ); - if ( ct ) { - res->connective = TRU; - free_ExpNode( res->lh ); - res->lh = NULL; - free_ExpNode( res->rh ); - res->rh = NULL; - res->comp = -1; - } else { - res->connective = FAL; - free_ExpNode( res->lh ); - res->lh = NULL; - free_ExpNode( res->rh ); - res->rh = NULL; - res->comp = -1; - } - break; - case TRU: - case FAL: - res = new_WffNode( w->connective ); - break; - default: - printf("\n\nillegal connective %d in instantiate formula\n\n", - w->connective); - exit( 1 ); - } - - return res; - -} - - - -void instantiate_exp( ExpNode **n ) - -{ - - int j, f, k, h; - Bool ok; - - switch ( (*n)->connective ) { - case AD: - instantiate_exp( &((*n)->leftson) ); - instantiate_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value + (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case SU: - instantiate_exp( &((*n)->leftson) ); - instantiate_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value - (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MU: - instantiate_exp( &((*n)->leftson) ); - instantiate_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case DI: - instantiate_exp( &((*n)->leftson) ); - instantiate_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - if ( (*n)->rightson->value == 0 ) { - /* kind of unclean: simply leave that in here; - * we will later determine the right thing - * to do with it. - */ - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value / (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MINUS: - instantiate_exp( &((*n)->son) ); - if ( (*n)->son->connective != NUMBER ) break; - (*n)->connective = NUMBER; - (*n)->value = ((float) (-1)) * (*n)->son->value; - free_ExpNode( (*n)->son ); - (*n)->son = NULL; - break; - case NUMBER: - break; - case FHEAD: - f = (*n)->fluent->function; - ok = TRUE; - for ( j = 0; j < gf_arity[f]; j++ ) { - h = ( (*n)->fluent->args[j] < 0 ) ? - linst_table[DECODE_VAR( (*n)->fluent->args[j] )] : (*n)->fluent->args[j]; - if ( h < 0 ) { - ok = FALSE; - } else { - (*n)->fluent->args[j] = h; - } - } - if ( !ok ) { - break; - } - /* we handle only the case where the fluent is fully instantiated, - * static, and in the initial state. - */ - if ( gis_changed[f] ) break; - for ( j = 0; j < gnum_initial_function[f]; j++ ) { - for ( k = 0; k < gf_arity[f]; k++ ) { - if ( ginitial_function[f][j].fluent.args[k] != - (*n)->fluent->args[k] ) break; - } - if ( k < gf_arity[f] ) continue; - (*n)->connective = NUMBER; - (*n)->value = ginitial_function[f][j].value; - break; - } - break; - default: - printf("\n\ninst exp: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - -} - - - -Bool full_possibly_positive( Fact *f ) - -{ - - int adr; - - if ( gis_added[f->predicate] ) { - return TRUE; - } - - adr = instantiated_fact_adress( f ); - - if ( lini[f->predicate][adr] > 0 ) { - return TRUE; - } else { - return FALSE; - } - -} - - - -Bool full_possibly_negative( Fact *f ) - -{ - - int adr; - - if ( gis_deleted[f->predicate] ) { - return TRUE; - } - - adr = instantiated_fact_adress( f ); - - if ( lini[f->predicate][adr] > 0 ) { - return FALSE; - } else { - return TRUE; - } - -} - - - -int instantiated_fact_adress( Fact *f ) - -{ - - int r = 0, b = 1, i; - - for ( i = 0; i < garity[f->predicate]; i++ ) { - r += b * f->args[i]; - b *= gnum_constants; - } - - return r; - -} - - - - - - - - - - - - - - -/********************************************************* - * CODE THAT MULTIPLIES EFFECT PARAMS --> PSEUDO ACTIONS * - *********************************************************/ - - - - - - - - - - - - - - - -void multiply_hard_effect_parameters( void ) - -{ - - MixedOperator *o; - PseudoAction *tmp; - int i; - Effect *e; - - ghard_templates = ( PseudoAction_pointer * ) - calloc( gnum_hard_mixed_operators, sizeof ( PseudoAction_pointer ) ); - gnum_hard_templates = 0; - - for ( o = ghard_mixed_operators; o; o = o->next ) { - tmp = new_PseudoAction( o ); - - for ( i = 0; i < tmp->operator->num_vars; i++ ) { - linst_table[i] = tmp->inst_table[i]; - } - - for ( e = o->effects; e; e = e->next ) { - create_hard_pseudo_effects( tmp, e, 0 ); - } - - ghard_templates[gnum_hard_templates++] = tmp; - } -} - - - -void create_hard_pseudo_effects( PseudoAction *a, Effect *e, int curr_var ) - -{ - - int par, t, i, m, mn; - WffNode *tmp1, *w, *ww; - PseudoActionEffect *tmp2; - - if ( curr_var < e->num_vars ) { - par = a->operator->num_vars + curr_var; - - t = e->var_types[curr_var]; - for ( i = 0; i < gtype_size[t]; i++ ) { - linst_table[par] = gtype_consts[t][i]; - - create_hard_pseudo_effects( a, e, curr_var + 1 ); - - linst_table[par] = -1; - } - return; - } - - tmp1 = instantiate_wff( e->conditions ); - - if ( tmp1->connective == FAL ) { - free_WffNode( tmp1 ); - return; - } - - dnf( &tmp1 ); - cleanup_wff( &tmp1 ); - - /* only debugging, REMOVE LATER - */ - if ( is_dnf( tmp1 ) == -1 ) { - printf("\n\nILLEGAL DNF %s AFTER INSTANTIATION\n\n", a->operator->name); - print_Wff( tmp1, 0 ); - exit( 1 ); - } - - switch ( tmp1->connective ) { - case OR: - for ( w = tmp1->sons; w; w = w->next ) { - tmp2 = new_PseudoActionEffect(); - if ( w->connective == AND ) { - m = 0; - mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) m++; - if ( ww->connective == COMP ) mn++; - } - tmp2->conditions = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp2->numeric_conditions_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp2->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->num_conditions = m; - tmp2->num_numeric_conditions = mn; - m = 0; mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) { - tmp2->conditions[m].predicate = ww->fact->predicate; - for ( i = 0; i < garity[ww->fact->predicate]; i++ ) { - tmp2->conditions[m].args[i] = ww->fact->args[i]; - } - m++; - } - if ( ww->connective == COMP ) { - tmp2->numeric_conditions_comp[mn] = ww->comp; - tmp2->numeric_conditions_lh[mn] = copy_Exp( ww->lh ); - tmp2->numeric_conditions_rh[mn] = copy_Exp( ww->rh ); - mn++; - } - } - } else { - if ( w->connective == ATOM ) { - tmp2->conditions = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp2->num_conditions = 1; - tmp2->conditions[0].predicate = w->fact->predicate; - for ( i = 0; i < garity[w->fact->predicate]; i++ ) { - tmp2->conditions[0].args[i] = w->fact->args[i]; - } - } - if ( w->connective == COMP ) { - tmp2->numeric_conditions_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp2->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_comp[0] = w->comp; - tmp2->numeric_conditions_lh[0] = copy_Exp( w->lh ); - tmp2->numeric_conditions_rh[0] = copy_Exp( w->rh ); - tmp2->num_numeric_conditions = 1; - } - } - make_instantiate_literals( tmp2, e->effects ); - make_instantiate_numeric_effects( tmp2, e->numeric_effects ); - tmp2->next = a->effects; - a->effects = tmp2; - a->num_effects++; - } - break; - case AND: - tmp2 = new_PseudoActionEffect(); - m = 0; - mn = 0; - for ( w = tmp1->sons; w; w = w->next ) { - if ( w->connective == ATOM ) m++; - if ( w->connective == COMP ) mn++; - } - tmp2->conditions = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp2->numeric_conditions_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp2->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp2->num_conditions = m; - tmp2->num_numeric_conditions = mn; - m = 0; mn = 0; - for ( w = tmp1->sons; w; w = w->next ) { - if ( w->connective == ATOM ) { - tmp2->conditions[m].predicate = w->fact->predicate; - for ( i = 0; i < garity[w->fact->predicate]; i++ ) { - tmp2->conditions[m].args[i] = w->fact->args[i]; - } - m++; - } - if ( w->connective == COMP ) { - tmp2->numeric_conditions_comp[mn] = w->comp; - tmp2->numeric_conditions_lh[mn] = copy_Exp( w->lh ); - tmp2->numeric_conditions_rh[mn] = copy_Exp( w->rh ); - mn++; - } - } - make_instantiate_literals( tmp2, e->effects ); - make_instantiate_numeric_effects( tmp2, e->numeric_effects ); - tmp2->next = a->effects; - a->effects = tmp2; - a->num_effects++; - break; - case ATOM: - tmp2 = new_PseudoActionEffect(); - tmp2->conditions = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp2->num_conditions = 1; - tmp2->conditions[0].predicate = tmp1->fact->predicate; - for ( i = 0; i < garity[tmp1->fact->predicate]; i++ ) { - tmp2->conditions[0].args[i] = tmp1->fact->args[i]; - } - make_instantiate_literals( tmp2, e->effects ); - make_instantiate_numeric_effects( tmp2, e->numeric_effects ); - tmp2->next = a->effects; - a->effects = tmp2; - a->num_effects++; - break; - case COMP: - tmp2 = new_PseudoActionEffect(); - tmp2->numeric_conditions_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp2->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp2->numeric_conditions_comp[0] = tmp1->comp; - tmp2->numeric_conditions_lh[0] = copy_Exp( tmp1->lh ); - tmp2->numeric_conditions_rh[0] = copy_Exp( tmp1->rh ); - tmp2->num_numeric_conditions = 1; - make_instantiate_literals( tmp2, e->effects ); - make_instantiate_numeric_effects( tmp2, e->numeric_effects ); - tmp2->next = a->effects; - a->effects = tmp2; - a->num_effects++; - break; - case TRU: - tmp2 = new_PseudoActionEffect(); - make_instantiate_literals( tmp2, e->effects ); - make_instantiate_numeric_effects( tmp2, e->numeric_effects ); - tmp2->next = a->effects; - a->effects = tmp2; - a->num_effects++; - break; - default: - printf("\n\nillegal connective %d in parsing DNF condition.\n\n", - tmp1->connective); - exit( 1 ); - } - - free_WffNode( tmp1 ); - -} - - - -void make_instantiate_literals( PseudoActionEffect *e, Literal *ll ) - -{ - - int ma = 0, md = 0, i; - Literal *l; - - for ( l = ll; l; l = l->next ) { - if ( l->negated ) { - md++; - } else { - ma++; - } - } - - e->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - e->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - - for ( l = ll; l; l = l->next ) { - if ( l->negated ) { - e->dels[e->num_dels].predicate = l->fact.predicate; - for ( i = 0; i < garity[l->fact.predicate]; i++ ) { - e->dels[e->num_dels].args[i] = ( l->fact.args[i] < 0 ) ? - linst_table[DECODE_VAR( l->fact.args[i] )] : l->fact.args[i]; - } - e->num_dels++; - } else { - e->adds[e->num_adds].predicate = l->fact.predicate; - for ( i = 0; i < garity[l->fact.predicate]; i++ ) { - e->adds[e->num_adds].args[i] = ( l->fact.args[i] < 0 ) ? - linst_table[DECODE_VAR( l->fact.args[i] )] : l->fact.args[i]; - } - e->num_adds++; - } - } - -} - - - -void make_instantiate_numeric_effects( PseudoActionEffect *e, NumericEffect *ne ) - -{ - - int m = 0, i; - NumericEffect *n; - - for ( n = ne; n; n = n->next ) m++; - - e->numeric_effects_neft = ( NumericEffectType * ) calloc( m, sizeof( NumericEffectType ) ); - e->numeric_effects_fluent = ( Fluent * ) calloc( m, sizeof( Fluent ) ); - e->numeric_effects_rh = ( ExpNode_pointer * ) calloc( m, sizeof( ExpNode_pointer ) ); - e->num_numeric_effects = m; - - m = 0; - for ( n = ne; n; n = n->next ) { - e->numeric_effects_neft[m] = n->neft; - e->numeric_effects_fluent[m].function = n->fluent.function; - for ( i = 0; i < gf_arity[n->fluent.function]; i++ ) { - e->numeric_effects_fluent[m].args[i] = ( n->fluent.args[i] < 0 ) ? - linst_table[DECODE_VAR( n->fluent.args[i] )] : n->fluent.args[i]; - } - e->numeric_effects_rh[m] = copy_Exp( n->rh ); - instantiate_exp( &(e->numeric_effects_rh[m]) ); - m++; - } - -} diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.h deleted file mode 100644 index babebc20..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_hard.h +++ /dev/null @@ -1,71 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: inst_hard.h - * Description: headers for multiplying hard operators. - * - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - -#ifndef _INST_HARD_H -#define _INST_HARD_H - - - -void build_hard_action_templates( void ); - - - -void cleanup_hard_domain( void ); -Bool var_used_in_literals( int code_var, Literal *ef ); -Bool var_used_in_numeric_effects( int code_var, NumericEffect *ef ); -void decrement_inferior_vars_in_literals( int var, Literal *ef ); -void decrement_inferior_vars_in_numeric_effects( int var, NumericEffect *ef ); - - - -void multiply_hard_op_parameters( void ); -void create_hard_mixed_operators( Operator *o, int curr_var ); -Effect *instantiate_Effect( Effect *e ); -WffNode *instantiate_wff( WffNode *w ); -void instantiate_exp( ExpNode **n ); -Bool full_possibly_positive( Fact *f ); -Bool full_possibly_negative( Fact *f ); -int instantiated_fact_adress( Fact *f ); - - - -void multiply_hard_effect_parameters( void ); -void create_hard_pseudo_effects( PseudoAction *a, Effect *e, int curr_var ); -void make_instantiate_literals( PseudoActionEffect *e, Literal *ll ); -void make_instantiate_numeric_effects( PseudoActionEffect *e, NumericEffect *ne ); - - - -#endif /* _INST_HARD_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.c deleted file mode 100644 index 3e687720..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.c +++ /dev/null @@ -1,3854 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - - -/********************************************************************* - * File: inst_pre.c - * Description: functions for instantiating operators, preprocessing part. - * - transform domain into integers - * - inertia preprocessing: - * - collect inertia info - * - split initial state in special arrays - * - Wff normalization: - * - simplification - * - quantifier expansion - * - NOT s down - * - negative preconditions translation - * - split operators into easy and hard to instantiate - * - * - full DNF functions, only feasible for fully instantiated - * formulae - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - -#include "inst_pre.h" - - - - - - - - - - - - - - - - - - -/******************************************************* - * TRANSFORM DOMAIN INTO INTEGER (FACT) REPRESENTATION * - *******************************************************/ - - - - - - - - - -char *lvar_names[MAX_VARS]; -int lvar_types[MAX_VARS]; - - - - - - - - - - -void encode_domain_in_integers( void ) - -{ - - int i,j; - - collect_all_strings(); - create_member_nrs(); - - if ( gcmd_line.display_info == 103 ) { - printf("\nconstant table:"); - for ( i = 0; i < gnum_constants; i++ ) { - printf("\n%d --> %s", i, gconstants[i]); - } - - printf("\n\ntypes table:"); - for ( i = 0; i < gnum_types; i++ ) { - printf("\n%d --> %s: ", i, gtype_names[i]); - for ( j = 0; j < gtype_size[i]; j++ ) { - printf("%d ", gtype_consts[i][j]); - } - } - - printf("\n\npredicates table:"); - for ( i = 0; i < gnum_predicates; i++ ) { - printf("\n%3d --> %s: ", i, gpredicates[i]); - for ( j = 0; j < garity[i]; j++ ) { - printf("%s ", gtype_names[gpredicates_args_type[i][j]]); - } - } - - printf("\n\nfunctions table:"); - for ( i = 0; i < gnum_functions; i++ ) { - printf("\n%3d --> %s: ", i, gfunctions[i]); - for ( j = 0; j < gf_arity[i]; j++ ) { - printf("%s ", gtype_names[gfunctions_args_type[i][j]]); - } - } - printf("\n\n"); - } - - create_integer_representation(); - - if ( gcmd_line.display_info == 104 ) { - printf("\n\nfirst step initial state is:"); - for ( i = 0; i < gnum_full_initial; i++ ) { - printf("\n"); - print_Fact( &(gfull_initial[i]) ); - } - printf("\n\nfirst step fluent initial state is:"); - for ( i = 0; i < gnum_full_fluents_initial; i++ ) { - printf("\n"); - print_Fluent( &(gfull_fluents_initial[i].fluent) ); - printf(": %f", gfull_fluents_initial[i].value); - } - - printf("\n\nfirst step operators are:"); - for ( i = 0; i < gnum_operators; i++ ) { - print_Operator( goperators[i] ); - } - printf("\n\n"); - - printf("\n\nfirst step goal is:\n"); - print_Wff( ggoal, 0 ); - fflush( stdout ); - - printf("\n\nfirst step metric is: (normalized to minimize)\n"); - print_ExpNode( gmetric ); - fflush( stdout ); - } - -} - - - -void create_member_nrs( void ) - -{ - - int i, j, num; - - for ( i = 0; i < MAX_CONSTANTS; i++ ) { - for ( j = 0; j < MAX_TYPES; j++ ) { - gmember_nr[i][j] = -1; - } - } - - for ( i = 0; i < gnum_types; i++ ) { - num = 0; - for ( j = 0; j < gtype_size[i]; j++ ) { - gmember_nr[gtype_consts[i][j]][i] = num; - num++; - } - } - -} - - - -void collect_all_strings( void ) - -{ - - FactList *f; - TokenList *t; - int p_num, type_num, c_num, ar; - int i; - - /* first are types and their objects. for = we make sure that there - * is one type that contains all objects. - */ - gtype_names[0] = new_Token( 50 ); - gtype_names[0] = "ARTFICIAL-ALL-OBJECTS"; - gtype_size[0] = 0; - for ( i = 0; i < MAX_CONSTANTS; i++ ) { - gis_member[i][0] = FALSE; - } - gnum_types = 1; - - for ( f = gorig_constant_list; f; f = f->next ) { - if ( (type_num = position_in_types_table( f->item->next->item )) == -1 ) { - if ( gnum_types == MAX_TYPES ) { - printf("\ntoo many types! increase MAX_TYPES (currently %d)\n\n", - MAX_TYPES); - exit( 1 ); - } - gtype_names[gnum_types] = new_Token( strlen( f->item->next->item ) + 1 ); - strcpy( gtype_names[gnum_types], f->item->next->item ); - gtype_size[gnum_types] = 0; - for ( i = 0; i < MAX_CONSTANTS; i++ ) { - gis_member[i][gnum_types] = FALSE; - } - type_num = gnum_types++; - } - - if ( (c_num = position_in_constants_table( f->item->item )) == -1 ) { - if ( gnum_constants == MAX_CONSTANTS ) { - printf("\ntoo many constants! increase MAX_CONSTANTS (currently %d)\n\n", - MAX_CONSTANTS); - exit( 1 ); - } - gconstants[gnum_constants] = new_Token( strlen( f->item->item ) + 1 ); - strcpy( gconstants[gnum_constants], f->item->item ); - c_num = gnum_constants++; - - /* all constants into 0-type. - */ - if ( gtype_size[0] == MAX_TYPE ) { - printf("\ntoo many consts in type %s! increase MAX_TYPE (currently %d)\n\n", - gtype_names[0], MAX_TYPE); - exit( 1 ); - } - gtype_consts[0][gtype_size[0]++] = c_num; - gis_member[c_num][0] = TRUE; - } - - if ( !gis_member[c_num][type_num] ) { - if ( gtype_size[type_num] == MAX_TYPE ) { - printf("\ntoo many consts in type %s! increase MAX_TYPE (currently %d)\n\n", - gtype_names[type_num], MAX_TYPE); - exit( 1 ); - } - gtype_consts[type_num][gtype_size[type_num]++] = c_num; - gis_member[c_num][type_num] = TRUE; - } - } - - /* next are predicates; first of all, create in-built predicate = - */ - gpredicates[0] = new_Token( 5 ); - gpredicates[0] = "="; - gpredicates_args_type[0][0] = 0;/* all objects type */ - gpredicates_args_type[0][1] = 0; - garity[0] = 2; - gnum_predicates = 1; - - for ( f = gpredicates_and_types; f; f = f->next ) { - if ( (p_num = position_in_predicates_table( f->item->item )) != -1 ) { - printf("\npredicate %s declared twice!\n\n", f->item->item); - exit( 1 ); - } - if ( gnum_predicates == MAX_PREDICATES ) { - printf("\ntoo many predicates! increase MAX_PREDICATES (currently %d)\n\n", - MAX_PREDICATES); - exit( 1 ); - } - gpredicates[gnum_predicates] = new_Token( strlen( f->item->item ) + 1 ); - strcpy( gpredicates[gnum_predicates], f->item->item ); - ar = 0; - for ( t = f->item->next; t; t = t->next ) { - if ( (type_num = position_in_types_table( t->item )) == -1 ) { - printf("\npredicate %s is declared to use unknown or empty type %s\n\n", - f->item->item, t->item); - exit( 1 ); - } - if ( ar == MAX_ARITY ) { - printf("\narity of %s to high! increase MAX_ARITY (currently %d)\n\n", - gpredicates[gnum_predicates], MAX_ARITY); - exit( 1 ); - } - gpredicates_args_type[gnum_predicates][ar++] = type_num; - } - garity[gnum_predicates] = ar; - gaxiom_added[gnum_predicates] = FALSE; - gnum_predicates++; - } - - - /* next are functions; first of all, create in-built function total-time - * for sole use in metric - */ - gfunctions[0] = new_Token( 20 ); - gfunctions[0] = "TOTAL-TIME"; - gf_arity[0] = 0; - gnum_functions = 1; - - for ( f = gfunctions_and_types; f; f = f->next ) { - if ( (p_num = position_in_functions_table( f->item->item )) != -1 ) { - printf("\nfunction %s declared twice!\n\n", f->item->item); - exit( 1 ); - } - if ( gnum_functions == MAX_FUNCTIONS ) { - printf("\ntoo many functions! increase MAX_FUNCTIONS (currently %d)\n\n", - MAX_FUNCTIONS); - exit( 1 ); - } - gfunctions[gnum_functions] = new_Token( strlen( f->item->item ) + 1 ); - strcpy( gfunctions[gnum_functions], f->item->item ); - ar = 0; - for ( t = f->item->next; t; t = t->next ) { - if ( (type_num = position_in_types_table( t->item )) == -1 ) { - printf("\nfunction %s is declared to use unknown or empty type %s\n\n", - f->item->item, t->item); - exit( 1 ); - } - if ( ar == MAX_ARITY ) { - printf("\narity of %s to high! increase MAX_ARITY (currently %d)\n\n", - gfunctions[gnum_functions], MAX_ARITY); - exit( 1 ); - } - gfunctions_args_type[gnum_functions][ar++] = type_num; - } - gf_arity[gnum_functions++] = ar; - } - - free_FactList( gorig_constant_list ); - free_FactList( gpredicates_and_types ); - free_FactList( gfunctions_and_types ); - -} - - - -int position_in_types_table( char *str ) - -{ - - int i; - - /* start at 1 because 0 is our artificial one - */ - for ( i = 1; i < gnum_types; i++ ) { - if ( str == gtype_names[i] || - (strcmp( str, gtype_names[i] ) == SAME) ) { - break; - } - } - - return ( i == gnum_types ) ? -1 : i; - -} - - - -int position_in_constants_table( char *str ) - -{ - - int i; - - for ( i=0; isons; n; n = n->next ) sum++; - sum += gnum_constants;/* space for equalities */ - gfull_initial = ( Fact * ) calloc( sum, sizeof( Fact ) ); - gfull_fluents_initial = ( FluentValue * ) - calloc( sum, sizeof( FluentValue )); - - for ( n = gorig_initial_facts->sons; n; n = n->next ) { - if ( n->connective == ATOM ) { - make_Fact( &(gfull_initial[gnum_full_initial]), n, 0 ); - if ( gfull_initial[gnum_full_initial].predicate == 0 ) { - printf("\nequality in initial state! check input files.\n\n"); - exit( 1 ); - } - - /* duplicate check!! - */ - for ( i = 0; i < gnum_full_initial; i++ ) { - if ( gfull_initial[i].predicate != gfull_initial[gnum_full_initial].predicate ) { - /* predicate different --> this ini fact is not a duplicate! - */ - continue; - } - for ( j = 0; j < garity[gfull_initial[i].predicate]; j++ ) { - if ( gfull_initial[i].args[j] != gfull_initial[gnum_full_initial].args[j] ) { - /* arg different --> this ini fact is not a duplicate! - */ - break; - } - } - if ( j == garity[gfull_initial[i].predicate] ) { - /* found a duplicate! - */ - break; - } - } - if ( i < gnum_full_initial ) { - /* simply skip the second occurence... - */ - continue; - } - - gnum_full_initial++; - } else { - /* a fluent value assignment - */ - make_Fluent( &(gfull_fluents_initial[gnum_full_fluents_initial].fluent), - n->lh->atom, 0 ); - gfull_fluents_initial[gnum_full_fluents_initial].value = - ( float ) strtod( n->rh->atom->item, NULL); - gnum_full_fluents_initial++; - } - } - free_PlNode( gorig_initial_facts ); - } - - /* now insert all our artificial equality constraints into initial state. - */ - for ( i = 0; i < gnum_constants; i++ ) { - gfull_initial[gnum_full_initial].predicate = 0; - gfull_initial[gnum_full_initial].args[0] = i; - gfull_initial[gnum_full_initial].args[1] = i; - gnum_full_initial++; - } - /* FINITO. the rest of equality handling will fully - * automatically be done by the rest of the machinery. - */ - - ggoal = make_Wff( gorig_goal_facts, 0 ); - - if ( gparse_metric != NULL ) { - /* no need to throw costs away, even if we're not explicitly asked to - * minimize them - */ - if ( 0 && !gcost_minimizing ) { - if ( gcmd_line.display_info ) { - printf("\n\nno optimization required. skipping criterion.\n\n"); - } - } else { - gmetric = make_ExpNode( gparse_metric, 0 ); - if ( strcmp( gparse_optimization, "MINIMIZE" ) != SAME && - strcmp( gparse_optimization, "minimize" ) != SAME && - strcmp( gparse_optimization, "MAXIMIZE" ) != SAME && - strcmp( gparse_optimization, "maximize" ) != SAME ) { - if ( gcmd_line.display_info ) { - printf("\n\nunknown optimization method %s. check input files\n\n", - gparse_optimization); - } - exit( 1 ); - } - if ( strcmp( gparse_optimization, "MAXIMIZE" ) == SAME || - strcmp( gparse_optimization, "maximize" ) == SAME ) { - t = new_ExpNode( MINUS ); - t->son = gmetric; - gmetric = t; - } - } - } - - for ( o = gloaded_ops; o; o = o->next ) { - tmp = new_Operator( o->name, o->number_of_real_params ); - tmp->axiom = o->axiom; - - for ( ff = o->params; ff; ff = ff->next ) { - if ( (type_num = position_in_types_table( ff->item->next->item )) == -1 ) { - printf("\nwarning: parameter %s of op %s has unknown or empty type %s. skipping op", - ff->item->item, o->name, ff->item->next->item); - break; - } - if ( tmp->num_vars == MAX_VARS ) { - printf("\ntoo many parameters! increase MAX_VARS (currently %d)\n\n", - MAX_VARS); - exit( 1 ); - } - for ( i = 0; i < tmp->num_vars; i++ ) { - if ( tmp->var_names[i] == ff->item->item || - strcmp( tmp->var_names[i], ff->item->item ) == SAME ) { - printf("\nwarning: operator %s parameter %s overwrites previous declaration\n\n", - tmp->name, ff->item->item); - } - } - tmp->var_names[tmp->num_vars] = new_Token( strlen( ff->item->item ) + 1 ); - strcpy( tmp->var_names[tmp->num_vars], ff->item->item ); - tmp->var_types[tmp->num_vars++] = type_num; - } - if ( ff ) { - free_Operator( tmp ); - continue; - } - - for ( i = 0; i < tmp->num_vars; i++ ) { - lvar_types[i] = tmp->var_types[i]; - lvar_names[i] = tmp->var_names[i]; - } - - tmp->preconds = make_Wff( o->preconds, tmp->num_vars ); - - if ( o->effects ) { - /* in make_effect, make sure that no one afects equality. - */ - nn = o->effects->sons; - while ( nn && - (tmp->effects = make_effect( nn, tmp->num_vars )) == NULL ) { - nn = nn->next; - } - if ( nn ) { - for ( n = nn->next; n; n = n->next ) { - if ( (tmp->effects->prev = make_effect( n, tmp->num_vars )) == NULL ) { - continue; - } - tmp->effects->prev->next = tmp->effects; - tmp->effects = tmp->effects->prev; - } - } - } - - if ( gnum_operators == MAX_OPERATORS ) { - printf("\ntoo many operators! increase MAX_OPERATORS (currently %d)\n\n", - MAX_OPERATORS); - exit( 1 ); - } - goperators[gnum_operators++] = tmp; - } - - if ( 0 ) { - /* currently not in use; leads to free memory reads and - * free memory frees (no memory leaks), which are hard to explain. - * - * almost no memory consumption anyway. - */ - free_PlOperator( gloaded_ops ); - } - - /* establish gaxiom_added markers. - * ascertain that derived predicates do not appear in effects!! - */ - for ( i = 0; i < gnum_operators; i++ ) { - for ( e = goperators[i]->effects; e; e = e->next ) { - for ( l = e->effects; l; l = l->next ) { - if ( goperators[i]->axiom ) { - gaxiom_added[l->fact.predicate] = TRUE; - } - } - } - } - for ( i = 0; i < gnum_operators; i++ ) { - for ( e = goperators[i]->effects; e; e = e->next ) { - for ( l = e->effects; l; l = l->next ) { - if ( !goperators[i]->axiom && - gaxiom_added[l->fact.predicate] ) { - printf("\nA derived predicate appears in an operator effect."); - printf("\nSorry, this is not allowed. Bailing out.\n\n"); - exit( 1 ); - } - } - } - } - -} - - - -void make_Fact( Fact *f, PlNode *n, int num_vars ) - -{ - - int m, i; - TokenList *t; - - if ( !n->atom ) { - /* can't happen after previous syntax check. Oh well, whatever... - */ - printf("\nillegal (empty) atom used in domain. check input files\n\n"); - exit( 1 ); - } - - f->predicate = position_in_predicates_table( n->atom->item ); - if ( f->predicate == -1 ) { - printf("\nundeclared predicate %s used in domain definition\n\n", - n->atom->item); - exit( 1 ); - } - - m = 0; - for ( t = n->atom->next; t; t = t->next ) { - if ( t->item[0] == '?' ) { - for ( i=num_vars-1; i>-1; i-- ) { - /* downwards, to always get most recent declaration/quantification - * of that variable - */ - if ( lvar_names[i] == t->item || - strcmp( lvar_names[i], t->item ) == SAME ) { - break; - } - } - if ( i == -1 ) { - printf("\nundeclared variable %s in literal %s. check input files\n\n", - t->item, n->atom->item); - exit( 1 ); - } - if ( lvar_types[i] != gpredicates_args_type[f->predicate][m] && - !is_subtype( lvar_types[i], gpredicates_args_type[f->predicate][m] ) ) { - printf("\ntype of var %s does not match type of arg %d of predicate %s\n\n", - lvar_names[i], m, gpredicates[f->predicate]); - exit( 1 ); - } - f->args[m] = ENCODE_VAR( i ); - } else { - if ( (f->args[m] = - position_in_constants_table( t->item )) == -1 ) { - printf("\nunknown constant %s in literal %s. check input files\n\n", - t->item, n->atom->item); - exit( 1 ); - } - if ( !gis_member[f->args[m]][gpredicates_args_type[f->predicate][m]] ) { - printf("\ntype mismatch: constant %s as arg %d of %s. check input files\n\n", - gconstants[f->args[m]], m, gpredicates[f->predicate]); - exit( 1 ); - } - } - m++; - } - if ( m != garity[f->predicate] ) { - printf("\npredicate %s is declared to have %d (not %d) arguments. check input files\n\n", - gpredicates[f->predicate], - garity[f->predicate], m); - exit( 1 ); - } - -} - - - -void make_Fluent( Fluent *f, TokenList *atom, int num_vars ) - -{ - - int m, i; - TokenList *t; - - if ( !atom ) { - /* can't happen after previous syntax check. Oh well, whatever... - */ - printf("\nillegal (empty) atom used in domain. check input files\n\n"); - exit( 1 ); - } - - f->function = position_in_functions_table( atom->item ); - if ( f->function == -1 ) { - printf("\nundeclared function %s used in domain definition\n\n", - atom->item); - exit( 1 ); - } - - m = 0; - for ( t = atom->next; t; t = t->next ) { - if ( t->item[0] == '?' ) { - for ( i=num_vars-1; i>-1; i-- ) { - /* downwards, to always get most recent declaration/quantification - * of that variable - */ - if ( lvar_names[i] == t->item || - strcmp( lvar_names[i], t->item ) == SAME ) { - break; - } - } - if ( i == -1 ) { - printf("\nundeclared variable %s in function %s. check input files\n\n", - t->item, atom->item); - exit( 1 ); - } - if ( lvar_types[i] != gfunctions_args_type[f->function][m] && - !is_subtype( lvar_types[i], gfunctions_args_type[f->function][m] ) ) { - printf("\ntype of var %s does not match type of arg %d of function %s\n\n", - lvar_names[i], m, gfunctions[f->function]); - exit( 1 ); - } - f->args[m] = ENCODE_VAR( i ); - } else { - if ( (f->args[m] = - position_in_constants_table( t->item )) == -1 ) { - printf("\nunknown constant %s in function %s. check input files\n\n", - t->item, atom->item); - exit( 1 ); - } - if ( !gis_member[f->args[m]][gfunctions_args_type[f->function][m]] ) { - printf("\ntype mismatch: constant %s as arg %d of %s. check input files\n\n", - gconstants[f->args[m]], m, gfunctions[f->function]); - exit( 1 ); - } - } - m++; - } - - if ( m != gf_arity[f->function] ) { - printf("\nfunction %s is declared to have %d (not %d) arguments. check input files\n\n", - gfunctions[f->function], - gf_arity[f->function], m); - exit( 1 ); - } - -} - - - -Bool is_subtype( int t1, int t2 ) - -{ - - int i; - - for ( i = 0; i < gtype_size[t1]; i++ ) { - if ( !gis_member[gtype_consts[t1][i]][t2] ) { - return FALSE; - } - } - - return TRUE; - -} - - - -WffNode *make_Wff( PlNode *p, int num_vars ) - -{ - - WffNode *tmp; - int i, t; - PlNode *n; - - if ( !p ) { - tmp = NULL; - return tmp; - } - - tmp = new_WffNode( p->connective ); - switch ( p->connective ) { - case ALL: - case EX: - for ( i = 0; i < num_vars; i++ ) { - if ( lvar_names[i] == p->atom->item || - strcmp( lvar_names[i], p->atom->item ) == SAME ) { - printf("\nwarning: var quantification of %s overwrites previous declaration\n\n", - p->atom->item); - } - } - if ( (t = position_in_types_table( p->atom->next->item )) == -1 ) { - printf("\nwarning: quantified var %s has unknown or empty type %s. simplifying.\n\n", - p->atom->item, p->atom->next->item); - tmp->connective = ( p->connective == EX ) ? FAL : TRU; - break; - } - tmp->var = num_vars; - tmp->var_type = t; - tmp->var_name = new_Token( strlen( p->atom->item ) + 1 ); - strcpy( tmp->var_name, p->atom->item ); - lvar_names[num_vars] = p->atom->item; - lvar_types[num_vars] = t; - tmp->son = make_Wff( p->sons, num_vars + 1 ); - break; - case AND: - case OR: - if ( !p->sons ) { - printf("\nwarning: empty con/disjunction in domain definition. simplifying.\n\n"); - tmp->connective = ( p->connective == OR ) ? FAL : TRU; - break; - } - tmp->sons = make_Wff( p->sons, num_vars ); - for ( n = p->sons->next; n; n = n->next ) { - tmp->sons->prev = make_Wff( n, num_vars ); - tmp->sons->prev->next = tmp->sons; - tmp->sons = tmp->sons->prev; - } - break; - case NOT: - tmp->son = make_Wff( p->sons, num_vars ); - break; - case ATOM: - tmp->fact = new_Fact(); - make_Fact( tmp->fact, p, num_vars ); - break; - case TRU: - case FAL: - break; - case COMP: - tmp->comp = p->comp; - tmp->lh = make_ExpNode( p->lh, num_vars ); - tmp->rh = make_ExpNode( p->rh, num_vars ); - break; - default: - printf("\nforbidden connective %d in Pl Wff. must be a bug somewhere...\n\n", - p->connective); - exit( 1 ); - } - - return tmp; - -} - - - -ExpNode *make_ExpNode( ParseExpNode *p, int num_vars ) - -{ - - ExpNode *tmp; - - if ( !p ) { - tmp = NULL; - return tmp; - } - - tmp = new_ExpNode( p->connective ); - switch ( p->connective ) { - case AD: - case SU: - case MU: - case DI: - tmp->leftson = make_ExpNode( p->leftson, num_vars ); - tmp->rightson = make_ExpNode( p->rightson, num_vars ); - break; - case MINUS: - tmp->son = make_ExpNode( p->leftson, num_vars ); - break; - case NUMBER: - tmp->value = ( float ) strtod( p->atom->item, NULL ); - break; - case FHEAD: - tmp->fluent = new_Fluent(); - make_Fluent( tmp->fluent, p->atom, num_vars ); - break; - default: - printf("\n\nmake expnode: wrong specifier %d", - p->connective); - exit( 1 ); - } - - return tmp; - -} - - - -Effect *make_effect( PlNode *p, int num_vars ) - -{ - - Effect *tmp = new_Effect(); - PlNode *n, *m; - int t, i; - - for ( n = p; n && n->connective == ALL; n = n->sons ) { - if ( (t = position_in_types_table( n->atom->next->item )) == -1 ) { - printf("\nwarning: effect parameter %s has unknown or empty type %s. skipping effect.\n\n", - n->atom->item, n->atom->next->item); - return NULL; - } - for ( i = 0; i < num_vars + tmp->num_vars; i++ ) { - if ( lvar_names[i] == n->atom->item || - strcmp( lvar_names[i], n->atom->item ) == SAME ) { - printf("\nwarning: effect parameter %s overwrites previous declaration\n\n", - n->atom->item); - } - } - lvar_types[num_vars + tmp->num_vars] = t; - lvar_names[num_vars + tmp->num_vars] = n->atom->item; - tmp->var_names[tmp->num_vars] = new_Token( strlen( n->atom->item ) + 1 ); - strcpy( tmp->var_names[tmp->num_vars], n->atom->item ); - tmp->var_types[tmp->num_vars++] = t; - } - - if ( !n || n->connective != WHEN ) { - printf("\nnon WHEN %d at end of effect parameters. debug me\n\n", - n->connective); - exit( 1 ); - } - - tmp->conditions = make_Wff( n->sons, num_vars + tmp->num_vars ); - - if ( n->sons->next->connective != AND ) { - printf("\nnon AND %d in front of literal effect list. debug me\n\n", - n->sons->next->connective); - exit( 1 ); - } - if ( !n->sons->next->sons ) { - return tmp; - } - for ( m = n->sons->next->sons; m; m = m->next ) { - if ( m->connective == NEF ) { - if ( tmp->numeric_effects != NULL ) { - tmp->numeric_effects->prev = new_NumericEffect(); - make_Fluent( &(tmp->numeric_effects->prev->fluent), - m->lh->atom, num_vars + tmp->num_vars ); - tmp->numeric_effects->prev->neft = m->neft; - tmp->numeric_effects->prev->rh = make_ExpNode( m->rh, num_vars + tmp->num_vars ); - - tmp->numeric_effects->prev->next = tmp->numeric_effects; - tmp->numeric_effects = tmp->numeric_effects->prev; - } else { - tmp->numeric_effects = new_NumericEffect(); - make_Fluent( &(tmp->numeric_effects->fluent), - m->lh->atom, num_vars + tmp->num_vars ); - tmp->numeric_effects->neft = m->neft; - tmp->numeric_effects->rh = make_ExpNode( m->rh, num_vars + tmp->num_vars ); - } - } else { - if ( tmp->effects != NULL ) { - tmp->effects->prev = new_Literal(); - if ( m->connective == NOT ) { - tmp->effects->prev->negated = TRUE; - make_Fact( &(tmp->effects->prev->fact), m->sons, num_vars + tmp->num_vars ); - if ( (tmp->effects->prev->fact).predicate == 0 ) { - printf("\n\nequality in effect! check input files!\n\n"); - exit( 1 ); - } - } else { - tmp->effects->prev->negated = FALSE; - make_Fact( &(tmp->effects->prev->fact), m, num_vars + tmp->num_vars ); - if ( (tmp->effects->prev->fact).predicate == 0 ) { - printf("\n\nequality in effect! check input files!\n\n"); - exit( 1 ); - } - } - tmp->effects->prev->next = tmp->effects; - tmp->effects = tmp->effects->prev; - } else { - tmp->effects = new_Literal(); - if ( m->connective == NOT ) { - tmp->effects->negated = TRUE; - make_Fact( &(tmp->effects->fact), m->sons, num_vars + tmp->num_vars ); - if ( (tmp->effects->fact).predicate == 0 ) { - printf("\n\nequality in effect! check input files!\n\n"); - exit( 1 ); - } - } else { - tmp->effects->negated = FALSE; - make_Fact( &(tmp->effects->fact), m, num_vars + tmp->num_vars ); - if ( (tmp->effects->fact).predicate == 0 ) { - printf("\n\nequality in effect! check input files!\n\n"); - exit( 1 ); - } - } - } - } - } - - return tmp; - -} - - - - - - - - - - - -/************************* - * INERTIA PREPROCESSING * - *************************/ - - - - - - - - - - - -void do_inertia_preprocessing_step_1( void ) - -{ - - int i, j; - Facts *f; - FluentValues *ff; - - collect_inertia_information(); - - if ( gcmd_line.display_info == 105 ) { - printf("\n\npredicates inertia info:"); - for ( i = 0; i < gnum_predicates; i++ ) { - printf("\n%3d --> %s: ", i, gpredicates[i]); - printf(" is %s, %s", - gis_added[i] ? "ADDED" : "NOT ADDED", - gis_deleted[i] ? "DELETED" : "NOT DELETED"); - } - printf("\n\nfunctions inertia info:"); - for ( i = 0; i < gnum_functions; i++ ) { - printf("\n%3d --> %s: ", i, gfunctions[i]); - printf(" is %s", - gis_changed[i] ? "CHANGED" : "NOT CHANGED"); - } - printf("\n\n"); - } - - split_initial_state(); - - if ( gcmd_line.display_info == 106 ) { - printf("\n\nsplitted initial state is:"); - printf("\nindividual predicates:"); - for ( i = 0; i < gnum_predicates; i++ ) { - printf("\n\n%s:", gpredicates[i]); - if ( !gis_added[i] && - !gis_deleted[i] ) { - printf(" --- STATIC"); - } - for ( j = 0; j < gnum_initial_predicate[i]; j++ ) { - printf("\n"); - print_Fact( &(ginitial_predicate[i][j]) ); - } - } - printf("\n\nnon static part:"); - for ( f = ginitial; f; f = f->next ) { - printf("\n"); - print_Fact( f->fact ); - } - - printf("\n\nextended types table:"); - for ( i = 0; i < gnum_types; i++ ) { - printf("\n%d --> ", i); - if ( gpredicate_to_type[i] == -1 ) { - printf("%s ", gtype_names[i]); - } else { - printf("UNARY INERTIA TYPE (%s) ", gpredicates[gpredicate_to_type[i]]); - } - for ( j = 0; j < gtype_size[i]; j++ ) { - printf("%d ", gtype_consts[i][j]); - } - } - - printf("\nindividual functions:"); - for ( i = 0; i < gnum_functions; i++ ) { - printf("\n\n%s:", gfunctions[i]); - if ( !gis_changed[i] ) { - printf(" --- STATIC"); - } - for ( j = 0; j < gnum_initial_function[i]; j++ ) { - printf("\n"); - print_Fluent( &(ginitial_function[i][j].fluent) ); - printf(": %f", ginitial_function[i][j].value); - } - } - printf("\n\nnon static part:"); - for ( ff = gf_initial; ff; ff = ff->next ) { - printf("\n"); - print_Fluent( &(ff->fluent) ); - printf(": %f", ff->value); - } - } - -} - - - -void collect_inertia_information( void ) - -{ - - int i; - Effect *e; - Literal *l; - NumericEffect *ne; - - for ( i = 0; i < gnum_predicates; i++ ) { - gis_added[i] = FALSE; - gis_deleted[i] = FALSE; - } - for ( i = 0; i < gnum_functions; i++ ) { - gis_changed[i] = FALSE; - } - - for ( i = 0; i < gnum_operators; i++ ) { - for ( e = goperators[i]->effects; e; e = e->next ) { - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - gis_deleted[l->fact.predicate] = TRUE; - } else { - gis_added[l->fact.predicate] = TRUE; - } - } - for ( ne = e->numeric_effects; ne; ne = ne->next ) { - gis_changed[ne->fluent.function] = TRUE; - } - } - } - -} - - - -void split_initial_state( void ) - -{ - - int i, j, p, t; - Facts *tmp; - FluentValues *ftmp; - - for ( i = 0; i < MAX_PREDICATES; i++ ) { - gtype_to_predicate[i] = -1; - } - for ( i = 0; i < MAX_TYPES; i++ ) { - gpredicate_to_type[i] = -1; - } - - for ( i = 0; i < gnum_predicates; i++ ) { - if ( !gis_added[i] && - !gis_deleted[i] && - garity[i] == 1 ) { - if ( gnum_types == MAX_TYPES ) { - printf("\ntoo many (inferred) types! increase MAX_TYPES (currently %d)\n\n", - MAX_TYPES); - exit( 1 ); - } - gtype_to_predicate[i] = gnum_types; - gpredicate_to_type[gnum_types] = i; - gtype_names[gnum_types] = NULL; - gtype_size[gnum_types] = 0; - for ( j = 0; j < MAX_CONSTANTS; j++ ) { - gis_member[j][gnum_types] = FALSE; - } - gnum_types++; - } - } - - - /* double size of predicates table as each predicate might need - * to be translated to NOT-p - */ - ginitial_predicate = ( Fact ** ) calloc( gnum_predicates * 2, sizeof( Fact * ) ); - gnum_initial_predicate = ( int * ) calloc( gnum_predicates * 2, sizeof( int ) ); - for ( i = 0; i < gnum_predicates * 2; i++ ) { - gnum_initial_predicate[i] = 0; - } - for ( i = 0; i < gnum_full_initial; i++ ) { - p = gfull_initial[i].predicate; - gnum_initial_predicate[p]++; - } - for ( i = 0; i < gnum_predicates; i++ ) { - ginitial_predicate[i] = ( Fact * ) calloc( gnum_initial_predicate[i], sizeof( Fact ) ); - gnum_initial_predicate[i] = 0; - } - ginitial = NULL; - gnum_initial = 0; - - for ( i = 0; i < gnum_full_initial; i++ ) { - p = gfull_initial[i].predicate; - ginitial_predicate[p][gnum_initial_predicate[p]].predicate = p; - for ( j = 0; j < garity[p]; j++ ) { - ginitial_predicate[p][gnum_initial_predicate[p]].args[j] = gfull_initial[i].args[j]; - } - gnum_initial_predicate[p]++; - if ( gis_added[p] || - gis_deleted[p] ) { - tmp = new_Facts(); - tmp->fact->predicate = p; - for ( j = 0; j < garity[p]; j++ ) { - tmp->fact->args[j] = gfull_initial[i].args[j]; - } - tmp->next = ginitial; - ginitial = tmp; - gnum_initial++; - } else { - if ( garity[p] == 1 ) { - t = gtype_to_predicate[p]; - if ( gtype_size[t] == MAX_TYPE ) { - printf("\ntoo many consts in type %s! increase MAX_TYPE (currently %d)\n\n", - gtype_names[t], MAX_TYPE); - exit( 1 ); - } - if ( !gis_member[gfull_initial[i].args[0]][gpredicates_args_type[p][0]] ) { - printf("\ntype mismatch in initial state! %s as arg 0 of %s\n\n", - gconstants[gfull_initial[i].args[0]], gpredicates[p]); - exit( 1 ); - } - gtype_consts[t][gtype_size[t]++] = gfull_initial[i].args[0]; - gis_member[gfull_initial[i].args[0]][t] = TRUE; - } - } - } - - ginitial_function = ( FluentValue ** ) - calloc( gnum_functions, sizeof( FluentValue * ) ); - gnum_initial_function = ( int * ) calloc( gnum_functions, sizeof( int ) ); - for ( i = 0; i < gnum_functions; i++ ) { - gnum_initial_function[i] = 0; - } - for ( i = 0; i < gnum_full_fluents_initial; i++ ) { - p = gfull_fluents_initial[i].fluent.function; - gnum_initial_function[p]++; - } - for ( i = 0; i < gnum_functions; i++ ) { - ginitial_function[i] = ( FluentValue * ) - calloc( gnum_initial_function[i], sizeof( FluentValue ) ); - gnum_initial_function[i] = 0; - } - gf_initial = NULL; - gnum_f_initial = 0; - - for ( i = 0; i < gnum_full_fluents_initial; i++ ) { - p = gfull_fluents_initial[i].fluent.function; - ginitial_function[p][gnum_initial_function[p]].fluent.function = p; - for ( j = 0; j < gf_arity[p]; j++ ) { - ginitial_function[p][gnum_initial_function[p]].fluent.args[j] = - gfull_fluents_initial[i].fluent.args[j]; - } - ginitial_function[p][gnum_initial_function[p]].value = - gfull_fluents_initial[i].value; - gnum_initial_function[p]++; - if ( gis_changed[p] ) { - ftmp = new_FluentValues(); - ftmp->fluent.function = p; - for ( j = 0; j < gf_arity[p]; j++ ) { - ftmp->fluent.args[j] = gfull_fluents_initial[i].fluent.args[j]; - } - ftmp->value = gfull_fluents_initial[i].value; - ftmp->next = gf_initial; - gf_initial = ftmp; - gnum_f_initial++; - } - } - -} - - - - - - - - - - - -/****************************** - * NORMALIZE ALL PL1 FORMULAE * - ******************************/ - - - - - - - - - - - - -void normalize_all_wffs( void ) - -{ - - int i; - Effect *e; - - simplify_wff( &ggoal ); - remove_unused_vars_in_wff( &ggoal ); - expand_quantifiers_in_wff( &ggoal, -1, -1 ); - NOTs_down_in_wff( &ggoal ); - cleanup_wff( &ggoal ); - - if ( ggoal->connective == TRU ) { - printf("\nff: goal can be simplified to TRUE. The empty plan solves it\n\n"); - gnum_plan_ops = 0; - exit( 1 ); - } - if ( ggoal->connective == FAL ) { - printf("\nff: goal can be simplified to FALSE. No plan will solve it\n\n"); - exit( 1 ); - } - - /* put goal into DNF right away: fully instantiated already - */ - dnf( &ggoal ); - cleanup_wff( &ggoal ); - - /* all we can do here is simplify if that's possible. - */ - if ( gmetric != NULL ) { - simplify_exp( &gmetric ); - } - - - for ( i = 0; i < gnum_operators; i++ ) { - simplify_wff( &(goperators[i]->preconds) ); - remove_unused_vars_in_wff( &(goperators[i]->preconds) ); - expand_quantifiers_in_wff( &(goperators[i]->preconds), -1, -1 ); - NOTs_down_in_wff( &(goperators[i]->preconds) ); - cleanup_wff( &(goperators[i]->preconds) ); - - for ( e = goperators[i]->effects; e; e = e->next ) { - simplify_wff( &(e->conditions) ); - remove_unused_vars_in_wff( &(e->conditions) ); - expand_quantifiers_in_wff( &(e->conditions), -1, -1 ); - NOTs_down_in_wff( &(e->conditions) ); - cleanup_wff( &(e->conditions) ); - } - } - - if ( gcmd_line.display_info == 107 ) { - printf("\n\ndomain with normalized PL1 formula:"); - - printf("\n\noperators are:"); - for ( i = 0; i < gnum_operators; i++ ) { - print_Operator( goperators[i] ); - } - printf("\n\n"); - - printf("\n\ngoal is:\n"); - print_Wff( ggoal, 0 ); - - if ( gmetric ) { - printf("\n\nmetric is (minimize):\n"); - print_ExpNode( gmetric ); - } else { - printf("\n\nmetric: none, i.e. plan length\n"); - } - } - -} - - - -void remove_unused_vars_in_wff( WffNode **w ) - -{ - - WffNode *tmp; - WffNode *i; - - switch ( (*w)->connective ) { - case ALL: - case EX: - remove_unused_vars_in_wff( &((*w)->son) ); - if ( !var_used_in_wff( ENCODE_VAR( (*w)->var ), (*w)->son ) ) { - decrement_inferior_vars((*w)->var, (*w)->son ); - (*w)->connective = (*w)->son->connective; - (*w)->var = (*w)->son->var; - (*w)->var_type = (*w)->son->var_type; - if ( (*w)->var_name ) { - free( (*w)->var_name ); - } - (*w)->var_name = (*w)->son->var_name; - (*w)->sons = (*w)->son->sons; - if ( (*w)->fact ) { - free( (*w)->fact ); - } - (*w)->fact = (*w)->son->fact; - (*w)->comp = (*w)->son->comp; - if ( (*w)->lh ) free_ExpNode( (*w)->lh ); - if ( (*w)->rh ) free_ExpNode( (*w)->rh ); - (*w)->lh = (*w)->son->lh; - (*w)->rh = (*w)->son->rh; - - tmp = (*w)->son; - (*w)->son = (*w)->son->son; - free( tmp ); - } - break; - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - remove_unused_vars_in_wff( &i ); - } - break; - case NOT: - remove_unused_vars_in_wff( &((*w)->son) ); - break; - case COMP: - case ATOM: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: remove var, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -Bool var_used_in_wff( int code_var, WffNode *w ) - -{ - - WffNode *i; - int j; - - switch ( w->connective ) { - case ALL: - case EX: - return var_used_in_wff( code_var, w->son ); - case AND: - case OR: - for ( i = w->sons; i; i = i->next ) { - if ( var_used_in_wff( code_var, i ) ) { - return TRUE; - } - } - return FALSE; - case NOT: - return var_used_in_wff( code_var, w->son ); - case ATOM: - for ( j = 0; j < garity[w->fact->predicate]; j++ ) { - if ( w->fact->args[j] >= 0 ) { - continue; - } - if ( w->fact->args[j] == code_var ) { - return TRUE; - } - } - return FALSE; - case COMP: - if ( var_used_in_exp( code_var, w->lh ) ) { - return TRUE; - } - if ( var_used_in_exp( code_var, w->rh ) ) { - return TRUE; - } - return FALSE; - case TRU: - case FAL: - return FALSE; - default: - printf("\nwon't get here: var used ?, non logical %d\n\n", - w->connective); - exit( 1 ); - } - - -} - - - -Bool var_used_in_exp( int code_var, ExpNode *n ) - -{ - - int i; - - switch ( n->connective ) { - case AD: - case SU: - case MU: - case DI: - if ( var_used_in_exp( code_var, n->leftson ) || - var_used_in_exp( code_var, n->rightson ) ) { - return TRUE; - } - return FALSE; - case MINUS: - if ( var_used_in_exp( code_var, n->son ) ) { - return TRUE; - } - return FALSE; - case NUMBER: - return FALSE; - case FHEAD: - if ( n->fluent ) { - for ( i = 0; i < gf_arity[n->fluent->function]; i++ ) { - if ( n->fluent->args[i] >= 0 ) { - continue; - } - if ( n->fluent->args[i] == code_var ) { - return TRUE; - } - } - } else { - /* in the case that this is called from ahead, where fluents - * have been replaced with their identifiers - */ - } - return FALSE; - default: - printf("\n\nvar used in expnode: wrong specifier %d", - n->connective); - exit( 1 ); - } - -} - - - -void decrement_inferior_vars( int var, WffNode *w ) - -{ - - WffNode *i; - int j; - - switch ( w->connective ) { - case ALL: - case EX: - w->var--; - decrement_inferior_vars( var, w->son ); - break; - case AND: - case OR: - for ( i = w->sons; i; i = i->next ) { - decrement_inferior_vars( var, i ); - } - break; - case NOT: - decrement_inferior_vars( var, w->son ); - break; - case ATOM: - for ( j = 0; j < garity[w->fact->predicate]; j++ ) { - if ( w->fact->args[j] >= 0 ) { - continue; - } - if ( DECODE_VAR( w->fact->args[j] ) > var ) { - w->fact->args[j]++; - } - } - break; - case COMP: - decrement_inferior_vars_in_exp( var, w->lh ); - decrement_inferior_vars_in_exp( var, w->rh ); - break; - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: decrement, non logical %d\n\n", - w->connective); - exit( 1 ); - } - -} - - - -void decrement_inferior_vars_in_exp( int var, ExpNode *n ) - -{ - - int j; - - switch ( n->connective ) { - case AD: - case SU: - case MU: - case DI: - decrement_inferior_vars_in_exp( var, n->leftson ); - decrement_inferior_vars_in_exp( var, n->rightson ); - break; - case MINUS: - decrement_inferior_vars_in_exp( var, n->son ); - break; - case NUMBER: - break; - case FHEAD: - if ( n->fluent ) { - for ( j = 0; j < gf_arity[n->fluent->function]; j++ ) { - if ( n->fluent->args[j] >= 0 ) { - continue; - } - if ( DECODE_VAR( n->fluent->args[j] ) > var ) { - n->fluent->args[j]++; - } - } - } else { - /* in the case that this is called from ahead, where fluents - * have been replaced with their identifiers - */ - } - break; - default: - printf("\n\ndecr inf vars in expnode: wrong specifier %d", - n->connective); - exit( 1 ); - } - -} - - - -void simplify_wff( WffNode **w ) - -{ - - WffNode *i, *tmp; - int m; - Bool ct; - - switch ( (*w)->connective ) { - case ALL: - case EX: - simplify_wff( &((*w)->son) ); - if ( (*w)->son->connective == TRU || - (*w)->son->connective == FAL ) { - (*w)->connective = (*w)->son->connective; - free( (*w)->son ); - (*w)->son = NULL; - if ( (*w)->var_name ) { - free( (*w)->var_name ); - } - } - break; - case AND: - m = 0; - i = (*w)->sons; - while ( i ) { - simplify_wff( &i ); - if ( i->connective == FAL ) { - (*w)->connective = FAL; - /* free_WffNode( (*w)->sons ); */ - (*w)->sons = NULL; - return; - } - if ( i->connective == TRU ) { - if ( i->prev ) { - i->prev->next = i->next; - } else { - (*w)->sons = i->next; - } - if ( i->next ) { - i->next->prev = i->prev; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - i = i->next; - m++; - } - if ( m == 0 ) { - (*w)->connective = TRU; - free_WffNode( (*w)->sons ); - (*w)->sons = NULL; - } - if ( m == 1 ) { - (*w)->connective = (*w)->sons->connective; - (*w)->var = (*w)->sons->var; - (*w)->var_type = (*w)->sons->var_type; - if ( (*w)->var_name ) { - free( (*w)->var_name ); - } - (*w)->var_name = (*w)->sons->var_name; - (*w)->son = (*w)->sons->son; - if ( (*w)->fact ) { - free( (*w)->fact ); - } - (*w)->fact = (*w)->sons->fact; - (*w)->comp = (*w)->sons->comp; - if ( (*w)->lh ) free_ExpNode( (*w)->lh ); - if ( (*w)->rh ) free_ExpNode( (*w)->rh ); - (*w)->lh = (*w)->sons->lh; - (*w)->rh = (*w)->sons->rh; - - tmp = (*w)->sons; - (*w)->sons = (*w)->sons->sons; - free( tmp ); - } - break; - case OR: - m = 0; - i = (*w)->sons; - while ( i ) { - simplify_wff( &i ); - if ( i->connective == TRU ) { - (*w)->connective = TRU; - free_WffNode( (*w)->sons ); - (*w)->sons = NULL; - return; - } - if ( i->connective == FAL ) { - if ( i->prev ) { - i->prev->next = i->next; - } else { - (*w)->sons = i->next; - } - if ( i->next ) { - i->next->prev = i->prev; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - i = i->next; - m++; - } - if ( m == 0 ) { - (*w)->connective = FAL; - /* free_WffNode( (*w)->sons ); */ - (*w)->sons = NULL; - } - if ( m == 1 ) { - (*w)->connective = (*w)->sons->connective; - (*w)->var = (*w)->sons->var; - (*w)->var_type = (*w)->sons->var_type; - if ( (*w)->var_name ) { - free( (*w)->var_name ); - } - (*w)->var_name = (*w)->sons->var_name; - (*w)->son = (*w)->sons->son; - if ( (*w)->fact ) { - free( (*w)->fact ); - } - (*w)->fact = (*w)->sons->fact; - (*w)->comp = (*w)->sons->comp; - if ( (*w)->lh ) free_ExpNode( (*w)->lh ); - if ( (*w)->rh ) free_ExpNode( (*w)->rh ); - (*w)->lh = (*w)->sons->lh; - (*w)->rh = (*w)->sons->rh; - - tmp = (*w)->sons; - (*w)->sons = (*w)->sons->sons; - free( tmp ); - } - break; - case NOT: - simplify_wff( &((*w)->son) ); - if ( (*w)->son->connective == TRU || - (*w)->son->connective == FAL ) { - (*w)->connective = ( (*w)->son->connective == TRU ) ? FAL : TRU; - free( (*w)->son ); - (*w)->son = NULL; - } - break; - case ATOM: - if ( (*w)->visited ) { - /* already seen and not changed - */ - break; - } - if ( !possibly_negative( (*w)->fact ) ) { - (*w)->connective = TRU; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - if ( !possibly_positive( (*w)->fact ) ) { - (*w)->connective = FAL; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - (*w)->visited = TRUE; - break; - case COMP: - simplify_exp( &((*w)->lh) ); - simplify_exp( &((*w)->rh) ); - if ( (*w)->lh->connective != NUMBER || - (*w)->rh->connective != NUMBER ) { - /* logical simplification only possible if both parts are numbers - */ - break; - } - ct = number_comparison_holds( (*w)->comp, (*w)->lh->value, (*w)->rh->value ); - if ( ct ) { - (*w)->connective = TRU; - free_ExpNode( (*w)->lh ); - (*w)->lh = NULL; - free_ExpNode( (*w)->rh ); - (*w)->rh = NULL; - (*w)->comp = -1; - break; - } else { - (*w)->connective = FAL; - free_ExpNode( (*w)->lh ); - (*w)->lh = NULL; - free_ExpNode( (*w)->rh ); - (*w)->rh = NULL; - (*w)->comp = -1; - break; - } - break; - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: simplify, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -void simplify_exp( ExpNode **n ) - -{ - - int j, f, k; - - switch ( (*n)->connective ) { - case AD: - simplify_exp( &((*n)->leftson) ); - simplify_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value + (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case SU: - simplify_exp( &((*n)->leftson) ); - simplify_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value - (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MU: - simplify_exp( &((*n)->leftson) ); - simplify_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case DI: - simplify_exp( &((*n)->leftson) ); - simplify_exp( &((*n)->rightson) ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - if ( (*n)->rightson->value == 0 ) { - /* kind of unclean: simply leave that in here; - * we will later determine the right thing - * to do with it. - */ - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value / (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MINUS: - simplify_exp( &((*n)->son) ); - if ( (*n)->son->connective != NUMBER ) break; - (*n)->connective = NUMBER; - (*n)->value = ((float) (-1)) * (*n)->son->value; - free_ExpNode( (*n)->son ); - (*n)->son = NULL; - break; - case NUMBER: - break; - case FHEAD: - if ( !(*n)->fluent ) { - /* in the case that this is called from ahead, where fluents - * have been replaced with their identifiers - */ - break; - } - f = (*n)->fluent->function; - for ( j = 0; j < gf_arity[f]; j++ ) { - if ( (*n)->fluent->args[j] < 0 ) { - break; - } - } - if ( j < gf_arity[f] ) { - break; - } - /* we handle only the case where the fluent is fully instantiated, - * static, and in the initial state. - */ - if ( gis_changed[f] ) break; - for ( j = 0; j < gnum_initial_function[f]; j++ ) { - for ( k = 0; k < gf_arity[f]; k++ ) { - if ( ginitial_function[f][j].fluent.args[k] != - (*n)->fluent->args[k] ) break; - } - if ( k < gf_arity[f] ) continue; - (*n)->connective = NUMBER; - (*n)->value = ginitial_function[f][j].value; - break; - } - break; - default: - printf("\n\nsimplify expnode: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - -} - - - -void expand_quantifiers_in_wff( WffNode **w, int var, int constant ) - -{ - - WffNode *r = NULL, *tmp, *i; - int j, l; - Bool change, ct; - - if ( !(*w) ) { - return; - } - - switch ( (*w)->connective ) { - case ALL: - case EX: - if ( var != -1 ) {/* depth first: upper node is active */ - expand_quantifiers_in_wff( &((*w)->son), var, constant ); - return; - } - - (*w)->connective = ( (*w)->connective == ALL ) ? AND : OR; - for ( j = 0; j < gtype_size[(*w)->var_type]; j++ ) { - tmp = copy_Wff( (*w)->son ); - expand_quantifiers_in_wff( &tmp, (*w)->var, gtype_consts[(*w)->var_type][j] ); - tmp->next = r; - if ( r ) { - r->prev = tmp; - } - r = tmp; - } - - free_WffNode( (*w)->son ); - (*w)->sons = r; - (*w)->var = -1; - (*w)->var_type = -1; - if ( (*w)->var_name ) { - free( (*w)->var_name ); - } - (*w)->var_name = NULL; - - /* now make all sons expand their quantifiers - */ - for ( i = (*w)->sons; i; i = i->next ) { - expand_quantifiers_in_wff( &i, -1, -1 ); - } - break; - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - expand_quantifiers_in_wff( &i, var, constant ); - } - break; - case NOT: - expand_quantifiers_in_wff( &((*w)->son), var, constant ); - break; - case ATOM: - if ( var == -1 ) { - break; - } - - change = FALSE; - for ( l = 0; l < garity[(*w)->fact->predicate]; l++ ) { - if ( (*w)->fact->args[l] == ENCODE_VAR( var ) ) { - (*w)->fact->args[l] = constant; - change = TRUE; - } - } - if ( !change && (*w)->visited ) { - /* we did not change anything and we've already seen that node - * --> it cant be simplified - */ - break; - } - if ( !possibly_negative( (*w)->fact ) ) { - (*w)->connective = TRU; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - if ( !possibly_positive( (*w)->fact ) ) { - (*w)->connective = FAL; - free( (*w)->fact ); - (*w)->fact = NULL; - break; - } - (*w)->visited = TRUE; - break; - case COMP: - if ( var == -1 ) { - break; - } - - replace_var_with_const_in_exp( &((*w)->lh), var, constant ); - replace_var_with_const_in_exp( &((*w)->rh), var, constant ); - if ( (*w)->lh->connective != NUMBER || - (*w)->rh->connective != NUMBER ) { - /* logical simplification only possible if both parts are numbers - */ - break; - } - ct = number_comparison_holds( (*w)->comp, (*w)->lh->value, (*w)->rh->value ); - if ( ct ) { - (*w)->connective = TRU; - free_ExpNode( (*w)->lh ); - (*w)->lh = NULL; - free_ExpNode( (*w)->rh ); - (*w)->rh = NULL; - (*w)->comp = -1; - break; - } else { - (*w)->connective = FAL; - free_ExpNode( (*w)->lh ); - (*w)->lh = NULL; - free_ExpNode( (*w)->rh ); - (*w)->rh = NULL; - (*w)->comp = -1; - break; - } - break; - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: expansion, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -void replace_var_with_const_in_exp( ExpNode **n, int var, int constant ) - -{ - - int j, f, k; - - switch ( (*n)->connective ) { - case AD: - replace_var_with_const_in_exp( &((*n)->leftson), var, constant ); - replace_var_with_const_in_exp( &((*n)->rightson), var, constant ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value + (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case SU: - replace_var_with_const_in_exp( &((*n)->leftson), var, constant ); - replace_var_with_const_in_exp( &((*n)->rightson), var, constant ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value - (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MU: - replace_var_with_const_in_exp( &((*n)->leftson), var, constant ); - replace_var_with_const_in_exp( &((*n)->rightson), var, constant ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value * (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case DI: - replace_var_with_const_in_exp( &((*n)->leftson), var, constant ); - replace_var_with_const_in_exp( &((*n)->rightson), var, constant ); - if ( (*n)->leftson->connective != NUMBER || - (*n)->rightson->connective != NUMBER ) { - break; - } - if ( (*n)->rightson->value == 0 ) { - /* kind of unclean: simply leave that in here; - * we will later determine the right thing - * to do with it. - */ - break; - } - (*n)->connective = NUMBER; - (*n)->value = (*n)->leftson->value / (*n)->rightson->value; - free_ExpNode( (*n)->leftson ); - (*n)->leftson = NULL; - free_ExpNode( (*n)->rightson ); - (*n)->rightson = NULL; - break; - case MINUS: - replace_var_with_const_in_exp( &((*n)->son), var, constant ); - if ( (*n)->son->connective != NUMBER ) break; - (*n)->connective = NUMBER; - (*n)->value = ((float) (-1)) * (*n)->son->value; - free_ExpNode( (*n)->son ); - (*n)->son = NULL; - break; - case NUMBER: - break; - case FHEAD: - if ( !(*n)->fluent ) { - /* in the case that this is called from ahead, where fluents - * have been replaced with their identifiers - */ - break; - } - f = (*n)->fluent->function; - for ( j = 0; j < gf_arity[f]; j++ ) { - if ( (*n)->fluent->args[j] == ENCODE_VAR( var ) ) { - (*n)->fluent->args[j] = constant; - } - } - for ( j = 0; j < gf_arity[f]; j++ ) { - if ( (*n)->fluent->args[j] < 0 ) { - break; - } - } - if ( j < gf_arity[f] ) { - break; - } - /* we handle only the case where the fluent is fully instantiated, - * static, and in the initial state. - */ - if ( gis_changed[f] ) break; - for ( j = 0; j < gnum_initial_function[f]; j++ ) { - for ( k = 0; k < gf_arity[f]; k++ ) { - if ( ginitial_function[f][j].fluent.args[k] != - (*n)->fluent->args[k] ) break; - } - if ( k < gf_arity[f] ) continue; - (*n)->connective = NUMBER; - (*n)->value = ginitial_function[f][j].value; - break; - } - break; - default: - printf("\n\nreplace var with const in expnode: wrong specifier %d", - (*n)->connective); - exit( 1 ); - } - -} - - - -WffNode *copy_Wff( WffNode *w ) - -{ - - WffNode *tmp, *tmp2, *i; - int j; - - tmp = new_WffNode( w->connective ); - - switch ( w->connective ) { - case ALL: - case EX: - tmp->var = w->var; - tmp->var_type = w->var_type; - tmp->son = copy_Wff( w->son ); - break; - case AND: - case OR: - for ( i = w->sons; i; i = i->next ) { - tmp2 = copy_Wff( i ); - if ( tmp->sons ) { - tmp->sons->prev = tmp2; - } - tmp2->next = tmp->sons; - tmp->sons = tmp2; - } - break; - case NOT: - tmp->son = copy_Wff( w->son ); - break; - case ATOM: - tmp->fact = new_Fact(); - tmp->fact->predicate = w->fact->predicate; - for ( j = 0; j < garity[w->fact->predicate]; j++ ) { - tmp->fact->args[j] = w->fact->args[j]; - } - tmp->visited = w->visited; - break; - case COMP: - tmp->comp = w->comp; - tmp->lh = copy_Exp( w->lh ); - tmp->rh = copy_Exp( w->rh ); - break; - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: copy, non logical %d\n\n", - w->connective); - exit( 1 ); - } - - return tmp; - -} - - - -ExpNode *copy_Exp( ExpNode *n ) - -{ - - ExpNode *tmp; - int i; - - tmp = new_ExpNode( n->connective ); - - switch ( n->connective ) { - case AD: - case SU: - case MU: - case DI: - tmp->leftson = copy_Exp( n->leftson ); - tmp->rightson = copy_Exp( n->rightson ); - break; - case MINUS: - tmp->son = copy_Exp( n->son ); - break; - case NUMBER: - tmp->value = n->value; - break; - case FHEAD: - if ( n->fluent ) { - tmp->fluent = new_Fluent(); - tmp->fluent->function = n->fluent->function; - for ( i = 0; i < gf_arity[tmp->fluent->function]; i++ ) { - tmp->fluent->args[i] = n->fluent->args[i]; - } - } else { - /* in the case that this is called from ahead, where fluents - * have been replaced with their identifiers - */ - tmp->fl = n->fl; - } - break; - default: - printf("\n\ncopy expnode: wrong specifier %d", - n->connective); - exit( 1 ); - } - - return tmp; - -} - - - -Bool possibly_positive( Fact *f ) - -{ - - int i; - - if ( gis_added[f->predicate] ) { - return TRUE; - } - - for ( i = 0; i < gnum_initial_predicate[f->predicate]; i++ ) { - if ( matches( f, &(ginitial_predicate[f->predicate][i]) ) ) { - return TRUE; - } - } - - return FALSE; - -} - - - -Bool possibly_negative( Fact *f ) - -{ - - int i; - - if ( gis_deleted[f->predicate] ) { - return TRUE; - } - - for ( i = 0; i < garity[f->predicate]; i++ ) { - if ( f->args[i] < 0 ) { - return TRUE; - } - } - - for ( i = 0; i < gnum_initial_predicate[f->predicate]; i++ ) { - if ( matches( f, &(ginitial_predicate[f->predicate][i]) ) ) { - return FALSE; - } - } - - return TRUE; - -} - - - -Bool matches( Fact *f1, Fact *f2 ) - -{ - - int i; - - for ( i = 0; i < garity[f1->predicate]; i++ ) { - if ( f1->args[i] >= 0 ) { - if ( f2->args[i] >= 0 && - f1->args[i] != f2->args[i] ) { - return FALSE; - } - } - } - - return TRUE; - -} - - - -void cleanup_wff( WffNode **w ) - -{ - - merge_ANDs_and_ORs_in_wff( w ); - detect_tautologies_in_wff( w ); - simplify_wff( w ); - detect_tautologies_in_wff( w ); - merge_ANDs_and_ORs_in_wff( w ); - -} - - - -void detect_tautologies_in_wff( WffNode **w ) - -{ - - WffNode *i, *j, *tmp; - - switch ( (*w)->connective ) { - case ALL: - case EX: - detect_tautologies_in_wff( &((*w)->son) ); - break; - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - detect_tautologies_in_wff( &i ); - } - for ( i = (*w)->sons; i && i->next; i = i->next ) { - j = i->next; - while ( j ) { - if ( are_identical_ATOMs( i, j ) ) { - j->prev->next = j->next; - if ( j->next ) { - j->next->prev = j->prev; - } - tmp = j; - j = j->next; - if ( tmp->fact ) { - free( tmp->fact ); - } - free( tmp ); - continue; - } - if ( i->connective == NOT && - are_identical_ATOMs( i->son, j ) ) { - (*w)->connective = ( (*w)->connective == AND ) ? FAL : TRU; - free_WffNode( (*w)->son ); - (*w)->son = NULL; - return; - } - if ( j->connective == NOT && - are_identical_ATOMs( i, j->son ) ) { - (*w)->connective = ( (*w)->connective == AND ) ? FAL : TRU; - free_WffNode( (*w)->son ); - (*w)->son = NULL; - return; - } - j = j->next; - } - } - break; - case NOT: - detect_tautologies_in_wff( &((*w)->son) ); - break; - case ATOM: - case COMP: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: tautologies, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -Bool are_identical_ATOMs( WffNode *w1, WffNode *w2 ) - -{ - - int i; - - if ( w1->connective != ATOM || - w2->connective != ATOM ) { - return FALSE; - } - - if ( w1->fact->predicate != w2->fact->predicate ) { - return FALSE; - } - - for ( i = 0; i < garity[w1->fact->predicate]; i++ ) { - if ( w1->fact->args[i] != w2->fact->args[i] ) { - return FALSE; - } - } - - return TRUE; - -} - - - -void merge_ANDs_and_ORs_in_wff( WffNode **w ) - -{ - - WffNode *i, *j, *tmp; - - switch ( (*w)->connective ) { - case ALL: - case EX: - merge_ANDs_and_ORs_in_wff( &((*w)->son) ); - break; - case AND: - case OR: - i = (*w)->sons; - while ( i ) { - merge_ANDs_and_ORs_in_wff( &i ); - if ( i->connective == (*w)->connective ) { - if ( !(i->sons) ) { - if ( i->next ) { - i->next->prev = i->prev; - } - if ( i->prev ) { - i->prev->next = i->next; - } else { - (*w)->sons = i->next; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - for ( j = i->sons; j->next; j = j->next ); - j->next = i->next; - if ( i->next ) { - i->next->prev = j; - } - if ( i->prev ) { - i->prev->next = i->sons; - i->sons->prev = i->prev; - } else { - (*w)->sons = i->sons; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - i = i->next; - } - break; - case NOT: - merge_ANDs_and_ORs_in_wff( &((*w)->son) ); - break; - case COMP: - case ATOM: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: merge, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -void NOTs_down_in_wff( WffNode **w ) - -{ - - WffNode *tmp1, *tmp2, *i; - - switch ( (*w)->connective ) { - case ALL: - case EX: - printf("\ntrying to put nots down in quantified formula! debug me\n\n"); - exit( 1 ); - break; - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - NOTs_down_in_wff( &i ); - } - break; - case NOT: - if ( (*w)->son->connective == NOT ) { - (*w)->connective = (*w)->son->son->connective; - (*w)->fact = (*w)->son->son->fact; - (*w)->comp = (*w)->son->son->comp; - (*w)->lh = (*w)->son->son->lh; - (*w)->rh = (*w)->son->son->rh; - tmp1 = (*w)->son; - tmp2 = (*w)->son->son; - (*w)->sons = (*w)->son->son->sons; - (*w)->son = (*w)->son->son->son; - /* don't need to remember (*w)->son->son->next: this is empty because - * otherwise the resp. father, (*w)->son, would have been an - * AND or OR - */ - free( tmp1 ); - free( tmp2 ); - NOTs_down_in_wff( w ); - break; - } - if ( (*w)->son->connective == AND || - (*w)->son->connective == OR ) { - (*w)->connective = ( (*w)->son->connective == AND ) ? OR : AND; - (*w)->sons = (*w)->son->sons; - free( (*w)->son ); - (*w)->son = NULL; - for ( i = (*w)->sons; i; i = i->next ) { - tmp1 = new_WffNode( i->connective ); - tmp1->son = i->son; - tmp1->sons = i->sons; - tmp1->fact = i->fact; - tmp1->comp = i->comp; - tmp1->lh = i->lh; - tmp1->rh = i->rh; - i->connective = NOT; - i->son = tmp1; - i->sons = NULL; - i->fact = NULL; - i->comp = -1; - i->lh = NULL; - i->rh = NULL; - NOTs_down_in_wff( &i ); - } - break; - } - if ( (*w)->son->connective == COMP ) { - if ( (*w)->son->comp != EQ ) { - (*w)->connective = COMP; - (*w)->lh = (*w)->son->lh; - (*w)->rh = (*w)->son->rh; - switch ( (*w)->son->comp ) { - case LE: - (*w)->comp = GEQ; - break; - case LEQ: - (*w)->comp = GE; - break; - case GEQ: - (*w)->comp = LE; - break; - case GE: - (*w)->comp = LEQ; - break; - default: - printf("\n\nillegal comparator not EQ %d in nots down", - (*w)->son->comp); - exit( 1 ); - } - free( (*w)->son ); - (*w)->son = NULL; - } else { - (*w)->connective = OR; - (*w)->sons = (*w)->son; - (*w)->son = NULL; - (*w)->sons->comp = LE; - tmp1 = new_WffNode( COMP ); - tmp1->lh = copy_Exp( (*w)->sons->lh ); - tmp1->rh = copy_Exp( (*w)->sons->rh ); - tmp1->comp = GE; - tmp1->prev = (*w)->sons; - (*w)->sons->next = tmp1; - } - } - break; - case COMP: - case ATOM: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: nots down, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - - -} - - - - - - - - - - - -/**************************************************** - * NEGATIVE PRE- AND EFFECT- CONDITIONS TRANSLATION * - ****************************************************/ - - - - - - - - -int lconsts[MAX_ARITY]; - - - - - - - - -void translate_negative_preconds( void ) - -{ - - int i, j; - Effect *e; - Facts *f; - FluentValues *ff; - - while ( translate_one_negative_cond( ggoal ) ); - - for ( i = 0; i < gnum_operators; i++ ) { - while ( translate_one_negative_cond( goperators[i]->preconds ) ); - - for ( e = goperators[i]->effects; e; e = e->next ) { - while ( translate_one_negative_cond( e->conditions ) ); - } - } - - if ( gcmd_line.display_info == 108 ) { - printf("\n\ndomain with translated negative conds:"); - - printf("\n\noperators are:"); - for ( i = 0; i < gnum_operators; i++ ) { - print_Operator( goperators[i] ); - } - printf("\n\n"); - - printf("\ninitial state is:\n"); - for ( f = ginitial; f; f = f->next ) { - printf("\n"); - print_Fact( f->fact ); - } - printf("\n"); - for ( ff = gf_initial; ff; ff = ff->next ) { - printf("\n"); - print_Fluent( &(ff->fluent) ); - printf(": %f", ff->value); - } - printf("\n\n"); - - printf("\n\nindividual predicates:\n"); - for ( i = 0; i < gnum_predicates; i++ ) { - printf("\n\n%s:", gpredicates[i]); - if ( !gis_added[i] && - !gis_deleted[i] ) { - printf(" --- STATIC"); - } - for ( j = 0; j < gnum_initial_predicate[i]; j++ ) { - printf("\n"); - print_Fact( &(ginitial_predicate[i][j]) ); - } - } - printf("\n\nindividual functions:"); - for ( i = 0; i < gnum_functions; i++ ) { - printf("\n\n%s:", gfunctions[i]); - if ( !gis_changed[i] ) { - printf(" --- STATIC"); - } - for ( j = 0; j < gnum_initial_function[i]; j++ ) { - printf("\n"); - print_Fluent( &(ginitial_function[i][j].fluent) ); - printf(": %f", ginitial_function[i][j].value); - } - } - printf("\n\n"); - - printf("\n\ngoal is:\n"); - print_Wff( ggoal, 0 ); - printf("\n\n"); - } - -} - - - -Bool translate_one_negative_cond( WffNode *w ) - -{ - - WffNode *i; - int p, j, k, m; - Effect *e; - Literal *l, *tmp; - - switch ( w->connective ) { - case ALL: - case EX: - printf("\ntranslating NOT in quantified formula! debug me\n\n"); - exit( 1 ); - case AND: - case OR: - for ( i = w->sons; i; i = i->next ) { - if ( translate_one_negative_cond( i ) ) { - return TRUE; - } - } - return FALSE; - case NOT: - if ( w->son->fact->predicate == -1 ) { - return FALSE; - } - break; - case COMP: - case ATOM: - case TRU: - case FAL: - return FALSE; - default: - printf("\nwon't get here: translate one neg cond, non logical %d\n\n", - w->connective); - exit( 1 ); - } - - - if ( gnum_predicates == MAX_PREDICATES ) { - printf("\ntoo many predicates in translation! increase MAX_PREDICATES (currently %d)\n\n", - MAX_PREDICATES); - exit( 1 ); - } - p = w->son->fact->predicate; - /* safety check: we disallow negative conds on derived preds!! - */ - if ( gaxiom_added[p]) { - printf("\nA derived predicate appears negated in the negation normal form of a derivation rule condition, an operator precondition, or the goal."); - printf("\nSorry, this version of FF does not allow any of this. Bailing out.\n\n"); - exit( 1 ); - } else { - printf("\ntranslating negated cond for predicate %s", gpredicates[p]); - } - - gpredicates[gnum_predicates] = new_Token( strlen( gpredicates[p] ) + 5 ); - sprintf( gpredicates[gnum_predicates], "NOT-%s", gpredicates[p] ); - garity[gnum_predicates] = garity[p]; - for ( j = 0; j < garity[p]; j++ ) { - gpredicates_args_type[gnum_predicates][j] = - gpredicates_args_type[p][j]; - } - gis_added[gnum_predicates] = FALSE; - gis_deleted[gnum_predicates] = FALSE; - m = 1; - for ( j = 0; j < garity[gnum_predicates]; j++ ) { - m *= gtype_size[gpredicates_args_type[gnum_predicates][j]]; - } - ginitial_predicate[gnum_predicates] = ( Fact * ) calloc( m, sizeof( Fact ) ); - gnum_predicates++; - - - replace_not_p_with_n_in_wff( p, gnum_predicates - 1, &ggoal ); - - for ( j = 0; j < gnum_operators; j++ ) { - replace_not_p_with_n_in_wff( p, gnum_predicates - 1, - &(goperators[j]->preconds) ); - - for ( e = goperators[j]->effects; e; e = e->next ) { - replace_not_p_with_n_in_wff( p, gnum_predicates - 1, - &(e->conditions) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->fact.predicate != p ) { - continue; - } - tmp = new_Literal(); - if ( l->negated ) { - tmp->negated = FALSE; - gis_added[gnum_predicates - 1] = TRUE; - } else { - tmp->negated = TRUE; - gis_deleted[gnum_predicates - 1] = TRUE; - } - tmp->fact.predicate = gnum_predicates - 1; - for ( k = 0; k < garity[p]; k++ ) { - tmp->fact.args[k] = l->fact.args[k]; - } - if ( l->prev ) { - tmp->prev = l->prev; - tmp->prev->next = tmp; - } else { - e->effects = tmp; - } - tmp->next = l; - l->prev = tmp; - } - } - } - - add_to_initial_state( p, gnum_predicates - 1, 0 ); - - return TRUE; - -} - - - -void replace_not_p_with_n_in_wff( int p, int n, WffNode **w ) - -{ - - WffNode *i; - - switch ( (*w)->connective ) { - case ALL: - case EX: - printf("\nreplacing p with NOT-p in quantified formula! debug me\n\n"); - exit( 1 ); - case AND: - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - replace_not_p_with_n_in_wff( p, n, &i ); - } - break; - case NOT: - if ( (*w)->son->fact->predicate == p ) { - (*w)->connective = ATOM; - (*w)->NOT_p = p; - (*w)->fact = (*w)->son->fact; - (*w)->fact->predicate = n; - free( (*w)->son ); - (*w)->son = NULL; - } - break; - case ATOM: - case COMP: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: replace p with NOT-p, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -void add_to_initial_state( int p, int n, int index ) - -{ - - int i, j; - Facts *tmp; - - if ( index == garity[p] ) { - /* see if contrary fact is there in ini - */ - for ( i = 0; i < gnum_initial_predicate[p]; i++ ) { - for ( j = 0; j < garity[p]; j++ ) { - if ( ginitial_predicate[p][i].args[j] != lconsts[j] ) { - break; - } - } - if ( j == garity[p] ) { - break; - } - } - if ( i < gnum_initial_predicate[p] ) { - return; - } - - /* no: add new fact to ini - */ - ginitial_predicate[n][gnum_initial_predicate[n]].predicate = n; - for ( i = 0; i < garity[n]; i++ ) { - ginitial_predicate[n][gnum_initial_predicate[n]].args[i] = lconsts[i]; - } - gnum_initial_predicate[n]++; - - if ( !gis_added[n] && - !gis_deleted[n] ) { - return; - } - - tmp = new_Facts(); - tmp->fact->predicate = n; - for ( i = 0; i < garity[p]; i++ ) { - tmp->fact->args[i] = lconsts[i]; - } - tmp->next = ginitial; - ginitial = tmp; - gnum_initial++; - return; - } - - for ( i = 0; i < gtype_size[gpredicates_args_type[p][index]]; i++ ) { - lconsts[index] = gtype_consts[gpredicates_args_type[p][index]][i]; - add_to_initial_state( p, n, index + 1 ); - } - -} - - - - - - - - - - - -/******************************************************************* - * SPLIT DOMAIN IN PREPARATION FOR SEPARATE INSTANTIATION ROUTINES * - *******************************************************************/ - - - - - - - - - - -void split_domain( void ) - -{ - - int i, j, m, s = 0, mn; - Effect *e; - WffNode *w, *ww, *www; - NormOperator *tmp_op; - Fact *tmp_ft; - - for ( i = 0; i < MAX_TYPES; i++ ) { - gnum_intersected_types[i] = -1; - } - - for ( i = 0; i < gnum_operators; i++ ) { - if ( (m = is_dnf( goperators[i]->preconds )) != -1 ) { - for ( e = goperators[i]->effects; e; e = e->next ) { - if ( is_dnf( e->conditions ) == -1 ) { - break; - } - } - if ( !e ) { - goperators[i]->hard = FALSE; - s += m; - } - } - } - - ghard_operators = ( Operator_pointer * ) calloc( MAX_OPERATORS, sizeof( Operator ) ); - gnum_hard_operators = 0; - geasy_operators = ( NormOperator_pointer * ) calloc( s, sizeof( NormOperator_pointer ) ); - gnum_easy_operators = 0; - - for ( i = 0; i < gnum_operators; i++ ) { - if ( goperators[i]->hard ) { - ghard_operators[gnum_hard_operators++] = goperators[i]; - continue; - } - w = goperators[i]->preconds; - switch ( w->connective ) { - case OR: - for ( ww = w->sons; ww; ww = ww->next ) { - tmp_op = new_NormOperator( goperators[i] ); - if ( ww->connective == AND ) { - m = 0; - mn = 0; - for ( www = ww->sons; www; www = www->next ) { - if ( www->connective == ATOM ) m++; - if ( www->connective == COMP ) mn++; - } - tmp_op->preconds = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp_op->numeric_preconds_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp_op->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - for ( www = ww->sons; www; www = www->next ) { - if ( www->connective == ATOM ) { - tmp_ft = &(tmp_op->preconds[tmp_op->num_preconds]); - tmp_ft->predicate = www->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = www->fact->args[j]; - } - tmp_op->num_preconds++; - } - if ( www->connective == COMP ) { - tmp_op->numeric_preconds_comp[tmp_op->num_numeric_preconds] = www->comp; - tmp_op->numeric_preconds_lh[tmp_op->num_numeric_preconds] = copy_Exp( www->lh ); - tmp_op->numeric_preconds_rh[tmp_op->num_numeric_preconds] = copy_Exp( www->rh ); - tmp_op->num_numeric_preconds++; - } - } - } else { - if ( ww->connective == ATOM ) { - tmp_op->preconds = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp_ft = &(tmp_op->preconds[0]); - tmp_ft->predicate = ww->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = ww->fact->args[j]; - } - tmp_op->num_preconds = 1; - } - if ( ww->connective == COMP ) { - tmp_op->numeric_preconds_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp_op->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_comp[0] = ww->comp; - tmp_op->numeric_preconds_lh[0] = copy_Exp( ww->lh ); - tmp_op->numeric_preconds_rh[0] = copy_Exp( ww->rh ); - tmp_op->num_numeric_preconds = 1; - } - } - make_normal_effects( &tmp_op, goperators[i] ); - geasy_operators[gnum_easy_operators++] = tmp_op; - } - break; - case AND: - tmp_op = new_NormOperator( goperators[i] ); - m = 0; - mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) m++; - if ( ww->connective == COMP ) mn++; - } - tmp_op->preconds = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp_op->numeric_preconds_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp_op->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) { - tmp_ft = &(tmp_op->preconds[tmp_op->num_preconds]); - tmp_ft->predicate = ww->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = ww->fact->args[j]; - } - tmp_op->num_preconds++; - } - if ( ww->connective == COMP ) { - tmp_op->numeric_preconds_comp[tmp_op->num_numeric_preconds] = ww->comp; - tmp_op->numeric_preconds_lh[tmp_op->num_numeric_preconds] = copy_Exp( ww->lh ); - tmp_op->numeric_preconds_rh[tmp_op->num_numeric_preconds] = copy_Exp( ww->rh ); - tmp_op->num_numeric_preconds++; - } - } - make_normal_effects( &tmp_op, goperators[i] ); - geasy_operators[gnum_easy_operators++] = tmp_op; - break; - case ATOM: - tmp_op = new_NormOperator( goperators[i] ); - tmp_op->preconds = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp_ft = &(tmp_op->preconds[0]); - tmp_ft->predicate = w->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = w->fact->args[j]; - } - tmp_op->num_preconds = 1; - make_normal_effects( &tmp_op, goperators[i] ); - geasy_operators[gnum_easy_operators++] = tmp_op; - break; - case COMP: - tmp_op = new_NormOperator( goperators[i] ); - tmp_op->numeric_preconds_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp_op->numeric_preconds_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_op->numeric_preconds_comp[0] = w->comp; - tmp_op->numeric_preconds_lh[0] = copy_Exp( w->lh ); - tmp_op->numeric_preconds_rh[0] = copy_Exp( w->rh ); - tmp_op->num_numeric_preconds = 1; - make_normal_effects( &tmp_op, goperators[i] ); - geasy_operators[gnum_easy_operators++] = tmp_op; - break; - case TRU: - tmp_op = new_NormOperator( goperators[i] ); - make_normal_effects( &tmp_op, goperators[i] ); - geasy_operators[gnum_easy_operators++] = tmp_op; - break; - case FAL: - break; - default: - printf("\nwon't get here: non OR, AND, ATOM, TRUE, FALSE in dnf. debug me\n\n"); - exit( 1 ); - } - } - - if ( gcmd_line.display_info == 109 ) { - printf("\n\nsplitted operators are:\n"); - - printf("\nEASY:\n"); - for ( i = 0; i < gnum_easy_operators; i++ ) { - print_NormOperator( geasy_operators[i] ); - } - - printf("\n\n\nHARD:\n"); - for ( i = 0; i < gnum_hard_operators; i++ ) { - print_Operator( ghard_operators[i] ); - } - } - -} - - - -int is_dnf( WffNode *w ) - -{ - - WffNode *i; - int s = 0; - - switch ( w->connective ) { - case ALL: - case EX: - printf("\nchecking quantifier for dnf. debug me\n\n"); - exit( 1 ); - case AND: - for ( i = w->sons; i; i = i->next ) { - if ( i->connective == ATOM || - i->connective == COMP ) { - continue; - } - return -1; - } - return 1; - case OR: - for ( i = w->sons; i; i = i->next ) { - s++; - if ( i->connective == ATOM || - i->connective == COMP || - ( i->connective == AND && - is_dnf( i ) != -1 ) ) { - continue; - } - return -1; - } - return s; - case NOT: - printf("\n\nNOT in presimplified formula. debug me\n\n"); - exit( 1 ); - case ATOM: - case COMP: - case TRU: - case FAL: - return 1; - default: - printf("\nwon't get here: check dnf, conn %d\n\n", - w->connective); - exit( 1 ); - } - -} - - - -void make_normal_effects( NormOperator **nop, Operator *op ) - -{ - - Effect *e; - NormEffect *tmp_ef; - WffNode *w, *ww, *www; - int j, m, ma, md, mn; - Literal *l; - NumericEffect *ll; - Fact *tmp_ft; - Fluent *tmp_fl; - - for ( e = op->effects; e; e = e->next ) { - w = e->conditions; - switch ( w->connective ) { - case OR: - for ( ww = w->sons; ww; ww = ww->next ) { - tmp_ef = new_NormEffect1( e ); - if ( ww->connective == AND ) { - m = 0; - mn = 0; - for ( www = ww->sons; www; www = www->next ) { - if ( www->connective == ATOM ) m++; - if ( www->connective == COMP ) mn++; - } - tmp_ef->conditions = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp_ef->numeric_conditions_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp_ef->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - for ( www = ww->sons; www; www = www->next ) { - if ( www->connective == ATOM ) { - tmp_ft = &(tmp_ef->conditions[tmp_ef->num_conditions]); - tmp_ft->predicate = www->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = www->fact->args[j]; - } - tmp_ef->num_conditions++; - } - if ( www->connective == COMP ) { - tmp_ef->numeric_conditions_comp[tmp_ef->num_numeric_conditions] = www->comp; - tmp_ef->numeric_conditions_lh[tmp_ef->num_numeric_conditions] = copy_Exp( www->lh ); - tmp_ef->numeric_conditions_rh[tmp_ef->num_numeric_conditions] = copy_Exp( www->rh ); - tmp_ef->num_numeric_conditions++; - } - } - } else { - if ( ww->connective == ATOM ) { - tmp_ef->conditions = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp_ft = &(tmp_ef->conditions[0]); - tmp_ft->predicate = ww->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = ww->fact->args[j]; - } - tmp_ef->num_conditions = 1; - } - if ( ww->connective == COMP ) { - tmp_ef->numeric_conditions_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp_ef->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_comp[0] = ww->comp; - tmp_ef->numeric_conditions_lh[0] = copy_Exp( ww->lh ); - tmp_ef->numeric_conditions_rh[0] = copy_Exp( ww->rh ); - tmp_ef->num_numeric_conditions = 1; - } - } - ma = 0; md = 0; - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { md++; } else { ma++; } - } - tmp_ef->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - tmp_ef->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - tmp_ft = &(tmp_ef->dels[tmp_ef->num_dels++]); - } else { - tmp_ft = &(tmp_ef->adds[tmp_ef->num_adds++]); - } - tmp_ft->predicate = l->fact.predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = l->fact.args[j]; - } - } - ma = 0; - for ( ll = e->numeric_effects; ll; ll = ll->next ) ma++; - tmp_ef->numeric_effects_neft = ( NumericEffectType * ) calloc( ma, sizeof( NumericEffectType ) ); - tmp_ef->numeric_effects_fluent = ( Fluent * ) calloc( ma, sizeof( Fluent ) ); - tmp_ef->numeric_effects_rh = ( ExpNode_pointer * ) calloc( ma, sizeof( ExpNode_pointer ) ); - for ( ll = e->numeric_effects; ll; ll = ll->next ) { - tmp_ef->numeric_effects_neft[tmp_ef->num_numeric_effects] = ll->neft; - tmp_fl = &(tmp_ef->numeric_effects_fluent[tmp_ef->num_numeric_effects]); - tmp_fl->function = ll->fluent.function; - for ( j = 0; j < gf_arity[tmp_fl->function]; j++ ) { - tmp_fl->args[j] = ll->fluent.args[j]; - } - tmp_ef->numeric_effects_rh[tmp_ef->num_numeric_effects] = copy_Exp( ll->rh ); - tmp_ef->num_numeric_effects++; - } - tmp_ef->next = (*nop)->effects; - if ( (*nop)->effects ) { - (*nop)->effects->prev = tmp_ef; - } - (*nop)->effects = tmp_ef; - } - break; - case AND: - tmp_ef = new_NormEffect1( e ); - m = 0; - mn = 0; - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) m++; - if ( ww->connective == COMP ) mn++; - } - tmp_ef->conditions = ( Fact * ) calloc( m, sizeof( Fact ) ); - tmp_ef->numeric_conditions_comp = ( Comparator * ) calloc( mn, sizeof( Comparator ) ); - tmp_ef->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( mn, sizeof( ExpNode_pointer ) ); - for ( ww = w->sons; ww; ww = ww->next ) { - if ( ww->connective == ATOM ) { - tmp_ft = &(tmp_ef->conditions[tmp_ef->num_conditions]); - tmp_ft->predicate = ww->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = ww->fact->args[j]; - } - tmp_ef->num_conditions++; - } - if ( ww->connective == COMP ) { - tmp_ef->numeric_conditions_comp[tmp_ef->num_numeric_conditions] = ww->comp; - tmp_ef->numeric_conditions_lh[tmp_ef->num_numeric_conditions] = copy_Exp( ww->lh ); - tmp_ef->numeric_conditions_rh[tmp_ef->num_numeric_conditions] = copy_Exp( ww->rh ); - tmp_ef->num_numeric_conditions++; - } - } - ma = 0; md = 0; - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { md++; } else { ma++; } - } - tmp_ef->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - tmp_ef->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - tmp_ft = &(tmp_ef->dels[tmp_ef->num_dels++]); - } else { - tmp_ft = &(tmp_ef->adds[tmp_ef->num_adds++]); - } - tmp_ft->predicate = l->fact.predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = l->fact.args[j]; - } - } - ma = 0; - for ( ll = e->numeric_effects; ll; ll = ll->next ) ma++; - tmp_ef->numeric_effects_neft = ( NumericEffectType * ) calloc( ma, sizeof( NumericEffectType ) ); - tmp_ef->numeric_effects_fluent = ( Fluent * ) calloc( ma, sizeof( Fluent ) ); - tmp_ef->numeric_effects_rh = ( ExpNode_pointer * ) calloc( ma, sizeof( ExpNode_pointer ) ); - for ( ll = e->numeric_effects; ll; ll = ll->next ) { - tmp_ef->numeric_effects_neft[tmp_ef->num_numeric_effects] = ll->neft; - tmp_fl = &(tmp_ef->numeric_effects_fluent[tmp_ef->num_numeric_effects]); - tmp_fl->function = ll->fluent.function; - for ( j = 0; j < gf_arity[tmp_fl->function]; j++ ) { - tmp_fl->args[j] = ll->fluent.args[j]; - } - tmp_ef->numeric_effects_rh[tmp_ef->num_numeric_effects] = copy_Exp( ll->rh ); - tmp_ef->num_numeric_effects++; - } - tmp_ef->next = (*nop)->effects; - if ( (*nop)->effects ) { - (*nop)->effects->prev = tmp_ef; - } - (*nop)->effects = tmp_ef; - break; - case ATOM: - tmp_ef = new_NormEffect1( e ); - tmp_ef->conditions = ( Fact * ) calloc( 1, sizeof( Fact ) ); - tmp_ft = &(tmp_ef->conditions[0]); - tmp_ft->predicate = w->fact->predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = w->fact->args[j]; - } - tmp_ef->num_conditions = 1; - ma = 0; md = 0; - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { md++; } else { ma++; } - } - tmp_ef->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - tmp_ef->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - tmp_ft = &(tmp_ef->dels[tmp_ef->num_dels++]); - } else { - tmp_ft = &(tmp_ef->adds[tmp_ef->num_adds++]); - } - tmp_ft->predicate = l->fact.predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = l->fact.args[j]; - } - } - ma = 0; - for ( ll = e->numeric_effects; ll; ll = ll->next ) ma++; - tmp_ef->numeric_effects_neft = ( NumericEffectType * ) calloc( ma, sizeof( NumericEffectType ) ); - tmp_ef->numeric_effects_fluent = ( Fluent * ) calloc( ma, sizeof( Fluent ) ); - tmp_ef->numeric_effects_rh = ( ExpNode_pointer * ) calloc( ma, sizeof( ExpNode_pointer ) ); - for ( ll = e->numeric_effects; ll; ll = ll->next ) { - tmp_ef->numeric_effects_neft[tmp_ef->num_numeric_effects] = ll->neft; - tmp_fl = &(tmp_ef->numeric_effects_fluent[tmp_ef->num_numeric_effects]); - tmp_fl->function = ll->fluent.function; - for ( j = 0; j < gf_arity[tmp_fl->function]; j++ ) { - tmp_fl->args[j] = ll->fluent.args[j]; - } - tmp_ef->numeric_effects_rh[tmp_ef->num_numeric_effects] = copy_Exp( ll->rh ); - tmp_ef->num_numeric_effects++; - } - tmp_ef->next = (*nop)->effects; - if ( (*nop)->effects ) { - (*nop)->effects->prev = tmp_ef; - } - (*nop)->effects = tmp_ef; - break; - case COMP: - tmp_ef = new_NormEffect1( e ); - tmp_ef->numeric_conditions_comp = ( Comparator * ) calloc( 1, sizeof( Comparator ) ); - tmp_ef->numeric_conditions_lh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_rh = ( ExpNode_pointer * ) calloc( 1, sizeof( ExpNode_pointer ) ); - tmp_ef->numeric_conditions_comp[0] = w->comp; - tmp_ef->numeric_conditions_lh[0] = copy_Exp( w->lh ); - tmp_ef->numeric_conditions_rh[0] = copy_Exp( w->rh ); - tmp_ef->num_numeric_conditions = 1; - ma = 0; md = 0; - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { md++; } else { ma++; } - } - tmp_ef->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - tmp_ef->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - tmp_ft = &(tmp_ef->dels[tmp_ef->num_dels++]); - } else { - tmp_ft = &(tmp_ef->adds[tmp_ef->num_adds++]); - } - tmp_ft->predicate = l->fact.predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = l->fact.args[j]; - } - } - ma = 0; - for ( ll = e->numeric_effects; ll; ll = ll->next ) ma++; - tmp_ef->numeric_effects_neft = ( NumericEffectType * ) calloc( ma, sizeof( NumericEffectType ) ); - tmp_ef->numeric_effects_fluent = ( Fluent * ) calloc( ma, sizeof( Fluent ) ); - tmp_ef->numeric_effects_rh = ( ExpNode_pointer * ) calloc( ma, sizeof( ExpNode_pointer ) ); - for ( ll = e->numeric_effects; ll; ll = ll->next ) { - tmp_ef->numeric_effects_neft[tmp_ef->num_numeric_effects] = ll->neft; - tmp_fl = &(tmp_ef->numeric_effects_fluent[tmp_ef->num_numeric_effects]); - tmp_fl->function = ll->fluent.function; - for ( j = 0; j < gf_arity[tmp_fl->function]; j++ ) { - tmp_fl->args[j] = ll->fluent.args[j]; - } - tmp_ef->numeric_effects_rh[tmp_ef->num_numeric_effects] = copy_Exp( ll->rh ); - tmp_ef->num_numeric_effects++; - } - tmp_ef->next = (*nop)->effects; - if ( (*nop)->effects ) { - (*nop)->effects->prev = tmp_ef; - } - (*nop)->effects = tmp_ef; - break; - case TRU: - tmp_ef = new_NormEffect1( e ); - ma = 0; md = 0; - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { md++; } else { ma++; } - } - tmp_ef->adds = ( Fact * ) calloc( ma, sizeof( Fact ) ); - tmp_ef->dels = ( Fact * ) calloc( md, sizeof( Fact ) ); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - tmp_ft = &(tmp_ef->dels[tmp_ef->num_dels++]); - } else { - tmp_ft = &(tmp_ef->adds[tmp_ef->num_adds++]); - } - tmp_ft->predicate = l->fact.predicate; - for ( j = 0; j < garity[tmp_ft->predicate]; j++ ) { - tmp_ft->args[j] = l->fact.args[j]; - } - } - ma = 0; - for ( ll = e->numeric_effects; ll; ll = ll->next ) ma++; - tmp_ef->numeric_effects_neft = ( NumericEffectType * ) calloc( ma, sizeof( NumericEffectType ) ); - tmp_ef->numeric_effects_fluent = ( Fluent * ) calloc( ma, sizeof( Fluent ) ); - tmp_ef->numeric_effects_rh = ( ExpNode_pointer * ) calloc( ma, sizeof( ExpNode_pointer ) ); - for ( ll = e->numeric_effects; ll; ll = ll->next ) { - tmp_ef->numeric_effects_neft[tmp_ef->num_numeric_effects] = ll->neft; - tmp_fl = &(tmp_ef->numeric_effects_fluent[tmp_ef->num_numeric_effects]); - tmp_fl->function = ll->fluent.function; - for ( j = 0; j < gf_arity[tmp_fl->function]; j++ ) { - tmp_fl->args[j] = ll->fluent.args[j]; - } - tmp_ef->numeric_effects_rh[tmp_ef->num_numeric_effects] = copy_Exp( ll->rh ); - tmp_ef->num_numeric_effects++; - } - tmp_ef->next = (*nop)->effects; - if ( (*nop)->effects ) { - (*nop)->effects->prev = tmp_ef; - } - (*nop)->effects = tmp_ef; - break; - case FAL: - break; - default: - printf("\nwon't get here: non OR, AND, ATOM, TRUE, FALSE in dnf. debug me\n\n"); - exit( 1 ); - } - } - -} - - - - - - - - - -/************************************************************************* - * ADDITIONAL: FULL DNF, only compute on fully instantiated formulae!!!! * - *************************************************************************/ - - - - - - - - - - -/* dnf - */ - -WffNode *lhitting_sets; -WffNode_pointer *lset; -int lmax_set; - - - - - - -void dnf( WffNode **w ) - -{ - - static Bool first_call = TRUE; - - if ( first_call ) { - lset = ( WffNode_pointer * ) - calloc( MAX_HITTING_SET_DEFAULT, sizeof( WffNode_pointer ) ); - lmax_set = MAX_HITTING_SET_DEFAULT; - first_call = FALSE; - } - - ANDs_below_ORs_in_wff( w ); - -} - - - -void ANDs_below_ORs_in_wff( WffNode **w ) - -{ - - WffNode *i, *tmp; - int c, m; - - switch ( (*w)->connective ) { - case ALL: - case EX: - printf("\ntrying to put quantified formula into DNF! (ands down) debug me\n\n"); - exit( 1 ); - break; - case AND: - c = 0; - m = 0; - for ( i = (*w)->sons; i; i = i->next ) { - ANDs_below_ORs_in_wff( &i ); - if ( i->connective == OR ) { - c++; - } - m++; - } - if ( c == 0 ) { - /* no ORs as sons --> all sons are literals. OK - */ - merge_next_step_ANDs_and_ORs_in_wff( w ); - break; - } - /* crucial part: AND node, sons can be merged OR's. - * (i.e., sons are either literals or disjunctions of - * conjunctions of literals) - * create OR node with one hitting set of w's sons for - * each disjunct - */ - lhitting_sets = NULL; - if ( m > lmax_set ) { - free( lset ); - lset = ( WffNode_pointer * ) calloc( m, sizeof( WffNode_pointer ) ); - lmax_set = m; - } - collect_hitting_sets( (*w)->sons, 0 ); - (*w)->connective = OR; - tmp = (*w)->sons; - (*w)->sons = lhitting_sets; - if ( 0 ) free_WffNode( tmp ); - merge_next_step_ANDs_and_ORs_in_wff( w ); - break; - case OR: - for ( i = (*w)->sons; i; i = i->next ) { - ANDs_below_ORs_in_wff( &i ); - } - merge_next_step_ANDs_and_ORs_in_wff( w ); - break; - case NOT: - case ATOM: - case COMP: - case TRU: - case FAL: - break; - default: - printf("\nwon't get here: ands down, non logical %d\n\n", - (*w)->connective); - exit( 1 ); - } - -} - - - -void collect_hitting_sets( WffNode *ORlist, int index ) - -{ - - WffNode *tmp1, *tmp2, *j; - int i; - - if ( !ORlist ) { - tmp1 = new_WffNode( AND ); - for ( i = 0; i < index; i++ ) { - tmp2 = copy_Wff( lset[i] ); - tmp2->next = tmp1->sons; - if ( tmp1->sons ) { - tmp1->sons->prev = tmp2; - } - tmp1->sons = tmp2; - } - tmp1->next = lhitting_sets; - if ( lhitting_sets ) { - lhitting_sets->prev = tmp1; - } - lhitting_sets = tmp1; - return; - } - - if ( ORlist->connective != OR ) { - lset[index] = ORlist; - collect_hitting_sets( ORlist->next, index + 1 ); - return; - } - - for ( j = ORlist->sons; j; j = j->next ) { - lset[index] = j; - collect_hitting_sets( ORlist->next, index + 1 ); - } - -} - - - -void merge_next_step_ANDs_and_ORs_in_wff( WffNode **w ) - -{ - - WffNode *i, *j, *tmp; - - i = (*w)->sons; - while ( i ) { - if ( i->connective == (*w)->connective ) { - if ( !(i->sons) ) { - if ( i->next ) { - i->next->prev = i->prev; - } - if ( i->prev ) { - i->prev->next = i->next; - } else { - (*w)->sons = i->next; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - for ( j = i->sons; j->next; j = j->next ); - j->next = i->next; - if ( i->next ) { - i->next->prev = j; - } - if ( i->prev ) { - i->prev->next = i->sons; - i->sons->prev = i->prev; - } else { - (*w)->sons = i->sons; - } - tmp = i; - i = i->next; - free( tmp ); - continue; - } - i = i->next; - } - -} - - - -/* switch ( (*w)->connective ) { */ -/* case ALL: */ -/* case EX: */ -/* break; */ -/* case AND: */ -/* case OR: */ -/* for ( i = (*w)->sons; i; i = i->next ) { */ -/* } */ -/* break; */ -/* case NOT: */ -/* break; */ -/* case ATOM: */ -/* case TRU: */ -/* case FAL: */ -/* break; */ -/* default: */ -/* printf("\nwon't get here: remove var, non logical %d\n\n", */ -/* (*w)->connective); */ -/* exit( 1 ); */ -/* } */ - - - - - - - - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.h deleted file mode 100644 index de859b38..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/inst_pre.h +++ /dev/null @@ -1,123 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: inst_pre.h - * Description: headers for instantiating operators, preprocessing part. - * - transform domain into integers - * - inertia preprocessing: - * - collect inertia info - * - split initial state in special arrays - * - Wff normalization: - * - simplification - * - quantifier expansion - * - NOT s down - * - negative preconditions translation - * - split operators into easy and hard to instantiate ones - * - * - full DNF functions, only feasible for fully instantiated - * formulae - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - - - - - - -#ifndef _INST_PRE_H -#define _INST_PRE_H - - - -void encode_domain_in_integers( void ); -void collect_all_strings( void ); -void create_member_nrs( void ); -int position_in_types_table( char *str ); -int position_in_constants_table( char *str ); -int position_in_predicates_table( char *str ); -int position_in_functions_table( char *str ); -void create_integer_representation( void ); -void make_Fact( Fact *f, PlNode *n, int num_vars ); -void make_Fluent( Fluent *f, TokenList *atom, int num_vars ); -Bool is_subtype( int t1, int t2 ); -WffNode *make_Wff( PlNode *p, int num_vars ); -ExpNode *make_ExpNode( ParseExpNode *p, int num_vars ); -Effect *make_effect( PlNode *p, int num_vars ); - - - -void do_inertia_preprocessing_step_1( void ); -void collect_inertia_information( void ); -void split_initial_state( void ); - - - -void normalize_all_wffs( void ); -void remove_unused_vars_in_wff( WffNode **w ); -void decrement_inferior_vars( int var, WffNode *w ); -void decrement_inferior_vars_in_exp( int var, ExpNode *n ); -Bool var_used_in_wff( int code_var, WffNode *w ); -Bool var_used_in_exp( int code_var, ExpNode *n ); -void simplify_wff( WffNode **w ); -void simplify_exp( ExpNode **n ); -void expand_quantifiers_in_wff( WffNode **w, int var, int constant ); -void replace_var_with_const_in_exp( ExpNode **n, int var, int constant ); -WffNode *copy_Wff( WffNode *w ); -ExpNode *copy_Exp( ExpNode *n ); -Bool possibly_positive( Fact *f ); -Bool possibly_negative( Fact *f ); -Bool matches( Fact *f1, Fact *f2 ); -void cleanup_wff( WffNode **w ); -void detect_tautologies_in_wff( WffNode **w ); -Bool are_identical_ATOMs( WffNode *w1, WffNode *w2 ); -void merge_ANDs_and_ORs_in_wff( WffNode **w ); -void NOTs_down_in_wff( WffNode **w ); - - - -void translate_negative_preconds( void ); -Bool translate_one_negative_cond( WffNode *w ); -void replace_not_p_with_n_in_wff( int p, int n, WffNode **w ); -void add_to_initial_state( int p, int n, int index ); - - - -void split_domain( void ); -int is_dnf( WffNode *w ); -void make_normal_effects( NormOperator **nop, Operator *op ); - - - -void dnf( WffNode **w ); -void ANDs_below_ORs_in_wff( WffNode **w ); -void collect_hitting_sets( WffNode *ORlist, int index ); -void merge_next_step_ANDs_and_ORs_in_wff( WffNode **w ); - - - -#endif /* _INST_PRE_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-fct_pddl.l b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-fct_pddl.l deleted file mode 100644 index 850bbb40..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-fct_pddl.l +++ /dev/null @@ -1,139 +0,0 @@ -%{ -#include "ff.h" -#include "parse.h" - - /* default yywrap function - always treat EOF as an EOF */ -int fct_pddlwrap() { return 1; }; - -int gbracket_count = 0; - -%} - -a [Aa] -b [Bb] -c [Cc] -d [Dd] -e [Ee] -f [Ff] -g [Gg] -h [Hh] -i [Ii] -j [Jj] -k [Kk] -l [Ll] -m [Mm] -n [Nn] -o [Oo] -p [Pp] -q [Qq] -r [Rr] -s [Ss] -t [Tt] -u [Uu] -v [Vv] -w [Ww] -x [Xx] -y [Yy] -z [Zz] - -%x COMMENT OVERREAD - -%% - -"(" { return(OPEN_PAREN); } - -")" { return(CLOSE_PAREN); } - -\([ \t]*{i}{n}"-"{p}{a}{c}{k}{a}{g}{e} { gbracket_count = 1; - BEGIN OVERREAD; } - -\([ \t]*":"{l}{e}{n}{g}{t}{h} { gbracket_count = 1; - BEGIN OVERREAD; } - -\([ \t]*":"{r}{e}{q}{u}{i}{r}{e}{m}{e}{n}{t}{s} { gbracket_count = 1; - BEGIN OVERREAD; } - -{d}{e}{f}{i}{n}{e} { return(DEFINE_TOK); } - -{p}{r}{o}{b}{l}{e}{m} { return(PROBLEM_TOK); } - -{s}{i}{t}{u}{a}{t}{i}{o}{n} { return(SITUATION_TOK); } - -":"{s}{i}{t}{u}{a}{t}{i}{o}{n} { return(BSITUATION_TOK); } - -":"{o}{b}{j}{e}{c}{t}{s} { return(OBJECTS_TOK); } - -":"{g}{o}{a}{l} { return(GOAL_TOK); } - -":"{m}{e}{t}{r}{i}{c} { return(METRIC_TOK); } - -":"{i}{n}{i}{t} { return(INIT_TOK); } - -":"{d}{o}{m}{a}{i}{n} { return(BDOMAIN_TOK); } - -\([ \t]*":"{e}{x}{t}{e}{n}{d}{s} { gbracket_count = 1; - BEGIN OVERREAD; } - -{a}{n}{d} { return(AND_TOK); } - -{i}{m}{p}{l}{y} { return(IMPLY_TOK); } - -{o}{r} { return(OR_TOK); } - -{f}{o}{r}{a}{l}{l} { return(FORALL_TOK); } - -{e}{x}{i}{s}{t}{s} { return(EXISTS_TOK); } - -{n}{o}{t} { return(NOT_TOK); } - -"<" { return(LE_TOK); } - -"<=" { return(LEQ_TOK); } - -"=" { return(EQ_TOK); } - -">=" { return(GEQ_TOK); } - -">" { return(GE_TOK); } - -"-" { return(MINUS_TOK); } - -"+" { return(AD_TOK); } - -"*" { return(MU_TOK); } - -"/" { return(DI_TOK); } - -:?[a-zA-Z][a-zA-Z0-9\-_]* { strupcase( yytext ); - strcpy(yylval.string, yytext ); return(NAME); } - -\?[a-zA-Z][a-zA-Z0-9\-_\[\]]* {strupcase( yytext ); - strcpy(yylval.string, yytext); return(VARIABLE); } - -"-"?[0-9]*[.]?[0-9]* { strcpy(yylval.string, yytext); return(NUM);} - -"-"[ \t]*"("[ \t]*{e}{i}{t}{h}{e}{r} { return(EITHER_TOK); } - -\;(.)*\n { lineno++; } -\;(.)* { /* this will hold only in files that end with - a comment but no linefeed */ } - -(.^\")*\n { lineno++; } ; - -\" { BEGIN COMMENT;} - -\" { BEGIN INITIAL;} - -\n { lineno++; } - -(.^\(\))*\n { lineno++; } - -[^\(\)] { } - -\( { gbracket_count++; } - -\) { gbracket_count--; - if (!gbracket_count) BEGIN INITIAL; } - -. {} -%% diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-ops_pddl.l b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-ops_pddl.l deleted file mode 100644 index 0e9d8499..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/lex-ops_pddl.l +++ /dev/null @@ -1,151 +0,0 @@ -%{ -#include "ff.h" -#include "parse.h" - -/* default yywrap function - always treat EOF as an EOF */ -int ops_pddlwrap() { return 1; }; - -%} - -a [Aa] -b [Bb] -c [Cc] -d [Dd] -e [Ee] -f [Ff] -g [Gg] -h [Hh] -i [Ii] -j [Jj] -k [Kk] -l [Ll] -m [Mm] -n [Nn] -o [Oo] -p [Pp] -q [Qq] -r [Rr] -s [Ss] -t [Tt] -u [Uu] -v [Vv] -w [Ww] -x [Xx] -y [Yy] -z [Zz] - -%x COMMENT OVERREAD - -%% - -"(" { return(OPEN_PAREN); } - -")" { return(CLOSE_PAREN); } - -{d}{e}{f}{i}{n}{e} { return(DEFINE_TOK); } - -{d}{o}{m}{a}{i}{n} { return(DOMAIN_TOK); } - -":"{r}{e}{q}{u}{i}{r}{e}{m}{e}{n}{t}{s} { return(REQUIREMENTS_TOK); } - -":"{t}{y}{p}{e}{s} { return(TYPES_TOK); } - -{n}{u}{m}{b}{e}{r} { return(NUMBER_TOK); } - -":"{c}{o}{n}{s}{t}{a}{n}{t}{s} { return(CONSTANTS_TOK); } - -":"{p}{r}{e}{d}{i}{c}{a}{t}{e}{s} { return(PREDICATES_TOK); } - -":"{f}{u}{n}{c}{t}{i}{o}{n}{s} { return(FUNCTIONS_TOK); } - -":"{a}{c}{t}{i}{o}{n} { return(ACTION_TOK); } - -":"{d}{e}{r}{i}{v}{e}{d} { return(AXIOM_TOK); } - -":"{p}{a}{r}{a}{m}{e}{t}{e}{r}{s} { return(PARAMETERS_TOK); } - -":"{v}{a}{r}{s} { return(VARS_TOK); } - -":"{p}{r}{e}{c}{o}{n}{d}{i}{t}{i}{o}{n} { return(PRECONDITION_TOK); } - -":"{e}{f}{f}{e}{c}{t} { return(EFFECT_TOK); } - -":"{i}{m}{p}{l}{i}{e}{s} { return(IMPLIES_TOK); } - -{a}{n}{d} { return(AND_TOK); } - -{n}{o}{t} { return(NOT_TOK); } - -{w}{h}{e}{n} { return(WHEN_TOK); } - -{i}{m}{p}{l}{y} { return(IMPLY_TOK); } - -{o}{r} { return(OR_TOK); } - -{f}{o}{r}{a}{l}{l} { return(FORALL_TOK); } - -{e}{x}{i}{s}{t}{s} { return(EXISTS_TOK); } - -"<" { return(LE_TOK); } - -"<=" { return(LEQ_TOK); } - -"=" { return(EQ_TOK); } - -">=" { return(GEQ_TOK); } - -">" { return(GE_TOK); } - -"-" { return(MINUS_TOK); } - -"+" { return(AD_TOK); } - -"*" { return(MU_TOK); } - -"/" { return(DI_TOK); } - -{a}{s}{s}{i}{g}{n} { return(ASSIGN_TOK); } - -{s}{c}{a}{l}{e}"-"{u}{p} { return(SCALE_UP_TOK); } - -{s}{c}{a}{l}{e}"-"{d}{o}{w}{n} { return(SCALE_DOWN_TOK); } - -{i}{n}{c}{r}{e}{a}{s}{e} { return(INCREASE_TOK); } - -{d}{e}{c}{r}{e}{a}{s}{e} { return(DECREASE_TOK); } - - -:?[a-zA-Z][a-zA-Z0-9\-_]* { strupcase(yytext); strcpy(yylval.string, yytext); - return(NAME); } - -\?[a-zA-Z][a-zA-Z0-9\-_\[\]]* { strupcase(yytext); strcpy(yylval.string, yytext); - return(VARIABLE); } - -"-"?[0-9]*[.]?[0-9]* { strcpy(yylval.string, yytext); return(NUM);} - - -"-"[ \t]*"("[ \t]*{e}{i}{t}{h}{e}{r} { return(EITHER_TOK); } - -\;(.)*\n { lineno++; } -\;(.)* { /* this will hold only in files that end with - a comment but no linefeed */ } - -(.^\")*\n { lineno++; } ; - -\" { BEGIN COMMENT;} - -\" { BEGIN INITIAL;} - -\n { lineno++; } - -(.^\(\))*\n { lineno++; } - -[^\(\)] { } - -\( { BEGIN OVERREAD; gbracket_count++; } - -\) { BEGIN OVERREAD; gbracket_count--; - if (!gbracket_count) BEGIN INITIAL; } - -. {} -%% diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/main.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/main.c deleted file mode 100644 index bc3a795b..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/main.c +++ /dev/null @@ -1,1230 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - -/********************************************************************* - * File: main.c - * Description: The main routine for the Metric-FastForward Planner. - * Modified July 2011 to allow more command-line search - * confiogurations, including improved cost-minimization - * - * Author: original version Joerg Hoffmann 2001/2002 - * modified version Joerg Hoffmann 2012 - * - *********************************************************************/ - - - - - - - - -#include "ff.h" - -#include "memory.h" -#include "output.h" - -#include "parse.h" - -#include "expressions.h" - -#include "inst_pre.h" -#include "inst_easy.h" -#include "inst_hard.h" -#include "inst_final.h" - -#include "relax.h" -#include "search.h" - - - - - - - - - - - -/* - * ----------------------------- GLOBAL VARIABLES ---------------------------- - */ - - - - - - - - - - - - -/******************* - * GENERAL HELPERS * - *******************/ - - - - - - - - -/* used to time the different stages of the planner - */ -float gtempl_time = 0, greach_time = 0, grelev_time = 0, gconn_time = 0; -float gLNF_time = 0, gsearch_time = 0; - - -/* the command line inputs - */ -struct _command_line gcmd_line; - -/* number of states that got heuristically evaluated - */ -int gevaluated_states = 0; - -/* maximal depth of breadth first search - */ -int gmax_search_depth = 0; - - - - - -/*********** - * PARSING * - ***********/ - - - - - - - -/* used for pddl parsing, flex only allows global variables - */ -int gbracket_count; -char *gproblem_name; - -/* The current input line number - */ -int lineno = 1; - -/* The current input filename - */ -char *gact_filename; - -/* The pddl domain name - */ -char *gdomain_name = NULL; - -/* loaded, uninstantiated operators - */ -PlOperator *gloaded_ops = NULL; - -/* stores initials as fact_list - */ -PlNode *gorig_initial_facts = NULL; - -/* not yet preprocessed goal facts - */ -PlNode *gorig_goal_facts = NULL; - -/* axioms as in UCPOP before being changed to ops - */ -PlOperator *gloaded_axioms = NULL; - -/* the types, as defined in the domain file - */ -TypedList *gparse_types = NULL; - -/* the constants, as defined in domain file - */ -TypedList *gparse_constants = NULL; - -/* the predicates and their arg types, as defined in the domain file - */ -TypedListList *gparse_predicates = NULL; - -/* the functions and their arg types, as defined in the domain file - */ -TypedListList *gparse_functions = NULL; - -/* the objects, declared in the problem file - */ -TypedList *gparse_objects = NULL; - -/* the metric - */ -Token gparse_optimization; -ParseExpNode *gparse_metric = NULL; - - -/* connection to instantiation ( except ops, goal, initial ) - */ - -/* all typed objects - */ -FactList *gorig_constant_list = NULL; - -/* the predicates and their types - */ -FactList *gpredicates_and_types = NULL; - -/* the functions and their types - */ -FactList *gfunctions_and_types = NULL; - - - - - - - - - - - - -/***************** - * INSTANTIATING * - *****************/ - - - - - - - - - -/* global arrays of constant names, - * type names (with their constants), - * predicate names, - * predicate aritys, - * defined types of predicate args - */ -Token gconstants[MAX_CONSTANTS]; -int gnum_constants = 0; -Token gtype_names[MAX_TYPES]; -int gtype_consts[MAX_TYPES][MAX_TYPE]; -Bool gis_member[MAX_CONSTANTS][MAX_TYPES]; -int gmember_nr[MAX_CONSTANTS][MAX_TYPES];/* nr of object within a type */ -int gtype_size[MAX_TYPES]; -int gnum_types = 0; -Token gpredicates[MAX_PREDICATES]; -int garity[MAX_PREDICATES]; -Bool gaxiom_added[MAX_PREDICATES]; -int gpredicates_args_type[MAX_PREDICATES][MAX_ARITY]; -int gnum_predicates = 0; -Token gfunctions[MAX_FUNCTIONS]; -int gf_arity[MAX_FUNCTIONS]; -int gfunctions_args_type[MAX_FUNCTIONS][MAX_ARITY]; -int gnum_functions = 0; - - - - - -/* the domain in integer (Fact) representation - */ -Operator_pointer goperators[MAX_OPERATORS]; -int gnum_operators = 0; -Fact *gfull_initial; -int gnum_full_initial = 0; -FluentValue *gfull_fluents_initial; -int gnum_full_fluents_initial = 0; -WffNode *ggoal = NULL; - -ExpNode *gmetric = NULL; - - - -/* stores inertia - information: is any occurence of the predicate - * added / deleted in the uninstantiated ops ? - */ -Bool gis_added[MAX_PREDICATES]; -Bool gis_deleted[MAX_PREDICATES]; - - -/* for functions we *might* want to say, symmetrically, whether it is - * increased resp. decreased at all. - * - * that is, however, somewhat involved because the right hand - * sides can be arbirtray expressions, so we have no guarantee - * that increasing really does adds to a functions value... - * - * thus (for the time being), we settle for "is the function changed at all?" - */ -Bool gis_changed[MAX_FUNCTIONS]; - - - -/* splitted initial state: - * initial non static facts, - * initial static facts, divided into predicates - * (will be two dimensional array, allocated directly before need) - */ -Facts *ginitial = NULL; -int gnum_initial = 0; -Fact **ginitial_predicate; -int *gnum_initial_predicate; - -/* same thing for functions - */ -FluentValues *gf_initial; -int gnum_f_initial = 0; -FluentValue **ginitial_function; -int *gnum_initial_function; - - - -/* the type numbers corresponding to any unary inertia - */ -int gtype_to_predicate[MAX_PREDICATES]; -int gpredicate_to_type[MAX_TYPES]; - -/* (ordered) numbers of types that new type is intersection of - */ -TypeArray gintersected_types[MAX_TYPES]; -int gnum_intersected_types[MAX_TYPES]; - - - -/* splitted domain: hard n easy ops - */ -Operator_pointer *ghard_operators; -int gnum_hard_operators; -NormOperator_pointer *geasy_operators; -int gnum_easy_operators; - - - -/* so called Templates for easy ops: possible inertia constrained - * instantiation constants - */ -EasyTemplate *geasy_templates; -int gnum_easy_templates; - - - -/* first step for hard ops: create mixed operators, with conjunctive - * precondition and arbitrary effects - */ -MixedOperator *ghard_mixed_operators; -int gnum_hard_mixed_operators; - - - -/* hard ''templates'' : pseudo actions - */ -PseudoAction_pointer *ghard_templates; -int gnum_hard_templates; - - - -/* store the final "relevant facts" - */ -Fact grelevant_facts[MAX_RELEVANT_FACTS]; -int gnum_relevant_facts = 0; -int gnum_pp_facts = 0; -/* store the "relevant fluents" - */ -Fluent grelevant_fluents[MAX_RELEVANT_FLUENTS]; -int gnum_relevant_fluents = 0; -Token grelevant_fluents_name[MAX_RELEVANT_FLUENTS]; -/* this is NULL for normal, and the LNF for - * artificial fluents. - */ -LnfExpNode_pointer grelevant_fluents_lnf[MAX_RELEVANT_FLUENTS]; - - - -/* the final actions and problem representation - */ -Action *gactions = NULL; -int gnum_actions; -State ginitial_state; -int *glogic_goal = NULL; -int gnum_logic_goal = 0; -Comparator *gnumeric_goal_comp = NULL; -ExpNode_pointer *gnumeric_goal_lh = NULL, *gnumeric_goal_rh = NULL; -int gnum_numeric_goal = 0; - -/* direct numeric goal access - */ -Comparator *gnumeric_goal_direct_comp; -float *gnumeric_goal_direct_c; - - - -/* to avoid memory leaks; too complicated to identify - * the exact state of the action to throw away (during construction), - * memory gain not worth the implementation effort. - */ -Action *gtrash_actions = NULL; - - - -/* additional lnf step between finalized inst and - * conn graph - */ -Comparator *glnf_goal_comp = NULL; -LnfExpNode_pointer *glnf_goal_lh = NULL; -float *glnf_goal_rh = NULL; -int gnum_lnf_goal = 0; - -LnfExpNode glnf_metric; -Bool goptimization_established = FALSE; - - - - - - - -/********************** - * CONNECTIVITY GRAPH * - **********************/ - - - - - - - -/* one ops (actions) array ... - */ -OpConn *gop_conn; -int gnum_op_conn; - - - -/* one effects array ... - */ -EfConn *gef_conn; -int gnum_ef_conn; - - - -/* one facts array. - */ -FtConn *gft_conn; -int gnum_ft_conn; - - - -/* and: one fluents array. - */ -FlConn *gfl_conn; -int gnum_fl_conn; -int gnum_real_fl_conn;/* number of non-artificial ones */ - - - -/* final goal is also transformed one more step. - */ -int *gflogic_goal = NULL; -int gnum_flogic_goal = 0; -Comparator *gfnumeric_goal_comp = NULL; -int *gfnumeric_goal_fl = NULL; -float *gfnumeric_goal_c = NULL; -int gnum_fnumeric_goal = 0; - -/* direct access (by relevant fluents) - */ -Comparator *gfnumeric_goal_direct_comp = NULL; -float *gfnumeric_goal_direct_c = NULL; - - - - - - - - - - - -/******************* - * SEARCHING NEEDS * - *******************/ - - - - - - - - - - - -/* applicable actions - */ -int *gA;/* non-axioms */ -int gnum_A; -int *gA_axioms; /* axioms */ -int gnum_A_axioms; - - - -/* communication from extract 1.P. to search engine: - * 1P action choice - */ -int *gH; -int gnum_H; -/* added cost of relaxed plan - */ -float gh_cost; -/* hmax value - */ -float ghmax; - - - -/* to store plan - */ -int gplan_ops[MAX_PLAN_LENGTH]; -int gnum_plan_ops = 0; - - - -/* stores the states that the current plan goes through - * ( for knowing where new agenda entry starts from ) - */ -State gplan_states[MAX_PLAN_LENGTH + 1]; - - - - - - - -/* dirty: multiplic. of total-time in final metric LNF - */ -float gtt; - - - - - - - -/* the mneed structures - */ -Bool **gassign_influence; -Bool **gTassign_influence; - - - -/* the real var input to the mneed computation. - */ -Bool *gmneed_start_D; -float *gmneed_start_V; - - - -/* does this contain conditional effects? - * (if it does then the state hashing has to be made more - * cautiously) - */ -Bool gconditional_effects; - - - -/* easier to question: are we optimizing or no? - */ -Bool gcost_minimizing; - - - -/* stores current A* weight: this is initially given by user, - * but changes during anytime search. - */ -float gw; -/* this is the minimum weight, ie we'll stop once the weight update - * does/would yield a value <= this. - * if no such minim weight is given, this will be -1 - */ -float gmin_w = -1; - - - -/* this one says whether or not we are actually using - * cost-minimizing rplans. - * this will be the case by default if we're running cost- - * minimizing searches. it can be switched off by a flag; - * it is automatically switched off in case there are - * numeric preconditions/goals: for this case, - * cost-minimizing rplans are not implemented (a numeric prec - * may cause an action to come in "later" on in the RPG although - * its logical pres are easy. in that case, any new effects will - * have a smaller RPGcost value than facts we already have waiting. - * in other words, the "Dijsktra" nature breaks. - * - * ... I suppose there may be a generic solution to this that - * can handle numeric precs/goals. Doesn't seem important enough - * to bother. - */ -Bool gcost_rplans; - - - - - - - - - - - - - -/* - * ----------------------------- HEADERS FOR PARSING ---------------------------- - * ( fns defined in the scan-* files ) - */ - - - - - - - -void get_fct_file_name( char *filename ); -void load_ops_file( char *filename ); -void load_fct_file( char *filename ); - - - - - - - - - - - -/* - * ----------------------------- MAIN ROUTINE ---------------------------- - */ - - - - - -struct tms lstart, lend; - - - - - -int main( int argc, char *argv[] ) - -{ - - /* resulting name for ops file - */ - char ops_file[MAX_LENGTH] = ""; - /* same for fct file - */ - char fct_file[MAX_LENGTH] = ""; - - struct tms start, end; - - Bool found_plan; - int i; - float cost; - - Bool prev_gcost_rplans; - - - - times ( &lstart ); - - /* command line treatment - */ - gcmd_line.display_info = 1; - gcmd_line.debug = 0; - - /* search settings - */ - gcmd_line.search_config = 5; - gcmd_line.cost_rplans = TRUE; - gcmd_line.w = 5; - gcmd_line.cost_bound = -1; - - memset(gcmd_line.ops_file_name, 0, MAX_LENGTH); - memset(gcmd_line.fct_file_name, 0, MAX_LENGTH); - memset(gcmd_line.path, 0, MAX_LENGTH); - - if ( argc == 1 || ( argc == 2 && *++argv[0] == '?' ) ) { - ff_usage(); - exit( 1 ); - } - if ( !process_command_line( argc, argv ) ) { - ff_usage(); - exit( 1 ); - } - - - /* make file names - */ - - /* one input name missing - */ - if ( !gcmd_line.ops_file_name || - !gcmd_line.fct_file_name ) { - fprintf(stdout, "\nff: two input files needed\n\n"); - ff_usage(); - exit( 1 ); - } - /* add path info, complete file names will be stored in - * ops_file and fct_file - */ - sprintf(ops_file, "%s%s", gcmd_line.path, gcmd_line.ops_file_name); - sprintf(fct_file, "%s%s", gcmd_line.path, gcmd_line.fct_file_name); - - - /* parse the input files - */ - - /* start parse & instantiation timing - */ - times( &start ); - /* domain file (ops) - */ - if ( gcmd_line.display_info >= 1 ) { - printf("\nff: parsing domain file"); - } - /* it is important for the pddl language to define the domain before - * reading the problem - */ - load_ops_file( ops_file ); - /* problem file (facts) - */ - if ( gcmd_line.display_info >= 1 ) { - printf(" ... done.\nff: parsing problem file"); - } - load_fct_file( fct_file ); - if ( gcmd_line.display_info >= 1 ) { - printf(" ... done.\n\n"); - } - - /* This is needed to get all types. - */ - build_orig_constant_list(); - - /* last step of parsing: see if it's an ADL domain! - */ - if ( !make_adl_domain() ) { - printf("\nff: this is not an ADL problem!"); - printf("\n can't be handled by this version.\n\n"); - exit( 1 ); - } - - - /* now instantiate operators; - */ - - - /************************** - * first do PREPROCESSING * - **************************/ - - /* start by collecting all strings and thereby encoding - * the domain in integers. - */ - encode_domain_in_integers(); - - /* inertia preprocessing, first step: - * - collect inertia information - * - split initial state into - * - arrays for individual predicates - * - arrays for all static relations - * - array containing non - static relations - */ - do_inertia_preprocessing_step_1(); - - /* normalize all PL1 formulae in domain description: - * (goal, preconds and effect conditions) - * - simplify formula - * - expand quantifiers - * - NOTs down - */ - normalize_all_wffs(); - - /* translate negative preconds: introduce symmetric new predicate - * NOT-p(..) (e.g., not-in(?ob) in briefcaseworld) - */ - translate_negative_preconds(); - - /* split domain in easy (disjunction of conjunctive preconds) - * and hard (non DNF preconds) part, to apply - * different instantiation algorithms - */ - split_domain(); - - /*********************************************** - * PREPROCESSING FINISHED * - * * - * NOW MULTIPLY PARAMETERS IN EFFECTIVE MANNER * - ***********************************************/ - - build_easy_action_templates(); - build_hard_action_templates(); - - times( &end ); - TIME( gtempl_time ); - - times( &start ); - - /* perform reachability analysis in terms of relaxed - * fixpoint - */ - perform_reachability_analysis(); - - times( &end ); - TIME( greach_time ); - - times( &start ); - - /* collect the relevant facts and build final domain - * and problem representations. - */ - collect_relevant_facts_and_fluents(); - - times( &end ); - TIME( grelev_time ); - - - /* now transform problem to additive normal form, - * if possible - */ - times( &start ); - if ( !transform_to_LNF() ) { - printf("\n\nThis is not a linear task!\n\n"); - exit( 1 ); - } - times( &end ); - TIME( gLNF_time ); - - times( &start ); - - /* now build globally accessable connectivity graph - */ - build_connectivity_graph(); - - /* now check for acyclic := effects (in expressions.c) - */ - check_assigncycles(); - /* set the relevanc info (in expressions.c) - */ - determine_fl_relevance(); - - times( &end ); - TIME( gconn_time ); - - /*********************************************************** - * we are finally through with preprocessing and can worry * - * bout finding a plan instead. * - ***********************************************************/ - - if ( gcmd_line.display_info ) { - printf("\n\nff: search configuration is "); - switch ( gcmd_line.search_config ) { - case 0: - printf("Enforced Hill-Climbing, if that fails then best-first search.\nMetric is plan length."); - printf("\nNO COST MINIMIZATION"); - if ( !gcost_rplans ) { - printf(" (and no cost-minimizing relaxed plans)."); - } else { - printf("\nDEBUG ME: cost min rplans in non-cost minimizing search config?\n\n"); - exit( 1 ); - } - break; - case 1: - printf("best-first search.\nMetric is plan length."); - printf("\nNO COST MINIMIZATION"); - if ( !gcost_rplans ) { - printf(" (and no cost-minimizing relaxed plans)."); - } else { - printf("\nDEBUG ME: cost min rplans in non-cost minimizing search config?\n\n"); - exit( 1 ); - } - break; - case 2: - printf("best-first search with helpful actions pruning.\nMetric is plan length."); - printf("\nNO COST MINIMIZATION."); - if ( !gcost_rplans ) { - printf(" (and no cost-minimizing relaxed plans)."); - } else { - printf("\nDEBUG ME: cost min rplans in non-cost minimizing search config?\n\n"); - exit( 1 ); - } - break; - case 3: - printf("weighted A* with weight %d.", gcmd_line.w); - if ( goptimization_established ) { - printf("\nMetric is "); - print_LnfExpNode( &glnf_metric ); - } else { - printf(" plan length"); - } - printf("\nCOST MINIMIZATION DONE"); - if ( !gcost_rplans ) { - printf(" (WITHOUT cost-minimizing relaxed plans)."); - } else { - printf(" (WITH cost-minimizing relaxed plans)."); - } - break; - case 4: - printf("A*epsilon with weight %d.", gcmd_line.w); - if ( goptimization_established ) { - printf("\nMetric is "); - print_LnfExpNode( &glnf_metric ); - } else { - printf("\nError! Optimization criterion not established.\nA*epsilon not defined.\n\n"); - exit( 1 ); - } - printf("\nCOST MINIMIZATION DONE"); - if ( !gcost_rplans ) { - printf(" (WITHOUT cost-minimizing relaxed plans)."); - } else { - printf(" (WITH cost-minimizing relaxed plans)."); - } - break; - case 5: - printf("Enforced Hill-Climbing, then A*epsilon with weight %d.", gcmd_line.w); - if ( goptimization_established ) { - printf("\nMetric is "); - print_LnfExpNode( &glnf_metric ); - } else { - printf("\nError! Optimization criterion not established.\nA*epsilon not defined.\n\n"); - exit( 1 ); - } - printf("\nCOST MINIMIZATION DONE"); - if ( !gcost_rplans ) { - printf(" (WITHOUT cost-minimizing relaxed plans)."); - } else { - printf(" (WITH cost-minimizing relaxed plans)."); - } - break; - default: - printf("\n\nUnknown search configuration: %d\n\n", gcmd_line.search_config ); - exit( 1 ); - } - } else { - if ( gcmd_line.search_config == 4 && !goptimization_established ) { - exit( 1 ); - } - } - - - times( &start ); - - - - /* need to evaluate derived predicates in initial state! - */ - do_axiom_update( &ginitial_state ); - - - if ( !gcost_rplans ) { - gcmd_line.cost_bound = -1; - } - - switch ( gcmd_line.search_config ) { - case 0: - found_plan = do_enforced_hill_climbing(); - if ( found_plan ) { - if ( gcmd_line.display_info ) { - print_plan(); - } - } else { - if ( gcmd_line.display_info ) { - printf("\n\nEnforced Hill-climbing failed !"); - printf("\nswitching to Best-first Search now.\n"); - } - do_best_first_search(); - } - break; - case 1: - case 2: - do_best_first_search(); - break; - case 3: - do_weighted_Astar(); - break; - case 4: - do_Astar_epsilon(); - break; - case 5: - /* gcost_rplans controls whether or not we compute cost-minimal relaxed plans - * gcost_minimizing is only used in h fn to decide whether or not we - * need to count the weights of the operators in the relaxed plan. - * - * gcost_rplans may be false even for search options 3,4,5, namely if there are - * numeric preconditions/goals which make this relaxed plan variant invalid. - * hence we need to remember, when switching it off for EHC, whether or not - * it was previously on. - */ - prev_gcost_rplans = gcost_rplans; - gcost_rplans = FALSE; - gcost_minimizing = FALSE; - found_plan = do_enforced_hill_climbing(); - if ( found_plan ) { - print_plan(); - } else { - if ( gcmd_line.display_info ) { - printf("\n\nEnforced Hill-climbing not successful."); - printf("\nSwitching to A*epsilon now."); - } - gcost_rplans = prev_gcost_rplans; - gcost_minimizing = TRUE; - do_Astar_epsilon(); - } - break; - default: - printf("\n\nUnknown search configuration: %d\n\n", gcmd_line.search_config ); - exit( 1 ); - } - - times( &end ); - TIME( gsearch_time ); - - - - output_planner_info(); - - printf("\n\n"); - exit( 0 ); - -} - - - - - - - - - - - -/* - * ----------------------------- HELPING FUNCTIONS ---------------------------- - */ - - - - - - - - - - - - -void output_planner_info( void ) - -{ - - printf( "\n\ntime spent: %7.2f seconds instantiating %d easy, %d hard action templates", - gtempl_time, gnum_easy_templates, gnum_hard_mixed_operators ); - printf( "\n %7.2f seconds reachability analysis, yielding %d facts and %d actions", - greach_time, gnum_pp_facts, gnum_actions ); - printf( "\n %7.2f seconds creating final representation with %d relevant facts, %d relevant fluents", - grelev_time, gnum_relevant_facts, gnum_relevant_fluents ); - printf( "\n %7.2f seconds computing LNF", - gLNF_time ); - printf( "\n %7.2f seconds building connectivity graph", - gconn_time ); - printf( "\n %7.2f seconds searching, evaluating %d states, to a max depth of %d", - gsearch_time, gevaluated_states, gmax_search_depth ); - printf( "\n %7.2f seconds total time", - gtempl_time + greach_time + grelev_time + gLNF_time + gconn_time + gsearch_time ); - - printf("\n\n"); - - exit( 0 ); - -} - - - -void ff_usage( void ) - -{ - - printf("\nusage of ff:\n"); - - printf("\nOPTIONS DESCRIPTIONS\n\n"); - printf("-p Path for operator and fact file\n"); - printf("-o Operator file name\n"); - printf("-f Fact file name\n\n"); - - printf("-r Random seed [used for random restarts; preset: 0]\n\n"); - - printf("-s Search configuration [preset: s=5]; '+H': helpful actions pruning\n"); - printf(" 0 Standard-FF: EHC+H then BFS (cost minimization: NO)\n"); - printf(" 1 BFS (cost minimization: NO)\n"); - printf(" 2 BFS+H (cost minimization: NO)\n"); - printf(" 3 Weighted A* (cost minimization: YES)\n"); - printf(" 4 A*epsilon (cost minimization: YES)\n"); - printf(" 5 EHC+H then A*epsilon (cost minimization: YES)\n"); - printf("-w Set weight w for search configs 3,4,5 [preset: w=5]\n\n"); - - printf("-C Do NOT use cost-minimizing relaxed plans for options 3,4,5\n\n"); - - printf("-b Fixed upper bound on solution cost (prune based on g+hmax); active only with cost minimization\n\n"); - - if ( 0 ) { - printf("-i run-time information level( preset: 1 )\n"); - printf(" 0 only times\n"); - printf(" 1 problem name, planning process infos\n"); - printf(" 101 parsed problem data\n"); - printf(" 102 cleaned up ADL problem\n"); - printf(" 103 collected string tables\n"); - printf(" 104 encoded domain\n"); - printf(" 105 predicates inertia info\n"); - printf(" 106 splitted initial state\n"); - printf(" 107 domain with Wff s normalized\n"); - printf(" 108 domain with NOT conds translated\n"); - printf(" 109 splitted domain\n"); - printf(" 110 cleaned up easy domain\n"); - printf(" 111 unaries encoded easy domain\n"); - printf(" 112 effects multiplied easy domain\n"); - printf(" 113 inertia removed easy domain\n"); - printf(" 114 easy action templates\n"); - printf(" 115 cleaned up hard domain representation\n"); - printf(" 116 mixed hard domain representation\n"); - printf(" 117 final hard domain representation\n"); - printf(" 118 reachability analysis results\n"); - printf(" 119 facts selected as relevant\n"); - printf(" 120 final domain and problem representations\n"); - printf(" 121 normalized expressions representation\n"); - printf(" 122 LNF: translated subtractions representation\n"); - printf(" 123 summarized effects LNF representation\n"); - printf(" 124 encoded LNF representation\n"); - printf(" 125 connectivity graph\n"); - printf(" 126 fixpoint result on each evaluated state\n"); - printf(" 127 1P extracted on each evaluated state\n"); - printf(" 128 H set collected for each evaluated state\n"); - - printf("\n-d switch on debugging\n\n"); - } - -} - - - -Bool process_command_line( int argc, char *argv[] ) - -{ - - char option; - - while ( --argc && ++argv ) { - if ( *argv[0] != '-' || strlen(*argv) != 2 ) { - return FALSE; - } - option = *++argv[0]; - switch ( option ) { -/* case 'E': */ -/* gcmd_line.ehc = FALSE; */ -/* break; */ -/* case 'O': */ -/* gcmd_line.optimize = TRUE; */ -/* gcmd_line.ehc = FALSE; */ -/* break; */ - case 'C': - gcmd_line.cost_rplans = FALSE; - break; - default: - if ( --argc && ++argv ) { - switch ( option ) { - case 'p': - strncpy( gcmd_line.path, *argv, MAX_LENGTH ); - break; - case 'o': - strncpy( gcmd_line.ops_file_name, *argv, MAX_LENGTH ); - break; - case 'f': - strncpy( gcmd_line.fct_file_name, *argv, MAX_LENGTH ); - break; - case 'i': - sscanf( *argv, "%d", &gcmd_line.display_info ); - break; - case 'd': - sscanf( *argv, "%d", &gcmd_line.debug ); - break; - case 's': - sscanf( *argv, "%d", &gcmd_line.search_config ); - break; - case 'w': - sscanf( *argv, "%d", &gcmd_line.w ); - break; - case 'b': - sscanf( *argv, "%f", &gcmd_line.cost_bound ); - break; - default: - printf( "\nff: unknown option: %c entered\n\n", option ); - return FALSE; - } - } else { - return FALSE; - } - } - } - - if ( 0 > gcmd_line.search_config || gcmd_line.search_config > 5 ) { - printf("\n\nff: unknown search configuration %d.\n\n", - gcmd_line.search_config); - return FALSE; - } - - if ( gcmd_line.search_config <= 2 ) { - gcost_minimizing = FALSE; - gcost_rplans = FALSE; - } else { - gcost_minimizing = TRUE; - gcost_rplans = TRUE; - } - - gw = gcmd_line.w; - - if ( !gcmd_line.cost_rplans ) { - gcost_rplans = FALSE; - } - - if ( gcmd_line.cost_bound != -1 && gcmd_line.cost_bound < 0 ) { - printf("\n\nff: invalid cost bound %f; must be >= 0.\n\n", - gcmd_line.cost_bound); - return FALSE; - } - - return TRUE; - -} - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/makefile b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/makefile deleted file mode 100644 index b8ace7b8..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/makefile +++ /dev/null @@ -1,89 +0,0 @@ -#!/bin/sh -# - - -####### FLAGS - -TYPE = -ADDONS = - -CC = gcc - -CFLAGS = -O6 -ansi $(TYPE) $(ADDONS) -g -# -g -pg - -LIBS = -lm - - -####### Files - -PDDL_PARSER_SRC = scan-fct_pddl.tab.c \ - scan-ops_pddl.tab.c \ - scan-probname.tab.c \ - lex.fct_pddl.c \ - lex.ops_pddl.c - -PDDL_PARSER_OBJ = scan-fct_pddl.tab.o \ - scan-ops_pddl.tab.o - - -SOURCES = main.c \ - memory.c \ - output.c \ - parse.c \ - expressions.c \ - inst_pre.c \ - inst_easy.c \ - inst_hard.c \ - inst_final.c \ - relax.c \ - search.c - -OBJECTS = $(SOURCES:.c=.o) - -####### Implicit rules - -.SUFFIXES: - -.SUFFIXES: .c .o - -.c.o:; $(CC) -c $(CFLAGS) $< - -####### Build rules - - -ff: $(OBJECTS) $(PDDL_PARSER_OBJ) - $(CC) -o ff $(OBJECTS) $(PDDL_PARSER_OBJ) $(CFLAGS) $(LIBS) - -# pddl syntax -scan-fct_pddl.tab.c: scan-fct_pddl.y lex.fct_pddl.c - bison -pfct_pddl -bscan-fct_pddl scan-fct_pddl.y - -scan-ops_pddl.tab.c: scan-ops_pddl.y lex.ops_pddl.c - bison -pops_pddl -bscan-ops_pddl scan-ops_pddl.y - -lex.fct_pddl.c: lex-fct_pddl.l - flex -Pfct_pddl lex-fct_pddl.l - -lex.ops_pddl.c: lex-ops_pddl.l - flex -Pops_pddl lex-ops_pddl.l - - -# misc -clean: - rm -f *.o *.bak *~ *% core *_pure_p9_c0_400.o.warnings \ - \#*\# $(RES_PARSER_SRC) $(PDDL_PARSER_SRC) - -veryclean: clean - rm -f ff H* J* K* L* O* graph.* *.symbex gmon.out \ - $(PDDL_PARSER_SRC) \ - lex.fct_pddl.c lex.ops_pddl.c lex.probname.c \ - *.output - -depend: - makedepend -- $(SOURCES) $(PDDL_PARSER_SRC) - -lint: - lclint -booltype Bool $(SOURCES) 2> output.lint - -# DO NOT DELETE diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.c deleted file mode 100644 index 601cea49..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.c +++ /dev/null @@ -1,1278 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: memory.c - * Description: Creation and Deletion functions for all data structures. - * - * Author: Joerg Hoffmann - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" -#include "memory.h" - - -#include "inst_pre.h" - - - - - - -/********************** - * CREATION FUNCTIONS * - **********************/ - - - - - - - - - - - -/* parsing - */ - - - - - - - - - -char *new_Token( int len ) - -{ - - char *tok = ( char * ) calloc( len, sizeof( char ) ); - CHECK_PTR(tok); - - return tok; - -} - - - -TokenList *new_TokenList( void ) - -{ - - TokenList *result = ( TokenList * ) calloc( 1, sizeof( TokenList ) ); - CHECK_PTR(result); - - result->item = NULL; - result->next = NULL; - - return result; - -} - - - -FactList *new_FactList( void ) - -{ - - FactList *result = ( FactList * ) calloc( 1, sizeof( FactList ) ); - CHECK_PTR(result); - - result->item = NULL; - result->next = NULL; - - return result; - -} - - - -TypedList *new_TypedList( void ) - -{ - - TypedList *result = ( TypedList * ) calloc( 1, sizeof( TypedList ) ); - CHECK_PTR(result); - - result->name = NULL; - result->type = NULL; - result->n = -1; - - return result; - -} - - - -TypedListList *new_TypedListList( void ) - -{ - - TypedListList *result = ( TypedListList * ) calloc( 1, sizeof( TypedListList ) ); - CHECK_PTR(result); - - result->predicate = NULL; - result->args = NULL; - - return result; - -} - - - -ParseExpNode *new_ParseExpNode( ExpConnective c ) - -{ - - ParseExpNode *result = ( ParseExpNode * ) calloc( 1, sizeof( ParseExpNode ) ); - CHECK_PTR(result); - - result->connective = c; - result->atom = NULL; - result->leftson = NULL; - result->rightson = NULL; - - return result; - -} - - - -PlNode *new_PlNode( Connective c ) - -{ - - PlNode *result = ( PlNode * ) calloc( 1, sizeof( PlNode ) ); - CHECK_PTR(result); - - result->connective = c; - result->atom = NULL; - - result->comp = -1; - result->neft = -1; - result->lh = NULL; - result->rh = NULL; - - result->sons = NULL; - result->next = NULL; - - return result; - -} - - - -PlOperator *new_PlOperator( char *name ) - -{ - - PlOperator *result = ( PlOperator * ) calloc( 1, sizeof( PlOperator ) ); - CHECK_PTR(result); - - if ( name ) { - result->name = new_Token(strlen(name)+1); - CHECK_PTR(result->name); - strcpy(result->name, name); - } else { - result->name = NULL; - } - - result->params = NULL; - result->preconds = NULL; - result->effects = NULL; - result->number_of_real_params = 0; - result->next = NULL; - - return result; - -} - - - -PlOperator *new_axiom_op_list( void ) - -{ - - static int count; - char *name; - PlOperator *ret; - - /* WARNING: count should not exceed 999 - */ - count++; - if ( count == 10000 ) { - printf("\ntoo many axioms! look into memory.c, line 157\n\n"); - exit( 1 ); - } - name = new_Token(strlen(HIDDEN_STR)+strlen(AXIOM_STR)+4+1); - sprintf(name, "%s%s%4d", HIDDEN_STR, AXIOM_STR, count); - - ret = new_PlOperator(name); - free(name); - - return ret; - -} - - - - - - - - - - - - - - -/* instantiation - */ - - - - - - - - - - - -Fact *new_Fact( void ) - -{ - - Fact *result = ( Fact * ) calloc( 1, sizeof( Fact ) ); - CHECK_PTR(result); - - return result; - -} - - - -Fluent *new_Fluent( void ) - -{ - - Fluent *result = ( Fluent * ) calloc( 1, sizeof( Fluent ) ); - CHECK_PTR(result); - - return result; - -} - - - -FluentValue *new_FluentValue( void ) - -{ - - FluentValue *result = ( FluentValue * ) calloc( 1, sizeof( FluentValue ) ); - CHECK_PTR(result); - - return result; - -} - - - -Facts *new_Facts( void ) - -{ - - Facts *result = ( Facts * ) calloc( 1, sizeof( Facts ) ); - CHECK_PTR(result); - - result->fact = new_Fact(); - - result->next = NULL; - - return result; - -} - - - -FluentValues *new_FluentValues( void ) - -{ - - FluentValues *result = ( FluentValues * ) calloc( 1, sizeof( FluentValues ) ); - CHECK_PTR(result); - - result->next = NULL; - - return result; - -} - - - -ExpNode *new_ExpNode( ExpConnective c ) - -{ - - ExpNode *result = ( ExpNode * ) calloc( 1, sizeof( ExpNode ) ); - CHECK_PTR(result); - - result->connective = c; - result->fluent = NULL; - result->fl = -2; - result->c = 1; - result->son = NULL; - result->leftson = NULL; - result->rightson = NULL; - - return result; - -} - - - -WffNode *new_WffNode( Connective c ) - -{ - - WffNode *result = ( WffNode * ) calloc( 1, sizeof( WffNode ) ); - CHECK_PTR(result); - - result->connective = c; - - result->var = -1; - result->var_type = -1; - result->var_name = NULL; - - result->sons = NULL; - result->next = NULL; - result->prev = NULL; - - result->fact = NULL; - result->NOT_p = -1; - - result->son = NULL; - - result->comp = -1; - result->lh = NULL; - result->rh = NULL; - - result->visited = FALSE; - - return result; - -} - - - -Literal *new_Literal( void ) - -{ - - Literal *result = ( Literal * ) calloc( 1, sizeof( Literal ) ); - CHECK_PTR(result); - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -NumericEffect *new_NumericEffect( void ) - -{ - - NumericEffect *result = ( NumericEffect * ) calloc( 1, sizeof( NumericEffect ) ); - CHECK_PTR(result); - - result->rh = NULL; - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -Effect *new_Effect( void ) - -{ - - Effect *result = ( Effect * ) calloc( 1, sizeof( Effect ) ); - CHECK_PTR(result); - - result->num_vars = 0; - - result->conditions = NULL; - - result->effects = NULL; - result->numeric_effects = NULL; - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -Operator *new_Operator( char *name, int norp ) - -{ - - int i; - - Operator *result = ( Operator * ) calloc( 1, sizeof( Operator ) ); - CHECK_PTR(result); - - if ( name ) { - result->name = new_Token( strlen( name ) + 1 ); - CHECK_PTR( result->name ); - strcpy( result->name, name ); - } else { - result->name = NULL; - } - - result->num_vars = 0; - result->number_of_real_params = norp; - - for ( i = 0; i < MAX_VARS; i++ ) { - result->removed[i] = FALSE; - } - - result->preconds = NULL; - - result->effects = NULL; - - result->hard = TRUE; - - return result; - -} - - - -NormEffect *new_NormEffect1( Effect *e ) - -{ - - int i; - - NormEffect *result = ( NormEffect * ) calloc( 1, sizeof( NormEffect ) ); - CHECK_PTR(result); - - result->num_vars = e->num_vars; - for ( i = 0; i < e->num_vars; i++ ) { - result->var_types[i] = e->var_types[i]; - result->inst_table[i] = -1; - } - - result->conditions = NULL; - result->num_conditions = 0; - - result->adds = NULL; - result->num_adds = 0; - result->dels = NULL; - result->num_dels = 0; - - result->numeric_conditions_comp = NULL; - result->numeric_conditions_lh = NULL; - result->numeric_conditions_rh = NULL; - result->num_numeric_conditions = 0; - - result->numeric_effects_neft = NULL; - result->numeric_effects_fluent = NULL; - result->numeric_effects_rh = NULL; - result->num_numeric_effects = 0; - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -NormEffect *new_NormEffect2( NormEffect *e ) - -{ - - int i, j; - - NormEffect *result = ( NormEffect * ) calloc( 1, sizeof( NormEffect ) ); - CHECK_PTR(result); - - result->num_vars = 0; - - result->conditions = ( Fact * ) calloc( e->num_conditions, sizeof( Fact ) ); - result->num_conditions = e->num_conditions; - for ( i = 0; i < e->num_conditions; i++ ) { - result->conditions[i].predicate = e->conditions[i].predicate; - for ( j = 0; j < garity[e->conditions[i].predicate]; j++ ) { - result->conditions[i].args[j] = e->conditions[i].args[j]; - } - } - result->adds = ( Fact * ) calloc( e->num_adds, sizeof( Fact ) ); - result->num_adds = e->num_adds; - for ( i = 0; i < e->num_adds; i++ ) { - result->adds[i].predicate = e->adds[i].predicate; - for ( j = 0; j < garity[e->adds[i].predicate]; j++ ) { - result->adds[i].args[j] = e->adds[i].args[j]; - } - } - result->dels = ( Fact * ) calloc( e->num_dels, sizeof( Fact ) ); - result->num_dels = e->num_dels; - for ( i = 0; i < e->num_dels; i++ ) { - result->dels[i].predicate = e->dels[i].predicate; - for ( j = 0; j < garity[e->dels[i].predicate]; j++ ) { - result->dels[i].args[j] = e->dels[i].args[j]; - } - } - - result->numeric_conditions_comp = ( Comparator * ) - calloc( e->num_numeric_conditions, sizeof( Comparator ) ); - result->numeric_conditions_lh = ( ExpNode_pointer * ) - calloc( e->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - result->numeric_conditions_rh = ( ExpNode_pointer * ) - calloc( e->num_numeric_conditions, sizeof( ExpNode_pointer ) ); - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - result->numeric_conditions_comp[i] = e->numeric_conditions_comp[i]; - result->numeric_conditions_lh[i] = copy_Exp( e->numeric_conditions_lh[i] ); - result->numeric_conditions_rh[i] = copy_Exp( e->numeric_conditions_rh[i] ); - } - result->num_numeric_conditions = e->num_numeric_conditions; - result->numeric_effects_neft = ( NumericEffectType * ) - calloc( e->num_numeric_effects, sizeof( NumericEffectType ) ); - result->numeric_effects_fluent = ( Fluent * ) - calloc( e->num_numeric_effects, sizeof( Fluent ) ); - result->numeric_effects_rh = ( ExpNode_pointer * ) - calloc( e->num_numeric_effects, sizeof( ExpNode_pointer ) ); - for ( i = 0; i < e->num_numeric_effects; i++ ) { - result->numeric_effects_neft[i] = e->numeric_effects_neft[i]; - result->numeric_effects_fluent[i].function = e->numeric_effects_fluent[i].function; - for ( j = 0; j < gf_arity[e->numeric_effects_fluent[i].function]; j++ ) { - result->numeric_effects_fluent[i].args[j] = e->numeric_effects_fluent[i].args[j]; - } - result->numeric_effects_rh[i] = copy_Exp( e->numeric_effects_rh[i] ); - } - result->num_numeric_effects = e->num_numeric_effects; - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -NormOperator *new_NormOperator( Operator *op ) - -{ - - int i; - - NormOperator *result = ( NormOperator * ) calloc( 1, sizeof( NormOperator ) ); - CHECK_PTR(result); - - result->operator = op; - - result->num_vars = op->num_vars; - for ( i = 0; i < op->num_vars; i++ ) { - result->var_types[i] = op->var_types[i]; - result->inst_table[i] = -1; - } - result->num_removed_vars = 0; - - result->preconds = NULL; - result->num_preconds = 0; - - result->numeric_preconds_comp = NULL; - result->numeric_preconds_lh = NULL; - result->numeric_preconds_rh = NULL; - result->num_numeric_preconds = 0; - - result->effects = NULL; - - return result; - -} - - - - -EasyTemplate *new_EasyTemplate( NormOperator *op ) - -{ - - EasyTemplate *result = ( EasyTemplate * ) calloc( 1, sizeof( EasyTemplate ) ); - CHECK_PTR(result); - - result->op = op; - - result->prev = NULL; - result->next = NULL; - - return result; - -} - - - -MixedOperator *new_MixedOperator( Operator *op ) - -{ - - MixedOperator *result = ( MixedOperator * ) calloc( 1, sizeof( MixedOperator ) ); - CHECK_PTR(result); - - result->operator = op; - - result->preconds = NULL; - result->num_preconds = 0; - - result->effects = NULL; - - return result; - -} - - - -PseudoActionEffect *new_PseudoActionEffect( void ) - -{ - - PseudoActionEffect *result = - ( PseudoActionEffect * ) calloc( 1, sizeof( PseudoActionEffect ) ); - CHECK_PTR(result); - - result->conditions = NULL; - result->num_conditions = 0; - - result->adds = NULL; - result->num_adds = 0; - result->dels = NULL; - result->num_dels = 0; - - result->numeric_conditions_comp = NULL; - result->numeric_conditions_lh = NULL; - result->numeric_conditions_rh = NULL; - result->num_numeric_conditions = 0; - - result->numeric_effects_neft = NULL; - result->numeric_effects_fluent = NULL; - result->numeric_effects_rh = NULL; - result->num_numeric_effects = 0; - - result->next = NULL; - - return result; - -} - - - -PseudoAction *new_PseudoAction( MixedOperator *op ) - -{ - - int i; - - PseudoAction *result = ( PseudoAction * ) calloc( 1, sizeof( PseudoAction ) ); - CHECK_PTR(result); - - result->operator = op->operator; - for ( i = 0; i < op->operator->num_vars; i++ ) { - result->inst_table[i] = op->inst_table[i]; - } - - result->preconds = op->preconds; - result->num_preconds = op->num_preconds; - - result->numeric_preconds_comp = op->numeric_preconds_comp; - result->numeric_preconds_lh = op->numeric_preconds_lh; - result->numeric_preconds_rh = op->numeric_preconds_rh; - result->num_numeric_preconds = op->num_numeric_preconds; - - result->effects = NULL; - result->num_effects = 0; - - return result; - -} - - - -LnfExpNode *new_LnfExpNode( void ) - -{ - - LnfExpNode *result = ( LnfExpNode * ) calloc( 1, sizeof( LnfExpNode ) ); - CHECK_PTR(result); - - result->num_pF = 0; - result->num_nF = 0; - - result->c = 0; - - return result; - -} - - - -Action *new_Action( void ) - -{ - - Action *result = ( Action * ) calloc( 1, sizeof( Action ) ); - CHECK_PTR(result); - - result->norm_operator = NULL; - result->pseudo_action = NULL; - - result->next = NULL; - - return result; - -} - - - -void make_state( State *pointer, int ft, int fl ) - -{ - - int i; - - pointer->F = ( int * ) calloc( ft, sizeof( int ) ); - pointer->f_D = ( Bool * ) calloc( fl, sizeof( Bool ) ); - pointer->f_V = ( float * ) calloc( fl, sizeof( float ) ); - - for ( i = 0; i < fl; i++ ) { - pointer->f_D[i] = FALSE; - } - -} - - - -EhcNode *new_EhcNode( void ) - -{ - - EhcNode *result = ( EhcNode * ) calloc( 1, sizeof( EhcNode ) ); - CHECK_PTR(result); - - make_state( &(result->S), gnum_ft_conn, gnum_fl_conn ); - - result->father = NULL; - result->next = NULL; - - return result; - -} - - - -EhcHashEntry *new_EhcHashEntry( void ) - -{ - - EhcHashEntry *result = ( EhcHashEntry * ) calloc( 1, sizeof( EhcHashEntry ) ); - CHECK_PTR(result); - - result->ehc_node = NULL; - - result->next = NULL; - - return result; - -} - - - -PlanHashEntry *new_PlanHashEntry( void ) - -{ - - PlanHashEntry *result = ( PlanHashEntry * ) calloc( 1, sizeof( PlanHashEntry ) ); - CHECK_PTR(result); - - result->next_step = NULL; - - result->next = NULL; - - return result; - -} - - - -BfsNode *new_BfsNode( void ) - -{ - - BfsNode *result = ( BfsNode * ) calloc( 1, sizeof( BfsNode ) ); - CHECK_PTR(result); - - result->father = NULL; - - result->next = NULL; - result->prev = NULL; - - return result; - -} - - - -BfsHashEntry *new_BfsHashEntry( void ) - -{ - - BfsHashEntry *result = ( BfsHashEntry * ) calloc( 1, sizeof( BfsHashEntry ) ); - CHECK_PTR(result); - - result->bfs_node = NULL; - - result->next = NULL; - - return result; - -} - - - - - - - - - - - -/********************** - * DELETION FUNCTIONS * - **********************/ - - - - - - - - - - - - -void free_TokenList( TokenList *source ) - -{ - - if ( source ) { - free_TokenList( source->next ); - if ( source->item ) { - free( source->item ); - } - free( source ); - } - -} - - - -void free_FactList( FactList *source ) - -{ - - if ( source ) { - free_FactList( source->next ); - free_TokenList( source->item ); - free( source ); - } - -} - - - -void free_ParseExpNode( ParseExpNode *n ) - -{ - - if ( n ) { - free_TokenList( n->atom ); - free_ParseExpNode( n->leftson ); - free_ParseExpNode( n->rightson ); - free( n ); - } - -} - - - -void free_PlNode( PlNode *node ) - -{ - - if ( node ) { - free_ParseExpNode( node->lh ); - free_ParseExpNode( node->rh ); - free_PlNode( node->sons ); - free_PlNode( node->next ); - free_TokenList( node->atom ); - free( node ); - } - -} - - - -void free_PlOperator( PlOperator *o ) - -{ - - if ( o ) { - free_PlOperator( o->next ); - - if ( o->name ) { - free( o->name ); - } - - free_FactList( o->params ); - free_PlNode( o->preconds ); - free_PlNode( o->effects ); - - free( o ); - } - -} - - - -void free_Operator( Operator *o ) - -{ - - if ( o ) { - /* need not free more: the only point where that happens - * is only directly after first allocation - */ - - if ( o->name ) { - free( o->name ); - } - - free( o ); - } - -} - - - -void free_ExpNode( ExpNode *n ) - -{ - - if ( n ) { - if ( n->fluent ) free( n->fluent ); - free_ExpNode( n->son ); - free_ExpNode( n->leftson ); - free_ExpNode( n->rightson ); - free( n ); - } - -} - - - -void free_WffNode( WffNode *w ) - -{ - - if ( w ) { - free_WffNode( w->son ); - free_WffNode( w->sons ); - free_WffNode( w->next ); - if ( w->var_name ) { - free( w->var_name ); - } - if ( w->fact ) free( w->fact ); - free_ExpNode( w->lh ); - free_ExpNode( w->rh ); - free( w ); - } - -} - - - -void free_NormEffect( NormEffect *e ) - -{ - - int i; - - if ( e ) { - free_NormEffect( e->next ); - - if ( e->conditions ) { - free( e->conditions ); - } - if ( e->adds ) { - free( e->adds ); - } - if ( e->dels ) { - free( e->dels ); - } - - if ( e->numeric_conditions_comp ) { - free( e->numeric_conditions_comp ); - } - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - free_ExpNode( e->numeric_conditions_lh[i] ); - free_ExpNode( e->numeric_conditions_rh[i] ); - } - if ( e->numeric_conditions_lh ) { - free( e->numeric_conditions_lh ); - } - if ( e->numeric_conditions_rh ) { - free( e->numeric_conditions_rh ); - } - - if ( e->numeric_effects_neft ) { - free( e->numeric_effects_neft ); - } - if ( e->numeric_effects_fluent ) { - free( e->numeric_effects_fluent ); - } - for ( i = 0; i < e->num_numeric_effects; i++ ) { - free_ExpNode( e->numeric_effects_rh[i] ); - } - if ( e->numeric_effects_rh ) { - free( e->numeric_effects_rh ); - } - - free( e ); - } - -} - - - -void free_partial_Effect( Effect *e ) - -{ - - if ( e ) { - free_partial_Effect( e->next ); - - free_WffNode( e->conditions ); - - free( e ); - } - -} - - - -void free_NormOperator( NormOperator *o ) - -{ - - int i; - - if ( o ) { - - if ( o->preconds ) { - free( o->preconds ); - } - if ( o->numeric_preconds_comp ) { - free( o->numeric_preconds_comp ); - } - for ( i = 0; i < o->num_numeric_preconds; i++ ) { - free_ExpNode( o->numeric_preconds_lh[i] ); - free_ExpNode( o->numeric_preconds_rh[i] ); - } - if ( o->numeric_preconds_lh ) { - free( o->numeric_preconds_lh ); - } - if ( o->numeric_preconds_rh ) { - free( o->numeric_preconds_rh ); - } - free_NormEffect( o->effects ); - - free( o ); - } - -} - - - -void free_single_NormEffect( NormEffect *e ) - -{ - - int i; - - if ( e ) { - if ( e->conditions ) { - free( e->conditions ); - } - if ( e->adds ) { - free( e->adds ); - } - if ( e->dels ) { - free( e->dels ); - } - - if ( e->numeric_conditions_comp ) { - free( e->numeric_conditions_comp ); - } - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - free_ExpNode( e->numeric_conditions_lh[i] ); - free_ExpNode( e->numeric_conditions_rh[i] ); - } - if ( e->numeric_conditions_lh ) { - free( e->numeric_conditions_lh ); - } - if ( e->numeric_conditions_rh ) { - free( e->numeric_conditions_rh ); - } - - if ( e->numeric_effects_neft ) { - free( e->numeric_effects_neft ); - } - if ( e->numeric_effects_fluent ) { - free( e->numeric_effects_fluent ); - } - for ( i = 0; i < e->num_numeric_effects; i++ ) { - free_ExpNode( e->numeric_effects_rh[i] ); - } - if ( e->numeric_effects_rh ) { - free( e->numeric_effects_rh ); - } - - free( e ); - } - -} - - - -void free_single_EasyTemplate( EasyTemplate *t ) - -{ - - if ( t ) { - free( t ); - } - -} - - - -void free_TypedList( TypedList *t ) - -{ - - if ( t ) { - if ( t->name ) { - free( t->name ); - t->name = NULL; - } - if ( t->type ) { - free_TokenList( t->type ); - t->type = NULL; - } - free_TypedList( t->next ); - - free( t ); - } - -} - - - -void free_TypedListList( TypedListList *t ) - -{ - - if ( t ) { - if ( t->predicate ) { - free( t->predicate ); - t->predicate = NULL; - } - if ( t->args ) { - free_TypedList( t->args ); - t->args = NULL; - } - free_TypedListList( t->next ); - - free( t ); - } - -} - - - -void free_BfsNode( BfsNode *n ) - -{ - - if ( n ) { - free_BfsNode( n->next ); - free( n ); - } - -} - - - -void free_BfsHashEntry( BfsHashEntry *n ) - -{ - - if ( n ) { - free_BfsHashEntry( n->next ); - free( n ); - } - -} diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.h deleted file mode 100644 index 13e8ddfb..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/memory.h +++ /dev/null @@ -1,109 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - -/********************************************************************* - * File: memory.h - * Description: Creation / Deletion functions for all data structures. - * - * Author: Joerg Hoffmann / Frank Rittinger - * - *********************************************************************/ - - - - - - -#ifndef _MEMORY_H -#define _MEMORY_H - - - - - -char *new_Token( int len ); -TokenList *new_TokenList( void ); -FactList *new_FactList( void ); -TypedList *new_TypedList( void ); -TypedListList *new_TypedListList( void ); -ParseExpNode *new_ParseExpNode( ExpConnective c ); -PlNode *new_PlNode( Connective c ); -PlOperator *new_PlOperator( char *name ); -PlOperator *new_axiom_op_list( void ); - - - -Fact *new_Fact( void ); -Fluent *new_Fluent( void ); -FluentValue *new_FluentValue( void ); -Facts *new_Facts( void ); -FluentValues *new_FluentValues( void ); -ExpNode *new_ExpNode( ExpConnective c ); -WffNode *new_WffNode( Connective c ); -Literal *new_Literal( void ); -NumericEffect *new_NumericEffect( void ); -Effect *new_Effect( void ); -Operator *new_Operator( char *name, int norp ); -NormEffect *new_NormEffect1( Effect *e ); -NormEffect *new_NormEffect2( NormEffect *e ); -NormOperator *new_NormOperator( Operator *op ); -EasyTemplate *new_EasyTemplate( NormOperator *op ); -MixedOperator *new_MixedOperator( Operator *op ); -PseudoActionEffect *new_PseudoActionEffect( void ); -PseudoAction *new_PseudoAction( MixedOperator *op ); -LnfExpNode *new_LnfExpNode( void ); -Action *new_Action( void ); -void make_state( State *pointer, int ft, int fl ); -EhcNode *new_EhcNode( void ); -EhcHashEntry *new_EhcHashEntry( void ); -PlanHashEntry *new_PlanHashEntry( void ); -BfsNode *new_BfsNode( void ); -BfsHashEntry *new_BfsHashEntry( void ); - - - - - - - -void free_TokenList( TokenList *source ); -void free_FactList( FactList *source ); -void free_ParseExpNode( ParseExpNode *n ); -void free_PlNode( PlNode *node ); -void free_PlOperator( PlOperator *o ); -void free_Operator( Operator *o ); -void free_ExpNode( ExpNode *n ); -void free_WffNode( WffNode *w ); -void free_NormEffect( NormEffect *e ); -void free_partial_Effect( Effect *e ); -void free_NormOperator( NormOperator *o ); -void free_single_NormEffect( NormEffect *e ); -void free_single_EasyTemplate( EasyTemplate *t ); -void free_TypedList( TypedList *t ); -void free_TypedListList( TypedListList *t ); -void free_ActionEffect( ActionEffect *e ); -void free_BfsNode( BfsNode *n ); -void free_BfsHashEntry( BfsHashEntry *n ); - - - - - - -#endif /* _MEMORY_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.c deleted file mode 100644 index 1341eff7..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.c +++ /dev/null @@ -1,1482 +0,0 @@ -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: output.c - * Description: printing info out - * - * Author: Joerg Hoffmann - * - *********************************************************************/ - - - - - -#include "ff.h" - -#include "output.h" - - - - - - - -/* parsing - */ - - - - - - - -void print_FactList( FactList *list, char *sepf, char *sept ) - -{ - - FactList *i_list; - TokenList *i_tl; - - if ( list ) { - i_tl = list->item; - if (NULL == i_tl || NULL == i_tl->item) { - printf("empty"); - } else { - printf("%s", i_tl->item); - i_tl = i_tl->next; - } - - while (NULL != i_tl) { - if (NULL != i_tl->item) { - printf("%s%s", sept, i_tl->item); - } - i_tl = i_tl->next; - } - - for ( i_list = list->next; i_list; i_list = i_list->next ) { - printf("%s", sepf); - i_tl = i_list->item; - if (NULL == i_tl || NULL == i_tl->item) { - printf("empty"); - } else { - printf("%s", i_tl->item); - i_tl = i_tl->next; - } - - while (NULL != i_tl) { - if (NULL != i_tl->item) { - printf("%s%s", sept, i_tl->item); - } - i_tl = i_tl->next; - } - } - } - -} - - - -void print_hidden_TokenList( TokenList *list, char *sep ) - -{ - - TokenList *i_tl; - - i_tl = list; - if (NULL!=i_tl) { - printf("%s", i_tl->item); - i_tl = i_tl->next; - } else { - printf("empty"); - } - - while (NULL != i_tl) { - printf("%s%s", sep, i_tl->item); - i_tl = i_tl->next; - } - -} - - - -void print_indent( int indent ) - -{ - - int i; - for (i=0;iconnective) { - case AD: - printf("(+ "); - print_ParseExpNode( n->leftson ); - print_ParseExpNode( n->rightson ); - printf(")"); - break; - case SU: - printf("(- "); - print_ParseExpNode( n->leftson ); - print_ParseExpNode( n->rightson ); - printf(")"); - break; - case MU: - printf("(* "); - print_ParseExpNode( n->leftson ); - print_ParseExpNode( n->rightson ); - printf(")"); - break; - case DI: - printf("(/ "); - print_ParseExpNode( n->leftson ); - print_ParseExpNode( n->rightson ); - printf(")"); - break; - case MINUS: - printf("(- "); - print_ParseExpNode( n->leftson ); - printf(")"); - break; - case NUMBER: - printf("%s", n->atom->item); - break; - case FHEAD: - printf("("); - print_hidden_TokenList(n->atom, " "); - printf(")"); - break; - default: - printf("\n\nprint Parseexpnode: wrong specifier %d", - n->connective); - } - -} - - - -void print_PlNode( PlNode *plnode, int indent ) - -{ - - PlNode *i_son; - - if ( !plnode ) { - printf("none\n"); - return; - } - - switch (plnode->connective) { - case ALL: - printf("ALL %s : %s\n", plnode->atom->item, - plnode->atom->next->item); - print_indent(indent); - printf("( "); - print_PlNode(plnode->sons,indent+4); - print_indent(indent); - printf(")\n"); - break; - case EX: - printf("EX %s : %s\n", plnode->atom->item, - plnode->atom->next->item); - print_indent(indent); - printf("( "); - print_PlNode(plnode->sons,indent+4); - print_indent(indent); - printf(")\n"); - break; - case AND: - printf("A( "); - print_PlNode(plnode->sons, indent+4); - if ( plnode->sons ) { - for ( i_son = plnode->sons->next; i_son!=NULL; i_son = i_son->next ) { - print_indent(indent); - printf("AND "); - print_PlNode(i_son,indent+4); - } - } - print_indent(indent); - printf(")\n"); - break; - case OR: - printf("O( "); - print_PlNode(plnode->sons, indent+4); - for ( i_son = plnode->sons->next; i_son!=NULL; i_son = i_son->next ) { - print_indent(indent); - printf("OR "); - print_PlNode(i_son,indent+4); - } - print_indent(indent); - printf(")\n"); - break; - case WHEN: - printf("IF "); - print_PlNode(plnode->sons,indent+5); - print_indent(indent); - printf("THEN "); - print_PlNode(plnode->sons->next,indent+5); - print_indent(indent); - printf("ENDIF\n"); - break; - case NOT: - if (ATOM==plnode->sons->connective) { - printf("NOT "); - print_PlNode(plnode->sons,indent+4); - } else { - printf("NOT("); - print_PlNode(plnode->sons,indent+4); - print_indent(indent+3); - printf(")\n"); - } - break; - case ATOM: - printf("("); - print_hidden_TokenList(plnode->atom, " "); - printf(")\n"); - break; - case TRU: - printf("(TRUE)\n"); - break; - case FAL: - printf("(FALSE)\n"); - break; - case COMP: - switch (plnode->comp) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\n\nillegal comp in parse tree!\n\n"); - exit( 1 ); - } - print_ParseExpNode( plnode->lh ); - print_ParseExpNode( plnode->rh ); - printf(")\n"); - break; - case NEF: - switch (plnode->neft) { - case ASSIGN: - printf("(assign "); - break; - case SCALE_UP: - printf("(scale-up "); - break; - case SCALE_DOWN: - printf("(scale-down "); - break; - case INCREASE: - printf("(increase "); - break; - case DECREASE: - printf("(decrease "); - break; - } - print_ParseExpNode( plnode->lh ); - print_ParseExpNode( plnode->rh ); - printf(")\n"); - break; - default: - printf("\n***** ERROR ****"); - printf("\nprint_plnode: %d > Wrong Node specifier\n", plnode->connective); - exit(1); - } - -} - - - -void print_plops( PlOperator *plop ) - -{ - - PlOperator *i_plop; - int count = 0; - - if ( !plop ) { - printf("none\n"); - } - - for ( i_plop = plop; i_plop!=NULL; i_plop = i_plop->next ) { - printf("\n"); - if ( i_plop->axiom ) printf("AXIOM-"); - printf("OPERATOR "); - printf("%s", i_plop->name); - printf("\nparameters: (%d real)\n", i_plop->number_of_real_params); - print_FactList ( i_plop->params, "\n", " : "); - printf("\n\npreconditions:\n"); - print_PlNode(i_plop->preconds, 0); - printf("effects:\n"); - print_PlNode(i_plop->effects, 0); - printf("\n-----\n"); - count++; - } - printf("\nAnzahl der Operatoren: %d\n", count); - -} - - - -void print_ExpNode( ExpNode *n ) - -{ - - if ( !n ) return; - - switch ( n->connective) { - case AD: - printf("(+ "); - print_ExpNode( n->leftson ); - print_ExpNode( n->rightson ); - printf(")"); - break; - case SU: - printf("(- "); - print_ExpNode( n->leftson ); - print_ExpNode( n->rightson ); - printf(")"); - break; - case MU: - printf("(* "); - print_ExpNode( n->leftson ); - print_ExpNode( n->rightson ); - printf(")"); - break; - case DI: - printf("(/ "); - print_ExpNode( n->leftson ); - print_ExpNode( n->rightson ); - printf(")"); - break; - case MINUS: - printf("(- "); - print_ExpNode( n->son ); - printf(")"); - break; - case NUMBER: - printf("%.2f", n->value); - break; - case FHEAD: - if ( n->fluent ) { - print_Fluent( n->fluent ); - } else { - if ( n->fl >= 0 ) { - printf(" %.2f*", n->c); - print_fl_name( n->fl ); - } else { - printf("[UNDEF]"); - } - } - break; - default: - printf("\n\nprint Expnode: wrong specifier %d", - n->connective); - } - -} - - - -void print_Wff( WffNode *n, int indent ) - -{ - - WffNode *i; - - if ( !n ) { - printf("none\n"); - return; - } - - switch (n->connective) { - case ALL: - printf("ALL x%d (%s): %s\n", n->var, n->var_name, - gtype_names[n->var_type]); - print_indent(indent); - printf("( "); - print_Wff(n->son,indent+4); - print_indent(indent); - printf(")\n"); - break; - case EX: - printf("EX x%d (%s) : %s\n", n->var, n->var_name, - gtype_names[n->var_type]); - print_indent(indent); - printf("( "); - print_Wff(n->son,indent+4); - print_indent(indent); - printf(")\n"); - break; - case AND: - printf("A( "); - print_Wff(n->sons, indent+4); - if ( n->sons ) { - for ( i = n->sons->next; i!=NULL; i = i->next ) { - if ( !i->prev ) { - printf("\nprev in AND not correctly set!\n\n"); - exit( 1 ); - } - print_indent(indent); - printf("AND "); - print_Wff(i,indent+4); - } - } - print_indent(indent); - printf(")\n"); - break; - case OR: - printf("O( "); - print_Wff(n->sons, indent+4); - for ( i = n->sons->next; i!=NULL; i = i->next ) { - print_indent(indent); - printf("OR "); - print_Wff(i,indent+4); - } - print_indent(indent); - printf(")\n"); - break; - case NOT: - if (ATOM==n->son->connective) { - printf("NOT "); - print_Wff(n->son,indent+4); - } else { - printf("NOT("); - print_Wff(n->son,indent+4); - print_indent(indent+3); - printf(")\n"); - } - break; - case ATOM: - print_Fact(n->fact); - if ( n->NOT_p != -1 ) printf(" - translation NOT"); - printf("\n"); - break; - case TRU: - printf("(TRUE)\n"); - break; - case FAL: - printf("(FALSE)\n"); - break; - case COMP: - switch (n->comp) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in WFF %d\n\n", n->comp); - exit( 1 ); - } - print_ExpNode( n->lh ); - print_ExpNode( n->rh ); - printf(")\n"); - break; - default: - printf("\n***** ERROR ****"); - printf("\nprint_Wff: %d > Wrong Node specifier\n", n->connective); - exit(1); - } - -} - - - -void print_Operator( Operator *o ) - -{ - - Effect *e; - Literal *l; - NumericEffect *ne; - int i, m = 0; - - printf("\n\n----------------Operator %s, axiom %d, translated form, step 1--------------\n", - o->name, o->axiom); - - for ( i = 0; i < o->num_vars; i++ ) { - printf("\nx%d (%s) of type %s, removed ? %s", - i, o->var_names[i], gtype_names[o->var_types[i]], - o->removed[i] ? "YES" : "NO"); - } - printf("\ntotal params %d, real params %d\n", - o->num_vars, o->number_of_real_params); - - printf("\nPreconds:\n"); - print_Wff( o->preconds, 0 ); - - printf("\n\nEffects:"); - for ( e = o->effects; e; e = e->next ) { - printf("\n\neffect %d, parameters %d", m++, e->num_vars); - - for ( i = 0; i < e->num_vars; i++ ) { - printf("\nx%d (%s) of type %s", - o->num_vars + i, e->var_names[i], gtype_names[e->var_types[i]]); - } - printf("\nConditions\n"); - print_Wff( e->conditions, 0 ); - printf("\nEffect Literals"); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - printf("\nNOT "); - } else { - printf("\n"); - } - print_Fact( &(l->fact) ); - } - printf("\nNumeric Effects"); - for ( ne = e->numeric_effects; ne; ne = ne->next ) { - switch ( ne->neft ) { - case ASSIGN: - printf("\nassign "); - break; - case SCALE_UP: - printf("\nscale-up "); - break; - case SCALE_DOWN: - printf("\nscale-down "); - break; - case INCREASE: - printf("\nincrease "); - break; - case DECREASE: - printf("\ndecrease "); - break; - default: - printf("\n\nprint effect: illegal neft %d\n\n", ne->neft); - exit( 1 ); - } - print_Fluent( &(ne->fluent) ); - print_ExpNode( ne->rh ); - } - } - -} - - - -void print_NormOperator( NormOperator *o ) - -{ - - NormEffect *e; - int i, m; - - printf("\n\n----------------Operator %s, normalized form--------------\n", - o->operator->name); - - for ( i = 0; i < o->num_vars; i++ ) { - printf("\nx%d of type ", i); - print_type( o->var_types[i] ); - } - printf("\n\n%d vars removed from original operator:", - o->num_removed_vars); - for ( i = 0; i < o->num_removed_vars; i++ ) { - m = o->removed_vars[i]; - printf("\nx%d (%s) of type %s, type constraint ", m, o->operator->var_names[m], - gtype_names[o->operator->var_types[m]]); - print_type( o->type_removed_vars[i] ); - } - - printf("\nPreconds:\n"); - for ( i = 0; i < o->num_preconds; i++ ) { - print_Fact( &(o->preconds[i]) ); - printf("\n"); - } - for ( i = 0; i < o->num_numeric_preconds; i++ ) { - switch ( o->numeric_preconds_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in normpre %d\n\n", - o->numeric_preconds_comp[i]); - exit( 1 ); - } - print_ExpNode( o->numeric_preconds_lh[i] ); - print_ExpNode( o->numeric_preconds_rh[i] ); - printf(")\n"); - } - - m = 0; - printf("\n\nEffects:"); - for ( e = o->effects; e; e = e->next ) { - printf("\n\neffect %d, parameters %d", m++, e->num_vars); - - for ( i = 0; i < e->num_vars; i++ ) { - printf("\nx%d of type ", o->num_vars + i); - print_type( e->var_types[i] ); - } - printf("\nConditions\n"); - for ( i = 0; i < e->num_conditions; i++ ) { - print_Fact( &(e->conditions[i]) ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - switch ( e->numeric_conditions_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in normeff %d\n\n", - e->numeric_conditions_comp[i]); - exit( 1 ); - } - print_ExpNode( e->numeric_conditions_lh[i] ); - print_ExpNode( e->numeric_conditions_rh[i] ); - printf(")\n"); - } - - printf("\nAdds\n"); - for ( i = 0; i < e->num_adds; i++ ) { - print_Fact( &(e->adds[i]) ); - printf("\n"); - } - printf("\nDels\n"); - for ( i = 0; i < e->num_dels; i++ ) { - print_Fact( &(e->dels[i]) ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_effects; i++ ) { - switch ( e->numeric_effects_neft[i] ) { - case ASSIGN: - printf("\nassign "); - break; - case SCALE_UP: - printf("\nscale-up "); - break; - case SCALE_DOWN: - printf("\nscale-down "); - break; - case INCREASE: - printf("\nincrease "); - break; - case DECREASE: - printf("\ndecrease "); - break; - default: - printf("\n\nprint normop: illegal neft %d\n\n", - e->numeric_effects_neft[i]); - exit( 1 ); - } - print_Fluent( &(e->numeric_effects_fluent[i]) ); - print_ExpNode( e->numeric_effects_rh[i] ); - } - } - -} - - - -void print_MixedOperator( MixedOperator *o ) - -{ - - int i, m; - Effect *e; - NumericEffect *ne; - Literal *l; - - printf("\n\n----------------Operator %s, mixed form--------------\n", - o->operator->name); - - for ( i = 0; i < o->operator->num_vars; i++ ) { - printf("\nx%d = %s of type ", i, gconstants[o->inst_table[i]]); - print_type( o->operator->var_types[i] ); - } - - printf("\nPreconds:\n"); - for ( i = 0; i < o->num_preconds; i++ ) { - print_Fact( &(o->preconds[i]) ); - printf("\n"); - } - for ( i = 0; i < o->num_numeric_preconds; i++ ) { - switch ( o->numeric_preconds_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in mixedpre %d\n\n", - o->numeric_preconds_comp[i]); - exit( 1 ); - } - print_ExpNode( o->numeric_preconds_lh[i] ); - print_ExpNode( o->numeric_preconds_rh[i] ); - printf(")\n"); - } - - m = 0; - printf("\n\nEffects:"); - for ( e = o->effects; e; e = e->next ) { - printf("\n\neffect %d, parameters %d", m++, e->num_vars); - - for ( i = 0; i < e->num_vars; i++ ) { - printf("\nx%d of type %s", - o->operator->num_vars + i, gtype_names[e->var_types[i]]); - } - printf("\nConditions\n"); - print_Wff( e->conditions, 0 ); - printf("\nEffect Literals"); - for ( l = e->effects; l; l = l->next ) { - if ( l->negated ) { - printf("\nNOT "); - } else { - printf("\n"); - } - print_Fact( &(l->fact) ); - } - printf("\nNumeric Effects"); - for ( ne = e->numeric_effects; ne; ne = ne->next ) { - switch ( ne->neft ) { - case ASSIGN: - printf("\nassign "); - break; - case SCALE_UP: - printf("\nscale-up "); - break; - case SCALE_DOWN: - printf("\nscale-down "); - break; - case INCREASE: - printf("\nincrease "); - break; - case DECREASE: - printf("\ndecrease "); - break; - default: - printf("\n\nprint effect: illegal neft %d\n\n", ne->neft); - exit( 1 ); - } - print_Fluent( &(ne->fluent) ); - print_ExpNode( ne->rh ); - } - } - -} - - - -void print_PseudoAction( PseudoAction *o ) - -{ - - PseudoActionEffect *e; - int i, m; - - printf("\n\n----------------Pseudo Action %s--------------\n", - o->operator->name); - - for ( i = 0; i < o->operator->num_vars; i++ ) { - printf("\nx%d = %s of type ", i, gconstants[o->inst_table[i]]); - print_type( o->operator->var_types[i] ); - } - - printf("\nPreconds:\n"); - for ( i = 0; i < o->num_preconds; i++ ) { - print_Fact( &(o->preconds[i]) ); - printf("\n"); - } - for ( i = 0; i < o->num_numeric_preconds; i++ ) { - switch ( o->numeric_preconds_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in mixedpre %d\n\n", - o->numeric_preconds_comp[i]); - exit( 1 ); - } - print_ExpNode( o->numeric_preconds_lh[i] ); - print_ExpNode( o->numeric_preconds_rh[i] ); - printf(")\n"); - } - - m = 0; - printf("\n\nEffects:"); - for ( e = o->effects; e; e = e->next ) { - printf("\n\neffect %d", m++); - printf("\n\nConditions\n"); - for ( i = 0; i < e->num_conditions; i++ ) { - print_Fact( &(e->conditions[i]) ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - switch ( e->numeric_conditions_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in normeff %d\n\n", - e->numeric_conditions_comp[i]); - exit( 1 ); - } - print_ExpNode( e->numeric_conditions_lh[i] ); - print_ExpNode( e->numeric_conditions_rh[i] ); - printf(")\n"); - } - - printf("\nAdds\n"); - for ( i = 0; i < e->num_adds; i++ ) { - print_Fact( &(e->adds[i]) ); - printf("\n"); - } - printf("\nDels\n"); - for ( i = 0; i < e->num_dels; i++ ) { - print_Fact( &(e->dels[i]) ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_effects; i++ ) { - switch ( e->numeric_effects_neft[i] ) { - case ASSIGN: - printf("\nassign "); - break; - case SCALE_UP: - printf("\nscale-up "); - break; - case SCALE_DOWN: - printf("\nscale-down "); - break; - case INCREASE: - printf("\nincrease "); - break; - case DECREASE: - printf("\ndecrease "); - break; - default: - printf("\n\nprint normop: illegal neft %d\n\n", - e->numeric_effects_neft[i]); - exit( 1 ); - } - print_Fluent( &(e->numeric_effects_fluent[i]) ); - print_ExpNode( e->numeric_effects_rh[i] ); - } - } - -} - - - -void print_Action( Action *a ) - -{ - - ActionEffect *e; - int i, j; - - if ( !a->norm_operator && - !a->pseudo_action ) { - printf("\n\nAction REACH-GOAL"); - } else { - printf("\n\nAction %s", a->name ); - for ( i = 0; i < a->num_name_vars; i++ ) { - printf(" %s", gconstants[a->name_inst_table[i]]); - } - } - - printf("\n\nPreconds:\n"); - for ( i = 0; i < a->num_preconds; i++ ) { - print_ft_name( a->preconds[i] ); - printf("\n"); - } - for ( i = 0; i < a->num_numeric_preconds; i++ ) { - switch ( a->numeric_preconds_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in actionpre %d\n\n", - a->numeric_preconds_comp[i]); - exit( 1 ); - } - print_ExpNode( a->numeric_preconds_lh[i] ); - print_ExpNode( a->numeric_preconds_rh[i] ); - printf(")\n"); - } - - printf("\n\nEffects:"); - for ( j = 0; j < a->num_effects; j++ ) { - printf("\n\neffect %d", j); - e = &(a->effects[j]); - if ( e->illegal ) printf(" ILLEGAL EFFECT!"); - printf("\n\nConditions\n"); - for ( i = 0; i < e->num_conditions; i++ ) { - print_ft_name( e->conditions[i] ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_conditions; i++ ) { - switch ( e->numeric_conditions_comp[i] ) { - case LE: - printf("(< "); - break; - case LEQ: - printf("(<= "); - break; - case EQ: - printf("(= "); - break; - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in normeff %d\n\n", - e->numeric_conditions_comp[i]); - exit( 1 ); - } - print_ExpNode( e->numeric_conditions_lh[i] ); - print_ExpNode( e->numeric_conditions_rh[i] ); - printf(")\n"); - } - printf("\nAdds\n"); - for ( i = 0; i < e->num_adds; i++ ) { - print_ft_name( e->adds[i] ); - printf("\n"); - } - printf("\nDels\n"); - for ( i = 0; i < e->num_dels; i++ ) { - print_ft_name( e->dels[i] ); - printf("\n"); - } - for ( i = 0; i < e->num_numeric_effects; i++ ) { - switch ( e->numeric_effects_neft[i] ) { - case ASSIGN: - printf("\nassign "); - break; - case SCALE_UP: - printf("\nscale-up "); - break; - case SCALE_DOWN: - printf("\nscale-down "); - break; - case INCREASE: - printf("\nincrease "); - break; - case DECREASE: - printf("\ndecrease "); - break; - default: - printf("\n\nprint normop: illegal neft %d\n\n", - e->numeric_effects_neft[i]); - exit( 1 ); - } - if ( e->numeric_effects_fl[i] >= 0 ) { - print_fl_name( e->numeric_effects_fl[i] ); - } else { - printf("[UNDEF]"); - } - print_ExpNode( e->numeric_effects_rh[i] ); - } - } - -} - - - -void print_Action_name( Action *a ) - -{ - - int i; - - if ( !a->norm_operator && - !a->pseudo_action ) { - printf("REACH-GOAL"); - } else { - printf("%s", a->name ); - for ( i = 0; i < a->num_name_vars; i++ ) { - printf(" %s", gconstants[a->name_inst_table[i]]); - } - } - -} - - - -void print_lnf_Action( Action *a ) - -{ - - ActionEffect *e; - int i, j; - - if ( !a->norm_operator && - !a->pseudo_action ) { - printf("\n\nAction REACH-GOAL"); - } else { - printf("\n\nAction %s", a->name ); - for ( i = 0; i < a->num_name_vars; i++ ) { - printf(" %s", gconstants[a->name_inst_table[i]]); - } - } - - printf("\n\nPreconds:\n"); - for ( i = 0; i < a->num_preconds; i++ ) { - print_ft_name( a->preconds[i] ); - printf("\n"); - } - for ( i = 0; i < a->num_lnf_preconds; i++ ) { - switch ( a->lnf_preconds_comp[i] ) { - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in lnf actionpre %d\n\n", - a->lnf_preconds_comp[i]); - exit( 1 ); - } - print_LnfExpNode( a->lnf_preconds_lh[i] ); - printf(" %.2f)\n", a->lnf_preconds_rh[i]); - } - - printf("\n\nEffects:"); - for ( j = 0; j < a->num_effects; j++ ) { - printf("\n\neffect %d COST %f", j, a->effects[j].cost); - e = &(a->effects[j]); - if ( e->illegal ) printf(" ILLEGAL EFFECT!"); - if ( e->removed ) printf(" REMOVED!!!"); - printf("\n\nConditions\n"); - for ( i = 0; i < e->num_conditions; i++ ) { - print_ft_name( e->conditions[i] ); - printf("\n"); - } - for ( i = 0; i < e->num_lnf_conditions; i++ ) { - switch ( e->lnf_conditions_comp[i] ) { - case GEQ: - printf("(>= "); - break; - case GE: - printf("(> "); - break; - default: - printf("\nwrong comparator of Expnodes in lnf normeff %d\n\n", - e->lnf_conditions_comp[i]); - exit( 1 ); - } - print_LnfExpNode( e->lnf_conditions_lh[i] ); - printf(" %.2f)\n", e->lnf_conditions_rh[i] ); - } - printf("\nAdds\n"); - for ( i = 0; i < e->num_adds; i++ ) { - print_ft_name( e->adds[i] ); - printf("\n"); - } - printf("\nDels\n"); - for ( i = 0; i < e->num_dels; i++ ) { - print_ft_name( e->dels[i] ); - printf("\n"); - } - for ( i = 0; i < e->num_lnf_effects; i++ ) { - switch ( e->lnf_effects_neft[i] ) { - case ASSIGN: - printf("\nassign "); - break; - case INCREASE: - printf("\nincrease "); - break; - default: - printf("\n\nprint lnf normop: illegal neft %d\n\n", - e->lnf_effects_neft[i]); - exit( 1 ); - } - if ( e->lnf_effects_fl[i] >= 0 ) { - print_fl_name( e->lnf_effects_fl[i] ); - } else { - printf("[UNDEF]"); - } - print_LnfExpNode( e->lnf_effects_rh[i] ); - } - } - -} - - - -void print_type( int t ) - -{ - - int j; - - if ( gpredicate_to_type[t] == -1 ) { - if ( gnum_intersected_types[t] == -1 ) { - printf("%s", gtype_names[t]); - } else { - printf("INTERSECTED TYPE ("); - for ( j = 0; j < gnum_intersected_types[t]; j++ ) { - if ( gpredicate_to_type[gintersected_types[t][j]] == -1 ) { - printf("%s", gtype_names[gintersected_types[t][j]]); - } else { - printf("UNARY INERTIA TYPE (%s)", - gpredicates[gpredicate_to_type[gintersected_types[t][j]]]); - } - if ( j < gnum_intersected_types[t] - 1 ) { - printf(" and "); - } - } - printf(")"); - } - } else { - printf("UNARY INERTIA TYPE (%s)", gpredicates[gpredicate_to_type[t]]); - } - -} - - - -void print_Fact( Fact *f ) - -{ - - int j; - - if ( f->predicate == -3 ) { - printf("GOAL-REACHED"); - return; - } - - if ( f->predicate == -1 ) { - printf("(="); - for ( j=0; j<2; j++ ) { - printf(" "); - if ( f->args[j] >= 0 ) { - printf("%s", gconstants[(f->args)[j]]); - } else { - printf("x%d", DECODE_VAR( f->args[j] )); - } - } - printf(")"); - return; - } - - if ( f->predicate == -2 ) { - printf("(!="); - for ( j=0; j<2; j++ ) { - printf(" "); - if ( f->args[j] >= 0 ) { - printf("%s", gconstants[(f->args)[j]]); - } else { - printf("x%d", DECODE_VAR( f->args[j] )); - } - } - printf(")"); - return; - } - - printf("(%s", gpredicates[f->predicate]); - for ( j=0; jpredicate]; j++ ) { - printf(" "); - if ( f->args[j] >= 0 ) { - printf("%s", gconstants[(f->args)[j]]); - } else { - printf("x%d", DECODE_VAR( f->args[j] )); - } - } - printf(")"); - -} - - - -void print_Fluent( Fluent *f ) - -{ - - int j, ff = f->function; - - printf("(%s", gfunctions[ff]); - for ( j=0; jargs[j] >= 0 ) { - printf("%s", gconstants[(f->args)[j]]); - } else { - printf("x%d", DECODE_VAR( f->args[j] )); - } - } - printf(")"); - -} - - - -void print_ft_name( int index ) - -{ - - print_Fact( &(grelevant_facts[index]) ); - -} - - - -void print_fl_name( int index ) - -{ - - int i; - - if ( index < 0 ) { - if ( index != -2 ) { - printf("[UNDEF]"); - } else { - printf("[TOTAL-TIME]"); - } - return; - } - - if ( grelevant_fluents_lnf[index] == NULL ) { - /* this is a non-artificial "atomic" one - * (or the mirrored version of one) - */ - printf("[RF%d](%s)", index, grelevant_fluents_name[index]); - } else { - /* this only summarizes a LNF requirement - */ - printf("[artRF%d]", index); - for ( i = 0; i < grelevant_fluents_lnf[index]->num_pF; i++ ) { - printf("%.2f*", grelevant_fluents_lnf[index]->pC[i] ); - print_fl_name( grelevant_fluents_lnf[index]->pF[i] ); - if ( i < grelevant_fluents_lnf[index]->num_pF - 1 ) { - printf(" + "); - } - } - } - -} - - - -void print_LnfExpNode( LnfExpNode *n ) - -{ - - int i; - - printf("(("); - for ( i = 0; i < n->num_pF; i++ ) { - printf("%.2f*", n->pC[i]); - print_fl_name( n->pF[i] ); - } - printf(") - ("); - for ( i = 0; i < n->num_nF; i++ ) { - printf("%.2f*", n->nC[i]); - print_fl_name( n->nF[i] ); - } - printf(") + %.2f)", n->c); - -} - - - -void print_op_name( int index ) - -{ - - int i; - Action *a = gop_conn[index].action; - - if ( !a->norm_operator && - !a->pseudo_action ) { - printf("REACH-GOAL"); - } else { - printf("%s", a->name ); - for ( i = 0; i < a->num_name_vars; i++ ) { - printf(" %s", gconstants[a->name_inst_table[i]]); - } - } - -} - - - -void print_State( State S ) - -{ - - int i; - - for ( i = 0; i < S.num_F; i++ ) { - printf("\n"); - print_ft_name( S.F[i] ); - } - for ( i = 0; i < gnum_relevant_fluents; i++ ) { - printf("\n"); - print_fl_name( i ); - printf(": "); - if ( S.f_D[i] ) { - printf("%.2f", S.f_V[i]); - } else { - printf("UNDEF"); - } - } - -} - - - - - - - - -/* - * program output routines - */ - - - - - - - - - -void print_plan( void ) - -{ - - int i; - float cost = 0; - - printf("\n\nff: found legal plan as follows"); - printf("\nstep "); - for ( i = 0; i < gnum_plan_ops; i++ ) { - printf("%4d: ", i); - print_op_name( gplan_ops[i] ); - if ( i < gnum_plan_ops-1 ) { - printf("\n "); - } - if ( goptimization_established ) { - cost += gop_conn[gplan_ops[i]].cost; - } - } - if ( goptimization_established ) { - printf("\nplan cost: %f", cost); - } - -} diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.h deleted file mode 100644 index a74e8760..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/output.h +++ /dev/null @@ -1,68 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: output.h - * Description: print headers - * - * Author: Joerg Hoffmann 1999 - * - *********************************************************************/ - - - - - -#ifndef _OUTPUT_H -#define _OUTPUT_H - - - -void print_FactList( FactList *list, char *sepf, char *sept ); -void print_hidden_TokenList( TokenList *list, char *sep ); -void print_indent( int indent ); -void print_ParseExpNode( ParseExpNode *n ); -void print_PlNode( PlNode *plnode, int indent ); -void print_ExpNode( ExpNode *n ); -void print_Wff( WffNode *n, int indent ); -void print_plops( PlOperator *plop ); -void print_Operator( Operator *o ); -void print_NormOperator( NormOperator *o ); -void print_MixedOperator( MixedOperator *o ); -void print_PseudoAction( PseudoAction *o ); -void print_Action( Action *a ); -void print_Action_name( Action *a ); -void print_lnf_Action( Action *a ); -void print_type( int t ); -void print_Fact( Fact *f ); -void print_Fluent( Fluent *f ); -void print_ft_name( int index ); -void print_op_name( int index ); -void print_fl_name( int index ); -void print_LnfExpNode( LnfExpNode *n ); -void print_State( State S ); - - - -void print_plan( void ); - - - -#endif /* _OUTPUT_H */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.c deleted file mode 100644 index cc5a099f..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.c +++ /dev/null @@ -1,1339 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: parse.c - * Description: Functions for the pddl parser - * - * Author: Joerg Hoffmann 2000 - * - *********************************************************************/ - - - - - - -#include "ff.h" - -#include "memory.h" -#include "output.h" - -#include "parse.h" - - - - - - - - - - - -/* simple parse helpers - */ - - - - - - - -char *copy_Token( char *s ) - -{ - - char *d = new_Token( strlen( s ) + 1 ); - strcpy(d, s); - - return d; - -} - - - -TokenList *copy_TokenList( TokenList *source ) - -{ - - TokenList *temp; - - if ( !source ) { - temp = NULL; - } else { - temp = new_TokenList(); - if ( source->item ) { - temp->item = new_Token( strlen( source->item ) + 1 ); - strcpy( temp->item, source->item ); - } - temp->next = copy_TokenList( source->next ); - } - - return temp; - -} - - - -void strupcase( char *from ) - -{ - - char tmp; - - tmp = *from; - while ('\0' != tmp) { - *from = (char) toupper((int) tmp); - tmp = *++from; - } - -} - - - -char *rmdash( char *s ) - -{ - - s++; - - for( ; (*s == ' ') || (*s == '\t'); s++ ); - - return s; - -} - - - - - - - - - - -/* typed-list-of preprocessing - */ - - - - - - - -Token ltype_names[MAX_TYPES]; -int lnum_types; - - -int leither_ty[MAX_TYPES][MAX_TYPES]; -int lnum_either_ty[MAX_TYPES]; - - - - - -void build_orig_constant_list( void ) - -{ - - char *tmp = NULL; - TypedList *tyl; - TypedListList *tyll; - TokenList *tl, *p_tl, *tmp_tl; - PlOperator *po; - - int i, j, k, n, std; - - Bool m[MAX_TYPES][MAX_TYPES]; - - FactList *fl, *p_fl; - - lnum_types = 0; - for ( tyl = gparse_types; tyl; tyl = tyl->next ) { - if ( get_type( tyl->name ) == -1 ) { - ltype_names[lnum_types++] = copy_Token( tyl->name ); - } - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - - for ( tyl = gparse_constants; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - - for ( tyl = gparse_objects; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - - for ( tyll = gparse_predicates; tyll; tyll = tyll->next ) { - for ( tyl = tyll->args; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - } - - for ( tyll = gparse_functions; tyll; tyll = tyll->next ) { - for ( tyl = tyll->args; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - } - - collect_type_names_in_pl( gorig_goal_facts ); - - for ( po = gloaded_ops; po; po = po->next ) { - collect_type_names_in_pl( po->preconds ); - collect_type_names_in_pl( po->effects ); - for ( tyl = po->parse_params; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (n = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = n; - } - free( tmp ); - tmp = NULL; - } - } - - - /* now get the numbers of all composed either types - */ - for ( i = 0; i < lnum_types; i++ ) { - lnum_either_ty[i] = 0; - } - for ( tyl = gparse_types; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - for ( tyl = gparse_constants; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - for ( tyl = gparse_objects; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - for ( tyll = gparse_predicates; tyll; tyll = tyll->next ) { - for ( tyl = tyll->args; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - } - for ( tyll = gparse_functions; tyll; tyll = tyll->next ) { - for ( tyl = tyll->args; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - } - make_either_ty_in_pl( gorig_goal_facts ); - for ( po = gloaded_ops; po; po = po->next ) { - make_either_ty_in_pl( po->preconds ); - make_either_ty_in_pl( po->effects ); - for ( tyl = po->parse_params; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - } - - - /* now, compute the transitive closure of all type inclusions. - * first initialize the matrix. - */ - for ( i = 0; i < lnum_types; i++ ) { - for ( j = 0; j < lnum_types; j++ ) { - m[i][j] = ( i == j ? TRUE : FALSE ); - } - } - std = -1; - for ( i = 0; i < lnum_types; i++ ) { - if ( strcmp( ltype_names[i], STANDARD_TYPE ) == SAME ) { - std = i; - break; - } - } - for ( i = 0; i < lnum_types; i++ ) { - m[i][std] = TRUE;/* all types are subtypes of OBJECT */ - } - for ( tyl = gparse_types; tyl; tyl = tyl->next ) { - /* all inclusions as are defined in domain file - */ - m[get_type( tyl->name )][tyl->n] = TRUE; - } - /* compute transitive closure on inclusions matrix - */ - for ( j = 0; j < lnum_types; j++ ) { - for ( i = 0; i < lnum_types; i++ ) { - if ( m[i][j] ) { - for ( k = 0; k < lnum_types; k++ ) { - if ( m[j][k] ) { - m[i][k] = TRUE; - } - } - } - } - } - /* union types are subsets of all those types that contain all - * their components, and - * all component types are subsets of the either type ! - */ - for ( i = 0; i < lnum_types; i++ ) { - if ( lnum_either_ty[i] < 2 ) continue; - for ( j = 0; j < lnum_types; j++ ) { - if ( j == i ) continue; - /* get supertypes of all component types - */ - for ( k = 0; k < lnum_either_ty[i]; k++ ) { - if ( !m[leither_ty[i][k]][j] ) break; - } - if ( k < lnum_either_ty[i] ) continue; - m[i][j] = TRUE; - /* make components subtypes of either type - */ - for ( k = 0; k < lnum_either_ty[i]; k++ ) { - m[leither_ty[i][k]][i] = TRUE; - } - } - } - /* and again, compute transitive closure on inclusions matrix. - * I guess, this won't change anything (?), but it also won't need - * any remarkable computation time, so why should one think about it ? - */ - for ( j = 0; j < lnum_types; j++ ) { - for ( i = 0; i < lnum_types; i++ ) { - if ( m[i][j] ) { - for ( k = 0; k < lnum_types; k++ ) { - if ( m[j][k] ) { - m[i][k] = TRUE; - } - } - } - } - } - - - /* now build FactList of ALL constant -> type pairs. - * for each constant / object, let it appear separately - * for each type it is a member of; compute type - * membership based on propagating constants / objects - * through inclusions matrix. - * - * this might make the same pair appear doubly, if an object - * is declared in type T as well as in some supertype T'. - * such cases will be filtered out in string collection. - */ - for ( tyl = gparse_constants; tyl; tyl = tyl->next ) { - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( tyl->name ); - if ( tyl->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( tyl->type->item ); - } - fl->next = gorig_constant_list; - gorig_constant_list = fl; - /* now add constant to all supertypes - */ - n = get_type( fl->item->next->item ); - for ( i = 0; i < lnum_types; i++ ) { - if ( i == n || - !m[n][i] ) continue; - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( tyl->name ); - fl->item->next->item = copy_Token( ltype_names[i] ); - fl->next = gorig_constant_list; - gorig_constant_list = fl; - } - } - for ( tyl = gparse_objects; tyl; tyl = tyl->next ) { - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( tyl->name ); - if ( tyl->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( tyl->type->item ); - } - fl->next = gorig_constant_list; - gorig_constant_list = fl; - /* now add constant to all supertypes - */ - n = get_type( fl->item->next->item ); - for ( i = 0; i < lnum_types; i++ ) { - if ( i == n || - !m[n][i] ) continue; - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( tyl->name ); - fl->item->next->item = copy_Token( ltype_names[i] ); - fl->next = gorig_constant_list; - gorig_constant_list = fl; - } - } - - - /* now, normalize all typed-list-of s in domain and problem def, - * i.e., in all PlNode quantifiers and in op parameters - * - * at the same time, remove typed-listof structures in these defs - */ - normalize_tyl_in_pl( &gorig_goal_facts ); - for ( po = gloaded_ops; po; po = po->next ) { - normalize_tyl_in_pl( &po->preconds ); - normalize_tyl_in_pl( &po->effects ); - /* be careful to maintain parameter ordering ! - */ - if ( !po->parse_params ) { - continue;/* no params at all */ - } - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( po->parse_params->name ); - if ( po->parse_params->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = po->parse_params->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( po->parse_params->type->item ); - } - po->params = fl; - p_fl = fl; - for ( tyl = po->parse_params->next; tyl; tyl = tyl->next ) { - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->next = new_TokenList(); - fl->item->item = copy_Token( tyl->name ); - if ( tyl->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( tyl->type->item ); - } - p_fl->next = fl; - p_fl = fl; - } - free_TypedList( po->parse_params ); - po->parse_params = NULL; - } - - - /* finally, build gpredicates_and_types by chaining predicate names - * together with the names of their args' types. - */ - for ( tyll = gparse_predicates; tyll; tyll = tyll->next ) { - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->item = copy_Token( tyll->predicate ); - fl->next = gpredicates_and_types; - gpredicates_and_types = fl; - if ( !tyll->args ) continue; - /* add arg types; MAINTAIN ORDERING ! - */ - fl->item->next = new_TokenList(); - if ( tyll->args->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = tyll->args->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( tyll->args->type->item ); - } - p_tl = fl->item->next; - for ( tyl = tyll->args->next; tyl; tyl = tyl->next ) { - tmp_tl = new_TokenList(); - if ( tyl->type->next ) { - tmp_tl->item = new_Token( MAX_LENGTH ); - strcpy( tmp_tl->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp_tl->item, CONNECTOR ); - strcat( tmp_tl->item, tl->item ); - } - } else { - tmp_tl->item = copy_Token( tyl->type->item ); - } - p_tl->next = tmp_tl; - p_tl = tmp_tl; - } - } - - for ( tyll = gparse_functions; tyll; tyll = tyll->next ) { - fl = new_FactList(); - fl->item = new_TokenList(); - fl->item->item = copy_Token( tyll->predicate ); - fl->next = gfunctions_and_types; - gfunctions_and_types = fl; - if ( !tyll->args ) continue; - /* add arg types; MAINTAIN ORDERING ! - */ - fl->item->next = new_TokenList(); - if ( tyll->args->type->next ) { - fl->item->next->item = new_Token( MAX_LENGTH ); - strcpy( fl->item->next->item, EITHER_STR ); - for ( tl = tyll->args->type; tl; tl = tl->next ) { - strcat( fl->item->next->item, CONNECTOR ); - strcat( fl->item->next->item, tl->item ); - } - } else { - fl->item->next->item = copy_Token( tyll->args->type->item ); - } - p_tl = fl->item->next; - for ( tyl = tyll->args->next; tyl; tyl = tyl->next ) { - tmp_tl = new_TokenList(); - if ( tyl->type->next ) { - tmp_tl->item = new_Token( MAX_LENGTH ); - strcpy( tmp_tl->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp_tl->item, CONNECTOR ); - strcat( tmp_tl->item, tl->item ); - } - } else { - tmp_tl->item = copy_Token( tyl->type->item ); - } - p_tl->next = tmp_tl; - p_tl = tmp_tl; - } - } - - /* now get rid of remaining typed-list-of parsing structures - */ - free_TypedList( gparse_types ); - gparse_types = NULL; - free_TypedList( gparse_constants ); - gparse_constants = NULL; - free_TypedList( gparse_objects ); - gparse_objects = NULL; - free_TypedListList( gparse_predicates ); - gparse_predicates = NULL; - free_TypedListList( gparse_functions ); - gparse_functions = NULL; - -} - - - -void collect_type_names_in_pl( PlNode *n ) - -{ - - PlNode *i; - TypedList *tyl; - TokenList *tl; - char *tmp = NULL; - int nn; - - if ( !n ) { - return; - } - - switch( n->connective ) { - case ALL: - case EX: - for ( tyl = n->parse_vars; tyl; tyl = tyl->next ) { - if ( tyl->type->next ) { - tmp = new_Token( MAX_LENGTH ); - strcpy( tmp, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp, CONNECTOR ); - strcat( tmp, tl->item ); - } - } else { - tmp = copy_Token( tyl->type->item ); - } - if ( (nn = get_type( tmp )) == -1 ) { - tyl->n = lnum_types; - ltype_names[lnum_types++] = copy_Token( tmp ); - } else { - tyl->n = nn; - } - free( tmp ); - tmp = NULL; - } - collect_type_names_in_pl( n->sons ); - break; - case AND: - case OR: - for ( i = n->sons; i; i = i->next ) { - collect_type_names_in_pl( i ); - } - break; - case NOT: - collect_type_names_in_pl( n->sons ); - break; - case ATOM: - case TRU: - case FAL: - break; - case WHEN: - collect_type_names_in_pl( n->sons ); - collect_type_names_in_pl( n->sons->next ); - break; - default: - break; - } - -} - - - -int get_type( char *str ) - -{ - - int i; - - for ( i = 0; i < lnum_types; i++ ) { - if ( strcmp( str, ltype_names[i] ) == SAME ) return i; - } - - return -1; - -} - - - -void make_either_ty( TypedList *tyl ) - -{ - - TokenList *i; - - if ( lnum_either_ty[tyl->n] > 0 ) { - return; - } - - for ( i = tyl->type; i; i = i->next ) { - leither_ty[tyl->n][lnum_either_ty[tyl->n]++] = get_type( i->item ); - } - -} - - - -void make_either_ty_in_pl( PlNode *n ) - -{ - - PlNode *i; - TypedList *tyl; - - if ( !n ) { - return; - } - - switch( n->connective ) { - case ALL: - case EX: - for ( tyl = n->parse_vars; tyl; tyl = tyl->next ) { - make_either_ty( tyl ); - } - make_either_ty_in_pl( n->sons ); - break; - case AND: - case OR: - for ( i = n->sons; i; i = i->next ) { - make_either_ty_in_pl( i ); - } - break; - case NOT: - make_either_ty_in_pl( n->sons ); - break; - case ATOM: - case TRU: - case FAL: - break; - case WHEN: - make_either_ty_in_pl( n->sons ); - make_either_ty_in_pl( n->sons->next ); - break; - default: - break; - } - -} - - - -void normalize_tyl_in_pl( PlNode **n ) - -{ - - PlNode *i; - TypedList *tyl; - PlNode *tmp_pl = NULL, *sons, *p_pl; - TokenList *tmp_tl, *tl; - - - if ( !(*n) ) { - return; - } - - switch( (*n)->connective ) { - case ALL: - case EX: - /* we need to make a sequence of quantifiers ( ->sons ...) - * out of the given sequence of TypedList elements, - * with connected type names, var - name in TokenList - * and KEEPING THE SAME ORDERING !! - */ - if ( !(*n)->parse_vars ) { - printf("\n\nquantifier without argument !! check input files.\n\n"); - exit( 1 ); - } - tmp_tl = new_TokenList(); - tmp_tl->next = new_TokenList(); - tmp_tl->item = copy_Token( (*n)->parse_vars->name ); - if ( (*n)->parse_vars->type->next ) { - tmp_tl->next->item = new_Token( MAX_LENGTH ); - strcpy( tmp_tl->next->item, EITHER_STR ); - for ( tl = (*n)->parse_vars->type; tl; tl = tl->next ) { - strcat( tmp_tl->next->item, CONNECTOR ); - strcat( tmp_tl->next->item, tl->item ); - } - } else { - tmp_tl->next->item = copy_Token( (*n)->parse_vars->type->item ); - } - (*n)->atom = tmp_tl; - /* now add list of sons - */ - sons = (*n)->sons; - p_pl = *n; - for ( tyl = (*n)->parse_vars->next; tyl; tyl = tyl->next ) { - tmp_tl = new_TokenList(); - tmp_tl->next = new_TokenList(); - tmp_tl->item = copy_Token( tyl->name ); - if ( tyl->type->next ) { - tmp_tl->next->item = new_Token( MAX_LENGTH ); - strcpy( tmp_tl->next->item, EITHER_STR ); - for ( tl = tyl->type; tl; tl = tl->next ) { - strcat( tmp_tl->next->item, CONNECTOR ); - strcat( tmp_tl->next->item, tl->item ); - } - } else { - tmp_tl->next->item = copy_Token( tyl->type->item ); - } - tmp_pl = new_PlNode( (*n)->connective ); - tmp_pl->atom = tmp_tl; - p_pl->sons = tmp_pl; - p_pl = tmp_pl; - } - /* remove typed-list-of info - */ - free_TypedList( (*n)->parse_vars ); - (*n)->parse_vars = NULL; - /* the last son in list takes over ->sons - */ - p_pl->sons = sons; - /* normalize this sons and get out - */ - normalize_tyl_in_pl( &(p_pl->sons) ); - break; - case AND: - case OR: - for ( i = (*n)->sons; i; i = i->next ) { - normalize_tyl_in_pl( &i ); - } - break; - case NOT: - normalize_tyl_in_pl( &((*n)->sons) ); - break; - case ATOM: - case TRU: - case FAL: - break; - case WHEN: - normalize_tyl_in_pl( &((*n)->sons) ); - normalize_tyl_in_pl( &((*n)->sons->next) ); - break; - default: - break; - } - -} - - - - - - - - - - - - -/* ADL syntax test - and normalization (AND s etc.) - */ - - - - - - - - - - - - -Bool make_adl_domain( void ) - -{ - - PlOperator *i; - FactList *ff; - - if ( gcmd_line.display_info == 101 ) { - printf("\noriginal problem parsing is:\n"); - printf("\nobjects:"); - for ( ff = gorig_constant_list; ff; ff = ff->next ) { - printf("\n%s : %s", ff->item->item, ff->item->next->item); - } - printf("\n\ninitial state:\n"); - print_PlNode( gorig_initial_facts, 0 ); - printf("\n\ngoal state:\n"); - print_PlNode( gorig_goal_facts, 0 ); - printf("\n\nops:"); - print_plops( gloaded_ops ); - } - - if ( !make_conjunction_of_atoms( &gorig_initial_facts ) ) { - printf("\nillegal initial state"); - return FALSE; - } - - if ( !gorig_goal_facts ) { - gorig_goal_facts = new_PlNode( TRU ); - } - - if ( !is_wff( gorig_goal_facts ) ) { - printf("\nillegal goal formula"); - print_PlNode( gorig_goal_facts, 0 ); - return FALSE; - } - - for ( i = gloaded_ops; i; i = i->next ) { - if ( !i->preconds ) { - i->preconds = new_PlNode( TRU ); - } - if ( !is_wff( i->preconds ) ) { - printf("\nop %s has illegal precondition", i->name); - return FALSE; - } - if ( !make_effects( &(i->effects) ) ) { - printf("\nop %s has illegal effects", i->name); - return FALSE; - } - } - - if ( gcmd_line.display_info == 102 ) { - printf("\nfinal ADL representation is:\n"); - printf("\nobjects:"); - for ( ff = gorig_constant_list; ff; ff = ff->next ) { - printf("\n%s : %s", ff->item->item, ff->item->next->item); - } - printf("\n\ninitial state:\n"); - print_PlNode( gorig_initial_facts, 0 ); - printf("\n\ngoal formula:\n"); - print_PlNode( gorig_goal_facts, 0 ); - printf("\n\nops:"); - print_plops( gloaded_ops ); - } - - return TRUE; - -} - - - -Bool make_conjunction_of_atoms( PlNode **n ) - -{ - - PlNode *tmp, *i, *p, *m; - - if ( !(*n) ) { - return TRUE; - } - - if ( (*n)->connective != AND ) { - switch ( (*n)->connective ) { - case ATOM: - tmp = new_PlNode( ATOM ); - tmp->atom = (*n)->atom; - (*n)->atom = NULL; - (*n)->connective = AND; - (*n)->sons = tmp; - return TRUE; - case COMP: - tmp = new_PlNode( COMP ); - tmp->comp = (*n)->comp; - tmp->lh = (*n)->lh; - tmp->rh = (*n)->rh; - (*n)->lh = NULL; - (*n)->rh = NULL; - (*n)->comp = -1; - (*n)->connective = AND; - (*n)->sons = tmp; - return TRUE; - case NOT: - free_PlNode( *n ); - (*n) = NULL; - return TRUE; - default: - return FALSE; - } - } - - p = NULL; - i = (*n)->sons; - while ( i ) { - switch ( i->connective ) { - case ATOM: - break; - case COMP: - break; - case NOT: - if ( p ) { - p->next = i->next; - } else { - (*n)->sons = i->next; - } - m = i->next; - i->next = NULL; - free_PlNode( i ); - i = m; - break; - default: - return FALSE; - } - if ( i->connective != NOT ) { - p = i; - i = i->next; - } - } - - return TRUE; - -} - - - -Bool is_wff( PlNode *n ) - -{ - - PlNode *i; - - if ( !n ) { - return FALSE; - } - - switch( n->connective ) { - case ALL: - case EX: - if ( !(n->atom) || - !(n->atom->next ) || - n->atom->next->next != NULL ) { - return FALSE; - } - return is_wff( n->sons ); - case AND: - case OR: - for ( i = n->sons; i; i = i->next ) { - if ( !is_wff( i ) ) { - return FALSE; - } - } - return TRUE; - case NOT: - return is_wff( n->sons ); - case ATOM: - if ( !(n->atom) || - n->sons != NULL ) { - return FALSE; - } - return TRUE; - case TRU: - case FAL: - if ( n->sons != NULL ) { - return FALSE; - } - return TRUE; - case COMP: - if ( n->sons != NULL || - n->atom != NULL || - n->lh == NULL || - n->rh == NULL || - n->comp < 0 ) { - return FALSE; - } - return TRUE; - default: - return FALSE; - } - -} - - - -Bool make_effects( PlNode **n ) - -{ - - PlNode *tmp, *i, *literals, *j, *k, *next; - int m = 0; - - if ( (*n)->connective != AND ) { - if ( !is_eff_literal( *n ) && - (*n)->connective != ALL && - (*n)->connective != WHEN ) { - return FALSE; - } - tmp = new_PlNode( (*n)->connective ); - tmp->atom = (*n)->atom; - tmp->sons = (*n)->sons; - tmp->neft = (*n)->neft; - tmp->lh = (*n)->lh; - tmp->rh = (*n)->rh; - (*n)->connective = AND; - (*n)->sons = tmp; - (*n)->lh = NULL; - (*n)->rh = NULL; - (*n)->neft = -1; - } - - for ( i = (*n)->sons; i; i = i->next ) { - if ( is_eff_literal( i ) ) { - m++; - continue; - } - if ( i->connective == AND ) { - for ( j = i->sons; j; j = j->next ) { - if ( !is_eff_literal( j ) ) { - return FALSE; - } - m++; - } - continue; - } - if ( i->connective == ALL ) { - for ( j = i->sons; j && j->connective == ALL; j = j->sons ) { - if ( !j->atom || - !j->atom->next || - j->atom->next->next != NULL ) { - return FALSE; - } - } - if ( !j ) { - return FALSE; - } - if ( is_eff_literal( j ) ) { - tmp = new_PlNode( AND ); - for ( k = i; k->sons->connective == ALL; k = k->sons ); - k->sons = tmp; - tmp->sons = j; - j = tmp; - } - if ( j->connective == AND ) { - for ( k = j->sons; k; k = k->next ) { - if ( !is_eff_literal( k ) ) { - return FALSE; - } - } - tmp = new_PlNode( WHEN ); - for ( k = i; k->sons->connective == ALL; k = k->sons ); - k->sons = tmp; - tmp->sons = new_PlNode( TRU ); - tmp->sons->next = j; - continue; - } - if ( j->connective != WHEN ) { - return FALSE; - } - if ( !(j->sons) ) { - j->sons = new_PlNode( TRU ); - } - if ( !is_wff( j->sons ) ) { - return FALSE; - } - if ( !make_conjunction_of_literals( &(j->sons->next) ) ) { - return FALSE; - } - continue; - } - if ( i->connective != WHEN ) { - return FALSE; - } - if ( !(i->sons) ) { - i->sons = new_PlNode( TRU ); - } - if ( !is_wff( i->sons ) ) { - return FALSE; - } - if ( !make_conjunction_of_literals( &(i->sons->next) ) ) { - return FALSE; - } - } - - if ( m == 0 ) { - return TRUE; - } - - tmp = new_PlNode( WHEN ); - tmp->sons = new_PlNode( TRU ); - literals = new_PlNode( AND ); - tmp->sons->next = literals; - tmp->next = (*n)->sons; - (*n)->sons = tmp; - i = (*n)->sons; - while ( i->next ) { - if ( is_eff_literal( i->next ) ) { - next = i->next->next; - i->next->next = literals->sons; - literals->sons = i->next; - i->next = next; - continue; - } - if ( i->next->connective == AND ) { - next = i->next->next; - for ( j = i->next->sons; j && j->next; j = j->next ); - if ( j ) { - j->next = literals->sons; - literals->sons = i->next->sons; - } - i->next = next; - continue; - } - i = i->next; - } - return TRUE; - -} - - - -Bool is_eff_literal( PlNode *n ) - -{ - - if ( !n ) { - return FALSE; - } - - if ( n->connective == NOT ) { - if ( !n->sons || - n->sons->connective != ATOM || - !n->sons->atom ) { - return FALSE; - } - return TRUE; - } - - if ( n->connective == ATOM ) { - if ( !n->atom ) { - return FALSE; - } - return TRUE; - } - - if ( n->connective == NEF ) { - if ( !n->lh || - !n->rh || - n->neft < 0 ) { - return FALSE; - } - return TRUE; - } - - return FALSE; - -} - - - -Bool make_conjunction_of_literals( PlNode **n ) - -{ - - PlNode *tmp, *i; - - if ( !(*n) ) { - return FALSE; - } - - if ( (*n)->connective != AND ) { - if ( (*n)->connective == NOT ) { - if ( !((*n)->sons) || - (*n)->sons->connective != ATOM ) { - return FALSE; - } - tmp = new_PlNode( NOT ); - tmp->sons = (*n)->sons; - (*n)->connective = AND; - (*n)->sons = tmp; - return TRUE; - } - if ( (*n)->connective == NEF ) { - tmp = new_PlNode( NEF ); - tmp->neft = (*n)->neft; - tmp->lh = (*n)->lh; - tmp->rh = (*n)->rh; - (*n)->lh = NULL; - (*n)->rh = NULL; - (*n)->neft = -1; - (*n)->connective = AND; - (*n)->sons = tmp; - return TRUE; - } - if ( (*n)->connective != ATOM ) { - return FALSE; - } - tmp = new_PlNode( ATOM ); - tmp->atom = (*n)->atom; - (*n)->atom = NULL; - (*n)->connective = AND; - (*n)->sons = tmp; - return TRUE; - } - - for ( i = (*n)->sons; i; i = i->next ) { - if ( !is_eff_literal( i ) ) { - return FALSE; - } - } - - return TRUE; - -} - - diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.h b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.h deleted file mode 100644 index f9924c08..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/parse.h +++ /dev/null @@ -1,63 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: parse.h - * Description: Functions for the pddl parser - * - * Author: Frank Rittinger 1998 / Joerg Hoffmann 1999 - * - *********************************************************************/ - - - - - -#ifndef _PARSE_H -#define _PARSE_H - - - -char *copy_Token( char *s ); -TokenList *copy_TokenList( TokenList *source ); -void strupcase( char *from ); -char *rmdash( char *s ); - - - -void build_orig_constant_list( void ); -void collect_type_names_in_pl( PlNode *n ); -int get_type( char *str ); -void make_either_ty( TypedList *tyl ); -void make_either_ty_in_pl( PlNode *n ); -void normalize_tyl_in_pl( PlNode **n ); - - - -Bool make_adl_domain( void ); -Bool make_conjunction_of_atoms( PlNode **n ); -Bool is_wff( PlNode *n ); -Bool make_effects( PlNode **n ); -Bool is_eff_literal( PlNode *n ); -Bool make_conjunction_of_literals( PlNode **n ); - - - -#endif /* PARSE */ diff --git a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/relax.c b/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/relax.c deleted file mode 100644 index dd657ac6..00000000 --- a/agent_system/environments/env_package/alfworld/alfworld/gen/ff_planner/relax.c +++ /dev/null @@ -1,2756 +0,0 @@ - -/********************************************************************* - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * as published by the Free Software Foundation; either version 2 - * of the License, or (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. - * - *********************************************************************/ - - -/********************************************************************* - * File: relax.c - * Description: this file handles the relaxed planning problem, i.e., - * the code is responsible for the heuristic evaluation - * of states during search. - * - * --- THE HEART PEACE OF THE FF PLANNER ! --- - * - * here: linear tasks +=,-=,:= / le / le le - * - * - * Author: Joerg Hoffmann 2000--2002, 2011 - * - *********************************************************************/ - - - - - - - - - -#include "ff.h" - -#include "output.h" -#include "memory.h" - -#include "expressions.h" - -#include "relax.h" -#include "search.h" - - - - - - - -/* local globals - */ - - - - - - - - -/* fixpoint - */ -int *lF; -int lnum_F; -int *lE; -int lnum_E; - -int *lch_E; -int lnum_ch_E; - -int *l0P_E; -int lnum_0P_E; - - - - - -/* 1P extraction - */ -int **lgoals_at; -int *lnum_goals_at; - -float **lf_goals_c_at; -Comparator **lf_goals_comp_at; - -int lh; - -int *lch_F; -int lnum_ch_F; - -int *lused_O; -int lnum_used_O; - -int *lin_plan_E; -int lnum_in_plan_E; - - -/* helpful actions numerical helpers - */ -Comparator *lHcomp; -float *lHc; - - - - - - - - - - - - - - - - - - - - -/************************************* - * helper, for -1 == INFINITY method * - *************************************/ - - - - - - - - - - - - -Bool LESS( int a, int b ) - -{ - - if ( a == INFINITY ) { - return FALSE; - } - - if ( b == INFINITY ) { - return TRUE; - } - - return ( a < b ? TRUE : FALSE ); - -} - - - -Bool FLOAT_LE( float a, float b ) - -{ - - if ( b == INFINITY ) { - return TRUE; - } - - if ( a == INFINITY ) { - return FALSE; - } - - return ( a <= b ? TRUE : FALSE ); - -} - - - - - - - - - - - - - - -/*********************************** - * FUNCTIONS ACCESSED FROM OUTSIDE * - ***********************************/ - - - - - - - - - - - - - - - - - -int get_1P( State *S ) - -{ - - int max, h; - Bool solvable; - - gevaluated_states++; - - solvable = build_fixpoint( S, &max ); - - if ( gcmd_line.display_info == 126 ) { - print_fixpoint_result(); - } - - if ( solvable ) { - h = extract_1P( max ); - } else { - h = INFINITY; - } - - reset_fixpoint( max ); - - return h; - -} - - - -int get_1P_and_H( State *S ) - -{ - - int max, h; - Bool solvable; - - gevaluated_states++; - - solvable = build_fixpoint( S, &max ); - - if ( gcmd_line.display_info == 126 ) { - print_fixpoint_result(); - } - - if ( solvable ) { - h = extract_1P( max ); - collect_H_info(); - } else { - h = INFINITY; - } - - reset_fixpoint( max ); - - return h; - -} - - - -int get_1P_and_A( State *S ) - -{ - - int max, h; - Bool solvable; - - gevaluated_states++; - - solvable = build_fixpoint( S, &max ); - - if ( gcmd_line.display_info == 126 ) { - print_fixpoint_result(); - } - - if ( solvable ) { - h = extract_1P( max ); - } else { - h = INFINITY; - } - - collect_1P_and_A_info(); - reset_fixpoint( max ); - - return h; - -} - - - -void collect_1P_and_A_info( void ) - -{ - - static Bool first_call = TRUE; - - int i; - - if ( first_call ) { - gA = ( int * ) calloc( gnum_op_conn, sizeof( int ) ); - gnum_A = 0; - first_call = FALSE; - } - - if ( gcmd_line.debug ) { - printf("\ncollect_1P_and_A_info"); - } - - for ( i = 0; i < gnum_A; i++ ) { - gop_conn[gA[i]].is_in_A = FALSE; - } - gnum_A = 0; - - for ( i = 0; i < lnum_E; i++ ) { - if ( gef_conn[lE[i]].level != 0 ) break; - if ( gcmd_line.debug ) { - printf("\ngot applicable op: "); - print_op_name(gef_conn[lE[i]].op); - } - if ( gop_conn[gef_conn[lE[i]].op].is_in_A ) { - if ( gcmd_line.debug ) { - printf(" -- already in, skipping it!"); - } - continue; - } - if ( gop_conn[gef_conn[lE[i]].op].axiom ) { - if ( gcmd_line.debug ) { - printf(" -- axiom, skipping it!"); - } - continue; - } - if ( gcmd_line.debug ) { - printf(" -- adding it!"); - } - gop_conn[gef_conn[lE[i]].op].is_in_A = TRUE; - gA[gnum_A++] = gef_conn[lE[i]].op; - } - -} - - - -void get_A( State *S ) - -{ - - int i; - - initialize_fixpoint( S ); - - for ( i = 0; i < lnum_F; i++ ) { - activate_ft( lF[i], 0 ); - } - for ( i = 0; i < lnum_0P_E; i++ ) { - if ( gef_conn[l0P_E[i]].in_E ) { - continue; - } - new_ef( l0P_E[i] ); - } - for ( i = 0; i < gnum_fl_conn; i++ ) { - activate_fl( i, 0 ); - } - - collect_A_info(); - - /* 0 should be enough here... - */ - reset_fixpoint( 1 ); - -} - - - -void collect_A_info( void ) - -{ - - static Bool first_call = TRUE; - - int i; - - if ( first_call ) { - gA = ( int * ) calloc( gnum_op_conn, sizeof( int ) ); - gnum_A = 0; - first_call = FALSE; - } - - if ( gcmd_line.debug ) { - printf("\ncollect_A_info"); - } - - for ( i = 0; i < gnum_A; i++ ) { - gop_conn[gA[i]].is_in_A = FALSE; - } - gnum_A = 0; - - for ( i = 0; i < lnum_E; i++ ) { - /* levels are not set unless we actually build the RPG! -/* if ( gef_conn[lE[i]].level != 0 ) break; */ - if ( gcmd_line.debug ) { - printf("\ngot applicable op: "); - print_op_name(gef_conn[lE[i]].op); - } - if ( gop_conn[gef_conn[lE[i]].op].is_in_A ) { - if ( gcmd_line.debug ) { - printf(" -- already in, skipping it!"); - } - continue; - } - if ( gop_conn[gef_conn[lE[i]].op].axiom ) { - if ( gcmd_line.debug ) { - printf(" -- axiom, skipping it!"); - } - continue; - } - if ( gcmd_line.debug ) { - printf(" -- adding it!"); - } - gop_conn[gef_conn[lE[i]].op].is_in_A = TRUE; - gA[gnum_A++] = gef_conn[lE[i]].op; - } - -} - - - -void get_A_axioms( State *S ) - -{ - - int i; - - initialize_fixpoint( S ); - - for ( i = 0; i < lnum_F; i++ ) { - activate_ft( lF[i], 0 ); - } - for ( i = 0; i < lnum_0P_E; i++ ) { - if ( gef_conn[l0P_E[i]].in_E ) { - continue; - } - new_ef( l0P_E[i] ); - } - for ( i = 0; i < gnum_fl_conn; i++ ) { - activate_fl( i, 0 ); - } - - collect_A_axioms_info(); - - /* 0 should be enough here... - */ - reset_fixpoint( 1 ); - -} - - - -void collect_A_axioms_info( void ) - -{ - - static Bool first_call = TRUE; - - int i; - - if ( first_call ) { - gA_axioms = ( int * ) calloc( gnum_op_conn, sizeof( int ) ); - gnum_A_axioms = 0; - first_call = FALSE; - } - - if ( gcmd_line.debug ) { - printf("\ncollect_A_axioms_info"); - } - - for ( i = 0; i < gnum_A_axioms; i++ ) { - gop_conn[gA_axioms[i]].is_in_A_axioms = FALSE; - } - gnum_A_axioms = 0; - - for ( i = 0; i < lnum_E; i++ ) { - /* levels are not set unless we actually build the RPG! -/* if ( gef_conn[lE[i]].level != 0 ) break; */ - if ( gcmd_line.debug ) { - printf("\ngot applicable op: "); - print_op_name(gef_conn[lE[i]].op); - } - if ( gop_conn[gef_conn[lE[i]].op].is_in_A_axioms ) { - if ( gcmd_line.debug ) { - printf(" -- already in, skipping it!"); - } - continue; - } - if ( !gop_conn[gef_conn[lE[i]].op].axiom ) { - if ( gcmd_line.debug ) { - printf(" -- no axiom, skipping it!"); - } - continue; - } - if ( gcmd_line.debug ) { - printf(" -- adding it!"); - } - - gop_conn[gef_conn[lE[i]].op].is_in_A_axioms = TRUE; - gA_axioms[gnum_A_axioms++] = gef_conn[lE[i]].op; - } - -} - - - - - - - - - - - - - - - - - - - - - - - - - - - -/******************************* - * RELAXED FIXPOINT ON A STATE * - *******************************/ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -Bool build_fixpoint( State *S, int *max ) - -{ - - int start_ft, stop_ft, start_ef, stop_ef, i, time = 0; - float costlevel; - - initialize_fixpoint( S ); - - start_ft = 0; - start_ef = 0; - while ( TRUE ) { - if ( gcmd_line.debug ) { - printf("\n======================================FP time %d", time); - } - - if ( all_goals_activated( time ) ) { - break; - } - if ( time > 0 || lnum_0P_E == 0 ) { - if ( start_ft == lnum_F ) { - if ( fluents_hopeless( time ) ) { - /* fixpoint, goals not reached - */ - *max = time; - return FALSE; - } - } - } - /* make space if necessary, and copy over - * info from time to time+1 for fluents - */ - extend_fluent_levels( time ); - for ( i = 0; i < gnum_fl_conn; i++ ) { - if ( gfl_conn[i].def[time] ) { - gfl_conn[i].def[time+1] = TRUE; - gfl_conn[i].level[time+1] = gfl_conn[i].level[time]; - } - } - - /* determine the next effect layer: - * - activate the facts - * - if level 0 activate the no preconds-ops - * - activate the fluents at their