-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest.cpp
More file actions
2267 lines (1885 loc) · 77.3 KB
/
Copy pathtest.cpp
File metadata and controls
2267 lines (1885 loc) · 77.3 KB
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
/*--------------------------------------------------------------------------*/
/*-------------------------- File test.cpp ---------------------------------*/
/*--------------------------------------------------------------------------*/
/** @file
* Main for testing LagBFunction
*
* Given three input parameters n, k and p:
*
* - k "random" PolyhedralFunction are constructed, each inside a
* PolyhedralFunctionBlock.
*
* - p random uncapacitated *max-cost* transportation problems
* (with *negative* costs) on complete bipartite n-graphs (n origins, n
* destinations) are constructed "by hand", each inside an AbstractBlock;
* the problems have balanced supply and demands, no directed cycles,
* and no capacities on a craftly chosen set of "crucial" arcs, so as to
* ensure that they surely attain finite optimal solutions.
*
* - The above p AbstractBlock are inserted as inner Block, each inside a
* LagBFunction. If the command line parameter dictates that the
* LagBFunction will actually be computed (the NDO Solver does not have
* the "easy components" feature), an appropriate TP Solver (typically
* an LP Solver) is registered to all the inner Block of the LagBFunction.
*
* - The above p LagBFunction are put each inside the FRealObjective of a
* new AbstractBlock, otherwise empty.
*
* - The k PolyhedralFunctionBlock (configured to use "natural"
* representation) and the p AbstractBlock are inserted inside a single
* AbstractBlock (NDOBlock), possibly with a linear function, to represent
* a problem of the form (for k = 1 and p = 2)
*
* min { l x + f(x) + max { ( B x + c_1 ) z_1 : E z_1 = b_1 , 0 <= z_1 }
* + max { ( B x + c_2 ) z_2 : E z_2 = b_2 , 0 <= z_2 } }
*
* Assuming that arcs are ordered lexicographically (first all the ones
* outgoing node 0, ordered by tail node, then all the ones outgoing node
* 1, ...), the matrix E has the form (ignoring bound constraints)
*
* n^2
* | e^T 0 ... 0 |
* n | 0 e^T ... 0 |
* | : : : |
* | 0 0 ... e^T |
* +-----------------+
* n | I I ... I |
*
* corresponding to constraints (with I = J = { 0 ... n - 1 })
*
* \sum_{ j \in J } z[ i ][ j ] == s[ i ] i \in I
*
* \sum_{ i \in I } z[ i ][ j ] == d[ j ] j \in J
*
* with s[] and d[] being the vectors of supplies and demand. The matrix
* B has the form
*
* n^2
* n | I I ... I |
*
* corresponding to the fact that the cost of arc ( i , j ) is
*
* c[ i ][ j ] + x[ j ]
*
* i.e., x[ j ] is added to the cost of all arcs ingoing destination j.
*
* - Some arc ( i , j ) will have a finite upper bound u[ i ][ j ] >= 0,
* with the value 0 being possible (basically, fixing the variable).
* However, this immediately creates the risk that the transportation
* problem is unfeasible, which we don't want to handle. To avoid that,
* the following cunning plan has been devised:
*
* = none of the arcs ( i , i ) will ever have finite upper bound;
*
* = the i-th supply and demand will be equal: s[ i ] = d[ i ].
*
* This guarantees that satisfying the i-th supply/demand pair via the
* direct arc ( i , j ) is always possible, albeit is may easily not be
* the best choice due to the costs being random. Note that one may have
* also put any finite upper bound >= s[ i ] = d[ i ] for this to work,
* but if bounds and capacities are randomly changed then one should be
* careful to guarantee that this always holds; by not having the bound
* at all we guarantee that this can never be a problem, since we will
* never create a finite upper bound when an infinite one was (nor
* vice-versa, for that matter).
*
* - An appropriate NDO Solver is attached to NDOBlock; this can in general
* be any Solver capable of solving it, but some specific provisions
* are done for BundleSolver, in particular when very verbose log is
* activated.
*
* Then, an LP equivalent of NDOBlock is constructed into a different
* AbstractBlock (LPBlock) with the following steps:
*
* - The linear objective and the k PolyhedralFunctionBlock are just
* copied over, the latter using the R3Block.
*
* - For the p LagBFunction, an LP equivalent is constructed by the
* following derivation:
*
* min { l x + f(x) + max { ( B x + c_1 ) z_1 : E z_1 = b_1 , 0 <= z_1 }
* + max { ( B x + c_2 ) z_2 : E z_2 = b_2 , 0 <= z_2 }
* } =
*
* min { l x + f(x) + min { y_1 b_1 : y_1 E >= B x + c_1 }
* + min { y_2 b_2 : y_2 E >= B x + c_2 } } =
*
* min { l x + f(x) + y_1 b_1 + y_2 b_2 :
* y_1 E >= B x + c_1 , y_2 E >= B x + c_2 }
*
* Since the transpose of E has the form
*
* n n
* | e 0 ... 0 | I |
* n^2 | 0 e ... 0 | I |
* | : : : | : |
* | 0 0 ... e | I |
*
* this corresponds to variables yo[ i ] and yd[ j ] for each origin and
* destination, with costs s[ i ] and d[ j ] respectively, as well as
* constraints
*
* ys[ i ] + yd[ j ] - x[ j ] >= c[ i ][ j ]
*
* for all i \in I and j \in J. This works if the variable z[ i ][ j ] has
* *no* finite bound; if, instead, the constraint
*
* z[ i ][ j ] <= u[ i ][ j ]
*
* is present (with u[ i ][ j ] = 0 possible), then it has a dual variable
* w[ i ][ j ]; this means that a term u[ i ][ j ] * w[ i ][ j ] is added
* to the objective function, and that the constraint becomes
*
* ys[ i ] + yd[ j ] + w[ i ][ j ] - x[ j ] >= c[ i ][ j ]
*
* w[ i ][ j ] >= 0
*
* All this, however, is only correct for the convex case; in the concave
* one, the problem is rather
*
* max { l x + f(x) + min { ( B x + c_1 ) z_1 : E z_1 = b_1 , 0 <= z_1 }
* + min { ( B x + c_2 ) z_2 : E z_2 = b_2 , 0 <= z_2 } }
* yelding
*
* max { l x + f(x) + y_1 b_1 + y_2 b_2 :
* y_1 E <= B x + c_1 , y_2 E <= B x + c_2 }
*
* and therefore the constraints are
*
* ys[ i ] + yd[ j ] - w[ i ][ j ] - x[ j ] <= c[ i ][ j ]
*
* w[ i ][ j ] >= 0
*
* assuming u[ i ][ j ] is finite, else without the "- w[ i ][ j ]" term
* and the w[ i ][ j ] variable; note having put a "-" to keep w[ i ][ j ]
* non-negative, since the natural sign of the dual variable of a <=
* constraint in a minimization LP is <= 0. However, this means that the
* corresponding term in the objective, that would ordinarily be
*
* + u[ i ][ j ] * w[ i ][ j ]
*
* must then become
*
* - u[ i ][ j ] * w[ i ][ j ]
*
* because w[ i ][ j ] has changed sign (w[ i ][ j ] ==> - w[ i ][ j ]).
*
* - The variables ys[ i ] and yd[ j ], the objective function and the
* constraints (linking them with x[]) are constructed manually into an
* AbstractBlock for each p.
*
* - A LPSolver is attached to this AbstractBlock
*
* The PolyhedralFunction and/or the costs and demands (not supplies) of the
* uncapacitated transportation problems are then repeatedly randomly
* modified "in the same way", and re-solved several times; results of the
* two solvers are compared.
*
* \author Antonio Frangioni \n
* Dipartimento di Informatica \n
* Universita' di Pisa \n
*
* \copyright © by Antonio Frangioni
*/
/*--------------------------------------------------------------------------*/
/*-------------------------------- MACROS ----------------------------------*/
/*--------------------------------------------------------------------------*/
#define LOG_LEVEL 0
// 0 = only pass/fail
// 1 = result of each test
// 2 = + solver log
// 3 = + save LP file
// 4 = + save every LP for every iteration
// 5 = + print data
#if( LOG_LEVEL >= 1 )
#define LOG1( x ) cout << x
#define CLOG1( y , x ) if( y ) cout << x
#if( LOG_LEVEL >= 2 )
#define LOG_ON_COUT 1
// if nonzero, the NDO Solver log is sent on cout rather than on a file
#endif
#else
#define LOG1( x )
#define CLOG1( y , x )
#endif
/*--------------------------------------------------------------------------*/
// if HAVE_CONSTRAINTS == 1, then about 50% of the variables will have a
// non-negativity constraint implemented via ColVariable::is_positive()
// if HAVE_CONSTRAINTS == 2, then about 50% of the variables will have
// bound constraints; of these, 33% will only have 0 lower bound, 33% will
// only have random upper bound, and the rest will have both. of the
// remaining 50% of the variables, another 50% will have a non-negativity
// constraint implemented via ColVariable::is_positive()
#define HAVE_CONSTRAINTS 2
/*--------------------------------------------------------------------------*/
// if nonzero, the Solver attached to the NDOBlock is detached and re-attached
// to it at all iterations
#define DETACH_NDO 0
// if nonzero, the Solver attached to the LPBlock is detached and re-attached
// to it at all iterations
#define DETACH_LP 0
/*--------------------------------------------------------------------------*/
// if nonzero, the two Block are not solved at every round of changes, but
// only every SKIP_BEAT + 1 rounds. this allows changes to accumulate, and
// therefore puts more pressure on the Modification handling of the Solver
// (in case this tries to do "smart" things rather than dumbly processing
// each one in turn)
//
// note that the number of rounds of changes is them multiplied by
// SKIP_BEAT + 1, so that the input parameter still dictates the number of
// compute() calls per (Solver per) Block
#define SKIP_BEAT 3
/*--------------------------------------------------------------------------*/
#define USECOLORS 1
#if( USECOLORS )
#define RED( x ) "\x1B[31m" #x "\033[0m"
#define GREEN( x ) "\x1B[32m" #x "\033[0m"
#else
#define RED( x ) #x
#define GREEN( x ) #x
#endif
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
// if 1, the w variables are dynamic
#define DYNAMIC_w 0
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
// if 1, the bc constraints are dynamic
#define DYNAMIC_bc 0
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
// if 1, half of the variables are dynamic
#define DYNAMIC_VARS 0
/*--------------------------------------------------------------------------*/
/*------------------------------ INCLUDES ----------------------------------*/
/*--------------------------------------------------------------------------*/
#include <chrono>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <random>
#include "MILPSolver.h"
#include "common_utils.h"
#include "LagBFunction.h"
#include "PolyhedralFunctionBlock.h"
#include "UpdateSolver.h"
/*--------------------------------------------------------------------------*/
/*-------------------------------- USING -----------------------------------*/
/*--------------------------------------------------------------------------*/
using namespace std;
using namespace SMSpp_di_unipi_it;
/*--------------------------------------------------------------------------*/
/*-------------------------------- TYPES -----------------------------------*/
/*--------------------------------------------------------------------------*/
using Index = Block::Index;
using Range = Block::Range;
using Subset = Block::Subset;
using FunctionValue = Function::FunctionValue;
using c_FunctionValue = Function::c_FunctionValue;
using MultiVector = PolyhedralFunction::MultiVector;
using RealVector = PolyhedralFunction::RealVector;
using VarVector = PolyhedralFunction::VarVector;
using v_coeff_pair = LinearFunction::v_coeff_pair;
using p_AB = AbstractBlock *;
using p_PFB = PolyhedralFunctionBlock *;
using p_LF = LinearFunction *;
using p_PF = PolyhedralFunction *;
using p_LBF = LagBFunction *;
/*--------------------------------------------------------------------------*/
/*------------------------------- CONSTANTS --------------------------------*/
/*--------------------------------------------------------------------------*/
const double scale = 10;
const char * const logF = "log.bn";
c_FunctionValue INF = SMSpp_di_unipi_it::Inf< FunctionValue >();
/*--------------------------------------------------------------------------*/
/*------------------------------- GLOBALS ----------------------------------*/
/*--------------------------------------------------------------------------*/
p_AB LPBlock; // the "partially dualised" LP representaion
p_AB NDOBlock; // the "natural" NDO representation
bool convex = true; // true if everything is convex
double bound = 1000; // a tentative bound to detect unbounded instances
FunctionValue BND; // the bound in the PolyhedralFunction (if any)
Index nvar = 10; // number of variables
#if DYNAMIC_VARS > 0
Index nsvar; // number of static variables
Index ndvar; // number of dynamic variables
#else
#define nsvar nvar // all variables are static
#endif
std::mt19937 rg; // base random generator
std::uniform_real_distribution<> dis( 0.0 , 1.0 );
MultiVector A; // rows
RealVector b; // constants
MultiVector C; // arc costs
MultiVector U; // arc capacities
RealVector s; // supplies == demands
/*--------------------------------------------------------------------------*/
/*------------------------------ FUNCTIONS ---------------------------------*/
/*--------------------------------------------------------------------------*/
// convex ==> minimize ==> negative numbers
static double rs( double x ) { return( convex ? -x : x ); }
/*--------------------------------------------------------------------------*/
static double rndfctr( void )
{
// a random number between 0.5 and 2, with 50% probability of being < 1
double fctr = dis( rg ) - 0.5;
return( fctr < 0 ? - fctr : fctr * 4 );
}
/*--------------------------------------------------------------------------*/
static void GenerateAi( RealVector & Ai , Index nc )
{
Ai.resize( nc );
for( auto & aij : Ai )
aij = scale * ( 2 * dis( rg ) - 1 );
}
/*--------------------------------------------------------------------------*/
static void GenerateA( Index nr , Index nc )
{
A.resize( nr );
for( auto & Ai : A )
GenerateAi( Ai , nc );
}
/*--------------------------------------------------------------------------*/
static void Generateb( Index nr )
{
b.resize( nr );
for( auto & bj : b )
bj = scale * nvar * ( 2 * dis( rg ) - 1 ) / 4;
}
/*--------------------------------------------------------------------------*/
static void GenerateAb( Index nr , Index nc )
{
// rationale: the solution x^* will be more or less the solution of some
// square sub-system A_B x = b_B. We want x^* to be "well scaled", i.e.,
// the entries to be ~= 1 (in absolute value). The average of each row A_i
// is 0, the maximum (and minimum) expected value is something like
// scale * nvar / 2. So we take each b_j in +- scale * nvar / 4
GenerateA( nr , nc );
Generateb( nr );
}
/*--------------------------------------------------------------------------*/
static void GenerateBND( void )
{
// rationale: we expect the solution x^* to have entries ~= 1 (in absolute
// value, and the coefficients of A are <= scale (in absolute value), so
// the LHS should be at most around - scale * nvar; the RHS can add it
// a further - scale * nvar / 4, so we expect - (5/4) * scale * nvar to
// be a "natural" LB. We therefore set the LB to a mean of 1/2 of that
// (tight) 33% of the time, a mean of 2 times that (loose) 33% of the time,
// and -INF the rest
if( dis( rg ) <= 0.333 ) { // "tight" bound
BND = rs( dis( rg ) * 5 * scale * nvar / 4 );
return;
}
if( dis( rg ) <= 0.333 ) { // "loose" bound
BND = rs( dis( rg ) * 5 * scale * nvar );
return;
}
BND = INF;
}
/*--------------------------------------------------------------------------*/
static Index GenerateCi( RealVector & Ci )
{
// 10% of costs are zero, the rest random between:
// -10 and 0 in the convex case (where the problem is max)
// 0 and 10 in the concave case (where the problem is min)
Index nzc = 0;
if( convex ) {
for( auto & cij : Ci )
if( dis( rg ) < 0.1 )
cij = 0;
else {
cij = - 10 * dis( rg );
++nzc;
}
}
else
for( auto & cij : Ci )
if( dis( rg ) < 0.1 )
cij = 0;
else {
cij = 10 * dis( rg );
++nzc;
}
return( nzc );
}
/*--------------------------------------------------------------------------*/
static Index GenerateCosts( void )
{
Index nzc = 0;
for( auto & Ci : C )
nzc += GenerateCi( Ci );
return( nzc );
}
/*--------------------------------------------------------------------------*/
static void GenerateSupplies( void )
{
s.resize( nvar );
for( auto & si : s )
si = 10 * dis( rg );
}
/*--------------------------------------------------------------------------*/
static void GenerateCapacities( RealVector & Ui )
{
// in 85% of the cases the capacity is random between 0 and 5 (to make it
// hopefully "byte" over a demand between 0 and 10), in the remaining 15%
// of the cases it is 0 (which "surely bytes")
for( auto & uij : Ui )
uij = dis( rg ) < 0.15 ? 0 : 5 * dis( rg );
}
/*--------------------------------------------------------------------------*/
static Index GenerateCapacities( void )
{
// in 30% and in all arcs ( i , i ) the capacity is infinite, otherwise as
// in GenerateCapacities( Ui )
Index nic = 0;
for( Index i = 0 ; i < nvar ; ++i )
for( Index j = 0 ; j < nvar ; ++j )
if( ( i == j ) || ( dis( rg ) < 0.3 ) )
U[ i ][ j ] = INF;
else {
U[ i ][ j ] = dis( rg ) < 0.15 ? 0 : 5 * dis( rg );
++nic;
}
return( nic );
}
/*--------------------------------------------------------------------------*/
static Subset GenerateSubset( Index m , Index k )
{
// generate a sorted random k-vector of unique integers in 0 ... m - 1
Subset rnd( m );
std::iota( rnd.begin() , rnd.end() , 0 );
std::shuffle( rnd.begin() , rnd.end() , rg );
rnd.resize( k );
sort( rnd.begin() , rnd.end() );
return( std::move( rnd ) );
}
/*--------------------------------------------------------------------------*/
static void printAb( const MultiVector & tA , const RealVector & tb ,
double bound )
{
cout << "n = " << nvar << ", m = " << tA.size();
if( convex )
cout << " (convex)";
else
cout << " (concave)";
if( std::abs( bound ) == INF )
cout << " (no bound)" << endl;
else
cout << ", bound = " << bound << endl;
for( Index i = 0 ; i < tA.size() ; ++i ) {
cout << "A[ " << i << " ] = [ ";
for( Index j = 0 ; j < nvar ; ++j )
cout << tA[ i ][ j ] << " ";
cout << "], b[ " << i << " ] = " << tb[ i ] << endl;
}
}
/*--------------------------------------------------------------------------*/
static void printC( void )
{
for( Index i = 0 ; i < nvar ; ++i ) {
cout << "C[ " << i << " ] = [ ";
for( Index j = 0 ; j < nvar ; ++j )
cout << C[ i ][ j ] << " ";
cout << "]" << endl;
}
}
/*--------------------------------------------------------------------------*/
static void printU( void )
{
for( Index i = 0 ; i < nvar ; ++i ) {
cout << "U[ " << i << " ] = [ ";
for( Index j = 0 ; j < nvar ; ++j )
if( U[ i ][ j ] == INF )
cout << "INF ";
else
cout << U[ i ][ j ] << " ";
cout << "]" << endl;
}
}
/*--------------------------------------------------------------------------*/
static void printT( void )
{
cout << "s = [ ";
for( Index j = 0 ; j < nvar ; ++j )
cout << s[ j ] << " ";
cout << "]" << endl;
printC();
printU();
}
/*--------------------------------------------------------------------------*/
static void ConstructObj( p_AB AB )
{
// construct the Linear Objective (FRealObjective with a LinearFunction
// inside) in the given AbstractBlock on the "x" static Variable; this is
// only called if nf < 0
auto x = AB->get_static_variable_v< ColVariable >( "x" );
#if DYNAMIC_VARS > 0
auto xd = AB->get_dynamic_variable< ColVariable >( "x" );
#endif
v_coeff_pair cp( nvar );
Index i = 0;
// static x
for( ; i < nsvar ; ++i )
cp[ i ] = std::make_pair( &((*x)[ i ] ) , A[ 0 ][ i ] );
#if DYNAMIC_VARS > 0
// dynamic x
auto xdit = xd.begin();
for( ; i < nvar ; ++i , ++xdit )
cp[ j ] = std::make_pair( &(*xdit) , A[ 0 ][ i ] );
#endif
auto obj = new FRealObjective( AB , new LinearFunction( std::move( cp ) ) );
obj->set_sense( convex ? Objective::eMin : Objective::eMax , eNoMod );
AB->set_objective( obj , eNoMod );
}
/*--------------------------------------------------------------------------*/
static bool SolveBoth( void )
{
try {
// solve the LPBlock- - - - - - - - - - - - - - - - - - - - - - - - - - - -
Solver * slvrLP = ( LPBlock->get_registered_solvers() ).front();
#if DETACH_LP
LPBlock->unregister_Solver( slvrLP );
LPBlock->register_Solver( slvrLP , true ); // push it to the front
#endif
auto startLP = std::chrono::system_clock::now();
int rtrnLP = slvrLP->compute( false );
auto endLP = std::chrono::system_clock::now();
double tLP = std::chrono::duration< double >( endLP - startLP ).count();
bool hsLP = ( ( rtrnLP >= Solver::kOK ) && ( rtrnLP < Solver::kError ) )
|| ( rtrnLP == Solver::kLowPrecision );
double foLP = hsLP ? ( convex ? slvrLP->get_ub() : slvrLP->get_lb() )
: ( convex ? INF : -INF );
// solve the NODBlock - - - - - - - - - - - - - - - - - - - - - - - - - - -
Solver * slvrNDO = ( NDOBlock->get_registered_solvers() ).front();
#if DETACH_NDO
NDOBlock->unregister_Solver( slvrNDO );
NDOBlock->register_Solver( slvrNDO );
#endif
auto startNDO = std::chrono::system_clock::now();
int rtrnNDO = slvrNDO->compute( false );
auto endNDO = std::chrono::system_clock::now();
double tNDO = std::chrono::duration< double >( endNDO - startNDO ).count();
bool hsNDO = ( ( rtrnNDO >= Solver::kOK ) && ( rtrnNDO < Solver::kError ) )
|| ( rtrnNDO == Solver::kLowPrecision );
double foNDO = hsNDO ? ( convex ? slvrNDO->get_ub() : slvrNDO->get_lb() )
: ( convex ? INF : -INF );
// bespoke verdict (Pattern A, LPBlock vs NDOBlock; keeps the conditional
// valid-bound doubling), then the unified per-instance line - - - - - - - -
bool ok = false;
std::string verdict = "KO";
bool decided = false;
if( hsLP && hsNDO && ( abs( foLP - foNDO ) <= 2e-7 *
max( double( 1 ) , abs( max( foLP , foNDO ) ) ) ) ) {
ok = true; verdict = "OK(f)"; decided = true;
}
if( ( ! decided ) && hsLP && ( rtrnNDO == Solver::kUnbounded ) ) {
/* Weird case: the LP found an optimal solution but the NDO declared the
* problem unbounded below, because the tentative lb is too high; if so,
* accept the run and lower (double) the bound. */
if( ( convex && ( foNDO <= bound * ( 1 + 1e-9 ) ) ) ||
( ( ! convex ) && ( foNDO >= bound * ( 1 + 1e-9 ) ) ) ) {
bound *= 2;
if( convex )
NDOBlock->set_valid_lower_bound( -bound );
else
NDOBlock->set_valid_upper_bound( bound );
ok = true; verdict = "OK(?bound?)"; decided = true;
}
}
if( ( ! decided ) && ( rtrnLP == Solver::kInfeasible ) &&
( rtrnNDO == Solver::kInfeasible ) ) {
ok = true; verdict = "OK(?e?)"; decided = true;
}
if( ( ! decided ) && ( rtrnLP == Solver::kUnbounded ) &&
( rtrnNDO == Solver::kUnbounded ) ) {
ok = true; verdict = "OK(u)"; decided = true;
}
auto tok = []( bool hs , int rtrn , double fo ) -> std::string {
if( hs ) return( fmt_obj( fo ) );
if( rtrn == Solver::kInfeasible ) return( "Unfeas" );
if( rtrn == Solver::kUnbounded ) return( "Unbounded" );
return( "Error!" );
};
print_instance_line(
{ tLP , tNDO } ,
{ tok( hsLP , rtrnLP , foLP ) , tok( hsNDO , rtrnNDO , foNDO ) } ,
std::numeric_limits< double >::quiet_NaN() , verdict );
return( ok );
}
catch( exception &e ) {
cerr << e.what() << endl;
exit( 1 );
}
catch(...) {
cerr << "Error: unknown exception thrown" << endl;
exit( 1 );
}
} // end( SolveBoth )
/*--------------------------------------------------------------------------*/
int main( int argc , char **argv )
{
// override the default terminate handler to print the exception message
std::set_terminate( smspp_terminate );
// reading command line parameters - - - - - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
assert( SKIP_BEAT >= 0 );
long int seed = 0;
Index wchg = 511;
int nf = 1;
int nt = 1;
double dens = 3;
Index n_repeat = 40;
Index n_change = 10;
double p_change = 0.5;
switch( argc ) {
case( 10 ): Str2Sthg( argv[ 9 ] , p_change );
case( 9 ): Str2Sthg( argv[ 8 ] , n_change );
case( 8 ): Str2Sthg( argv[ 7 ] , n_repeat );
case( 7 ): Str2Sthg( argv[ 6 ] , dens );
case( 6 ): Str2Sthg( argv[ 5 ] , nt );
case( 5 ): Str2Sthg( argv[ 4 ] , nf );
case( 4 ): Str2Sthg( argv[ 3 ] , nvar );
case( 3 ): Str2Sthg( argv[ 2 ] , wchg );
case( 2 ): Str2Sthg( argv[ 1 ] , seed );
break;
default: cerr << "Usage: " << argv[ 0 ] <<
" seed [wchg nvar #nf #nt dens #rounds #chng %chng]"
<< endl <<
" wchg: what to change, coded bit-wise [511]"
<< endl <<
" 0 = add rows, 1 = delete rows "
<< endl <<
" 2 = modify rows, 3 = modify constants"
<< endl <<
" 4 = change global lower/upper bound"
<< endl <<
" 5 = modify costs, 6 = modify demands"
<< endl <<
" 7 = modify flow bounds"
<< endl <<
" 8 = change linear objective"
<< endl <<
" 9 = each LagBFunction dualises a random subset "
"(exercises sparse Lambda)"
<< endl <<
" 10 = remove one dual_pair from a single LagBFunction "
"(naked, not GroupMod;"
<< endl <<
" exercises dense->sparse auto-promotion + "
"per-Function Mod dispatch)"
#if DYNAMIC_VARS > 0
<< endl <<
" (with DYNAMIC_VARS, bit 7 = add variables, "
"bit 8 = delete variables)"
#endif
<< endl <<
" nvar: number of variables [10]"
<< endl <<
" |#nf|: number of PolyFunction (< 0: linear function) [1]"
<< endl <<
" |#nt|: number of transportation (< 0: easy comp.) [1]"
<< endl <<
" dens: rows / variables [3]"
<< endl <<
" #rounds: how many iterations [40]"
<< endl <<
" #chng: number of changes [10]"
<< endl <<
" %chng: probability of changing [0.5]"
<< endl;
return( 1 );
}
if( nvar < 1 ) {
cout << "error: nvar too small";
exit( 1 );
}
bool HasLin = ( nf < 0 );
nf = std::abs( nf );
bool HasEasy = ( nt < 0 );
nt = std::abs( nt );
// wchg bit 9: each LagBFunction dualises only a random subset (about
// half) of the NDOBlock x variables, instead of all of them. Different
// LagBFunction get independent random subsets, so the union LamVcblr
// covers all nvar x's but each v_c05f[ h ] exposes a strict subset (in
// ascending order, as required by MPSolver::SetItemBse), which makes
// the BundleSolver::set_Block auto-detect engage the sparse Lambda
// path. To keep the LPBlock-vs-NDOBlock comparison mathematically
// sound, the corresponding (i,j) constraint in the LPBlock
// transportation block omits the xLP[ j ] term whenever j is not in
// the subset: this mirrors the fact that x_NDO[ j ] does not shift
// column j's cost in the inner LP of that LagBFunction.
bool sparse_subset = ( wchg & ( 1 << 9 ) );
if( ( ! nf ) && ( ! nt ) ) {
cout << "error: no sub-Block";
exit( 1 );
}
#if DYNAMIC_VARS > 0
nsvar = nvar / 2; // half of the variables are dynamic
ndvar = nvar - nsvar; // the other half are static
#endif
Index m = nvar * dens; // number of rows
if( m < 1 ) {
cout << "error: dens too small";
exit( 1 );
}
// adjust the bound depending on the number of components
bound *= std::max( 1 , std::abs( nf ) );
rg.seed( seed ); // seed the pseudo-random number generator
cout.setf( ios::scientific, ios::floatfield );
cout << setprecision( 10 );
// construction and loading of the objects - - - - - - - - - - - - - - - - -
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// choosing whether convex or concave: toss a(n unbiased, two-sided) coin
convex = ( dis( rg ) < 0.5 );
LPBlock = new AbstractBlock();
LPBlock->set_name( "LPBlock" );
NDOBlock = new AbstractBlock();
NDOBlock->set_name( "NDOBlock" );
// immediately set the global conditional bound on NDOBlock
if( convex )
NDOBlock->set_valid_lower_bound( -bound , true );
else
NDOBlock->set_valid_upper_bound( bound , true );
{
// ensure all original pointers go out of scope immediately after that
// the construction has finished
// construct the Variable in LPBlock
auto xLP = new std::vector< ColVariable >( nsvar );
VarVector LPvars( nvar );
auto vit = LPvars.begin();
for( auto & xi : *xLP )
*(vit++) = & xi;
#if DYNAMIC_VARS > 0
auto xLPd = new std::list< ColVariable >( ndvar );
for( auto & xi : *xLPd )
*(vit++) = & xi;
#endif
// now set the Variable in LPBlock
LPBlock->add_static_variable( *xLP , "x" );
#if DYNAMIC_VARS > 0
LPBlock->add_dynamic_variable( *xLPd , "d" );
#endif
// construct the Variable in NDOBlock
auto xNDO = new std::vector< ColVariable >( nsvar );
VarVector NDOvars( nvar );
vit = NDOvars.begin();
for( auto & xi : *xNDO )
*(vit++) = & xi;
#if DYNAMIC_VARS > 0
auto xNDOd = new std::list< ColVariable >( ndvar );
for( auto & xi : *xNDOd )
*(vit++) = & xi;
#endif
// now set the Variable in NDOBlock
NDOBlock->add_static_variable( *xNDO , "x" );
#if DYNAMIC_VARS > 0
NDOBlock->add_dynamic_variable( *xNDOd , "x" );
#endif
// construct the linear objective (in both)
if( HasLin ) { // if any
A.resize( 1 );
GenerateAi( A[ 0 ] , nvar );
ConstructObj( LPBlock );
ConstructObj( NDOBlock );
#if( LOG_LEVEL >= 5 )
cout << "L = [ ";
for( Index j = 0 ; j < nvar ; ++j )
cout << A[ 0 ][ j ] << " ";
cout << "]" << endl;
#endif
}
// construct the PolyhedralFunctionBlocks (in both) - - - - - - - - - - - -
for( Index k = 0 ; k < Index( nf ) ; ++k ) {
// construct the PolyhedralFunctionBlock
auto PFBLPk = new PolyhedralFunctionBlock( LPBlock );
PFBLPk->set_name( "LP-PFB_" + std::to_string( k ) );
// pass it to LPBlock
LPBlock->add_nested_Block( PFBLPk );
// construct the m x nvar matrix A, the m-vector b, and the bound
GenerateAb( m , nvar );
GenerateBND();
#if( LOG_LEVEL >= 5 )
cout << "PF[ " << k << " ] = " << endl;
printAb( A , b , rs( BND ) );
#endif
// pass all the data of the PolyhedralFunction
PFBLPk->get_PolyhedralFunction().set_PolyhedralFunction( std::move( A ) ,
std::move( b ) ,
rs( BND ) ,
convex );
// copy the PolyhedralFunctionBlock
auto PFBNDOk = static_cast< p_PFB >(
PFBLPk->get_R3_Block( nullptr , nullptr , NDOBlock ) );
PFBNDOk->set_name( "NDO-PFB_" + std::to_string( k ) );
// pass it to NDOBlock
NDOBlock->add_nested_Block( PFBNDOk );
// pass the Variable to the PolyhedralFunction in LP (copy the vector)
PFBLPk->get_PolyhedralFunction().set_variables( VarVector( LPvars ) );
// pass the Variable to the PolyhedralFunction in NDO (copy the vector)
PFBNDOk->get_PolyhedralFunction().set_variables( VarVector( NDOvars ) );
// configure the PolyhedralFunctionBlock in LPBlock to use the
// "linearised" representation
auto bc = new BlockConfig();
bc->f_static_variables_Configuration = new SimpleConfiguration< int >( 1 );
PFBLPk->set_BlockConfig( bc );
} // end( for( k ) )
// now construct the transportation problems (and their duals)- - - - - - -
// first allocate C and U memory once and for all
C.resize( nvar );
for( auto & Ci : C )
Ci.resize( nvar );
U.resize( nvar );
for( auto & Ui : U )
Ui.resize( nvar );
// if LagBFunctions are treated as not-easy, load once and for all the
// ComputeConfig containing the BlockSolverConfig that will be used to
// have the appropriate Solver attached to them
auto cfg = Configuration::deserialize( ( nt && ( ! HasEasy ) ) ?
"LBFTPPar-Hard.txt" :
"LBFTPPar-Easy.txt" );
auto LBFC = dynamic_cast< ComputeConfig * >( cfg );
if( ! LBFC ) {
cout << "error loading Configuration file for "
<< ( ( nt && ( ! HasEasy ) ) ? "hard" : "easy" )
<< " LagBFunction" << endl;
delete( cfg );
exit( 1 );
}