-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimplifiedAlgorithm.py
More file actions
6481 lines (5969 loc) · 277 KB
/
Copy pathsimplifiedAlgorithm.py
File metadata and controls
6481 lines (5969 loc) · 277 KB
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
# %% Setup
import numpy as np # linear algebra
import pandas as pd
import json
from pathlib import Path
import torch
import torch.nn as nn
import torch.nn.functional as F
import operator
from collections import Counter
import copy
from itertools import product, permutations, combinations, combinations_with_replacement
from functools import partial
import matplotlib.pyplot as plt
from matplotlib import colors
#data_path = Path('/kaggle/input/abstraction-and-reasoning-challenge/')
data_path = Path('data')
train_path = data_path / 'training'
eval_path = data_path / 'evaluation'
test_path = data_path / 'test'
train_tasks = { task.stem: json.load(task.open()) for task in train_path.iterdir() }
eval_tasks = { task.stem: json.load(task.open()) for task in eval_path.iterdir() }
test_tasks = { task.stem: json.load(task.open()) for task in test_path.iterdir() }
data = test_tasks
cmap = colors.ListedColormap(
['#000000', '#0074D9','#FF4136','#2ECC40','#FFDC00',
'#AAAAAA', '#F012BE', '#FF851B', '#7FDBFF', '#870C25'])
norm = colors.Normalize(vmin=0, vmax=9)
def plot_pictures(pictures, labels):
fig, axs = plt.subplots(1, len(pictures), figsize=(2*len(pictures),32))
for i, (pict, label) in enumerate(zip(pictures, labels)):
axs[i].imshow(np.array(pict), cmap=cmap, norm=norm)
axs[i].set_title(label)
plt.show()
def plot_sample(sample, predict=None):
"""
This function plots a sample. sample is an object of the class Task.Sample.
predict is any matrix (numpy ndarray).
"""
if predict is None:
plot_pictures([sample.inMatrix.m, sample.outMatrix.m], ['Input', 'Output'])
else:
plot_pictures([sample.inMatrix.m, sample.outMatrix.m, predict], ['Input', 'Output', 'Predict'])
def plot_task(task):
"""
Given a task (in its original format), this function plots all of its
matrices.
"""
len_train = len(task['train'])
len_test = len(task['test'])
len_max = max(len_train, len_test)
length = {'train': len_train, 'test': len_test}
fig, axs = plt.subplots(len_max, 4, figsize=(15, 15*len_max//4))
for col, mode in enumerate(['train', 'test']):
for idx in range(length[mode]):
axs[idx][2*col+0].axis('off')
axs[idx][2*col+0].imshow(task[mode][idx]['input'], cmap=cmap, norm=norm)
axs[idx][2*col+0].set_title(f"Input {mode}, {np.array(task[mode][idx]['input']).shape}")
try:
axs[idx][2*col+1].axis('off')
axs[idx][2*col+1].imshow(task[mode][idx]['output'], cmap=cmap, norm=norm)
axs[idx][2*col+1].set_title(f"Output {mode}, {np.array(task[mode][idx]['output']).shape}")
except:
pass
for idx in range(length[mode], len_max):
axs[idx][2*col+0].axis('off')
axs[idx][2*col+1].axis('off')
plt.tight_layout()
plt.axis('off')
plt.show()
def flattener(pred):
str_pred = str([row for row in pred])
str_pred = str_pred.replace(', ', '')
str_pred = str_pred.replace('[[', '|')
str_pred = str_pred.replace('][', '|')
str_pred = str_pred.replace(']]', '|')
return str_pred
##############################################################################
# %% CORE OBJECTS
# %% Frontiers
class Frontier:
"""
A Frontier is defined as a straight line with a single color that crosses
all of the matrix. For example, if the matrix has shape MxN, then a
Frontier will have shape Mx1 or 1xN. See the function "detectFrontiers"
for details in the implementation.
...
Attributes
----------
color: int
The color of the frontier
directrion: str
A character ('h' or 'v') determining whether the frontier is horizontal
or vertical
position: tuple
A 2-tuple of ints determining the position of the upper-left pixel of
the frontier
"""
def __init__(self, color, direction, position):
"""
direction can be 'h' or 'v' (horizontal, vertical)
color, position and are all integers
"""
self.color = color
self.direction = direction
self.position = position
def __eq__(self, other):
if isinstance(other, self.__class__):
return self.__dict__ == other.__dict__
else:
return False
def detectFrontiers(m):
"""
m is a numpy 2-dimensional matrix.
"""
frontiers = []
# Horizontal lines
if m.shape[0]>1:
for i in range(m.shape[0]):
color = m[i, 0]
isFrontier = True
for j in range(m.shape[1]):
if color != m[i,j]:
isFrontier = False
break
if isFrontier:
frontiers.append(Frontier(color, 'h', i))
# Vertical lines
if m.shape[1]>1:
for j in range(m.shape[1]):
color = m[0, j]
isFrontier = True
for i in range(m.shape[0]):
if color != m[i,j]:
isFrontier = False
break
if isFrontier:
frontiers.append(Frontier(color, 'v', j))
return frontiers
# %% Grids
class Grid:
"""
An object of the class Grid is basically a collection of frontiers that
have all the same color.
It is useful to check, for example, whether the cells defined by the grid
always have the same size or not.
...
Attributes
----------
color: int
The color of the grid
m: numpy.ndarray
The whole matrix
frontiers: list
A list of all the frontiers the grid is composed of
cells: list of list of 2-tuples
cells can be viewed as a 2-dimensional matrix of 2-tuples (Matrix,
position). The first element is an object of the class Matrix, and the
second element is the position of the cell in m.
Each element represents a cell of the grid.
shape: tuple
A 2-tuple of ints representing the number of cells of the grid
nCells: int
Number of cells of the grid
cellList: list
A list of all the cells
allCellsSameShape: bool
Determines whether all the cells of the grid have the same shape (as
matrices).
cellShape: tuple
Only defined if allCellsSameShape is True. Shape of the cells.
allCellsHaveOneColor: bool
Determines whether the ALL of the cells of the grid are composed of
pixels of the same color
"""
def __init__(self, m, frontiers):
self.color = frontiers[0].color
self.m = m
self.frontiers = frontiers
hPositions = [f.position for f in frontiers if f.direction == 'h']
hPositions.append(-1)
hPositions.append(m.shape[0])
hPositions.sort()
vPositions = [f.position for f in frontiers if f.direction == 'v']
vPositions.append(-1)
vPositions.append(m.shape[1])
vPositions.sort()
# cells is a matrix (list of lists) of 2-tuples (Matrix, position)
self.cells = []
hShape = 0
vShape = 0
for h in range(len(hPositions)-1):
if hPositions[h]+1 == hPositions[h+1]:
continue
self.cells.append([])
for v in range(len(vPositions)-1):
if vPositions[v]+1 == vPositions[v+1]:
continue
if hShape == 0:
vShape += 1
self.cells[hShape].append((Matrix(m[hPositions[h]+1:hPositions[h+1], \
vPositions[v]+1:vPositions[v+1]], \
detectGrid=False), \
(hPositions[h]+1, vPositions[v]+1)))
hShape += 1
self.shape = (hShape, vShape) # N of h cells x N of v cells
self.cellList = []
for cellRow in range(len(self.cells)):
for cellCol in range(len(self.cells[0])):
self.cellList.append(self.cells[cellRow][cellCol])
self.allCellsSameShape = len(set([c[0].shape for c in self.cellList])) == 1
if self.allCellsSameShape:
self.cellShape = self.cells[0][0][0].shape
self.nCells = len(self.cellList)
# Check whether each cell has one and only one color
self.allCellsHaveOneColor = True
for c in self.cellList:
if c[0].nColors!=1:
self.allCellsHaveOneColor = False
break
def __eq__(self, other):
if isinstance(other, self.__class__):
return all([f in other.frontiers for f in self.frontiers])
else:
return False
# %% Frames
"""
class Frame:
def __init__(self, matrix):
self.m
self.color
self.position
self.shape
self.isFull
def detectFrames(matrix):
frames = []
m = matrix.m.copy()
for i,j in np.ndindex(m.shape):
color = m[i,j]
iMax = m.shape[0]
jMax = m.shape[1]
for k in range(i+1, m.shape[0]):
for l in range(j+1, m.shape[1]):
if m[k,l]==color:
return frames
"""
# %% Shapes and subclasses
class Shape:
def __init__(self, m, xPos, yPos, background, isBorder):
# pixels is a 2xn numpy array, where n is the number of pixels
self.m = m
self.nPixels = m.size - np.count_nonzero(m==255)
self.background = background
self.shape = m.shape
self.position = (xPos, yPos)
self.pixels = set([(i,j) for i,j in np.ndindex(m.shape) if m[i,j]!=255])
# Is the shape in the border?
self.isBorder = isBorder
# Which colors does the shape have?
self.colors = set(np.unique(m)) - set([255])
self.nColors = len(self.colors)
if self.nColors==1:
self.color = next(iter(self.colors))
self.colorCount = Counter(self.m.flatten()) + Counter({0:0, 1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0, 9:0})
del self.colorCount[255]
# Symmetries
self.lrSymmetric = np.array_equal(self.m, np.fliplr(self.m))
self.udSymmetric = np.array_equal(self.m, np.flipud(self.m))
if self.m.shape[0] == self.m.shape[1]:
self.d1Symmetric = np.array_equal(self.m, self.m.T)
self.d2Symmetric = np.array_equal(np.fliplr(self.m), (np.fliplr(self.m)).T)
else:
self.d1Symmetric = False
self.d2Symmetric = False
self.isRectangle = 255 not in np.unique(m)
self.isSquare = self.isRectangle and self.shape[0]==self.shape[1]
if self.isRectangle and self.nColors > 1:
self.subshapes = detectShapes(self.m, background=self.colorCount.most_common(1)[0][0],\
singleColor=True, diagonals=False)
self.nHoles = self.getNHoles()
if self.nColors==1:
self.isFullFrame = self.isFullFrame()
self.isPartialFrame = self.isPartialFrame()
else:
self.isFullFrame = False
self.isPartialFrame = False
if self.nColors==1:
self.boolFeatures = []
for c in range(10):
self.boolFeatures.append(self.color==c)
self.boolFeatures.append(self.isBorder)
self.boolFeatures.append(not self.isBorder)
self.boolFeatures.append(self.lrSymmetric)
self.boolFeatures.append(self.udSymmetric)
self.boolFeatures.append(self.d1Symmetric)
self.boolFeatures.append(self.d2Symmetric)
self.boolFeatures.append(self.isSquare)
self.boolFeatures.append(self.isRectangle)
for nPix in range(1,30):
self.boolFeatures.append(self.nPixels==nPix)
self.boolFeatures.append((self.nPixels%2)==0)
self.boolFeatures.append((self.nPixels%2)==1)
def hasSameShape(self, other, sameColor=False, samePosition=False, rotation=False, \
mirror=False, scaling=False):
if samePosition:
if self.position != other.position:
return False
if sameColor:
m1 = self.m
m2 = other.m
else:
m1 = self.shapeDummyMatrix()
m2 = other.shapeDummyMatrix()
if scaling and m1.shape!=m2.shape:
def multiplyPixels(matrix, factor):
m = np.zeros(tuple(s * f for s, f in zip(matrix.shape, factor)), dtype=np.uint8)
for i,j in np.ndindex(matrix.shape):
for k,l in np.ndindex(factor):
m[i*factor[0]+k, j*factor[1]+l] = matrix[i,j]
return m
if (m1.shape[0]%m2.shape[0])==0 and (m1.shape[1]%m2.shape[1])==0:
factor = (int(m1.shape[0]/m2.shape[0]), int(m1.shape[1]/m2.shape[1]))
m2 = multiplyPixels(m2, factor)
elif (m2.shape[0]%m1.shape[0])==0 and (m2.shape[1]%m1.shape[1])==0:
factor = (int(m2.shape[0]/m1.shape[0]), int(m2.shape[1]/m1.shape[1]))
m1 = multiplyPixels(m1, factor)
elif rotation and (m1.shape[0]%m2.shape[1])==0 and (m1.shape[1]%m2.shape[0])==0:
factor = (int(m1.shape[0]/m2.shape[1]), int(m1.shape[1]/m2.shape[0]))
m2 = multiplyPixels(m2, factor)
elif rotation and (m2.shape[0]%m1.shape[1])==0 and (m2.shape[1]%m1.shape[0])==0:
factor = (int(m2.shape[0]/m1.shape[1]), int(m2.shape[1]/m1.shape[0]))
m1 = multiplyPixels(m1, factor)
else:
return False
if rotation and not mirror:
if any([np.array_equal(m1, np.rot90(m2,x)) for x in range(1,4)]):
return True
if mirror and not rotation:
if np.array_equal(m1, np.fliplr(m2)) or np.array_equal(m1, np.flipud(m2)):
return True
if mirror and rotation:
for x in range(1, 4):
if any([np.array_equal(m1, np.rot90(m2,x))\
or np.array_equal(m1, np.fliplr(np.rot90(m2,x))) for x in range(0,4)]):
return True
return np.array_equal(m1,m2)
def __eq__(self, other):
if isinstance(other, self.__class__):
if self.shape != other.shape:
return False
return np.array_equal(self.m, other.m)
else:
return False
"""
def __hash__(self):
return self.m
"""
def isSubshape(self, other, sameColor=False, rotation=False, mirror=False):
"""
The method checks if a shape fits inside another. Can take into account rotations and mirrors.
Maybe it should be updated to return the positions of subshapes instead of a boolean?
"""
#return positions
if rotation:
m1 = self.m
for x in range(1,4):
if Shape(np.rot90(m1,x), 0, 0, 0, self.isBorder).isSubshape(other, sameColor, False, mirror):
return True
if mirror == 'lr':
if Shape(self.m[::,::-1], 0, 0, 0, self.isBorder).isSubshape(other, sameColor, rotation, False):
return True
if mirror == 'ud':
if Shape(self.m[::-1,::], 0, 0, 0, self.isBorder).isSubshape(other, sameColor, rotation, False):
return True
if sameColor:
if hasattr(self,'color') and hasattr(other,'color') and self.color != other.color:
return False
if any(other.shape[i] < self.shape[i] for i in [0,1]):
return False
for yIn in range(other.shape[1] - self.shape[1] + 1):
for xIn in range(other.shape[0] - self.shape[0] + 1):
if sameColor:
if np.all(np.logical_or((self.m == other.m[xIn: xIn + self.shape[0], yIn: yIn + self.shape[1]]),\
self.m==255)):
return True
else:
if set([tuple(np.add(ps,[xIn,yIn])) for ps in self.pixels]) <= other.pixels:
return True
return False
def shapeDummyMatrix(self):
"""
Returns the smallest possible matrix containing the shape. The values
of the matrix are ones and zeros, depending on whether the pixel is a
shape pixel or not.
"""
return (self.m!=255).astype(np.uint8)
def hasFeatures(self, features):
for i in range(len(features)):
if features[i] and not self.boolFeatures[i]:
return False
return True
def getNHoles(self):
nHoles = 0
m = self.m
seen = np.zeros((self.shape[0], self.shape[1]), dtype=np.bool)
def isInHole(i,j):
if i<0 or j<0 or i>self.shape[0]-1 or j>self.shape[1]-1:
return False
if seen[i,j] or m[i,j] != 255:
return True
seen[i,j] = True
ret = isInHole(i+1,j)*isInHole(i-1,j)*isInHole(i,j+1)*isInHole(i,j-1)
return ret
for i,j in np.ndindex(m.shape):
if m[i,j] == 255 and not seen[i,j]:
if isInHole(i,j):
nHoles += 1
return nHoles
def isRotationInvariant(self, color=False):
if color:
m = np.rot90(self.m, 1)
return np.array_equal(m, self.m)
else:
m2 = self.shapeDummyMatrix()
m = np.rot90(m2, 1)
return np.array_equal(m, m2)
"""
def isFullFrame(self):
if self.shape[0]<3 or self.shape[1]<3:
return False
for i in range(1, self.shape[0]-1):
for j in range(1, self.shape[1]-1):
if self.m[i,j] != 255:
return False
if self.nPixels == 2 * (self.shape[0]+self.shape[1]-2):
return True
return False
"""
def isPartialFrame(self):
if self.shape[0] < 4 or self.shape[1] < 4 or len(self.pixels) < 4:
return False
if len(np.unique(self.m[1:-1,1:-1])) > 1 or self.color in np.unique(self.m[1:-1,1:-1]):
return False
return True
def isFullFrame(self):
if self.shape[0]<3 or self.shape[1]<3:
return False
for i in range(self.shape[0]):
if self.m[i,0]==255 or self.m[i,self.shape[1]-1]==255:
return False
for j in range(self.shape[1]):
if self.m[0,j]==255 or self.m[self.shape[0]-1,j]==255:
return False
# We require fullFrames to have less than 20% of the pixels inside the
# frame of the same color of the frame
if self.nPixels - 2*(self.shape[0]+self.shape[1]-2) < 0.2*(self.shape[0]-2)*(self.shape[1]-2):
return True
return False
def detectShapesByColor(x, background):
shapes = []
for c in range(10):
if c == background or c not in x:
continue
mc = np.zeros(x.shape, dtype=int)
mc[x==c] = c
mc[x!=c] = 255
x1, x2, y1, y2 = 0, mc.shape[0]-1, 0, mc.shape[1]-1
while x1 <= x2 and np.all(mc[x1,:] == 255):
x1 += 1
while x2 >= x1 and np.all(mc[x2,:] == 255):
x2 -= 1
while y1 <= y2 and np.all(mc[:,y1] == 255):
y1 += 1
while y2 >= y1 and np.all(mc[:,y2] == 255):
y2 -= 1
m = mc[x1:x2+1,y1:y2+1]
s = Shape(m.copy(), x1, y1, background, False)
shapes.append(s)
return shapes
def detectShapes(x, background, singleColor=False, diagonals=False):
"""
Given a numpy array x (2D), returns a list of the Shapes present in x
"""
# Helper function to add pixels to a shape
def addPixelsAround(i,j):
def addPixel(i,j):
if i < 0 or j < 0 or i > iMax or j > jMax or seen[i,j] == True:
return
if singleColor:
if x[i,j] != color:
return
newShape[i,j] = color
else:
if x[i,j] == background:
return
newShape[i,j] = x[i,j]
seen[i,j] = True
addPixelsAround(i,j)
addPixel(i-1,j)
addPixel(i+1,j)
addPixel(i,j-1)
addPixel(i,j+1)
if diagonals:
addPixel(i-1,j-1)
addPixel(i-1,j+1)
addPixel(i+1,j-1)
addPixel(i+1,j+1)
def crop(matrix):
ret = matrix.copy()
for k in range(x.shape[0]):
if any(matrix[k,:] != 255): # -1==255 for dtype=np.uint8
x0 = k
break
for k in reversed(range(x.shape[0])):
if any(matrix[k,:] != 255): # -1==255 for dtype=np.uint8
x1 = k
break
for k in range(x.shape[1]):
if any(matrix[:,k] != 255): # -1==255 for dtype=np.uint8
y0 = k
break
for k in reversed(range(x.shape[1])):
if any(matrix[:,k] != 255): # -1==255 for dtype=np.uint8
y1 = k
break
return ret[x0:x1+1,y0:y1+1], x0, y0
shapes = []
seen = np.zeros(x.shape, dtype=bool)
iMax = x.shape[0]-1
jMax = x.shape[1]-1
for i, j in np.ndindex(x.shape):
if seen[i,j] == False:
seen[i,j] = True
if not singleColor and x[i,j]==background:
continue
newShape = np.full((x.shape), -1, dtype=np.uint8)
newShape[i,j] = x[i,j]
if singleColor:
color = x[i][j]
addPixelsAround(i,j)
m, xPos, yPos = crop(newShape)
isBorder = xPos==0 or yPos==0 or (xPos+m.shape[0]==x.shape[0]) or (yPos+m.shape[1]==x.shape[1])
s = Shape(m.copy(), xPos, yPos, background, isBorder)
shapes.append(s)
return shapes
def detectIsolatedPixels(matrix, dShapeList):
pixList = []
for sh in dShapeList:
if sh.nPixels > 1 or sh.color == matrix.backgroundColor:
continue
else:
cc = set()
for i,j in np.ndindex(3, 3):
if i - 1 + sh.position[0] < matrix.shape[0] and i - 1 + sh.position[0] >= 0 \
and j - 1 + sh.position[1] < matrix.shape[1] and j - 1 + sh.position[1] >= 0:
cc = cc.union(set([matrix.m[i - 1 + sh.position[0],j - 1 + sh.position[1]]]))
if len(cc) == 2:
pixList.append(sh)
return pixList
# %% Class Matrix
class Matrix():
def __init__(self, m, detectGrid=True, backgroundColor=None):
if type(m) == Matrix:
return m
self.m = np.array(m)
# interesting properties:
# Dimensions
self.shape = self.m.shape
self.nElements = self.m.size
# Counter of colors
self.colorCount = self.getColors()
self.colors = set(self.colorCount.keys())
self.nColors = len(self.colorCount)
# Background color
if backgroundColor==None:
self.backgroundColor = max(self.colorCount, key=self.colorCount.get)
else:
self.backgroundColor = backgroundColor
# Shapes
self.shapes = detectShapes(self.m, self.backgroundColor, singleColor=True)
self.nShapes = len(self.shapes)
self.dShapes = detectShapes(self.m, self.backgroundColor, singleColor=True, diagonals=True)
self.nDShapes = len(self.dShapes)
self.fullFrames = [shape for shape in self.shapes if shape.isFullFrame]
self.fullFrames = sorted(self.fullFrames, key=lambda x: x.shape[0]*x.shape[1], reverse=True)
self.shapesByColor = detectShapesByColor(self.m, self.backgroundColor)
self.partialFrames = [shape for shape in self.shapesByColor if shape.isPartialFrame]
self.isolatedPixels = detectIsolatedPixels(self, self.dShapes)
self.nIsolatedPixels = len(self.isolatedPixels)
self.shapeColorCounter = Counter([s.color for s in self.shapes])
self.blanks = []
for s in self.shapes:
if s.isRectangle and self.shapeColorCounter[s.color]==1:
self.blanks.append(s)
# Frontiers
self.frontiers = detectFrontiers(self.m)
self.frontierColors = [f.color for f in self.frontiers]
if len(self.frontiers) == 0:
self.allFrontiersEqualColor = False
else: self.allFrontiersEqualColor = (self.frontierColors.count(self.frontiers[0]) ==\
len(self.frontiers))
# Check if it's a grid and the dimensions of the cells
self.isGrid = False
self.isAsymmetricGrid = False
if detectGrid:
for fc in set(self.frontierColors):
possibleGrid = [f for f in self.frontiers if f.color==fc]
possibleGrid = Grid(self.m, possibleGrid)
if possibleGrid.nCells>1:
if possibleGrid.allCellsSameShape:
self.grid = copy.deepcopy(possibleGrid)
self.isGrid = True
self.asymmetricGrid = copy.deepcopy(possibleGrid)
self.isAsymmetricGrid = True
break
else:
self.asymmetricGrid = copy.deepcopy(possibleGrid)
self.isAsymmetricGrid=True
# Shape-based backgroundColor
if not self.isGrid:
for shape in self.shapes:
if shape.shape==self.shape:
self.backgroundColor = shape.color
break
# Define multicolor shapes based on the background color
self.multicolorShapes = detectShapes(self.m, self.backgroundColor)
self.multicolorDShapes = detectShapes(self.m, self.backgroundColor, diagonals=True)
self.dummyMatrix = (self.m!=self.backgroundColor).astype(np.uint8)
# Symmetries
self.lrSymmetric = np.array_equal(self.m, np.fliplr(self.m))
# Up-Down
self.udSymmetric = np.array_equal(self.m, np.flipud(self.m))
# Diagonals (only if square)
if self.m.shape[0] == self.m.shape[1]:
self.d1Symmetric = np.array_equal(self.m, self.m.T)
self.d2Symmetric = np.array_equal(np.fliplr(self.m), (np.fliplr(self.m)).T)
else:
self.d1Symmetric = False
self.d2Symmetric = False
self.totalSymmetric = self.lrSymmetric and self.udSymmetric and \
self.d1Symmetric and self.d2Symmetric
self.fullBorders = []
for f in self.frontiers:
if f.color != self.backgroundColor:
if f.position==0:
self.fullBorders.append(f)
elif (f.direction=='h' and f.position==self.shape[0]-1) or\
(f.direction=='v' and f.position==self.shape[1]-1):
self.fullBorders.append(f)
self.isVertical = False
self.isHorizontal = False
if len(self.frontiers)!=0:
self.isVertical = all([f.direction=='v' for f in self.frontiers])
self.isHorizontal = all([f.direction=='h' for f in self.frontiers])
def getColors(self):
unique, counts = np.unique(self.m, return_counts=True)
return dict(zip(unique, counts))
def getShapes(self, color=None, bigOrSmall=None, isBorder=None, diag=False):
"""
Return a list of the shapes meeting the required specifications.
"""
if diag:
candidates = self.dShapes
else:
candidates = self.shapes
if color != None:
candidates = [c for c in candidates if c.color == color]
if isBorder==True:
candidates = [c for c in candidates if c.isBorder]
if isBorder==False:
candidates = [c for c in candidates if not c.isBorder]
if len(candidates) == 0:
return []
sizes = [c.nPixels for c in candidates]
if bigOrSmall == "big":
maxSize = max(sizes)
return [c for c in candidates if c.nPixels==maxSize]
elif bigOrSmall == "small":
minSize = min(sizes)
return [c for c in candidates if c.nPixels==minSize]
else:
return candidates
def followsColPattern(self):
"""
This function checks whether the matrix follows a pattern of lines or
columns being always the same (task 771 for example).
Meant to be used for the output matrix mainly.
It returns a number (length of the pattern) and "row" or "col".
"""
m = self.m.copy()
col0 = m[:,0]
for i in range(1,int(m.shape[1]/2)+1):
if np.all(col0 == m[:,i]):
isPattern=True
for j in range(i):
k=0
while k*i+j < m.shape[1]:
if np.any(m[:,j] != m[:,k*i+j]):
isPattern=False
break
k+=1
if not isPattern:
break
if isPattern:
return i
return False
def followsRowPattern(self):
m = self.m.copy()
row0 = m[0,:]
for i in range(1,int(m.shape[0]/2)+1):
if np.all(row0 == m[i,:]):
isPattern=True
for j in range(i):
k=0
while k*i+j < m.shape[0]:
if np.any(m[j,:] != m[k*i+j,:]):
isPattern=False
break
k+=1
if not isPattern:
break
if isPattern:
return i
return False
def isUniqueShape(self, shape):
count = 0
for sh in self.shapes:
if sh.hasSameShape(shape):
count += 1
if count==1:
return True
return False
def getShapeAttributes(self, backgroundColor=0, singleColor=True, diagonals=True):
'''
Returns list of shape attributes that matches list of shapes
Add:
- is border
- has neighbors
- is reference
- is referenced
'''
if singleColor:
if diagonals:
shapeList = [sh for sh in self.dShapes]
else:
shapeList = [sh for sh in self.shapes]
if len([sh for sh in shapeList if sh.color != backgroundColor]) == 0:
return [set() for sh in shapeList]
else:
if diagonals:
shapeList = [sh for sh in self.multicolorDShapes]
else:
shapeList = [sh for sh in self.multicolorShapes]
if len(shapeList) == 0:
return [set()]
attrList =[[] for i in range(len(shapeList))]
if singleColor:
cc = Counter([sh.color for sh in shapeList])
if singleColor:
sc = Counter([sh.nPixels for sh in shapeList if sh.color != backgroundColor])
else:
sc = Counter([sh.nPixels for sh in shapeList])
largest, smallest, mcopies, mcolors = -1, 1000, 0, 0
if singleColor:
maxH, minH = max([sh.nHoles for sh in shapeList if sh.color != backgroundColor]),\
min([sh.nHoles for sh in shapeList if sh.color != backgroundColor])
ila, ism = [], []
for i in range(len(shapeList)):
#color count
if singleColor:
if shapeList[i].color == backgroundColor:
attrList[i].append(-1)
continue
else:
attrList[i].append(shapeList[i].color)
else:
attrList[i].append(shapeList[i].nColors)
if shapeList[i].nColors > mcolors:
mcolors = shapeList[i].nColors
#copies
if singleColor:
attrList[i] = [np.count_nonzero([np.all(shapeList[i].pixels == osh.pixels) for osh in shapeList])] + attrList[i]
if attrList[i][0] > mcopies:
mcopies = attrList[i][0]
else:
attrList[i] = [np.count_nonzero([shapeList[i] == osh for osh in shapeList])] + attrList[i]
if attrList[i][0] > mcopies:
mcopies = attrList[i][0]
#unique color?
if singleColor:
if cc[shapeList[i].color] == 1:
attrList[i].append('UnCo')
#more of x color?
if not singleColor:
for c in range(10):
if shapeList[i].colorCount[c] > 0 and shapeList[i].colorCount[c] == max([sh.colorCount[c] for sh in shapeList]):
attrList[i].append('mo'+str(c))
#largest?
if len(shapeList[i].pixels) >= largest:
ila += [i]
if len(shapeList[i].pixels) > largest:
largest = len(shapeList[i].pixels)
ila = [i]
#smallest?
if len(shapeList[i].pixels) <= smallest:
ism += [i]
if len(shapeList[i].pixels) < smallest:
smallest = len(shapeList[i].pixels)
ism = [i]
#unique size
if sc[shapeList[i].nPixels] == 1 and len(sc) == 2:
attrList[i].append('UnSi')
#symmetric?
if shapeList[i].lrSymmetric:
attrList[i].append('LrSy')
else:
attrList[i].append('NlrSy')
if shapeList[i].udSymmetric:
attrList[i].append('UdSy')
else:
attrList[i].append('NudSy')
if shapeList[i].d1Symmetric:
attrList[i].append('D1Sy')
else:
attrList[i].append('ND1Sy')
if shapeList[i].d2Symmetric:
attrList[i].append('D2Sy')
else:
attrList[i].append('ND2Sy')
attrList[i].append(shapeList[i].position)
#pixels
if len(shapeList[i].pixels) == 1:
attrList[i].append('PiXl')
#holes
if singleColor:
if maxH>minH:
if shapeList[i].nHoles == maxH:
attrList[i].append('MoHo')
elif shapeList[i].nHoles == minH:
attrList[i].append('LeHo')
#is referenced by a full/partial frame?
if any((shapeList[i].position[0] >= fr.position[0] and shapeList[i].position[1] >= fr.position[1]\
and shapeList[i].position[0] + shapeList[i].shape[0] <= fr.position[0] + fr.shape[0] and\
shapeList[i].position[1] + shapeList[i].shape[1] <= fr.position[1] + fr.shape[1] and\
shapeList[i].color != fr.color) for fr in self.partialFrames):
attrList[i].append('IsRef')
if any((shapeList[i].position[0] >= fr.position[0] and shapeList[i].position[1] >= fr.position[1]\
and shapeList[i].position[0] + shapeList[i].shape[0] <= fr.position[0] + fr.shape[0] and\
shapeList[i].position[1] + shapeList[i].shape[1] <= fr.position[1] + fr.shape[1] and\
shapeList[i].color != fr.color) for fr in self.fullFrames):
attrList[i].append('IsFRef')
if len(ism) == 1:
attrList[ism[0]].append('SmSh')
if len(ila) == 1:
attrList[ila[0]].append('LaSh')
for i in range(len(shapeList)):
if len(attrList[i]) > 0 and attrList[i][0] == mcopies:
attrList[i].append('MoCo')
if not singleColor:
for i in range(len(shapeList)):
if len(attrList[i]) > 0 and attrList[i][1] == mcolors:
attrList[i].append('MoCl')
if [l[0] for l in attrList].count(1) == 1:
for i in range(len(shapeList)):
if len(attrList[i]) > 0 and attrList[i][0] == 1:
attrList[i].append('UnSh')
break
return [set(l[1:]) for l in attrList]
# %% Class Sample
class Sample():
def __init__(self, s, trainOrTest, submission=False, backgroundColor=None):
self.inMatrix = Matrix(s['input'], backgroundColor=backgroundColor)
if trainOrTest == "train" or submission==False:
self.outMatrix = Matrix(s['output'], backgroundColor=backgroundColor)
# We want to compare the input and the output
# Do they have the same dimensions?
self.sameHeight = self.inMatrix.shape[0] == self.outMatrix.shape[0]
self.sameWidth = self.inMatrix.shape[1] == self.outMatrix.shape[1]
self.sameShape = self.sameHeight and self.sameWidth
# Is the input shape a factor of the output shape?
# Or the other way around?
if not self.sameShape:
if (self.inMatrix.shape[0] % self.outMatrix.shape[0]) == 0 and \
(self.inMatrix.shape[1] % self.outMatrix.shape[1]) == 0 :
self.outShapeFactor = (int(self.inMatrix.shape[0]/self.outMatrix.shape[0]),\
int(self.inMatrix.shape[1]/self.outMatrix.shape[1]))
if (self.outMatrix.shape[0] % self.inMatrix.shape[0]) == 0 and \
(self.outMatrix.shape[1] % self.inMatrix.shape[1]) == 0 :
self.inShapeFactor = (int(self.outMatrix.shape[0]/self.inMatrix.shape[0]),\
int(self.outMatrix.shape[1]/self.inMatrix.shape[1]))
# Is one a subset of the other? for now always includes diagonals
self.inSmallerThanOut = all(self.inMatrix.shape[i] <= self.outMatrix.shape[i] for i in [0,1]) and not self.sameShape
self.outSmallerThanIn = all(self.inMatrix.shape[i] >= self.outMatrix.shape[i] for i in [0,1]) and not self.sameShape
#R: Is the output a shape (faster than checking if is a subset?
if self.outSmallerThanIn:
#check if output is the size of a multicolored shape
self.outIsInMulticolorShapeSize = any((sh.shape == self.outMatrix.shape) for sh in self.inMatrix.multicolorShapes)
self.outIsInMulticolorDShapeSize = any((sh.shape == self.outMatrix.shape) for sh in self.inMatrix.multicolorDShapes)
self.commonShapes, self.commonDShapes, self.commonMulticolorShapes, self.commonMulticolorDShapes = [], [], [], []
if len(self.inMatrix.shapes) < 15 or len(self.outMatrix.shapes) < 10:
self.commonShapes = self.getCommonShapes(diagonal=False, sameColor=True,\
multicolor=False, rotation=True, scaling=True, mirror=True)
if len(self.inMatrix.dShapes) < 15 or len(self.outMatrix.dShapes) < 10:
self.commonDShapes = self.getCommonShapes(diagonal=True, sameColor=True,\
multicolor=False, rotation=True, scaling=True, mirror=True)
if len(self.inMatrix.multicolorShapes) < 15 or len(self.outMatrix.multicolorShapes) < 10:
self.commonMulticolorShapes = self.getCommonShapes(diagonal=False, sameColor=True,\
multicolor=True, rotation=True, scaling=True, mirror=True)
if len(self.inMatrix.multicolorDShapes) < 15 or len(self.outMatrix.multicolorDShapes) < 10: