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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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
import numpy as np
from queue import Queue
from enum import Enum
from src.geometry.convex_hull_processor import ConvexHullProcessor_2d
from src.geometry.basic_geometries import Basic2DGeometry
from src.utils.string_convertor import StringConvertor
from src.utils.config_manager import (
    get_config_manager,
    get_config,
    get_outcome_based_task_generation_config,
)
import copy

import itertools
import jsonschema
import glog
import time
import os

NINE_DIRECTIONS = [
    "rear",
    "rear-left",
    "left",
    "front-left",
    "front",
    "front-right",
    "right",
    "rear-right",
    "center",
]
OPPOSITE_DIRECTIONS = {
    "front": "rear",
    "front-right": "rear-left",
    "right": "left",
    "rear-right": "front-left",
    "rear": "front",
    "rear-left": "front-right",
    "left": "right",
    "front-left": "rear-right",
}
fovy_range_default = [np.deg2rad(5), np.deg2rad(100)]


class ItemType(Enum):
    GROUND = 0
    GROUND_OBJECT = 1
    NON_GROUND_OBJECT = 2
    MOVEABLE_OBJECT = 3
    DEFAULT = -1


class TaskType(Enum):

    NOT_FOR_TASK = -1
    ONLY_FOR_WANDER = -2
    # move a from A to B's empty platform
    MOVE_TO_EMPTY_PLATFORM = 0
    MOVE_TO_EMPTY_PLATFORM_9_GRID = 1
    # move a from A to b's {dir} freespace
    MOVE_AROUND_OBJECT = 2
    MOVE_TO_OBJECT_FREESPACE_9_GRID = 3

    # move a fromt A to b and c's middle (i.e. any shared freespace of B and C)
    MOVE_TO_MIDDLE_OF_OBJECTS = 4


class TaskStatusCode(Enum):
    SUCCESS = 0
    FAILURE = 1


