-
Notifications
You must be signed in to change notification settings - Fork 0
/
DD.cpp
1939 lines (1743 loc) · 64.3 KB
/
DD.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
//
// Created by nandgate on 6/3/24.
//
#include "DD.h"
#include <queue>
#include <limits>
/**
* Compiles the decision diagram tree with given node as the root.
*/
optional<vector<Node_t>> DD::build(DDNode &node) {
// node parameter should be initialized before calling this function. node should contain states.
// the given node parameter will be inserted as the root of the tree.
const auto& arcOrder = networkPtr->processingOrder;
const auto& stateUpdateMap = networkPtr->stateUpdateMap;
// set the node to the root.
vector<ulint> currentLayer; // should be root layer.
startTree = node.globalLayer; // LATER, size of solution vector of the root might be appropriate
node.incomingArcs.clear();
node.outgoingArcs.clear();
node.id = 0; // make new node if necessary.
node.nodeLayer = 0; // TODO change during branch and bound.
nodes.insert(std::make_pair(node.id, node));
currentLayer.push_back(node.id);
// insert root layer to tree.
tree.push_back(currentLayer);
auto start = arcOrder.begin() + startTree;
auto end = arcOrder.end();
uint index = 0; // for node layer.
for (; start != end; ++start){
auto[a,b] = *start;
if (stateUpdateMap.count(a)) { // update state of each node in the layer.
const auto& newStates = stateUpdateMap.at(a);
updateState(currentLayer, newStates);
}
//const unordered_set<int> temp = stateUpdateMap.at(a);
vector<ulint> nextLayer;
//nextLayer.reserve(MAX_WIDTH);
isExact = buildNextLayer(currentLayer, nextLayer, networkPtr->hasStateChanged[a+1]);
if (isExact) exactLayer++; // at last, this number should be exact layer number.
//reduceLayer(nextLayer); // INFO not doing reduction.
++index;
tree.push_back(nextLayer);
currentLayer = std::move(nextLayer);
}
// terminal node layer.
vector<ulint> terminalLayer;
DDNode terminalNode {number.getNext()};
terminalNode.nodeLayer = ++index;
// current layer points to last layer of tree.
for (const auto& id: currentLayer){
// only add single arc for each node in the last layer.
ulint arcId = number.getNext();
auto& parentNode = nodes[id];
// create arc add to incoming of terminal node.
DDArc arc{arcId, id, terminalNode.id, 1};
arc.weight = std::numeric_limits<double>::max();
terminalNode.incomingArcs.push_back(arcId);
parentNode.outgoingArcs.push_back(arcId);
arcs.insert(make_pair(arcId, arc));
}
nodes.insert(make_pair(terminalNode.id, terminalNode));
terminalLayer.push_back(terminalNode.id);
tree.push_back(terminalLayer);
// generate cutset.
//cutSet = generateExactCutSet(); TODO uncomment this.
#ifdef DEBUG
// displayArcLabels();
displayStats();
#endif
if (exactLayer == index-1) return {};
return generateExactCutSet();
// return (exactLayer == index+1) ? generateExactCutSet() : std::nullopt;
}
inline void DD::updateState(const vector<ulint> ¤tLayer, const set<int> &states){
for (auto id: currentLayer){
auto& node = nodes[id];
node.states.clear();
node.states.insert(states.begin(), states.end());
}
}
/**
* Builds the next layer given the current layer corresponding to the type of DD.
* Strategies to build the next layer can be modified by changing '_STRATEGY' macro.
* Returns boolean true if the newly built layer is an exact layer, else returns boolean false.
*/
bool DD::buildNextLayer(vector<ulint> ¤tLayer, vector<ulint> &nextLayer, bool stateChangesNext) {
/*
* builds next layer from the given current layer.
* adds new child nodes and outgoing arcs to their respective maps.
* updates current layer's nodes and their arcs in the map.
* This function uses reduction only during compilation of relaxed tree.
*/
bool isExact = true;
if (type == RESTRICTED) {
#if RESTRICTED_STRATEGY == 1
{
if (currentLayer.size() >= MAX_WIDTH) { // new strategy after tree becomes non-exact.
buildNextLayer6(currentLayer, nextLayer);
return false;
}
uint count = 0;
for (const auto id: currentLayer) {
DDNode &parentNode = nodes[id];
const auto parentStates = parentNode.states;
// INFO; states should contain -1.
for (auto start = parentNode.states.rbegin(); start != parentNode.states.rend(); ++start){
auto decision = *start; // iterate reverse order.
// for (const auto decision: parentNode.states) {
if (count >= MAX_WIDTH) {isExact = false; break; } // jump with goto, instead of this.
auto lastInserted = number.getNext();
DDNode node{lastInserted};
DDArc arc{lastInserted, parentNode.id, node.id, decision};
node.states = parentStates;
if (decision != -1) node.states.erase(decision);
//node.solutionVector = parentNode.solutionVector; // solutions are computed during bulding cutset.
//node.solutionVector.emplace_back(decision);
node.incomingArcs.emplace_back(arc.id);
node.nodeLayer = parentNode.nodeLayer+1;
node.globalLayer = parentNode.globalLayer+1;
parentNode.outgoingArcs.push_back(arc.id);
// insert node and arc to map
nodes.insert(std::make_pair(node.id, node));
arcs.insert(std::make_pair(arc.id, arc));
count++;
nextLayer.emplace_back(node.id);
}
}
}
#elif RESTRICTED_STRATEGY == 2
// remove nodes at random
#endif
}
else if(type == RELAXED){
/*
* RELAXED_STRATEGY . make relaxed arcs to point to last inserted node in
* the current layer.
*/
#if RELAXED_STRATEGY == 3
{
int count = 0;
ulint lastNodeId = 0;
for (const auto id: currentLayer) {
DDNode &parentNode = nodes[id];
auto parentStates = parentNode.states;
for (auto decision: parentNode.states) {
auto lastInserted = number.getNext();
if (count < MAX_WIDTH) {
DDNode node{lastInserted};
DDArc arc{lastInserted, id, node.id, decision};
node.states = parentStates;
if (decision != -1) node.states.erase(decision);
//node.solutionVector = parentNode.solutionVector;
//node.solutionVector.emplace_back(decision);
node.incomingArcs.emplace_back(arc.id);
parentNode.outgoingArcs.push_back(arc.id);
node.nodeLayer = index;
// insert node and arc to map
nodes.insert(std::make_pair(node.id, node));
arcs.insert(std::make_pair(arc.id, arc));
lastNodeId = node.id;
nextLayer.emplace_back(node.id);
} else { // create only arc and make it point to the last node.
// QUESTION: do we create all arcs in relaxed version.
DDArc arc{lastInserted, id, lastNodeId, decision};
DDNode &node = nodes[lastNodeId];
node.states.insert(parentStates.begin(), parentStates.end()); // insert parent states
if(decision != -1) node.states.erase(decision); // remove decision
node.incomingArcs.emplace_back(arc.id);
parentNode.outgoingArcs.emplace_back(arc.id);
arcs.insert(std::make_pair(arc.id, arc));
isExact = false;
}
count++;
//lastInserted++;
}
}
}
//#endif
#elif RELAXED_STRATEGY == 2
{
// merge all outgoing arcs of parent to the same children.
int count = 0;
ulint lastNode;
if (currentLayer.size() >= MAX_WIDTH) {
// for each parent, create only one child.
for (const auto& id: currentLayer) {
// create child node.
auto& parentNode = nodes[id];
auto parentStates = parentNode.states;
auto lastInserted = number.getNext();
DDNode node{lastInserted};
node.states = parentStates;
for (auto decision : parentStates) {
//lastInserted = number.getNext();
DDArc arc{lastInserted, id, node.id, decision};
//node.states = parentStates;
//if (decision != -1) node.states.erase(decision); // INFO not required, because relaxation.
parentNode.outgoingArcs.push_back(lastInserted);
node.incomingArcs.push_back(lastInserted);
arcs.insert(std::make_pair(lastInserted, arc));
lastInserted = number.getNext();
//nodes.insert(std::make_pair(lastInserted, node));
}
// insert node to the map and node id to tree.
nodes.insert(std::make_pair(node.id, node));
nextLayer.push_back(node.id);
isExact = false; // TODO is this correct?
}
}
else { // build complete layer. this might cross MAX_WIDTH.
for (const auto& id : currentLayer) {
auto& parentNode = nodes[id];
auto parentStates = parentNode.states;
for(auto decision : parentStates) {
auto nextId = number.getNext();
DDNode node{nextId};
DDArc arc{nextId, id, node.id, decision};
node.states = parentStates;
if (decision != -1) node.states.erase(decision);
node.incomingArcs.push_back(arc.id);
parentNode.outgoingArcs.push_back(arc.id);
nodes.insert(std::make_pair(node.id, node));
arcs.insert(std::make_pair(arc.id, arc));
nextLayer.push_back(node.id);
}
}
if (nextLayer.size() > MAX_WIDTH) isExact = false;
}
}
#elif RELAXED_STRATEGY == 1
#endif
}
else { // exact tree.
#if EXACT_STRATEGY == 1
{
// build complete tree with state reduction.
if (stateChangesNext) { // next DD layer will undergo state change, so create only one node.
// if current layer is trouble maker, then handle edge case.
const auto& layer = nodes[currentLayer.front()].globalLayer;
bool res = stateChangesNext; //networkPtr->troubleMaker[layer] == 1;
auto nextNodeId = number.getNext();
DDNode newNode{nextNodeId};
//newNode.nodeLayer = index;
for (const auto id : currentLayer) {
assert(nodes.count(id));
auto &node = nodes[id];
newNode.nodeLayer = node.nodeLayer+1;
newNode.globalLayer = node.globalLayer+1;
for (auto decision: node.states) {
if (res && node.states.size() > 1 && decision == -1) {
// do not create arc.
// cout << "Trouble maker arc is not created." << endl;
continue;
}
auto nextId = number.getNext();
DDArc newArc{nextId, id, nextNodeId, decision};
node.outgoingArcs.push_back(nextId);
newNode.incomingArcs.push_back(nextId);
arcs.insert(make_pair(nextId, newArc));
}
} // state of this node is updated in the build() in next iteration.
nextLayer.push_back(nextNodeId);
nodes.insert(make_pair(nextNodeId, newNode));
}
else {
vector<DDNode> nodesVector;
unordered_set<tuple<set<int>, int, int>, tuple_hash, tuple_equal> allStates;
int j = 0;
for (const auto id: currentLayer) {
assert(nodes.count(id));
auto &node = nodes[id];
auto statesCopy = node.states;
for (auto decision: node.states) {
auto newStates(statesCopy);
if (decision != -1) newStates.erase(decision);
auto nextId = number.getNext();
// if newStates already in allStates, update exising node in nodesVector.
// auto [it, isInserted] = allStates.insert({newStates, 0, j});
// if (isInserted) { // create new Node
DDNode newNode{nextId};
DDArc newArc{nextId, id, nextId, decision};
newNode.nodeLayer = node.nodeLayer+1;
newNode.globalLayer = node.globalLayer+1;
newNode.states = newStates;
newNode.incomingArcs.push_back(nextId);
node.outgoingArcs.push_back(nextId);
arcs.insert(make_pair(nextId, newArc));
nodesVector.push_back(newNode);
j++;
// } else { // state already exists, update existing node in nodesVector.
// auto [tempState, state2, pos] = *(it);
// auto &prevNode = nodesVector[pos];
// DDArc newArc{nextId, id, prevNode.id, decision};
// prevNode.incomingArcs.push_back(nextId);
// node.outgoingArcs.push_back(nextId);
// arcs.insert(make_pair(nextId, newArc));
// }
}
}
// populate nextLayer. LATER. move nodes from vector.
for (auto& node : nodesVector) {
nextLayer.push_back(node.id);
nodes.insert(make_pair(node.id, node));
}
}
}
#elif EXACT_STRATEGY == 2
// without state reduction.
#endif
}
return isExact;
}
/**
* Creates a child node for the given parent node, and the corresponding arc
* between them. Inserts the child node and the arc to the map. Returns the
* id of the child node, this id is same for the arc between them.
* @param parent parent node
* @param decision decision of the arc between parent and child node.
* @return id of the child node (= id of arc between parent and child).
*/
ulint DD::createChild(DDNode& parent, int decision) {
// create child for this node with the decision.
auto nextId = number.getNext();
DDNode newNode{nextId};
newNode.states = parent.states;
if (decision != -1) newNode.states.erase(decision);
DDArc arc {nextId, parent.id, nextId, decision};
newNode.incomingArcs.push_back(nextId);
parent.outgoingArcs.push_back(nextId);
nodes.insert(make_pair(nextId, newNode));
arcs.insert(make_pair(nextId, arc));
return nextId;
}
/**
* Build next layer with minimum number of nodes that can be created with -1.
* Assumes next layer is not exact. DO NOT CALL this function if DD is still exact.
* @param currentLayer
* @param nextLayer
*/
void DD::buildNextLayer2(vector<ulint> ¤tLayer, vector<ulint> &nextLayer) {
uint count = 0;
for (const auto id: currentLayer) {
auto& node = nodes[id];
if (node.states.size() > 1) {
for (auto decision: node.states) {
if (decision == -1) continue;
auto childId = createChild(node, decision);
nextLayer.push_back(childId);
if (count++ >= MAX_WIDTH) return;
}
}
else {
auto childId = createChild(node, -1);
nextLayer.push_back(childId);
if (count++ >= MAX_WIDTH) return;
}
}
}
void DD::buildNextLayer3(vector<ulint>& currentLayer, vector<ulint>& nextLayer) {
uint count = 0;
// for each node, create only one child
for (const auto id: currentLayer) {
auto& node = nodes[id];
if (node.states.size() > 1) {
for (auto state: node.states) {
if (state == -1) continue;
// create child
auto childId = createChild(node, state);
nextLayer.push_back(childId);
break;
}
}
else {
auto childId = createChild(node, -1);
nextLayer.push_back(childId);
}
count++;
if (count >= MAX_WIDTH) return;
}
}
void DD::buildNextLayer4(vector<ulint> ¤tLayer, vector<ulint> &nextLayer) {
// select arc with maximum reward. for each parent create single child
for (const auto id: currentLayer) {
auto& node = nodes[id];
int decision = -1;
if (node.states.size() > 1) // select arc with maximum reward.
decision = networkPtr->getBestArc(node.states);
auto childId = createChild(node, decision);
nextLayer.push_back(childId);
}
}
void DD::buildNextLayer5(vector<ulint> ¤tLayer, vector<ulint> &nextLayer) {
// match out arc that has max reward to the current incoming arc.
for (const auto id: currentLayer) {
auto& node = nodes[id];
// get layer number
auto inArcReward = networkPtr->layerRewards[node.globalLayer];
// get best arc
auto bestState = networkPtr->getBestArc(node.states);
int decision = -1;
if (bestState != -1 && networkPtr->networkArcs[bestState].rewards[0] + inArcReward >= 0) {
// match this out arc with in arc.
decision = bestState;
}
auto childId = createChild(node, decision);
nextLayer.push_back(childId);
}
}
void DD::buildNextLayer6(vector<ulint> ¤tLayer, vector<ulint> &nextLayer) {
// if current layer is trouble maker, then handle troublemaker node.
const auto& layerNumber = nodes[currentLayer.front()].globalLayer;
// bool res = (networkPtr->troubleMaker[layerNumber] == 1);
// if (networkPtr->troubleMaker[layerNumber] == 1) {
if (networkPtr->hasStateChanged[layerNumber+1]){ // state changes in next layer, thus remove -1 arcs from this layer.
// for all the nodes, remove paths that contains all -1's for this node.
for (const auto id: currentLayer) {
auto& node = nodes[id];
int decision = -1;
for (auto start = node.states.rbegin(); start != node.states.rend(); ++start) {
auto state = *start;
if (state > decision) decision = state;
}
// for (auto state: node.states){ if (state > decision) decision = state;}
auto childId = createChild(node, decision);
nextLayer.push_back(childId);
}
return;
}
// select one state from states at random
srand(time(nullptr));
for (const auto id: currentLayer) {
auto& node = nodes[id];
vi states{node.states.begin(), node.states.end()};
auto s = rand()%states.size();
auto decision = states.back();
auto childId = createChild(node, decision);
nextLayer.push_back(childId);
}
}
/**
* Merges the second DDNode into the first DDNode.
* Updates fist node's attributes and deletes second node from the map.
*/
void DD::mergeNodes(DDNode& node1, DDNode& node2) {
/*
* Merge node2 with node1. Updates node1 attributes and removes node2 from dictionary.
* Used in reduceNodes().
*/
for (auto parent: node2.incomingArcs){ // update head id of the incoming arcs to node1.id
auto& arc = arcs[parent];
arc.head = node1.id; // TODO: change other attributes if needed
}
for (auto child: node2.outgoingArcs){ // update tail id of outgoing arcs to node1.id
auto& arc = arcs[child];
arc.tail = node1.id; // TODO: change other attributes if needed.
}
// update node1 incomingArcs to add node2's incomingArcs.
node1.incomingArcs.insert(node1.incomingArcs.end(), node2.incomingArcs.begin(), node2.incomingArcs.end());
node1.outgoingArcs.insert(node1.outgoingArcs.end(), node2.outgoingArcs.begin(), node2.outgoingArcs.end());
node2.incomingArcs.clear();
node2.outgoingArcs.clear();
}
void DD::reduceLayer(vector<ulint> ¤tLayer) {
/*
* Merge two nodes that containing same state. Update incoming and outgoing arcs to point to merged node.
*/
queue<ulint> q;
unordered_set<tuple<set<int>,int,int>,tuple_hash,tuple_equal> allStates;
uint j = 0;
for (auto i: currentLayer){
auto& node = nodes[i];
auto [it,isInserted] = allStates.insert({node.states, node.state2, i});
if (!isInserted) { // already exists, merge both nodes.
auto& [temp_state, temp_stat2, pos ] = *(it);
// get node from dict with pos as key and update its attributes.
auto& node2 = nodes[pos];
mergeNodes(node2, node);
// delete node from nodes.
nodes.erase(node.id);
q.push(i);
}
j++;
}
queue tempQ {q};
while (!tempQ.empty()) {number.setNext(tempQ.front()); tempQ.pop();}
// remove filtered nodeIds from current layer.
currentLayer.erase(std::remove_if(currentLayer.begin(), currentLayer.end(),
[&q](const int x) mutable{
if ((!q.empty()) && (q.front() == x)) { q.pop(); return true;}
return false;
}),currentLayer.end());
}
/**
* Deletes the arc from the arcs map given its id.
*/
void DD::deleteArcById(ulint id){
/*
* deletes arc by id.`
* removes the arc from tail and head nodes.
* deletes arc from arcs dictionary.
*
* INFO function assumes both the head and tail nodes are in the nodes dictionary.
*/
auto& arc = arcs[id];
auto& tailNode = nodes[arc.tail];
auto& headNode = nodes[arc.head];
headNode.incomingArcs.erase(std::find(headNode.incomingArcs.begin(), headNode.incomingArcs.end(), id));
tailNode.outgoingArcs.erase(std::find(tailNode.outgoingArcs.begin(), tailNode.outgoingArcs.end(), id));
arcs.erase(id);
}
/**
*
*/
void DD::deleteNodeById(ulint id) {
/*
* deletes node by its id.
* delete outgoing arcs vector. destructor deletes remaining attributes.
*/
auto& node = nodes[id];
auto outgoingArcs = node.outgoingArcs;
for (const auto arcId : outgoingArcs){
deleteArcById(arcId);
}
// INFO not sure if this function shoudl remove the node from the map.
nodes.erase(id); // remove this if node deletion happens outside of the function.
deletedNodeIds.insert(id); // this id should be removed from the tree layer, after refinement.
}
inline DDNode DD::duplicate(const DDNode& node){
// clone the node. for every outgoing arc, create new arc and point it to child node.
auto lastInserted = number.getNext();
DDNode dupNode(lastInserted);
dupNode.state2 = node.state2;
dupNode.states = node.states;
// LATER not sure how to copy solution vector
// incoming arc is updated by the caller.
for (const auto& outArcId: node.outgoingArcs){
const auto& childNodeId = arcs[outArcId].head;
lastInserted = number.getNext();
DDArc newArc{lastInserted, dupNode.id, childNodeId, arcs[outArcId].decision};
dupNode.outgoingArcs.push_back(newArc.id);
nodes[childNodeId].incomingArcs.push_back(newArc.id);
arcs.insert(std::make_pair(newArc.id, newArc));
//lastInserted++;
}
return dupNode;
}
void DD::duplicateNode(ulint id){
/*
* for every incoming arc, create new node (copy state parameters)
* TODO: complete it today.
*/
auto& node = nodes[id];
auto incomingArcs = node.incomingArcs;
// skip first arc.
for (uint i = 1; i < incomingArcs.size(); i++) {
//
ulint arcId = incomingArcs[i];
DDArc& arc = arcs[arcId];
// TODO compute state.
bool feasible = true; // TODO: based on the cut, build if node is feasible.
if (feasible){
DDNode newNode = duplicate(node); // set incoming arc.
// update incoming arc and make the arc to point to new node.
newNode.incomingArcs.push_back(arcId);
nodes.insert(std::make_pair(newNode.id, newNode));
arc.head = newNode.id;
}
else {
// delete arc.
deleteArcById(arcId);
auto& tailOutArcs = nodes[arc.tail].outgoingArcs;
tailOutArcs.erase(std::find(tailOutArcs.begin(), tailOutArcs.end(), arcId));
// remove arc
arcs.erase(arcId);
}
}
// remove the incoming arcs of original node.
// compute state and keep it if node is feasible.
if (true){ // feasible, delete all incoming arcs except the first.
node.incomingArcs.erase(node.incomingArcs.begin()+1, node.incomingArcs.end());
}
else {
// delete node.
deleteArcById(node.incomingArcs[0]);
deleteNodeById(node.id);
}
}
vi DD::solution() {
/*
* Start from terminal node and iterate through incoming arcs and select arc.
* Returns the maximum path from the tree.
*/
// find maxVal parent node.
double maxVal = std::numeric_limits<double>::lowest();
ulint maxNodeId = 0;
vi path;
path.reserve(tree.size()-1);
ulint terminalNodeId = tree[tree.size()-1][0];
const auto& terminalNode = nodes[terminalNodeId];
for (const auto arcId: terminalNode.incomingArcs){ // find maxValue path.
const auto& arc = arcs[arcId];
if (arc.weight > maxVal){
maxVal = arc.weight; // change to objective value later.
maxNodeId = arc.tail;
}
}
// maxVal and maxNodeId is populated.
for (size_t l = tree.size()-2; l > 0; l--){
// const auto& node = nodes[maxNodeId];
// const auto& arc = arcs[node.incomingArcs[0]];
// path[l] = arc.decision;
// maxNodeId = arc.tail;
const auto& node = nodes[maxNodeId];
for (const auto& arcId : node.incomingArcs){
const auto& arc = arcs[arcId];
const auto& tailNode = nodes[arc.tail];
if ((tailNode.state2 + arc.weight) == node.state2){
maxNodeId = tailNode.id;
path.push_back(arc.decision);
break;
}
}
}
// prepend root solution to path.
const auto& rootNode = nodes[tree[0][0]];
vi finalPath(rootNode.solutionVector);
finalPath.insert(finalPath.end(), path.rbegin(), path.rend());
return finalPath;
}
/**
* Returns solution vector for a given node in the exact layer. function should only used for
* a node in the exact cutset.
* @param nodeId - id of node in the cutset.
* @return - vector of solutions from root to the given node.
*/
vi DD::computePathForExactNode(ulint nodeId) const{
DDNode node = nodes.at(nodeId);
vi solutionVector;
// iterate through all nodes from current node till root.
while (!node.incomingArcs.empty()) {
const auto& inArc = arcs.at(node.incomingArcs[0]);
solutionVector.push_back(inArc.decision);
node = nodes.at(inArc.tail);
}
// add root's solution.
vi result(node.solutionVector);
result.insert(result.end(), solutionVector.rbegin(), solutionVector.rend());
return result;
}
/**
* Creates a copy of given node. copies only the id,states
* and node-layer attributes.
* @param node
* @return
*/
DDNode copyNode(const DDNode& node) {
DDNode newNode{node.id};
newNode.states = node.states;
newNode.nodeLayer = node.nodeLayer;
return newNode;
}
/**
* Computes and returns a vector of nodes that are in exact cutset.
* @return vector of nodes that are in exact cutset.
*/
vector<Node_t> DD::generateExactCutSet() const {
/*
* returns a vector containing the nodes in the exact layer as cutset.
*/
vector<Node_t> cutsetNodes;
cutsetNodes.reserve(MAX_WIDTH);
for (const auto id: tree[exactLayer]){
const auto& node = nodes.at(id);
vi states{node.states.begin(), node.states.end()};
cutsetNodes.emplace_back(states, computePathForExactNode(id),
std::numeric_limits<double>::lowest(),std::numeric_limits<double>::max(),
node.globalLayer);
}
return cutsetNodes;
}
vector<Node_t> DD::getExactCutSet() {
return cutSet;
}
static vector<double> helperFunction(const Network &network, const Cut &cut) {
/*
* generates the lower bounds for each DD layer. used in feasibilitycut refinement.
*/
vector<double> lowerBounds(network.processingOrder.size());
const auto& coeff = cut.cutCoeff;
for (const auto[id_t, arcId]: network.processingOrder){
const auto& arc = network.networkArcs[arcId];
auto i = arc.tailId;
auto q = arc.headId;
const auto& node = network.networkNodes[q];
double max = 0;
for (const auto j: node.outNodeIds){
auto c = coeff.at(make_tuple(static_cast<int>(i),static_cast<int>(q),static_cast<int>(j)));
if (c > max) max = c;
}
lowerBounds[id_t] = max;
}
// compute suffix sum
double pref = 0;
for (auto start = lowerBounds.rbegin(); start != lowerBounds.rend(); start++){
*start = *start + pref;
pref = *start;
}
return lowerBounds; // automatic copy elision?
}
void DD::refineTree(const Network &network, Cut cut) {
if (cut.cutType == OPTIMALITY){
applyOptimalityCut(network, cut);
}
else applyFeasibilityCut(network, cut);
}
void DD::applyFeasibilityCut(const Network &network, const Cut &cut) {
vector<double> lowerBounds = helperFunction(network, cut);
const auto& coeff = cut.cutCoeff;
double RHS = cut.RHS;
}
void DD::applyOptimalityCut(const Network &network, const Cut &cut) {
// TODO: incorporate semiroot partial solution.
}
void DD::deleteArc(DDNode& tailNode, DDArc& arc, DDNode& headNode){
/*
* deletes the given arc from the arcs map.
* updates the head node's incomingArcs vector and tail node's outgoingArcs vector.
*/
assert(tailNode.id == arc.tail && headNode.id == arc.head);
assert(arcs.count(arc.id));
auto pos = std::find(headNode.incomingArcs.begin(), headNode.incomingArcs.end(), arc.id);
if (pos != headNode.incomingArcs.end()) headNode.incomingArcs.erase(pos);
auto pos2 = std::find(tailNode.outgoingArcs.begin(), tailNode.outgoingArcs.end(), arc.id);
if (pos2 != tailNode.outgoingArcs.end()) tailNode.outgoingArcs.erase(pos2);
arcs.erase(arc.id);
}
/**
* Deletes the given node from the nodes container. Inserts the node id to the list of
* deleted node Ids.
*
* A call to this function should be made iff both incoming and outgoing arcs are empty.
*/
void DD::deleteNode(DDNode& node){
assert(nodes.count(node.id));
deletedNodeIds.insert(node.id);
nodes.erase(node.id);
}
/**
* Deletes the subtree of the given node recursively.
*
* Removes only the child nodes that have one incoming arc.
*/
void DD::topDownDelete(ulint id) { // hard delete function.
/*
* start from the current node and recursively delete the children nodes
* until next node is terminal node or node with multiple incoming arcs.
* remove the last outgoing arc of the last node.
*/
{
assert(nodes.count(id));
auto &node = nodes[id];
// remove the incoming arc here.
//deleteArcById(node.incomingArcs[0]);
//assert(!node.outgoingArcs.empty());
auto arcsToDelete = node.outgoingArcs;
for (auto outArcId: arcsToDelete) {
// for each outArcId, find its head and apply topDownDelete() if head has single incoming arc.
assert(arcs.count(outArcId));
auto& outArc = arcs.at(outArcId);
auto childId = outArc.head;
assert(nodes.count(childId));
auto &childNode = nodes[childId];
deleteArc(node, outArc, childNode);
if (childNode.incomingArcs.empty()) topDownDelete(childId); // orphan node
}
assert(node.outgoingArcs.empty());
deleteNode(node);
}
// here, node has no outgoing arcs and incoming arcs left,
// also remove the node id from the tree layer.
//deleteNode(node);
}
/**
* Removes the node and its associated nodes from the nodes map and updates the
* tree vector if deletion is not occurring in batch.
* @param id Id of the node to be removed.
* @param isBatch updates the tree vector if parameter is false. Default value is false.
*/
void DD::removeNode(ulint id, bool isBatch){
/*
* NOTE:
*/
// if current node has multiple parents and multiple children, do this.
auto& node = nodes[id];
auto outArcs = node.outgoingArcs;
assert(!node.outgoingArcs.empty());
for (auto childArcId : outArcs){
assert(arcs.count(childArcId));
auto& childArc = arcs[childArcId];
assert(nodes.count(childArc.head));
auto& child = nodes[childArc.head];
deleteArc(node, childArc, child);
if (child.incomingArcs.empty()) topDownDelete(child.id); // orphan node
}
//if (node.incomingArcs.size() > 1) { // multiple parents
auto incomingArcs = node.incomingArcs;
assert(!node.incomingArcs.empty());
for (auto arcId: incomingArcs){
assert(arcs.count(arcId));
auto& arc = arcs[arcId];
assert(nodes.count(arc.tail));
auto& parentNode = nodes[arc.tail];
deleteArc(parentNode, arc, node);
if (parentNode.outgoingArcs.empty()) bottomUpDelete(parentNode.id); // orphan node
}
assert(node.incomingArcs.empty() && node.outgoingArcs.empty());
// actual delete.
deleteNode(node);
assert(!nodes.count(id));
if (!isBatch) updateTree(); // no batch deletion.
}
/**
* Removes the deleted node ids from the tree. Resets the deletedNodeIds variable after
* updating the tree. Adds the deletedNodeIds to the number.
*
* Optimized to call the function when removing nodes in batch.
*/
void DD::updateTree() {
int n_removed = deletedNodeIds.size();
auto& deletedNodeIds_l = this->deletedNodeIds;
auto f = [&n_removed, &deletedNodeIds_l] (ulint x) mutable {
if (deletedNodeIds_l.count(x)) { n_removed--; return true;}
return false;
};
#ifdef DEBUG
// cout << "Removing " << n_removed << " nodes from tree." << endl;
#endif
for (int i = tree.size()-2; i > 0; i--){ // iterate every layer until all deleted Ids are removed from tree.
if (n_removed){
auto& layer = tree[i];
layer.erase(std::remove_if(layer.begin(), layer.end(), f), layer.end());
}
else break;
}
// add deleted Ids to the numbers.
auto& num = number;
std::for_each(deletedNodeIds.begin(), deletedNodeIds.end(), [&num](ulint x) mutable{num.setNext(x);});
deletedNodeIds.clear(); // clear the deleted NodeIds set.
}
/**
* Removes the given node ids from the DD and updates the tree at once.
* @param ids vector of node ids to be removed.
*/
void DD::batchRemoveNodes(const vulint& ids) {
// remove all the ids without updating the tree.
for (auto id : ids) removeNode(id, true);
// update tree
updateTree();
}
void DD::bottomUpDelete(ulint id){
// INFO this node might contain multiple incoming parents, but might contain one (or zero) children.
// for each incoming arc, remove arc and call soft delete on incoming node (iff has single outgoing arc).
auto& node = nodes[id];
auto incomingArcs = node.incomingArcs;
for (const auto& arcId : incomingArcs){
auto& arc = arcs[arcId];
auto& parentNode = nodes[arc.tail];
deleteArc(parentNode, arc, node);
//deleteArcById(arcId); // delete this incoming arc.
if (parentNode.outgoingArcs.empty()){
bottomUpDelete(parentNode.id);
}
}
// delete this node from nodes.
deleteNode(node);
// phase 1: recursively reach parents if they don't have multiple children.
// if multiple incoming arcs? all bottomUpDelete () on each of the incoming nodes.
// phase 2: recursively reach down the tree until reaching terminal node or children with multiple incoming arcs.
// delete each node and arc in between.
}
void DD::applyFeasibilityCutRestricted(const Network &network, const Cut &cut) {
// set the root state to RHS. // TODO: during refinement, compute new RHS for the subroot.
nodes[0].state2 = cut.RHS;
// heuristic to remove nodes.
vector<double> lowerBounds = helperFunction(network, cut);