forked from NextCenturyCorporation/mcs-scene-generator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
interactive_hypercubes.py
2095 lines (1886 loc) · 82.4 KB
/
interactive_hypercubes.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
import copy
import logging
import random
import uuid
from typing import Any, Callable, Dict, List, Optional, Tuple
import containers
import exceptions
import geometry
from interactive_goals import InteractiveGoal, RetrievalGoal
from interactive_plans import InteractivePlan, ObjectLocationPlan, \
ObjectPlan, create_container_hypercube_plan_list, \
create_obstacle_hypercube_plan_list, create_occluder_hypercube_plan_list
import materials
import objects
from object_data import ObjectData, ReceptacleData, TargetData, \
identify_larger_definition
import separating_axis_theorem
import hypercubes
import tags
import util
LAST_STEP = 10000
SMALL_CONTEXT_OBJECT_CHOICES = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
SMALL_CONTEXT_OBJECT_WEIGHTS = [5, 5, 10, 10, 12.5, 15, 12.5, 10, 10, 5, 5]
WALL_CHOICES = [0, 1, 2, 3]
WALL_WEIGHTS = [40, 30, 20, 10]
WALL_MAX_WIDTH = 4
WALL_MIN_WIDTH = 1
WALL_Y = 1.5
WALL_HEIGHT = 3
WALL_DEPTH = 0.1
WALL_SEPARATION = 1
def retrieve_definition_lists(
original_definition_list: List[Dict[str, Any]],
object_type: str
) -> Tuple[List[Dict[str, Any]], List[Dict[str, Any]]]:
"""Return the trained and untrained shape definition lists."""
complete_definition_list = util.retrieve_complete_definition_list(
original_definition_list
)
trained_definition_list = util.retrieve_trained_definition_list(
complete_definition_list
)
untrained_definition_list = util.retrieve_untrained_definition_list(
complete_definition_list,
tags.SCENE.UNTRAINED_SHAPE
)
return trained_definition_list, untrained_definition_list
class InteractiveHypercube(hypercubes.Hypercube):
"""A hypercube of interactive scenes that each have the same goals,
targets, distractors, walls, materials, and performer starts, except for
specific differences detailed in its plan."""
def __init__(
self,
body_template: Dict[str, Any],
goal: InteractiveGoal,
role_to_type: Dict[str, str],
plan_name: str,
plan_list: List[InteractivePlan],
training=False
) -> None:
self._goal = goal
self._plan_list = plan_list
self._role_to_type = role_to_type
self._initialize_object_data()
self._validate_object_plan()
super().__init__(
goal.get_name() + ((' ' + plan_name) if plan_name else ''),
body_template,
goal.get_goal_template(),
training=training
)
def _initialize_object_data(self) -> None:
# Save each possible object's plans across all scenes.
self._data = {
'target': [TargetData(self._plan_list[0].target_plan, 0)],
'confusor': [
ObjectData(tags.ROLES.CONFUSOR, object_plan) for object_plan
in self._plan_list[0].confusor_plan_list
],
'large_container': [
ReceptacleData(tags.ROLES.CONTAINER, object_plan)
for object_plan in self._plan_list[0].large_container_plan_list
],
'obstacle': [
ReceptacleData(tags.ROLES.OBSTACLE, object_plan)
for object_plan in self._plan_list[0].obstacle_plan_list
],
'occluder': [
ReceptacleData(tags.ROLES.OCCLUDER, object_plan)
for object_plan in self._plan_list[0].occluder_plan_list
],
'small_container': [
ReceptacleData(tags.ROLES.CONTAINER, object_plan)
for object_plan in self._plan_list[0].small_container_plan_list
]
}
# Assume that each object has a plan in each scene. An object that does
# not appear in a scene should be given a NONE location plan.
for scene_plan in self._plan_list[1:]:
for role, object_plan_list in scene_plan.object_plans().items():
for index, object_plan in enumerate(object_plan_list):
self._data[role][index].append_object_plan(object_plan)
# Assume only one target plan, and always use the index 0 target.
self._target_data = self._data['target'][0]
# Assume only zero or one confusor plan.
self._confusor_data = (
self._data['confusor'][0] if len(self._data['confusor']) > 0
else None
)
def _validate_object_plan(self) -> None:
if any([
scene_plan.target_plan.definition !=
self._target_data.original_definition
for scene_plan in self._plan_list
]):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle a target with '
'different definitions across scenes')
if any(self._target_data.untrained_plan_list):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle a target with '
'a randomly chosen (not pre-defined) untrained shape')
# Update _assign_each_object_location to handle new location plans.
for object_data in self._data['target']:
if (
object_data.is_between() or object_data.is_far()
):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle the '
'target location plans: BETWEEN, FAR')
for object_data in self._data['confusor']:
if (
object_data.is_between() or object_data.is_random()
):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle the '
'confusor location plans: BETWEEN, RANDOM')
for object_data in (
self._data['large_container'] + self._data['small_container']
):
if (
object_data.is_back() or object_data.is_between() or
object_data.is_close() or object_data.is_far() or
object_data.is_front() or object_data.is_inside()
):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle the '
'container location plans: BACK, BETWEEN, CLOSE, FAR, '
'FRONT, INSIDE')
for object_data in (self._data['obstacle'] + self._data['occluder']):
if (
object_data.is_back() or object_data.is_far() or
object_data.is_front() or object_data.is_inside()
):
raise exceptions.SceneException(
'Interactive hypercubes cannot currently handle the '
'obstacle or occluder location plans: BACK, FAR, FRONT, '
'INSIDE')
# Override
def _create_scenes(
self,
body_template: Dict[str, Any],
goal_template: Dict[str, Any]
) -> List[Dict[str, Any]]:
tries = 0
while True:
tries += 1
try:
logging.debug(
f'\n\n{self.get_name()} initialize scenes try {tries}\n')
# Reset the half-finished scenes, all of their objects, and
# their other properties on each try.
scenes = [
copy.deepcopy(body_template) for _
in range(len(self._plan_list))
]
for object_data_list in self._data.values():
for object_data in object_data_list:
object_data.reset_all_properties()
# Save the bounds of each object in each of its possible
# locations across all the scenes to detect collisions with
# any subsequently positioned objects.
self._bounds_list = []
# Save the targets used in the hypercube that are not defined
# by the plan, if the goal has multiple targets.
self._common_target_list = []
# Save the interior walls used in the hypercube.
self._interior_wall_list = []
# Save the performer's start location in the hypercube.
self._performer_start = self._generate_performer_start()
# Save the small context objects used in the hypercube.
self._small_context_object_list = []
# Initialize all of the objects in all of the scenes.
self._initialize_each_hypercube_object()
# Update each scene's template with its corresponding objects,
# goal, tags, and other specific properties.
for index, scene in enumerate(scenes):
self._update_scene_at_index(scene, index, goal_template)
logging.debug(
f'\n\n{self.get_name()} initialize scenes is done\n ')
scenes = self._update_floor(body_template, scenes)
break
except exceptions.SceneException:
logging.exception(
f'{self.get_name()} _initialize_each_hypercube_object')
if tries >= util.MAX_TRIES:
raise exceptions.SceneException(
f'{self.get_name()} cannot successfully initialize scenes '
f'-- please redo.')
return scenes
# Override
def _get_training_scenes(self) -> List[Dict[str, Any]]:
return [scene for scene in self._scenes if not scene['evaluationOnly']]
def _assign_confusor_obstacle_occluder_location(
self,
target_data: TargetData,
target_or_receptacle_definition: Dict[str, Any],
confusor_data: Optional[ObjectData],
obstacle_occluder_data_list: List[ObjectData],
large_container_data_list: List[ReceptacleData],
goal: InteractiveGoal,
performer_start: Dict[str, Dict[str, float]],
bounds_list: List[List[Dict[str, float]]],
plans_to_locations: Dict[ObjectLocationPlan, List[Dict[str, Any]]]
) -> None:
"""Generate and assign locations to the given confusor, obstacle, and
occluder objects, if needed. Will update the given bounds_list."""
# Objects positioned relative to the target (confusors, obstacles, and
# occluders) must each choose new locations for each of the target's
# distinct locations (or its receptacle's locations) across scenes.
target_locations_with_indexes = (
target_data.locations_with_indexes(large_container_data_list)
)
# Next, choose a location for an obstacle/occluder either between the
# performer's start location and the target or behind the target (if
# needed). Assume only one obstacle or occluder is ever "in between"
# OR "close" in a single scene.
for target_location_plan, indexes in target_locations_with_indexes:
for object_data in obstacle_occluder_data_list:
is_obstacle = (object_data.role == tags.ROLES.OBSTACLE)
if object_data.is_between():
# Use the same location for the object across scenes in
# which the target is in this specific location.
self._assign_single_obstacle_occluder_location(
object_data,
target_or_receptacle_definition,
plans_to_locations[target_location_plan],
performer_start,
bounds_list,
'between',
object_data.assign_location_between,
indexes,
obstruct=(not is_obstacle),
unreachable=is_obstacle
)
if object_data.is_close():
# Use the same location for the object across scenes in
# which the target is in this specific location.
self._assign_single_obstacle_occluder_location(
object_data,
target_or_receptacle_definition,
plans_to_locations[target_location_plan],
performer_start,
bounds_list,
'behind',
object_data.assign_location_close,
indexes,
behind=True
)
if object_data.is_random():
# Use the same location for the object across scenes in
# which the target is in this specific location.
location = self._generate_random_location(
object_data.trained_definition,
goal,
performer_start,
bounds_list,
target_location=(
plans_to_locations[target_location_plan]
),
second_definition=object_data.untrained_definition
)
logging.debug(
f'{self.get_name()} obstacle/occluder location '
f'randomly chosen but not obstructing target: '
f'{location}')
bounds = object_data.assign_location_random(location)
bounds_list.extend(bounds)
# Next, choose a location for the confusor, close to or far from the
# target (if needed).
if confusor_data:
for target_location_plan, indexes in target_locations_with_indexes:
if confusor_data.is_close():
# Use the same location for the object across scenes in
# which the target is in this specific location.
location = self._generate_close_to(
confusor_data.larger_definition(),
target_or_receptacle_definition,
plans_to_locations[target_location_plan],
performer_start,
bounds_list,
adjacent=True
)
logging.debug(
f'{self.get_name()} confusor location close to: '
f'{location}')
bounds = confusor_data.assign_location_close(
location,
indexes
)
bounds_list.extend(bounds)
if confusor_data.is_far():
# Use the same location for the object across scenes in
# which the target is in this specific location.
location = self._generate_far_from(
confusor_data.larger_definition(),
plans_to_locations[target_location_plan],
performer_start,
bounds_list
)
logging.debug(
f'{self.get_name()} confusor location far from: '
f'{location}')
bounds = confusor_data.assign_location_far(
location,
indexes
)
bounds_list.extend(bounds)
def _assign_container_location(
self,
container_data_list: List[ReceptacleData],
goal: InteractiveGoal,
performer_start: Dict[str, Dict[str, float]],
bounds_list: List[List[Dict[str, float]]]
) -> None:
"""Generate and assign locations to the given container receptacle
objects, if needed. Will update the given bounds_list."""
# Next, choose the locations for the remaining containers (if needed).
for container_data in container_data_list:
if container_data.is_random():
# Use the same location for the object across scenes in which
# the object is randomly positioned.
location = self._generate_random_location(
container_data.larger_definition(),
goal,
performer_start,
bounds_list
)
logging.debug(
f'{self.get_name()} container location randomly chosen: '
f'{location}')
bounds = container_data.assign_location_random(location)
bounds_list.extend(bounds)
def _assign_front_and_back_location(
self,
target_data: TargetData,
target_or_receptacle_definition: Dict[str, Any],
confusor_data_list: List[ObjectData],
bounds_list: List[List[Dict[str, float]]]
) -> Dict[ObjectLocationPlan, List[Dict[str, Any]]]:
"""Generate and assign front and back locations to the given target and
confusor objects, if needed. Will update the given bounds_list. Return
the target's location corresponding to each unique location plan."""
# Save the target's location corresponding to each location plan.
plans_to_locations = {}
front_and_back_object_data_list = [target_data] + confusor_data_list
if any([
(object_data.is_front() or object_data.is_back()) for object_data
in front_and_back_object_data_list
]):
# Assume only one object is ever "in front" and only one object
# is ever "in back" in a single scene, so use the same front and
# back locations on each relevant object.
location_front, location_back = self._generate_front_and_back(
target_or_receptacle_definition,
target_data.choice
)
logging.debug(
f'{self.get_name()} location in front of performer start:'
f'{location_front}')
logging.debug(
f'{self.get_name()} location in back of performer start:'
f'{location_back}')
for object_data in front_and_back_object_data_list:
bounds = object_data.assign_location_front(location_front)
bounds_list.extend(bounds)
bounds = object_data.assign_location_back(location_back)
bounds_list.extend(bounds)
plans_to_locations[ObjectLocationPlan.FRONT] = location_front
plans_to_locations[ObjectLocationPlan.BACK] = location_back
# We assume the performer_start won't be modified past here.
logging.debug(
f'{self.get_name()} performer start: {self._performer_start}')
return plans_to_locations
def _assign_object_location_inside_container(
self,
target_data: TargetData,
confusor_data: Optional[ObjectData],
large_container_data_list: List[ReceptacleData]
) -> None:
"""Generate and assign locations to the given target and confusor
objects inside the given container objects, if needed. Will update the
given bounds_list."""
target_contained_indexes = target_data.contained_indexes(
large_container_data_list,
confusor_data
)
# Finally, position the target and confusor inside containers.
for index, container_data, confusor_data in target_contained_indexes:
# Create a new instance of each object to use in this scene.
target_instance = copy.deepcopy(target_data.trained_template)
containment = (
container_data.untrained_containment
if container_data.untrained_plan_list[index]
else container_data.trained_containment
)
# If confusor_data is None, put just the target in the container.
if not confusor_data:
containers.put_object_in_container(
target_instance,
container_data.instance_list[index],
containment.area_index,
containment.target_angle
)
# Else, put both the target and confusor together in the container.
else:
confusor_instance = copy.deepcopy(
confusor_data.untrained_template
if confusor_data.untrained_plan_list[index]
else confusor_data.trained_template
)
containers.put_objects_in_container(
target_instance,
confusor_instance,
container_data.instance_list[index],
containment.area_index,
containment.orientation,
containment.target_angle,
containment.confusor_angle
)
# Save the confusor instance in the hypercube data.
confusor_data.instance_list[index] = confusor_instance
# Save the target instance in the hypercube data.
target_data.instance_list[index] = target_instance
confusor_contained_indexes = confusor_data.contained_indexes(
large_container_data_list,
target_data
) if confusor_data else []
for index, container_data, target_data in confusor_contained_indexes:
# Create a new instance of each object to use in this scene.
confusor_instance = copy.deepcopy(
confusor_data.untrained_template
if confusor_data.untrained_plan_list[index]
else confusor_data.trained_template
)
# If target_data is None, put just the confusor in the container.
if not target_data:
containers.put_object_in_container(
confusor_instance,
container_data.instance_list[index],
container_data.area_index,
container_data.confusor_angle
)
# Save the confusor instance in the hypercube data.
confusor_data.instance_list[index] = confusor_instance
# Else, we already put both objects together in a container, above.
def _assign_single_obstacle_occluder_location(
self,
obstacle_occluder_data: ObjectData,
target_or_receptacle_definition: Dict[str, Any],
target_location: Dict[str, Any],
performer_start: Dict[str, Dict[str, float]],
bounds_list: List[List[Dict[str, float]]],
debug_label: str,
location_function: Callable,
indexes: List[float],
behind: bool = False,
obstruct: bool = False,
unreachable: bool = False
) -> None:
"""Generate and assign new locations to a single given obstacle or
occluder using the given function either obstructing or behind the
target. Find separate locations for both the trained and the untrained
definitions because each must be able to obstruct the target."""
trained_location = self._generate_close_to(
obstacle_occluder_data.trained_definition,
target_or_receptacle_definition,
target_location,
performer_start,
bounds_list,
behind=behind,
obstruct=obstruct,
unreachable=unreachable
)
logging.debug(
f'{self.get_name()} trained obstacle/occluder location '
f'{debug_label} target and performer start: {trained_location}')
untrained_location = self._generate_close_to(
obstacle_occluder_data.untrained_definition,
target_or_receptacle_definition,
target_location,
performer_start,
bounds_list,
behind=behind,
obstruct=obstruct,
unreachable=unreachable
)
logging.debug(
f'{self.get_name()} untrained obstacle/occluder location '
f'{debug_label} target and performer start: {untrained_location}')
bounds_trained = location_function(trained_location, [
index for index in indexes
if not obstacle_occluder_data.untrained_plan_list[index]
])
bounds_list.extend(bounds_trained)
bounds_untrained = location_function(untrained_location, [
index for index in indexes
if obstacle_occluder_data.untrained_plan_list[index]
])
bounds_list.extend(bounds_untrained)
def _assign_target_location(
self,
target_data: TargetData,
target_or_receptacle_definition: Dict[str, Any],
container_data: Optional[ReceptacleData],
confusor_data_list: List[ObjectData],
goal: InteractiveGoal,
performer_start: Dict[str, Dict[str, float]],
bounds_list: List[List[Dict[str, float]]]
) -> Dict[ObjectLocationPlan, List[Dict[str, Any]]]:
"""Generate and assign locations to the given target, as well as the
given target's receptacle and confusor objects if needed. Will update
the given bounds_list. Return the target's location corresponding to
each unique location plan."""
# First, choose the locations for the objects positioned relative to
# the performer's start location (if needed), both in front of it and
# in back of it. Do FIRST because it may change performer_start.
plans_to_locations = self._assign_front_and_back_location(
target_data,
target_or_receptacle_definition,
confusor_data_list,
bounds_list
)
# Next, choose the locations for the target's container (if needed).
target_container_location = None
if container_data and container_data.is_random():
# Use the same location for the object across scenes in which
# the object is randomly positioned.
target_container_location = self._generate_random_location(
container_data.larger_definition(),
goal,
performer_start,
bounds_list
)
logging.debug(
f'{self.get_name()} container location randomly chosen: '
f'{target_container_location}')
bounds = container_data.assign_location_random(
target_container_location
)
bounds_list.extend(bounds)
# Next, choose a location close to the target's container (if any).
# Assume a "close" target is always close to its container.
if target_data.is_close():
target_definition = target_data.larger_definition()
# If the target was turned sideways, revert it for the location
# close to the target's container.
if target_definition.get('notSideways', None):
target_definition = copy.deepcopy(target_definition)
target_definition['dimensions'] = (
target_definition['notSideways']['dimensions']
)
target_definition['offset'] = (
target_definition['notSideways'].get('offset', {})
)
target_definition['positionY'] = (
target_definition['notSideways'].get('positionY', 0)
)
target_definition['rotation'] = (
target_definition['notSideways'].get('rotation', {})
)
location = self._generate_close_to(
target_definition,
container_data.larger_definition(),
target_container_location,
performer_start,
bounds_list
)
logging.debug(
f'{self.get_name()} target location close to the first '
f'large container: {location}')
bounds = target_data.assign_location_close(
location,
None
)
bounds_list.extend(bounds)
plans_to_locations[ObjectLocationPlan.CLOSE] = location
# Next, handle the remaining cases for choosing the target's location.
if target_data.is_random():
# Use the same location for the target across scenes in which the
# target is positioned randomly.
location = self._generate_random_location(
target_or_receptacle_definition,
goal,
performer_start,
bounds_list,
target_choice=target_data.choice
)
logging.debug(
f'{self.get_name()} target location randomly chosen: '
f'{location}')
bounds = target_data.assign_location_random(location)
bounds_list.extend(bounds)
plans_to_locations[ObjectLocationPlan.RANDOM] = location
return plans_to_locations
def _assign_each_object_location(self) -> None:
"""Assign each object's final location in all of the scenes by creating
separate instances of them to use in each individual scene."""
# Use the larger definition of the target or its receptacle in any
# scene to save a big enough area for all objects.
larger_target_definition = self._target_data.larger_definition_of(
self._data['large_container'],
self._confusor_data
)
logging.debug(
f'{self.get_name()} larger definition of trained/untrained '
f'target/confusor/container: {larger_target_definition}')
# Save the target's location corresponding to each location plan.
target_location_plans_to_locations = self._assign_target_location(
self._target_data,
larger_target_definition,
# Assume the 1st large container may have the target inside of it.
self._data['large_container'][0]
if len(self._data['large_container']) > 0 else None,
self._data['confusor'],
self._goal,
self._performer_start,
self._bounds_list
)
self._assign_confusor_obstacle_occluder_location(
self._target_data,
larger_target_definition,
self._confusor_data,
self._data['obstacle'] + self._data['occluder'],
self._data['large_container'],
self._goal,
self._performer_start,
self._bounds_list,
target_location_plans_to_locations
)
self._assign_container_location(
# Assume the 1st large container may have the target inside of it,
# and thus it will have been positioned previously, but the other
# containers will not have any objects inside of them.
self._data['large_container'][1:] + self._data['small_container'],
self._goal,
self._performer_start,
self._bounds_list
)
self._assign_object_location_inside_container(
self._target_data,
self._confusor_data,
self._data['large_container']
)
def _assign_confusor_definition(
self,
confusor_data: Optional[ObjectData],
target_definition: Dict[str, Any]
) -> None:
"""Update the given confusor data with its object definition using the
given target data."""
if not confusor_data:
return
trained_list, untrained_list = retrieve_definition_lists(objects.get(
objects.ObjectDefinitionList.ALL
), None)
if not confusor_data.trained_definition:
confusor_data.trained_definition = util.get_similar_definition(
target_definition,
trained_list
)
if not confusor_data.trained_definition:
raise exceptions.SceneException(
f'{self.get_name()} cannot find trained confusor '
f'definition_list_length={len(trained_list)} '
f'target={target_definition}')
if not confusor_data.untrained_definition:
confusor_data.untrained_definition = util.get_similar_definition(
target_definition,
untrained_list
)
if not confusor_data.untrained_definition:
raise exceptions.SceneException(
f'{self.get_name()} cannot find untrained confusor '
f'definition_list_length={len(untrained_list)} '
f'target={target_definition}')
logging.debug(
f'{self.get_name()} confusor definition: '
f'trained={confusor_data.trained_definition}'
f'untrained={confusor_data.untrained_definition}')
def _choose_small_context_definition(
self,
target_confusor_data_list: List[ObjectData]
) -> Dict[str, Any]:
"""Choose and return a small context object definition for the given
target and confusor objects from the given definition list."""
return util.choose_distractor_definition([
object_data.trained_definition for object_data
in target_confusor_data_list
] + [
object_data.untrained_definition for object_data
in target_confusor_data_list if object_data.untrained_definition
])
def _assign_obstacle_or_occluder_definition(
self,
object_data: ObjectData,
target_definition: Dict[str, Any],
is_occluder: bool
) -> None:
"""Update the given obstacle or occluder data with its object
definition using the given target data."""
role = tags.ROLES.OCCLUDER if is_occluder else tags.ROLES.OBSTACLE
trained_list, untrained_list = retrieve_definition_lists(objects.get(
objects.ObjectDefinitionList.OCCLUDERS if is_occluder else
objects.ObjectDefinitionList.OBSTACLES
), self._role_to_type[role])
if not object_data.trained_definition:
object_data.trained_definition = (
self._choose_obstacle_or_occluder_definition(
target_definition,
trained_list,
is_occluder
)
)
if not object_data.untrained_definition:
object_data.untrained_definition = (
self._choose_obstacle_or_occluder_definition(
target_definition,
untrained_list,
is_occluder
)
)
logging.debug(
f'{self.get_name()} {"occluder" if is_occluder else "obstacle"} '
f'definition: trained={object_data.trained_definition} '
f'untrained={object_data.untrained_definition}')
def _choose_obstacle_or_occluder_definition(
self,
target_definition: Dict[str, Any],
nested_definition_list: List[List[Dict[str, Any]]],
is_occluder: bool
) -> Dict[str, Any]:
"""Choose and return an obstacle or occluder definition for the given
target object from the given definition list."""
obstacle_occluder_definition_list = (
geometry.retrieve_obstacle_occluder_definition_list(
target_definition,
nested_definition_list,
is_occluder
)
)
if not obstacle_occluder_definition_list:
raise exceptions.SceneException(
f'{self.get_name()} cannot find '
f'{"occluder" if is_occluder else "obstacle"} '
f'definition_list_length={len(nested_definition_list)} '
f'target={target_definition}')
definition, angle = random.choice(random.choice(
obstacle_occluder_definition_list
))
if 'rotation' not in definition:
definition['rotation'] = {
'x': 0,
'y': 0,
'z': 0
}
# Note that this rotation must be also modified with the final
# performer start Y.
definition['rotation']['y'] += angle
return definition
def _assign_container_definition(
self,
container_data: ReceptacleData,
target_data: TargetData,
confusor_data: Optional[ObjectData],
find_invalid_container: bool = False
) -> None:
"""Update the given container data with its object definition using the
given target and confusor data and whether it should be a valid or an
invalid size to fit either or both of the objects inside of it."""
trained_list, untrained_list = retrieve_definition_lists(objects.get(
objects.ObjectDefinitionList.CONTAINERS
), self._role_to_type[tags.ROLES.CONTAINER])
if not container_data.trained_definition:
(
definition,
area_index,
orientation,
target_angle,
confusor_angle
) = self._choose_container_definition(
target_data,
confusor_data,
confusor_data.trained_definition if confusor_data else None,
trained_list,
find_invalid_container
)
container_data.trained_definition = definition
container_data.trained_containment.area_index = area_index
container_data.trained_containment.orientation = orientation
container_data.trained_containment.target_angle = target_angle
container_data.trained_containment.confusor_angle = confusor_angle
if not container_data.untrained_definition:
(
definition,
area_index,
orientation,
target_angle,
confusor_angle
) = self._choose_container_definition(
target_data,
confusor_data,
confusor_data.untrained_definition if confusor_data else None,
untrained_list,
find_invalid_container
)
container_data.untrained_definition = definition
container_data.untrained_containment.area_index = area_index
container_data.untrained_containment.orientation = orientation
container_data.untrained_containment.target_angle = target_angle
container_data.untrained_containment.confusor_angle = (
confusor_angle
)
logging.debug(
f'{self.get_name()} container definition: '
f'trained={container_data.trained_definition} '
f'untrained={container_data.untrained_definition}')
def _choose_container_definition(
self,
target_data: TargetData,
confusor_data: Optional[ObjectData],
confusor_definition: Optional[Dict[str, Any]],
nested_definition_list: List[List[Dict[str, Any]]],
find_invalid_container: bool = False,
) -> Tuple[Dict[str, Any], int, containers.Orientation, float, float]:
"""Choose and return a valid or an invalid container definition for the
given target and confusor objects from the given definition list."""
container_definition = None
area_index = None
orientation = None
target_angle = None
confusor_angle = None
target_definition_list = [target_data.trained_definition]
# Also try the target definition's sideways option if it exists.
if target_data.trained_definition.get('sideways'):
sideways = copy.deepcopy(target_data.trained_definition)
# Save the original properties.
sideways['notSideways'] = {
'dimensions': sideways['dimensions'],
'offset': sideways.get('offset', {}),
'positionY': sideways.get('positionY', 0),
'rotation': sideways.get('rotation', {})
}
# Override the original properties with the sideways properties.
sideways['dimensions'] = sideways['sideways']['dimensions']
sideways['offset'] = sideways['sideways'].get('offset', {})
sideways['positionY'] = sideways['sideways'].get('positionY', 0)
sideways['rotation'] = sideways['sideways'].get('rotation', {})
sideways['sideways'] = None
target_definition_list.append(sideways)
# If needed, find an enclosable container that can hold both the
# target and the confusor together.
if target_data.containerize_with(confusor_data):
for definition_list in nested_definition_list:
for definition in definition_list:
for target_definition in target_definition_list:
valid_containment = containers.can_contain_both(
definition,
target_definition,
confusor_definition
)
if valid_containment and not find_invalid_container:
target_data.trained_definition = target_definition
container_definition = definition
area_index, angles, orientation = valid_containment
target_angle = angles[0]
confusor_angle = angles[1]
break
elif not valid_containment and find_invalid_container:
target_data.trained_definition = target_definition
container_definition = definition
break
# Else, find an enclosable container that can hold either the target
# or confusor individually.
else:
confusor_definition_or_none = (
confusor_definition if confusor_data and
confusor_data.is_inside() else None
)
if not target_data.is_inside():
target_definition_list = [None]
for definition_list in nested_definition_list:
for definition in definition_list:
for target_definition in target_definition_list:
valid_containment = containers.can_contain(
definition,
target_definition,