-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathQUANTUM_PACKER.py
1803 lines (1700 loc) · 88 KB
/
QUANTUM_PACKER.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 matplotlib.pyplot as plt
from shapely.geometry import Point, LineString, MultiPoint
from shapely.geometry import Polygon, MultiPolygon
from shapely import affinity
from QUBO_SA_SOLVER import *
from TSP_BATCH_SOLVER_QAOA import *
from RECTANGLE_PACKER import RECTANGLE_PACKER
import pickle
import random
import copy
import time
from datetime import datetime
class QUANTUM_PACKER():
def __init__(self, instance_name, container_height, pieces, n_rotations, tsp_solver, distance_threshold, max_cluster_size,
n_partitions, num_qubits,
backend, solver_backend):
"""
:param instance_name:
:param container_height: fixed height of the container
:param pieces:
:param n_rotations:
:param tsp_solver: string, one of:
BF (brute force),
SA (simulated annealing) or
QAOA (Quantum Approximate Optimization Algorithm) or
QAOA+ (Quantum Alternating Operator Ansatz)
:param distance_threshold: maximum geometric incompatibility between pieces for clustering
:param max_cluster_size:
:param n_partitions: number of partitions to filter
:param num_qubits:
:param backend:
:param solver_backend:
"""
self.instance_name = instance_name
self.H = container_height
self.pieces = [Polygon(piece) for piece in pieces]
self.num_pieces = len(self.pieces)
self.n_rotations = n_rotations
self.TSP_solver = tsp_solver
self.distance_threshold = distance_threshold
self.num_qubits = num_qubits
self.max_cluster_size = max_cluster_size
self.n_partitions = n_partitions
self.alpha = 10.0 # percentage increase for length relaxation
self.beta = 10.0 # percentage increase for height relaxation
self.num_relaxations = 3
self.phi_set = np.arange(0, 360, 5)
self.theta_set = np.arange(0, 360, 360.0 / n_rotations)
self.radius_step = 5
# QAOA setting
if tsp_solver == 'QAOA':
self.use_approximate_optimization = True
self.optimizer = 'COBYLA'
self.num_repeats = 5
elif tsp_solver == 'QAOA+':
self.use_approximate_optimization = False
self.optimizer = 'COBYLA'
self.num_repeats = 4
self.num_shots = 1000
# Quantum backend
self.backend = backend
self.solver_backend = solver_backend
def center_of_shape(self, shape):
"""
Centroid of the shape.
:param shape: Shapely geometry
:return: a Point
"""
center = shape.centroid
return Point(center.x, center.y)
def rotate_shape(self, shape, rotation_angle, rotation_center=None):
"""
Rotates a shape around a center.
:param shape: a Shapely geometry
:param rotation_angle: angle in degrees
:param rotation_center: center of rotation, by default set to the center of the shape.
:return:
"""
if str(type(shape)) == '<class \'list\'>':
shape = MultiPolygon(shape)
if rotation_center == None:
rotation_center = self.center_of_shape(shape)
try:
rotated_shape = affinity.rotate(shape, rotation_angle, rotation_center)
except:
pass
return rotated_shape
def translate_shape(self, shape, vector):
"""
Translates a shape.
:param shape: Shapely geometry
:param vector: translation vector as a Point
:return: translated shape
"""
translated_shape = affinity.translate(shape, xoff=vector.x, yoff=vector.y)
return translated_shape
def place_shape(self, shape, position, angle):
"""
Rotates a shape and places its center at the desired position.
:param shape: Shapely geometry
:param position: Point where to place the center
:param angle: rotation angle in degrees
:return: placed shape
"""
placed_shape = self.rotate_shape(shape, angle)
c = self.center_of_shape(placed_shape)
translation_vector = Point(position.x - c.x, position.y - c.y)
placed_shape = self.translate_shape(placed_shape, translation_vector)
return placed_shape
def is_intersection(self, shape1, shape2):
"""
Test if two shapes intercept.
:param shape1: Shapely geometry
:param shape2: Shapely geometry
:return: True of False
"""
# intersection of a polygon and a polygon
if (str(type(shape1)) == '<class \'shapely.geometry.polygon.Polygon\'>') and (str(type(shape2)) == '<class \'shapely.geometry.polygon.Polygon\'>'):
if shape1.intersection(shape2).is_empty:
return False
else:
return True
# intersection of a segment [A,B] with a polygon
elif str(type(shape1)) == '<class \'shapely.geometry.linestring.LineString\'>' and (str(type(shape2)) == '<class \'shapely.geometry.polygon.Polygon\'>'):
A = shape1.boundary[0]
B = shape1.boundary[1]
L = shape1.length
u_x = B.x - A.x
u_y = B.y - A.y
# for points P in the open segment (A,B)
for i in range(1, 10):
P = Point([A.x + i * u_x / 10.0, A.y + i * u_y / 10.0])
# if P is in shape2
if shape2.contains(P):
# the segment intersects shape2
return True
# otherwise there is no intersection
return False
# intersection of a list of polygons and a polygon
elif str(type(shape1)) == '<class \'list\'>' and (str(type(shape2)) == '<class \'shapely.geometry.polygon.Polygon\'>'):
for polygon in shape1:
if self.is_intersection(polygon, shape2):
return True
return False
# intersection of a polygon and a list of polygons
elif str(type(shape1) == '<class \'shapely.geometry.polygon.Polygon\'>') and str(type(shape2)) == '<class \'list\'>':
for polygon in shape2:
if self.is_intersection(shape1, polygon):
return True
return False
# intersection of a multipolygon and a polygon
elif str(type(shape1)) == '<class \'shapely.geometry.multipolygon.MultiPolygon\'>' and (str(type(shape2)) == '<class \'shapely.geometry.polygon.Polygon\'>'):
return self.is_intersection(list(shape1), shape2)
else:
print('WARNING: UNCOVERED SITUATION IN QUANTUM_PACKER.is_intersection')
def open_segment(self, A, B):
"""
Creates the open segment between two points.
:param A: Point
:param B: Point
:return: LineString
"""
u_AB = np.array([B.x - A.x, B.y - A.x])
u_AB = u_AB / np.linalg.norm(u_AB, 2)
A_prime = Point(A.x + u_AB[0], A.y + u_AB[1])
B_prime = Point(B.x - u_AB[0], B.y - u_AB[1])
return LineString([A_prime, B_prime])
def get_vertices(self, piece):
"""
Vertices of a Polygon.
:param piece: Shapely geometry
:return: list of Points
"""
if str(type(piece)) == '<class \'shapely.geometry.polygon.Polygon\'>':
vertices = list(piece.exterior.coords)
vertices = [Point(e) for e in vertices]
else:
vertices = []
for polygon in piece.geoms:
vertices += self.get_vertices(polygon)
return vertices
def distance(self, e1, e2):
"""
Minimum Euclidean distance between two geometries.
:param e1: geometry
:param e2: geometry
:return: scalar
"""
return e1.distance(e2)
@staticmethod
def get_bounding_polygon(geometry):
if type(geometry) == list:
geometry = MultiPolygon(geometry)
bounding_polygon = geometry.convex_hull
area = bounding_polygon.area
return bounding_polygon, area
def is_facing(self, v1, v2, piece1, piece2):
v1_v2 = self.open_segment(v1, v2)
cond1 = self.is_intersection(v1_v2, piece1)
cond2 = self.is_intersection(v1_v2, piece2)
if (cond1 is False) and (cond2 is False):
return True
else:
return False
def facing_vertices(self, piece1, piece2, show_result=False):
# set of vertices of piece1
V1 = self.get_vertices(piece1)
# set of vertices of piece2
V2 = self.get_vertices(piece2)
# facing vertices
F1 = []
F2 = []
for v1 in V1:
for v2 in V2:
if self.is_facing(v1, v2, piece1, piece2):
F1.append(v1)
break
for v2 in V2:
for v1 in V1:
if self.is_facing(v2, v1, piece2, piece1):
F2.append(v2)
break
if show_result:
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
xs, ys = piece1.exterior.xy
axs.fill(xs, ys, alpha=1, fc='white', ec='black')
xs, ys = piece2.exterior.xy
axs.fill(xs, ys, alpha=1, fc='white', ec='black')
for vertex in V1 + V2:
axs.scatter(vertex.x, vertex.y, c='grey')
for vertex in F1:
axs.scatter(vertex.x, vertex.y, c='black')
for vertex in F2:
axs.scatter(vertex.x, vertex.y, c='black')
plt.title('Facing vertices')
plt.show()
return F1, F2
def distance_between_pieces(self, piece1, piece2):
"""
Computes the distance between two pieces that do not overlap, defined as the complement area inside their
convex hull.
:param piece1: Shapely geometry
:param piece2: Shapely geometry
:return: wasted area and convex hull
"""
area_of_pieces = piece1.area + piece2.area
convex_hull = MultiPolygon([piece1, piece2]).convex_hull
return convex_hull.area - area_of_pieces, convex_hull
def compute_radius(self, shape):
"""
Radius of a shape, defined as the maximum distance of a point of the shape to its center.
:param shape: Polygon
:return: radius
"""
c = self.center_of_shape(shape)
E = self.get_vertices(shape)
radius = 0
for e in E:
d = e.distance(c)
if d > radius:
radius = d
return radius
def place_shape_relative_to(self, shape2, shape1, translation_vector, orientation_shape2):
# rotate shape2 around its center
placed_shape_2 = self.rotate_shape(shape2, orientation_shape2)
# reposition center of shape2 on the center of shape1
center1 = self.center_of_shape(shape1)
center2 = self.center_of_shape(shape2)
placed_shape_2 = self.translate_shape(placed_shape_2, Point([center1.x - center2.x, center1.y - center2.y]))
# translate the center of shape2 wrt to the center of shape1
placed_shape_2 = self.translate_shape(placed_shape_2, translation_vector)
return placed_shape_2
def compute_minimum_distance_between_shapes_at_angle(self, shape1, shape2, phi, show_result=False):
d_min = np.inf
gi_star = 0
best_orientation_2 = 0
u_phi = [math.cos(phi * math.pi / 180), math.sin(phi * math.pi / 180)]
max_radius = self.compute_radius(shape1) + self.compute_radius(shape2)
for orientation_shape2 in self.theta_set:
radius = 0
while radius <= max_radius + self.radius_step:
translation_vector = Point(radius * u_phi[0], radius * u_phi[1])
placed_shape2 = self.place_shape_relative_to(shape2, shape1, translation_vector, orientation_shape2)
if self.is_intersection(shape1, placed_shape2) == False:
d, ch = self.distance_between_pieces(shape1, placed_shape2)
if d < d_min:
d_min = d
best_orientation_2 = orientation_shape2
best_translation = translation_vector
best_placed_shape2 = placed_shape2
gi_star = d_min / ch.area
radius += self.radius_step
if show_result:
if str(type(shape1)) == '<class \'shapely.geometry.polygon.Polygon\'>':
list_of_polygons = [shape1, best_placed_shape2]
else:
list_of_polygons = [polygon for polygon in shape1.geoms] + [best_placed_shape2]
title = 'for phi=' + "{:.1f}".format(phi) + ': ' + 'd=' +"{:.2f}".format(d_min) + \
' using theta=' + "{:.1f}".format(best_orientation_2) + ' and tau=[' + \
"{:.1f}".format(best_translation.x) + ',' + "{:.1f}".format(best_translation.y) + ']'
self.plot_Multipolygon(MultiPolygon(list_of_polygons), title)
return d_min, best_orientation_2, best_translation, best_placed_shape2, gi_star
def minimum_distance_between_shapes_at_angle(self, shape1, shape2, phi, shape1_index, shape2_index, show_result=False):
# file where to store the these calculations
storage_file = 'nofit_function_memory_' + self.instance_name + '.p'
# check if the storage file exists
try:
# load the dictionary
saved_calculations_dict = pickle.load(open(storage_file, 'rb'))
except:
# create an empty dictionary
saved_calculations_dict = {}
# save the file
pickle.dump(saved_calculations_dict, open(storage_file, 'wb'))
# key associated to the calculation needed
key_calculation = str(shape1_index) + '; ' + str(shape2_index) + '; ' + str(phi)
# if the calculation has already been made
if key_calculation in saved_calculations_dict.keys():
# get the results of the calculation
(d_min, best_orientation_2, best_translation, best_placed_shape2, gi_star) = saved_calculations_dict[key_calculation]
# otherwise
else:
# execute the calculation
d_min, best_orientation_2, best_translation, best_placed_shape2, gi_star = self.compute_minimum_distance_between_shapes_at_angle(shape1, shape2, phi)
# store NFF_{shape1,shape2}(phi) = (d_min, best_orientation_2, best_translation, best_placed_shape2)
saved_calculations_dict.update({key_calculation: (d_min, best_orientation_2, best_translation, best_placed_shape2, gi_star)})
# store also the implied value for NFF_{shape2,shape1}(phi)
phi_prime = (phi+180-best_orientation_2) % 360
key_calculation_converse = str(shape2_index) + '; ' + str(shape1_index) + '; ' + str(phi_prime)
best_orientation_1_converse = - best_orientation_2 + 360
r = np.sqrt(best_translation.x ** 2 + best_translation.y ** 2)
best_translation_converse = Point([r * math.cos(phi_prime * math.pi / 180), r * math.sin(phi_prime * math.pi / 180)])
best_placed_shape1 = self.place_shape_relative_to(shape1, shape2, best_translation_converse,
best_orientation_1_converse)
saved_calculations_dict.update({key_calculation_converse: (d_min,
best_orientation_1_converse,
best_translation_converse, best_placed_shape1, gi_star)})
# save the file
pickle.dump(saved_calculations_dict, open(storage_file, 'wb'))
# return the results
return d_min, best_orientation_2, best_translation, best_placed_shape2, gi_star
def minimum_distance_between_shapes(self, piece1, piece2, piece1_name, piece2_name):
d_min_star = np.inf
gi_star = 0
best_placed_shape2_star = None
# for each orbiting angle phi
for phi in self.phi_set:
# compute the value of the nofit function
piece1_index = piece1_name[1:]
piece2_index = piece2_name[1:]
d_min, best_orientation_2, best_translation, best_placed_shape2, gi = self.minimum_distance_between_shapes_at_angle(piece1, piece2, phi, piece1_index, piece2_index)
if d_min < d_min_star:
d_min_star = d_min
gi_star = gi
best_placed_shape2_star = best_placed_shape2
# create a new plot
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
# plot the convex hull area in grey
_, ch = self.distance_between_pieces(piece1, best_placed_shape2_star)
xs, ys = ch.exterior.xy
axs.fill(xs, ys, alpha=1.0, fc='grey', ec='black')
# plot piece1 in white
xs, ys = piece1.exterior.xy
axs.fill(xs, ys, alpha=1.0, fc='white', ec='black')
# plot best_placed_shape2_star in white
xs, ys = best_placed_shape2_star.exterior.xy
axs.fill(xs, ys, alpha=1.0, fc='white', ec='black')
# add title
title = 'd(' + piece1_name + ', ' + piece2_name + ') = ' + "{:.1f}".format(d_min_star) + ' gi=' + "{:.3f}".format(gi_star)
plt.title(title)
# show plot
plt.show()
plt.show()
# save plot
file_name = 'd(' + piece1_name + ', ' + piece2_name + ').pdf'
fig.savefig(file_name)
# return the distance
return d_min_star, gi_star
def identical_pieces_lower_index_dict(self):
# for each piece index, determines which list of pieces of strictly lower index are the same
identical_pieces_dict = {}
for i in range(self.num_pieces):
pieces_identical_to_i = []
for j in range(i):
if self.pieces[i].equals(self.pieces[j]):
pieces_identical_to_i.append(j)
identical_pieces_dict.update({i: pieces_identical_to_i})
return identical_pieces_dict
def compute_distance_matrix(self):
# file where to store the distance matrix
storage_file = 'distance_matrix_' + self.instance_name + '.p'
storage_file_incompatibility = 'incompatibility_matrix_' + self.instance_name + '.p'
# check if the distance matrix has already been computed and saved locally
try:
D = pickle.load(open(storage_file, 'rb'))
GI = pickle.load(open(storage_file_incompatibility, 'rb'))
print('The distance matrix and nofit functions have already been pre-computed and will be directly loaded')
except:
print('The distance matrix and nofit functions need to be pre-computed. Please wait...')
num_shapes = len(self.pieces)
# for each piece index, determines which list of pieces of strictly lower index are the same
identical_pieces_dict = self.identical_pieces_lower_index_dict()
# compute distance matrix avoiding recomputing distances between identical pieces
D = np.zeros((num_shapes, num_shapes))
GI = np.zeros((num_shapes, num_shapes))
computed_distances = []
for i in range(num_shapes):
pieces_identical_to_i = identical_pieces_dict[i]
if len(pieces_identical_to_i) == 0:
for j in range(num_shapes):
pieces_identical_to_j = identical_pieces_dict[j]
if len(pieces_identical_to_j) == 0:
d_ij, gi_ij = self.minimum_distance_between_shapes(self.pieces[i], self.pieces[j], 'P'+str(i), 'P'+str(j))
distance_key = str(i) + '-' + str(j)
computed_distances.append(distance_key)
else:
first_piece_identical_to_j = min(pieces_identical_to_j)
if (first_piece_identical_to_j < j):
distance_key = str(i) + '-' + str(first_piece_identical_to_j)
if distance_key in computed_distances:
d_ij = D[i, first_piece_identical_to_j]
gi_ij = GI[i, first_piece_identical_to_j]
else:
d_ij, gi_ij = self.minimum_distance_between_shapes(self.pieces[i], self.pieces[j])
computed_distances.append(distance_key)
else:
d_ij, gi_ij = self.minimum_distance_between_shapes(self.pieces[i], self.pieces[j])
distance_key = str(i) + '-' + str(j)
computed_distances.append(distance_key)
# store d_ij in the distance matrix
D[i, j] = d_ij
GI[i, j] = gi_ij
print('Computed distance between P' + str(i) + ' and P' + str(j))
else:
first_piece_identical_to_i = min(pieces_identical_to_i)
D[i, :] = D[first_piece_identical_to_i, :]
D[:, i] = D[i, :]
GI[i, :] = GI[first_piece_identical_to_i, :]
GI[:, i] = GI[i, :]
# round D to first decimal
D = np.round(D, decimals=1)
GI = np.round(GI, decimals=3)
# save the distance matrix
pickle.dump(D, open(storage_file, 'wb'))
pickle.dump(GI, open(storage_file_incompatibility, 'wb'))
print('Computation done! Saved matrix in ' + storage_file)
# print matrix
print(D)
# show matrix in latex code
print('$$ D = \left[ \\begin{array}{rrrrrrrr}')
for i in range(D.shape[0]):
row = ''
values = ["{:.1f}".format(D[i, j]) for j in range(D.shape[1])]
row = ' & '.join(values) + ' \\\\'
print(row)
print('\\end{array}\\right] $$')
print('$$ GI = \left[ \\begin{array}{rrrrrrrr}')
for i in range(GI.shape[0]):
row = ''
values = ["{:.3f}".format(GI[i, j]) for j in range(GI.shape[1])]
row = ' & '.join(values) + ' \\\\'
print(row)
print('\\end{array}\\right] $$')
# return the distance matrix
return D, GI
def decode_TSP_solution(self, results_dictionary):
num_cities = int(math.sqrt(len(results_dictionary.keys())))
hamiltonian_path = np.zeros(num_cities)
for var in results_dictionary.keys():
parsed_variable_name = var.split('_')
i = int(parsed_variable_name[1])
p = int(parsed_variable_name[2])
value = results_dictionary[var]
if value == 1:
hamiltonian_path[p-1] = i
return hamiltonian_path
@staticmethod
def merge(p1, p2):
"""
Merges two geometric figures into one.
:param p1: Shapely geometry
:param p2: Shapely geometry
:return: Shapely geometry
"""
if str(type(p1)) == '<class \'shapely.geometry.multipolygon.MultiPolygon\'>':
list_of_polygons = list(p1) + [p2]
result = MultiPolygon(list_of_polygons)
else:
if str(type(p1)) != '<class \'list\'>':
result = MultiPolygon([p1, p2])
else:
result = MultiPolygon(p1 + [p2])
return result
def greedy_packer(self, pieces, show_result=False):
"""
Packs a list of pieces one by one and in the order given by the list, trying at any step to minimize the area
of the bounding box.
:param pieces: list of pieces as Polygons
:return: all pieces packed as a MultiPolygon
"""
# number of pieces to pack
num_pieces = len(pieces)
# initialize the packed pieces with the first piece
packed_pieces = [self.pieces[pieces[0]]]
# position of center and orientation of the last piece packed
tau_last = self.center_of_shape(self.pieces[pieces[0]])
theta_last = 0
previous_placed_piece_to_pack = self.pieces[pieces[0]]
# for following pieces i to pack
for i in range(1, num_pieces):
# the lastly packed piece
last_piece_packed = pieces[i-1]
# the piece to pack now
piece_to_pack = pieces[i]
# initialize status of packing
status_packing = 'fail'
# initialize the wasted area of the bounding box with which the new pieces can be packed
w_star = np.inf
# for every possible rotation angle phi of piece_to_pack around last_piece_packed
for phi in self.phi_set:
# determine theta_2 and translation_2 using the nofit function
_, theta_2, translation_2, _, _ = self.minimum_distance_between_shapes_at_angle(self.pieces[last_piece_packed], self.pieces[piece_to_pack], phi, last_piece_packed, piece_to_pack)
# position the new piece to pack relative to the last one
theta_new = theta_last + theta_2
r = math.sqrt(translation_2.x ** 2 + translation_2.y ** 2)
tau_new = Point([r * math.cos((theta_last + phi) * math.pi / 180), r * math.sin((theta_last + phi) * math.pi / 180)])
placed_piece_to_pack = self.place_shape_relative_to(self.pieces[piece_to_pack], previous_placed_piece_to_pack, tau_new, theta_new)
# compute the new waste
_, new_w = self.fit_bounding_box(self.merge(packed_pieces, placed_piece_to_pack))
# if the placement at angle phi given by the nofit function for the piece to pack is valid (avoids overlapping)
if self.is_intersection(packed_pieces, placed_piece_to_pack) == False:
# if the placement at angle phi reduces the area of the bounding box
if new_w < w_star:
# record the best distance and the placement for the piece to pack
w_star = new_w
placed_piece_to_pack_star = placed_piece_to_pack
theta_star = theta_new
tau_star = tau_new
# update the status of packing
status_packing = 'success'
# show result
#if show_result:
# title = ' improved for phi=' + "{:.1f}".format(phi) + ' with theta=' + "{:.1f}".format(theta_star)
# self.plot_Multipolygon(self.merge(packed_pieces, placed_piece_to_pack), title)
# else, the placement given by the nofit function at angle phi has failed
else:
# keep theta_2 but keep translating the piece in the direction of translation_2 until the piece fits
translation_2_norm = math.sqrt(translation_2.x ** 2 + translation_2.y ** 2)
delta_translation_2 = Point([self.radius_step * translation_2.x / translation_2_norm, self.radius_step * translation_2.y / translation_2_norm])
while self.is_intersection(packed_pieces, placed_piece_to_pack) == True:
# enlarge a bit translation_2
translation_2 = Point([translation_2.x + delta_translation_2.x,
translation_2.y + delta_translation_2.y])
# re-position the new piece to pack relative to the last one
theta_new = theta_last + theta_2
r = math.sqrt(translation_2.x ** 2 + translation_2.y ** 2)
tau_new = Point([tau_last.x + r * math.cos((theta_last + phi) * math.pi / 180),
tau_last.y + r * math.sin((theta_last + phi) * math.pi / 180)])
placed_piece_to_pack = self.place_shape_relative_to(self.pieces[piece_to_pack], self.pieces[last_piece_packed], tau_new, theta_new)
# compute the new waste
_, new_w = self.fit_bounding_box(self.merge(packed_pieces, placed_piece_to_pack))
# if the placement at angle phi reduces the area of the bounding box
if new_w < w_star:
# record the best distance and the placement for the piece to pack
w_star = new_w
placed_piece_to_pack_star = placed_piece_to_pack
theta_star = theta_new
tau_star = tau_new
# update the status of packing
status_packing = 'success'
# show result
#if show_result:
# title = 'improved for phi=' + "{:.1f}".format(phi) + ' with theta=' + "{:.1f}".format(theta_star)
# self.plot_Multipolygon(self.merge(packed_pieces, placed_piece_to_pack), title)
# if packing piece i was possible
if status_packing == 'success':
# greedily pack the piece to pack with the others according to the best placement found
packed_pieces = copy.deepcopy(self.merge(packed_pieces, placed_piece_to_pack_star))
# update position center and orientation of the last piece packed
tau_last = tau_star
theta_last = theta_star
previous_placed_piece_to_pack = placed_piece_to_pack_star
# otherwise, packing is impossible and must be aborted
else:
packed_pieces = None
break
if show_result:
title = 'Greedy packing of pieces ' + '-'.join([str(p) for p in pieces])
self.plot_Multipolygon(packed_pieces, title)
return packed_pieces
def plot_Multipolygon(self, multi_polygon, my_title=''):
# if multi_polygon is just a polygon then make it a list of one polygon
if str(type(multi_polygon)) == '<class \'shapely.geometry.polygon.Polygon\'>':
multi_polygon = MultiPolygon([multi_polygon])
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
for geom in multi_polygon:
xs, ys = geom.exterior.xy
axs.fill(xs, ys, alpha=0.5, fc='r', ec='none')
plt.title(my_title)
plt.show()
def show_pieces(self):
num_pieces = len(self.pieces)
num_pieces_per_row = int(math.sqrt(num_pieces))
W = 0
H = 0
for i, p in enumerate(self.pieces):
bbox = p.bounds
minx = bbox[0]
miny = bbox[1]
maxx = bbox[2]
maxy = bbox[3]
width = maxx - minx
height = maxy - miny
if width > W:
W = width
if height > H:
H = height
cell_spacing = 20
W += cell_spacing
H += cell_spacing
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
row = 1
column = 1
for i, p in enumerate(self.pieces):
position = Point([row * W, column * H])
p_placed = self.place_shape(p, position, 0)
xs, ys = p_placed.exterior.xy
axs.fill(xs, ys, alpha=1.0, fc='white', ec='black')
center = self.center_of_shape(p_placed)
axs.plot((center.x), (center.y), 'o', color='k')
axs.text(center.x + 30, center.y - 30, 'P'+str(i))
if column >= num_pieces_per_row:
column = 1
row += 1
else:
column += 1
plt.title(self.instance_name + ': ' + str(num_pieces) + ' pieces')
plt.show()
file_name = 'PIECES ' + self.instance_name + '.pdf'
fig.savefig(file_name)
def fit_bounding_box(self, multi_polygon, show_result=False):
"""
Returns the general minimum bounding rectangle that contains the object.
This rectangle is not constrained to be parallel to the coordinate axes.
"""
# if multi_polygon is just a polygon then make it a list of one polygon
if str(type(multi_polygon)) == '<class \'shapely.geometry.polygon.Polygon\'>':
multi_polygon = MultiPolygon([multi_polygon])
# if multi_polygon is a list of polygons, then make it a MultiPolygon
if str(type(multi_polygon)) == '<class \'list\'>':
multi_polygon = MultiPolygon(multi_polygon)
# find rectangular bounding box with minimum area not parallel to the axis
bounding_box = multi_polygon.minimum_rotated_rectangle
# show result of fitting a bounding box around the pieces
if show_result:
fig, axs = plt.subplots()
axs.set_aspect('equal', 'datalim')
xs, ys = bounding_box.exterior.xy
axs.fill(xs, ys, alpha=0.5, fc='b', ec='none')
for geom in multi_polygon.geoms:
xs, ys = geom.exterior.xy
axs.fill(xs, ys, alpha=0.5, fc='r', ec='none')
plt.title('Bounding box')
plt.show()
bounding_box_area = bounding_box.area
return bounding_box, bounding_box_area
def get_bounding_box_dimensions(self, polygon):
x_min = polygon.bounds[0]
y_min = polygon.bounds[1]
x_max = polygon.bounds[2]
y_max = polygon.bounds[3]
# get length of bounding box edges
dimensions = (x_max - x_min, y_max - y_min)
return dimensions
@staticmethod
def build_EXACT_COVER_objective_function(N, S):
"""
Given a set of N elements, X={c_1, ..., c_N}, a family of M subsets of X,
S={S_1, ..., S_M} such that S_i \subset X and \cup_{i=1}^M S_i = X, find a
subset I of {1, ..., M} such that \cup_{i \in I} S_i = X where S_i \cap S_j = \emptyset
for i \neq j \in I.
:param N: number of elements in X
:param S: list of lists of integers in [1, ..., N]
:return: list I of indices of the sets selected from S
"""
# number of subsets in S
M = len(S)
# build list of binary variables s_i, i \in {1, ..., M}
binary_variables = []
for i in range(1, M + 1):
binary_variables.append('s_' + str(i))
# build list of coefficients w_i of the binary variables s_i
linear_coefficients = []
for i in range(1, M + 1):
# coefficient of s_i is w_i = - 2 * |S_i|
w_i = - 2 * len(S[i-1])
linear_coefficients.append(w_i)
# build dictionary of quadratic coefficients
quadratic_coefficients = {}
for i in range(1, M + 1):
for k in range(1, M + 1):
# coefficient of s_i * s_k is |S_i \cap S_k|
w_ik = len([e for e in S[i-1] if e in S[k-1]])
s_i = 's_' + str(i)
s_k = 's_' + str(k)
quadratic_coefficients.update({(s_i, s_k): w_ik})
return binary_variables, linear_coefficients, quadratic_coefficients
def pack_rectangles(self, rectangles, rectangle_names, height_limit):
my_rect_packer = RECTANGLE_PACKER(rectangles, rectangle_names, height_limit)
rectangles_arrangement = my_rect_packer.solve()
return rectangles_arrangement
def unpack_rectangles(self, rectangles_arrangement, R):
# initialize the layout (list of polygons)
layout = []
# initialize the rectangle layout (list of rectangles)
rectangle_layout = []
# plot the pieces
for rectangle_id, value in rectangles_arrangement.items():
# position of the rectangle in the board
x, y, w, h, b = value[0], value[1], value[2], value[3], value[4]
rectangle = Polygon([(x, y), (x + w, y), (x + w, y + h), (x, y + h)])
# pieces packed in a bounding box
packed_pieces = R[rectangle_id][0]
bounding_box = R[rectangle_id][1]
# determines the geometric transformation (translation and rotation) that maps the bounding box to the rectangle
position_bounding_box = self.center_of_shape(bounding_box)
position_rectangle = self.center_of_shape(rectangle)
translation = Point(
(position_rectangle.x - position_bounding_box.x, position_rectangle.y - position_bounding_box.y))
superposition_ratio_star = 0.0
for angle in range(360):
placed_bounding_box = self.place_shape(bounding_box, position_rectangle, angle)
superposition_ratio = rectangle.intersection(placed_bounding_box).area / rectangle.area
if superposition_ratio > superposition_ratio_star:
superposition_ratio_star = superposition_ratio
angle_star = angle
if superposition_ratio_star > 0.999:
break
# move the packed pieces using this transformation
packed_pieces = self.rotate_shape(packed_pieces, angle_star, position_bounding_box)
packed_pieces = self.translate_shape(packed_pieces, translation)
# if packed_pieces is just a polygon then make it a list of one polygon
if str(type(packed_pieces)) == '<class \'shapely.geometry.polygon.Polygon\'>':
packed_pieces = MultiPolygon([packed_pieces])
# adds the packed pieces to the layout
layout += list(packed_pieces)
# adds the rectangle to the rectangle layout
rectangle_layout.append(rectangle)
return layout, rectangle_layout
def is_in_upper_right_quadrant(self, piece):
"""
Check that a piece is positionned within the quadrant x >= 0 and y >= 0
:param translated_piece:
:return: Boolean
"""
V = self.get_vertices(piece)
for v in V:
if v.x < 0 or v.y < 0:
return False
return True
def local_optimization(self, layout, container):
"""
Moves all pieces of the layout to the left and down, while avoiding piece overlapping and going out of the container.
:param layout: list of pieces
:param container: a polygon
:return: optimized layout
"""
print(' running local optimization...')
# prioritized list of unitary vectors for translating down and to the left
prioritized_directions = []
prioritized_directions.append(Point([-1, 0]))
prioritized_directions.append(Point([-1, -1]))
prioritized_directions.append(Point([-1, +1]))
prioritized_directions.append(Point([0, -1]))
is_optimal = False
while is_optimal == False:
is_optimal = True
for i, piece in enumerate(layout):
# list of pieces without i
other_pieces = layout
del other_pieces[i]
# move the piece towards the origin as much as possible, while avoiding overlapping with the other ones
keep_moving_piece = True
while keep_moving_piece:
# test if we can move the piece in one of the allowed directions and if so do it
keep_moving_piece = False
# for each allowed direction
for vector in prioritized_directions:
# translate the piece
translated_piece = self.translate_shape(piece, vector)
# if the piece is still in the upper right quadrant (x >= 0 and y >= 0)
if self.is_in_upper_right_quadrant(translated_piece):
# check if the translated piece intersects another one
intersection_test = False
for other_piece in other_pieces:
if self.is_intersection(translated_piece, other_piece):
intersection_test = True
break
# and if the translated piece doesn't intersect another one
if not intersection_test:
# translate the piece
piece = translated_piece
# keep moving it
keep_moving_piece = True
# the layout is still not optimal
is_optimal = False
# don't look at the remaining directions
break
# replace moved pieced i of the layout
other_pieces[i:i] = [piece]
layout = other_pieces
# return optimal layout
return layout
def relocate_rightmost_piece(self, layout):
"""
:param layout:
:return:
"""
# initialize the improved layout
improved_layout = layout
# finds the rightmost piece
x_max = -np.inf
rightmost_piece_index = -1
rightmost_piece = None
success = False
for i, piece in enumerate(layout):
piece_x_max = piece.bounds[2]
if piece_x_max > x_max:
x_max = piece_x_max
rightmost_piece_index = i
rightmost_piece = piece
# delete the rightmost piece from the layout
layout_without_rightmost_piece = copy.deepcopy(layout)
del layout_without_rightmost_piece[rightmost_piece_index]
# find a placement for the piece to relocate
grid_step_x = x_max / 100
grid_step_y = self.H / 100
for x in np.arange(0, x_max, grid_step_x):
for y in np.arange(0, self.H, grid_step_y):
for theta in self.theta_set:
# place the piece at (x,y) with angle theta
repositionned_piece = self.place_shape(rightmost_piece, Point(x, y), theta)
# if the piece is in the upper right quadrant
if self.is_in_upper_right_quadrant(repositionned_piece):
# if the container height is not exceeded by the re-positioned piece
h = repositionned_piece.bounds[3]
if h <= self.H:
# check if the translated piece intersects another one
intersection_test = False
for other_piece in layout_without_rightmost_piece:
if self.is_intersection(repositionned_piece, other_piece):
intersection_test = True
break
# if the translated piece doesn't intersect another one
if not intersection_test:
# insert the re-positionned piece in the layout
new_layout = copy.deepcopy(layout_without_rightmost_piece)
new_layout.append(repositionned_piece)
# if the repositionned piece is more to the left that before
x_max_new = repositionned_piece.bounds[2]
if x_max_new < x_max:
print('Shifting rightmost piece from x_max=' + str(x_max) + ' to ' + str(x_max_new))
improved_layout = new_layout
success = True
return improved_layout, rightmost_piece_index, success
print('Layout could not be improved by shifting the rightmost piece !')
return improved_layout, rightmost_piece_index, success
# return improved layout
return improved_layout
def required_height(self, multipolygon):
multipolygon = MultiPolygon(multipolygon)
# bounds of the multipolygon
bounds = list(multipolygon.bounds)
multipolygon_y_min = round(bounds[1], 3)
multipolygon_y_max = round(bounds[3], 3)
height = multipolygon_y_max - multipolygon_y_min
return height
def is_in_container(self, multipolygon, container):
# bounds of the multipolygon
bounds = list(multipolygon.bounds)
multipolygon_x_min = round(bounds[0], 3)
multipolygon_y_min = round(bounds[1], 3)
multipolygon_x_max = round(bounds[2], 3)
multipolygon_y_max = round(bounds[3], 3)
# bounds of the container
bounds = list(container.bounds)
x_min = round(bounds[0], 3)
y_min = round(bounds[1], 3)
x_max = round(bounds[2], 3)
y_max = round(bounds[3], 3)
# test if the multipolygon is in the container
if (multipolygon_x_min >= x_min) and (multipolygon_y_min >= y_min) and (multipolygon_x_max <= x_max) and (multipolygon_y_max <= y_max):
return True
else:
return False
def generate_partitions(self, num_partitions, min_cardinality, max_cardinality):
"""
Generates a list of random partitions of the set {0, 1, ..., num_pieces-1}.
:param num_partitions: number of partitions generates
:param max_cardinality: maximum cardinality of elements in the partitions
:return: list of partitions, each partition itself being a list of strings of the form '0-2-3-4-5-9'
"""
partitions = []
support = []
for i in range(num_partitions):
# initialize a new partition
partition = []
# initialize list of piece indices
Q = list(range(self.num_pieces))
while len(Q) > 0:
# generate a random integer k between 1 and max_cardinality
k = random.randint(min_cardinality, max_cardinality)
# select randomly k elements from Q without replacement
try:
P = random.sample(Q, k)
# unless Q has size less than k
except:
# take all pieces left in Q
P = Q
# sort the indices in P
P.sort()
# add the P as element to the partition
partition.append(P)
# add P to the support, if P is not already in the support
if P not in support:
support.append(P)
# remove P from Q
Q = [e for e in Q if e not in P]
# add the partition to the list
partitions.append(partition)
# return the list of partitions
return partitions, support
def modulo_key(self, key):
"""
Takes a key for a set of pieces, e.g. '0-4-12-15' and replaces each piece index
by the minimum index of an identical piece.
:param key:
:return: string
"""
indices = key.split('-')
indices = [int(s) for s in indices]
minimum_indices = []
identical_pieces_dict = self.identical_pieces_lower_index_dict()
for index in indices: