-
Notifications
You must be signed in to change notification settings - Fork 2
/
lpsolve.cc
2729 lines (2643 loc) · 97.4 KB
/
lpsolve.cc
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
/*
* lpsolve.cc
*
* Copyright 2021 Luka Marohnić
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "giacPCH.h"
#include "giac.h"
#include "lpsolve.h"
#include "optimization.h"
#include <ctime>
#include <set>
#ifndef DBL_MAX
#define DBL_MAX 1.79769313486e+308
#endif
using namespace std;
#ifndef NO_NAMESPACE_GIAC
namespace giac {
#endif //ndef NO_NAMESPACE_GIAC
/*
* A variant of "is_positive" which hopefully does not hang.
* Implemented here because optimization.cc includes pari.h which redefines taille!
*/
bool is_positive_safe(const gen &g,bool strict,unsigned max_taille,GIAC_CONTEXT) {
vecteur s;
gen alg=g;//to_algebraic(g,s,contextptr); // FIXME
if (max_taille>0 && taille(alg,max_taille+1)>=max_taille)
return false;
bool ret=strict?is_strictly_positive(alg,contextptr):is_positive(alg,contextptr);
if (!s.empty())
_purge(s,contextptr);
return ret;
}
/*
* Return the number of digits of an unsigned integer.
*/
int numdigits(unsigned i) {
return 1+(i>0?(int)std::log10((double)i):0);
}
/*
* Return true iff g is a (vector of) real number(s), +inf, or -inf.
*/
bool is_realcons(const gen &g,GIAC_CONTEXT) {
if (g.type==_VECT) {
const vecteur &v = *g._VECTptr;
const_iterateur it=v.begin(),itend=v.end();
for (;it!=itend;++it) {
if (!is_realcons(*it,contextptr))
return false;
}
return true;
}
return (is_inf(g) || g.type==_REAL || _evalf(g,contextptr).type==_DOUBLE_);
}
/*
* If g is an interval, store its bounds to pair p and return true.
* If g is not an interval, return false.
*/
bool interval2pair(const gen &g,pair<gen,gen> &p,GIAC_CONTEXT) {
if (g.type!=_SYMB || !g.is_symb_of_sommet(at_interval))
return false; //g is not an interval
const vecteur &v=*g._SYMBptr->feuille._VECTptr;
p=make_pair(v[0],v[1]);
return is_realcons(v,contextptr);
}
/*
* Return true iff g is a vector of identifiers.
*/
bool is_idnt_vecteur(const gen &g,GIAC_CONTEXT) {
if (g.type!=_VECT)
return false;
const_iterateur it=g._VECTptr->begin(),itend=g._VECTptr->end();
for (;it!=itend;++it) {
if (it->type!=_IDNT)
return false;
}
return true;
}
/*
* Make a singleton vector with 1 at position j and 0 at other positions.
*/
vecteur singleton(int n,int j,bool negative=false) {
vecteur v(n,0);
v[j]=negative?-1:1;
return v;
}
/*
* Insert column c in matrix at position j.
*/
void insert_column(matrice &m,const vecteur &c,int j) {
assert(m.size()==c.size());
for (int i=m.size();i-->0;) {
vecteur &row=*m[i]._VECTptr;
row.insert(j>=0?row.begin()+j:row.end()+j,c[i]);
}
}
/*
* Append a column c to matrix m.
*/
void append_column(matrice &m,const vecteur &c) {
assert(m.size()==c.size());
for (iterateur it=m.begin();it!=m.end();++it) {
it->_VECTptr->push_back(c[it-m.begin()]);
}
}
/*
* Remove the jth column from the matrix m.
* If j<0, count from the last column towards the first.
*/
void remove_column(matrice &m,int j) {
for (iterateur it=m.begin();it!=m.end();++it) {
it->_VECTptr->erase(j+(j>=0?it->_VECTptr->begin():it->_VECTptr->end()));
}
}
/*
* Get the jth column from matrix m.
* If j<0, count from the last column towards the the first.
*/
vecteur jth_column(const matrice &m,int j) {
int n=m.front()._VECTptr->size();
vecteur col(m.size());
for (const_iterateur it=m.begin();it!=m.end();++it) {
col[it-m.begin()]=it->_VECTptr->at(j>=0?j:n+j);
}
return col;
}
/*
* Multiply the coefficients in v_orig by LCM of
* denominators and then divide by their GCD.
*/
void integralize(vecteur &v,GIAC_CONTEXT) {
vecteur vd;
for (const_iterateur it=v.begin();it!=v.end();++it) {
if (!is_zero(*it,contextptr))
vd.push_back(_denom(*it,contextptr));
}
if (vd.empty())
return;
v=multvecteur(abs(_lcm(vd,contextptr),contextptr),v);
v=divvecteur(v,abs(_gcd(v,contextptr),contextptr));
}
void lp_variable::assign(const lp_variable &other) {
_is_integral=other._is_integral;
_sign_type=other._sign_type;
_range=other._range;
_name=other._name;
_subs_coef=other._subs_coef;
pseudocost[0]=other.pseudocost[0];
pseudocost[1]=other.pseudocost[1];
nbranch[0]=other.nbranch[0];
nbranch[1]=other.nbranch[1];
}
/*
* LP variable constructor. By default, it is a nonnegative variable
* unrestricted from above.
*/
lp_variable::lp_variable() {
_is_integral=false;
_sign_type=_LP_VARSIGN_POS;
_range=lp_range();
_range.set_lb(0);
fill_n(nbranch,2,0);
}
/*
* Update lower (dir=0) or upper (dir=1) pseudocost.
*/
void lp_variable::update_pseudocost(double delta,double fr,int dir) {
if (fr==0) return;
double sigma=pseudocost[dir]*nbranch[dir];
sigma+=delta/(dir==0?fr:(1-fr));
pseudocost[dir]=sigma/(++nbranch[dir]);
}
/*
* Return score, a positive value based on pseudocost values. Variable with the
* best (highest) score is selected for branching.
*/
double lp_variable::score(double fr) const {
if (nbranch[0]==0 || nbranch[1]==0)
return 0;
double qlo=fr*pseudocost[0],qhi=(1-fr)*pseudocost[1];
return (1-LP_SCORE_FACTOR)*std::min(qlo,qhi)+LP_SCORE_FACTOR*std::max(qlo,qhi);
}
/* Set the type of this variable. */
void lp_variable::set_type(int t,GIAC_CONTEXT) {
switch (t) {
case _LP_BINARYVARIABLES:
tighten_lbound(0,contextptr);
tighten_ubound(1,contextptr);
case _LP_INTEGERVARIABLES:
_is_integral=true;
break;
}
}
/*
* Range constructor: by default, it contains no restriction.
*/
lp_range::lp_range () {
lbound=minus_inf;
ubound=plus_inf;
}
/*
* Settings constructor loads some sensible defaults.
*/
lp_settings::lp_settings() {
verbose=false;
status_report_freq=0.2;
solver=_LP_SIMPLEX;
precision=_LP_PROB_DEPENDENT;
presolve=1;
maximize=false;
acyclic=true;
relative_gap_tolerance=0.0;
has_binary_vars=false;
varselect=-1;
nodeselect=-1;
depth_limit=0;
node_limit=0;
iteration_limit=0;
time_limit=0;
max_cuts=5;
use_heuristic=true;
}
/*
* Stats constructor initializes the status container for the problem being
* solved. It is used to monitor the progress and to summarize when done.
*/
lp_stats::lp_stats() {
subproblems_examined=0;
cuts_applied=0;
cut_improvement=0;
max_active_nodes=0;
mip_gap=-1; //negative means undefined
}
/*
* Pivot on element with coordinates I,J.
*/
void lp_node::pivot_ij(matrice &m,int I,int J,bool negate) {
pivot_elm=m[I][J];
vecteur &mI=*m[I]._VECTptr;
iterateur it=mI.begin(),itend=mI.end(),jt;
vector<intgen>::iterator rcbeg=pivot_row.begin(),rc;
int i,j,jprev,jmax;
for (j=jprev=0,rc=rcbeg;it!=itend;++it,++j) {
if (j!=J && !is_zero(*it,prob->ctx)) {
*(rc++)=make_pair(j-jprev,*it=*it/pivot_elm);
jprev=j;
}
}
jmax=rc-rcbeg;
mI[J]=gen(negate?-1:1)/pivot_elm;
for (it=m.begin(),itend=m.end(),i=0;it!=itend;++it,++i) {
vecteur &mi=*it->_VECTptr;
gen &miJ=mi[J];
if (i!=I && !is_zero(miJ,prob->ctx)) {
j=jmax;
for (rc=rcbeg,jt=mi.begin();j-->0;++rc)
*(jt+=rc->first)-=miJ*rc->second;
miJ=gen(negate?1:-1)*miJ/pivot_elm;
}
}
}
static clock_t srbt;
/*
* Change basis by choosing entering and leaving variables and swapping them.
* Return true iff there is no need to change basis any further.
*/
bool lp_node::change_basis(matrice &m,const vecteur &u,vector<bool> &is_slack,ints &basis,ints &cols) {
// ev, lv: indices of entering and leaving variables
// ec, lr: 'entering' column and 'leaving' row in matrix m, respectively
int ec,ev,lr,lv,nc=cols.size(),nr=basis.size(),i,j;
gen ratio,mincoeff=0;
// choose a variable to enter basis
ev=-1;
const vecteur &last=*m.back()._VECTptr;
vector<int>::const_iterator it;
const_iterateur jt,jtend;
for (j=0,it=cols.begin(),jt=last.begin();j<nc;++j,++it,++jt) {
if ((use_bland && !is_positive(*jt,prob->ctx) &&
(ev<0 || *it+(is_slack[*it]?nv:0)<ev+(is_slack[ev]?nv:0))) ||
(!use_bland && is_strictly_greater(mincoeff,*jt,prob->ctx))) {
ec=j;
ev=*it;
mincoeff=*jt;
}
}
if (ev<0) // current solution is optimal
return true;
// choose a variable to leave basis
mincoeff=plus_inf;
lv=-1;
bool hits_ub,ub_subs;
for (i=0,jt=m.begin();i<nr;++i,++jt) {
const gen &a=jt->_VECTptr->at(ec),&b=jt->_VECTptr->back();
j=basis[i];
if (is_strictly_positive(a,prob->ctx) && is_greater(mincoeff,ratio=b/a,prob->ctx))
hits_ub=false;
else if (!is_positive(a,prob->ctx) && !is_inf(u[j]) &&
is_greater(mincoeff,ratio=(b-u[j])/a,prob->ctx))
hits_ub=true;
else continue;
if (is_strictly_greater(mincoeff,ratio,prob->ctx)) {
lv=-1;
mincoeff=ratio;
}
if (lv<0 || (use_bland && j+(is_slack[j]?nv:0)<lv+(is_slack[lv]?nv:0))) {
lv=j;
lr=i;
ub_subs=hits_ub;
}
}
if (lv<0 && is_inf(u[ev])) { // solution is unbounded
optimum=minus_inf;
return true;
}
if (prob->settings.acyclic)
use_bland=is_zero(mincoeff,prob->ctx); // Bland's rule
if (lv<0 || is_greater(mincoeff,u[ev],prob->ctx)) {
for (jt=m.begin(),jtend=m.end();jt!=jtend;++jt) {
gen &a=jt->_VECTptr->at(ec);
a=-a;
jt->_VECTptr->back()+=u[ev]*a;
}
if (ev<nv)
is_slack[ev]=!is_slack[ev];
return false;
}
// swap variables: basic leaves, nonbasic enters
if (ub_subs) {
m[lr]._VECTptr->back()-=u[lv];
if (lv<nv)
is_slack[lv]=!is_slack[lv];
}
pivot_ij(m,lr,ec,ub_subs);
basis[lr]=ev;
cols[ec]=lv;
return false;
}
/*
* Simplex algorithm that handles upper bounds of the variables. The solution x
* satisfies 0<=x<=u. An initial basis must be provided.
*
* Basis is a vector of integers B and B[i]=j means that j-th variable is basic
* and appears in i-th row (constraint). Basic columns are not kept in matrix,
* which contains only the columns of nonbasic variables. A nonbasic variable
* is assigned to the respective column with integer vector 'cols': cols[i]=j
* means that i-th column of the matrix is associated with the j-th variable. The
* algorithm uses the upper-bounding technique when pivoting and an adaptation
* of Bland's rule to prevent cycling. i-th element of 'is_slack' is true iff
* the i-th (nonbasic) variable is at its upper bound.
*
* If limit>0, the simplex algorithm will terminate after that many iterations.
*/
void lp_node::simplex_reduce_bounded(matrice &m,const vecteur &u,vector<bool> &is_slack,
ints &basis,ints &cols,int phase,const gen &obj_ct) {
int nr=basis.size(),nc=cols.size();
int limit=prob->settings.iteration_limit;
int &icount=prob->iteration_count;
// iterate the simplex method
use_bland=false;
optimum=undef;
char buffer[256],numbuf[8];
double obj0=-1;
while (true) {
++icount;
if (limit>0 && icount>limit)
break;
if (phase>0) {
clock_t now=clock();
double obj=_evalf(phase==1?-m[nr][nc]:(prob->settings.maximize?-1:1)*(obj_ct-m[nr][nc]),prob->ctx).DOUBLE_val();
if (phase==1 && obj0<obj) {
if (is_zero(m[nr][nc],prob->ctx))
break;
obj0=obj;
}
if (CLOCKS_PER_SEC/double(now-srbt)<=0.5) { // display progress info
sprintf(numbuf,"%d",icount);
string ns(numbuf);
while (ns.length()<7) ns.insert(0,1,' ');
sprintf(buffer," %s %s obj: %g%s",phase==1?" ":"*",ns.c_str(),phase==1?100*obj/obj0:obj,phase==1?"%":"");
prob->message(buffer);
srbt=now;
}
}
if (change_basis(m,u,is_slack,basis,cols) || (std::abs(phase)==1 && is_zero(m[nr][nc],prob->ctx)))
break;
}
if (is_undef(optimum))
optimum=m[nr][nc];
}
/*
* Remove a free (empty-column) variable corresponding to the j-th column.
*/
bool lp_node::remove_free_variable(int j,const vecteur &l,const vecteur &u,ints &cols,const vecteur &obj,gen &obj_ct) {
gen val;
int v=cols[j];
if (is_positive(obj[v],prob->ctx))
val=l[v];
else if (is_inf(u[v]))
return false; // unbounded
else val=u[v];
vector<intgen> rcol(1,make_pair(v,val));
removed_cols.push(rcol);
obj_ct+=obj[v]*val;
cols.erase(cols.begin()+j);
return true;
}
/*
* Preprocess a B&B-tree node.
*/
int lp_node::preprocess(matrice &m,vecteur &bv,vecteur &l,vecteur &u,ints &cols,vecteur &obj,gen &obj_ct) {
bool changed;
do {
changed=false;
for (int i=m.size();i-->0;) { // detect empty and singleton rows
const vecteur &a=*m[i]._VECTptr;
const gen &b=bv[i];
int nz=0,j0=-1;
for (int j=cols.size();j-->0;) {
if (!is_zero(a[j],prob->ctx)) {
++nz;
j0=j;
}
}
if (nz==0) { // empty row detected
if (!is_zero(b,prob->ctx))
return _LP_INFEASIBLE;
} else if (nz==1) { // singleton row detected
assert(j0>=0);
int v=cols[j0];
if (is_strictly_greater(b/a[j0],u[v],prob->ctx) || is_strictly_greater(l[v],b/a[j0],prob->ctx))
return _LP_INFEASIBLE;
u[v]=l[v]=b/a[j0];
} else continue;
m.erase(m.begin()+i);
bv.erase(bv.begin()+i);
if (m.empty()) return 0;
changed=true;
}
for (int i=m.size();i-->0;) { // detect forcing constraints
const vecteur &a=*m[i]._VECTptr;
const gen &b=bv[i];
gen g(0),h(0);
for (int j=cols.size();j-->0;) {
if (is_zero(a[j],prob->ctx))
continue;
int v=cols[j];
g+=a[j]*(is_positive(a[j],prob->ctx)?l[v]:u[v]);
h+=a[j]*(is_positive(a[j],prob->ctx)?u[v]:l[v]);
}
if (is_undef(g) || is_undef(h))
continue;
if (is_strictly_greater(b,h,prob->ctx) || is_strictly_greater(g,b,prob->ctx))
return _LP_INFEASIBLE;
if (is_inf(g) || is_inf(h))
continue;
if (is_zero(g-b,prob->ctx) || is_zero(h-b,prob->ctx)) { // forcing constraint detected
for (int j=cols.size();j-->0;) {
if (is_zero(a[j],prob->ctx))
continue;
int v=cols[j];
if (is_positive(a[j]*gen(is_zero(g-b,prob->ctx)?1:-1),prob->ctx))
u[v]=l[v];
else l[v]=u[v];
}
m.erase(m.begin()+i);
bv.erase(bv.begin()+i);
if (m.empty()) return 0;
changed=true;
continue;
}
// detect free singleton columns, tighten variable bounds
for (int j=cols.size();j-->0;) {
if (is_zero(a[j],prob->ctx))
continue;
int v=cols[j];
gen vl=(is_positive(a[j],prob->ctx)?b-h:b-g)/a[j]+u[v];
gen vu=(is_positive(a[j],prob->ctx)?b-g:b-h)/a[j]+l[v];
int k=0;
for (;k<int(m.size()) && (k==i || is_zero(m[k][j],prob->ctx));++k);
if (k==int(m.size()) && is_greater(vl,l[v],prob->ctx) && is_greater(u[v],vu,prob->ctx)) {
// free column singleton detected
vector<intgen> rcol(1,make_pair(v,b/a[j]));
obj_ct+=obj[v]*b/a[j];
for (k=cols.size();k-->0;) {
if (k!=j && !is_zero(a[k],prob->ctx)) {
rcol.push_back(make_pair(cols[k],-a[k]/a[j]));
obj[cols[k]]-=obj[v]*a[k]/a[j];
}
}
removed_cols.push(rcol);
cols.erase(cols.begin()+j);
m.erase(m.begin()+i);
bv.erase(bv.begin()+i);
if (m.empty()) return 0;
remove_column(m,j);
if (m.front()._VECTptr->empty()) return 0;
changed=true;
break;
} else { // tighten bounds on var
l[v]=max(l[v],vl,prob->ctx);
u[v]=min(u[v],vu,prob->ctx);
}
}
}
// integralize bounds, check for impossible bounds
for (ints::const_iterator it=cols.begin();it!=cols.end();++it) {
if (prob->variables[*it].is_integral()) {
l[*it]=_ceil(l[*it],prob->ctx);
u[*it]=_floor(u[*it],prob->ctx);
}
if (is_strictly_greater(l[*it],u[*it],prob->ctx))
return _LP_INFEASIBLE;
}
// remove empty columns and fixed variables
for (int j=cols.size();j-->0;) {
int v=cols[j];
if (is_zero__VECT(jth_column(m,j),prob->ctx)) { // j-th column is empty
if (!remove_free_variable(j,l,u,cols,obj,obj_ct))
return _LP_UNBOUNDED;
remove_column(m,j);
if (m.front()._VECTptr->empty()) return 0;
changed=true;
} else if (is_zero(u[v]-l[v],prob->ctx)) { // variable v is fixed
if (!is_zero(l[v]),prob->ctx) for (int i=bv.size();i-->0;) {
bv[i]-=m[i][j]*l[v];
}
vector<intgen> rcol(1,make_pair(v,l[v]));
removed_cols.push(rcol);
obj_ct+=obj[v]*l[v];
cols.erase(cols.begin()+j);
remove_column(m,j);
if (m.front()._VECTptr->empty()) return 0;
changed=true;
}
}
} while (changed);
return 0;
}
/*
* Solve the relaxed subproblem corresponding to this node.
*
* This function uses two-phase simplex method and applies suitable Gomory
* mixed integer cuts generated after (each re)optimization. Weak GMI cuts are
* discarded either because of small away or because not being parallel enough
* to the objective. Cuts with too large coefficients (when integralized) are
* discarded too because they slow down the computational process. Generated
* cuts are kept in the problem structure to be used by child suboproblems
* during the branch&bound algorithm.
*/
int lp_node::solve_relaxation() {
int nrows=prob->constr.nrows(),ncols=prob->constr.ncols(),bs,nc;
matrice m,cuts;
vecteur obj=prob->objective.first,l(ncols),u(ncols),br,row,b,lh;
gen rh,obj_ct(prob->objective.second),mgn;
ints cols(ncols),basis;
vector<bool> is_slack(ncols,false);
bool is_mip=prob->has_integral_variables();
// determine the upper and the lower bound
for (int j=0;j<ncols;++j) {
cols[j]=j;
const lp_variable &var=prob->variables[j];
const lp_range &rng=ranges[j];
l[j]=max(var.lb(),rng.lb(),prob->ctx);
u[j]=min(var.ub(),rng.ub(),prob->ctx);
if (is_strictly_greater(l[j],u[j],prob->ctx))
return _LP_INFEASIBLE;
}
// populate matrix with constraint coefficients
m=*_matrix(makesequence(nrows,ncols,0),prob->ctx)._VECTptr;
for (int i=0;i<nrows;++i) for (int j=0;j<ncols;++j)
m[i]._VECTptr->at(j)=prob->constr.lhs[i][j];
b=prob->constr.rhs;
// preprocess
if (prob->settings.presolve==1 && is_mip) {
int res=preprocess(m,b,l,u,cols,obj,obj_ct);
if (res!=0)
return res;
if (m.empty()) for (int j=cols.size();j-->0;) {
if (!remove_free_variable(j,l,u,cols,obj,obj_ct))
return _LP_UNBOUNDED;
}
nrows=m.size();
}
nc=cols.size();
// shift tableau variables so that l<=x<=u becomes 0<=x'<=u'
ints shifted;
for (ints::const_iterator it=cols.begin();it!=cols.end();++it) {
int i=it-cols.begin(),j=*it;
if (!is_zero(l[j],prob->ctx)) {
b=subvecteur(b,multvecteur(l[j],jth_column(m,i)));
u[j]-=l[j];
obj_ct+=obj[j]*l[j];
shifted.push_back(j);
}
}
// append b to the tableau
if (!m.empty())
append_column(m,b);
// assure that the right-hand side column is nonnegative
iterateur it=m.begin(),itend=m.end();
for (;it!=itend;++it) {
if (!is_positive(it->_VECTptr->back(),prob->ctx)) {
*it=multvecteur(-1,*(it->_VECTptr));
}
}
// optimize and cut, repeat
srbt=clock();
int pass=0,cuts0;
gen opt1;
double imp=0;
if (nc>0) while (true) { // apply two-phase simplex algorithm
++pass;
nv=ncols+nrows;
nc=cols.size();
if (pivot_row.size()<=cols.size())
pivot_row.resize(nc+1);
br=vecteur(nc+1,0);
bs=basis.size();
basis.resize(nrows);
u.resize(ncols+nrows-bs);
for (int i=bs;i<nrows;++i) {
br=subvecteur(br,*m[i]._VECTptr);
basis[i]=ncols+i-bs;
u[ncols+i-bs]=plus_inf;
}
m.push_back(br);
assert(ckmatrix(m));
// phase 1: minimize the sum of artificial variables
simplex_reduce_bounded(m,u,is_slack,basis,cols,is_mip || !prob->settings.verbose?-1:1,obj_ct);
if (!is_zero(optimum,prob->ctx))
return _LP_INFEASIBLE; // at least one artificial variable is basic and positive
m.pop_back();
// push artificial variables out of the basis (requires that m is full-rank)
for (int i=0;i<nrows;++i) {
int j=basis[i];
if (j<ncols)
continue;
int k=0;
for (;k<nc && (is_zero(m[i][k],prob->ctx) || cols[k]>=ncols);++k);
if (k==nc)
return _LP_ERROR;
pivot_ij(m,i,k);
basis[i]=cols[k];
cols[k]=j;
}
// remove artificial columns from m
for (int i=nc;i-->0;) {
if (cols[i]>=ncols) {
remove_column(m,i);
cols.erase(cols.begin()+i);
--nc;
}
}
// append the bottom row to maximize -obj
br=vecteur(nc+1,0);
for (int i=0;i<nc;++i) {
int j=cols[i];
br[i]=obj[j];
if (is_slack[j]) {
br.back()-=br[i]*u[j];
br[i]=-br[i];
}
}
for (int i=0;i<nrows;++i) {
int j=basis[i];
if (is_slack[j])
br.back()-=obj[j]*u[j];
br=subvecteur(br,multvecteur(is_slack[j]?-obj[j]:obj[j],*m[i]._VECTptr));
}
m.push_back(br);
assert(ckmatrix(m));
u.resize(ncols);
// phase 2: optimize the objective
simplex_reduce_bounded(m,u,is_slack,basis,cols,is_mip || !prob->settings.verbose?-2:2,obj_ct);
if (is_inf(optimum))
return _LP_UNBOUNDED; // the solution is unbounded
if (pass==1) {
opt1=optimum;
cuts0=prob->stats.cuts_applied;
}
else if (!is_zero(opt1,prob->ctx))
imp=((opt1-optimum)/_abs(opt1,prob->ctx)).to_double(prob->ctx)*100;
// get the solution
solution=vecteur(ncols+nrows,0);
for (int i=0;i<nrows;++i) {
solution[basis[i]]=m[i]._VECTptr->back();
}
for (int j=solution.size();j-->0;) {
if (is_slack[j])
solution[j]=u[j]-solution[j];
}
if (prob->stats.cuts_applied-cuts0>=prob->settings.max_cuts)
break;
m.pop_back(); // remove the bottom row
// attempt to generate GMI cuts
cuts.clear();
for (int i=0;i<nrows;++i) {
int j0=basis[i];
vecteur eq(*m[i]._VECTptr);
gen f0=fracpart(eq.back()),fj,sp(0),eqnorm(0);
if (j0>=prob->nv() || !prob->variables[j0].is_integral() || is_zero(f0,prob->ctx) ||
min(f0,1-f0,prob->ctx).to_double(prob->ctx)<LP_MIN_AWAY)
continue;
eq.pop_back();
for (int k=0;k<nc;++k) {
int j=cols[k];
if (j<prob->nv() && prob->variables[j].is_integral()) {
fj=fracpart(eq[k]);
eq[k]=is_strictly_greater(fj,f0,prob->ctx)?(fj-1)/(f0-1):fj/f0;
} else eq[k]=eq[k]/(is_positive(eq[k],prob->ctx)?f0:f0-1);
if (j<prob->nv()) {
sp+=eq[k]*obj[j];
eqnorm+=eq[k]*eq[k];
}
}
if (is_zero__VECT(eq,prob->ctx))
continue; // not integer feasible anyway
if (std::abs(sp.to_double(prob->ctx)/(prob->objective_norm*std::sqrt(eqnorm.to_double(prob->ctx))))<LP_MIN_PARALLELISM)
continue; // this cut is not parallel enough to the objective
integralize(eq,prob->ctx);
mgn=_max(_abs(eq,prob->ctx),prob->ctx);
if (mgn.to_double(prob->ctx)>LP_MAX_MAGNITUDE)
continue; // this cut has too large coefficients
cuts.push_back(eq);
}
if (cuts.empty())
break;
// append GMI cuts to the simplex tableau and reoptimize
for (int cc=cuts.size();cc-->0;) {
insert_column(m,vecteur(nrows,0),-1);
l.push_back(0);
u.push_back(plus_inf);
is_slack.push_back(false);
obj.push_back(0);
cols.push_back(ncols++);
}
const_iterateur ct=cuts.begin(),itend=cuts.end();
for (;ct!=itend;++ct) {
int cc=ct-cuts.begin();
vecteur cut=mergevecteur(*(ct->_VECTptr),singleton(cuts.size(),cc,true));
cut.push_back(1);
m.push_back(cut);
++nrows;
if (++prob->stats.cuts_applied==prob->settings.max_cuts+cuts0)
break;
}
assert(ckmatrix(m));
}
pivot_row.clear();
prob->stats.cut_improvement+=imp;
// undo shifting variables
for (ints::const_iterator it=shifted.begin();it!=shifted.end();++it) {
solution[*it]+=l[*it];
}
// restore removed variables
while (!removed_cols.empty()) {
const vector<intgen> &rcol=removed_cols.top();
int v=rcol.front().first;
for (vector<intgen>::const_iterator it=rcol.begin();it!=rcol.end();++it) {
solution[v]+=(it==rcol.begin()?1:solution[it->first])*it->second;
}
removed_cols.pop();
if (is_strictly_greater(l[v],solution[v],prob->ctx) || is_strictly_greater(solution[v],u[v],prob->ctx))
return _LP_INFEASIBLE;
}
solution.resize(prob->nv());
// compute objective value
if (nc>0)
optimum=obj_ct-optimum;
else {
obj.resize(prob->nv());
optimum=prob->objective.second+scalarproduct(prob->objective.first,solution,prob->ctx);
}
// compute some useful data for branch&bound
opt_approx=optimum.to_double(prob->ctx);
infeas=0;
most_fractional=-1;
gen p,ifs,max_ifs(-1);
ints mf_cand;
for (int i=0;i<prob->nv();++i) {
if (!prob->variables[i].is_integral())
continue;
if (is_zero(p=fracpart(solution[i]),prob->ctx))
continue;
ifs=min(p,1-p,prob->ctx);
fractional_vars[i]=p.to_double(prob->ctx);
infeas+=ifs;
if (is_greater(ifs,max_ifs,prob->ctx)) {
if (is_strictly_greater(ifs,max_ifs,prob->ctx))
mf_cand.clear();
mf_cand.push_back(i);
max_ifs=ifs;
}
}
most_fractional=_rand(vector_int_2_vecteur(mf_cand),prob->ctx).val;
return _LP_SOLVED;
}
/*
* Return true iff a feasible solution sol can be obtained by rounding heuristic
*/
bool lp_node::rounding_heuristic(vecteur &sol,gen &cost) const {
map<int,bool> fv;
sol=solution;
for (map<int,double>::const_iterator it=fractional_vars.begin();it!=fractional_vars.end();++it) {
int i=it->first;
gen &s=sol[i];
s=_round(s,prob->ctx);
fv[i]=is_greater(s,solution[i],prob->ctx);
}
double viol;
int vc,j,last_j=-1,pass=0;
vecteur solc;
pair<int,double> vp,min_vp,cur_vp;
cur_vp=prob->constr.violated_constraints(sol,prob->ctx);
if (cur_vp.first>0) do {
solc=sol;
min_vp=cur_vp;
j=-1;
for (map<int,bool>::const_iterator it=fv.begin();it!=fv.end();++it) {
if (last_j==it->first)
continue;
solc[it->first]+=it->second?-1:1;
vp=prob->constr.violated_constraints(solc,prob->ctx);
if (vp<min_vp) {
j=it->first;
min_vp=vp;
}
solc[it->first]+=it->second?1:-1;
}
if (j<0)
break;
sol[j]+=fv[j]?-1:1;
fv[j]=!fv[j];
last_j=j;
} while ((cur_vp=min_vp).first>0);
if (cur_vp.first>0)
return false;
cost=scalarproduct(sol,prob->objective.first,prob->ctx)+prob->objective.second;
return true;
}
double lp_node::get_fractional_var(int index) const {
if (fractional_vars.find(index)!=fractional_vars.end())
return fractional_vars.at(index);
return 0;
}
void lp_node::assign(const lp_node &other) {
prob=other.prob;
depth=other.depth;
ranges=other.ranges;
optimum=other.optimum;
solution=other.solution;
opt_approx=other.opt_approx;
infeas=other.infeas;
most_fractional=other.most_fractional;
fractional_vars=other.fractional_vars;
removed_cols=other.removed_cols;
pivot_row.resize(other.pivot_row.size());
}
/*
* Return the fractional part of g, i.e. [g]=g-floor(g). It is always 0<=[g]<1.
*/
gen lp_node::fracpart(const gen &g) const {
return g-_floor(g,prob->ctx);
}
/*
* Initialize child node with copy of ranges and depth increased by one.
*/
void lp_node::init_child(lp_node &child) {
child.depth=depth+1;
child.ranges=this->ranges;
}
/*
* Return true iff this is a (mixed) integer problem.
*/
bool lp_problem::has_integral_variables() {
for (vector<lp_variable>::const_iterator it=variables.begin();it!=variables.end();++it) {
if (it->is_integral())
return true;
}
return false;
}
/*
* Return true iff the problem has floating-point coefficients.
*/
bool lp_problem::has_approx_coefficients() {
if (is_approx(objective.first) ||
objective.second.is_approx() ||
is_approx(constr.lhs) ||
is_approx(constr.rhs))
return true;
for (vector<lp_variable>::const_iterator it=variables.begin();it!=variables.end();++it) {
if (it->lb().is_approx() || it->ub().is_approx())
return true;
}
return false;
}
/*
* Set the objective function parameters.
*/
void lp_problem::set_objective(const vecteur &v,const gen &ft) {
objective.first=v;
objective.second=ft;
const_iterateur it=v.begin(),itend=v.end();
for (;it!=itend;++it) {
obj_approx.push_back(abs(*it,ctx).to_double(ctx));
}
}
/*
* Display a message.
*/
void lp_problem::message(const char *msg,int type) {
if (type==1 || settings.verbose) {
switch (type) {
case 0:
break;
case 1:
*logptr(ctx) << gettext("Error") << ": ";
break;
case 2:
*logptr(ctx) << gettext("Warning") << ": ";
}
*logptr(ctx) << gettext(msg) << "\n";
}
}
/*
* Duplicate the jth column by inserting a copy to the position j.
*/
void lp_constraints::duplicate_column(int index) {
assert(index<ncols());
vecteur col=jth_column(lhs,index);
insert_column(lhs,col,index);
}
/*
* Change signs of the coefficients in the jth column.
*/
void lp_constraints::negate_column(int index) {
for (int i=0;i<nrows();++i) {
vecteur &lh=*lhs[i]._VECTptr;
lh[index]=-lh[index];
}
}
/*
* Subtract v from rhs column of constraints.
*/
void lp_constraints::subtract_from_rhs_column(const vecteur &v) {
assert(int(v.size())==nrows());