Skip to content

Commit

Permalink
Added extendColor and fillRectangleInside
Browse files Browse the repository at this point in the history
- fillRectangleInside is a minor function, but could be useful for tasks like 525
- extendColor is a function that I've wanted to implement for a long time now. It solves task 23, for example, and will help solving tasks like 348 (once surroundShapes is implemented)
  • Loading branch information
alejandrodemiquel committed May 8, 2020
1 parent d2c1f05 commit 87deaea
Show file tree
Hide file tree
Showing 3 changed files with 221 additions and 130 deletions.
131 changes: 85 additions & 46 deletions Utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -610,6 +610,7 @@ def evolveInputMatrices(mIn, mOut, changeCIC=False):

return [colorFromNeighboursK2, colorFromNeighboursK3,\
colorFromNeighboursK5, colorfromNeighboursK3Background]


def applyEvolve(matrix, cfn, nColors, changedOutColors=set(), fixedColors=set(),\
changedInColors=set(), referenceIsFixed=False, commonColors=set(),\
Expand Down Expand Up @@ -2309,57 +2310,89 @@ def addPixel(i,j):
return x

# TODO
def surroundAllShapes(m, shape, shapeColor, surroundColor, nSteps = False, untilColor = False):
x = m.m.copy()
def surroundAllShapes(matrix, shape, shapeColor, surroundColor, nSteps = False, untilColor = False):
x = matrix.m.copy()
shapesToSurround = [s for s in m.shapes if s.color == shapeColor]
for s in shapesToSurround:
x = surroundShape(x, s, outColor, untilColor)
return x

# TODO
def extendColorAcross(matrix, color, direction, until, untilBorder = True):
m = matrix.copy()
def extendColor(matrix, color, direction, cic, sourceColor=None):
m = matrix.m.copy()

if sourceColor==None:
sourceColor=color

if direction == "v" or direction == "u":
# Vertical
if direction=='v' or direction=='u':
for j in range(m.shape[1]):
colorCells = False
colorCells=False
for i in reversed(range(m.shape[0])):
if not colorCells:
if matrix[i,j] == color:
colorCells = True
else:
if matrix[i,j] == until:
colorCells = False
else:
m[i,j] = color
if colorCells and not untilBorder:
for i in range(m.shape[0]):
if matrix[i,j] == color:
break
m[i,j] = matrix[i,j]

if direction == "v" or direction == "d":
if matrix.m[i,j]==sourceColor:
colorCells=True
if colorCells and matrix.m[i,j] in cic:
m[i,j] = color
if direction=='v' or direction=='d':
for j in range(m.shape[1]):
colorCells = False
colorCells=False
for i in range(m.shape[0]):
if not colorCells:
if matrix[i,j] == color:
colorCells = True
else:
if matrix[i,j] == until:
colorCells = False
else:
m[i,j] = color
if colorCells and not untilBorder:
for i in reversed(range(m.shape[0])):
if matrix[i,j] == color:
break
m[i,j] = matrix[i,j]

#if direction == "h" or direction == "l":
#if direction == "h" or direction == "r":
if matrix.m[i,j]==sourceColor:
colorCells=True
if colorCells and matrix.m[i,j] in cic:
m[i,j] = color

# Horizontal
if direction=='h' or direction=='l':
for i in range(m.shape[0]):
colorCells=False
for j in reversed(range(m.shape[1])):
if matrix.m[i,j]==sourceColor:
colorCells=True
if colorCells and matrix.m[i,j] in cic:
m[i,j] = color
if direction=='h' or direction=='r':
for i in range(m.shape[0]):
colorCells=False
for j in range(m.shape[1]):
if matrix.m[i,j]==sourceColor:
colorCells=True
if colorCells and matrix.m[i,j] in cic:
m[i,j] = color

return m

def getBestExtendColor(t):
bestScore = 1000
bestFunction = partial(identityM)

cic = t.commonChangedInColors
for coc in t.commonChangedOutColors:
for d in ['r', 'l', 'h', 'u', 'd', 'v']:
f = partial(extendColor, color=coc, direction=d, cic=cic)
bestFunction, bestScore = updateBestFunction(t, f, bestScore, bestFunction)
if bestScore==0:
return bestFunction
for fc in t.fixedColors:
f = partial(extendColor, color=coc, direction=d, cic=cic, sourceColor=fc)
bestFunction, bestScore = updateBestFunction(t, f, bestScore, bestFunction)
if bestScore==0:
return bestFunction

return bestFunction

# %% Fill rectangleInside (task 525)

def fillRectangleInside(matrix, rectangleColor, fillColor):
m = matrix.m.copy()
for shape in matrix.shapes:
if shape.isRectangle and shape.color==rectangleColor:
if shape.shape[0] > 2 and shape.shape[1] > 2:
rect = np.full((shape.shape[0]-2, shape.shape[1]-2), fillColor, dtype=np.uint8)
m[shape.position[0]+1:shape.position[0]+shape.shape[0]-1,\
shape.position[1]+1:shape.position[1]+shape.shape[1]-1] = rect
return m


# %% Color longest line
def colorLongestLines(matrix, cic, coc, direction):
"""
Expand Down Expand Up @@ -4425,11 +4458,6 @@ def getPossibleOperations(t, c):
if t.backgroundColor!=-1:
x.append(partial(downsize, newShape=outShape, falseColor=t.backgroundColor))


# minimize
if not candTask.sameIOShapes:
x.append(partial(minimize))


###########################################################################
# sameIOShapes
Expand Down Expand Up @@ -4573,6 +4601,14 @@ def getPossibleOperations(t, c):
fun = getPixelChangeCriteria(candTask)
if fun != 0:
x.append(fun)

# extendColor
x.append(getBestExtendColor(candTask))

# fillRectangleInside
for cic in candTask.commonChangedInColors:
for coc in candTask.commonChangedOutColors:
x.append(partial(fillRectangleInside, rectangleColor=cic, fillColor=coc))

# Color longest lines
if len(candTask.colorChanges)==1:
Expand Down Expand Up @@ -4674,8 +4710,8 @@ def getPossibleOperations(t, c):
#if candTask.sameIOShapes and all([len(x)==1 for x in candTask.changedInColors]) and\
#len(candTask.commonChangedInColors)==1:

#if candTask.sameIOShapes and len(candTask.commonChangedInColors)==1:
# x.append(getBestEvolvingLines(candTask))
if candTask.sameIOShapes and len(candTask.commonChangedInColors)==1:
x.append(getBestEvolvingLines(candTask))

###########################################################################
# Other cases
Expand Down Expand Up @@ -4857,5 +4893,8 @@ def getPossibleOperations(t, c):
x.append(partial(cropFullFrame, bigOrSmall="big", includeBorder=False))
x.append(partial(cropFullFrame, bigOrSmall="small", includeBorder=False))

# minimize
if not candTask.sameIOShapes:
x.append(partial(minimize))

return x
18 changes: 9 additions & 9 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ def tryOperations(t, c, firstIt=False):
return
startOps = ("switchColors", "cropShape", "cropAllBackground", "minimize", \
"maxColorFromCell")
#repeatIfPerfect = ("changeShapes")
repeatIfPerfect = ("extendColor")
possibleOps = Utils.getPossibleOperations(t, c)
for op in possibleOps:
for s in range(t.nTrain):
Expand All @@ -549,8 +549,8 @@ def tryOperations(t, c, firstIt=False):
c.t.fixedColors).tolist()
cScore = sum([Utils.incorrectPixels(np.array(cTask["train"][s]["input"]), \
t.trainSamples[s].outMatrix.m) for s in range(t.nTrain)])
#changedPixels = sum([Utils.incorrectPixels(c.t.trainSamples[s].inMatrix.m, \
# np.array(cTask["train"][s]["input"])) for s in range(t.nTrain)])
changedPixels = sum([Utils.incorrectPixels(c.t.trainSamples[s].inMatrix.m, \
np.array(cTask["train"][s]["input"])) for s in range(t.nTrain)])
#print(op, cScore)
newCandidate = Candidate(c.ops+[op], c.tasks+[copy.deepcopy(cTask)], cScore)
b3c.addCandidate(newCandidate)
Expand All @@ -560,9 +560,9 @@ def tryOperations(t, c, firstIt=False):
continue
newCandidate.generateTask()
tryOperations(t, newCandidate)
#elif str(op)[28:60].startswith(repeatIfPerfect) and c.score - changedPixels == cScore and changedPixels != 0:
# newCandidate.generateTask()
# tryOperations(t, newCandidate)
elif str(op)[28:60].startswith(repeatIfPerfect) and c.score - changedPixels == cScore and changedPixels != 0:
newCandidate.generateTask()
tryOperations(t, newCandidate)

class Solution():
def __init__(self, index, taskId, ops):
Expand Down Expand Up @@ -609,7 +609,7 @@ def __init__(self, index, taskId, ops):
# 92,130,567,29,34,52,77,127
# 7,24,31,249,269,545,719,741,24,788
for idx in tqdm([], position=0, leave=True):
taskId = index[idx]
taskId = index[119]
task = allTasks[taskId]
originalT = Task.Task(task, taskId, submission=False)

Expand Down Expand Up @@ -671,7 +671,7 @@ def __init__(self, index, taskId, ops):
# Once the best 3 candidates have been found, make the predictions
for s in range(t.nTest):
for c in b3c.candidates:
#print(c.ops)
print(c.ops)
x = t2.testSamples[s].inMatrix.m.copy()
for opI in range(len(c.ops)):
newX = c.ops[opI](Task.Matrix(x))
Expand All @@ -688,7 +688,7 @@ def __init__(self, index, taskId, ops):
x = recoverAsymmetricGrid(t, x, s)
if taskNeedsRecoloring:
x = recoverOriginalColors(x, testRels[s])
#plot_sample(originalT.testSamples[s], x)
plot_sample(originalT.testSamples[s], x)
if Utils.incorrectPixels(x, originalT.testSamples[s].outMatrix.m) == 0:
#print(idx)
print(idx, c.ops)
Expand Down
Loading

0 comments on commit 87deaea

Please sign in to comment.