class Task:

    def __init__(

        self,

        item,

        destination,

        type: TaskType = None,

        feature=None,

        intermediate_state_list=None,

        goal_translation=None,

        single_freespace_translation=None,

        need_merge_freespace=False,

    ):
        # print(type)
        # assert isinstance(type, TaskType)
        # assert dir in NINE_DIRECTIONS
        self.item = item
        self.destination = destination
        self.type = type
        self.feature = [feature] if isinstance(feature, str) else feature
        """

        MOVE_TO_EMPTY_PLATFORM:

        feature = {}

        MOVE_TO_EMPTY_PLATFORM_9_GRID:

        feature = {dir: str}

        MOVE_AROUND_OBJECT:

        feature = {object: node}

        MOVE_TO_OBJECT_FREESPACE_9_GRID:

        feature = {object: node, dir: str}

        MOVE_TO_MIDDLE_OF_OBJECTS:

        feature = {object1: node, object2: node}

        """

        self.goal_translation = goal_translation
        self._goal_primitive_expression = None
        self.single_freespace_translation = single_freespace_translation
        self.need_merge_freespace = need_merge_freespace
        self.intermediate_state_list = intermediate_state_list
        self.intermedaite_state_repr_list = None

        if self.intermediate_state_list is None:
            self.generate_default_intermediate_state()

    @property
    def goal_primitive_expression(self):
        if self._goal_primitive_expression is None:
            from src.core.task_primitive import TaskPrimitive

            self._goal_primitive_expression = TaskPrimitive.from_task(self)
        return self._goal_primitive_expression

    def generate_default_intermediate_state(self):
        """

        Generates a default intermediate state list based on the item and destination, used for calculating the IP.



        """

        item_platform_name = (
            self.item.get_bel_ground_platform().get_name_for_interaction()
        )
        item_name = self.item.get_name_for_interaction()
        destination_name = self.destination.get_name_for_interaction()
        self.intermediate_state_list = [
            {"holding": "any", "at_platform": item_platform_name},
            {"holding": self.item.name, "at_platform": "any"},
            {"holding": self.item.name, "at_platform": destination_name},
        ]

        self.intermediate_state_repr_list = [
            f"Go to {item_platform_name} where {item_name} is located.",
            f"Pick up {item_name} from the {item_platform_name}",
            f"Go to {destination_name} to place {item_name}.",
            f"Place {item_name} on the {destination_name} and make sure it is placed according the task requirement.",
        ]

    def check_pattern_jsonschema(data, schema):
        try:
            jsonschema.validate(data, schema)
        except jsonschema.exceptions.ValidationError as e:
            return False
        return True

    def validate_task(self):

        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            if not self.check_pattern_jsonschema(self.feature, {}):
                return False
        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            if not self.check_pattern_jsonschema(self.feature, {"dir": str}):
                return False
        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            if not self.check_pattern_jsonschema(self.feature, {"object": str}):
                return False
        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            if not self.check_pattern_jsonschema(
                self.feature, {"object": str, "dir": str}
            ):
                return False
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            if not self.check_pattern_jsonschema(
                self.feature, {"object1": str, "object2": str}
            ):
                return False

    def debug_check_bboxes(self):
        print(
            self.destination.bbox[3] - self.destination.bbox[0],
            self.destination.bbox[1] - self.destination.bbox[0],
        )
        heading = (
            self.destination.bbox[3] - self.destination.bbox[0]
        ) / np.linalg.norm(self.destination.bbox[3] - self.destination.bbox[0])
        headed_bbox = ConvexHullProcessor_2d.get_headed_bbox(
            self.item.object.convex_hull_2d.vertices, heading
        )
        print(headed_bbox[3] - headed_bbox[0], headed_bbox[1] - headed_bbox[0])

    def is_ambiguous(self, scene_graph):
        """



        Checks if the task is ambiguous based on the scene graph tree.

        The ambiguity is determined by the ambiguity of all the items involved in the tasks.



        Args:

            scene_graph: SceneGraphTree object

        Returns:

            bool: True if the task is ambiguous, False otherwise.



        """

        if (
            self.type == TaskType.MOVE_TO_EMPTY_PLATFORM
            or self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID
        ):
            return scene_graph.nodes[self.item.name].is_ambiguous
        elif (
            self.type == TaskType.MOVE_AROUND_OBJECT
            or self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
        ):

            return (
                scene_graph.nodes[self.item.name].is_ambiguous
                or scene_graph.nodes[self.feature[0]].is_ambiguous
            )
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return (
                scene_graph.nodes[self.item.name].is_ambiguous
                or scene_graph.nodes[self.feature[0]].is_ambiguous
                or scene_graph.nodes[self.feature[1]].is_ambiguous
            )
        pass

    def task_auto_finish(self, scene_graph):
        """ """

        scene_graph.update_platform_children()
        scene_graph.remove_node(self.item.name)
        scene_graph.add_node(
            self.item.name,
            self.destination.bel_object,
            self.destination.name,
            self.goal_translation,
        )
        return scene_graph

    def task_debug(self, scene_graph, id=-1):
        img_save_path = f'./image4debug/goal/Task{id}_{self.item.get_name_for_interaction()}_{self.destination.get_name_for_interaction()}_{[feature.split("/") for feature in self.feature ]if self.feature is not None else None}.png'
        scene_graph = self.task_auto_finish(scene_graph)

        item_node = scene_graph.nodes[self.item.name]
        destination_bel_object = scene_graph.nodes[self.destination.bel_object]
        standing_direction = [
            dir
            for dir in range(0, 8, 2)
            if self.destination.freespace_is_visible(dir)
            and destination_bel_object.freespace_is_standable(dir)
        ]
        if len(standing_direction) == 0:
            glog.info(
                f"Item {self.item.name} cannot be placed on {self.destination.name}"
            )
            return
        img = item_node.auto_take_non_ground_object_picture(
            scene=scene_graph.corresponding_scene,
            view="human_focus",
            mark_object=False,
            only_mark_itself=False,
            mark_freespace=False,
            standing_direction=standing_direction[0],
            width=1366,
            height=768,
            focus_ratio=0.5,
            fovy_range=[np.deg2rad(40), np.deg2rad(60)],
            save_path=img_save_path,
        )

        goal_translation = self.goal_translation

    def check_task_success(self, scene_graph):
        """

        wait to be implemented

        maybe don't need to be implemented



        """
        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            return self.check_empty_platform(scene_graph)
        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            return self.check_empty_platform_9_grid(scene_graph)
        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            return self.check_around_object(scene_graph)
        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            return self.check_object_freespace_9_grid(scene_graph)
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return self.check_middle_of_objects(scene_graph)
        pass

    def __repr__(self):

        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            return f"Move {self.item.name} to {self.destination.name}.\n\n"
        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            return f"Move {self.item.name} to {self.destination.name}'s {self.feature[0]} part\n\n"
        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            return f"Move {self.item.name} around {self.feature[0]} \n\n"
        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            return f"Move {self.item.name} to {self.feature[0]}'s {self.feature[1]} freespace\n\n"
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return f"Move {self.item.name} between {self.feature[0]} and {self.feature[1]} \n\n"

    def __repr_rough__(self):

        rough_item_name = StringConvertor.get_noslash_name_wo_id(self.item.name)
        rough_destination_name = self.destination.get_name_for_interaction()
        if self.feature and len(self.feature) > 0:
            rough_feature0_name = StringConvertor.get_noslash_name_wo_id(
                self.feature[0]
            )
        if self.feature and len(self.feature) > 1:
            rough_feature1_name = StringConvertor.get_noslash_name_wo_id(
                self.feature[1]
            )
        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            return f"Move {rough_item_name} to {rough_destination_name}."
        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            return f"Move {rough_item_name} to {rough_destination_name}'s {rough_feature0_name} part"
        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            return f"Move {rough_item_name} around {rough_feature0_name}"
        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            return f"Move {rough_item_name} to {rough_feature0_name}'s {rough_feature1_name} freespace"
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return f"Move {rough_item_name} between {rough_feature0_name} and {rough_feature1_name}"

    def initial_state_information(self):
        item_platform_name = (
            self.item.get_bel_ground_platform().get_name_for_interaction()
        )
        destination_name = self.destination.get_name_for_interaction()
        rough_item_name = StringConvertor.get_noslash_name_wo_id(self.item.name)
        feature_0_name = (
            StringConvertor.get_noslash_name_wo_id(self.feature[0])
            if self.feature and len(self.feature) > 0
            else ""
        )
        feature_1_name = (
            StringConvertor.get_noslash_name_wo_id(self.feature[1])
            if self.feature and len(self.feature) > 1
            else ""
        )

        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            return f"\nInitially, {rough_item_name} is on {item_platform_name}\n"
        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:
            return f"\nInitially, {rough_item_name} is on {item_platform_name}, and {destination_name} is empty.\n"
        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            return f"\nInitially, {rough_item_name} is on {item_platform_name}, and {feature_0_name} is on {destination_name}.\n"
        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            return f"\nInitially, {rough_item_name} is on {item_platform_name}, and {feature_0_name} is on {destination_name}.\n"
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            return f"\nInitially, {rough_item_name} is on {item_platform_name}, and {feature_0_name} is on {destination_name}, together with {feature_1_name}.\n"

    @staticmethod
    def generate_pic_description(

        pic_type="object",

        child_name_list=[],

        child_node=None,

        standing_direction=0,

    ):

        if pic_type == "occupied":
            child_info_list = [
                f"{i+1}: {child_name_list[i]}" for i in range(len(child_name_list))
            ]
            prompt = f"The picture(s) show the objects on the platform and their indices. They are:{child_info_list} respectively."
            pass
        elif pic_type == "empty":

            direction_list = NINE_DIRECTIONS[:-1]
            direction_list = (
                direction_list[-standing_direction:]
                + direction_list[:-standing_direction]
                + NINE_DIRECTIONS[-1:]
            )
            platform_region_info_list = [
                f"Region No. {i+1}: {direction_list[i]}" for i in range(9)
            ]
            prompt = f"The picture(s) show the platform, divided into 3x3 grid with each grid region has a number. They are:{platform_region_info_list} respectively."
            pass
        elif pic_type == "object":
            glog.info(f"standing_direction:{standing_direction}")
            probable_directions = [dir for dir in range(0, 8)]
            probable_directions = (
                probable_directions[-standing_direction:]
                + probable_directions[:-standing_direction]
            )
            dir_list = []
            for dir in probable_directions:
                if child_node.is_freespace_big_enough(dir):
                    i = len(dir_list) + 1
                    dir_list.append(f"freespace No. {i}: {NINE_DIRECTIONS[(dir ) % 8]}")
            prompt = f"The picture shows a focused view of object {child_node.get_name_for_interaction()} and its freespace. The freespace are: {dir_list} respectively."
            pass

        return prompt

    def generate_goal_information(

        self,

        scene_graph,

        width=683,

        height=384,

        id=-1,

        model="human",

        current_path=os.path.dirname(os.path.abspath(__file__)),

        detailed_pic_explanation=True,

    ):

        goal_action_list = []
        goal_explanation_list = []
        goal_picture_list = []
        source_platform = self.item.get_bel_ground_platform()
        source_platform_name = (
            self.item.get_bel_ground_platform().get_name_for_interaction()
        )
        source_object = scene_graph.nodes[self.item.get_bel_ground_object().name]
        source_item_name = StringConvertor.get_noslash_name_wo_id(self.item.name)
        source_item_id = [
            id
            for id, _ in enumerate(self.item.get_bel_ground_platform().children)
            if _.name == self.item.name
        ][0] + 1

        destination_platform_name = self.destination.get_name_for_interaction()
        destination_object = scene_graph.nodes[self.destination.bel_object]

        available_directions = [
            dir
            for dir in range(0, 8, 2)
            if source_platform.freespace_is_visible(dir)
            and source_object.freespace_is_standable(dir)
        ]
        standing_direction = (
            available_directions[0] if len(available_directions) > 0 else 0
        )

        goto_source_platform_action = f"goto_{source_platform_name}"
        goto_source_platform_explanation = (
            f"Go to {source_platform_name} where {source_item_name} is located."
        )

        goal_action_list.append(goto_source_platform_action)
        goal_explanation_list.append(goto_source_platform_explanation)
        goal_picture_list.append([])

        platform_img, platform_img_list = scene_graph.auto_take_platform_picture(
            platform_name=source_platform.name,
            view="human_full",
            mark_object=True,
            mark_freespace=len(source_platform.children) == 0,
            standing_direction=standing_direction,
            width=width,
            height=height,
            focus_ratio=0.6,
            save_path=f"{current_path}/image4reflection/{model}/Task{id}_before_pickup_object.png",
        )
        n_platform_img_list = len(platform_img_list)
        image_name_list = [
            f"{current_path}/image4reflection/{model}/Task{id}_before_pickup_object_{(i+1)}_out_of_{n_platform_img_list}.png"
            for i in range(len(platform_img_list))
        ]

        pickup_source_item_action = (
            f"pick_up_object_{source_item_id}_of_current_platform"
        )
        pickup_source_item_explanation = f"Now you see single or multiple images of the current platform, they are {image_name_list}, showing you the items on the platform and their index in one or more view angles. We can recognize the number of {source_item_name} is {source_item_id},  and pick up {source_item_name} from the current platform."
        scene_graph.remove_node(self.item.name)

        goal_action_list.append(pickup_source_item_action)
        goal_explanation_list.append(pickup_source_item_explanation)
        goal_picture_list.append(image_name_list)

        platform_img, platform_img_list = scene_graph.auto_take_platform_picture(
            platform_name=source_platform.name,
            view="human_full",
            mark_object=True,
            mark_freespace=len(source_platform.children) == 0,
            standing_direction=standing_direction,
            width=width,
            height=height,
            focus_ratio=0.6,
            save_path=f"{current_path}/image4reflection/{model}/Task{id}_before_goto_destination.png",
        )
        n_platform_img_list = len(platform_img_list)
        image_name_list = [
            f"{current_path}/image4reflection/{model}/Task{id}_before_goto_destination_{(i+1)}_out_of_{n_platform_img_list}.png"
            for i in range(len(platform_img_list))
        ]
        goto_destination_platform_action = f"goto_{destination_platform_name}"
        goto_destination_platform_explanation = f"Now you have picked up object, you can see the scene {image_name_list}. Go to {destination_platform_name} to place {source_item_name}."

        goal_action_list.append(goto_destination_platform_action)
        goal_explanation_list.append(goto_destination_platform_explanation)
        goal_picture_list.append(image_name_list)

        available_directions = [
            dir
            for dir in range(0, 8, 2)
            if self.destination.freespace_is_visible(dir)
            and destination_object.freespace_is_standable(dir)
        ]
        first_standing_direction = available_directions[
            0
        ]  # if len(available_directions) > 1 else available_directions[0]
        first_standing_direction_id = 0  # if len(available_directions) > 1 else 0
        if len(available_directions) > 1 and destination_object.get_bbox_line_length(
            available_directions[0]
        ) < destination_object.get_bbox_line_length(available_directions[1]):
            first_standing_direction = available_directions[1]
            first_standing_direction_id = 1
            platform_img, platform_img_list = scene_graph.auto_take_platform_picture(
                platform_name=self.destination.name,
                view="human_full",
                mark_object=True,
                mark_freespace=len(self.destination.children) == 0,
                standing_direction=available_directions[0],
                width=width,
                height=height,
                focus_ratio=0.6,
                save_path=f"{current_path}/image4reflection/{model}/Task{id}_before_rotate_view.png",
            )
            n_platform_img_list = len(platform_img_list)
            image_name_list = [
                f"{current_path}/image4reflection/{model}/Task{id}_before_rotate_view_{(i+1)}_out_of_{n_platform_img_list}.png"
                for i in range(len(platform_img_list))
            ]
            goal_picture_list.append(image_name_list)
            goal_action_list.append(f"rotate_observation_view_of_current_platform")
            goal_explanation_list.append(
                f"Now you see single or multiple images of the current platform, they are {image_name_list}, showing you the items on the platform and their index in one or more view angles, and an image you've required in previous step, showing an object and its freespace with their indices."
                f"rotate your observation view angle to avoid a bad and could-be-good view angle. If the view angle is getting worse, just repeat this action for at most 4 times until you find a good view angle."
            )

        place_destination_platform_action = ""
        place_destination_platform_explanation = ""
        freespace_list = []

        platform_img, platform_img_list = scene_graph.auto_take_platform_picture(
            platform_name=self.destination.name,
            view="human_full",
            mark_object=True,
            mark_freespace=len(self.destination.children) == 0,
            standing_direction=first_standing_direction,
            width=width,
            height=height,
            focus_ratio=0.6,
            save_path=f"{current_path}/image4reflection/{model}/Task{id}_before_place_object.png",
        )
        n_platform_img_list = len(platform_img_list)
        image_name_list = [
            f"{current_path}/image4reflection/{model}/Task{id}_before_place_object_{(i+1)}_out_of_{n_platform_img_list}.png"
            for i in range(len(platform_img_list))
        ]
        goal_picture_list.append(image_name_list)
        child_name_list = [
            child.get_name_for_interaction() for child in self.destination.children
        ]

        if self.type == TaskType.MOVE_TO_EMPTY_PLATFORM:
            place_destination_platform_action = "place_at_anywhere"
            place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the platform, divided into 3x3 grid with each grid has a number, in one or more view angles. The task only asks you to put the object on the destination platform, so just select all the regions of the platform."

        elif self.type == TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID:

            direction_id = (
                (NINE_DIRECTIONS.index(self.feature[0]) + first_standing_direction) % 8
                if self.feature[0] != "center"
                else 8
            )

            place_destination_platform_action = f"place_at_freespace_[{direction_id}]"

            cardinal_extend_direction_list = [direction_id, 8]

            diagonal_extend_direction_list = [
                direction_id,
                (direction_id + 1) % 8,
                (direction_id + 7) % 8,
                8,
            ]
            cardinal_extend_more_direction_list = [
                direction_id,
                (direction_id + 1) % 8,
                (direction_id + 7) % 8,
                (direction_id + 2) % 8,
                (direction_id + 6) % 8,
                8,
            ]

            direction_id += 1

            cardinal_extend_direction_list = [
                dir + 1 for dir in cardinal_extend_direction_list
            ]

            diggonal_extend_direction_list = [
                dir + 1 for dir in diagonal_extend_direction_list
            ]
            cardinal_extend_more_direction_list = [
                dir + 1 for dir in cardinal_extend_more_direction_list
            ]

            empty_platform_prompt = Task.generate_pic_description(
                # self,
                pic_type="empty",
                child_name_list=[],
                child_node=None,
                standing_direction=first_standing_direction,
            )
            if direction_id in [1, 3, 5, 7]:
                place_destination_platform_action = place_destination_platform_action
                place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the platform, divided into 3x3 grid with each grid has a number, in one or more view angles.{empty_platform_prompt} the task asks you to put at {self.feature[0]}, {direction_id} corresponds to that direction according to the picture; in case the free space cannot afford this item, try place_at_freespace_{cardinal_extend_direction_list}  or place_at_freespace_{cardinal_extend_more_direction_list} as  the region {direction_id} is adjacent to them according to the picture in 8-directional space."
            elif direction_id in [2, 4, 6, 8]:
                place_destination_platform_action = place_destination_platform_action
                place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the platform, divided into 3x3 grid with each grid has a number, in one or more view angles.{empty_platform_prompt} the task asks you to put at {self.feature[0]}, {direction_id} corresponds to that direction according to the picture; in case the free space cannot afford this item, try  place_at_freespace_{diggonal_extend_direction_list} as  the region {direction_id} is adjacent to them according to the picture in 8-directional space."
            else:
                place_destination_platform_action = place_destination_platform_action
                place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the platform, divided into 3x3 grid with each grid has a number, in one or more view angles.{empty_platform_prompt} the task asks you to put at {self.feature[0]}, {direction_id} corresponds to that direction according to the picture; in case the free space cannot afford this item, try  place_at_anywhere."

        elif self.type == TaskType.MOVE_AROUND_OBJECT:
            if not self.feature or len(self.feature) == 0:
                glog.error("MOVE_AROUND_OBJECT task without feature is invalid.")
                return [], []

            dest_item_node = scene_graph.nodes[self.feature[0]]
            dest_item_name = StringConvertor.get_noslash_name_wo_id(self.feature[0])
            freespace_num = dest_item_node.get_num_of_critical_space()
            dest_item_id = [
                id
                for id, _ in enumerate(self.destination.children)
                if _.name == self.feature[0]
            ][0] + 1

            freespace_list = [(dest_item_id, i) for i in range(1, freespace_num + 1)]

            occupied_platform_prompt = Task.generate_pic_description(
                #  self,
                pic_type="occupied",
                child_name_list=child_name_list,
                child_node=None,
                standing_direction=first_standing_direction,
            )
            goal_action_list.append(f"show_freespace_of_object_{dest_item_id}")
            goal_explanation_list.append(
                f"Now you see single or multiple images of the current platform, they are {image_name_list},  showing you the items on the platform and their index in one or more view angles. {occupied_platform_prompt}"
                f"Because we want to place item near {dest_item_name} , we check the freespace of {dest_item_name} (or the number you think correct) to see if you've recognized the correct item and where is available for placing the object. Repeat if you find your recognition is wrong or you need to check the freespace of other objects."
            )

            # next step's picture
            object_to_show = scene_graph.nodes[self.feature[0]]
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=True,
                standing_direction=standing_direction,
                width=width,
                height=height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=f"{current_path}/image4reflection/{model}/Task{id}_showfreespace.png",
            )
            image_name_list = [
                f"{current_path}/image4reflection/{model}/Task{id}_showfreespace.png"
            ]
            image_name_list += goal_picture_list[-1]
            goal_picture_list.append(image_name_list)

            place_destination_platform_action = f"place_at_freespace_{freespace_list}"
            place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the items on the platform and their index in one or more view angles, they are {image_name_list[:-1]}; and an image you've required in previous step, showing an object and its freespace with their indices, it is {image_name_list[-1]}."
            place_destination_platform_explanation += f"recognize the number of {dest_item_name} is {dest_item_id} on that platform, and then place {source_item_name} around {dest_item_name} at any of the available freespace. If you can't recognize at once, use 'show_freespace_of_object_x' to check xth object and its freespace to see if x is the number you're looking for;  In case the free space cannot afford this item, try combining freespace of other objects, "
            place_destination_platform_explanation += f"or use 'rotate_observation_view_of_current_platform' to change your view angle."

        elif self.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID:
            if not self.feature or len(self.feature) < 2:
                glog.error(
                    "MOVE_TO_OBJECT_FREESPACE_9_GRID task without feature is invalid."
                )
                return [], []

            dest_item_node = scene_graph.nodes[self.feature[0]]
            dest_item_name = StringConvertor.get_noslash_name_wo_id(self.feature[0])
            dest_item_id = [
                id
                for id, _ in enumerate(self.destination.children)
                if _.name == self.feature[0]
            ][0] + 1
            direction_id = (
                NINE_DIRECTIONS.index(self.feature[1]) + first_standing_direction
            ) % 8
            direction_id = dest_item_node.get_on_picture_freespace_id(direction_id)

            for i in range(4):
                if direction_id != -1:
                    break
                platform_img, platform_img_list = (
                    scene_graph.auto_take_platform_picture(
                        platform_name=self.destination.name,
                        view="human_full",
                        mark_object=True,
                        mark_freespace=len(self.destination.children) == 0,
                        standing_direction=available_directions[
                            first_standing_direction_id
                        ],
                        width=width,
                        height=height,
                        focus_ratio=0.6,
                        save_path=f"{current_path}/image4reflection/{model}/Task{id}_rotate_view.png",
                    )
                )
                n_platform_img_list = len(platform_img_list)
                image_name_list = [
                    f"{current_path}/image4reflection/{model}/Task{id}_rotate_view_{available_directions[first_standing_direction_id]}_{(i+1)}_out_of_{n_platform_img_list}.png"
                    for i in range(len(platform_img_list))
                ]

                first_standing_direction_id = (first_standing_direction_id + 1) % len(
                    available_directions
                )
                first_standing_direction = available_directions[
                    first_standing_direction_id
                ]
                direction_id = (
                    NINE_DIRECTIONS.index(self.feature[1]) + first_standing_direction
                ) % 8
                direction_id = dest_item_node.get_on_picture_freespace_id(direction_id)
                goal_picture_list.append(image_name_list)
                goal_action_list.append(f"rotate_observation_view_of_current_platform")
                goal_explanation_list.append(
                    f"Now you see single or multiple images of the current platform, they are {image_name_list},  showing you the items on the platform and their index in one or more view angles."
                    f"rotate your observation view angle to avoid a bad and could-be-good view angle. If the view angle is getting worse, just repeat this action for at most 4 times until you find a good view angle."
                )
            if direction_id == -1:
                direction_id = 2

            freespace_list = [(dest_item_id, direction_id)]

            occupied_platform_prompt = Task.generate_pic_description(
                #   self,
                pic_type="occupied",
                child_name_list=child_name_list,
                child_node=None,
                standing_direction=first_standing_direction,
            )
            goal_action_list.append(f"show_freespace_of_object_{dest_item_id}")
            goal_explanation_list.append(
                f"Now you see single or multiple images of the current platform, showing you the items on the platform and their index in one or more view angles. they are {image_name_list}. {occupied_platform_prompt}"
                f"Because we want to place item near {dest_item_name} , we check the freespace of {dest_item_name} (or the number you think correct) to see if you've recognized the correct item and where is available for placing the object. Repeat if you find your recognition is wrong or you need to check the freespace of other objects."
            )

            object_to_show = scene_graph.nodes[self.feature[0]]
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=True,
                standing_direction=first_standing_direction,
                width=width,
                height=height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=f"{current_path}/image4reflection/{model}/Task{id}_show_freespace.png",
            )
            image_name_list = [
                f"{current_path}/image4reflection/{model}/Task{id}_show_freespace.png"
            ]
            image_name_list += goal_picture_list[-1]
            goal_picture_list.append(image_name_list)

            object_prompt = Task.generate_pic_description(
                #   self,
                pic_type="object",
                child_name_list=[],
                child_node=dest_item_node,
                standing_direction=first_standing_direction,
            )
            place_destination_platform_action = f"place_at_freespace_{freespace_list}"
            place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, they are {image_name_list}, showing you the items on the platform and their index in one or more view angles, and an image you've required in previous step, showing an object and its freespace with their indices. {object_prompt}"
            place_destination_platform_explanation += f"recognize the number of {dest_item_name} is {dest_item_id} on that platform and the number of freespace {self.feature[1]} is {direction_id}, and then place {source_item_name} at the freespace {direction_id} of {dest_item_name}. If you can't recognize at once, use 'show_freespace_of_object_x' to check xth object and its freespace to see if x is the number you're looking for;  In case the free space cannot afford this item, try combining freespace of other objects,  or use 'rotate_observation_view_of_current_platform' to change your view angle."
            """

            dir_id = (

                self.platform_list[self.at_place]

                .children[child_id]

                .get_on_picture_freespace_id(freespace_pair_list[i][1])

            )

            """
        elif self.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
            dest_item_node_a = scene_graph.nodes[self.feature[0]]
            dest_item_node_b = scene_graph.nodes[self.feature[1]]

            dest_item_a_name = StringConvertor.get_noslash_name_wo_id(self.feature[0])
            dest_item_b_name = StringConvertor.get_noslash_name_wo_id(self.feature[1])

            select_item_id_a = [
                id
                for id, _ in enumerate(self.destination.children)
                if _.name == self.feature[0]
            ][0] + 1
            select_item_id_b = [
                id
                for id, _ in enumerate(self.destination.children)
                if _.name == self.feature[1]
            ][0] + 1

            ba_dir = []
            ab_dir = []
            while dest_item_node_a.depth > 2:
                dest_item_node_a = dest_item_node_a.parent
            while dest_item_node_b.depth > 2:
                dest_item_node_b = dest_item_node_b.parent

            for dir in range(8):
                if dest_item_node_b in dest_item_node_a.free_space[dir]["Objects"]:
                    ba_dir.append(dir)
                if dest_item_node_a in dest_item_node_b.free_space[dir]["Objects"]:
                    ab_dir.append(dir)

            ba_dir = [
                dest_item_node_a.get_on_picture_freespace_id(dir) for dir in ba_dir
            ]
            ab_dir = [
                dest_item_node_b.get_on_picture_freespace_id(dir) for dir in ab_dir
            ]

            freespace_list = [
                (select_item_id_a, dir) for dir in ba_dir if dir != -1
            ] + [(select_item_id_b, dir) for dir in ab_dir if dir != -1]

            occupied_platform_prompt = Task.generate_pic_description(
                #    self,
                pic_type="occupied",
                child_name_list=child_name_list,
                child_node=None,
                standing_direction=first_standing_direction,
            )
            goal_action_list.append(f"show_freespace_of_object_{select_item_id_a}")
            goal_explanation_list.append(
                f"Now you see single or multiple images of the current platform, showing you the items on the platform and their index in one or more view angles, they are {image_name_list}. {occupied_platform_prompt}"
                f"Because we want to place item near {dest_item_a_name} , we check the freespace of {dest_item_a_name} (or the number you think correct) to see if you've recognized the correct item and where is available for placing the object. Repeat if you find your recognition is wrong or you need to check the freespace of other objects."
            )

            object_to_show = scene_graph.nodes[self.feature[0]]
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=True,
                standing_direction=first_standing_direction,
                width=width,
                height=height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=f"{current_path}/image4reflection/{model}/Task{id}_showfreespace_a.png",
            )
            image_name_list = [
                f"{current_path}/image4reflection/{model}/Task{id}_showfreespace_a.png"
            ]
            image_name_list += goal_picture_list[-1]
            goal_picture_list.append(image_name_list)

            object_prompt = Task.generate_pic_description(
                #   self,
                pic_type="object",
                child_name_list=[],
                child_node=dest_item_node_a,
                standing_direction=first_standing_direction,
            )
            goal_action_list.append(f"show_freespace_of_object_{select_item_id_b}")
            goal_explanation_list.append(
                f"Now you see single or multiple images of the current platform, showing you the items on the platform and their index in one or more view angles, they are {image_name_list[:-1]}; and an image you've required in previous step, showing an object and its freespace with their indices, it is {image_name_list [-1]}. {object_prompt}"
                f"Because we also want to place item near {dest_item_b_name} , we should further check the freespace of {dest_item_b_name} (or the number you think correct) to see if you've recognized the correct item and where is available for placing the object. Repeat if you find your recognition is wrong or you need to check the freespace of other objects."
            )

            object_to_show = scene_graph.nodes[self.feature[1]]
            img = object_to_show.auto_take_non_ground_object_picture(
                scene=scene_graph.corresponding_scene,
                view="human_focus",
                mark_object=False,
                only_mark_itself=False,
                mark_freespace=True,
                standing_direction=first_standing_direction,
                width=width,
                height=height,
                focus_ratio=0.5,
                fovy_range=[np.deg2rad(40), np.deg2rad(60)],
                save_path=f"{current_path}/image4reflection/{model}/Task{id}_showfreespace_b.png",
            )
            image_name_list = [
                f"{current_path}/image4reflection/{model}/Task{id}_showfreespace_b.png"
            ]
            image_name_list += goal_picture_list[-1]
            goal_picture_list.append(image_name_list)

            object_prompt = Task.generate_pic_description(
                #    self,
                pic_type="object",
                child_name_list=[],
                child_node=dest_item_node_b,
                standing_direction=first_standing_direction,
            )
            place_destination_platform_action = f"place_at_freespace_{freespace_list}"
            place_destination_platform_explanation = f"Now you see single or multiple images of the current platform, showing you the items on the platform and their index in one or more view angles, and an image you've required in previous step, showing an object and its freespace with their indices. the pictures you can see are {image_name_list[-1]}. {object_prompt} Note that you can only see one image at a time, so please memorize the last image you've seen."
            place_destination_platform_explanation += f"we have recognized the number of {dest_item_a_name} is {select_item_id_a} and the number of {dest_item_b_name} is {select_item_id_b} on that platform, and the indices of the freespace between them are {freespace_list}, so we place {source_item_name} at the freespace {freespace_list}. If you can't recognize at once, use 'show_freespace_of_object_x' to check xth object and its freespace to see if x is the number you're looking for;  In case the free space cannot afford this item, try combining freespace of other objects,  or use 'rotate_observation_view_of_current_platform' to change your view angle."

        goal_action_list.append(place_destination_platform_action)
        goal_explanation_list.append(place_destination_platform_explanation)

        return goal_action_list, goal_explanation_list, goal_picture_list

        pass


class TaskChain:

    def __init__(self, subtask_list=None):
        if subtask_list is not None:
            self.subtask_list = subtask_list
        self.subtask_list = []

    def __repr__(self):

        repr_str = f"TaskChain with {len(self.subtask_list)} subtasks:\n"
        for i, subtask in enumerate(self.subtask_list):
            repr_str += f"Subtask {i+1}: {subtask}"

        return repr_str

    def __repr_rough__(self):
        repr_str = ""
        for i, subtask in enumerate(self.subtask_list):
            repr_str += subtask.__repr_rough__()
            if i < len(self.subtask_list) - 1:
                repr_str += ", THEN "
        return repr_str

    def initial_state_information(self):
        if len(self.subtask_list) == 0:
            return "No subtasks in the task chain."
        else:
            return " and ".join(
                [subtask.initial_state_information() for subtask in self.subtask_list]
            )


class TaskGeneration:

    direction_mapping = {
        (0, 0): "rear-left",
        (0, 1): "left",
        (0, 2): "front-left",
        (1, 0): "rear",
        (1, 1): "center",
        (1, 2): "front",
        (2, 0): "rear-right",
        (2, 1): "right",
        (2, 2): "front-right",
    }
    diagonal_direction_mapping = {
        (0, 0): "rear-left",
        (0, 2): "front-left",
        (2, 0): "rear-right",
        (2, 2): "front-right",
    }
    horizontal_direction_mapping = {
        (0, 1): "left",
        (1, 2): "front",
    }
    vertical_direction_mapping = {
        (0, 1): "rear",
        (2, 1): "front",
    }

    def __init__(self, scene_graph=None, items=[], places=[]):
        self.scene_graph = scene_graph
        self.tasks = []
        self.use_level1_tasks = False

        # self.place_for_index = {}
        scene_graph.update_platform_children()
        # for node in scene_graph.get_ground_object_list():
        #     for platform in node.own_platform:
        #         self.place_for_index[platform.name] = platform

    @classmethod
    def get_config(cls):
        from ..utils.config_manager import get_process_based_task_config

        return get_process_based_task_config()

    def parse_from_file(self, tree_file=None, node_details_file=None):
        if tree_file:
            self.scene_graph.parse_tree_from_file(tree_file)
        if node_details_file:
            self.scene_graph.parse_node_details_from_file(node_details_file)

    def generate_single_subtask(self, cur_scene_graph, fixed_object_list=[]):
        """



        Generate a single subtask given the current state of the scene graph.



        To generate a chained subtask, we can call this function multiple times and combine the results.







        """

        item_node_list = cur_scene_graph.get_non_ground_object_list()
        if self.use_level1_tasks:
            item_node_list = [
                item_node for item_node in item_node_list if not item_node.is_ambiguous
            ]
        place_node_list = cur_scene_graph.get_ground_object_list()

        platform_list = []
        for place_node in place_node_list:
            tmp_platform_list = [
                platform
                for platform in place_node.own_platform
                if any(
                    len(platform.standing_point_list[dir // 2]) > 0
                    and platform.freespace_is_visible(dir)
                    and place_node.freespace_is_standable(dir)
                    for dir in range(0, 8, 2)
                )
            ]

            platform_list.extend(tmp_platform_list)

        item_platform_pairs = [
            (item_node, platform)
            for item_node in item_node_list
            for platform in platform_list
            if (item_node.top - item_node.bottom) <= platform.avl_height
        ]
        if len(item_platform_pairs) == 0:
            glog.info("No item or platform to generate task.")
            return None

        import random

        random.shuffle(item_platform_pairs)

        for item_node, platform in item_platform_pairs:
            if item_node.name in fixed_object_list:
                continue
            # import ipdb; ipdb.set_trace()
            if self.use_level1_tasks:
                if item_node.is_ambiguous:
                    continue
            available_directions = [
                dir
                for dir in range(0, 8, 2)
                if len(platform.standing_point_list[dir // 2]) > 0
                and platform.freespace_is_visible(dir)
            ]
            if len(available_directions) == 0:
                continue
            available_direction = random.choice(available_directions)

            goal_translation_height = (
                platform.bottom + (item_node.top - item_node.bottom) * 0.5
            )

            result_tuple = platform.get_fitable_tasks_any_number(
                item_node,
                all_standing_directions=available_directions,
            )
            # import ipdb
            # ipdb.set_trace()
            if result_tuple and len(result_tuple) == 8:
                (
                    result,
                    put_on_platform,
                    put_around_object_list,
                    put_on_object_dir_list,
                    put_between_2_object_list,
                    put_around_object_dict,
                    put_on_object_dir_dict,
                    put_between_2_object_dict,
                ) = result_tuple
            else:
                raise ValueError(
                    "Unexpected return value from get_fitable_tasks_any_number"
                )
            #   glog.info('Result from get_fitable_tasks_any_number: %s, %s, %s, %s', item_node.name, platform.name, put_around_object_dict, put_around_object_list)
            if result == "non_empty":
                if put_on_platform:
                    task_options = [
                        (
                            TaskType.MOVE_AROUND_OBJECT,
                            put_around_object_list,
                            put_around_object_dict,
                        ),
                        (
                            TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID,
                            put_on_object_dir_list,
                            put_on_object_dir_dict,
                        ),
                        (
                            TaskType.MOVE_TO_MIDDLE_OF_OBJECTS,
                            put_between_2_object_list,
                            put_between_2_object_dict,
                        ),
                    ]
                    random.shuffle(task_options)
                    for task_type, feature_list, feature_dict in task_options:
                        if len(feature_list) > 0:
                            random_feature = random.choice(feature_list)
                            if self.use_level1_tasks:
                                if isinstance(random_feature, list):
                                    skip_flag = False
                                    for rf in random_feature:
                                        if (
                                            cur_scene_graph.nodes.get(rf, None)
                                            is not None
                                            and cur_scene_graph.nodes[rf].is_ambiguous
                                        ):
                                            skip_flag = True
                                    if skip_flag:
                                        continue
                                else:
                                    if (
                                        cur_scene_graph.nodes.get(random_feature, None)
                                        is not None
                                        and cur_scene_graph.nodes.get(
                                            random_feature, None
                                        )
                                        is not None
                                        and cur_scene_graph.nodes[
                                            random_feature
                                        ].is_ambiguous
                                    ):
                                        continue

                            goal_translation_2d = feature_dict[random_feature]
                            goal_translation_3d = [
                                goal_translation_2d[0],
                                goal_translation_2d[1],
                                goal_translation_height,
                            ]
                            # print(task_type)
                            # import ipdb; ipdb.set_trace()
                            new_task = Task(
                                item=item_node,
                                destination=platform,
                                type=task_type,
                                feature=random_feature,
                                goal_translation=goal_translation_3d,
                                need_merge_freespace=not platform.single_freespace_available(
                                    item_node, single_type=random_feature
                                ),
                            )
                            # print(new_task)
                            return new_task

                pass
            else:
                platform_convex_hull_2d = platform.convex_hull_2d
                platform_bounding_box = (
                    platform_convex_hull_2d.get_headed_bbox_instance()
                )

                if "center" in result:
                    direction = random.randint(0, 9)
                    if direction == 9:
                        continue
                    new_task = Task(
                        item=item_node,
                        destination=platform,
                        type=TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID,
                        feature=[NINE_DIRECTIONS[direction]],
                        goal_translation=np.append(
                            platform.get_dir_point(
                                dir=(
                                    NINE_DIRECTIONS[
                                        (direction + available_direction) % 8
                                    ]
                                    if direction < 8
                                    else "center"
                                ),
                                item_node=item_node,
                            ),
                            [goal_translation_height],
                        ),
                        need_merge_freespace=not platform.single_freespace_available(
                            item_node, single_type="empty"
                        ),
                    )
                    return new_task
                elif "wholetable" in result:
                    new_task = Task(
                        item=item_node,
                        destination=platform,
                        type=TaskType.MOVE_TO_EMPTY_PLATFORM,
                        feature=None,
                        goal_translation=np.append(
                            platform.get_dir_point(dir="center", item_node=item_node),
                            [goal_translation_height],
                        ),
                        need_merge_freespace=not platform.single_freespace_available(
                            item_node, single_type="empty"
                        ),
                    )
                    return new_task
                else:
                    continue

        glog.info("No suitable item or platform to generate task.")

        # Find the first task that can be generated.

        pass

    def generate_task_chain(

        self, cur_scene_graph, chain_num=None, fixed_object_list=None

    ):
        """

        Generate a task chain given the current state of the scene graph.



        This function generates a chain of tasks until the maximum number of tasks is reached or no more tasks can be generated.



        """

        scene_graph = copy.deepcopy(cur_scene_graph)

        task_chain = TaskChain()
        chain_num = chain_num if chain_num is not None else self.CHAIN_NUM
        fixed_object_list = fixed_object_list if fixed_object_list is not None else []

        for _ in range(chain_num):
            new_task = self.generate_single_subtask(cur_scene_graph, fixed_object_list)
            if new_task is None:
                break
            new_task.item = copy.deepcopy(scene_graph.nodes[new_task.item.name])
            new_task.destination = copy.deepcopy(
                scene_graph.platforms[new_task.destination.name]
            )
            task_chain.subtask_list.append(new_task)
            if (
                new_task.type == TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID
                or new_task.type == TaskType.MOVE_AROUND_OBJECT
            ):
                fixed_object_list.append(new_task.feature[0])
            if new_task.type == TaskType.MOVE_TO_MIDDLE_OF_OBJECTS:
                fixed_object_list.extend(new_task.feature)

            cur_scene_graph = new_task.task_auto_finish(cur_scene_graph)

        return task_chain

    def generate_task(self, task_length=None, max_task_num=None):
        # import ipdb; ipdb.set_trace()
        config = self.get_config()
        task_length = (
            task_length
            if task_length is not None
            else getattr(config, "max_task_length", 2)
        )
        max_task_num = (
            max_task_num
            if max_task_num is not None
            else getattr(config, "max_task_num", 10)
        )

        self.use_level1_tasks = getattr(config, "use_level1_tasks", False)

        self.CHAIN_NUM = task_length
        self.MAX_TASK_NUM = max_task_num
        if self.use_level1_tasks:
            self.CHAIN_NUM = 1
            pass

        for _ in range(self.MAX_TASK_NUM):
            self.tasks.append(self.generate_task_chain(self.scene_graph))

        glog.info(f"Generated {len(self.tasks)} tasks.")

        pass

    def generate_task_from_scene_graph(self):
        """

        generate tasks from the scene graph.



        This function generates 1 task given the current state of the scene graph.



        """

        item_node_list = self.scene_graph.get_non_ground_object_list()
        place_node_list = self.scene_graph.get_ground_object_list()

        object_task_info_dict = {}
        glog.info(
            len(item_node_list)
            * np.sum([len(place_node.own_platform) for place_node in place_node_list])
        )
        ts = time.perf_counter()
        task_set = set()
        for item_node in item_node_list:
            glog.info(f"Generating tasks for {item_node.name}")

            for place_node in place_node_list:
                platform_list = [
                    platform
                    for platform in place_node.own_platform
                    if any(
                        [platform.freespace_is_visible(dir) for dir in range(0, 8, 2)]
                    )
                    and any(
                        [
                            len(platform.standing_point_list[dir // 2]) > 0
                            for dir in range(0, 8, 2)
                        ]
                    )
                    and (platform.avl_height > 0.05 or len(platform.children) > 0)
                ]

                # glog.info([platform.name for platform in platform_list])
                for place_platform in platform_list:

                    if (item_node.top - item_node.bottom) > place_platform.avl_height:
                        continue
                    available_directions = [
                        dir
                        for dir in range(0, 8, 2)
                        if len(place_platform.standing_point_list[dir // 2]) > 0
                        and place_platform.freespace_is_visible(dir)
                    ]
                    if len(available_directions) == 0:
                        continue
                    available_directions = (
                        available_directions[:1] if len(available_directions) else [0]
                    )

                    (
                        result,
                        put_on_platform,
                        put_around_object_list,
                        put_on_object_dir_list,
                        put_between_2_object_list,
                        put_around_object_dict,
                        put_on_object_dir_dict,
                        put_between_2_object_dict,
                    ) = place_platform.get_fitable_tasks_any_number(
                        item_node, all_standing_directions=available_directions
                    )

                    goal_translation_height = (
                        place_platform.bottom + (item_node.top - item_node.bottom) * 0.5
                    )

                    # if len(put_around_object_list) > 0:
                    #     import ipdb
                    #     ipdb.set_trace()

                    if result == "non_empty":
                        if put_on_platform:
                            if (
                                put_around_object_list == []
                                and put_on_object_dir_list == []
                                and put_between_2_object_list == []
                            ):
                                continue

                            goal_translation_2d = list(put_on_object_dir_dict.values())[
                                0
                            ]
                            goal_translation_3d = [
                                goal_translation_2d[0],
                                goal_translation_2d[1],
                                goal_translation_height,
                            ]

                            new_empty_platform_task = Task(
                                item=item_node,
                                destination=place_platform,
                                type=TaskType.MOVE_TO_EMPTY_PLATFORM,
                                feature=None,
                                goal_translation=goal_translation_3d,
                                need_merge_freespace=not place_platform.single_freespace_available(
                                    item_node, single_type="all"
                                ),
                            )
                            self.tasks.append(new_empty_platform_task)

                            for put_around_object_info in put_around_object_list:

                                new_object_around_task = Task(
                                    item=item_node,
                                    destination=place_platform,
                                    type=TaskType.MOVE_AROUND_OBJECT,
                                    feature=[put_around_object_info],
                                    goal_translation=np.append(
                                        put_around_object_dict[put_around_object_info],
                                        [goal_translation_height],
                                    ),
                                    need_merge_freespace=not place_platform.single_freespace_available(
                                        item_node, single_type=put_around_object_info
                                    ),
                                )
                                self.tasks.append(new_object_around_task)
                                pass
                            for put_on_object_dir_info in put_on_object_dir_list:
                                new_object_freespace_task = Task(
                                    item=item_node,
                                    destination=place_platform,
                                    type=TaskType.MOVE_TO_OBJECT_FREESPACE_9_GRID,
                                    feature=[
                                        put_on_object_dir_info[0],
                                        put_on_object_dir_info[1],
                                    ],
                                    goal_translation=np.append(
                                        put_on_object_dir_dict[put_on_object_dir_info],
                                        [goal_translation_height],
                                    ),
                                    need_merge_freespace=not place_platform.single_freespace_available(
                                        item_node,
                                        single_type=[
                                            put_on_object_dir_info[0],
                                            (
                                                NINE_DIRECTIONS.index(
                                                    put_on_object_dir_info[1]
                                                )
                                                + available_directions[0]
                                            )
                                            % 8,
                                        ],
                                    ),
                                )
                                self.tasks.append(new_object_freespace_task)
                                pass
                            for put_between_2_object_info in put_between_2_object_list:
                                new_object_between_task = Task(
                                    item=item_node,
                                    destination=place_platform,
                                    type=TaskType.MOVE_TO_MIDDLE_OF_OBJECTS,
                                    feature=[
                                        put_between_2_object_info[0],
                                        put_between_2_object_info[1],
                                    ],
                                    goal_translation=np.append(
                                        put_between_2_object_dict[
                                            put_between_2_object_info
                                        ],
                                        [goal_translation_height],
                                    ),
                                    need_merge_freespace=not place_platform.single_freespace_available(
                                        item_node, single_type=put_between_2_object_info
                                    ),
                                )
                                self.tasks.append(new_object_between_task)

                            pass
                        pass
                    else:
                        place_platform_convex_hull_2d = place_platform.convex_hull_2d
                        place_platform_bounding_box = (
                            place_platform_convex_hull_2d.get_headed_bbox_instance()
                        )

                        if "wholetable" in result:
                            new_empty_platform_task = Task(
                                item=item_node,
                                destination=place_platform,
                                type=TaskType.MOVE_TO_EMPTY_PLATFORM,
                                feature=None,
                                goal_translation=np.append(
                                    place_platform.get_dir_point(
                                        dir="center", item_node=item_node
                                    ),
                                    [goal_translation_height],
                                ),
                                need_merge_freespace=not place_platform.single_freespace_available(
                                    item_node, single_type="empty"
                                ),
                            )
                            self.tasks.append(new_empty_platform_task)
                        if "center" in result:
                            for i in range(9):
                                new_empty_platform_task = Task(
                                    item=item_node,
                                    destination=place_platform,
                                    type=TaskType.MOVE_TO_EMPTY_PLATFORM_9_GRID,
                                    feature=[NINE_DIRECTIONS[i]],
                                    goal_translation=np.append(
                                        place_platform.get_dir_point(
                                            dir=(
                                                NINE_DIRECTIONS[
                                                    (i + available_directions[0]) % 8
                                                ]
                                                if i < 8
                                                else "center"
                                            ),
                                            item_node=item_node,
                                        ),
                                        [goal_translation_height],
                                    ),
                                    need_merge_freespace=not place_platform.single_freespace_available(
                                        item_node, single_type="empty"
                                    ),
                                )
                                self.tasks.append(new_empty_platform_task)
                        pass

                    pass
        glog.info(
            f"Task generation finished, {len(self.tasks)} tasks generated, lasts {time.perf_counter() - ts} seconds"
        )
        return self.tasks


def main():
    pass


# scene_graph = SceneGraphTree()
# scene_graph.parse_tree_from_file()
# scene_graph.print_tree(scene_graph.root)
# scene_graph.parse_node_details_from_file()

# atomic_motions = TaskGeneration(scene_graph)
# atomic_motions.generate_items_and_places()
# $atomic_motions.generate_tasks()

if __name__ == "__main__":
    main()
    pass