-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathDissection.cpp
More file actions
1505 lines (1176 loc) · 52.1 KB
/
Dissection.cpp
File metadata and controls
1505 lines (1176 loc) · 52.1 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
#include "Dissection.h"
#include "Util.h"
#include <random>
#include <iostream>
using namespace std::chrono;
using namespace std;
Shape generatePiecesLocally_distribution(Shape & shape, int pieceNumThreshold)
{
Shape newShape = shape;
bool isSuccess = false;
int minTileSize = newShape.getSmallestPieceSize();
int maxTileSize = newShape.getLargestPieceSize();
for(int k = 0; k < 30; ++k)
{
Shape currShape = newShape;
bool noPossiblePieceTemplate;
Piece eliminationPieceTemplate = selectEliminationPieceTemplate(currShape.current_templates, currShape, pieceNumThreshold, noPossiblePieceTemplate);
cout << endl << eliminationPieceTemplate.printPixels() << endl;
if (noPossiblePieceTemplate)
{
cout << "no Possible Piece Template. " << endl;
break;
}
vector<Piece> eliminationPieces = getTemplateInstances(eliminationPieceTemplate, currShape);
// cout << "eliminationPieces: " << eliminationPieces.size() << endl;
// select one piece from them
vector<float> possibList(eliminationPieces.size(), 1);
vector<Piece> oneEliminationPieceList;
oneEliminationPieceList.push_back(eliminationPieces[GetRandomObjIndex(possibList, 1)]);
int N, K;
vector<int> eliminationPieceIDList;
Shape subShape = getSubShape(oneEliminationPieceList, currShape, N, K, eliminationPieceIDList);
subShape.updateTemplates(false);
updateAccessibilityAndBlockability(subShape);
// cout << "Subshape: N = " << N << ", K = " << K << endl;
// cout << endl << subShape.printAllPixels() << endl;
int original_K = currShape.current_templates.size();
double original_var = currShape.getInstanceNumDeviation();
// cout << "before delete K: " << currShape.current_templates.size() << endl;
// cout << "before delete N: " << currShape.pieces.size() << endl;
sort(eliminationPieceIDList.begin(), eliminationPieceIDList.end());
for (int i = eliminationPieceIDList.size() - 1; i >= 0; --i)
{
currShape.pieces.erase(currShape.pieces.begin() + eliminationPieceIDList[i]);
}
currShape.updateTemplates(false);
// cout << "after delete K: " << currShape.current_templates.size() << endl;
// cout << "after delete N: " << currShape.pieces.size() << endl;
double timeLimitForEachSubshape = 10.0;
double runningTime;
int bestScore;
auto start = high_resolution_clock::now();
int seed = 0;
while (1)
{
bool isFound = false;
Shape newSubShape = generatePieces(subShape, N, K, 15, 2, false, " ",
seed, 0.3, 3.0, minTileSize, maxTileSize, 2, true, 10, runningTime, bestScore, currShape.current_templates, isFound, false);
if (isFound)
{
vector<Piece> updatedTemplates = currShape.current_templates;
for (auto & piece : newSubShape.current_templates)
{
if (!isPieceinTemplates(piece, updatedTemplates))
{
updatedTemplates.push_back(piece);
}
}
cout << "original_K: " << original_K << endl;
cout << "after_K: " << updatedTemplates.size() << endl;
if (updatedTemplates.size() == original_K)
// if (1)
{
// cout << "successfully reduce " << original_K - updatedTemplates.size() << " templates. " << endl;
for (auto & piece : newSubShape.pieces)
{
currShape.pieces.push_back(piece);
}
Shape tempShape;
tempShape = currShape;
tempShape.updateTemplates(false);
tempShape.assignPieceID();
tempShape.assignPieceClusterID();
double after_var = tempShape.getInstanceNumDeviation();
cout << "original_var: " << original_var << endl;
cout << "after_var: " << after_var << endl;
if (after_var < original_var)
{
cout << "original_var: " << original_var << endl;
cout << "after_var: " << after_var << endl;
newShape = currShape;
newShape.updateTemplates(false);
newShape.assignPieceID();
newShape.assignPieceClusterID();
isSuccess = true;
break;
}
}
// if (updatedTemplates.size() == original_K)
// {
// if (newSubShape.getSmallestPieceSize() > minTileSize or newSubShape.getLargestPieceSize() < maxTileSize)
// {
// newShape = currShape;
// newShape.updateTemplates();
// newShape.assignPieceID();
// newShape.assignPieceClusterID();
// }
// isSuccess = true;
// break;
// }
}
auto time_now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(time_now - start);
double time_elapsed = (duration.count() / (double)1000) / 60;
if (time_elapsed > timeLimitForEachSubshape)
{
cout << "unsuccessfuly to reduce K. " << endl;
break;
}
++seed;
}
if (isSuccess)
break;
}
return newShape;
}
Shape generatePiecesLocally(Shape & shape, int pieceNumThreshold)
{
Shape newShape = shape;
bool isSuccess = false;
int minTileSize = newShape.getSmallestPieceSize();
int maxTileSize = newShape.getLargestPieceSize();
for(int k = 0; k < 20; ++k)
{
Shape currShape = newShape;
bool noPossiblePieceTemplate;
Piece eliminationPieceTemplate = selectEliminationPieceTemplate(currShape.current_templates, currShape, pieceNumThreshold, noPossiblePieceTemplate);
cout << endl << eliminationPieceTemplate.printPixels() << endl;
if (noPossiblePieceTemplate)
{
cout << "no Possible Piece Template. " << endl;
break;
}
vector<Piece> eliminationPieces = getTemplateInstances(eliminationPieceTemplate, currShape);
cout << "eliminationPieces: " << eliminationPieces.size() << endl;
for (auto & piece : eliminationPieces)
{
cout << endl << piece.printPixels() << endl;
}
int N, K;
vector<int> eliminationPieceIDList;
Shape subShape = getSubShape(eliminationPieces, currShape, N, K, eliminationPieceIDList);
subShape.updateTemplates(false);
updateAccessibilityAndBlockability(subShape);
// cout << "Subshape: N = " << N << ", K = " << K << endl;
// cout << endl << subShape.printAllPixels() << endl;
int original_K = currShape.current_templates.size();
// cout << "before delete K: " << currShape.current_templates.size() << endl;
// cout << "before delete N: " << currShape.pieces.size() << endl;
sort(eliminationPieceIDList.begin(), eliminationPieceIDList.end());
for (int i = eliminationPieceIDList.size() - 1; i >= 0; --i)
{
currShape.pieces.erase(currShape.pieces.begin() + eliminationPieceIDList[i]);
}
currShape.updateTemplates(false);
// cout << "after delete K: " << currShape.current_templates.size() << endl;
// cout << "after delete N: " << currShape.pieces.size() << endl;
double timeLimitForEachSubshape = 5.0;
double runningTime;
int bestScore;
auto start = high_resolution_clock::now();
int seed = 0;
while (1)
{
bool isFound = false;
Shape newSubShape = generatePieces(subShape, N, K, 15, 5, false, " ",
seed, 0.3, 3.0, minTileSize, maxTileSize, 2, true, 10, runningTime, bestScore, currShape.current_templates, isFound, false);
if (isFound)
{
vector<Piece> updatedTemplates = currShape.current_templates;
for (auto & piece : newSubShape.current_templates)
{
if (!isPieceinTemplates(piece, updatedTemplates))
{
updatedTemplates.push_back(piece);
}
}
cout << "original_K: " << original_K << endl;
cout << "after_K: " << updatedTemplates.size() << endl;
if (updatedTemplates.size() < original_K)
{
cout << "successfully reduce " << original_K - updatedTemplates.size() << " templates. " << endl;
for (auto & piece : newSubShape.pieces)
{
currShape.pieces.push_back(piece);
}
newShape = currShape;
newShape.updateTemplates(false);
newShape.assignPieceID();
newShape.assignPieceClusterID();
isSuccess = true;
break;
}
}
auto time_now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(time_now - start);
double time_elapsed = (duration.count() / (double)1000) / 60;
if (time_elapsed > timeLimitForEachSubshape)
{
cout << "unsuccessfully to reduce K. " << endl;
break;
}
++seed;
}
if (isSuccess)
break;
}
return newShape;
}
Shape optimizePiecesSizeLocally(Shape & shape, int minTileSize, int maxTileSize)
{
Shape newShape = shape;
cout << "There are " << newShape.getSmallSizePiecesNum(minTileSize) << " small pieces and " << newShape.getLargeSizePiecesNum(maxTileSize) << " large pieces." << endl;
for(int k = 0; k < 1; ++k)
{
Shape currShape = newShape;
vector<Piece> eliminationPieces;
for (int i = 0; i < currShape.pieces.size(); ++i)
{
if (currShape.pieces[i].pixels.size() < minTileSize or currShape.pieces[i].pixels.size() > maxTileSize)
{
eliminationPieces.push_back(currShape.pieces[i]);
break;
}
}
int N, K;
vector<int> eliminationPieceIDList;
Shape subShape = getSubShape(eliminationPieces, currShape, N, K, eliminationPieceIDList);
subShape.updateTemplates(false);
updateAccessibilityAndBlockability(subShape);
int originalInvalidPieceNum = subShape.getSmallSizePiecesNum(minTileSize) + subShape.getLargeSizePiecesNum(maxTileSize);
sort(eliminationPieceIDList.begin(), eliminationPieceIDList.end());
for (int i = eliminationPieceIDList.size() - 1; i >= 0; --i)
{
currShape.pieces.erase(currShape.pieces.begin() + eliminationPieceIDList[i]);
}
currShape.updateTemplates(false);
double timeLimitForEachSubshape = 1.0;
double runningTime;
int bestScore;
auto start = high_resolution_clock::now();
int seed = 0;
while (1)
{
bool isFound = false;
Shape newSubShape = generatePieces(subShape, N, N, 10, 1, false, " ",
seed, 0.3, 3.0, minTileSize, maxTileSize, 2, true, 5, runningTime, bestScore, currShape.current_templates, isFound, false);
if (isFound)
{
for (auto & piece : newSubShape.pieces)
{
currShape.pieces.push_back(piece);
}
cout << "successfully reduce " << originalInvalidPieceNum << " invalid pieces. " << endl;
newShape = currShape;
newShape.updateTemplates(false);
newShape.assignPieceID();
newShape.assignPieceClusterID();
break;
}
auto time_now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(time_now - start);
double time_elapsed = (duration.count() / (double)1000) / 60;
if (time_elapsed > timeLimitForEachSubshape)
{
cout << "unsuccessfuly to reduce K. " << endl;
break;
}
++seed;
}
}
cout << "There are " << newShape.getSmallSizePiecesNum(minTileSize) << " small pieces and " << newShape.getLargeSizePiecesNum(maxTileSize) << " large pieces." << endl;
return newShape;
}
Shape getSubShape(vector<Piece> & eliminationPieces, Shape & shape, int & pieceNum, int & K, vector<int> & eliminationPieceIDList)
{
Shape newShape = shape;
newShape.all_pixels.clear();
newShape.pieces.clear();
set<int> pieceIDList;
vector<Piece> currentTemplates;
for (int i = 0; i < eliminationPieces.size(); ++i)
{
vector<Piece> pieceList = getNeighbouringAndCurrentPieces(eliminationPieces[i], shape);
for (auto & piece : pieceList)
{
if (!isPieceinTemplates(piece, currentTemplates))
{
currentTemplates.push_back(piece);
}
for (auto & px : piece.pixels)
{
newShape.all_pixels.insert(px);
}
pieceIDList.insert(shape.getPieceID(piece));
}
}
K = currentTemplates.size();
for (auto & i : pieceIDList)
{
eliminationPieceIDList.push_back(i);
}
pieceNum = eliminationPieceIDList.size();
return newShape;
}
Shape generatePieces(Shape & shape, int N, int K, int G, int T, bool autoSave, string pureFileName,
int seedNum, float minAvgSizeRatio, float maxAvgSizeRatio, int minTileSize, int maxTileSize,
int minSeedDist, bool isUniformDistribution, int shapeCandisNum,
double & runningTime, int & bestScore, vector<Piece> & existingTemplates, bool & isFound, bool isLooseSizeRequirement)
{
auto start = high_resolution_clock::now();
int best_score = INT_MAX;
srand(seedNum);
Shape best_solution;
Shape input = shape;
input.clear();
updateAccessibility(input);
updateBlockability(input);
while(1)
{
Shape seed = generateNSeedPieces(N, input, minSeedDist, isUniformDistribution);
cout << "Generate " << seed.pieces.size() << " seeds. " << endl;
seed.maxAvgSizeRatio = maxAvgSizeRatio;
seed.minAvgSizeRatio = minAvgSizeRatio;
seed.minTileSize = minTileSize;
seed.maxTileSize = maxTileSize;
auto time_now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(time_now - start);
double time_elapsed = (duration.count() / (double)1000) / 60;
if (time_elapsed > T) {
cout << "Exceeded runtime....exiting.\n";
break;
}
// repeat growing process G times and store each solution for testing
for (int j = 0; j < G; j++) {
Shape newShape = seed;
bool isDisconnected = false;
vector<Shape> growingStates;
growingStates.push_back(input);
growingStates.push_back(newShape);
while (true) {
newShape = growPiecesByOnePixel(newShape, shapeCandisNum, isDisconnected, existingTemplates, minTileSize, maxTileSize, isLooseSizeRequirement, growingStates);
if (isDisconnected)
{
cout << "Find unreachable pixels or fail to satisfy tile size requirement. " << endl;
break;
}
cout << "Grew all pieces by one pixel. " << newShape.getNumUnfilledPx() << " pixels remaining. \n";
// complete
if (newShape.getNumUnfilledPx() <= 0)
{
if (newShape.score <= best_score && newShape.getNumUnfilledPx() == 0 && newShape.score > 0)
{
cout << "Find a N = " << newShape.pieces.size() << " K = " << newShape.score << " result. " << endl;
best_score = newShape.score;
best_solution = newShape;
auto now = high_resolution_clock::now();
auto dura = duration_cast<milliseconds>(time_now - start);
double elapsed = (duration.count() / (double)1000) / 60;
best_solution.assignPieceID();
best_solution.assignPieceClusterID();
// save current best result
if (autoSave)
{
// string savingPath = "./Result/auto_save/";
string savingPath = "../";
string pureFolderName = best_solution.getOutputFolderPath(savingPath + pureFileName) + "_size" + to_string(best_solution.getSmallestPieceSize()) + "To" + to_string(best_solution.getLargestPieceSize()) + "_" + to_string(elapsed) + "min";
saveShape2File(best_solution, pureFolderName, best_solution.getOutputFileFullName(pureFolderName + "/" + pureFileName), elapsed);
string pureGrowingStateSavingFolderName = pureFolderName + "/enlarging_states";
for (int stateID = growingStates.size() - 1; stateID >= 0; --stateID)
{
if (growingStates[stateID].getNumUnfilledPx() > 0)
{
vector<Pixel> remaining_pixels;
for (const auto &px : growingStates[stateID].all_pixels)
if (!isPixelInPieces(px, growingStates[stateID].pieces))
remaining_pixels.push_back(px);
if (!remaining_pixels.empty())
growingStates[stateID].pieces.push_back(Piece(remaining_pixels, Color{150,150,150}));
}
// saveShape2File(growingStates[stateID], pureGrowingStateSavingFolderName, pureGrowingStateSavingFolderName + "/" + to_string(stateID) + ".puz", elapsed);
}
}
}
if (best_score <= K) {
isFound = true;
}
break;
}
}
// cout << "Time Elapsed: " << time_elapsed << " minutes.\n";
if (isFound)
break;
}
if (isFound)
break;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
runningTime = duration.count()/(double)1000/60;
bestScore = best_solution.score;
cout << endl << "Best solution with K = " << bestScore << "\n";
cout << "Total runtime: " << runningTime << "min.\n";
return best_solution;
}
Shape generatePiecesWithGivenSeeds(Shape & shape, int N, int K, int G, int T, bool autoSave, string pureFileName,
int seedNum, float minAvgSizeRatio, float maxAvgSizeRatio, int minTileSize, int maxTileSize,
int minSeedDist, bool isUniformDistribution, int shapeCandisNum,
double & runningTime, int & bestScore, vector<Piece> & existingTemplates, bool & isFound, bool isLooseSizeRequirement)
{
auto start = high_resolution_clock::now();
int best_score = INT_MAX;
srand(seedNum);
Shape best_solution;
Shape input = shape;
input.clear();
while(1)
{
Shape seed = input;
seed.maxAvgSizeRatio = maxAvgSizeRatio;
seed.minAvgSizeRatio = minAvgSizeRatio;
seed.minTileSize = minTileSize;
seed.maxTileSize = maxTileSize;
auto time_now = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(time_now - start);
double time_elapsed = (duration.count() / (double)1000) / 60;
if (time_elapsed > T) {
cout << "Exceeded runtime....exiting.\n";
break;
}
// repeat growing process G times and store each solution for testing
for (int j = 0; j < G; j++) {
Shape newShape = seed;
bool isDisconnected = false;
vector<Shape> growingStates;
while (true) {
newShape = growPiecesByOnePixel(newShape, shapeCandisNum, isDisconnected, existingTemplates, minTileSize, maxTileSize, isLooseSizeRequirement, growingStates);
if (isDisconnected)
{
cout << "Find unreachable pixels or fail to satisfy tile size requirement. " << endl;
break;
}
cout << "Grew all pieces by one pixel. " << newShape.getNumUnfilledPx() << " pixels remaining. \n";
if (newShape.getNumUnfilledPx() <= 0) {
// complete
if (newShape.getLargestPieceSize() > maxTileSize or newShape.getSmallestPieceSize() < minTileSize)
{
// cout << "Fail to satisfy tile size requirement." << endl;
break;
}
if (newShape.score <= best_score && newShape.getNumUnfilledPx() == 0 && newShape.score > 0) {
cout << "Find a N = " << newShape.pieces.size() << " K = " << newShape.score << " result. " << endl;
best_score = newShape.score;
best_solution = newShape;
auto now = high_resolution_clock::now();
auto dura = duration_cast<milliseconds>(time_now - start);
double elapsed = (duration.count() / (double)1000) / 60;
// save current best result
if (autoSave)
{
string savingPath = "../Result/auto_save/";
string pureFolderName = best_solution.getOutputFolderPath(savingPath + pureFileName) + "_size" + to_string(best_solution.getSmallestPieceSize()) + "To" + to_string(best_solution.getLargestPieceSize()) + "_" + to_string(elapsed) + "min";
saveShape2File(best_solution, pureFolderName,
best_solution.getOutputFileFullName(pureFolderName + "/" + pureFileName), elapsed);
}
}
if (best_score <= K) {
isFound = true;
}
break;
}
}
// cout << "Time Elapsed: " << time_elapsed << " minutes.\n";
if (isFound)
break;
}
if (isFound)
break;
}
auto stop = high_resolution_clock::now();
auto duration = duration_cast<milliseconds>(stop - start);
runningTime = duration.count()/(double)1000/60;
bestScore = best_solution.score;
cout << endl << "Best solution with K = " << bestScore << "\n";
cout << "Total runtime: " << runningTime << "min.\n";
return best_solution;
}
// Assumes N < the number of pixels in that piece
Shape generateNSeedPieces(int N, Shape & shape, int minSeedDist, bool isUniformDistribution) {
vector<float> possibList = shape.accessibilityList;
vector<Piece> pieces;
vector<Pixel> seed_pixels;
vector<Pixel> pixelsInShape = vector<Pixel>(shape.all_pixels.begin(), shape.all_pixels.end());
int count = 0;
while(1)
{
seed_pixels.clear();
possibList = shape.accessibilityList;
if (isUniformDistribution)
{
for (int i = 0; i < possibList.size(); ++i)
{
if (possibList[i] > 0)
possibList[i] = 1;
}
}
while(1)
{
int random_index = GetRandomObjIndex(possibList, 3.0);
Pixel seed_pixel = Pixel(int(random_index / shape.volCol), random_index % shape.volCol);
cout << "currSelectedSeedID: " << random_index << endl;
cout << "(x,y): " << seed_pixel.x << " " << seed_pixel.y << endl << endl;
seed_pixels.push_back(seed_pixel);
count ++;
if (count == N)
break;
vector<Pixel> visitedPixels;
vector<Pixel> nextVisits;
vector< pair<Pixel,int> > nextVisitPixels;
nextVisitPixels.push_back(pair(seed_pixel,0));
nextVisits.push_back(seed_pixel);
while (!nextVisitPixels.empty())
{
int currDepth = nextVisitPixels[0].second;
Pixel currPixel = nextVisits[0];
nextVisits.erase(nextVisits.begin());
nextVisitPixels.erase(nextVisitPixels.begin());
visitedPixels.push_back(currPixel);
cout << "currPixelID: " << currPixel.y * shape.volCol + currPixel.x << endl;
cout << "(x,y): " << currPixel.x << " " << currPixel.y << endl << endl;
possibList[currPixel.x * shape.volCol + currPixel.y] = 0;
// vector<Pixel> newNeigbouringPixels = getValidNeigbours(currPixel, shape);
vector<Pixel> newNeigbouringPixels = getValidCircleNeigbours(currPixel, shape);
for (int i = 0; i < newNeigbouringPixels.size(); ++i)
{
if (currDepth < minSeedDist - 1)
{
if(!isPixelInPixelList(newNeigbouringPixels[i], nextVisits) and !isPixelInPixelList(newNeigbouringPixels[i], visitedPixels))
{
nextVisitPixels.push_back(pair(newNeigbouringPixels[i], currDepth + 1));
nextVisits.push_back(newNeigbouringPixels[i]);
}
}
}
}
if (*max_element(possibList.begin(), possibList.end()) == 0)
break;
}
if (seed_pixels.size() == N)
break;
}
// cout << "Find " << count << " seeds with minimal dist " << minSeedDist << endl;
for (const auto& px : seed_pixels)
{
pieces.push_back(Piece(px));
}
Shape seed = shape;
for (auto piece : pieces)
{
seed.addPiece(piece);
}
seed.assignColors();
seed.valid = true;
Piece newPiece = pieces[0];
seed.current_templates.clear();
seed.current_templates.push_back(newPiece);
updateAccessibilityAndBlockability(seed);
return seed;
}
// grows each piece in the shape by one pixel according to the algorithm
// if use_access_val is true, it will pick pixels based on accessibility value, otherwise: pick randomly
// returns the result as a new shape
Shape growAllPiecesByOnePixel(const Shape& shape, bool use_access_val, vector<Shape> & shape_state) {
Shape newShape = shape; //copy shape
newShape.current_templates = vector<Piece>(); // clear current templates
// 1) randomly choose a starting piece (that is not blocked)
int random_piece_idx = getRandomNumber(0, newShape.pieces.size() - 1);
while (isBlocked(newShape.pieces[random_piece_idx], newShape)) {
random_piece_idx = getRandomNumber(0, newShape.pieces.size() - 1);
}
// 2) grow that piece by one pixel
Piece newPiece = growPiece(newShape, random_piece_idx, use_access_val);
newShape.pieces[random_piece_idx] = newPiece;
newShape.current_templates.push_back(newPiece);
// 3) grow remaining pieces
for (int i = 0; i < newShape.pieces.size(); i++) {
if (i != random_piece_idx) {
if (isBlocked(newShape.pieces[i], newShape)) {
if (isPieceinTemplates(newShape.pieces[i], newShape.blocked_templates)) {
// already a blocked template, leave this piece be and continue
continue;
} else {
double target_template_size = ((double)newShape.all_pixels.size() / (double)newShape.pieces.size());
if ((double)newShape.pieces[i].pixels.size() >= 0.8*target_template_size) { // if this piece is already big enough, add it to the blocked template list and continue
// add to blocked template list in this shape, and continue
newShape.blocked_templates.push_back(newShape.pieces[i]);
continue;
} else {
// remove backtracking temporarily
// backtrack randomly 1-3 rounds
// int backtrack_amt = getRandomNumber(1, 5);
// if (backtrack_amt >= shape_state.size()) {
// backtrack_amt = shape_state.size() - 1;
// }
// cout << "Backtacking " << backtrack_amt << " rounds....\n";
// while (backtrack_amt != 0) {
// shape_state.pop_back();
// backtrack_amt--;
// }
// int backtrack_count = newShape.backtrack_count;
// newShape = shape_state[shape_state.size() - 1];
// newShape.backtrack_count = backtrack_count + 1;
// shape_state.pop_back();
return newShape;
}
}
}
vector<Pixel> next_possible_pixels = getPossiblePixelsToGrow(newShape.pieces[i], newShape);
if (next_possible_pixels.size() == 0) {
// no possible pixels that match existing templates, so we create a new template
Piece newPiece = growPiece(newShape, i, use_access_val);
newShape.pieces[i] = newPiece;
newShape.current_templates.push_back(newPiece);
} else {
// randomly choose one of the possible pixels to grow
int rand_idx = getRandomNumber(0, next_possible_pixels.size() - 1);
Pixel next_px = next_possible_pixels[rand_idx];
if (next_px.x == -1) { // this represents a blocked template match: no need to grow the piece
continue;
} else {
newShape.pieces[i].addPixel(next_px);
}
}
}
}
newShape.score = newShape.current_templates.size() + newShape.blocked_templates.size();
return newShape;
}
Shape growPiecesByOnePixel(Shape & shape, int backtrackNum, bool & isDisconnected, vector<Piece> & existingTemplates, int minTileSize, int maxTileSize, bool isLooseSizeRequirement, vector<Shape> & growingStates)
{
vector<Shape> shapeCandis;
vector<vector<Shape>> intermediateShapeCandis;
vector<float> distinctPieceNumList;
vector<float> growingSpaceEvaluationList;
vector<float> possibList;
// growing pieces in the same piece group by adding one pixel
for(int k = 0; k < backtrackNum; ++k)
{
Shape newShape = shape; // new shape to grow
// 1) select the guiding piece class template according to:
// i. the number of instances
// ii. piece size
Piece guidingPieceClassTemplate = selectGuidingPieceClassTemplate(shape.current_templates, newShape, 5.0, isDisconnected);
if (isDisconnected)
{
// updateTemplates(newShape);
// cout << "Find one or more unreachable pixels." << endl;
return shape;
}
// 2) select a piece in guiding piece class according to:
// i. the less growing space
vector<Piece> unblocked_instances = getUnblockedTemplateInstances(guidingPieceClassTemplate, newShape);
// cout << "unblocked_instances: " << unblocked_instances.size() << endl;
Piece firstSelectedPiece = selectFirstGrowingPieceInGuidingPieceClass(unblocked_instances, newShape, 3.0);
// cout << "find first selected piece. " << endl;
// 3) grow the first selected piece by adding one pixel according to:
// i. match one of the existing current templates
// ii. be the subset of one of the existing current templates
// iii. accessibility
vector<Piece> combinedTemplates;
for (int i = 0; i < shape.current_templates.size(); ++i)
{
combinedTemplates.push_back(shape.current_templates[i]);
}
for (int i = 0; i < existingTemplates.size(); ++i)
{
combinedTemplates.push_back(existingTemplates[i]);
}
Piece firstGrowedPiece = growFirstSelectedPiece(newShape, combinedTemplates, firstSelectedPiece, 3.0);
int firstGrowedPieceID = newShape.getPieceID(firstSelectedPiece);
newShape.pieces[firstGrowedPieceID] = firstGrowedPiece;
// 4) grow the remaining piece to match this piece
// for each remaining piece that may be grow to the same shape:
// if blocked:
// add to blocked_templates<>;
// else:
// if can match the growed template:
// grow to match;
// else:
// leave it to be to the next iteration;
// isEraseSelectedTemplate = false;
vector<Pixel> addedPixels;
vector< pair<int, vector<Pixel>> > piecePairs;
for (int i = 0; i < newShape.pieces.size(); ++i)
{
if (i == firstGrowedPieceID)
{
continue;
}
else
{
// if the pieces[i] and firstSelectedPiece has the same shape
if (isSameShape(newShape.pieces[i], firstSelectedPiece))
{
if (isBlocked(newShape.pieces[i], newShape))
{
continue;
}
else
{
vector<Pixel> currPossibMatchPixels = getPossiblePixelsGrow2Match(newShape, newShape.pieces[i], firstGrowedPiece);
if (!currPossibMatchPixels.empty())
{
piecePairs.push_back(pair(i, currPossibMatchPixels));
}
}
continue;
}
}
}
std::sort(piecePairs.begin(), piecePairs.end(),
[](pair<int, vector<Pixel>> & a, pair<int, vector<Pixel>> & b) {
return a.second.size() < b.second.size();
});
while (!piecePairs.empty())
{
int currID = piecePairs[0].first;
Piece currPiece = newShape.pieces[currID];
vector<Pixel> currPossibPixels = piecePairs[0].second;
vector<float> currPossibList;
for (int i = 0; i < currPossibPixels.size(); ++i)
{
if (!isPixelInPixelList(currPossibPixels[i], addedPixels))
{
int currPixelID = newShape.getPixelID(currPossibPixels[i]);
currPossibList.push_back(round(5.0 * newShape.blockabilityList[currPixelID]));
}
else
{
currPossibList.push_back(0);
}
}
if (*max_element(currPossibList.begin(), currPossibList.end()) > 0)
{
int growPixelID = GetRandomObjIndex(currPossibList, 3.0);
Pixel growPixel = currPossibPixels[growPixelID];
currPiece.addPixel(growPixel);
newShape.pieces[currID] = currPiece;
addedPixels.push_back(growPixel);
}
piecePairs.erase(piecePairs.begin());
}
// 5) fill the disconnected pixels
vector<Shape> currentCandis;
currentCandis.push_back(newShape);
int prevUnfilledPxNum = newShape.getNumUnfilledPx();