-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathLCPtoLP.cpp
1565 lines (1477 loc) · 56.7 KB
/
LCPtoLP.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 "lcptolp.h"
#include <algorithm>
#include <armadillo>
#include <boost/log/trivial.hpp>
#include <boost/program_options.hpp>
#include <cmath>
#include <gurobi_c++.h>
#include <iostream>
#include <memory>
#include <random>
#include <set>
#include <string>
using namespace std;
using namespace Utils;
bool operator==(vector<short int> Fix1, vector<short int> Fix2)
/**
* @brief Checks if two vector<int> are of same size and hold same values in the
* same order
* @warning Might be deprecated, as it pollutes global namespaces
* @returns @p true if Fix1 and Fix2 have the same elements else @p false
*/
{
if (Fix1.size() != Fix2.size())
return false;
for (unsigned int i = 0; i < Fix1.size(); i++) {
if (Fix1.at(i) != Fix2.at(i))
return false;
}
return true;
}
bool operator<(vector<short int> Fix1, vector<short int> Fix2)
/**
* @details \b GrandParent:
* Either the same value as the grand child, or has 0 in that location
*
* \b Grandchild:
* Same val as grand parent in every location, except any val allowed, if
* grandparent is 0
* @warning Might be deprecated, as it pollutes global namespaces
* @returns @p true if Fix1 is (grand) child of Fix2
*/
{
if (Fix1.size() != Fix2.size())
return false;
for (unsigned int i = 0; i < Fix1.size(); i++) {
if (Fix1.at(i) != Fix2.at(i) && Fix1.at(i) * Fix2.at(i) != 0) {
return false; // Fix1 is not a child of Fix2
}
}
return true; // Fix1 is a child of Fix2
}
bool operator>(vector<int> Fix1, vector<int> Fix2) { return (Fix2 < Fix1); }
void Game::LCP::defConst(GRBEnv *env)
/**
* @brief Assign default values to LCP attributes
* @details Internal member that can be called from multiple constructors
* to assign default values to some attributes of the class.
*/
{
this->Ai = unique_ptr<spmat_Vec>(new spmat_Vec());
this->bi = unique_ptr<vec_Vec>(new vec_Vec());
this->RlxdModel.set(GRB_IntParam_OutputFlag, VERBOSE);
this->env = env;
this->nR = this->M.n_rows;
this->nC = this->M.n_cols;
}
Game::LCP::LCP(
GRBEnv *env, ///< Gurobi environment required
arma::sp_mat M, ///< @p M in @f$Mx+q@f$
arma::vec q, ///< @p q in @f$Mx+q@f$
perps Compl, ///< Pairing equations and variables for complementarity
arma::sp_mat A, ///< Any equations without a complemntarity variable
arma::vec b ///< RHS of equations without complementarity variables
)
: M{M}, q{q}, _A{A}, _b{b}, RlxdModel(*env)
/// @brief Constructor with M, q, compl pairs
{
defConst(env);
this->Compl = perps(Compl);
std::sort(
this->Compl.begin(), this->Compl.end(),
[](pair<unsigned int, unsigned int> a,
pair<unsigned int, unsigned int> b) { return a.first < b.first; });
for (auto p : this->Compl)
if (p.first != p.second) {
this->LeadStart = p.first;
this->LeadEnd = p.second - 1;
this->nLeader = this->LeadEnd - this->LeadStart + 1;
this->nLeader = this->nLeader > 0 ? this->nLeader : 0;
break;
}
this->initializeNotProcessed();
}
Game::LCP::LCP(
GRBEnv *env, ///< Gurobi environment required
arma::sp_mat M, ///< @p M in @f$Mx+q@f$
arma::vec q, ///< @p q in @f$Mx+q@f$
unsigned int LeadStart, ///< Position where variables which are not
///< complementary to any equation starts
unsigned LeadEnd, ///< Position where variables which are not complementary
///< to any equation ends
arma::sp_mat A, ///< Any equations without a complemntarity variable
arma::vec b ///< RHS of equations without complementarity variables
)
: M{M}, q{q}, _A{A}, _b{b}, RlxdModel(*env)
/// @brief Constructor with M,q,leader posn
/**
* @warning This might be deprecated to support LCP functioning without sticking
* to the output format of NashGame
*/
{
defConst(env);
this->LeadStart = LeadStart;
this->LeadEnd = LeadEnd;
this->nLeader = this->LeadEnd - this->LeadStart + 1;
this->nLeader = this->nLeader > 0 ? this->nLeader : 0;
for (unsigned int i = 0; i < M.n_rows; i++) {
unsigned int count = i < LeadStart ? i : i + nLeader;
this->Compl.push_back({i, count});
}
std::sort(
this->Compl.begin(), this->Compl.end(),
[](pair<unsigned int, unsigned int> a,
pair<unsigned int, unsigned int> b) { return a.first < b.first; });
this->initializeNotProcessed();
}
Game::LCP::LCP(GRBEnv *env, const NashGame &N)
: RlxdModel(*env)
/**
* @brief Constructer given a NashGame
* @details Given a NashGame, computes the KKT of the lower levels, and
*makes the appropriate LCP object.
*
* This constructor is the most suited for highlevel usage.
* @note Most preferred constructor for user interface.
*/
{
arma::sp_mat M;
arma::vec q;
perps Compl;
N.FormulateLCP(M, q, Compl);
// LCP(env, M, q, Compl, N.RewriteLeadCons(), N.getMCLeadRHS());
this->M = M;
this->q = q;
this->_A = N.RewriteLeadCons();
this->_b = N.getMCLeadRHS();
defConst(env);
this->Compl = perps(Compl);
sort(this->Compl.begin(), this->Compl.end(),
[](pair<unsigned int, unsigned int> a,
pair<unsigned int, unsigned int> b) { return a.first < b.first; });
// Delete no more!
for (auto p : this->Compl) {
if (p.first != p.second) {
this->LeadStart = p.first;
this->LeadEnd = p.second - 1;
this->nLeader = this->LeadEnd - this->LeadStart + 1;
this->nLeader = this->nLeader > 0 ? this->nLeader : 0;
break;
}
}
this->initializeNotProcessed();
}
Game::LCP::~LCP()
/** @brief Destructor of LCP */
/** LCP object owns the pointers to definitions of its polyhedra that it owns
It has to be deleted and freed. */
{}
void Game::LCP::makeRelaxed()
/** @brief Makes a Gurobi object that relaxes complementarity constraints in an
LCP */
/** @details A Gurobi object is stored in the LCP object, that has all
* complementarity constraints removed. A copy of this object is used by other
* member functions */
{
try {
if (this->madeRlxdModel)
return;
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::makeRelaxed: Creating a model with : " << nR
<< " variables and " << nC << " constraints";
GRBVar x[nC], z[nR];
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::makeRelaxed: Initializing variables";
for (unsigned int i = 0; i < nC; i++)
x[i] = RlxdModel.addVar(0, GRB_INFINITY, 1, GRB_CONTINUOUS,
"x_" + to_string(i));
for (unsigned int i = 0; i < nR; i++)
z[i] = RlxdModel.addVar(0, GRB_INFINITY, 1, GRB_CONTINUOUS,
"z_" + to_string(i));
BOOST_LOG_TRIVIAL(trace) << "Game::LCP::makeRelaxed: Added variables";
for (unsigned int i = 0; i < nR; i++) {
GRBLinExpr expr = 0;
for (auto v = M.begin_row(i); v != M.end_row(i); ++v)
expr += (*v) * x[v.col()];
expr += q(i);
RlxdModel.addConstr(expr, GRB_EQUAL, z[i], "z_" + to_string(i) + "_def");
}
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::makeRelaxed: Added equation definitions";
// If @f$Ax \leq b@f$ constraints are there, they should be included too!
if (this->_A.n_nonzero != 0 && this->_b.n_rows != 0) {
if (_A.n_cols != nC || _A.n_rows != _b.n_rows) {
BOOST_LOG_TRIVIAL(trace) << "(" << _A.n_rows << "," << _A.n_cols
<< ")\t" << _b.n_rows << " " << nC;
throw string("Game::LCP::makeRelaxed: A and b are incompatible! Thrown "
"from makeRelaxed()");
}
for (unsigned int i = 0; i < _A.n_rows; i++) {
GRBLinExpr expr = 0;
for (auto a = _A.begin_row(i); a != _A.end_row(i); ++a)
expr += (*a) * x[a.col()];
RlxdModel.addConstr(expr, GRB_LESS_EQUAL, _b(i),
"commonCons_" + to_string(i));
}
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::makeRelaxed: Added common constraints";
}
RlxdModel.update();
this->madeRlxdModel = true;
} catch (const char *e) {
cerr << "Error in Game::LCP::makeRelaxed: " << e << '\n';
throw;
} catch (string e) {
cerr << "String: Error in Game::LCP::makeRelaxed: " << e << '\n';
throw;
} catch (exception &e) {
cerr << "Exception: Error in Game::LCP::makeRelaxed: " << e.what() << '\n';
throw;
} catch (GRBException &e) {
cerr << "GRBException: Error in Game::LCP::makeRelaxed: "
<< e.getErrorCode() << "; " << e.getMessage() << '\n';
throw;
}
}
unique_ptr<GRBModel> Game::LCP::LCP_Polyhed_fixed(
vector<unsigned int>
FixEq, ///< If index is present, equality imposed on that variable
vector<unsigned int>
FixVar ///< If index is present, equality imposed on that equation
)
/**
* The returned model has constraints
* corresponding to the indices in FixEq set to equality
* and variables corresponding to the indices
* present in FixVar set to equality (=0)
* @note This model returned could either be a relaxation or a restriction or
* neither. If every index is present in at least one of the two vectors --- @p
* FixEq or @p FixVar --- then it is a restriction.
* @note <tt>LCP::LCP_Polyhed_fixed({},{})</tt> is equivalent to accessing
* LCP::RlxdModel
* @warning The FixEq and FixVar variables are used under a different convention
* here!
* @warning Note that the model returned by this function has to be explicitly
* deleted using the delete operator.
* @returns unique pointer to a GRBModel
*/
{
makeRelaxed();
unique_ptr<GRBModel> model(new GRBModel(this->RlxdModel));
for (auto i : FixEq) {
if (i >= nR)
throw "Game::LCP::LCP_Polyhed_fixed: Element in FixEq is greater than nC";
model->getVarByName("z_" + to_string(i)).set(GRB_DoubleAttr_UB, 0);
}
for (auto i : FixVar) {
if (i >= nC)
throw "Game::LCP::LCP_Polyhed_fixed: Element in FixEq is greater than nC";
model->getVarByName("z_" + to_string(i)).set(GRB_DoubleAttr_UB, 0);
}
return model;
}
unique_ptr<GRBModel> Game::LCP::LCP_Polyhed_fixed(
arma::Col<int> FixEq, ///< If non zero, equality imposed on variable
arma::Col<int> FixVar ///< If non zero, equality imposed on equation
)
/**
* Returs a model created from a given model
* The returned model has constraints
* corresponding to the non-zero elements of FixEq set to equality
* and variables corresponding to the non-zero
* elements of FixVar set to equality (=0)
* @note This model returned could either be a relaxation or a restriction or
* neither. If FixEq + FixVar is at least 1 (element-wise), then it is a
* restriction.
* @note <tt>LCP::LCP_Polyhed_fixed({0,...,0},{0,...,0})</tt> is equivalent to
* accessing LCP::RlxdModel
* @warning Note that the model returned by this function has to be explicitly
* deleted using the delete operator.
* @returns unique pointer to a GRBModel
*/
{
makeRelaxed();
unique_ptr<GRBModel> model{new GRBModel(this->RlxdModel)};
for (unsigned int i = 0; i < nC; i++)
if (FixVar[i])
model->getVarByName("x_" + to_string(i)).set(GRB_DoubleAttr_UB, 0);
for (unsigned int i = 0; i < nR; i++)
if (FixEq[i])
model->getVarByName("z_" + to_string(i)).set(GRB_DoubleAttr_UB, 0);
model->update();
return model;
}
unique_ptr<GRBModel> Game::LCP::LCPasMIP(
vector<short int>
Fixes, ///< For each Variable, +1 fixes the equation to equality and -1
///< fixes the variable to equality. A value of 0 fixes neither.
bool solve ///< Whether the model is to be solved before returned
)
/**
* Uses the big M method to solve the complementarity problem. The variables and
* eqns to be set to equality can be given in Fixes in 0/+1/-1 notation
* @note Returned model is \e always a restriction. For <tt>Fixes =
* {0,...,0}</tt>, the returned model would solve the exact LCP.
* @throws string if <tt> Fixes.size()!= </tt> number of equations (for
* complementarity).
* @warning Note that the model returned by this function has to be explicitly
* deleted using the delete operator.
* @returns unique pointer to a GRBModel
*/
{
if (Fixes.size() != this->nR)
throw string(
"Game::LCP::LCPasMIP: Bad size for Fixes in Game::LCP::LCPasMIP");
vector<unsigned int> FixVar, FixEq;
for (unsigned int i = 0; i < nR; i++) {
if (Fixes[i] == 1)
FixEq.push_back(i);
if (Fixes[i] == -1)
FixVar.push_back(i > this->LeadStart ? i + this->nLeader : i);
}
return this->LCPasMIP(FixEq, FixVar, solve);
}
unique_ptr<GRBModel> Game::LCP::LCPasMIP(
vector<unsigned int> FixEq, ///< If any equation is to be fixed to equality
vector<unsigned int> FixVar, ///< If any variable is to be fixed to equality
bool solve ///< Whether the model should be solved in the function before
///< returned.
)
/**
* Uses the big M method to solve the complementarity problem. The variables and
* eqns to be set to equality can be given in FixVar and FixEq.
* @note Returned model is \e always a restriction. For <tt>FixEq = FixVar =
* {}</tt>, the returned model would solve the exact LCP.
* @warning Note that the model returned by this function has to be explicitly
* deleted using the delete operator.
* @returns unique pointer to a GRBModel
*/
{
makeRelaxed();
unique_ptr<GRBModel> model{new GRBModel(this->RlxdModel)};
// Creating the model
try {
GRBVar x[nC], z[nR], u[nR], v[nR];
// Get hold of the Variables and Eqn Variables
for (unsigned int i = 0; i < nC; i++)
x[i] = model->getVarByName("x_" + to_string(i));
for (unsigned int i = 0; i < nR; i++)
z[i] = model->getVarByName("z_" + to_string(i));
// Define binary variables for bigM
for (unsigned int i = 0; i < nR; i++)
u[i] = model->addVar(0, 1, 0, GRB_BINARY, "u_" + to_string(i));
if (this->useIndicators)
for (unsigned int i = 0; i < nR; i++)
v[i] = model->addVar(0, 1, 0, GRB_BINARY, "v_" + to_string(i));
// Include ALL Complementarity constraints using bigM
if (this->useIndicators) {
BOOST_LOG_TRIVIAL(trace)
<< "Using indicator constraints for complementarities.";
} else {
BOOST_LOG_TRIVIAL(trace)
<< "Using bigM for complementarities with M=" << this->bigM;
}
GRBLinExpr expr = 0;
for (const auto p : Compl) {
// z[i] <= Mu constraint
// u[j]=0 --> z[i] <=0
if (!this->useIndicators) {
expr = bigM * u[p.first];
model->addConstr(expr, GRB_GREATER_EQUAL, z[p.first],
"z" + to_string(p.first) + "_L_Mu" +
to_string(p.first));
} else {
model->addGenConstrIndicator(
u[p.first], 1, z[p.first], GRB_LESS_EQUAL, 0,
"z_ind_" + to_string(p.first) + "_L_Mu_" + to_string(p.first));
}
// x[i] <= M(1-u) constraint
if (!this->useIndicators) {
expr = bigM - bigM * u[p.first];
model->addConstr(expr, GRB_GREATER_EQUAL, x[p.second],
"x" + to_string(p.first) + "_L_MuDash" +
to_string(p.first));
} else {
model->addGenConstrIndicator(
v[p.first], 1, x[p.second], GRB_LESS_EQUAL, 0,
"x_ind_" + to_string(p.first) + "_L_MuDash_" + to_string(p.first));
}
if (this->useIndicators)
model->addConstr(u[p.first] + v[p.first], GRB_EQUAL, 1,
"uv_sum_" + to_string(p.first));
}
// If any equation or variable is to be fixed to zero, that happens here!
for (auto i : FixVar)
model->addConstr(x[i], GRB_EQUAL, 0.0);
for (auto i : FixEq)
model->addConstr(z[i], GRB_EQUAL, 0.0);
model->update();
if (!this->useIndicators) {
model->set(GRB_DoubleParam_IntFeasTol, this->eps_int);
model->set(GRB_DoubleParam_FeasibilityTol, this->eps);
model->set(GRB_DoubleParam_OptimalityTol, this->eps);
}
// Get first Equilibrium
model->set(GRB_IntParam_SolutionLimit, 1);
if (solve)
model->optimize();
return model;
} catch (const char *e) {
cerr << "Error in Game::LCP::LCPasMIP: " << e << '\n';
throw;
} catch (string e) {
cerr << "String: Error in Game::LCP::LCPasMIP: " << e << '\n';
throw;
} catch (exception &e) {
cerr << "Exception: Error in Game::LCP::LCPasMIP: " << e.what() << '\n';
throw;
} catch (GRBException &e) {
cerr << "GRBException: Error in Game::LCP::LCPasMIP: " << e.getErrorCode()
<< "; " << e.getMessage() << '\n';
throw;
}
return nullptr;
}
bool Game::LCP::errorCheck(
bool throwErr ///< If this is true, function throws an
///< error, else, it just returns false
) const
/**
* Checks if the `M` and `q` given to create the LCP object are of
* compatible size, given the number of leader variables
*/
{
const unsigned int nR = M.n_rows;
const unsigned int nC = M.n_cols;
if (throwErr) {
if (nR != q.n_rows)
throw "Game::LCP::errorCheck: M and q have unequal number of rows";
if (nR + nLeader != nC)
throw "Game::LCP::errorCheck: Inconsistency between number of leader "
"vars " +
to_string(nLeader) + ", number of rows " + to_string(nR) +
" and number of cols " + to_string(nC);
}
return (nR == q.n_rows && nR + nLeader == nC);
}
void Game::LCP::print(string end) {
cout << "LCP with " << this->nR << " rows and " << this->nC << " columns."
<< end;
}
unsigned int
Game::LCP::ConvexHull(arma::sp_mat &A, ///< Convex hull inequality description
///< LHS to be stored here
arma::vec &b) ///< Convex hull inequality description RHS
///< to be stored here
/**
* Computes the convex hull of the feasible region of the LCP
*/
{
const std::vector<arma::sp_mat *> tempAi = [](spmat_Vec &uv) {
std::vector<arma::sp_mat *> v{};
for (const auto &x : uv)
v.push_back(x.get());
return v;
}(*this->Ai);
const std::vector<arma::vec *> tempbi = [](vec_Vec &uv) {
std::vector<arma::vec *> v{};
std::for_each(uv.begin(), uv.end(),
[&v](const std::unique_ptr<arma::vec> &ptr) {
v.push_back(ptr.get());
});
return v;
}(*this->bi);
arma::sp_mat A_common;
A_common = arma::join_cols(this->_A, -this->M);
arma::vec b_common = arma::join_cols(this->_b, this->q);
if (Ai->size() == 1) {
A.zeros(Ai->at(0)->n_rows + A_common.n_rows,
Ai->at(0)->n_cols + A_common.n_cols);
b.zeros(bi->at(0)->n_rows + b_common.n_rows);
A = arma::join_cols(*Ai->at(0), A_common);
b = arma::join_cols(*bi->at(0), b_common);
return 1;
} else
return Game::ConvexHull(&tempAi, &tempbi, A, b, A_common, b_common);
};
unsigned int Game::ConvexHull(
const vector<arma::sp_mat *>
*Ai, ///< Inequality constraints LHS that define polyhedra whose convex
///< hull is to be found
const vector<arma::vec *>
*bi, ///< Inequality constraints RHS that define
///< polyhedra whose convex hull is to be found
arma::sp_mat &A, ///< Pointer to store the output of the convex hull LHS
arma::vec &b, ///< Pointer to store the output of the convex hull RHS
const arma::sp_mat
Acom, ///< any common constraints to all the polyhedra - lhs.
const arma::vec bcom ///< Any common constraints to ALL the polyhedra - RHS.
)
/** @brief Computing convex hull of finite unioon of polyhedra
* @details Computes the convex hull of a finite union of polyhedra where
* each polyhedra @f$P_i@f$ is of the form
* @f{eqnarray}{
* A^ix &\leq& b^i\\
* x &\geq& 0
* @f}
* This uses Balas' approach to compute the convex hull.
*
* <b>Cross reference:</b> Conforti, Michele; Cornuéjols, Gérard; and Zambelli,
* Giacomo. Integer programming. Vol. 271. Berlin: Springer, 2014. Refer:
* Eqn 4.31
*/
{
// Count number of polyhedra and the space we are in!
const unsigned int nPoly{static_cast<unsigned int>(Ai->size())};
// Error check
if (nPoly == 0)
throw string(
"Game::ConvexHull: Empty vector of polyhedra given! Problem might be "
"infeasible."); // There should be at least 1 polyhedron to
// consider
const unsigned int nC{static_cast<unsigned int>(Ai->front()->n_cols)};
const unsigned int nComm{static_cast<unsigned int>(Acom.n_rows)};
if (nComm > 0 && Acom.n_cols != nC)
throw string("Game::ConvexHull: Inconsistent number of variables in the "
"common polyhedron");
if (nComm > 0 && nComm != bcom.n_rows)
throw string("Game::ConvexHull: Inconsistent number of rows in LHS and RHS "
"in the common polyhedron");
// Count the number of variables in the convex hull.
unsigned int nFinCons{0}, nFinVar{0};
if (nPoly != bi->size())
throw string(
"Game::ConvexHull: Inconsistent number of LHS and RHS for polyhedra");
for (unsigned int i = 0; i != nPoly; i++) {
if (Ai->at(i)->n_cols != nC)
throw string("Game::ConvexHull: Inconsistent number of variables in the "
"polyhedra ") +
to_string(i) + "; " + to_string(Ai->at(i)->n_cols) +
"!=" + to_string(nC);
if (Ai->at(i)->n_rows != bi->at(i)->n_rows)
throw string("Game::ConvexHull: Inconsistent number of rows in LHS and "
"RHS of polyhedra ") +
to_string(i) + ";" + to_string(Ai->at(i)->n_rows) +
"!=" + to_string(bi->at(i)->n_rows);
nFinCons += Ai->at(i)->n_rows;
}
// For common constraint copy
nFinCons += nPoly * nComm;
const unsigned int FirstCons = nFinCons;
// 2nd constraint in Eqn 4.31 of Conforti - twice so we have 2 ineq instead of
// 1 eq constr
nFinCons += nC * 2;
// 3rd constr in Eqn 4.31. Again as two ineq constr.
nFinCons += 2;
// Common constraints
// nFinCons += Acom.n_rows;
nFinVar = nPoly * nC + nPoly +
nC; // All x^i variables + delta variables+ original x variables
A.zeros(nFinCons, nFinVar);
b.zeros(nFinCons);
// A.zeros(nFinCons, nFinVar); b.zeros(nFinCons);
// Implements the first constraint more efficiently using better constructors
// for sparse matrix
Game::compConvSize(A, nFinCons, nFinVar, Ai, bi, Acom, bcom);
// Counting rows completed
/****************** SLOW LOOP BEWARE *******************/
for (unsigned int i = 0; i < nPoly; i++) {
BOOST_LOG_TRIVIAL(trace) << "Game::ConvexHull: Handling Polyhedron "
<< i + 1 << " out of " << nPoly;
// First constraint in (4.31)
// A.submat(complRow, i*nC, complRow+nConsInPoly-1, (i+1)*nC-1) =
// *Ai->at(i); // Slowest line. Will arma improve this? First constraint RHS
// A.submat(complRow, nPoly*nC+i, complRow+nConsInPoly-1, nPoly*nC+i) =
// -*bi->at(i); Second constraint in (4.31)
for (unsigned int j = 0; j < nC; j++) {
A.at(FirstCons + 2 * j, nC + (i * nC) + j) = 1;
A.at(FirstCons + 2 * j + 1, nC + (i * nC) + j) = -1;
}
// Third constraint in (4.31)
A.at(FirstCons + nC * 2, nC + nPoly * nC + i) = 1;
A.at(FirstCons + nC * 2 + 1, nC + nPoly * nC + i) = -1;
}
/****************** SLOW LOOP BEWARE *******************/
// Second Constraint RHS
for (unsigned int j = 0; j < nC; j++) {
A.at(FirstCons + 2 * j, j) = -1;
A.at(FirstCons + 2 * j + 1, j) = 1;
}
// Third Constraint RHS
b.at(FirstCons + nC * 2) = 1;
b.at(FirstCons + nC * 2 + 1) = -1;
return nPoly; ///< Perfrorm increasingly better inner approximations in
///< iterations
}
void Game::compConvSize(
arma::sp_mat &A, ///< Output parameter
const unsigned int nFinCons, ///< Number of rows in final matrix A
const unsigned int nFinVar, ///< Number of columns in the final matrix A
const vector<arma::sp_mat *>
*Ai, ///< Inequality constraints LHS that define polyhedra whose convex
///< hull is to be found
const vector<arma::vec *>
*bi, ///< Inequality constraints RHS that define
///< polyhedra whose convex hull is to be found
const arma::sp_mat
&Acom, ///< LHS of the common constraints for all polyhedra
const arma::vec &bcom ///< RHS of the common constraints for all polyhedra
)
/**
* @brief INTERNAL FUNCTION NOT FOR GENERAL USE.
* @warning INTERNAL FUNCTION NOT FOR GENERAL USE.
* @internal To generate the matrix "A" in Game::ConvexHull using batch
* insertion constructors. This is faster than the original line in the code:
* A.submat(complRow, i*nC, complRow+nConsInPoly-1, (i+1)*nC-1) = *Ai->at(i);
* Motivation behind this: Response from
* armadillo:-https://gitlab.com/conradsnicta/armadillo-code/issues/111
*/
{
const unsigned int nPoly{static_cast<unsigned int>(Ai->size())};
const unsigned int nC{static_cast<unsigned int>(Ai->front()->n_cols)};
unsigned int N{0}; // Total number of nonzero elements in the final matrix
const unsigned int nCommnz{
static_cast<unsigned int>(Acom.n_nonzero + bcom.n_rows)};
for (unsigned int i = 0; i < nPoly; i++) {
N += Ai->at(i)->n_nonzero;
N += bi->at(i)->n_rows;
}
N += nCommnz *
nPoly; // The common constraints have to be copied for each polyhedron.
// Now computed N which is the total number of nonzeros.
arma::umat locations; // location of nonzeros
arma::vec val; // nonzero values
locations.zeros(2, N);
val.zeros(N);
unsigned int count{0}, rowCount{0}, colCount{nC};
for (unsigned int i = 0; i < nPoly; i++) {
for (auto it = Ai->at(i)->begin(); it != Ai->at(i)->end();
++it) // First constraint
{
locations(0, count) = rowCount + it.row();
locations(1, count) = colCount + it.col();
val(count) = *it;
++count;
}
for (unsigned int j = 0; j < bi->at(i)->n_rows;
++j) // RHS of first constraint
{
locations(0, count) = rowCount + j;
locations(1, count) = nC + nC * nPoly + i;
val(count) = -bi->at(i)->at(j);
++count;
}
rowCount += Ai->at(i)->n_rows;
// For common constraints
for (auto it = Acom.begin(); it != Acom.end(); ++it) // First constraint
{
locations(0, count) = rowCount + it.row();
locations(1, count) = colCount + it.col();
val(count) = *it;
++count;
}
for (unsigned int j = 0; j < bcom.n_rows; ++j) // RHS of first constraint
{
locations(0, count) = rowCount + j;
locations(1, count) = nC + nC * nPoly + i;
val(count) = -bcom.at(j);
++count;
}
rowCount += Acom.n_rows;
colCount += nC;
}
A = arma::sp_mat(locations, val, nFinCons, nFinVar);
}
arma::vec
Game::LPSolve(const arma::sp_mat &A, ///< The constraint matrix
const arma::vec &b, ///< RHS of the constraint matrix
const arma::vec &c, ///< If feasible, returns a vector that
///< minimizes along this direction
int &status, ///< Status of the optimization problem. If optimal,
///< this will be GRB_OPTIMAL
bool Positivity ///< Should @f$x\geq0@f$ be enforced?
)
/**
Checks if the polyhedron given by @f$ Ax\leq b@f$ is feasible.
If yes, returns the point @f$x@f$ in the polyhedron that minimizes @f$c^Tx@f$
Positivity can be enforced on the variables easily.
*/
{
unsigned int nR, nC;
nR = A.n_rows;
nC = A.n_cols;
if (c.n_rows != nC)
throw "Game::LPSolve: Inconsistency in no of Vars in isFeas()";
if (b.n_rows != nR)
throw "Game::LPSolve: Inconsistency in no of Constr in isFeas()";
arma::vec sol = arma::vec(c.n_rows, arma::fill::zeros);
const double lb = Positivity ? 0 : -GRB_INFINITY;
GRBEnv env;
GRBModel model = GRBModel(env);
GRBVar x[nC];
GRBConstr a[nR];
// Adding Variables
for (unsigned int i = 0; i < nC; i++)
x[i] = model.addVar(lb, GRB_INFINITY, c.at(i), GRB_CONTINUOUS,
"x_" + to_string(i));
// Adding constraints
for (unsigned int i = 0; i < nR; i++) {
GRBLinExpr lin{0};
for (auto j = A.begin_row(i); j != A.end_row(i); ++j)
lin += (*j) * x[j.col()];
a[i] = model.addConstr(lin, GRB_LESS_EQUAL, b.at(i));
}
model.set(GRB_IntParam_OutputFlag, VERBOSE);
model.set(GRB_IntParam_DualReductions, 0);
model.optimize();
status = model.get(GRB_IntAttr_Status);
if (status == GRB_OPTIMAL)
for (unsigned int i = 0; i < nC; i++)
sol.at(i) = x[i].get(GRB_DoubleAttr_X);
return sol;
}
bool Game::LCP::extractSols(
GRBModel *model, ///< The Gurobi Model that was solved (perhaps using
///< Game::LCP::LCPasMIP)
arma::vec &z, ///< Output variable - where the equation values are stored
arma::vec &x, ///< Output variable - where the variable values are stored
bool extractZ ///< z values are filled only if this is true
) const
/** @brief Extracts variable and equation values from a solved Gurobi model for
LCP */
/** @warning This solves the model if the model is not already solve */
/** @returns @p false if the model is not solved to optimality. @p true
otherwise */
{
if (model->get(GRB_IntAttr_Status) == GRB_LOADED)
model->optimize();
auto status = model->get(GRB_IntAttr_Status);
if (!(status == GRB_OPTIMAL || status == GRB_SUBOPTIMAL ||
status == GRB_SOLUTION_LIMIT))
return false;
x.zeros(nC);
if (extractZ)
z.zeros(nR);
for (unsigned int i = 0; i < nR; i++) {
x[i] = model->getVarByName("x_" + to_string(i)).get(GRB_DoubleAttr_X);
if (extractZ)
z[i] = model->getVarByName("z_" + to_string(i)).get(GRB_DoubleAttr_X);
}
for (unsigned int i = nR; i < nC; i++)
x[i] = model->getVarByName("x_" + to_string(i)).get(GRB_DoubleAttr_X);
return true;
}
std::vector<short int> Game::LCP::solEncode(const arma::vec &x) const
/// @brief Given variable values, encodes it in 0/+1/-1
/// format and returns it.
/// @details Gives the 0/+1/-1 notation. The notation is defined as follows.
/// Note that, if the input is feasible, then in each complementarity pair (Eqn,
/// Var), at least one of the two is zero.
///
/// - If the equation is zero in a certain index and the variable is non-zero,
/// then that index is noted by +1.
/// - If the variable is zero in a certain index and the equation is non-zero,
/// then that index is noted by +1.
/// - If both the variable and equation are zero, then that index is noted by 0.
{
return this->solEncode(this->M * x + this->q, x);
}
vector<short int> Game::LCP::solEncode(const arma::vec &z, ///< Equation values
const arma::vec &x ///< Variable values
) const
/// @brief Given variable values and equation values, encodes it in 0/+1/-1
/// format and returns it.
{
vector<short int> solEncoded(nR, 0);
for (const auto p : Compl) {
unsigned int i, j;
i = p.first;
j = p.second;
if (isZero(z(i)))
solEncoded.at(i)++;
if (isZero(x(j)))
solEncoded.at(i)--;
if (!isZero(x(j)) && !isZero(z(i)))
BOOST_LOG_TRIVIAL(error) << "Infeasible point given! Stay alert! " << x(j)
<< " " << z(i) << " with i=" << i;
};
// std::stringstream enc_str;
// for(auto vv:solEncoded) enc_str << vv <<" ";
// BOOST_LOG_TRIVIAL (debug) << "Game::LCP::solEncode: Handling deviation with
// encoding: "<< enc_str.str() << '\n';
return solEncoded;
}
vector<short int> Game::LCP::solEncode(GRBModel *model) const
/// @brief Given a Gurobi model, extracts variable values and equation values,
/// encodes it in 0/+1/-1 format and returns it.
/// @warning Note that the vector returned by this function might have to be
/// explicitly deleted using the delete operator. For specific uses in
/// LCP::BranchAndPrune, this delete is handled by the class destructor.
{
arma::vec x, z;
if (!this->extractSols(model, z, x, true))
return {}; // If infeasible model, return empty!
else
return this->solEncode(z, x);
}
LCP &Game::LCP::addPolyFromX(const arma::vec &x, bool &ret)
/**
* Given a <i> feasible </i> point @p x, checks if any polyhedron that contains
* @p x is already a part of this->Ai and this-> bi. If it is, then this does
* nothing, except for printing a log message. If not, it adds a polyhedron
* containing this vector.
*/
{
const unsigned int nCompl = this->Compl.size();
vector<short int> encoding = this->solEncode(x);
std::stringstream enc_str;
for (auto vv : encoding)
enc_str << vv << " ";
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::addPolyFromX: Handling deviation with encoding: "
<< enc_str.str() << '\n';
// Check if the encoding polyhedron is already in this->AllPolyhedra
for (const auto &i : AllPolyhedra) {
std::vector<short int> bin = num_to_vec(i, nCompl);
if (encoding < bin) {
BOOST_LOG_TRIVIAL(trace) << "LCP::addPolyFromX: Encoding " << i
<< " already in All Polyhedra! ";
ret = false;
return *this;
}
}
BOOST_LOG_TRIVIAL(trace)
<< "LCP::addPolyFromX: New encoding not in All Polyhedra! ";
// If it is not in AllPolyhedra
// First change any zero indices of encoding to 1
for (short &i : encoding) {
if (i == 0)
++i;
}
// And then add the relevant polyhedra
ret = this->FixToPoly(encoding, false);
// ret = true;
return *this;
}
bool Game::LCP::FixToPoly(
const vector<short int>
Fix, ///< A vector of +1 and -1 referring to which
///< equations and variables are taking 0 value.
bool checkFeas, ///< The polyhedron is added after ensuring feasibility, if
///< this is true
bool custom, ///< Should the polyhedra be pushed into a custom vector of
///< polyhedra as opposed to LCP::Ai and LCP::bi
spmat_Vec *custAi, ///< If custom polyhedra vector is used, pointer to
///< vector of LHS constraint matrix
vec_Vec *custbi /// If custom polyhedra vector is used, pointer
/// to vector of RHS of constraints
)
/** @brief Computes the equation of the feasibility polyhedron corresponding to
*the given @p Fix
* @details The computed polyhedron is always pushed into a vector of @p
*arma::sp_mat and @p arma::vec If @p custom is false, this is the internal
*attribute of LCP, which are LCP::Ai and LCP::bi. Otherwise, the vectors can be
*provided as arguments.
* @p true value to @p checkFeas ensures that the polyhedron is pushed @e
*only if it is feasible.
* @returns @p true if successfully added, else false
* @warning Does not entertain 0 in the elements of *Fix. Only +1/-1 are
*allowed to not encounter undefined behavior. As a result, not meant for high
*level code. Instead use LCP::FixToPolies.
*/
{
unsigned int FixNumber = vec_to_num(Fix);
BOOST_LOG_TRIVIAL(trace) << "Game::LCP::FixToPoly: Working on polyhedron"
<< FixNumber;
if (knownInfeas.find(FixNumber) != knownInfeas.end()) {
BOOST_LOG_TRIVIAL(trace) << "Game::LCP::FixToPoly: Previously known "
"infeasible polyhedron. Not added"
<< FixNumber;
return false;
}
if (!custom && !AllPolyhedra.empty()) {
if (AllPolyhedra.find(FixNumber) != AllPolyhedra.end()) {
BOOST_LOG_TRIVIAL(trace)
<< "Game::LCP::FixToPoly: Previously added polyhedron. Not added "
<< FixNumber;
return false;
}
}
unique_ptr<arma::sp_mat> Aii =
unique_ptr<arma::sp_mat>(new arma::sp_mat(nR, nC));
Aii->zeros();
unique_ptr<arma::vec> bii =
unique_ptr<arma::vec>(new arma::vec(nR, arma::fill::zeros));
for (unsigned int i = 0; i < this->nR; i++) {
if (Fix.at(i) == 0) {
throw string(
"Error in Game::LCP::FixToPoly. 0s not allowed in argument vector");
}
if (Fix.at(i) == 1) // Equation to be fixed top zero
{
for (auto j = this->M.begin_row(i); j != this->M.end_row(i); ++j)
if (!this->isZero((*j)))
Aii->at(i, j.col()) =
(*j); // Only mess with non-zero elements of a sparse matrix!
bii->at(i) = -this->q(i);
} else // Variable to be fixed to zero, i.e. x(j) <= 0 constraint to be
// added
{
unsigned int varpos = (i >= this->LeadStart) ? i + this->nLeader : i;
Aii->at(i, varpos) = 1;
bii->at(i) = 0;
}
}
bool add = !checkFeas;
if (checkFeas) {
add = this->checkPolyFeas(Fix);
}
if (add) {
if (custom) {
custAi->push_back(std::move(Aii));
custbi->push_back(std::move(bii));
} else {
AllPolyhedra.insert(FixNumber);
this->Ai->push_back(std::move(Aii));
this->bi->push_back(std::move(bii));
}
return true; // Successfully added
}
return false;
}
bool Game::LCP::checkPolyFeas(
const unsigned long int
&decimalEncoding ///< Decimal encoding for the polyhedron
) {
return this->checkPolyFeas(num_to_vec(decimalEncoding, this->Compl.size()));
}
bool Game::LCP::checkPolyFeas(
const vector<short int> &Fix ///< A vector of +1 and -1 referring to which
///< equations and variables are taking 0 value.)
) {