-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathARCGraph.py
1557 lines (1467 loc) · 66.2 KB
/
ARCGraph.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 networkx as nx
import matplotlib.pyplot as plt
from itertools import combinations
import numpy as np
from utils import *
from filters import *
from transform import *
from task import *
import itertools
from typing import *
from OEValuesManager import *
from VocabMaker import *
class ARCGraph:
def __init__(self, graph, name, image, abstraction=None):
self.graph = graph
self.image = image
self.grid_size = self.image.image_size[0] * self.image.image_size[1]
self.abstraction = abstraction
if abstraction is None:
self.name = name
elif abstraction in name.split("_"):
self.name = name
else:
self.name = name + "_" + abstraction
if self.abstraction in image.multicolor_abstractions:
self.is_multicolor = True
self.most_common_color = 0
self.least_common_color = 0
else:
self.is_multicolor = False
self.most_common_color = image.most_common_color
self.least_common_color = image.least_common_color
self.width = max([node[1] for node in self.image.graph.nodes()]) + 1
self.height = max([node[0] for node in self.image.graph.nodes()]) + 1
self.task_id = name.split("_")[0]
# ------------------------------------------ transformations ------------------------------------------
def NoOp(self, node):
return self
def UpdateColor(self, node, color: Color):
"""
update node color to given color
"""
if color == "most":
color = self.most_common_color
elif color == "least":
color = self.least_common_color
color_map = {
"O": 0,
"B": 1,
"R": 2,
"G": 3,
"Y": 4,
"X": 5,
"F": 6,
"A": 7,
"C": 8,
"W": 9,
"most": self.most_common_color,
"least": self.least_common_color
}
if self.is_multicolor:
if isinstance(color, Tuple):
self.graph.nodes[node]["color"] = [self.get_color(color)] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
elif not isinstance(color, int):
self.graph.nodes[node]["color"] = [color_map[color]] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
else:
self.graph.nodes[node]["color"] = [color] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
else:
if isinstance(color, Tuple):
self.graph.nodes[node]["color"] = self.get_color(color)
elif not isinstance(color, int):
self.graph.nodes[node]["color"] = color_map[color]
else:
self.graph.nodes[node]["color"] = color
return self
def MoveNode(self, node, direction: Dir, n: Height = 1):
"""
move node by 1 pixel in a given direction
"""
assert direction is not None
ogpixels = set() # list of pixels which should go back to their original color!
updated_sub_nodes = set()
delta_x = 0
delta_y = 0
if direction == "UP" or direction == Dir.UP:
delta_y = -n
elif direction == "DOWN" or direction == Dir.DOWN:
delta_y = n
elif direction == "LEFT" or direction == Dir.LEFT:
delta_x = -n
elif direction == "RIGHT" or direction == Dir.RIGHT:
delta_x = n
elif direction == Dir.DOWN_RIGHT or direction == "DOWN_RIGHT":
delta_x = n
delta_y = n
elif direction == Dir.DOWN_LEFT or direction == "DOWN_LEFT":
delta_y = n
delta_x = -n
elif direction == Dir.UP_LEFT or direction == "UP_LEFT":
delta_x = -n
delta_y = -n
elif direction == Dir.UP_RIGHT or direction == "UP_RIGHT":
delta_x = n
delta_y = -n
for sub_node in self.graph.nodes[node]["nodes"]:
if sub_node[0] + delta_y == self.width or sub_node[1] + delta_x == self.height:
updated_sub_nodes.add((sub_node[0], sub_node[1]))
elif self.check_inbound((sub_node[0] + delta_y, sub_node[1] + delta_x)):
updated_sub_nodes.add(
(sub_node[0] + delta_y, sub_node[1] + delta_x))
for sub_node in self.graph.nodes[node]["nodes"]:
if (sub_node[0] + delta_y == sub_node[0] or sub_node[0] + delta_y == self.width) \
and (sub_node[1] + delta_x == sub_node[1] or sub_node[1] + delta_x == self.height) or sub_node in updated_sub_nodes:
continue
else:
ogpixels.add(sub_node)
if ogpixels:
new_node_id = self.generate_node_id(self.image.background_color)
if self.is_multicolor:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(ogpixels),
color=[self.image.background_color for _ in ogpixels],
size=len(ogpixels),
)
else:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(ogpixels),
color=self.image.background_color,
size=len(ogpixels),
)
self.graph.nodes[node]["nodes"] = updated_sub_nodes
self.graph.nodes[node]["size"] = len(updated_sub_nodes)
return self
def ExtendNode(self, node, direction: Dir, overlap: Overlap = False, n: int = 1):
"""
extend node in a given direction,
if overlap is true, extend node even if it overlaps with another node
if overlap is false, stop extending before it overlaps with another node
"""
assert direction is not None
updated_sub_nodes = []
delta_x = 0
delta_y = 0
if direction == "UP" or direction == Dir.UP:
delta_y = -n
elif direction == "DOWN" or direction == Dir.DOWN:
delta_y = n
elif direction == "LEFT" or direction == Dir.LEFT:
delta_x = -n
elif direction == "RIGHT" or direction == Dir.RIGHT:
delta_x = n
elif direction == Dir.DOWN_RIGHT or direction == "DOWN_RIGHT":
delta_x = n
delta_y = n
elif direction == Dir.DOWN_LEFT or direction == "DOWN_LEFT":
delta_y = n
delta_x = -n
elif direction == Dir.UP_LEFT or direction == "UP_LEFT":
delta_x = -n
delta_y = -n
elif direction == Dir.UP_RIGHT or direction == "UP_RIGHT":
delta_x = n
delta_y = -n
for sub_node in self.graph.nodes[node]["nodes"]:
sub_node_y = sub_node[0]
sub_node_x = sub_node[1]
max_allowed = 1000
for foo in range(max_allowed):
updated_sub_nodes.append((sub_node_y, sub_node_x))
sub_node_y += delta_y
sub_node_x += delta_x
if overlap and not self.check_inbound((sub_node_y, sub_node_x)):
# if overlap allowed, stop extending node until hitting edge of image
break
elif not overlap and (
self.check_collision(node, [(sub_node_y, sub_node_x)])
or not self.check_inbound((sub_node_y, sub_node_x))
):
# if overlap not allowed, stop extending node until hitting edge of image or another node
break
self.graph.nodes[node]["nodes"] = list(set(updated_sub_nodes))
self.graph.nodes[node]["size"] = len(updated_sub_nodes)
return self
def MoveNodeMax(self, node, direction: Dir, n: int = 1):
"""
move node in a given direction until it hits another node or the edge of the image
"""
ogpixels = set() # list of pixels which should go back to their original color!
assert direction is not None
delta_x = 0
delta_y = 0
if direction == "UP" or direction == Dir.UP:
delta_y = -n
elif direction == "DOWN" or direction == Dir.DOWN:
delta_y = n
elif direction == "LEFT" or direction == Dir.LEFT:
delta_x = -n
elif direction == "RIGHT" or direction == Dir.RIGHT:
delta_x = n
elif direction == Dir.DOWN_RIGHT or direction == "DOWN_RIGHT":
delta_x = n
delta_y = n
elif direction == Dir.DOWN_LEFT or direction == "DOWN_LEFT":
delta_y = n
delta_x = -n
elif direction == Dir.UP_LEFT or direction == "UP_LEFT":
delta_x = -n
delta_y = -n
elif direction == Dir.UP_RIGHT or direction == "UP_RIGHT":
delta_x = n
delta_y = -n
max_allowed = 1000
from copy import deepcopy
og_graph = deepcopy(self.graph.nodes[node]["nodes"])
for foo in range(max_allowed):
updated_nodes = set()
for sub_node in self.graph.nodes[node]["nodes"]:
updated_nodes.add(
(sub_node[0] + delta_y, sub_node[1] + delta_x))
if self.check_collision(node, updated_nodes) or not self.check_inbound(
list(updated_nodes)
):
break
self.graph.nodes[node]["nodes"] = list(updated_nodes)
for sub_node in og_graph:
if sub_node not in self.graph.nodes[node]["nodes"]:
ogpixels.add(sub_node)
if ogpixels:
if self.is_multicolor:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(ogpixels),
color=[self.image.background_color for _ in ogpixels],
size=len(ogpixels),
)
else:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(ogpixels),
color=self.image.background_color,
size=len(ogpixels),
)
return self
def RotateNode(self, node, rotation_dir: Rotation_Angle):
"""
rotates node around its center point in a given rotational direction
"""
mul = 0
rotate_times = 1
if rotation_dir == "270":
mul = -1
elif rotation_dir == "90":
mul = 1
elif rotation_dir == "180":
rotate_times = 2
mul = -1
# Check if the node size is zero or the nodes list is empty to prevent division by zero
if self.graph.nodes[node]["size"] == 0 or not self.graph.nodes[node]["nodes"]:
print("Cannot rotate node due to zero size or no subnodes.")
return self # Exit the function early
for t in range(rotate_times):
center_point = (
sum([n[0] for n in self.graph.nodes[node]["nodes"]])
// self.graph.nodes[node]["size"],
sum([n[1] for n in self.graph.nodes[node]["nodes"]])
// self.graph.nodes[node]["size"],
)
new_nodes = []
for sub_node in self.graph.nodes[node]["nodes"]:
new_sub_node = (
sub_node[0] - center_point[0],
sub_node[1] - center_point[1],
)
new_sub_node = (-new_sub_node[1] * mul, new_sub_node[0] * mul)
new_sub_node = (
new_sub_node[0] + center_point[0],
new_sub_node[1] + center_point[1],
)
if self.check_inbound(new_sub_node):
new_nodes.append(new_sub_node)
self.graph.nodes[node]["nodes"] = new_nodes
return self
def AddBorder(self, node, border_color: Color):
"""
add a border with thickness 1 and border_color around the given node
"""
delta = [-1, 0, 1]
border_pixels = []
for sub_node in self.graph.nodes[node]["nodes"]:
for x in delta:
for y in delta:
border_pixel = (sub_node[0] + y, sub_node[1] + x)
if border_pixel not in border_pixels and not self.check_pixel_occupied(border_pixel) and \
self.height > sub_node[0] + y >= 0 and self.width > sub_node[1] + x >= 0:
border_pixels.append(border_pixel)
color_map = {
"O": 0,
"B": 1,
"R": 2,
"G": 3,
"Y": 4,
"X": 5,
"F": 6,
"A": 7,
"C": 8,
"W": 9,
"most": self.most_common_color,
"least": self.least_common_color
}
if isinstance(border_color, Tuple):
border_color = self.get_color(border_color)
elif not isinstance(border_color, int):
border_color = color_map[border_color]
new_node_id = self.generate_node_id(border_color)
if self.is_multicolor:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(border_pixels),
color=[border_color for j in border_pixels],
size=len(border_pixels),
)
else:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(border_pixels),
color=border_color,
size=len(border_pixels),
)
return self
def FillRectangle(self, node, color: Color, overlap: Overlap = False):
"""
fill the rectangle containing the given node with the given color.
if overlap is True, fill the rectangle even if it overlaps with other nodes.
"""
if color == "same":
color = self.graph.nodes[node]["color"]
color_map = {
"O": 0,
"B": 1,
"R": 2,
"G": 3,
"Y": 4,
"X": 5,
"F": 6,
"A": 7,
"C": 8,
"W": 9,
"most": self.most_common_color,
"least": self.least_common_color
}
if isinstance(color, Tuple):
color = self.get_color(color)
elif not isinstance(color, int):
color = color_map[color]
all_x = [sub_node[1] for sub_node in self.graph.nodes[node]["nodes"]]
all_y = [sub_node[0] for sub_node in self.graph.nodes[node]["nodes"]]
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(self.graph.nodes[node]["nodes"]),
color=self.graph.nodes[node]["color"],
size=len(list(self.graph.nodes[node]["nodes"]))
)
if not all_x or not all_y: # Check if either list is empty
print("Cannot fill rectangle as node has no subnodes.")
return # Exit the function early if there are no subnodes
min_x, min_y, max_x, max_y = min(all_x), min(
all_y), max(all_x), max(all_y)
unfilled_pixels = []
for x in range(min_x, max_x + 1):
for y in range(min_y, max_y + 1):
pixel = (y, x)
if pixel not in self.graph.nodes[node]["nodes"]:
if overlap:
unfilled_pixels.append(pixel)
elif not self.check_pixel_occupied(pixel):
unfilled_pixels.append(pixel)
if len(unfilled_pixels) > 0:
new_node_id = self.generate_node_id(color)
if self.is_multicolor:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(unfilled_pixels),
color=[color for j in unfilled_pixels],
size=len(unfilled_pixels),
)
else:
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(unfilled_pixels),
color=color,
size=len(unfilled_pixels),
)
return self
def HollowRectangle(self, node, color: Color):
"""
hollowing the rectangle containing the given node with the given color.
"""
if not self.graph.nodes[node]["nodes"]: # Checks if the list of subnodes is empty
print("Node has no subnodes")
return
all_y = [n[0] for n in self.graph.nodes[node]["nodes"]]
all_x = [n[1] for n in self.graph.nodes[node]["nodes"]]
border_y = [min(all_y), max(all_y)]
border_x = [min(all_x), max(all_x)]
non_border_pixels = []
new_subnodes = []
color_map = {
"O": 0,
"B": 1,
"R": 2,
"G": 3,
"Y": 4,
"X": 5,
"F": 6,
"A": 7,
"C": 8,
"W": 9,
"most": self.most_common_color,
"least": self.least_common_color
}
if self.is_multicolor:
if not isinstance(color, int):
color = [color_map[color]] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
else:
color = [color] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
else:
if isinstance(color, Tuple):
color = self.get_color(color)
elif not isinstance(color, int):
color = color_map[color]
for subnode in self.graph.nodes[node]["nodes"]:
if subnode[0] in border_y or subnode[1] in border_x:
new_subnodes.append(subnode)
else:
non_border_pixels.append(subnode)
self.graph.nodes[node]["nodes"] = new_subnodes
# Updated the size parameter here
self.graph.nodes[node]["size"] = len(new_subnodes)
if color != self.image.background_color:
new_node_id = self.generate_node_id(color)
self.graph.add_node(
(node[0], node[1], 0),
nodes=list(non_border_pixels),
color=color,
size=len(non_border_pixels),
)
return self
def Mirror(self, node, mirror_axis: Mirror_Axis):
"""
mirroring a node with respect to the given axis.
mirror_axis takes the form of (y, x) where one of y, x equals None to
indicate the other being the axis of mirroring
"""
if mirror_axis[1] is None and mirror_axis[0] is not None:
axis = mirror_axis[0]
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_y = axis - (subnode[0] - axis)
new_x = subnode[1]
new_subnodes.append((new_y, new_x))
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
elif mirror_axis[0] is None and mirror_axis[1] is not None:
axis = mirror_axis[1]
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_y = subnode[0]
new_x = axis - (subnode[1] - axis)
new_subnodes.append((new_y, new_x))
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
return self
def Flip(self, node, mirror_direction: Symmetry_Axis):
"""
flips the given node given direction horizontal, vertical, diagonal left/right
"""
if not self.graph.nodes[node]["nodes"]: # Checks if the list is empty
print("No subnodes to flip")
return self # Exit the function as there's nothing to flip
if mirror_direction == "VERTICAL" or mirror_direction == Symmetry_Axis.VERTICAL: # todo: check sanity
max_y = max([subnode[0]
for subnode in self.graph.nodes[node]["nodes"]])
min_y = min([subnode[0]
for subnode in self.graph.nodes[node]["nodes"]])
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_y = max_y - (subnode[0] - min_y)
new_x = subnode[1]
if self.check_inbound((new_x, new_y)):
new_subnodes.append((new_y, new_x))
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
elif mirror_direction == "HORIZONTAL" or mirror_direction == Symmetry_Axis.HORIZONTAL:
max_x = max([subnode[1]
for subnode in self.graph.nodes[node]["nodes"]])
min_x = min([subnode[1]
for subnode in self.graph.nodes[node]["nodes"]])
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_y = subnode[0]
new_x = max_x - (subnode[1] - min_x)
if self.check_inbound((new_x, new_y)):
new_subnodes.append((new_y, new_x))
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
elif mirror_direction == "DIAGONAL_LEFT" or mirror_direction == Symmetry_Axis.DIAGONAL_LEFT: # \
min_x = min([subnode[1]
for subnode in self.graph.nodes[node]["nodes"]])
min_y = min([subnode[0]
for subnode in self.graph.nodes[node]["nodes"]])
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_subnode = (subnode[0] - min_y, subnode[1] - min_x)
new_subnode = (new_subnode[1], new_subnode[0])
new_subnode = (new_subnode[0] + min_y, new_subnode[1] + min_x)
if self.check_inbound(new_subnode):
new_subnodes.append(new_subnode)
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
elif mirror_direction == "DIAGONAL_RIGHT" or mirror_direction == Symmetry_Axis.DIAGONAL_RIGHT: # /
max_x = max([subnode[1]
for subnode in self.graph.nodes[node]["nodes"]])
min_y = min([subnode[0]
for subnode in self.graph.nodes[node]["nodes"]])
new_subnodes = []
for subnode in self.graph.nodes[node]["nodes"]:
new_subnode = (subnode[0] - min_y, subnode[1] - max_x)
new_subnode = (-new_subnode[1], -new_subnode[0])
new_subnode = (new_subnode[0] + min_y, new_subnode[1] + max_x)
if self.check_inbound(new_subnode):
new_subnodes.append(new_subnode)
if not self.check_collision(node, new_subnodes):
self.graph.nodes[node]["nodes"] = new_subnodes
return self
def Insert(
self, node, object_id, point: ImagePoints, relative_pos: RelativePosition
):
"""
insert some pattern identified by object_id at some location,
the location is defined as, the relative position between the given node and point.
for example, point=top, relative_pos=middle will insert the pattern between the given node
and the top of the image.
if object_id is -1, use the pattern given by node
"""
node_centroid = self.get_centroid(node)
if node_centroid is not None and (not isinstance(point, tuple)):
if point == "TOP" or point == ImagePoints.TOP:
point = (0, node_centroid[1])
elif point == "BOTTOM" or point == ImagePoints.BOTTOM:
point = (self.image.height - 1, node_centroid[1])
elif point == "LEFT" or point == ImagePoints.LEFT:
point = (node_centroid[0], 0)
elif point == "RIGHT" or point == ImagePoints.RIGHT:
point = (node_centroid[0], self.image.width - 1)
elif point == "TOP_LEFT" or point == ImagePoints.TOP_LEFT:
point = (0, 0)
elif point == "TOP_RIGHT" or point == ImagePoints.TOP_RIGHT:
point = (0, self.image.width - 1)
elif point == "BOTTOM_LEFT" or point == ImagePoints.BOTTOM_LEFT:
point = (self.image.height - 1, 0)
elif point == "BOTTOM_RIGHT" or point == ImagePoints.BOTTOM_RIGHT:
point = (self.image.height - 1, self.image.width - 1)
if object_id == -1:
# special id for dynamic objects, which uses the given nodes as objects
object = self.graph.nodes[node]
else:
object = self.image.task.static_objects_for_insertion[self.abstraction][
object_id
]
target_point = self.get_point_from_relative_pos(
node_centroid, point, relative_pos
)
object_centroid = self.get_centroid_from_pixels(object["nodes"])
subnodes_coords = []
for subnode in object["nodes"]:
delta_y = subnode[0] - object_centroid[0]
delta_x = subnode[1] - object_centroid[1]
if self.check_inbound((target_point[0] + delta_y, target_point[1] + delta_x)):
subnodes_coords.append(
(target_point[0] + delta_y, target_point[1] + delta_x)
)
new_node_id = self.generate_node_id(object["color"])
self.graph.add_node( # todo: side-effects
new_node_id,
nodes=list(subnodes_coords),
color=object["color"],
size=len(list(subnodes_coords)),
)
return self
def remove_node(self, node):
"""
remove a node from the graph
"""
self.graph.remove_node(node)
# ------------------------------------- filters ------------------------------------------
# filters take the form of filter(node, params), return true if node satisfies filter
def Color_Equals(self, color1: Color, color2: Color):
"""
return true if node has given color.
if exclude, return true if node does not have given color.
"""
color_map = {
"most": self.most_common_color,
"least": self.least_common_color,
"O": 0,
"B": 1,
"R": 2,
"G": 3,
"Y": 4,
"X": 5,
"F": 6,
"A": 7,
"C": 8,
"W": 9,
}
if isinstance(color2, Tuple): # object
color = self.graph.nodes[color2]["color"]
else:
color = color_map[color2]
if self.is_multicolor:
if not isinstance(color, int):
return color == [color_map[color1]] * sum(
len(data["nodes"]) for node, data in self.graph.nodes(data=True)
)
else:
return color == color_map[color1]
else:
return color == color_map[color1]
def Height_Equals(self, height: Height, node):
if not isinstance(node, Tuple):
return height == node
elif isinstance(node, Tuple):
if height == "MAX":
height = self.get_attribute_max("height")
elif height == "MIN":
height = self.get_attribute_min("height")
elif height == "ODD":
return self.graph.nodes[node]["height"] % 2 != 0
return self.graph.nodes[node]["height"] == height
def Width_Equals(self, width: Width, node):
if not isinstance(node, Tuple):
return width == node
elif isinstance(node, Tuple):
if width == "MAX":
width = self.get_attribute_max("width")
elif width == "MIN":
width = self.get_attribute_min("width")
elif width == "ODD":
return self.graph.nodes[node]["width"] % 2 != 0
return self.graph.nodes[node]["width"] == width
def Column_Equals(self, column: Column, node):
if not isinstance(node, Tuple):
return column == node
elif isinstance(node, Tuple):
column_nodes = [col[1] for col in self.graph.nodes[node]["nodes"]]
if column == "MOD3":
col = self.mod_3(column)
return all(node in col for node in column_nodes)
elif column == "ODD":
col = self.get_odd(column)
return all(node in col for node in column_nodes) # is the entire object in odd columns
elif column == "EVEN":
col = self.get_even(column)
return all(node in col for node in column_nodes) # is the entire object in even columns
elif column == "CENTER":
col = self.get_center("column")
return all(node in col for node in column_nodes) # is the entire object in the center column
elif column == "EVEN_FROM_RIGHT":
col = self.get_even_right(column)
return all(node in col for node in column_nodes) # is the entire object in even columns
return False
def Row_Equals(self, row: Row, node):
if not isinstance(node, Tuple):
return row == node
elif isinstance(node, Tuple):
row_nodes = [col[0] for col in self.graph.nodes[node]["nodes"]]
if row == "MOD3":
r = self.mod_3(row)
return all(node in r for node in row_nodes)
elif row == "ODD":
r = self.get_odd(row)
return all(node in r for node in row_nodes) # is the entire object in odd rows
elif row == "EVEN":
r = self.get_even(row)
return all(node in r for node in row_nodes) # is the entire object in even rows
if row == "CENTER":
r = self.get_center("row")
return all(node in r for node in row_nodes) # is the entire object in the center row
return False
def Size_Equals(self, size: Size, node):
"""
return true if node has size equal to given size.
if exclude, return true if node does not have size equal to given size.
"""
if not isinstance(node, Tuple):
return node == size
elif isinstance(node, Tuple):
if size == "MAX":
size = self.get_attribute_max("size")
elif size == "MIN":
size = self.get_attribute_min("size")
elif size == "ODD":
return self.graph.nodes[node]["size"] % 2 != 0
return self.graph.nodes[node]["size"] == size
def Degree_Equals(self, degree: Degree, degree2):
"""
return true if node has degree equal to given degree.
if exclude, return true if node does not have degree equal to given degree.
"""
if isinstance(degree2, Tuple): # object
return self.graph.degree[degree2] == degree
else:
degree == degree2
def Neighbor_Size(self, size: Size, node):
"""
return true if node has a neighbor of a given size.
if exclude, return true if node does not have a neighbor of a given size.
"""
if not isinstance(node, Tuple):
return node == size
elif isinstance(node, Tuple):
for neighbor in self.graph.neighbors(node):
if size == "MAX":
if self.graph.nodes[neighbor]["size"] == self.get_attribute_max("size"):
return True
elif size == "MIN":
if self.graph.nodes[neighbor]["size"] == self.get_attribute_min("size"):
return True
elif size == "ODD":
if self.graph.nodes[neighbor]["size"] % 2 != 0:
return True
else:
if self.graph.nodes[neighbor]["size"] == size:
return True
return False
def Neighbor_Degree(self, degree: Degree, degree2):
"""
return true if node has a neighbor of a given degree.
if exclude, return true if node does not have a neighbor of a given degree.
"""
if isinstance(degree2, Tuple): # object
for neighbor in self.graph.neighbors(degree2):
if self.graph.degree[degree2] == degree:
return True
return False
else:
degree == degree2
def Shape_Equals(self, shape: Shape, node):
"""
return true if node contains a square-shaped hole
"""
if not isinstance(node, Tuple): # object
return shape == node
if shape == Shape.enclosed or shape == "enclosed":
nodes = self.graph.nodes(data=True)[node]['nodes']
all_nodes = []
for node in self.graph.nodes():
all_nodes.extend(self.graph.nodes(data=True)[node]['nodes'])
if not nodes:
return False
min_x = min(nodes, key=lambda x: x[0])[0]
max_x = max(nodes, key=lambda x: x[0])[0]
min_y = min(nodes, key=lambda x: x[1])[1]
max_y = max(nodes, key=lambda x: x[1])[1]
all_points = {(x, y) for x in range(min_x, max_x + 1) for y in range(min_y, max_y + 1)}
nodes_set = set(nodes)
missing_points = all_points - nodes_set
# Remove edge points from missing set
edge_points = {(x, y) for x in [min_x, max_x] for y in range(min_y, max_y + 1)} | \
{(x, y) for y in [min_y, max_y] for x in range(min_x, max_x + 1)}
missing_points = missing_points - edge_points
missing_points = set([point for point in missing_points if point in all_nodes])
if not missing_points:
return False # No internal missing points means the shape is fully filled
combined_set = missing_points | nodes_set
for point in missing_points:
x, y = point
neighbors = {(x-1, y), (x+1, y), (x, y-1), (x, y+1)}
if not all(neighbor in combined_set for neighbor in neighbors):
return False # Found a missing point not fully surrounded by nodes/missing points
return True
elif shape == Shape.square or shape == "square":
nodes = self.graph.nodes(data=True)[node]['nodes']
if not nodes:
return False
min_x = min(nodes, key=lambda x: x[0])[0]
max_x = max(nodes, key=lambda x: x[0])[0]
min_y = min(nodes, key=lambda x: x[1])[1]
max_y = max(nodes, key=lambda x: x[1])[1]
def is_square_formed_by_points(points):
if not points: # Check if the points list is empty
return False
if len(points) == 1:
return True
x_coords = [p[0] for p in points]
y_coords = [p[1] for p in points]
min_x, max_x = min(x_coords), max(x_coords)
min_y, max_y = min(y_coords), max(y_coords)
width = max_x - min_x + 1
height = max_y - min_y + 1
# Check if the dimensions form a square and if the number of points matches the area of the square
if width == height and len(points) == width * height:
return True
return False
all_points = {(x, y) for x in range(min_x, max_x + 1) for y in range(min_y, max_y + 1)}
missing_points = set(all_points) - set(nodes)
edge_points = {(x, y) for x in [min_x, max_x] for y in range(min_y, max_y + 1)} | {(x, y) for y in [min_y, max_y] for x in range(min_x, max_x + 1)}
if any(point in edge_points for point in missing_points):
return False # Missing points are at the edge
return is_square_formed_by_points(list(missing_points))
# ------------------------------------- utils ------------------------------------------
def get_attribute_max(self, attribute_name):
"""
get the maximum value of the given attribute
"""
if len(list(self.graph.nodes)) == 0:
return None
return max([data[attribute_name] for node, data in self.graph.nodes(data=True)])
def get_attribute_min(self, attribute_name):
"""
get the minimum value of the given attribute
"""
if len(list(self.graph.nodes)) == 0:
return None
return min([data[attribute_name] for node, data in self.graph.nodes(data=True)])
def get_center(self, attribute_name):
"""
get the minimum value of the given attribute
"""
if attribute_name == "column":
if len(list(self.graph.nodes)) == 0:
return None
values = list(set([node[1] for node in self.image.graph.nodes()])) #[node[1] for node in self.graph.nodes]
n = len(values)
if n % 2 == 1:
# If odd, return the single middle element as a list
centers = [values[n // 2]]
else:
# If even, return the two middle elements as a list
centers = values[n // 2 - 1:n // 2 + 1]
return centers
elif attribute_name == "row":
if len(list(self.graph.nodes)) == 0:
return None
values = list(set([node[0] for node in self.image.graph.nodes()]))
n = len(values)
if n % 2 == 1:
# If odd, return the single middle element as a list
centers = [values[n // 2]]
else:
# If even, return the two middle elements as a list
centers = values[n // 2 - 1:n // 2 + 1]
return centers
def get_even(self, attribute_name):
"""
get the even columns
"""
if len(list(self.graph.nodes)) == 0:
return None
even_values = list(set([node[1] for node in self.image.graph.nodes() if node[1] % 2 == 0]))
return even_values
def get_odd(self, attribute_name):
"""
get the odd columns
"""
if len(list(self.graph.nodes)) == 0:
return None
odd_values = list(set([node[1] for node in self.image.graph.nodes() if node[1] % 2 != 0]))
return odd_values
def mod_3(self, attribute_name):
"""
get the mod % 3 columns
"""
if len(list(self.graph.nodes)) == 0:
return None
mod_values = list(set([node[1] for node in self.image.graph.nodes() if node[1] % 3 == 0]))
return mod_values
def get_even_right(self, attribute_name):
"""
Get the even columns from the right side.
"""
if len(list(self.graph.nodes)) == 0:
return None
all_columns = list(set([node[1] for node in self.graph.nodes]))
total_columns = max(all_columns)
right_side_indices = [total_columns - col + 1 for col in all_columns]
even_right_values = [col for col in right_side_indices if col % 2 == 0]
original_indices_for_even_right = [total_columns - col + 1 for col in even_right_values]
return original_indices_for_even_right
def get_color(self, node):
"""
return the color of the node
"""
if isinstance(node, list):
return [self.graph.nodes[node_i]["color"] for node_i in node]
else:
return self.graph.nodes[node]["color"]
def check_inbound(self, pixels):
"""
check if given pixels are all within the image boundary
"""
if not isinstance(pixels, list):
pixels = [pixels]
for pixel in pixels:
y, x = pixel
if x < 0 or y < 0 or x >= self.width or y >= self.height:
return False
return True
def check_collision(self, node_id, pixels_list=None):
"""
check if given pixels_list collide with other nodes in the graph
node_id is used to retrieve pixels_list if not given.
node_id is also used so that only collision with other nodes are detected.
"""
if pixels_list is None:
pixels_set = set(self.graph.nodes[node_id]["nodes"])
else:
pixels_set = set(pixels_list)
for node, data in self.graph.nodes(data=True):
if len(set(data["nodes"]) & pixels_set) != 0 and node != node_id:
return True
return False
def check_pixel_occupied(self, pixel):
"""
check if a pixel is occupied by any node in the graph
"""
for node, data in self.graph.nodes(data=True):
if pixel in data["nodes"]:
return True
return False
def get_shape(self, node):
"""
given a node, get the shape of the node.
the shape of the node is defined using its pixels shifted so that the top left is 0,0