-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRTV.cpp
1942 lines (1845 loc) · 89.8 KB
/
RTV.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
#define _HAS_STD_BYTE 0
#include <map>
#include <unordered_set>
#include "util.h"
#include <algorithm>
#include <string>
#include <cstdio>
#include <tuple>
#include "util.h"
#include <ctime>
#include <cmath>
#include <chrono>
#include <omp.h>
#include <random>
#include <iomanip>
#include <sstream>
#include <cstring>
#include <fstream>
#include <filesystem>
#include "hps_src/hps.h"
#include "gurobi_c++.h"
#include "globals.h"
#include "RTV.h"
#include "RV.h"
#include "GPtree.h"
#include "travel.h"
#include "util.h"
using namespace std;
std::unordered_set<int> floyd_sampling(const int& k, const int& N) {
std::default_random_engine gen;
std::unordered_set<int> elems(k);
for (int r = N - k; r < N; ++r) {
int v = std::uniform_int_distribution<>(1, r)(gen);
if (!elems.insert(v).second) elems.insert(r);
}
return elems;
}
void mapAdd(map_of_uos& inout, map_of_uos& in) {
for (auto initer = in.begin(); initer != in.end(); ++initer) {
auto it = inout.try_emplace(initer->first, initer->second);
if (it.second == false) {
it.first->second.first += initer->second.first;
it.first->second.second.insert(initer->second.second.begin(), initer->second.second.end());
}
}
}
bool equal_to_sub(vector<int>& compared, vector<int>& origin, int excludeIdx) {
auto iterCompared = compared.begin();
auto iterOrigin = origin.begin();
int originIdx = 0;
while (iterCompared != compared.end() && iterOrigin != origin.end()) {
if (originIdx == excludeIdx) {
iterOrigin++;
originIdx++;
continue;
}
if (*iterCompared != *iterOrigin) {
return false;
}
iterCompared++;
iterOrigin++;
originIdx++;
}
return true;
}
int RTVGraph::addVehicleId(int vehicleId) {
vIds.push_back(vehicleId);
vIdx_tIdxes.push_back(vector<pair<int, pair<int, int>> >());
return numVehicles++;
}
void RTVGraph::add_edge_trip_vehicle(const uos& reqsInTrip, int vIdx, int cost) {
int tIdx = getTIdx(reqsInTrip);
#pragma omp critical (addetv2)
tIdx_vCostIdxes[tIdx].push_back(pair<int, pair<int, int>>(cost, pair<int, int>{distribOfCars(gen1), vIdx}));
//#pragma omp critical (addetv3)
vIdx_tIdxes[vIdx].push_back(pair<int, pair<int, int>>(cost, pair<int, int>{distribOfTrips(gen2), tIdx}));
}
void RTVGraph::add_edge_trip_vehicle(int tIdx, int vIdx, int cost) {
#pragma omp critical (addetv2)
tIdx_vCostIdxes[tIdx].push_back(pair<int, pair<int, int>>(cost, pair<int, int>{distribOfCars(gen1), vIdx}));
//#pragma omp critical (addetv3)
vIdx_tIdxes[vIdx].push_back(pair<int, pair<int, int>>(cost, pair<int, int>{distribOfTrips(gen2), tIdx}));
}
int RTVGraph::getTIdx(const uos& trip) {
auto iter = trip_tIdx.find(trip);
if (iter != trip_tIdx.end()) {
return iter->second;
}
int toReturn = 0;
#pragma omp critical (addetv1)
{
trip_tIdx.emplace(trip, numTrips);
trips.push_back(trip);
toReturn = numTrips++;
}
return toReturn;
}
void RTVGraph::build_potential_trips(RVGraph* rvGraph, vector<Request>& requests, vector<Vehicle>& vehicles) {
//Enumerate trips of size=1
const int nVeh = vehicles.size();
const int nReq = requests.size();
int fullyConnectedVeh = 0;
int partlyConnectedVeh = 0;
int totalConnections = 0;
int maxConnections = 0;
set<pair<int, int>> vehConnex;
map<int, int> vehIDToVehIdx;
std::vector<std::pair<int, uos>> prevInclusions;
prevInclusions.reserve(nVeh);
int addedToPrevInclusions = 0;
for (int i = 0; i < nVeh; i++) {
if (rvGraph->has_vehicle(i)) {
int vIdx = addVehicleId(i);
vehIDToVehIdx[i] = vIdx;
const vector<std::pair<int, int>>& edges = rvGraph->get_vehicle_edges(i); //req, cost
int nConnex = edges.size();
if (nConnex > 1) {
prevInclusions.push_back(std::pair<int, uos>(i, uos()));
vehConnex.insert(make_pair(-nConnex, addedToPrevInclusions));
addedToPrevInclusions++;
}
for (auto it = edges.begin(); it != edges.end(); ++it) {
uos tempUOS{ it->first };
add_edge_trip_vehicle(tempUOS, vIdx, it->second);
if (nConnex > 1) prevInclusions[prevInclusions.size() - 1].second.insert(it->first);
}
if (nConnex > 0) {
maxConnections = max(maxConnections, nConnex);
partlyConnectedVeh++;
totalConnections += nConnex;
if (nConnex == nReq) {
fullyConnectedVeh++;
}
}
}
}
allPotentialTrips[0].reserve(requests.size());
int reqsAdded = 0;
for (int i = 0; i < requests.size(); i++) {
allPotentialTrips[0].push_back(tripCandidate(uos{ i }));
}
serialize_current_combos();
const bool bFullyConnectedVeh = fullyConnectedVeh > 0 ? true : false;
const double bFractionConnected = fullyConnectedVeh / numVehicles;
const double sparsity = totalConnections / (1.0 * (partlyConnectedVeh * nReq));
print_line(outDir, logFile, string_format("%d vehicles, %d requests, %d fully connected vehicles, %d most connected (%f), %f percent dense.", numVehicles, nReq, fullyConnectedVeh, maxConnections, maxConnections * 100.0 / nReq, 100.0 * sparsity));
const bool bSparseTwo = (!bFullyConnectedVeh) && (sparsity < 0.8);
//const bool bTesting = true;
unordered_map<int, int> adjustedTripIdxes;
auto time2 = std::chrono::system_clock::now();
int travelCounter = 0;
int lastSizeSize = requests.size();
double lastSizeMaxConnectedness = 0;
double lastSizeAvgConnectedness = 0;
int test1counter = 0, test2counter = 0, test3counter = 0;
for (int k = 2; k <= max_trip_size; k++) {
/* Ex: to combine 4 requests, previous entry is 3-way combos,
of which we need at least 4: 1-2-3, 1-2-4, 1-3-4, 2-3-4 */
if (allPotentialTrips[k - 2].size() < k) break;
allPotentialTrips.push_back(vector<tripCandidate>{});
auto startOfSizeK = std::chrono::system_clock::now();
bool bAltMethod = false;
int completeCliques = 0;
map_of_uos newTrips; //key: set of requests (union of two trips);
//value: indices within allPotentialTrips[k-2]
//print_line(outDir,logFile,string_format("Starting to build potential %d-request combinations.", k));
if (k == 2) {
if (bSparseTwo) {
print_line(outDir, logFile, std::string("Enumerating sparse 2"));
set_of_pairs sop;
sop.reserve(lastSizeSize * (lastSizeSize - 1) / 2);
int vIdx2 = 0;
#pragma omp declare reduction (merge : set_of_pairs : omp_out.merge(omp_in))
#pragma omp parallel for default(none) private(vIdx2) shared(k, rvGraph) reduction(merge: sop)
for (vIdx2 = 0; vIdx2 < numVehicles; vIdx2++) {
auto itv2 = rvGraph->car_req_cost.find(vIds[vIdx2]);
if (itv2 == rvGraph->car_req_cost.end()) continue;
const vector<std::pair<int, int>>& thisVehVec = itv2->second;
int thisSize = thisVehVec.size();
std::vector<std::pair<int, int>> vPair;
vPair.reserve(itv2->second.size() * (itv2->second.size() - 1) / 2);
int i, j = 0;
std::pair<int, int> thisSet;
for (i = 0; i < thisSize; i++)
{
thisSet.first = thisVehVec[i].first;
for (j = i + 1; j < thisSize; j++) {
thisSet.second = thisVehVec[j].first;
vPair.push_back(thisSet);
}
}
sop.insert(vPair.begin(), vPair.end());
}
std::vector<pair<uos, pair<int, uosTBB>>> allCombosOfTwo;
allCombosOfTwo.reserve(sop.size());
for (auto it = sop.begin(); it != sop.end(); ++it) {
uos thisSet{{ it->first, it->second }};
allCombosOfTwo.push_back(pair<uos, pair<int, uosTBB>>{thisSet, pair<int, uosTBB>{1, thisSet}});
}
set_of_pairs().swap(sop);
newTrips.insert(allCombosOfTwo.begin(), allCombosOfTwo.end());
std::vector<pair<uos, pair<int, uosTBB>>>().swap(allCombosOfTwo);
}
else {
print_line(outDir, logFile, std::string("Enumerating dense 2"));
std::vector<pair<uos, pair<int, uosTBB>>> allCombosOfTwo;
allCombosOfTwo.reserve(lastSizeSize * (lastSizeSize - 1) / 2);
for (int i = 0; i < lastSizeSize; i++) {
for (int j = i + 1; j < lastSizeSize; j++) {
uos thisSet{ { i, j } };
allCombosOfTwo.push_back(pair<uos, pair<int, uosTBB>>{thisSet, pair<int, uosTBB>{1, thisSet}});
}
}
newTrips.insert(allCombosOfTwo.begin(), allCombosOfTwo.end());
std::vector<pair<uos, pair<int, uosTBB>>>().swap(allCombosOfTwo);
}
}
else {
const bool bSparseThree = (!bFullyConnectedVeh) && lastSizeAvgConnectedness<0.01 && lastSizeMaxConnectedness < 0.75;
print_line(outDir, logFile, string_format("Starting enumeration: avg connectedness %f, max %f.",lastSizeAvgConnectedness,lastSizeMaxConnectedness));
/*
When generating trips of size 3:
Only need to look for pairwise combos of size=2 trips that have overlap = 1 request.
SO, they need to have one shared dependency (trip of size=1).
Can iterate over trips of size 1 where dependentTrips.size()>=2, and get all the pairwise combos of size=2 trips from that.
(Should be no duplicates?? 99% sure but should sketch it out maybe)
How many times? They have to have TWO pairwise combos (of trips of size 2) with overlap 1.
(eg: 12, 23, 13)
When generating trips of size 4:
Only need to look for pairwise combos of size=3 trips that have overlap = 2 requests.
SO, they need to have one shared dependency (trip of size = 2).
Can iterate over trips of size 2 where dependentTrips.size()>=2, and get all the pairwise combos of size=3 trips from that.
How many times? They need to have FOUR (k) pairwise combos of trips of size 3 (k-1) with overlap 2 (k-2).
eg: (12, 23, 13) or (123, 124, 134, 234) or (1234, 1235, 1245, 1345, 2345) or (12345, 12346, 12356, 12456, 13456, 23456)
k=3: for 123 to work, 12 & 13 & 23 have to be in 1, 1 & 2 & 3 have to be in 2
k=4: for 1234 to work, 123 & 124 & 134 & 234 have to be in 1, 12 & 23 & 13 & 14 & 24 & 34 have to be in 2, 1 & 2 & 3 & 4 have to each be in 3
k=5: 123 has to be in 2, 12 has to be in 3, 1 has to be in 4
for 12345 to work, 1234, 1235
for 123456 to work: 1234, 1235, 1236
*/
print_line(outDir, logFile, string_format("Enumerating potential %d-trips, default way.", k));
const int twoSmallerSize = allPotentialTrips[k - 3].size();
auto adjustedTripEnd = adjustedTripIdxes.end();
int m = 0;
#pragma omp declare reduction (mergeNewTrips : map_of_uos : mapAdd(omp_out, omp_in))
#pragma omp parallel for default(none) private(m) shared(k, newTrips, adjustedTripEnd, adjustedTripIdxes)
for (m = 0; m < twoSmallerSize; m++) {
const vector<int>& dependentTrips = allPotentialTrips[k - 3][m].dependentTrips;
int numDependentTrips = dependentTrips.size();
if (numDependentTrips < 2) continue;
pair<int, int> dj(-1,-1);
for (int i = 0; i < numDependentTrips; i++) {
auto itI = adjustedTripIdxes.find(dependentTrips[i]);
if (itI == adjustedTripEnd) continue;
int indexI = itI->second;
const uos& trip1 = allPotentialTrips[k - 2][indexI].requests;
for (int j = i + 1; j < numDependentTrips; j++) {
auto itJ = adjustedTripIdxes.find(dependentTrips[j]);
if (itJ == adjustedTripEnd) continue;
int indexJ = itJ->second;
const uos& trip2 = allPotentialTrips[k - 2][indexJ].requests;
getDisjunction(trip1, trip2, dj);
if (dj.first == -1) continue;
uos tripUnion = dj.first == 0 ? trip1 : trip2;
tripUnion.insert(dj.second);
#pragma omp critical(updateItNT)
{
auto itNT = newTrips.try_emplace(tripUnion, make_pair<int, uos>(1, { indexI, indexJ }));
if (itNT.second == false) {
itNT.first->second.first++;
itNT.first->second.second.insert({ indexI, indexJ });
}
}
}
}
}
}
//put the pointers in the vector
int newTripsSize = newTrips.size();
print_line(outDir, logFile, string_format("Starting to check feasibility of %d %d-request combinations.", newTripsSize, k));
int thisSizeCounter = 0;
int elementSize = 0;
vector<pair<const uos, pair<int, uosTBB>>*> elements;
if (k > 2 && !bAltMethod) {
for (auto it = newTrips.begin(); it != newTrips.end(); )
{ //complete clique requirement: all k subsets of size k-1 must be in here
if (it->second.second.size() == k && it->second.first >= k * (k - 1) / 2) { ++it; }
else { newTrips.erase(it++); }
}
newTrips.rehash(0);
}
elements.reserve(newTrips.size());
for (auto it = newTrips.begin(); it != newTrips.end(); it++) {
elements.push_back(&(*it));
}
elementSize = elements.size();
print_line(outDir, logFile, string_format("Enumerated %d potential %d-trips.", elementSize, k));
print_ram(outDir, string_format("%d_after_potential_trip_enumeration_%d", now_time, k));
int noVeh = 0;
int j = 0;
#pragma omp parallel for default(none) private(j) shared(noVeh, bAltMethod, prevInclusions, newTrips, elementSize, elements, requests, k, thisSizeCounter, vehConnex, rvGraph, treeCost, adjustedTripIdxes)
for (j = 0; j < elementSize; j++) {
if (!bFullyConnectedVeh && !(bSparseTwo && k == 2) && !bAltMethod) {
bool bVehicleIncludes = false;
for (auto itVeh = vehConnex.begin(); itVeh != vehConnex.end(); ++itVeh) {
bool bMatch = true;
for (auto itr = elements[j]->second.second.begin(); itr != elements[j]->second.second.end(); ++itr) {
if (prevInclusions[itVeh->second].second.find(*itr) == prevInclusions[itVeh->second].second.end()) {
bMatch = false;
break;
}
}
if (bMatch == true) {
bVehicleIncludes = true;
break;
}
}
if (bVehicleIncludes == false) {
#pragma omp atomic
noVeh++;
continue;
}
}
vector<Request> copiedRequests;
for (auto itr = elements[j]->first.begin(); itr != elements[j]->first.end(); itr++) {
copiedRequests.push_back(requests[*itr]);
}
Request* reqs[max_trip_size];
for (int i = 0; i < k; i++) {
reqs[i] = &copiedRequests[i];
}
bool pathFound = false;
//NOTE: as of now, start location is irrelevant BUT ONLY BECAUSE time starts at -9999 so delay time is zero
Vehicle virtualCar;
virtualCar.set_location(reqs[0]->start);
TravelHelper th;
if (th.travel(virtualCar, reqs, k, false, true, true) >= 0) {
pathFound = true;
}
//print_line(outDir, logFile, string_format("AnsTravvelled = %f, allPotentialTrips size = %d, elements size = %d, j = %d", th.ansCost, allPotentialTrips[k - 2].size(), elements.size(), j ));
if (pathFound == true) {
int thisSizeIdx = -1;
#pragma omp critical (updateprior1)
{
allPotentialTrips[k - 1].push_back(tripCandidate(elements[j]->first));
thisSizeIdx = thisSizeCounter++;
}
for (auto dependentIter = elements[j]->second.second.begin(); dependentIter != elements[j]->second.second.end(); dependentIter++) {
#pragma omp critical (updateprior2)
allPotentialTrips[k - 2][*dependentIter].dependentTrips.push_back(thisSizeIdx);
}
}
}
print_line(outDir, logFile, string_format("%d elements had no vehicle", noVeh));
vector<pair<const uos, pair<int, uosTBB>>*>().swap(elements);
map_of_uos().swap(newTrips);
allPotentialTrips[k - 1].shrink_to_fit();
std::vector<int> addedTrips(allPotentialTrips[k - 1].size(), 0);
vector<std::pair<int, uos>> theseInclusions;
theseInclusions.reserve(prevInclusions.size());
for (int m = 0; m < prevInclusions.size(); m++) {
theseInclusions.push_back(std::pair<int, uos>(prevInclusions[m].first, uos()));
}
print_line(outDir, logFile, string_format("Build_single_vehicles starting for %d trips and %d vehicles of prev size (%d of this size).", (int)allPotentialTrips[k - 1].size(), (int)prevInclusions.size(), (int)theseInclusions.size()));
build_single_vehicles(requests, vehicles, vehIDToVehIdx, k, adjustedTripIdxes, addedTrips, prevInclusions, theseInclusions);
theseInclusions.swap(prevInclusions);
vector<std::pair<int, uos>>().swap(theseInclusions);
print_line(outDir, logFile, "Build_single_vehicles done.");
print_line(outDir, logFile, "Trips labeled.");
adjustedTripIdxes.clear();
int oldIdx = 0;
int newIdx = 0;
int m = 0;
int sizeBeforeShrinking = allPotentialTrips[k - 1].size();
//When k-trips are invalidated, delete them (reducing # of links for k-1-trips)
for (m = 0; m < sizeBeforeShrinking; m++) {
if (addedTrips[m] == 1) {
adjustedTripIdxes[oldIdx] = newIdx++;
}
oldIdx++;
}
print_line(outDir, logFile, "Adjusted trip idxes created.");
vector<tripCandidate>& toShrink = allPotentialTrips[k - 1];
toShrink.erase(std::remove_if(toShrink.begin(), toShrink.end(),
[&addedTrips, &toShrink](const tripCandidate& o) { return !addedTrips[&o - &*(toShrink.begin())]; }),
toShrink.end());
allPotentialTrips[k - 1].shrink_to_fit();
print_line(outDir, logFile, "allPotentialTrips[k-1] shrunk where no trips were found.");
/* When building 3-trips, want to make a bimap between 2- & 3-trips
* When 3-trips are invalidated, delete them (reducing # of links for 2-trips)
* Then, in anticipation of 4-trips:
* Delete 2-trips with fewer than 2 3-trips
* Delete 3-trips with fewer than 3 2-trips
* Delete 2-trips with fewer than 2 3-trips
* etc.
* When building 4-trips, want to make a bimap between 3- & 4-trips
* When 4-trips are invalidated, delete them (reducing # of links for 3-trips)
* Then, in anticipation of 5-trips:
* Delete 3-trips with fewer than 2 4-trips
* Delete 4-trips with fewer than 3 3-trips
* Delete 3-trips with fewer than 2 4-trips
* etc.
*/
//Erase removed k-trip dependencies from k-1-trips
int temp1 = allPotentialTrips[k - 2].size();
int apt_i = 0;
#pragma omp parallel for default(none) num_threads(omp_get_max_threads()) private(apt_i) shared(noVeh, prevInclusions, newTrips, elementSize, elements, requests, k, thisSizeCounter, vehConnex, rvGraph, treeCost, adjustedTripIdxes)
for (apt_i = 0; apt_i < allPotentialTrips[k - 2].size(); apt_i++) { //
std::vector<int>& theseDependents = allPotentialTrips[k - 2][apt_i].dependentTrips;
theseDependents.erase(std::remove_if(theseDependents.begin(), theseDependents.end(),
[&adjustedTripIdxes](const int& o) { return adjustedTripIdxes.find(o) == adjustedTripIdxes.end(); }),
theseDependents.end());
}
print_line(outDir, logFile, "allPotentialTrips[k-2] orphaned dependencies removed.");
//Remove k-1-trips with fewer than 2 k-trip dependencies
int temp2 = temp1 - allPotentialTrips[k - 2].size();
allPotentialTrips[k - 2].erase(std::remove_if(allPotentialTrips[k - 2].begin(), allPotentialTrips[k - 2].end(),
[](const tripCandidate& o) { return o.dependentTrips.size() < 2; }),
allPotentialTrips[k - 2].end());
int temp3 = temp1 - allPotentialTrips[k - 2].size() - temp2;
print_line(outDir, logFile, string_format("%d-trips: of %d, removed %d with 0 dependents and %d with <2 dependents.", k - 1, temp1, temp2, temp3));
//Remove k-trips with fewer than 3 k-1-trips
map<int, int> reverseDependentCounts;
for (int i = 0; i < allPotentialTrips[k - 2].size(); i++) {
for (int j = 0; j < allPotentialTrips[k - 2][i].dependentTrips.size(); j++) {
reverseDependentCounts[allPotentialTrips[k - 2][i].dependentTrips[j]]++;
}
}
int b4adj = adjustedTripIdxes.size();
auto it = adjustedTripIdxes.begin();
while (it != adjustedTripIdxes.end()) {
auto it2 = reverseDependentCounts.find(it->first);
if (it2 == reverseDependentCounts.end() || it2->second < k) { adjustedTripIdxes.erase(it++); }
else { ++it; };
}
int afteradj = adjustedTripIdxes.size();
print_line(outDir, logFile, string_format("k-trips: of %d, removed %d with <2 antecedents.", b4adj, b4adj - afteradj));
if (k >= 3) {
vector<tripCandidate>().swap(allPotentialTrips[k - 3]);
allPotentialTrips[k - 3].clear();
allPotentialTrips[k - 3].shrink_to_fit();
}
lastSizeSize = allPotentialTrips[k - 1].size();
vehConnex.clear();
auto itPrev = prevInclusions.begin();
int idx = 0;
int totalConnex = 0;
while (itPrev != prevInclusions.end()) {
for (auto it2 = itPrev->second.begin(); it2 != itPrev->second.end(); )
{
if (adjustedTripIdxes.find(*it2) != adjustedTripIdxes.end()) { ++it2; }
else { it2 = itPrev->second.erase(it2); }
}
int connex = itPrev->second.size();
if (connex == 0) {
itPrev = prevInclusions.erase(itPrev);
}
else {
if (connex > k) {
vehConnex.insert(make_pair(-connex, idx));
totalConnex += connex;
}
idx++;
++itPrev;
}
}
lastSizeMaxConnectedness = vehConnex.size() > 0 ? (-1.0 * (vehConnex.begin()->first)) / (1.0 * lastSizeSize) : 0.0;
lastSizeAvgConnectedness = vehConnex.size() > 0 ? 1.0 * totalConnex / (1.0 * vehConnex.size()) / (1.0 * lastSizeSize) : 0.0;
std::chrono::duration<double> elapsed_seconds = std::chrono::system_clock::now() - startOfSizeK;
print_line(outDir, logFile, string_format("Potential %d-trips built (%f seconds, %d/%d met clique reqmt, %d after ideal vehicle, %d after single vehicles).",
k,
elapsed_seconds.count(),
elementSize,
newTripsSize,
sizeBeforeShrinking,
lastSizeSize
));
}
}
void RTVGraph::build_single_vehicles(vector<Request>& requests, vector<Vehicle>& vehicles,
const map<int, int>& vehIDToVehIdx, int tripSize,
const unordered_map<int, int>& adjustedTripIdxes, std::vector<int>& addedTrips,
const std::vector<std::pair<int, uos>>& prevInclusions, std::vector<std::pair<int, uos>>& theseInclusions) {
if (tripSize < 2) return;
if (allPotentialTrips.size() < tripSize) return;;
const std::vector<tripCandidate>& lastSizeVec = allPotentialTrips[tripSize - 2];
const std::vector<tripCandidate>& thisSizeVec = allPotentialTrips[tripSize - 1];
if (lastSizeVec.size() < tripSize || thisSizeVec.size() == 0) return;
std::vector<std::tuple<int,int,int>> validTripCosts;
int m = 0;
#pragma omp declare reduction (merge : std::vector<std::tuple<int,int,int>> : omp_out.insert(omp_out.end(), omp_in.begin(), omp_in.end()))
#pragma omp parallel for default(none) num_threads(omp_get_max_threads()) private(m) schedule(guided) shared(addedTrips, adjustedTripIdxes, requests, vehicles, vehIDToVehIdx, tripSize, treeCost, lastSizeVec, thisSizeVec, prevInclusions, theseInclusions) reduction(merge: validTripCosts)
for (m = 0; m < prevInclusions.size(); m++) {
int vId = prevInclusions[m].first; //index into vehicles, not RTV vehicle indices
const uos& carPrev = prevInclusions[m].second;
if (carPrev.size() < tripSize) continue;
int vIdx = -1;
auto itVeh = vehIDToVehIdx.find(vId);
if (itVeh != vehIDToVehIdx.end()) {
vIdx = itVeh->second;
}
else {
continue;
}
std::vector<std::tuple<int, int, int>> theseValidTripCosts;
theseValidTripCosts.reserve(carPrev.size() * (carPrev.size() - 1) / 2);
if (carPrev.size() == lastSizeVec.size()) {
for (int i = 0; i < thisSizeVec.size(); i++) {
vector<Request> copiedRequests;
copiedRequests.reserve(thisSizeVec[i].requests.size());
for (auto itr = thisSizeVec[i].requests.begin(); itr != thisSizeVec[i].requests.end(); ++itr) {
copiedRequests.push_back(requests[*itr]);
}
Request* reqs[max_trip_size];
for (int j = 0; j < tripSize; j++) {
reqs[j] = &copiedRequests[j];
}
Vehicle vCopy = vehicles[vId];
TravelHelper th;
int cost = th.travel(vCopy, reqs, tripSize, false);
if (cost >= 0) theseValidTripCosts.push_back(std::tuple<int,int,int>(cost, m, i));
}
}
else {
int sparseComplexity = carPrev.size() * (carPrev.size() - 1);
int denseComplexity = thisSizeVec.size() * tripSize;
unordered_map<int, int> carThis;
if (tripSize == 2) {
for (auto it = carPrev.begin(); it != carPrev.end(); ++it) {
int idx = *it;
for (int i = 0; i < lastSizeVec[idx].dependentTrips.size(); i++) {
carThis[lastSizeVec[idx].dependentTrips[i]]++;
}
}
}
else {
auto itEnd = adjustedTripIdxes.end();
for (auto it = carPrev.begin(); it != carPrev.end(); ++it) {
auto itr = adjustedTripIdxes.find(*it);
if (itr == itEnd) continue;
int idx = itr->second;
for (int i = 0; i < lastSizeVec[idx].dependentTrips.size(); i++) {
carThis[lastSizeVec[idx].dependentTrips[i]]++;
}
}
}
for (auto it = carThis.begin(); it != carThis.end(); ++it) {
if (it->second != tripSize) continue;
vector<Request> copiedRequests;
copiedRequests.reserve(thisSizeVec[it->first].requests.size());
for (auto itr = thisSizeVec[it->first].requests.begin(); itr != thisSizeVec[it->first].requests.end(); ++itr) {
copiedRequests.push_back(requests[*itr]);
}
Request* reqs[max_trip_size];
for (int j = 0; j < tripSize; j++) {
reqs[j] = &copiedRequests[j];
}
Vehicle vCopy = vehicles[vId];
TravelHelper th;
int cost = th.travel(vCopy, reqs, tripSize, false);
if (cost >= 0) theseValidTripCosts.push_back(std::tuple<int, int, int>(cost, m, it->first));
}
}
#pragma omp critical(pushingToVec)
validTripCosts.insert(validTripCosts.end(), theseValidTripCosts.begin(), theseValidTripCosts.end());
}
validTripCosts.shrink_to_fit();
std::sort(validTripCosts.begin(), validTripCosts.end());
std::vector<int> vAssignments(prevInclusions.size(), -1); //indexed as m above
//std::vector<int> tAssignments(thisSizeVec.size(), -1); //indexed as i above
std::vector<int> rAssignments(requests.size(), -1); //
std::vector<int> vAssignmentCounts(prevInclusions.size(), 0);
//std::vector<int> tAssignmentCounts(thisSizeVec.size(), 0);
std::vector<int> rAssignmentCounts(requests.size(), 0);
for (int i = 0; i < validTripCosts.size(); i++) {
int vIdx = std::get<1>(validTripCosts[i]);
int tIdx = std::get<2>(validTripCosts[i]);
const uos& tripReqIdxes = thisSizeVec[tIdx].requests;
bool bAllReqCovered = true;
bool bAnyReqAssigned = false;
for (auto it = tripReqIdxes.begin(); it != tripReqIdxes.end(); ++it) {
if (rAssignmentCounts[*it] < max_v_per_req) bAllReqCovered = false;
if (rAssignments[*it] != -1) bAnyReqAssigned = true;
}
if (vAssignmentCounts[vIdx] >= min_req_per_v && bAllReqCovered && (-1 != vAssignments[vIdx] || bAnyReqAssigned)) {
std::get<0>(validTripCosts[i]) = -1;
continue;
}
vAssignmentCounts[vIdx]++;
for (auto it = tripReqIdxes.begin(); it != tripReqIdxes.end(); ++it) {
rAssignmentCounts[*it]++;
}
if (-1 == vAssignments[vIdx] && !bAnyReqAssigned) {
vAssignments[vIdx] = tIdx;
for (auto it = tripReqIdxes.begin(); it != tripReqIdxes.end(); ++it) {
rAssignments[*it] = vIdx;
}
}
}
std::vector<int>().swap(vAssignmentCounts);
//std::vector<int>().swap(tAssignmentCounts);
//std::vector<int>().swap(rAssignmentCounts);
std::vector<int>().swap(vAssignments);
std::vector<int>().swap(rAssignments);
//std::vector<int>().swap(tAssignments);
validTripCosts.erase(std::remove_if(validTripCosts.begin(), validTripCosts.end(),
[](const std::tuple<int, int, int>& o) { return std::get<0>(o) == -1; }),
validTripCosts.end());
std::sort(validTripCosts.begin(), validTripCosts.end(),
[](const std::tuple<int, int, int>& a, const std::tuple<int, int, int>& b) {
return std::get<2>(a) < std::get<2>(b) || (std::get<2>(a) == std::get<2>(b) && std::get<1>(a) < std::get<1>(b));
}); //orders ascending by trip then vehicle
validTripCosts.shrink_to_fit();
int prevI = -1;
int prevM = -1;
int vIdx = -1;
int tIdx = -1;
for (int j = 0; j < validTripCosts.size(); j++) {
int cost = std::get<0>(validTripCosts[j]);
int m = std::get<1>(validTripCosts[j]); //vehicle
int i = std::get<2>(validTripCosts[j]); //trip
if (i != prevI) {
tIdx = getTIdx(thisSizeVec[i].requests);
prevI = i;
}
if (m != prevM){
prevM = m;
auto itVeh = vehIDToVehIdx.find(prevInclusions[m].first);
if (itVeh == vehIDToVehIdx.end()) { vIdx = -1; continue; }
else { vIdx = itVeh->second; };
}
if (vIdx == -1 || tIdx == -1 || cost == -1) continue;
addedTrips[i] = 1;
theseInclusions[m].second.insert(i);
std::get<1>(validTripCosts[j]) = vIdx;
std::get<2>(validTripCosts[j]) = tIdx;
}
std::string vehTripsFile = outDir + "Misc/Trips/trips_valid_" + to_string(tripSize) + ".hps";
std::ofstream out_file(vehTripsFile, std::ofstream::binary | std::ios_base::app);
hps::to_stream(validTripCosts, out_file);
out_file.close();
std::vector<std::tuple<int, int, int>>().swap(validTripCosts);
}
void RTVGraph::serialize_current_combos() {
{
std::string tvCombosFile = outDir + "Misc/Trips/tvCombos.hps";
std::ofstream out_tv(tvCombosFile, std::ofstream::binary | std::ios_base::app);
hps::to_stream(tIdx_vCostIdxes, out_tv);
out_tv.close();
map<TIdxComparable, vector<pair<int, pair<int, int>> > >().swap(tIdx_vCostIdxes);
}
{
std::string vtCombosFile = outDir + "Misc/Trips/vtCombos.hps";
std::ofstream out_vt(vtCombosFile, std::ofstream::binary | std::ios_base::app);
hps::to_stream(vIdx_tIdxes, out_vt);
out_vt.close();
vector<vector<pair<int, pair<int, int>> > >().swap(vIdx_tIdxes);
}
}
void RTVGraph::deserialize_current_combos() {
{
std::string tvCombosFile = outDir + "Misc/Trips/tvCombos.hps";
if (std::filesystem::exists(tvCombosFile)) {
std::ifstream in_tv(tvCombosFile, std::ofstream::binary);
tIdx_vCostIdxes = hps::from_stream <std::map<TIdxComparable, vector<pair<int, pair<int, int>>>>>(in_tv);
}
}
{
std::string vtCombosFile = outDir + "Misc/Trips/vtCombos.hps";
if (std::filesystem::exists(vtCombosFile)) {
std::ifstream in_vt(vtCombosFile, std::ofstream::binary);
vIdx_tIdxes = hps::from_stream<std::vector<std::vector<std::pair<int, std::pair<int, int>>>>>(in_vt);
}
}
}
void RTVGraph::deserialize_valid_trips() {
deserialize_current_combos();
std::string vehTripsPath = outDir + "Misc/Trips";
for (int tripSize = 2; tripSize < max_trip_size; tripSize++) {
std::string vehTripsFile = vehTripsPath + "/trips_valid_" + to_string(tripSize) + ".hps";
// #pragma omp parallel for default(none) private(thread) shared(tripSize, treeCost)
if (!std::filesystem::exists(vehTripsFile)) continue;
std::ifstream in_file(vehTripsFile, std::ofstream::binary);
auto parsed = hps::from_stream<std::vector<std::tuple<int,int,int>>>(in_file);
if (parsed.size() == 0) break;
for (int i = 0; i < parsed.size(); i++) {
//cost, v, t -> t, v, cost
add_edge_trip_vehicle(std::get<2>(parsed[i]), std::get<1>(parsed[i]), std::get<0>(parsed[i]));
}
}
std::filesystem::remove_all(vehTripsPath);
std::filesystem::create_directories(vehTripsPath + "/");
for (auto it = trip_tIdx.begin(); it != trip_tIdx.end(); ++it) {
for (auto it2 = it->first.begin(); it2 != it->first.end(); ++it2) {
rId_tIdxes[*it2].insert(it->second);
}
}
}
void RTVGraph::greedy_assign_same_trip_size(vector<vector<pair<int, pair<int, int>>>::iterator>& edgeIters, vector<vector<pair<int, pair<int, int>>>::iterator>& edgeEnds, vector<int>& tIdxes, set<int>& assignedRIds, set<int>& assignedVIdxes, GRBVar** epsilon, std::map<int, map<int, int>>& lookupRtoT, unordered_map<int, int>& validTripReverseLookup) {
int numEdgeVectors = edgeIters.size();
int numNotEnded = numEdgeVectors;
while (numNotEnded > 0) {
// get minimal cost edge
int minCost = 0x7fffffff, argMin = -1;
int i = 0;
//#pragma omp parallel for private(i) shared(minCost, argMin)
for (i = 0; i < numEdgeVectors; i++) {
if (edgeIters[i] != edgeEnds[i]) {
int tmpCost = edgeIters[i]->first;
//#pragma omp critical(edgevecloop)
//{
if (tmpCost < minCost)
minCost = tmpCost;
argMin = i;
//}
}
}
int tIdx = tIdxes[argMin];
int vIdx = edgeIters[argMin]->second.second;
// check if the edge can be assigned
bool allReqsUnassigned = true;
for (auto iterRId = trips[tIdx].begin(); iterRId != trips[tIdx].end(); ++iterRId) {
if (assignedRIds.find(*iterRId) != assignedRIds.end()) {
allReqsUnassigned = false;
break;
}
}
if (allReqsUnassigned && assignedVIdxes.find(vIdx) == assignedVIdxes.end()) {
// assign the edge
try {
int vIdxIntoCosts = lookupRtoT[vIdx][validTripReverseLookup[tIdx]];
epsilon[validTripReverseLookup[tIdx]][vIdxIntoCosts].set(GRB_DoubleAttr_Start, 1.0);
for (auto iterRId = trips[tIdx].begin(); iterRId != trips[tIdx].end(); ++iterRId) {
assignedRIds.insert(*iterRId);
}
assignedVIdxes.insert(vIdx);
}
catch (GRBException& e) {
print_line(outDir, logFile, string_format("Gurobi exception code: %d.", e.getErrorCode()));
print_line(outDir, logFile, "Gurobi exception message: " + e.getMessage());
}
}
// move the argMin-th iterator
edgeIters[argMin]++;
if (edgeIters[argMin] == edgeEnds[argMin]) {
numNotEnded--;
}
}
}
RTVGraph::RTVGraph(RVGraph* rvGraph, vector<Vehicle>& vehicles, vector<Request>& requests) {
gen1 = std::mt19937(rd());
gen2 = std::mt19937(rd());
distribOfCars = std::uniform_int_distribution<>(1, 1000000);
distribOfTrips = std::uniform_int_distribution<>(1, 1000000);
vector<vector<tripCandidate>>().swap(allPotentialTrips);
allPotentialTrips.push_back(vector<tripCandidate>{});
numRequests = requests.size();
numTrips = 0;
numVehicles = 0;
auto thisTime = std::chrono::system_clock::now();
build_potential_trips(rvGraph, requests, vehicles);
std::chrono::duration<double> elapsed_seconds = (std::chrono::system_clock::now() - thisTime);
print_line(outDir, logFile, string_format("Potential trips build and serialization time = %f.", elapsed_seconds.count()));
thisTime = std::chrono::system_clock::now();
deserialize_valid_trips();
elapsed_seconds = (std::chrono::system_clock::now() - thisTime);
print_line(outDir, logFile, string_format("Potential trips deserialization time = %f.", elapsed_seconds.count()));
thisTime = std::chrono::system_clock::now();
/* int m;
const int vehsize = vehicles.size();
print_line(outDir,logFile,std::string("Starting parallel section."));
#pragma omp parallel for default(none) private(m) shared(vehicles, rvGraph, requests, vehIDToVehIdx, allPotentialTrips, treeCost)
for (m=0; m < vehsize; m++) {
if (rvGraph->has_vehicle(m)) {
build_single_vehicle(m, vehIDToVehIdx[m], vehicles, rvGraph, requests);
}
} */
vector<vector<tripCandidate>>().swap(allPotentialTrips);
elapsed_seconds = (std::chrono::system_clock::now() - thisTime);
print_line(outDir, logFile, string_format("Vehicle-specific RTV graph build time = %f.", elapsed_seconds.count()));
}
void RTVGraph::update_unserved_from_rebalancing(vector<Request>& unserved, uos& newlyServed) {
std::vector<Request> stillUnserved;
if (unserved.size() - newlyServed.size() > 0) stillUnserved.reserve(unserved.size() - newlyServed.size());
for (int i = 0; i < unserved.size(); i++) {
if (newlyServed.find(i) == newlyServed.end()) {
stillUnserved.push_back(unserved[i]);
}
}
stillUnserved.swap(unserved);
}
void RTVGraph::rebalance_for_pruning_fix(GRBEnv* env, vector<Vehicle>& vehicles, vector<Request>& unserved) {
vector<int> idleVIds;
uos newlyServed;
for (int i = 0; i < vehicles.size(); i++) {
if (vehicles[i].get_num_passengers()<max_capacity && !vehicles[i].offline && vehicles[i].getAvailableSince() < now_time + time_step) idleVIds.push_back(i);
}
int idleCnt = (int)idleVIds.size();
int unservedCnt = (int)unserved.size();
std::vector<int> rAssignments(unserved.size(), -1);
std::vector<int> vAssignments(idleVIds.size(), -1);
std::vector<int> rAssignmentCounts(unserved.size(), 0);
std::vector<int> vAssignmentCounts(idleVIds.size(), 0);
std::vector<std::tuple<int, int, int>> allCosts(idleCnt * unservedCnt, std::make_tuple<int, int, int>(-1, -1, -1));
int i = 0;
#pragma omp parallel for default(none) num_threads(omp_get_max_threads()) private(i) shared(unserved, vehicles, idleVIds, allCosts, idleCnt, unservedCnt)
for (i = 0; i < idleCnt; i++) {
Vehicle vCopy = vehicles[idleVIds[i]];
for (int j = 0; j < unservedCnt; j++) {
Request copied = unserved[j];
TravelHelper th;
Request* reqs[1];
reqs[0] = &copied;
bool bConsiderReqWait = true;
int cost = th.travel(vCopy, reqs, 1, false, bConsiderReqWait);
if (cost != -1) {
int idx = i * unservedCnt + j;
std::get<0>(allCosts[idx]) = cost;
std::get<1>(allCosts[idx]) = i;
std::get<2>(allCosts[idx]) = j;
}
else {
bConsiderReqWait = false;
int cost = th.travel(vCopy, reqs, 1, false, bConsiderReqWait);
if (cost != -1) {
int idx = i * unservedCnt + j;
std::get<0>(allCosts[idx]) = cost;
std::get<1>(allCosts[idx]) = i;
std::get<2>(allCosts[idx]) = j;
}
}
}
}
allCosts.erase(std::remove_if(allCosts.begin(), allCosts.end(),
[](const std::tuple<int, int, int>& o) { return std::get<0>(o) == -1; }),
allCosts.end());
allCosts.shrink_to_fit();
std::sort(allCosts.begin(), allCosts.end());
int assignableCnt = 0;
for (int i = 0; i < allCosts.size(); i++) {
int vIdx = std::get<1>(allCosts[i]);
int rIdx = std::get<2>(allCosts[i]);
if (vAssignmentCounts[vIdx] >= min_req_per_v && rAssignmentCounts[rIdx] >= max_v_per_req && (-1 != vAssignments[vIdx] || -1 != rAssignments[rIdx])) {
std::get<0>(allCosts[i]) = -1;
continue;
}
vAssignmentCounts[vIdx]++;
rAssignmentCounts[rIdx]++;
if (-1 == vAssignments[vIdx] && -1 == rAssignments[rIdx]) {
vAssignments[vIdx] = rIdx;
rAssignments[rIdx] = vIdx;
assignableCnt++;
}
}
vector<int>().swap(vAssignmentCounts);
vector<int>().swap(rAssignmentCounts);
allCosts.erase(std::remove_if(allCosts.begin(), allCosts.end(),
[](const std::tuple<int, int, int>& o) { return std::get<0>(o) == -1; }),
allCosts.end());
std::sort(allCosts.begin(), allCosts.end(),
[](const std::tuple<int, int, int>& a, const std::tuple<int, int, int>& b) {
return std::get<1>(a) < std::get<1>(b) || (std::get<1>(a) == std::get<1>(b) && std::get<2>(a) < std::get<2>(b));
}); //orders ascending by vehicle then request
print_line(outDir, logFile, string_format("Rebalancing 1: shrunk from %d to %d combos.", idleCnt * unservedCnt, allCosts.size()));
if (allCosts.size() == 0) return;
int idleToDelete = idleCnt;
GRBLinExpr objective = 0;
GRBLinExpr totalEdgesCnt = 0;
GRBLinExpr* rEdgesCnt = new GRBLinExpr[unservedCnt];
GRBLinExpr* vEdgesCnt = new GRBLinExpr[idleCnt];
GRBModel model = GRBModel(*env);
GRBVar* y = model.addVars(allCosts.size(), GRB_BINARY); \
try {
for (int i = 0; i < unservedCnt; i++) { rEdgesCnt[i] = 0; }
for (int i = 0; i < idleCnt; i++) { vEdgesCnt[i] = 0; }
for (int i = 0; i < allCosts.size(); i++) {
//Order: cost, vIdx, rIdx
int cost = std::get<0>(allCosts[i]);
int vIdx = std::get<1>(allCosts[i]);
int rIdx = std::get<2>(allCosts[i]);
vEdgesCnt[vIdx] += y[i];
rEdgesCnt[rIdx] += y[i];
totalEdgesCnt += y[i];
objective += y[i] * cost;
if (rAssignments[rIdx] == vIdx) { y[i].set(GRB_DoubleAttr_Start, 1.0); }
else { y[i].set(GRB_DoubleAttr_Start, 0.0); }
}
for (int i = 0; i < unservedCnt; i++) {
model.addConstr(rEdgesCnt[i] <= 1.0 + minimal);
}
for (int i = 0; i < idleCnt; i++) {
model.addConstr(vEdgesCnt[i] <= 1.0 + minimal);
}
model.addConstr(totalEdgesCnt == assignableCnt);
model.setObjective(objective, GRB_MINIMIZE);
model.set("Threads", to_string(omp_get_max_threads() - 2));
model.set("Method", "1");
model.set("TimeLimit", "300.0");
model.set("MIPGap", "0.01");
model.set("NodeFileStart", "0.5");
std::string grbLogName = outDir + "GurobiLogs/" + "rebalance1_" + std::to_string(now_time);
model.set("LogFile", grbLogName + ".txt");
model.set("ResultFile", grbLogName + ".ilp");
model.optimize();
std::string part1 = std::to_string(model.get(GRB_IntAttr_Status));
std::string part2 = std::to_string((int)std::round(model.get(GRB_DoubleAttr_Runtime)));
for (int i = 0; i < allCosts.size(); i++) {
double val = y[i].get(GRB_DoubleAttr_X);
if (val > 1.0 + minimal || val < 1.0 - minimal) continue;
int vIdx = idleVIds[std::get<1>(allCosts[i])];
int rIdx = std::get<2>(allCosts[i]);
Request* reqs[1];
reqs[0] = &unserved[rIdx];
TravelHelper th;
if (-1 == th.travel(vehicles[vIdx], reqs, 1, true, true)) {
if (-1 == th.travel(vehicles[vIdx], reqs, 1, true, false))
continue;
}
newlyServed.emplace(rIdx);
for (auto it = vehicles[vIdx].passengers.begin(); it != vehicles[vIdx].passengers.end(); ++it) {
if (it->unique != reqs[0]->unique) continue;
int delay = it->scheduledOffTime - it->expectedOffTime;
int wait = it->scheduledOnTime - it->reqTime;
if (delay > it->allowedDelay || wait > it->allowedWait) {
it->allowedDelay = delay;
it->allowedWait = wait;
}
break;
}
}
}
catch (GRBException& e) {
print_line(outDir, logFile, string_format("Gurobi exception code in rebalancing 1: %d.", e.getErrorCode()));
print_line(outDir, logFile, "Gurobi exception message: " + e.getMessage());
}
delete[] rEdgesCnt;
delete[] vEdgesCnt;
delete[] y;
update_unserved_from_rebalancing(unserved, newlyServed);
}
void RTVGraph::rebalance_for_finishing_cars(GRBEnv* env, vector<Vehicle>& vehicles, vector<Request>& unserved) {
std::vector<int> idleVIds;
uos newlyServed;
//Loosen definition of "idle" to those dropping off a passenger before the next time window
idleVIds.reserve(vehicles.size()); //this is reserving too much, but that's OK
for (int i = 0; i < vehicles.size(); i++) {