-
Notifications
You must be signed in to change notification settings - Fork 0
/
mondrian-defect.jl
323 lines (250 loc) · 9.52 KB
/
mondrian-defect.jl
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
using DataStructures
using ProgressMeter
using JuMP, Gurobi, Suppressor
"""
Defect Mondrian Art Problem Solver
- Find minimal defect for given n
- Currently known up to 65 (https://oeis.org/A276523)
Solve the Mondrian Art problem
1) Collect all rectangles up to size nxn in a Priority Queue with descending area
2) Find all subsets of rectangle with area == n^2 and defect <= d
A) Convert to Integer Programming Problem and Solve with Gurobi
B) Simple Backtracking with Depth First Search
3) Parallel search starting with solutions of smallest defect by backtracking
"""
function mondrian(n::Int64, d::Int64; milp = true, dmin = 0)
# 1) Collect all rectangles up to size nxn in a Priority Queue with descending area
pq = PriorityQueue{Pair{Int64, Int64}, Int64}(Base.Order.Reverse)
for i in 1 : n
for j in i : n
if !(i == j == n)
pq[Pair(i, j)] = i * j
end
end
end
# 2) Find all subsets of rectangle with area == n^2 and defect <= d
areas = Vector{Int64}()
pairs = Vector{Pair{Int64, Int64}}()
for i in pq
push!(pairs, i[1])
push!(areas, i[2])
end
coll = PriorityQueue{Vector{Int64}, Int64}() # (rects, defect)
if milp
combinationsILP!(coll, areas, n, d) # solve with integer programming
else
combinationsDFS!(coll, fill(-1, length(pq)), areas, n, d) # solve with backtracking
end
if isempty(coll)
println("No combinations possible.")
return Inf, fill(0, 0, 0)
end
# filter defects bigger than dmin
while peek(coll)[2] < dmin
dequeue!(coll)
end
println("Combinations possible: " * string(length(coll)))
# 3) Parallel search starting with solutions of smallest defect by backtracking
collVec = Vector{Vector{Int64}}() # convert Priority Queue to Vector for thread access
for i in coll
push!(collVec, i[1])
end
done = Threads.Atomic{Bool}(false) # thread output values
result = fill(fill(0, 0, 0), Threads.nthreads())
defect = fill(typemax(Int64), Threads.nthreads())
p = Progress(length(coll), "Backtracking using " * string(Threads.nthreads()) * " threads.") # progress bar
ProgressMeter.update!(p, 0)
t = Threads.Atomic{Int64}(0)
l = Threads.SpinLock()
Threads.@threads for j in 1 : length(collVec) # Parallel search
if done[] # one thread found a solution
continue
end
# convert to list of rectangles
rects = Vector{Pair{Int64, Int64}}()
for i in 1 : length(collVec[j])
if collVec[j][i] == 1
push!(rects, pairs[i])
end
end
sort!(rects, rev=true, by = x -> x[2]) # heuristic sort by biggest width
rectsRot = rects # rotation by 90 degrees
for i in length(rects) : -1 : 1
push!(rectsRot, reverse(rects[i]))
end
success, result[Threads.threadid()] = solve(n, rects) # using backtracking
Threads.atomic_add!(t, 1) # progress bar update
Threads.lock(l)
ProgressMeter.update!(p, t[])
Threads.unlock(l)
if success # if current thread found solution
done[] = true
defect[Threads.threadid()] = coll[collVec[j]]
end
end
if !done[] # no thread found any solution
return Inf, fill(0, 0, 0)
else
# from all threads with a solution use solution with minimal defect
best = argmin(defect)
display(result[best])
return defect[best], result[best]
end
end
"""
Combinations via Integer Programming
- Translate into ILP and get all solutions via Gurobi
- Faster than Depth first search
"""
function combinationsILP!(coll::PriorityQueue{Vector{Int64}, Int64}, areas::Vector{Int64}, n::Int64, d::Int64)
@suppress begin # Gurobi license message
m = length(areas)
model = Model(Gurobi.Optimizer)
set_optimizer_attribute(model, "PoolSearchMode", 2)
set_optimizer_attribute(model, "PoolSolutions", 10e7)
@variable(model, x[1:m], Bin) # x[i] <=> i-th rectangle is contained in subset
# 2) constraints
@constraint(model, sum(x .* areas) == n^2) # sum equals n^2
# defect smaller or equal dmax
for i in 1 : m
for j in i + 1 : m
# defect condition only necessary if rectangle i and j are selected, so x[i] + x[j] = 2 and the left side simplifies to areas[i] - areas[j]
# otherwise left side is negative and the inequality is trivially fulfilled
@constraint(model, (2 * x[i] + 2 * x[j] - 3) * (areas[i] - areas[j]) <= d)
end
end
optimize!(model)
for i in 1 : result_count(model)
resAreas = areas[BitArray(Int.(round.(value.(x; result = i))))]
coll[Int.(round.(value.(x; result = i)))] = maximum(resAreas) - minimum(resAreas)
end
end # suppress
end
"""
Depth first search
- Backtracking with collection of solutions in Priority Queue
- dfs Vector contains which rectangle are included (1), which are excluded (0) and on which no decision has been made yet (-1)
+------------+---+---+---+----+-----+----+
| Rectangles | 1 | 2 | 3 | 4 | ... | m |
+------------+---+---+---+----+-----+----+
| dfs Vector | 1 | 0 | 1 | -1 | ... | -1 |
+------------+---+---+---+----+-----+----+
"""
function combinationsDFS!(coll::PriorityQueue{Vector{Int64}, Int64}, dfs::Vector{Int64}, areas::Vector{Int64}, n::Int64, d::Int64)
# 1) find next rectangle to decide inclusion in subset
next = findfirst(==(-1), dfs)
# since all possibilities need to be found, only stop when dfs = [0, ... 0, 1 ... 1]
firstOne = findfirst(==(1), dfs)
lastZero = findlast(==(0), dfs)
if !isnothing(firstOne) && !isnothing(lastZero) && isnothing(next)
if (firstOne > lastZero)
return true
end
end
if isnothing(next)
return false
end
# 2) backtracking step for A) include next rectangle in subset or (B) exclude
# A) include rectangle
dfs[next] = 1
valid, area = check(dfs, areas, n, d)
if (valid)
if (area == n^2)
first = findfirst(==(1), dfs)
last = findlast(==(1), dfs)
coll[copy(dfs)] = areas[first] - areas[last] # add solution with defect to Priority Queue
end
if (combinationsDFS!(coll, dfs, areas, n, d))
return true
end
end
# B) exclude rectangle
dfs[next] = 0
if (combinationsDFS!(coll, dfs, areas, n, d))
return true
end
dfs[next] = -1
return false
end
@inline function check(dfs::Vector{Int64}, areas::Vector{Int64}, n::Int64, d::Int64)
# 1) verify defect <= d
first = findfirst(==(1), dfs)
last = findlast(==(1), dfs)
if isnothing(first) # no square selected
return true, 0
end
if (areas[first] - areas[last] > d)
return false, 0
end
# 2) total area bigger than n^2
area = sum(areas[Bool[dfs[i] == 1 for i = 1 : length(areas)]])
return (area <= n^2), area
end
"""
Rectangle Packing via Backtracking
- Use top-left heuristic with rectangles sorted by descending height
"""
function solve(n::Int64, rects::Vector{Pair{Int64, Int64}})
s = length(rects)
height = fill(0, n) # save height stored in each row
used = fill(0, s) # rectangles used
coords = Vector{Pair{Int64, Int64}}() # remember coordinates
count = 0 # number of rectangles used
i = kStart = 1
j = 0
while count < s/2 && count >= 0
# 1) Try to place a rectangle on (i, j)
done = false
k = kStart
while (k <= ceil(s/2) || (k <= s && count > 0)) && !done
if used[k] == 0 && (i + rects[k][1] - 1 <= n && j + rects[k][2] <= n) # piece not used and fits
done = true
# check permiter of rectangle for collisions with other rectangles
for l = 1 : rects[k][1] - 1
if height[i+l] > height[i]
done = false
break
end
end
if !done
k += 1
end
else
k += 1 # try next piece
end
end
if done # rectangle k can be placed on (i, j)
push!(coords, Pair(i, j))
height[i : i + rects[k][1] - 1] .+= rects[k][2]
count += 1
used[s - k + 1] = -1 # different rotation can't be used anymore
used[k] = count
kStart = 1
else # no rectangle can be placed anymore, backtrack
k = argmax(used) # find which piece was last piece
if !isempty(coords)
last = pop!(coords) # find coordinates of last piece
height[last[1] : last[1] + rects[k][1] - 1] .-= rects[k][2] # remove from tiles
end
count -= 1
used[k] = 0
used[s - k + 1] = 0
kStart = k + 1
end
j = minimum(height)
i = findfirst(height .== j) # can't use argmin, since i needs to be minimal such that height[i] = j
end
if count == s/2
tiles = fill(0, n, n) # output square
for l in 1 : length(used)
if used[l] >= 1
i = coords[used[l]][1]
j = coords[used[l]][2] + 1 # since j is the minimal value of height, it is zero-indexed
tiles[i : i + rects[l][1] - 1, j : j + rects[l][2] - 1] = fill(used[l], rects[l][1], rects[l][2])
end
end
return true, tiles
else
return false, fill(0, 0, 0)
end
end