-
Notifications
You must be signed in to change notification settings - Fork 4
/
dataset_generator.py
3534 lines (3016 loc) · 126 KB
/
dataset_generator.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from typing import Iterable
import abc
from collections import Counter, defaultdict
import itertools
import random
import re
import sqlite3
import yaml
import jinja2 as jinja
from pddl.core import Problem
from pddl import formatter as pddl_formatter
from pddl.core import And, Constant, Domain, Predicate
from pddl.parser import domain as domain_parser
from planetarium import DOMAINS
import tqdm
SPLITS = None
def int_to_ordinal(number):
"""Converts an integer to its ordinal string representation (e.g., 1 -> 'first', 2 -> 'second').
Args:
number: The integer to convert.
Returns:
The ordinal string representation of the number, or None if the number is outside the range 1-20.
"""
ordinals = [
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth",
"thirteenth",
"fourteenth",
"fifteenth",
"sixteenth",
"seventeenth",
"eighteenth",
"nineteenth",
"twentieth",
"twenty-first",
"twenty-second",
"twenty-third",
"twenty-fourth",
"twenty-fifth",
"twenty-sixth",
"twenty-seventh",
"twenty-eighth",
"twenty-ninth",
"thirtieth",
]
if 1 <= number <= 30:
return ordinals[number - 1]
else:
raise ValueError(f"Number {number} is outside the range 1-20")
class DatasetGenerator(abc.ABC):
def __init__(self, domain: str, predicate_template: str = ""):
self.domain: Domain = domain_parser.DomainParser()(DOMAINS[domain])
# Remove leading whitespace from each line
self.predicate_template = jinja.Template(
re.sub(r"^\s+", "", predicate_template, flags=re.MULTILINE)
)
def explicit_description(
self,
predicates: list[Predicate],
is_init: bool = True,
randomize: bool = True,
**kwargs,
) -> str:
"""Generate an explicit description of the state.
Args:
predicates (list[Predicate]): List of predicates.
is_init (bool, optional): Whether the description is for the initial
state. Defaults to True.
**kwargs: Additional keyword arguments.
Returns:
str: State description.
"""
if randomize:
random.shuffle(predicates)
return self.predicate_template.render(
predicates=predicates,
is_init=is_init,
**kwargs,
).strip()
@abc.abstractmethod
def abstract_description(
self,
task: str,
is_init: bool = False,
**kwargs,
) -> str:
"""Generate an abstract description of the state.
Args:
task (str): The task to describe.
is_init (bool, optional): Whether the description is for the initial
state. Defaults to False.
Raises:
ValueError: If the task is invalid/unsupported, or if the number of
blocks is invalid.
Returns:
str: State description.
"""
@abc.abstractmethod
def get_task(
self,
init: str,
goal: str,
*args,
) -> tuple[Problem, dict[str, dict[str, str]], dict[str, int | float | str]]:
"""Generate a task.
Args:
init (str): Initial state setting type.
goal (str): Goal state setting type.
Returns:
tuple[Problem, dict[str, dict[str, str]]]: PDDL problem,
descriptions, and data.
"""
raise NotImplementedError
class BlocksworldDatasetGenerator(DatasetGenerator):
def __init__(self):
super().__init__(
"blocksworld",
"""
{%- set tense = "is" if is_init else "should be" -%}
{%- set arm_tense = "are" if is_init else "should be" -%}
{%- if is_init -%}
You have {{ num_blocks }} blocks.
{%- else -%}
Your goal is to have the following:
{%- endif -%}
{%- for predicate in predicates -%}
{%- if predicate.name == "clear" %}
{{ predicate.terms[0].name }} {{ tense }} {{ predicate.name }}.
{%- elif predicate.name == "on-table" %}
{{ predicate.terms[0].name }} {{ tense }} on the table.
{%- elif predicate.name == "arm-empty" %}
Your arm {{ tense }} empty.
{%- elif predicate.name == "holding" %}
You {{ arm_tense }} holding {{ predicate.terms[0].name }}.
{%- elif predicate.name == "on" %}
{{ predicate.terms[0].name }} {{ tense }} on {{ predicate.terms[1].name }}.
{%- endif -%}
{%- endfor -%}
""",
)
def stack(
self,
blocks: list[Constant],
blocks_list: list[int] | None,
goal: bool = False,
) -> list[Predicate]:
predicates = [Predicate("arm-empty")]
for i in range(1, len(blocks)):
predicates.append(
Predicate(
"on",
blocks[i],
blocks[i - 1],
)
)
predicates.append(Predicate("clear", blocks[-1]))
predicates.append(Predicate("on-table", blocks[0]))
return predicates
def on_table(
self,
blocks: list[Constant],
blocks_list: list[int] | None,
goal: bool = False,
) -> list[Predicate]:
predicates = [Predicate("arm-empty")]
for block in blocks:
predicates.append(Predicate("clear", block))
predicates.append(Predicate("on-table", block))
return predicates
def holding_one(
self,
blocks: list[Constant],
blocks_list: list[int],
goal: bool = False,
) -> list[Predicate]:
predicates = [Predicate("holding", blocks[0])]
for block in blocks[1:]:
predicates.append(Predicate("clear", block))
predicates.append(Predicate("on-table", block))
return predicates
def _staircase_num_steps(self, num_blocks: int) -> int:
num_steps: float = (2 * num_blocks + 0.25) ** 0.5 - 0.5
if not num_steps.is_integer():
raise ValueError(f"Invalid number of blocks for staircase: {num_blocks}")
return int(num_steps)
def staircase(
self,
blocks: list[Constant],
blocks_list: list[int] | None,
goal: bool = False,
) -> list[Predicate]:
predicates = [Predicate("arm-empty")]
idx = 0
steps = self._staircase_num_steps(len(blocks))
total = sum(range(steps + 1))
assert len(blocks) == total
for i in range(steps):
predicates.append(Predicate("clear", blocks[idx]))
for _ in range(i):
idx += 1
predicates.append(Predicate("on", blocks[idx - 1], blocks[idx]))
predicates.append(Predicate("on-table", blocks[idx]))
idx += 1
return predicates
def _equal_towers(self, num_blocks: int | list[int]) -> list[int]:
def _get_height(num_blocks) -> list[int]:
heights = [5, 4, 3, 2, 1]
for height in heights:
if num_blocks % height == 0:
tower_heights = [height] * (num_blocks // height)
return tower_heights
return num_blocks
if isinstance(num_blocks, int):
tower_heights = _get_height(num_blocks)
elif isinstance(num_blocks, list) and len(num_blocks) == 1:
tower_heights = _get_height(num_blocks[0])
elif isinstance(num_blocks, list) and any(
n != num_blocks[0] for n in num_blocks
):
tower_heights = _get_height(sum(num_blocks))
else:
raise ValueError("Invalid number of blocks for equal towers")
return tower_heights
def equal_towers(
self,
blocks: list[Constant],
blocks_list: list[int] | None,
goal: bool = False,
) -> list[Predicate]:
tower_heights = self._equal_towers(blocks_list or len(blocks))
assert sum(tower_heights) > 0, "Invalid number of blocks for equal towers"
predicates = [Predicate("arm-empty")]
blocks_iter = iter(blocks)
for _ in range(len(tower_heights)):
block = next(blocks_iter)
predicates.append(Predicate("on-table", block))
for _ in range(tower_heights[0] - 1):
next_block = next(blocks_iter)
predicates.append(Predicate("on", next_block, block))
block = next_block
predicates.append(Predicate("clear", block))
return predicates
def swap(
self,
blocks: list[Constant],
blocks_list: list[int],
goal: bool = False,
) -> list[Predicate]:
if len(blocks_list) != 2 or blocks_list[0] < 2 or blocks_list[1] < 2:
raise ValueError("Swap requires two towers with at least 2 blocks each")
new_blocks = blocks
if goal:
new_blocks[0], new_blocks[1] = new_blocks[1], new_blocks[0]
predicates = [Predicate("arm-empty")]
predicates.append(Predicate("on-table", blocks[0]))
predicates.append(Predicate("on-table", blocks[1]))
blocks_iter = iter(blocks[2:])
for i, num in enumerate(blocks_list):
block = blocks[i]
for _ in range(num - 1):
next_block = next(blocks_iter)
predicates.append(Predicate("on", next_block, block))
block = next_block
predicates.append(Predicate("clear", block))
return predicates
def invert(
self,
blocks: list[Constant],
blocks_list: list[int],
goal: bool = False,
) -> list[Predicate]:
blocks_list = blocks_list or [sum(blocks)]
if len(blocks) != sum(blocks_list):
raise ValueError("Number of blocks does not match the sum of block counts")
if goal:
blocks = blocks[::-1]
blocks_list = blocks_list[::-1]
predicates = [Predicate("arm-empty")]
idx = 0
for tower_height in blocks_list:
predicates.append(Predicate("clear", blocks[idx]))
for _ in range(tower_height - 1):
idx += 1
predicates.append(Predicate("on", blocks[idx - 1], blocks[idx]))
predicates.append(Predicate("on-table", blocks[idx]))
idx += 1
return predicates
def tower(
self,
blocks: list[Constant],
blocks_list: list[int],
goal: bool = False,
) -> list[Predicate]:
blocks_list = blocks_list or [sum(blocks)]
if len(blocks) != sum(blocks_list):
raise ValueError("Number of blocks does not match the sum of block counts")
predicates = [Predicate("arm-empty")]
idx = 0
for tower_height in blocks_list:
predicates.append(Predicate("clear", blocks[idx]))
for _ in range(tower_height - 1):
idx += 1
predicates.append(Predicate("on", blocks[idx - 1], blocks[idx]))
predicates.append(Predicate("on-table", blocks[idx]))
idx += 1
return predicates
def abstract_description(
self,
task: str,
blocks_list: list[int],
is_init: bool = False,
) -> str:
"""Generate an abstract description of the state.
Args:
task (str): The task to describe.
num_blocks (int | list[int]): Number of blocks in the scene.
is_init (bool, optional): Whether the description is for the initial
state. Defaults to False.
Raises:
ValueError: If the task is invalid/unsupported, or if the number of
blocks is invalid.
Returns:
str: State description.
"""
num_blocks = sum(blocks_list)
match task, is_init:
case ("on_table", True):
return f"You have {num_blocks} blocks, each laying directly on the table, and your arm is empty."
case ("on_table", False):
return "Your goal is to unstack the blocks into individual blocks on the table."
case ("stack", False):
return "Your goal is to stack the blocks into a single stack."
case ("stack", True):
return f"You have {num_blocks} blocks, b1 through b{num_blocks}, stacked on top of each other, and your arm is empty."
case ("holding_one", True):
return f"You have {num_blocks} blocks. You are holding one block, and the rest are on the table."
case ("holding_one", False):
return f"You have {num_blocks} blocks, b1 through b{num_blocks}. Your goal is to unstack the blocks into individual blocks on the table, and to hold one of the blocks."
case ("staircase", True):
num_steps = self._staircase_num_steps(num_blocks)
return f"You have {num_blocks} blocks, b1 through b{num_blocks}, stacked into {num_steps} stacks of increasing heights, starting with a stack of height 1."
case ("staircase", False):
num_steps = self._staircase_num_steps(num_blocks)
return f"Your goal is to stack the blocks into {num_steps} stacks of increasing heights, starting with a stack of height 1."
case ("equal_towers", True):
num_blocks = self._equal_towers(blocks_list)
return f"You have {sum(num_blocks)} blocks, b1 through b{sum(num_blocks)}, stacked into {len(blocks_list)} towers of equal heights, and your arm is empty."
case ("equal_towers", False):
num_blocks = self._equal_towers(blocks_list)
return f"Your goal is to stack the blocks into {len(blocks_list)} towers of equal heights."
case ("swap", True):
return f"You have {num_blocks} blocks, b1 through b{num_blocks} in two towers with {blocks_list[0]} blocks in one and {blocks_list[1]} blocks in the other, and your arm is empty."
case ("swap", False):
return f"Your goal is to swap all blocks except the bottom blocks from one tower to the other."
case ("invert", True):
return f"You have {num_blocks} blocks, stacked into {len(blocks_list)} towers of heights {', '.join(str(h) for h in blocks_list)}, and your arm is empty."
case ("invert", False):
return f"Your goal is to invert each individual stack of blocks, such that the block that in each tower that was originally on the bottom will be on the top."
case ("tower", True):
return f"You have {num_blocks} blocks, stacked into {len(blocks_list)} towers of heights {', '.join(str(h) for h in blocks_list)}, and your arm is empty."
case ("tower", False):
return f"Your goal is to stack the blocks into a towers of heights {', '.join(str(h) for h in blocks_list)}."
case _:
raise ValueError(f"Invalid task: {task}")
def get_task(
self,
init: str,
goal: str,
blocks_list: list[int],
randomize: bool = True,
) -> tuple[Problem, dict[str, dict[str, str]], dict[str, str]]:
"""Generate a blocksworld task.
Args:
init (str): Initial state setting type.
goal (str): Goal state setting type.
*args: Additional arguments for the task.
randomize (bool, optional): Whether to randomize the order of the
blocks. Defaults to True.
Returns:
tuple[Problem, dict[str, dict[str, str]]]: PDDL problem,
descriptions, and data.
"""
blocks_list_str = "_".join(str(arg) for arg in blocks_list)
num_blocks = sum(blocks_list)
constants = [Constant(f"b{i + 1}") for i in range(num_blocks)]
init_predicates = getattr(self, init)(
constants,
blocks_list=blocks_list,
goal=False,
)
goal_predicates = getattr(self, goal)(
constants,
blocks_list=blocks_list,
goal=True,
)
problem = Problem(
name=f"{init}_to_{goal}_{blocks_list_str}",
domain=self.domain,
objects=constants,
init=init_predicates,
goal=And(*goal_predicates),
)
descriptions = {
"init": {
"abstract": self.abstract_description(
init,
blocks_list=blocks_list,
is_init=True,
),
"explicit": self.explicit_description(
init_predicates,
is_init=True,
randomize=randomize,
num_blocks=num_blocks,
),
},
"goal": {
"abstract": self.abstract_description(
goal,
blocks_list=blocks_list,
is_init=False,
),
"explicit": self.explicit_description(
goal_predicates,
is_init=False,
randomize=randomize,
num_blocks=num_blocks,
),
},
}
data = {
"num_objects": len(constants),
"init_num_propositions": len(init_predicates),
"goal_num_propositions": len(goal_predicates),
}
return problem, descriptions, data
class GripperDatasetGenerator(DatasetGenerator):
def __init__(self):
super().__init__(
"gripper",
"""
{%- set tense = "is" if is_init else "should be" -%}
{%- if is_init -%}
You have {{ n_rooms }} rooms.
You have {{ n_balls }} balls.
You have {{ n_grippers }} grippers.
{%- else -%}
Your goal is to have the following:
{%- endif -%}
{%- for predicate in predicates -%}
{%- if predicate.name == "free" %}
{{ predicate.terms[0].name }} {{ tense }} {{ predicate.name }}.
{%- elif predicate.name == "at-robby" %}
{{ predicate.terms[0].name }} {{ tense }} on the table.
{%- elif predicate.name == "holding" %}
You {{ arm_tense }} holding {{ predicate.terms[0].name }}.
{%- elif predicate.name == "at" %}
{{ predicate.terms[0].name }} {{ tense }} at {{ predicate.terms[1].name }}.
{%- elif predicate.name == "carry" %}
Gripper {{ predicate.terms[1].name }} {{ tense }} carrying {{ predicate.terms[0].name }}.
{%- endif -%}
{%- endfor -%}""",
)
def _apply_typing(self, objects: list[Constant], typing: str) -> list[Predicate]:
"""Apply typing to a list of objects.
Args:
objects (list[Constant]): List of objects.
typing (str): The type of the objects.
Returns:
list[Predicate]: List of typing predicates.
"""
return [Predicate(typing, obj) for obj in objects]
def one_room(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
*_,
**kwargs,
) -> list[Predicate]:
"""Task where all balls are in a single room.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
Returns:
list[Predicate]: List of predicates describing the state.
"""
predicates = [Predicate("free", gripper) for gripper in grippers]
predicates += [Predicate("at", ball, rooms[0]) for ball in balls]
return predicates
def n_room_distributed(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_grippers: list[int],
balls_in_rooms: list[int],
*_,
**kwargs,
) -> list[Predicate]:
"""Task where balls are distributed across rooms.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
balls_count (list[int]): List of ball counts per room.
Returns:
list[Predicate]: List of predicates describing the state.
"""
if sum(balls_in_grippers) != 0:
raise ValueError("Grippers should not hold any balls in this task")
predicates = [Predicate("free", gripper) for gripper in grippers]
iter_balls = iter(balls)
for room, num_balls in zip(rooms, balls_in_rooms):
for _ in range(num_balls):
predicates.append(Predicate("at", next(iter_balls), room))
return predicates
def focus_max(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_rooms: list[int],
*_,
goal: bool = False,
**kwargs,
) -> list[Predicate]:
"""Bring all balls to the room with the most balls.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
balls_count (list[int]): List of ball counts per room.
Returns:
list[Predicate]: List of predicates describing the state.
Raises:
ValueError: If the max number of balls in a room is not unique.
ValueError: If there are less than 2 rooms or 2 balls.
ValueError: If this is not a goal.
"""
if len(balls_in_rooms) < 2 or sum(balls_in_rooms) < 2:
raise ValueError("Focus max requires at least 2 rooms and 2 balls")
if not goal:
raise ValueError("Focus max requires a goal state")
# find maximum and its frequency
max_balls = max(balls_in_rooms)
counts = Counter(balls_in_rooms)
if counts[max_balls] > 1:
raise ValueError("Focus max requires unique max number of balls in a room")
predicates = [Predicate("free", gripper) for gripper in grippers]
max_room = rooms[balls_in_rooms.index(max_balls)]
for ball in balls:
predicates.append(Predicate("at", ball, max_room))
return predicates
def focus_min(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_rooms: list[int],
*_,
goal: bool = False,
**kwargs,
) -> list[Predicate]:
"""Bring all balls to the room with the minimum number of balls.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
balls_count (list[int]): List of ball counts per room.
Returns:
list[Predicate]: List of predicates describing the state.
Raises:
ValueError: If the min number of balls in a room is not unique.
ValueError: If there are less than 2 rooms or 2 balls.
ValueError: If this is not a goal.
"""
if len(balls_in_rooms) < 2 or sum(balls_in_rooms) < 2:
raise ValueError("Focus min requires at least 2 rooms and 2 balls")
if not goal:
raise ValueError("Focus min requires a goal state")
# find maximum and its frequency
min_balls = min(balls_in_rooms)
counts = Counter(balls_in_rooms)
if counts[min_balls] > 1:
raise ValueError("Focus min requires unique min number of balls in a room")
predicates = [Predicate("free", gripper) for gripper in grippers]
min_room = rooms[balls_in_rooms.index(min_balls)]
for ball in balls:
predicates.append(Predicate("at", ball, min_room))
return predicates
def evenly_distributed(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
*_,
**kwargs,
) -> list[Predicate]:
"""Task where balls are evenly distributed across rooms.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
Returns:
list[Predicate]: List of predicates describing the state.
Raises:
ValueError: If the number of balls is not divisible by the number of
rooms.
"""
if len(balls) % len(rooms) != 0:
raise ValueError("Number of balls must be divisible by the number of rooms")
predicates = [Predicate("free", gripper) for gripper in grippers]
for i, room in enumerate(rooms):
for ball in balls[i :: len(rooms)]:
predicates.append(Predicate("at", ball, room))
return predicates
def swap(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
goal: bool = False,
**_,
) -> list[Predicate]:
"""Task where balls are swapped between rooms.
Args:
rooms (list[Constant]): List of all available rooms.
balls (list[Constant]): List of all balls.
grippers (list[Constant]): List of all grippers.
goal (bool, optional): Whether to return goal state. Defaults to False.
Returns:
list[Predicate]: List of predicates describing the state.
"""
if len(rooms) != 2:
raise ValueError("Swap requires exactly 2 rooms")
if len(balls) % 2 != 0:
raise ValueError("Swap requires an even number of balls")
if goal:
balls = balls[::-1]
predicates = [Predicate("free", gripper) for gripper in grippers]
for i, room in enumerate(rooms):
for ball in balls[i::2]:
predicates.append(Predicate("at", ball, room))
return predicates
def juggle(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_grippers: list[int],
balls_in_rooms: list[int],
goal: bool = False,
) -> list[Predicate]:
# only first room can have balls
if sum(balls_in_rooms[1:]) != 0:
raise ValueError("Juggle requires all balls to be in the first room")
used_grippers = [i for i, v in enumerate(balls_in_grippers) if v > 0]
if len(used_grippers) < 2:
raise ValueError("Juggle requires at least 2 grippers with balls")
held_balls = balls[: len(used_grippers)]
if goal:
# rotate by 1
held_balls = held_balls[1:] + held_balls[:1]
predicates = []
for i, gripper in enumerate(grippers):
if i in used_grippers:
predicates.append(Predicate("carry", held_balls[i], gripper))
else:
predicates.append(Predicate("free", gripper))
for ball in balls[len(used_grippers) :]:
predicates.append(Predicate("at", ball, rooms[0]))
return predicates
def pickup(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_grippers: list[int],
balls_in_rooms: list[int],
goal: bool = True,
) -> list[Predicate]:
assert goal
if len(balls) > len(grippers):
raise ValueError("Not enough grippers to hold all balls")
# NOTE: since we do not define any specific test cases for this task,
# all the variables for balls_in_grippres and balls_in_rooms come from
# the initial scene
held_balls = balls[: sum(balls_in_grippers)]
free_balls = balls[sum(balls_in_grippers) :]
used_grippers = [grippers[i] for i, v in enumerate(balls_in_grippers) if v > 0]
free_grippers = set(grippers) - set(used_grippers)
predicates = []
for gripper, ball in zip(used_grippers, held_balls):
predicates.append(Predicate("carry", ball, gripper))
for gripper, ball in zip(free_grippers, free_balls):
predicates.append(Predicate("carry", ball, gripper))
return predicates
def drop_and_pickup(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_grippers: list[int],
balls_in_rooms: list[int],
goal: bool = True,
) -> list[Predicate]:
assert goal
# NOTE: since we do not define any specific test cases for this task,
# all the variables for balls_in_grippres and balls_in_rooms come from
# the initial scene
if len(rooms) < 2:
raise ValueError("Drop and pickup requires at least 2 rooms")
if not any([b == 0 for b in balls_in_rooms[1:]]):
pass
if sum(balls_in_rooms) > len(grippers):
raise ValueError("Not enough grippers to hold all balls")
room_idx = balls_in_rooms[1:].index(0) + 1
free_room = rooms[room_idx]
held_balls = balls[: sum(balls_in_grippers)]
free_balls = balls[sum(balls_in_grippers) :]
assert len(free_balls) == sum(balls_in_rooms)
# drop all balls into free room
predicates = []
for ball in held_balls:
predicates.append(Predicate("at", ball, free_room))
for gripper, ball in zip(grippers, free_balls):
predicates.append(Predicate("carry", ball, gripper))
return predicates
def holding(
self,
rooms: list[Constant],
balls: list[Constant],
grippers: list[Constant],
balls_in_grippers: list[int],
balls_in_rooms: list[int],
goal: bool = False,
) -> list[Predicate]:
if not (len(grippers) and len(balls)):
raise ValueError("Holding requires at least one gripper and one ball")
held_balls = balls[: sum(balls_in_grippers)]
free_balls = balls[sum(balls_in_grippers) :]
predicates = []
for gripper, ball in zip(grippers, held_balls):
predicates.append(Predicate("carry", ball, gripper))
# free any additional grippers
for gripper in grippers[len(held_balls) :]:
predicates.append(Predicate("free", gripper))
# NOTE: we will ignore the balls in rooms argument for holding if this
# is a goal state
if not goal:
# place free balls according to balls_in_rooms
balls_iter = iter(free_balls)
for room_idx, num_balls in enumerate(balls_in_rooms):
room = rooms[room_idx]
for _ in range(num_balls):
predicates.append(Predicate("at", next(balls_iter), room))
return predicates
def abstract_description(
self,
task: str,
n_rooms: int,
n_balls: int,
n_grippers: int,
balls_in_grippers: list[int],
balls_in_rooms: list[int],
is_init: bool = False,
) -> str:
"""Generate an abstract description of the state.
Args:
task (str): The task to describe.
n_rooms (int): Number of rooms.
balls (list[int]): List of ball counts.
n_grippers (int, optional): Number of grippers. Defaults to 2.
is_init (bool, optional): Whether the description is for the initial
state. Defaults to False.
Raises:
ValueError: If the task is invalid/unsupported, or if the number of
blocks is invalid.
Returns:
str: State description.
"""
objects = (
f"You have {n_rooms} rooms, {n_balls} balls, and {n_grippers} grippers"
)
def n_room_distributed() -> str:
ball_counter = Counter(balls_in_rooms)
balls_per_room = ""
for i, (count, room) in enumerate(ball_counter.items()):
room_s = "s" if room > 1 else ""
count_s = "s" if count > 1 else ""
if i == len(ball_counter) - 1:
if len(ball_counter) > 1:
balls_per_room += "and "
balls_per_room += f"{room} room{room_s} with {count} ball{count_s}."
else:
balls_per_room += (
f"{room} room{room_s} with {count} ball{count_s}, "
)
return balls_per_room
match task, is_init:
case ("one_room", True):
return f"{objects}. All the balls are in the first room, and the grippers are free. The robby is in the first room."
case ("one_room", False):
return "Your goal is to gather all balls into one room."
case ("evenly_distributed", True):
return f"{objects}. The balls are equally distributed across the rooms, and the grippers are free. The robby is in the first room."
case ("evenly_distributed", False):
return "Your goal is to distribute the balls equally across the rooms."
case ("n_room_distributed", True):
return f"{objects}. You have {n_room_distributed()}. The grippers are free. The robby is in the first room."
case ("n_room_distributed", False):
return f"Your goal is to have {n_room_distributed()}"
case ("swap", True):
return f"{objects}. The balls are split evenly between both rooms, and the grippers are free. The robby is in the first room."
case ("swap", False):
return "Your goal is to swap the location of the balls between the two rooms."
case ("focus_max", False):
return "Your goal is to bring all the balls into the room which already has the most balls."
case ("focus_min", False):
return "Your goal is to bring all the balls into the room which already has the least balls."
case ("juggle", True):
return f"{objects}. {sum(balls_in_grippers)} balls are distributed across the same number of grippers, and the rest are in the first room. The robby is in the first room."
case ("juggle", False):
return 'Your goal is to "juggle" the balls between the grippers that started with balls, such that the balls are in the same grippers as before, but shifted by one. The remaining balls should remain untouched.'
case ("pickup", False):
return "Your goal is to pick up all the balls with grippers."
case ("drop_and_pickup", False):
return "Your goal is to drop all the balls held by grippers in an empty room that the robby didn't start in, and pick up the balls that started in rooms not held by the robby."
case ("holding", True):