Repository navigation
Expand file tree
/
Copy pathtest.cpp
More file actions
2807 lines (2364 loc) · 98.7 KB
/
Copy pathtest.cpp
File metadata and controls
2807 lines (2364 loc) · 98.7 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 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
/*- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -*/
// 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 <algorithm>
#include <chrono>
#include <cmath>
#include <fstream>
#include <sstream>
#include <iomanip>
#include <limits>
#include <map>
#include <memory>
#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
int SizeEasy = 0; // how an easy transportation problem is sized
bool DetachNDO = false; // if the Solver of NDOBlock are detached and
// re-attached to it before each compute()
/* The last command line parameter, size, says how the inner Block of an easy
* LagBFunction carries the size Variable that the dual master problem of
* BundleSolver scales it with [see MasterProblemBlock::configure()]: in the
* dual of the level and doubly stabilized master problems, as in that of any
* master problem with a global lower bound, the mass lambda of the lower
* model may differ from one, and the feasible set of each easy component has
* to be scaled with it. With a size Variable tau the balance and capacity
* constraints read
*
* sum_j f_ij - s_i tau = 0,
* sum_i f_ij - s_j tau = 0,
* f_ij - U_ij tau <= 0,
*
* and tau is
*
* - 0: absent, the balances keep their right-hand sides and the capacities
* are BoxConstraint; the inner Block is a plain AbstractBlock, which takes
* no size Variable, so that lambda is fixed to one, unless bit 5 of
* intDoEasy has the master put in its place a copy of it sized by lambda
* [see AbstractBlock::set_size_variable()], in which the master writes
* the changes the tester makes to it;
*
* - 1: a nonnegative ColVariable of the inner Block, declared with
* Block::set_owned_size_variable() and tied to lambda by the master;
*
* - 2: a Variable of the master given to the inner Block, a
* SizedTransportBlock, by Block::set_size_variable(), which writes it into
* the rows above as it gets it; the capacities are FRowConstraint, so that
* they can take it.
*
* Whether the master uses the size Variable, or the copy, is up to intDoEasy
* of the BundleSolver [see BundleSolver::intDoEasy], and the stabilization
* is up to its ComputeConfig. With a hard LagBFunction the parameter is
* ignored.
* The changes of supplies and capacities are written in the coefficients of
* tau when it is there, in the right-hand sides otherwise. */
/*--------------------------------------------------------------------------*/
/*------------------------------- CLASSES ----------------------------------*/
/*--------------------------------------------------------------------------*/
/// the transportation problem of an easy LagBFunction that takes its size
/** An AbstractBlock with the transportation problem built by main(), whose
* balances "sc" and "dc" and finite capacities "bc" are all FRowConstraint,
* which takes the size Variable of its father [see
* Block::set_size_variable()]: each of those rows, whose finite sides are
* all equal to some c, gets the Variable with coefficient - c, and the
* finite sides go to zero. The supplies and capacities are then the
* coefficients of the Variable, which is how main() changes them [see
* size_variable_of()]. It takes a single Variable, and the same one again
* changes nothing; the rows that are there are rewritten, at any time, and
* \p issueAMod says which Modification are issued. */
class SizedTransportBlock : public AbstractBlock
{
public:
bool set_size_variable( Variable * size_var ,
c_ModParam issueAMod = eNoBlck ) override {
auto tau = dynamic_cast< ColVariable * >( size_var );
if( ( ! tau ) || ( f_size && ( f_size != tau ) ) )
return( false );
if( f_size ) // there already
return( true );
f_size = tau;
auto scale = [ & ]( FRowConstraint & row ) {
const double c = std::isfinite( row.get_rhs() ) ? row.get_rhs()
: row.get_lhs();
static_cast< p_LF >( row.get_function() )->add_variable( tau , - c ,
issueAMod );
// the row registers itself with the Variable only when it receives the
// Modification, which issueAMod may not ask for
const auto & act = tau->active_stuff();
ThinVarDepInterface * me = & row;
if( ! std::binary_search( act.begin() , act.end() , me ) )
tau->add_active( me );
if( row.get_lhs() == row.get_rhs() )
row.set_both( 0.0 , issueAMod );
else
if( std::isfinite( row.get_rhs() ) )
row.set_rhs( 0.0 , issueAMod );
else
row.set_lhs( 0.0 , issueAMod );
};
for( auto & row : *get_static_constraint_v< FRowConstraint >( "sc" ) )
scale( row );
for( auto & row : *get_static_constraint_v< FRowConstraint >( "dc" ) )
scale( row );
#if DYNAMIC_bc
if( auto bc = get_dynamic_constraint< FRowConstraint >( "bc" ) )
#else
if( auto bc = get_static_constraint_v< FRowConstraint >( "bc" ) )
#endif
for( auto & row : *bc )
scale( row );
return( true );
}
/// the size Variable this Block has taken, nullptr if none
[[nodiscard]] ColVariable * get_given_size_variable( void ) const {
return( f_size );
}
private:
ColVariable * f_size = nullptr; ///< the size Variable taken, if any
};
/*--------------------------------------------------------------------------*/
/*------------------------------ FUNCTIONS ---------------------------------*/
/*--------------------------------------------------------------------------*/
/// the size Variable the rows of the transportation problem \p tb carry
/** The one \p tb owns [see Block::get_size_variable()] or the one it has
* taken [see SizedTransportBlock], and nullptr if its rows carry none. */
static ColVariable * size_variable_of( Block * tb )
{
if( auto tau = tb->get_size_variable() )
return( static_cast< ColVariable * >( tau ) );
if( auto stb = dynamic_cast< SizedTransportBlock * >( tb ) )
return( stb->get_given_size_variable() );
return( nullptr );
}
/*--------------------------------------------------------------------------*/
// 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 );
}
/*--------------------------------------------------------------------------*/
/// the value of a LagBFunction in the current value of its Variable, by copy
/** Returns the value of \p lbf in the current value of the multipliers y
* without computing \p lbf, which is what a LagBFunction treated as easy
* needs: its inner Block has no Solver, the NDO Solver handling it exactly
* in its master, and computing it with a Solver lent for the purpose would
* put into the Objective of its inner Block the Variable it keeps aside,
* changing what the following rounds of changes pick. The inner Block is
* copied [see AbstractBlock::mirror()], the copy is given the Lagrangian
* objective c( x ) + < y , g( x ) > in the sense of the original, and the
* copy is solved with the Solver of TPPar.txt; the value is NaN if anything
* of this cannot be done. */
static double LBF_value_by_copy( LagBFunction * lbf )
{
const double NaN = std::numeric_limits< double >::quiet_NaN();
AbstractBlock copy;
copy.mirror( lbf->get_inner_block() );
if( ! copy.get_mirror_issues().empty() )
return( NaN );
// Evaluate the original transportation problem, irrespective of the
// size chosen for this component in the last master solution: the size
// Variable is fixed to 1 in the copy if it is a Variable of the inner
// Block, and otherwise, being shared by the copy, taken out of its rows
// with its coefficient moved into their sides
if( auto tau = size_variable_of( lbf->get_inner_block() ) ) {
if( auto tau_copy = copy.mirror_of( tau ) ) {
tau_copy->is_fixed( false , eNoMod );
tau_copy->set_value( 1.0 );
tau_copy->is_fixed( true , eNoMod );
}
else {
std::vector< FRowConstraint * > rows;
for( auto stuff : tau->active_stuff() )
if( auto row = dynamic_cast< FRowConstraint * >( stuff ) )
if( row->get_Block() == & copy )
rows.push_back( row );
for( auto row : rows ) {
auto lf = static_cast< p_LF >( row->get_function() );
const Index ti = lf->is_active( tau );
const double a = lf->get_coefficient( ti );
row->remove_variable( ti , eNoMod );
if( std::isfinite( row->get_lhs() ) )
row->set_lhs( row->get_lhs() - a , eNoMod );
if( std::isfinite( row->get_rhs() ) )
row->set_rhs( row->get_rhs() - a , eNoMod );
}
}
}
auto obj = copy.get_objective< FRealObjective >();
auto clf = obj ? dynamic_cast< LinearFunction * >( obj->get_function() )
: nullptr;
if( ! clf )
return( NaN );
// the Lagrangian costs: first the original costs of the Variable of the
// Objective, in their order, which are those the LagBFunction keeps [see
// LagBFunction::get_A_by_col()] and not those in the Objective, where a
// LagBFunction that has been computed has written its Lagrangian ones
LinearFunction::v_coeff_pair cost( clf->get_v_var() );
std::map< ColVariable * , Index > pos;
for( Index h = 0 ; h < cost.size() ; ++h ) {
auto col = lbf->get_A_by_col( copy.mirrored_of( cost[ h ].first ) );
if( ! col )
return( NaN );
cost[ h ].second = col->first;
pos[ cost[ h ].first ] = h;
}
double ct = clf->get_constant_term();
for( Index i = 0 ; i < lbf->get_num_active_var() ; ++i ) {
const double yi =
static_cast< ColVariable * >( lbf->get_active_var( i ) )->get_value();
auto gi = static_cast< LinearFunction * >( lbf->get_Lagrangian_term( i ) );
ct += yi * gi->get_constant_term();
for( const auto & [ xj , aij ] : gi->get_v_var() ) {
auto cj = copy.mirror_of( static_cast< ColVariable * >( xj ) );
if( ! cj )
return( NaN );
auto it = pos.find( cj );
if( it == pos.end() ) {
pos[ cj ] = cost.size();
cost.emplace_back( cj , yi * aij );
}
else
cost[ it->second ].second += yi * aij;
}
}
obj->set_function( new LinearFunction( std::move( cost ) , ct ) , eNoMod );
auto cfg = Configuration::deserialize( "TPPar.txt" );
auto tpc = dynamic_cast< BlockSolverConfig * >( cfg );
if( ! tpc ) {
delete( cfg );
return( NaN );
}
tpc->apply( & copy );
double value = NaN;
if( ! copy.get_registered_solvers().empty() ) {
auto slvr = copy.get_registered_solvers().front();
const int rtrn = slvr->compute( false );
if( ( rtrn >= Solver::kOK ) && ( rtrn < Solver::kError ) )
value = slvr->get_var_value();
}
tpc->clear(); // take the Solver away again
tpc->apply( & copy );
delete( tpc );
return( value );
}
/*--------------------------------------------------------------------------*/
/// the value of the objective of NDOBlock in the current values of x
/** A LagBFunction whose inner Block has a size variable or no Solver is
* valued by copy [see LBF_value_by_copy()], a PolyhedralFunctionBlock by
* computing its PolyhedralFunction, since it may have no Objective, and any
* other Function by computing it; a Block with no Objective, as NDOBlock
* without the linear function, gives nothing. A sized inner Block must be
* evaluated at unit size. */
static double NDO_value( void )
{
double value = 0;
if( auto obj = dynamic_cast< FRealObjective * >(
NDOBlock->get_objective() ) ) {
obj->compute();
value += obj->value();
}
for( Index b = 0 ; b < NDOBlock->get_number_nested_Blocks() ; ++b ) {
auto nb = NDOBlock->get_nested_Block( b );
if( auto pfb = dynamic_cast< p_PFB >( nb ) ) {
auto & pf = pfb->get_PolyhedralFunction();
pf.compute();
value += pf.get_value();
continue;
}
if( auto obj = dynamic_cast< FRealObjective * >( nb->get_objective() ) ) {
auto lbf = dynamic_cast< LagBFunction * >( obj->get_function() );
if( lbf && ( size_variable_of( lbf->get_inner_block() ) ||
lbf->get_inner_block()->get_registered_solvers().empty() ) )
value += LBF_value_by_copy( lbf );
else {
obj->compute();
value += obj->value();
}
}
}
return( value );
}
/*--------------------------------------------------------------------------*/
/// true if the objective of NDOBlock improves along the ray of the LP
/** Called when the LP Solver has proved the LP unbounded, this reads the
* unbounded direction it gives as the certificate and, from the point where
* the NDO Solver has stopped, moves x along it by two steps s and 2 s, with s
* large with respect to both the point and the direction: the objective of
* NDOBlock has to improve at both, as it does along a direction of recession
* of the LP, which is an exact reformulation of the NDO problem. A direction
* that does not move x says nothing about NDOBlock, and is not taken as an
* agreement. The values of the Variable of both Block are put back as they
* were, and a LagBFunction treated as easy is valued by copy [see
* NDO_value()]. */
static bool NDO_improves_along_LP_ray( Solver * slvrLP )
{
if( ! slvrLP->has_var_direction() )
return( false );
auto LPx = LPBlock->get_static_variable_v< ColVariable >( "x" );
auto NDOx = NDOBlock->get_static_variable_v< ColVariable >( "x" );
const Index n = LPx->size();
std::vector< double > x0( n );
double xn = 0;
for( Index i = 0 ; i < n ; ++i ) {
x0[ i ] = (*NDOx)[ i ].get_value();
xn = std::max( xn , std::abs( x0[ i ] ) );
}
// the ray is written in all the Variable of LPBlock, whose values are put
// back as they were once the part of it along x has been read
std::unique_ptr< Solution > saved( LPBlock->get_Solution( nullptr , false ) );
slvrLP->get_var_direction();
std::vector< double > d( n );
double dn = 0;
for( Index i = 0 ; i < n ; ++i ) {
d[ i ] = (*LPx)[ i ].get_value();
dn = std::max( dn , std::abs( d[ i ] ) );
}
if( saved )
saved->write( LPBlock );
if( dn == 0 )
return( false );
const double s = 1e+3 * ( 1 + xn ) / dn;
auto value_at = [ & ]( double k ) {
for( Index i = 0 ; i < n ; ++i )
(*NDOx)[ i ].set_value( x0[ i ] + k * d[ i ] );
return( convex ? NDO_value() : - NDO_value() );
};
const double f0 = value_at( 0 );
const double f1 = value_at( s );
const double f2 = value_at( 2 * s );
for( Index i = 0 ; i < n ; ++i )
(*NDOx)[ i ].set_value( x0[ i ] );
const double eps = 1e-9 * std::max( { 1.0 , std::abs( f0 ) , std::abs( f1 ) } );
return( ( f1 < f0 - eps ) && ( f2 < f1 - eps ) );
}
/*--------------------------------------------------------------------------*/
static bool SolveEach( void )
{
// LPBlock with one Solver and NDOBlock with as many as its BlockSolverConfig
// attaches, each of the latter checked against the former
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 );
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" );