-
Notifications
You must be signed in to change notification settings - Fork 9
/
oldconvertft.cpp
1159 lines (985 loc) · 35.5 KB
/
oldconvertft.cpp
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 <sys/time.h>
#include <time.h>
#include "utils/profiling.h"
#include "gatenumbers.h"
#include "databasereader.h"
#include "decomposition.h"
#include "plumbingpieces.h"
#include "fileformats/infilereader.h"
#include "fileformats/geomfilewriter.h"
#include "fileformats/geomfilereader.h"
#include "fileformats/adamfilewriter.h"
#include "fileformats/iofilewriter.h"
#include "fileformats/boundingboxfilewriter.h"
#include "fileformats/chpfilewriter.h"
#include "fileformats/psfilewriter.h"
#include "fileformats/qcircfilewriter.h"
#include "fileformats/gmlfilewriter.h"
#include "fileformats/recycledcircuitwriter.h"
#include "fileformats/recycledcircuitreader.h"
#include "fileformats/generaldefines.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <string.h>
#include "recycling/recycle.h"
#include "cnotcounter.h"
#include "circuitgeometry.h"
#include "circuitmatrix.h"
#include "computeadditional.h"
#include "heuristicparameters.h"
#include "scheduling/schedulercontrol.h"
#include "scheduling/seqschedcontrol.h"
#include "scheduling/asapschedcontrol.h"
#include "scheduling/alaptschedcontrol.h"
#include <climits>
#include <map>
#include "boxworld2.h"
#include "connectpins.h"
#include "connectionmanager.h"
#include "fileformats/iofilewriter.h"
#include "fileformats/boxcoordfilewriter.h"
#include "fileformats/toconnectfilewriter.h"
#include "fileformats/geomfilewriter.h"
#include "fileformats/infilereader.h"
#include "recycling/wireelement.h"
#include "recycling/costmodel.h"
#include "recycling/causalgraph.h"
#include "recycling/recyclegate.h"
#include "circconvert.h"
#include "gidney.h"
//databasereader dbReader;
//cnotcounter cncounter;
circuitgeometry geom;
plumbingpiecesgenerator ppgen;
heuristicparameters heuristicParam;
std::string writeGeometry(char** argv)
{
/**
* The geometry
*/
geomfilewriter geomwr;
std::string fname = geomfilewriter::getGeomFileName(argv[1]);
FILE* geomfile = fopen(fname.c_str(), "w");
geomwr.writeGeomFile(geomfile, geom.simplegeom.io, geom.simplegeom.segs, geom.simplegeom.coords);
fclose(geomfile);
/**
* The plumbing pieces of a geometry
*/
adamfilewriter adamwr;
std::string fnamea = adamfilewriter::getAdamFileName(argv[1]);
FILE* adamfile = fopen(fnamea.c_str(), "w");
adamwr.writeAdamFile(adamfile, ppgen.pieces);
fclose(adamfile);
/**
* The I/O of a circuit. DEBUGGING PURPOSES ONLY
*/
iofilewriter iowr;
std::string iofname = iofilewriter::getIOFileName(fname.c_str());
FILE* iofile = fopen(iofname.c_str(), "w");
iowr.writeIOFile(iofile, geom.allpins.inputList);
fclose(iofile);
// /**
// * The bounding box of a circuit. DEBUGGING PURPOSES ONLY
// */
// boundingboxfilewriter bboxwr;
// std::string bboxname = boundingboxfilewriter::getBoundingBoxFileName(fname.c_str());
// FILE* bboxfile = fopen(bboxname.c_str(), "w");
// bboxwr.writeBoundingBoxFile(bboxfile, geom.simplegeom.boundingbox);
// fclose(bboxfile);
return iofname;
}
void writeOtherFormats(const char* basisname, circuitmatrix& circ)
{
/*chpfilewriter chpwr;
std::string chpfname = chpfilewriter::getCHPFileName(basisname);
FILE* chpfile = fopen(chpfname.c_str(), "w");
chpwr.writeCHPFile(chpfile, circ);
fclose(chpfile);*/
// qcircfilewriter qcircwr;
// std::string fname = qcircfilewriter::getQCircFileName(basisname);
// FILE* file = fopen(fname.c_str(), "w");
// qcircwr.writeQCircFile(file, circ);
// fclose(file);
/*PSFILEWRITER CAN HANDLE ONLY ICM*/
// psfilewriter pswr;
// std::string psfname = psfilewriter::getPostScriptFileName(basisname);
// FILE* psfile = fopen(psfname.c_str(), "w");
// pswr.writePostScriptFile(psfile, circ);
// fclose(psfile);
// gmlfilewriter gwr;
// std::string fname22 = gmlfilewriter::getGMLFileName(basisname, 0);
// FILE* filegwr = fopen(fname22.c_str(), "w");
// gwr.writeGMLFile(filegwr, causalG);
// fclose(filegwr);
//
// fname22 = gmlfilewriter::getGMLFileName(basisname, 1);
// filegwr = fopen(fname22.c_str(), "w");
// gwr.writeGMLFile2(filegwr, causalG);
// fclose(filegwr);
}
void placeGate(recyclegate* current, circuitmatrix& circ, cnotcounter& ccnot)
{
// printf("place %p\n", current);
int column = current->level;
int controlline = current->wirePointers[0]->getUpdatedWire(current->orderNrInGateList)->number;
int operation = current->type;
if(current->wirePointers.size() > 1)
{
/*almost certain this is a cnot, because only this should be left*/
int cnot = ccnot.getNextCnotNumber();
int targetline = current->wirePointers[1]->getUpdatedWire(current->orderNrInGateList)->number;
circ[controlline][column] = cnot + 0;//+0 because control
circ[targetline][column] = cnot + 1;//+1 because target
}
else if(current->wirePointers.size() == 1)
{
circ[controlline][column] = operation;
}
}
//circuitmatrix createCircuitMatrix(causalgraph& causal)
//{
//// std::vector<recyclegate*> order = causal.equalizeConsideringCosts();
//
// std::vector<recyclegate*> order = causal.bfs();
//
// //TODO
// //causal.equalizeInputLevels();
//
// //construct a vector of qubitlines
// long length = causal.getMaxLevel() + 1;
//
// //vector<vector<int> > inputs = extractSortedInputsList();
// std::vector<recyclegate*> inputs = causal.getRoots();
// int nrLines = inputs.size();
//
// std::vector<qubitline> temp;
// for (int k = 0; k < nrLines; k++)
// {
// qubitline wireQubit(length, WIRE);
// temp.push_back(wireQubit);
// }
//
// //construct the circuitmatrix from the causalgraph
// //for the ICM representation it should contain only cnot gates
// cnotcounter ccounter;
//
// //vector<int> operations = causal.bfs();
//
// circuitmatrix circ(temp);
//
// for(std::vector<recyclegate*>::iterator it = order.begin(); it != order.end(); it++)
// {
// placeGate(*it, circ, ccounter);
// }
//
// return circ;
//}
//void createCircuitText(causalgraph& causal)
//{
// std::vector<recyclegate*> order = causal.bfs();
//
// long length = causal.getMaxLevel() + 1;
//
// std::vector<recyclegate*> inputs = causal.getRoots();
// int nrLines = inputs.size();
//
// for(std::vector<recyclegate*>::iterator it = order.begin(); it != order.end(); it++)
// {
// writeGateText(*it);
// }
//}
void writeBoxSchedulerAndClearCoordList(boxworld2& boxworld, const char* basisname, int scheduleNumber)
{
boxcoordfilewriter bcwr;
std::string fname = boxcoordfilewriter::getBoxCoordFileName(basisname, scheduleNumber);
FILE* fboxplan = fopen(fname.c_str(), "w");
bcwr.writeBoxCoordFile(fboxplan, boxworld.currentConfig.boxSize, boxworld.boxCoords, scheduleNumber);
fclose(fboxplan);
//the box coords are cleared after writing them to a file
//because boxes are separate from the pins
//the boxes file is used for displaying it
//the pin file is used for computing the connections
boxworld.boxCoords.clear();
}
void initCostModels(costmodel* model)
{
//ASAP
model[0].gateTypeCosts['a'].gatecost = 1;
model[0].gateTypeCosts['a'].wirecost = 0;
model[0].gateTypeCosts['y'].gatecost = 1;
model[0].gateTypeCosts['y'].wirecost = 0;
model[0].gateTypeCosts['d'].gatecost = 1; //undeva tre sa fie 1, dar nu mai stiu de ce
model[0].gateTypeCosts['d'].wirecost = 0;
model[1].gateTypeCosts['a'].gatecost = 10 + 3; //1;
model[1].gateTypeCosts['a'].wirecost = 10 + 3; //0;
model[1].gateTypeCosts['y'].gatecost = 5 + 3; //1;
model[1].gateTypeCosts['y'].wirecost = 5 + 3; //0;
model[1].gateTypeCosts['d'].gatecost = 1; //undeva tre sa fie 1, dar nu mai stiu de ce
model[1].gateTypeCosts['d'].wirecost = 0;
}
bool mySortConnectionsFunction (pinpair p1, pinpair p2)
{
int orderOn1 = SOURCEPIN;
int orderOn2 = DESTPIN;
bool ret = (p1.getPinDetail(orderOn1).coord[CIRCUITWIDTH] < p2.getPinDetail(orderOn1).coord[CIRCUITWIDTH]);
if(p1.getPinDetail(orderOn1).coord[CIRCUITWIDTH] == p2.getPinDetail(orderOn1).coord[CIRCUITWIDTH])
{
ret = p1.getPinDetail(orderOn2).coord[CIRCUITDEPTH] < p2.getPinDetail(orderOn2).coord[CIRCUITDEPTH];
}
return ret;
}
void generateCircuitFromFile(causalgraph& causalG, std::vector<std::string>& cucCirc)
{
causalG.constructFrom2(cucCirc);
int nrGates0 = causalG.tmpCircuit.size();
wireelement* current = causalG.getFirstWireElement();
int nrWire = 0;
while (current != NULL)
{
nrWire++;
current = current->next;
}
int nrWires0 = nrWire;
double cpu0 = profiling::util_get_cpu_time();
circconvert convert;
/*replaces Toffoli gates with Clifford+T decomposition*/
printf("1\n");
convert.replaceNonICM2(causalG);
/*replaces Hadamard gates*/
//26.10.2017 - comment H and ICM transforms
// printf("2\n");
// convert.replaceNonICM2(causalG);
// printf("3\n");
// /*required for threshold*/
// causalG.numberGateList2();
// convert.replaceICM2(causalG);
printf("4\n");
double cpu1 = profiling::util_get_cpu_time();
for (std::list<recyclegate*>::iterator it = causalG.tmpCircuit.begin();
it != causalG.tmpCircuit.end(); it++)
{
for (size_t i = 0; i < (*it)->wirePointers.size(); i++)
{
(*it)->wirePointers[i] = (*it)->wirePointers[i]->getUpdatedWire(
(*it)->orderNrInGateList);
}
}
for (std::list<recyclegate*>::iterator it = causalG.tmpCircuit.begin();
it != causalG.tmpCircuit.end(); it++)
{
for (size_t i = 0; i < (*it)->wirePointers.size(); i++)
{
//11.05.2017
(*it)->wirePointers[i]->threshold = LONG_MIN;
}
}
int nrWires1 = causalG.numberWires2();
std::vector<recyclegate*> order = causalG.numberGateList2();
int nrGates1 = order.size();
printf("5 order:%d\n", order.size());
/*
* Prepare for recycling?
*/
causalG.reconstructWithoutConsideringCosts(order);
#if RELEVELCIRCUIT == 1
causalG.computeLevels();
#endif
#define TRANSITION 0
#if TRANSITION == 1
/*
* Recycle
*/
wirerecycle recycler;
recycler.recycle(causalG, RECYCLEWIRESEQ);
for (std::list<recyclegate*>::iterator it = causalG.tmpCircuit.begin();
it != causalG.tmpCircuit.end(); it++)
{
for (size_t i = 0; i < (*it)->wirePointers.size(); i++)
{
(*it)->wirePointers[i] = (*it)->wirePointers[i]->getUpdatedWire(0);
}
}
double cpu2 = profiling::util_get_cpu_time();
printf("STATS: nrW0 %d, nrG0 %d, nrW1 %d, nrG1 %d, time0 %f, time1 %f\n", nrWires0, nrGates0, nrWires1, nrGates1, cpu1-cpu0, cpu2-cpu1);
#endif
causalG.numberWires2();
causalG.numberGateList2();
#if RELEVELCIRCUIT == 1
printf("compute levels...\n");
causalG.computeLevels();
#endif
#if RELEVELCIRCUIT == 0
causalG.setLevelIterative();
#endif
// printf("writing file... \n");
// recycledcircuitwriter recwr;
// std::string recname = recycledcircuitwriter::getRecycledFileName("cuc");
// FILE* frec = fopen(recname.c_str(), "w");
// recwr.writeRecycledCircuitFile(frec, causalG);
// fclose(frec);
}
std::vector<std::string> generateRandomTGateCircuit(int nrqubits, int nrgates)
{
std::vector<std::string> circ;
std::string ins = "in ";
std::string outs = "out ";
for(int i=0; i<nrqubits; i++)
{
ins += "-";
outs += "-";
}
circ.push_back(ins);
circ.push_back(outs);
for(int i=0; i<nrgates; i++)
{
std::stringstream ss;
ss << (int)floor(drand48() * nrqubits);
std::string gate = "t " + ss.str();
circ.push_back(gate);
}
return circ;
}
#define RELEVELCIRCUIT 0
int main(int argc, char** argv)
{
FILE* badseedfile;
unsigned int seed = 0;
badseedfile = fopen("seeds.txt", "r");
fscanf(badseedfile, "%u", &seed);
fclose(badseedfile);
if(seed == 0)
{
timeval tim;
gettimeofday(&tim, NULL);
seed = (unsigned int) (tim.tv_usec);
}
srand48(seed);
printf("SIMULATION SEED %u\n", seed);
/**
* Take a circuit and convert it to ICM
*/
costmodel model[2];
initCostModels(model);
causalgraph causalG(model[0]);
bool generateCircuit = true;//false
if(generateCircuit)
{
// cuccaro cuc;
// int nrCucQb = 10; //1000;
// std::vector<std::string> cucCirc = cuc.makeCircuit(nrCucQb, false);
// gidney cuc;
// int nrCucQb = 100; //1000;
// std::vector<std::string> cucCirc = cuc.makeCircuit(nrCucQb);
// std::vector<std::string> cucCirc = generateRandomTGateCircuit(10, 100);
//
// std::vector<std::string> cucCirc;
// cucCirc.push_back("in --------------");//--0
// cucCirc.push_back("out --------------");//--z
//// cucCirc.push_back("c 0 3 4");
//// cucCirc.push_back("K 3 4 7");
//// cucCirc.push_back("c 0 7");
//// cucCirc.push_back("c 0 3 4");
// cucCirc.push_back("K 3 4 7");
// cucCirc.push_back("U 3 4 7");
//used for the adder
// generateCircuitFromFile(causalG, cucCirc);
infilereader inread;
std::vector<std::string> simple = inread.readInFile(argv[1]);
generateCircuitFromFile(causalG, simple);
}
else
{
printf("read file...start");
recycledcircuitreader recread;
std::string fname = recycledcircuitwriter::getRecycledFileName("cuc");
recread.readRecycledFile(fname.c_str(), causalG);
printf("...stop\n");
std::vector<recyclegate*> order = causalG.numberGateList2();
causalG.reconstructWithoutConsideringCosts(order);
causalG.computeLevels();
causalG.numberWires2();
}
printf("CONVERT END\n");
/**
* The causalgraph is used to generate the geometry
*/
geom.useBridge = true;
#if RELEVELCIRCUIT == 1
causalG.computeLevels();
causalG.equalizeConsideringCosts();
#endif
//rec.causal.computeLevels();
/**
* Heuristics
*/
heuristicParam.init();
Point::heuristicParam = &heuristicParam;
/**
* Boxworld
*/
boxworld2 boxworld;
boxworld.heuristicParam = &heuristicParam;
double aStateFail = atof(argv[3]);
double tGateFail = atof(argv[4]);
double yStateFail = atof(argv[5]);
double pGateFail = atof(argv[6]);
int schedulingType = atoi(argv[7]);
// boxworld.currentConfig._pinScenario = PINSHORIZRIGHT;
boxworld.currentConfig._pinScenario = PINSVERTICALLEFT;
boxworld.initGeomBoundingBox(-2 * DELTA, (causalG.getRoots().size() + 1) * 2 * DELTA,
INT_MIN, INT_MAX,
-DELTA - 1, DELTA + 1);
boxworld.initScheduleGreedy(aStateFail, yStateFail, tGateFail, pGateFail);
/**
* Prepare the iteration
*/
bfsState iterationState;
iterationState.septCurrentlyMaxLevel = -24;
// std::vector<recyclegate*> rootInputs = causalG.getRoots();
// iterationState.init(rootInputs);
std::vector<recyclegate*> bfsOrder = causalG.bfs();
int nrLines = causalG.getNrQubits();
/*
* 3NOV - adapt the number of wires and total on the grid line
*/
gridPosition::logicalQubitsPerLine = boxworld.currentConfig.getBoxTotalDimension(ATYPE, CIRCUITWIDTH) / (2*DELTA);
gridPosition::totalWires = nrLines; //for makeGeometry
iterationState.septInit(bfsOrder, nrLines);
causalG.stepwiseBfs(iterationState);
/**
* Initialise connnectpins
*/
connectpins pinConnector;
//set the pointer to the rtree of boxworld
pinConnector.pathfinder.useBoxWorld(&boxworld);
std::vector<pinpair> toConnBoxes;
std::vector<pinpair> toConnExtensions;
/**
* The connections pool
*/
connectionManager connManager(&heuristicParam);
/*
* There is something to draw or to schedule
*/
int counter = 0;
//greedy e cel care calculeaza cate trebuie in functie de probabilitati
// greedyschedulercontrol schedControl;
//seq e cel care planifica in secventa numar egal
seqschedulercontrol schedControl;
// asapschedcontrol schedControl;
// alaptschedcontrol schedControl;
#define WITHOUTSCHEDULING 0
while(iterationState.isSomethingToDo())
{
#if WITHOUTSCHEDULING == 1
iterationState.toDraw.insert(iterationState.toDraw.end(), iterationState.toScheduleInputs[0].begin(), iterationState.toScheduleInputs[0].end());
geom.makeGeometryFromCircuit(iterationState);
causalG.stepwiseBfs(iterationState);
#else
counter++;
pinblockjournalentry currentJournalEntry;
currentJournalEntry.synthesisStepNumber = counter;
printf("************\n STEP %d\n***********\n", counter);
/*
* Schedule the required boxes
*/
bool scheduledNewBoxes = false;
bool sufficientBoxes = true;
if(counter == 1)
{
iterationState.setMinimumLevel(0);
}
sufficientBoxes = false;
while(!sufficientBoxes)
{
/*
* Each round of scheduling requires recalibration
* of where the boxes are placed
*/
boxworld.setCalibration(true);
//greedy
// schedControl.updateControl(iterationState, heuristicParam, boxworld.currentConfig);
//seq
schedControl.updateControl(iterationState, heuristicParam, boxworld, connManager);
// schedControl.updateControl(iterationState, heuristicParam, boxworld);//for asap and alap?
if(schedControl.shouldTriggerScheduling())
{
// printf("THIS STEP IS SCHEDULING @%ld:", schedControl.getAssumedInputTimeCoordinate());
// for(std::set<recyclegate*>::iterator it = iterationState.toScheduleInputs[0].begin();
// it != iterationState.toScheduleInputs[0].end(); it++)
// {
// printf(" %d ", (*it)->getId());
// }
// printf("\n");
iterationState.septCurrentlyMaxLevel = schedControl.getAchievedCost();
}
scheduledNewBoxes = schedControl.shouldTriggerScheduling();
sufficientBoxes = !scheduledNewBoxes;
if(scheduledNewBoxes ||
(iterationState.getMaximumInputLevel() < iterationState.septCurrentlyMaxLevel))
{
/*
* This is, for the moment, required only for the seqschedcontrol
*/
#if RELEVELCIRCUIT == 1
causalG.updateLevelsAtValue(iterationState, iterationState.getMaximumInputLevel(), iterationState.septCurrentlyMaxLevel);
causalG.equalizeConsideringCosts();
#endif
#if RELEVELCIRCUIT == 0
// if(iterationState.toScheduleInputs[0].size() > 0)
// {
// //special case: determine if it could have been an r gate
// if((*iterationState.toScheduleInputs[0].begin())->pushedBy[0]->type == 'i')
// {
// printf("draw assume this was a an r gate\n");
//
// long costToAdd = -2;
// (*iterationState.toScheduleInputs[0].begin())->level = (counter) * 6;
// //long costToAdd = iterationState.septCurrentlyMaxLevel - iterationState.getMaximumInputLevel();
// //if(costToAdd > 0)
// {
// printf("draw cost to add %d starting from ordnr%d\n", costToAdd, iterationState.septLastIndex - 1);
// for(size_t i = iterationState.septLastIndex/* - 1*/; i < iterationState.septBfs.size(); i++)
// {
// iterationState.septBfs[i]->level += costToAdd;
// }
// }
// }
// }
#endif
printf("NEW COST %ld where prev%ld curr%ld box %ld\n",
iterationState.septCurrentlyMaxLevel, iterationState.getMaximumInputLevel(),
iterationState.getRequiredMaximumInputLevel(),
boxworld.greedyLevel.maxDepth);
#if RELEVELCIRCUIT == 1
/*
* Recalculate the bfs, because the levels were changed
*/
std::vector<recyclegate*> bfsOrder = causalG.bfs();
iterationState.septBfs = bfsOrder;
#endif
/*
* aici nu e frumos: ultima linie arata ca cea din updateControl
*/
/**
* 3 NOV
* this changes the maximumInputLevel
*/
if(iterationState.getMaximumInputLevel() < iterationState.septCurrentlyMaxLevel)
{
iterationState.saveMaxLevel(iterationState.septCurrentlyMaxLevel);
schedControl.timeWhenPoolEnds = iterationState.septCurrentlyMaxLevel - heuristicParam.timeBeforePoolEnd;
}
}
/* Check which connections are free
* Compute where the pins would be on the time axis using achievedCost
*/
connManager.releaseIfNotUsed(/*iterationState.requiredMaximumInputLevel*/
//connManager.getTimeWhenPoolEnds(iterationState),
schedControl.getTimeWhenPoolEnds(),
heuristicParam.connectionHeight,
pinConnector.pathfinder,
true /*3 NOV d*/);
for(int boxType = 0; boxType <= ATYPE; boxType++)
{
/*
* Check if there are previously successful boxes
*/
int necessary = iterationState.toScheduleInputs[boxType].size() - iterationState.septNrAssignedInputs;
int available = connManager.getUnusedReservedNr(boxType);
printf("Greedy Schedule @ level%ld type%c exist%d nec%lu \n",
// iterationState.getRequiredMaximumInputLevel(),
schedControl.getBoxStartTimeCoordinate(),
boxType == ATYPE ? 'A' : 'Y',
/*available, necessary*/
connManager.getUnusedReservedNr(boxType), iterationState.toScheduleInputs[boxType].size());
if(schedControl.shouldTriggerScheduling(boxType))
{
schedControl.cancelTrigger();
std::queue<int> greedyBoxPinIds = boxworld.greedyScheduleBoxes(schedControl.getBoxStartTimeCoordinate(), boxType, available, necessary);
// queue<int> greedyBoxPinIds = boxworld.computeScheduleCanonical(schedControl.getBoxStartTimeCoordinate(), rec.causal);//(schedControl.getBoxStartTimeCoordinate(), boxType, available, necessary);
// queue<int> greedyBoxPinIds = boxworld.computeScheduleALAPT(schedControl.getBoxStartTimeCoordinate(boxType), boxType, available, necessary);
/*
* Reserve connections for the successful boxes
*/
while(greedyBoxPinIds.size() > 0)
{
int boxPinId = greedyBoxPinIds.front();
/*inside, skip if too many*/
/*in cazul asap .. addconnection nu merge*/
int stopStop = connManager.addConnection(/*is this parameter still used?*/boxType, boxworld.boxPins[boxPinId]);
if(stopStop == -1)
{
printf("1. limit reached\n");
}
greedyBoxPinIds.pop();
/*
* 3 NOV - functioneaza doar pentru ca e o singura legatura
* in updateConnections ia toata lista la rand si atunci ar putea
* iese mai multe legaturi identice
*/
connManager.updateConnections(BOXCONNECTION, schedControl.getTimeWhenPoolEnds(), heuristicParam.connectionHeight, toConnBoxes);
}
}
}
/*
* Consume connections for the inputs that need scheduling
*/
for(int boxType = 0; boxType <= ATYPE; boxType++)
{
for(std::set<recyclegate*>::iterator it = iterationState.toScheduleInputs[boxType].begin();
it != iterationState.toScheduleInputs[boxType].end(); it++)
{
int opId = (*it)->getId();
if(connManager.assignedIdToConnection.find(opId) == connManager.assignedIdToConnection.end())
{
if(!connManager.assignOperationToConnection(opId, boxType))
{
printf("NO CONN AVAILABLE for type %d\n", boxType);
// break;
}
else
{
iterationState.septNrAssignedInputs++;
/*
* 3 NOV
*/
(*it)->connChannel = connManager.assignedIdToConnection[opId];
}
}
}
printf("remaining TOSCHEDULE %d\n", iterationState.toScheduleInputs[boxType].size() - iterationState.septNrAssignedInputs);
sufficientBoxes = (iterationState.toScheduleInputs[boxType].size() - iterationState.septNrAssignedInputs) == 0;
}
}
/**
* 3 NOV
*/
for(std::set<recyclegate*>::iterator it = iterationState.toScheduleInputs[0].begin();
it != iterationState.toScheduleInputs[0].end(); it++)
{
iterationState.toDraw.push_back(*it);
}
/*
* Are there sufficient successful boxes?
*/
if(!sufficientBoxes)
{
printf("Not sufficient successful boxes. Another scheduling round is required.\n");
}
/*
* Draw geometry until the inputs that were scheduled.
* The inputs are not drawn in this iteration, but in the future one
* The explanation is that after inputs are found (at level d1), the inputs could
* need to be moved at a later level (d2). However, there may be other unscheduled
* inputs at level d3 so that d1<d3<d2. Therefore, it seemed easier, to schedule as they come,
* and draw as they result after the scheduling
*/
geom.makeGeometryFromCircuit(iterationState);
currentJournalEntry.operationType = "connect and extend";
// connManager.updateConnections(BOXCONNECTION, schedControl.getTimeWhenPoolEnds(), heuristicParam.connectionHeight, toConnBoxes);
/*Sort the connections*/
// std::sort(toConnBoxes.begin(), toConnBoxes.end(), mySortConnectionsFunction);
// for(size_t i = 0; i < toConnBoxes.size(); i++)
// {
// //TODO: this seems not to work. keep false
// toConnBoxes[i].hasSourceAndDestinationReversed = false;
// /*
// * The first connection has lowest block priority
// */
// currentJournalEntry.blockPriority = 50 + i;
//
// if(!toConnBoxes[i].isColinear())
// {
// //points are not guaranteed colinear if a box is to be connected
// //to the connections rail
// currentJournalEntry.blockType = WALKBLOCKED_OCCUPY;
//
// toConnBoxes[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITDEPTH, /*heuristicParam.connectionBufferTimeLength -*/ 10/*2,3*/, WALKBLOCKED_OCCUPY, currentJournalEntry);//dubios
//
// toConnBoxes[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITHEIGHT, 15/*-10*//*-4*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ghid
//
// //15.05.2017
// toConnBoxes[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITDEPTH, -6/*-4*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ghid
// }
// else
// {
// currentJournalEntry.blockType = WALKBLOCKED_GUIDE;
// toConnBoxes[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITDEPTH, 100 /*HEURISTIC block forever*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ocupat viitor
// }
//
// currentJournalEntry.blockType = WALKBLOCKED_GUIDE;
// toConnBoxes[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITDEPTH, 100 /*block forever*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ocupat viitor
// }
connManager.updateConnections(EXTENDCONNECTION, schedControl.getTimeWhenPoolEnds(), heuristicParam.connectionHeight, toConnExtensions);
// /*Sort the connections*/
// std::sort(toConnExtensions.begin(), toConnExtensions.end(), mySortConnectionsFunction);
// for(size_t i = 0; i < toConnExtensions.size(); i++)
// {
// //TODO: this seems not to work. keep false
// toConnExtensions[i].hasSourceAndDestinationReversed = false;
// /*
// * The first connection has lowest block priority
// */
// currentJournalEntry.blockPriority = 50 + i;
//
// if(!toConnExtensions[i].isColinear())
// {
// //points are not guaranteed colinear if a box is to be connected
// //to the connections rail
// currentJournalEntry.blockType = WALKBLOCKED_OCCUPY;
//
// toConnExtensions[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITDEPTH, /*heuristicParam.connectionBufferTimeLength -*/ 10/*2,3*/, WALKBLOCKED_OCCUPY, currentJournalEntry);//dubios
//
// currentJournalEntry.blockType = WALKBLOCKED_GUIDE;
// toConnExtensions[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITHEIGHT, 15/*-10*//*-4*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ghid
// toConnExtensions[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITDEPTH, 100 /*HEURISTIC block forever*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ocupat viitor
// }
// else
// {
// currentJournalEntry.blockType = WALKBLOCKED_GUIDE;
// toConnExtensions[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITDEPTH, 100 /*HEURISTIC block forever*/, WALKBLOCKED_GUIDE, currentJournalEntry);//ocupat viitor
// }
// }
/*
* Form pairs of pool connections and circuit pins
*/
std::vector<pinpair> finaliseConn;
currentJournalEntry.operationType = "finalise";
bool executedOK = connManager.finaliseAssignedConnections(iterationState, geom.allpins.inputList, finaliseConn);
if(!executedOK)
{
/*
* A pair was not possible
*/
printf("A PAIR FAILED\n");
break;
}
else
{
// /*
// * The first pin is connection. The second pin is circuit.
// * Because circuit pins are drawn in a future step
// */
// for(size_t i = 0; i < finaliseConn.size(); i++)
// {
// currentJournalEntry.blockPriority = 300 + i;
//
// //03.11.2017
// currentJournalEntry.blockType = WALKBLOCKED_OCCUPY;
// finaliseConn[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITDEPTH, heuristicParam.timeBeforePoolEnd, WALKBLOCKED_OCCUPY, currentJournalEntry);
//
// currentJournalEntry.blockType = WALKBLOCKED_OCCUPY;
// finaliseConn[i].getPinDetail(SOURCEPIN).
// addPinBlock(0, CIRCUITHEIGHT, -3, WALKBLOCKED_OCCUPY, currentJournalEntry);
//
// currentJournalEntry.blockType = WALKBLOCKED_OCCUPY;
// finaliseConn[i].getPinDetail(DESTPIN).
// addPinBlock(0, CIRCUITHEIGHT, 20/*heuristicParam.connectionHeight / 2*/, WALKBLOCKED_OCCUPY, currentJournalEntry);
// }
}
printf("## Finalise %lu FromBoxes %lu Extend %lu\n", finaliseConn.size(), toConnBoxes.size(), toConnExtensions.size());
/*
* Compute
*/
pinConnector.blockPins(toConnBoxes);
pinConnector.blockPins(toConnExtensions);
pinConnector.blockPins(finaliseConn);
printf("Bring to Pool...\n");
if(!pinConnector.processPins(toConnBoxes, CANONICAL1))
{
/*
* A connection was not possible
*/
printf("TO POOL: A CONNECTION FAILED\a\n");
break;
}
/*
* Extend the pool connections
*/
printf("Extend in Pool...\n");
if(!pinConnector.processPins(toConnExtensions, CANONICAL2))
{
/*
* A connection was not possible
*/
printf("EXTEND: A CONNECTION FAILED\a\n");
break;
}
for(std::vector<pinpair>::iterator it = toConnExtensions.begin(); it != toConnExtensions.end(); it++)
{
pinConnector.setWalkable(it->getPinDetail(SOURCEPIN), REMOVE_BLOCK, WALKBLOCKED_GUIDE);
pinConnector.setWalkable(it->getPinDetail(DESTPIN), REMOVE_BLOCK, WALKBLOCKED_GUIDE);
it->getPinDetail(SOURCEPIN).removeBlocks();//blocks.clear();
it->getPinDetail(DESTPIN).removeBlocks();//blocks.clear();
}
printf("Get from pool...\n");
if(!pinConnector.processPins(finaliseConn, CANONICAL1))
{
/*
* A connection was not possible
*/
printf("FROM POOL: A CONNECTION FAILED\a\n");
break;
}
else
{
// /*
// * 3NOV - add segment connecting the last connections
// * should be only two connections in this resource estimator
// */
// if(finaliseConn.size() > 0)
// {
// int idx1 = pinConnector.connectionsGeometry.addCoordinate(finaliseConn[0].getPinDetail(DESTPIN).coord);
// int idx2 = pinConnector.connectionsGeometry.addCoordinate(finaliseConn[1].getPinDetail(DESTPIN).coord);
// pinConnector.connectionsGeometry.addSegment(idx1, idx2);
// }
}
/**