-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_SRsolver.cpp
More file actions
1594 lines (1319 loc) · 46.1 KB
/
Copy pathtest_SRsolver.cpp
File metadata and controls
1594 lines (1319 loc) · 46.1 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_SRsolver.cpp --------------------------*/
/*--------------------------------------------------------------------------*/
/** @file
* Test suite for ScenarioReductionSolver class.
*
* Test 1 - Parameter Management:
* - Part 1: Setting and getting all parameter types (intAlgorithm, intShuffle,
* intRandomSeed)
* - Part 2: Boundary value testing (min/max algorithm values, small rho)
* - Part 3: Parameter validation and error handling (invalid algorithm,
* negative rho)
* - Part 4: Default parameter values through get_dflt_*_par methods
*
* Test 2 - Solution Handling:
* - Part 1: Basic functionality with y variables (facility selection)
* - Part 2: X variable assignments (customer-to-facility mapping)
* - Part 3: Algorithm comparison (Baseline vs Dupacova objective values)
* - Part 4: Solution independence (multiple solvers on same block)
* - Part 5: Solution persistence through parameters
* - Part 6: Warm start with vintWarmstartIndices
* - Part 7: has_var_solution() and get_var_solution() behavior
*
* Test 3 - Thread Safety & Concurrency:
* - Part 1: Concurrent parameter setting
* - Part 2: Preventing simultaneous compute() calls
* - Part 3: Thread safety during set_Block()
* - Part 4: Thread safety of get_var_solution()
* - Part 5: Stress test with mixed operations
*
* Test 4 - Error Handling & Edge Cases:
* - Part 1: refresh_cached_data() error conditions (negative k, k > n)
* - Part 2: Non-square matrix validation
* - Part 3: Weight normalization (unnormalized and pre-normalized)
* - Part 4: Edge cases (k=0, k=n, single scenario)
*
* \author Benoît Tran \n
* Dipartimento di Informatica \n
* Universita' di Pisa \n
*
* \copyright © by Benoît Tran
*/
/*--------------------------------------------------------------------------*/
/*-------------------------------- INCLUDES --------------------------------*/
/*--------------------------------------------------------------------------*/
#include "BlockSolverConfig.h"
#include "CapacitatedFacilityLocationBlock.h"
#include "ScenarioReductionSolver.h"
#include <atomic> // std::atomic
#include <chrono> // std::chrono
#include <cstdlib> // std::rand, std::srand
#include <iomanip> // std::setprecision
#include <iostream> // std::cout, std::cerr, std::endl
#include <stdexcept> // std::runtime_error, std::invalid_argument, etc.
#include <thread> // std::thread
/*--------------------------------------------------------------------------*/
/*--------------------------------- USING ----------------------------------*/
/*--------------------------------------------------------------------------*/
using namespace SMSpp_di_unipi_it;
/*--------------------------------------------------------------------------*/
/*------------------------------ FUNCTIONS ---------------------------------*/
/*--------------------------------------------------------------------------*/
/// Custom terminate function to print the exception message
void smspp_terminate( void ) {
std::cerr << "Uncaught exception in executing SMS++:\n";
try {
std::rethrow_exception( std::current_exception() );
}
catch( const std::exception & e ) {
std::cerr << "\tException type: " << typeid( e ).name() << "\n";
std::cerr << "\tException message: " << e.what() << "\n";
} catch( ... ) {
std::cerr << "\tUnknown exception" << std::endl;
}
std::abort(); // or exit(1)
}
/*--------------------------------------------------------------------------*/
/*--------------------------- TEST FRAMEWORK -------------------------------*/
/*--------------------------------------------------------------------------*/
struct TestResult {
bool passed;
std::string message;
};
// Global test counters
static int tests_run = 0;
static int tests_passed = 0;
static int tests_failed = 0;
// Global verbose flag
static bool verbose = false;
// Test registry
static std::map< std::string , std::function< TestResult( ) > > test_registry;
// Register a test
#define REGISTER_TEST( name , func ) \
static bool _reg_ ## func = []() { \
test_registry[ name ] = func; \
return(true); \
}( )
// Helper to run a single test
void run_test( const std::string & name , std::function< TestResult( ) >
test_func ) {
if( verbose ) {
std::cout << "\n=== Running: " << name << " ===" << std::endl;
}
tests_run++;
// Redirect cout to null if not verbose during test execution
std::streambuf * orig_cout = nullptr;
std::ostringstream null_stream;
if( ! verbose ) {
orig_cout = std::cout.rdbuf();
std::cout.rdbuf( null_stream.rdbuf() );
}
try {
TestResult result = test_func();
// Restore cout
if( ! verbose && orig_cout ) { std::cout.rdbuf( orig_cout ); }
if( result.passed ) {
if( verbose ) {
std::cout << "PASSED: " << result.message << std::endl;
}
else {
std::cout << "[PASS] " << name << std::endl;
}
tests_passed++;
}
else {
std::cout << "[FAIL] " << name << ": " << result.message << std::endl;
tests_failed++;
}
}
catch( const std::exception & e ) {
if( ! verbose && orig_cout ) { std::cout.rdbuf( orig_cout ); }
std::cout << "[EXCEPTION] " << name << ": " << e.what() << std::endl;
tests_failed++;
}
}
/*--------------------------------------------------------------------------*/
/*---------------------------- TEST HELPERS --------------------------------*/
/*--------------------------------------------------------------------------*/
// Helper function to check if two doubles are approximately equal
bool approx_equal( double a , double b , double epsilon = 1e-6 ) {
return( std::abs( a - b ) < epsilon );
}
// Helper function to create a small test CFL block
// k is the number of facilities to select (must be positive)
CapacitatedFacilityLocationBlock * create_test_block( int k ) {
if( k <= 0 ) { throw( std::invalid_argument( "k must be positive" ) ); }
auto cfl_block = new CapacitatedFacilityLocationBlock();
// Create a small problem: for scenario reduction, we need a square distance
// matrix If we interpret customers as scenarios, we need nc x nc matrix
int nf = 4; // Must equal nc for square matrix
int nc = 4;
// Set up facility costs
CapacitatedFacilityLocationBlock::CVector fcosts( nf );
for( int i = 0 ; i < nf ; ++i ) {
fcosts[ i ] = 100.0 * ( i + 1 ); // 100, 200, 300, 400
}
// Set up transportation costs as a distance matrix between scenarios
CapacitatedFacilityLocationBlock::CMatrix tcosts( boost::extents[ nf ][ nc ] );
for( int i = 0 ; i < nf ; ++i ) {
for( int j = 0 ; j < nc ; ++j ) {
if( i == j ) {
tcosts[ i ][ j ] = 0.0; // Zero distance to self
}
else {
tcosts[ i ][ j ] = 10.0 * std::abs( i - j );
// Distance based on index difference
}
}
}
// Set up capacities - must be 1.0 for scenario reduction (allows sending all
// mass to single facility)
CapacitatedFacilityLocationBlock::DVector caps( nf );
caps[ 0 ] = 1.0;
caps[ 1 ] = 1.0;
caps[ 2 ] = 1.0;
caps[ 3 ] = 1.0;
// Set up demands
CapacitatedFacilityLocationBlock::DVector dems( nc );
for( int i = 0 ; i < nc ; ++i ) {
dems[ i ] = 50.0 * ( i + 1 ); // 50, 100, 150, 200
}
// Load data into block with k as the max number of facilities
cfl_block->load( nf , nc , caps , fcosts , dems , tcosts , true , k );
return( cfl_block );
}
/*--------------------------------------------------------------------------*/
/*------------------------------ TEST CASES --------------------------------*/
/*--------------------------------------------------------------------------*/
// Test 1: Parameter Management
TestResult test_parameter_management( ) {
try {
// Part 1: Setting and getting all parameter types
ScenarioReductionSolver solver;
solver.set_par( ScenarioReductionSolver::intAlgorithm , 2 );
if( solver.get_int_par( ScenarioReductionSolver::intAlgorithm ) != 2 ) {
return { false , "Failed to set/get algorithm parameter" };
}
solver.set_par( ScenarioReductionSolver::intShuffle , 1 );
if( solver.get_int_par( ScenarioReductionSolver::intShuffle ) != 1 ) {
return { false , "Failed to set/get shuffle parameter" };
}
solver.set_par( ScenarioReductionSolver::intRandomSeed , 12345 );
// Note: We can't verify the seed value, just that set_par doesn't throw
// Part 2: Boundary value testing
solver.set_par( ScenarioReductionSolver::intAlgorithm , 0 ); // Min valid
if( solver.get_int_par( ScenarioReductionSolver::intAlgorithm ) != 0 ) {
return { false , "Failed to set min algorithm value" };
}
solver.set_par( ScenarioReductionSolver::intAlgorithm , 3 ); // Max valid
if( solver.get_int_par( ScenarioReductionSolver::intAlgorithm ) != 3 ) {
return { false , "Failed to set max algorithm value" };
}
// Small value test for rho removed - parameter no longer exists
// Part 3: Parameter validation and error handling
try {
solver.set_par( ScenarioReductionSolver::intAlgorithm , -1 );
return { false , "Should throw for negative algorithm value" };
}
catch( const std::invalid_argument & ) {
// Expected
}
try {
solver.set_par( ScenarioReductionSolver::intAlgorithm , 4 );
return { false , "Should throw for algorithm value > 3" };
}
catch( const std::invalid_argument & ) {
// Expected
}
// Negative rho test removed - parameter no longer exists
// Part 4: Default parameter values
ScenarioReductionSolver solver2;
if( solver2.get_dflt_int_par( ScenarioReductionSolver::intAlgorithm ) != 1 ) {
return { false , "Default algorithm should be 1 (Dupacova)" };
}
if( solver2.get_dflt_int_par( ScenarioReductionSolver::intShuffle ) != 0 ) {
return { false , "Default shuffle should be 0 (false)" };
}
if( solver2.get_dflt_int_par( ScenarioReductionSolver::intRandomSeed ) !=
0 ) {
return { false , "Default random seed should be 0" };
}
// Default rho test removed - parameter no longer exists
// Verify get_*_par returns defaults initially
if( solver2.get_int_par( ScenarioReductionSolver::intAlgorithm ) != 1 ||
solver2.get_int_par( ScenarioReductionSolver::intShuffle ) != 0 ) {
return { false , "get_*_par should return default values initially" };
}
// Part 5: Test get_vint_par for warm start indices
ScenarioReductionSolver solver3;
std::vector< int > test_indices = { 0 , 2 , 3 };
solver3.set_par(
ScenarioReductionSolver::vintWarmstartIndices ,
std::move( test_indices ) );
const auto & retrieved_indices =
solver3.get_vint_par( ScenarioReductionSolver::vintWarmstartIndices );
if( retrieved_indices.size() != 3 || retrieved_indices[ 0 ] != 0 ||
retrieved_indices[ 1 ] != 2 || retrieved_indices[ 2 ] != 3 ) {
return {
false ,
"get_vint_par failed to retrieve warm start indices correctly"
};
}
return { true , "All parameter management tests passed" };
}
catch( const std::exception & e ) {
return { false , std::string( "Exception: " ) + e.what() };
}
}
REGISTER_TEST( "Test 1 - Parameter Management" , test_parameter_management );
// Test 2: Solution Handling (with x variable verification)
TestResult test_solution_handling( ) {
try {
// Part 1: Basic functionality with y variables (facility selection)
{
auto * block = new CapacitatedFacilityLocationBlock();
// Set up a simple test instance
int nf = 2; // facilities (must equal customers for square distance matrix)
int nc = 2; // customers (scenarios)
int k = 1; // number of scenarios to select
CapacitatedFacilityLocationBlock::DVector caps( nf );
caps[ 0 ] = 1.0; // Must be 1.0 for scenario reduction
caps[ 1 ] = 1.0;
CapacitatedFacilityLocationBlock::CVector fcosts( nf );
fcosts[ 0 ] = 10.0;
fcosts[ 1 ] = 15.0;
CapacitatedFacilityLocationBlock::DVector dems( nc );
dems[ 0 ] = 1.0;
dems[ 1 ] = 1.0;
CapacitatedFacilityLocationBlock::CMatrix tcosts( boost::extents[ nf ][ nc ]
);
tcosts[ 0 ][ 0 ] = 0.0; // Distance from scenario 0 to 0
tcosts[ 0 ][ 1 ] = 2.0; // Distance from scenario 0 to 1
tcosts[ 1 ][ 0 ] = 2.0; // Distance from scenario 1 to 0 (symmetric)
tcosts[ 1 ][ 1 ] = 0.0; // Distance from scenario 1 to 1
block->load( nf , nc , caps , fcosts , dems , tcosts , true , k );
ScenarioReductionSolver solver;
solver.set_Block( block );
solver.set_par( ScenarioReductionSolver::intAlgorithm , 1 ); // Dupacova
int status = solver.compute();
if( status != Solver::kOK ) {
delete block;
return { false , "Solver failed to compute" };
}
const auto & reduced = solver.get_reduced_atoms();
solver.get_var_solution();
// Check y variables
for( int i = 0 ; i < nc ; ++i ) {
auto * y_var = block->get_y( i );
if( ! y_var ) {
delete block;
return { false , "y variable not found" };
}
double val = y_var->get_value();
bool is_selected = ( val > 0.5 ); // y should be 0 or 1
if( is_selected != reduced[ i ] ) {
delete block;
return { false , "y variable value doesn't match solver's solution" };
}
}
// Verify exactly k scenarios selected
int selected_count = std::count( reduced.begin() , reduced.end() , true );
if( selected_count != k ) {
delete block;
return { false , "Wrong number of scenarios selected" };
}
delete block;
}
// Part 2: X variable assignments (customer-to-facility mapping) - NEW TEST
{
auto * block = create_test_block( 2 ); // Select 2 out of 4 scenarios
ScenarioReductionSolver solver;
solver.set_Block( block );
solver.compute();
const auto & reduced = solver.get_reduced_atoms();
solver.get_var_solution();
// Get the transportation costs for verification
const auto & tcosts = block->get_Transportation_Costs();
// Verify x variables are set correctly
for( int j = 0 ; j < block->get_NCustomers() ; ++j ) {
// For each customer/scenario
bool customer_assigned = false;
int assigned_facility = -1;
double assignment_cost = 0.0;
for( int i = 0 ; i < block->get_NFacilities() ; ++i ) {
// Check all facilities
auto * x_var = block->get_x( i , j );
if( ! x_var ) {
delete block;
return {
false ,
"x variable [" + std::to_string( i ) + "][" + std::to_string( j ) +
"] not found"
};
}
double val = x_var->get_value();
if( val > 0.5 ) { // x should be 0 or 1
if( customer_assigned ) {
delete block;
return {
false ,
"Customer " + std::to_string( j ) +
" assigned to multiple facilities"
};
}
customer_assigned = true;
assigned_facility = i;
assignment_cost = tcosts[ j ][ i ];
// Note: tcosts indexing is [customer][facility]
// Verify the assigned facility is actually selected
if( ! reduced[ i ] ) {
delete block;
return {
false ,
"Customer " + std::to_string( j ) +
" assigned to unselected facility " + std::to_string( i )
};
}
}
}
if( ! customer_assigned ) {
delete block;
return {
false ,
"Customer " + std::to_string( j ) + " not assigned to any facility"
};
}
// Verify this is the closest selected facility
for( int i = 0 ; i < block->get_NFacilities() ; ++i ) {
if( reduced[ i ] && i != assigned_facility ) {
double other_cost = tcosts[ j ][ i ];
if( other_cost < assignment_cost - 1e-6 ) {
// Allow small numerical tolerance
delete block;
return {
false ,
"Customer " + std::to_string( j ) +
" not assigned to closest facility (assigned to " +
std::to_string( assigned_facility ) + " with cost " +
std::to_string( assignment_cost ) + " but facility " +
std::to_string( i ) + " has cost " + std::to_string( other_cost ) +
")"
};
}
}
}
}
delete block;
}
// Part 3: Algorithm comparison (Baseline vs Dupacova)
{
auto * block = create_test_block( 2 );
// Run Baseline
ScenarioReductionSolver baseline_solver;
baseline_solver.set_Block( block );
baseline_solver.set_par( ScenarioReductionSolver::intAlgorithm , 0 );
// Baseline
baseline_solver.compute();
double baseline_obj = baseline_solver.get_var_value();
// Run Dupacova
ScenarioReductionSolver dupacova_solver;
dupacova_solver.set_Block( block );
dupacova_solver.set_par( ScenarioReductionSolver::intAlgorithm , 1 );
// Dupacova
dupacova_solver.compute();
double dupacova_obj = dupacova_solver.get_var_value();
// Baseline should have worse or equal objective value than Dupacova
if( baseline_obj < dupacova_obj - 1e-6 ) {
delete block;
return {
false ,
"Baseline objective (" + std::to_string( baseline_obj ) +
") should not be better than Dupacova (" +
std::to_string( dupacova_obj ) + ")"
};
}
delete block;
}
// Part 4: Solution independence (multiple solvers on same block)
{
auto * block = create_test_block( 2 );
ScenarioReductionSolver solver1;
solver1.set_Block( block );
solver1.compute();
std::vector< bool > solution1 = solver1.get_reduced_atoms();
double obj1 = solver1.get_var_value();
ScenarioReductionSolver solver2;
solver2.set_Block( block );
solver2.set_par( ScenarioReductionSolver::intAlgorithm , 0 ); // Baseline
solver2.compute();
// Verify both solvers maintain their own solutions
const auto & solution1_check = solver1.get_reduced_atoms();
for( size_t i = 0 ; i < solution1.size() ; ++i ) {
if( solution1[ i ] != solution1_check[ i ] ) {
delete block;
return { false , "First solver's solution was corrupted" };
}
}
delete block;
}
// Part 5: Solution persistence through parameters
{
auto * block = create_test_block( 2 );
ScenarioReductionSolver solver;
solver.set_Block( block );
solver.compute();
int algorithm = solver.get_int_par( ScenarioReductionSolver::intAlgorithm );
std::vector< bool > solution = solver.get_reduced_atoms();
ScenarioReductionSolver solver2;
solver2.set_Block( block );
solver2.set_par( ScenarioReductionSolver::intAlgorithm , algorithm );
solver2.compute();
const auto & solution2 = solver2.get_reduced_atoms();
if( solution.size() != solution2.size() ) {
delete block;
return { false , "Solution sizes don't match after parameter restoration" };
}
for( size_t i = 0 ; i < solution.size() ; ++i ) {
if( solution[ i ] != solution2[ i ] ) {
delete block;
return { false , "Solutions don't match after restoring parameters" };
}
}
delete block;
}
// Part 6: Warm start with vintWarmstartIndices
{
auto * block = create_test_block( 4 );
ScenarioReductionSolver solver1;
solver1.set_Block( block );
solver1.set_par( ScenarioReductionSolver::intAlgorithm , 1 ); // Dupacova
solver1.compute();
const auto & solution1 = solver1.get_reduced_atoms();
std::vector< int > warm_indices;
for( size_t i = 0 ; i < solution1.size() ; ++i ) {
if( solution1[ i ] ) { warm_indices.push_back( static_cast< int >( i ) ); }
}
ScenarioReductionSolver solver2;
solver2.set_Block( block );
solver2.set_par( ScenarioReductionSolver::intAlgorithm , 2 ); // BestFit
solver2.set_par( ScenarioReductionSolver::intUseWarmstart , 1 );
solver2.set_par(
ScenarioReductionSolver::vintWarmstartIndices ,
std::move( warm_indices ) );
solver2.compute();
double obj1 = solver1.get_var_value();
double obj2 = solver2.get_var_value();
if( obj2 > obj1 + 1e-6 ) {
// Local search should be at least as good as Dupacova with warm start
delete block;
return {
false ,
"Warm start local search should not be worse than Dupacova"
};
}
delete block;
}
// Part 7: has_var_solution() and get_var_solution() behavior
{
auto * block = create_test_block( 2 );
ScenarioReductionSolver solver;
solver.set_Block( block );
if( solver.has_var_solution() ) {
delete block;
return {
false , "has_var_solution() should return false before compute()"
};
}
int status = solver.compute();
if( status != Solver::kOK ) {
delete block;
return { false , "Compute failed" };
}
if( ! solver.has_var_solution() ) {
delete block;
return {
false ,
"has_var_solution() should return true after successful compute()"
};
}
// Test get_nb_atoms(), get_nb_reduced(), and get_weights()
if( solver.get_nb_atoms() != 4 ) {
delete block;
return { false , "get_nb_atoms() should return 4 for test block" };
}
if( solver.get_nb_reduced() != 2 ) {
delete block;
return { false , "get_nb_reduced() should return 2 (k value)" };
}
const auto * weights = solver.get_weights();
if( ! weights ) {
delete block;
return { false , "get_weights() should not return nullptr" };
}
// Weights should be normalized (sum to 1.0)
double weight_sum = 0.0;
for( size_t i = 0 ; i < 4 ; ++i ) {
weight_sum += ( *weights )[ i ];
}
if( ! approx_equal( weight_sum , 1.0 , 1e-6 ) ) {
delete block;
return {
false ,
"Weights should be normalized to sum to 1.0, got " +
std::to_string( weight_sum )
};
}
// Test error when no solution available
ScenarioReductionSolver solver2;
solver2.set_Block( block );
try {
solver2.get_var_solution();
delete block;
return { false , "Should throw when no solution available" };
}
catch( const std::logic_error & e ) {
if( std::string( e.what() ).find( "no solution available" ) ==
std::string::npos ) {
delete block;
return { false , "Wrong error message for no solution" };
}
}
// Test all algorithms produce valid x and y variables
for( int algo = 0 ; algo <= 3 ; ++algo ) {
ScenarioReductionSolver algo_solver;
algo_solver.set_Block( block );
algo_solver.set_par( ScenarioReductionSolver::intAlgorithm , algo );
algo_solver.compute();
algo_solver.get_var_solution();
int count_selected = 0;
for( CapacitatedFacilityLocationBlock::Index i = 0 ;
i < block->get_NFacilities() ;
++i ) {
auto y_var = block->get_y( i );
if( y_var && approx_equal( y_var->get_value() , 1.0 ) ) {
count_selected++;
}
}
if( count_selected != 2 ) { // Should select exactly k=2 facilities
delete block;
return {
false ,
"Algorithm " + std::to_string( algo ) + " selected " +
std::to_string( count_selected ) + " facilities instead of 2"
};
}
}
delete block;
}
return {
true ,
"All solution handling tests passed (including x variable verification)"
};
}
catch( const std::exception & e ) {
return { false , std::string( "Exception: " ) + e.what() };
}
}
REGISTER_TEST( "Test 2 - Solution Handling" , test_solution_handling );
// Test 3: Thread Safety & Concurrency
TestResult test_thread_safety( ) {
try {
// Part 1: Concurrent parameter setting
{
ScenarioReductionSolver solver;
std::vector< std::thread > threads;
std::atomic< int > errors( 0 );
// Launch multiple threads that try to set parameters
for( int i = 0 ; i < 10 ; ++i ) {
threads.emplace_back( [ & solver , & errors , i ]( ) {
try {
solver.lock();
// Each thread sets different parameter values
solver.set_par( ScenarioReductionSolver::intAlgorithm , i % 4 );
// Verify the values are what we just set
int alg = solver.get_int_par( ScenarioReductionSolver::intAlgorithm );
if( alg != i % 4 ) { errors++; }
solver.unlock();
}
catch( ... ) { errors++; }
} );
}
// Wait for all threads
for( auto & t : threads ) {
t.join();
}
if( errors > 0 ) {
return {
false ,
"Concurrent parameter setting had " + std::to_string( errors ) +
" errors"
};
}
}
// Part 2: Preventing simultaneous compute() calls
{
auto block = create_test_block( 1 );
ScenarioReductionSolver solver;
solver.set_Block( block );
std::atomic< int > concurrent_computes( 0 );
std::atomic< int > max_concurrent( 0 );
std::atomic< int > completed( 0 );
std::vector< std::thread > threads;
// Launch multiple threads that try to compute simultaneously
for( int i = 0 ; i < 5 ; ++i ) {
threads.emplace_back(
[ & solver , & concurrent_computes , & max_concurrent , & completed ]( ) {
int current = concurrent_computes.fetch_add( 1 ) + 1;
// Update max concurrent if needed
int expected = max_concurrent.load();
while( current > expected &&
! max_concurrent.compare_exchange_weak( expected , current ) ) {
}
// Call compute - should be properly serialized
int status = solver.compute();
concurrent_computes--;
if( status == Solver::kOK ) { completed++; }
} );
}
// Wait for all threads
for( auto & t : threads ) {
t.join();
}
delete block;
// Verify all threads completed successfully
if( completed != 5 ) {
return {
false ,
"Not all threads completed compute(): " +
std::to_string( completed.load() ) + "/5"
};
}
}
// Part 3: Thread safety during set_Block()
{
std::vector< std::thread > threads;
std::atomic< int > errors( 0 );
// Create multiple solvers and blocks
for( int i = 0 ; i < 5 ; ++i ) {
threads.emplace_back( [ & errors , i ]( ) {
try {
auto solver = new ScenarioReductionSolver();
auto block = create_test_block( 2 );
// Lock before set_Block
solver->lock();
solver->set_Block( block );
solver->unlock();
// Verify block was set
solver->lock();
auto retrieved_block = solver->get_Block();
solver->unlock();
if( retrieved_block != block ) { errors++; }
delete solver;
delete block;
}
catch( ... ) { errors++; }
} );
}
// Wait for all threads
for( auto & t : threads ) {
t.join();
}
if( errors > 0 ) {
return {
false ,
"Errors during concurrent set_Block: " + std::to_string( errors )
};
}
}
// Part 4: Thread safety of get_var_solution()
{
auto block = create_test_block( 1 );
ScenarioReductionSolver solver;
solver.lock();
solver.set_Block( block );
int status = solver.compute();
solver.unlock();
if( status != Solver::kOK ) {
delete block;
return {
false , "Compute failed with status: " + std::to_string( status )
};
}
std::vector< std::thread > threads;
std::atomic< int > errors( 0 );
// Multiple threads trying to get solution
for( int i = 0 ; i < 5 ; ++i ) {
threads.emplace_back( [ & solver , & block , & errors ]( ) {
try {
// Block should be locked before calling get_var_solution
solver.lock();
block->lock( solver.id() );
if( solver.has_var_solution() ) { solver.get_var_solution(); }
block->unlock( solver.id() );
solver.unlock();
}
catch( ... ) { errors++; }
} );
}
// Wait for all threads
for( auto & t : threads ) {
t.join();
}
delete block;
if( errors > 0 ) {
return {
false ,
"Errors during concurrent get_var_solution: " + std::to_string( errors )
};
}
}
// Part 5: Stress test with mixed operations
{
auto block = create_test_block( 2 );
ScenarioReductionSolver solver;
solver.lock();
solver.set_Block( block );
solver.unlock();
std::atomic< int > errors( 0 );
std::atomic< bool > stop( false );
std::vector< std::thread > threads;
// Thread 1: Continuously set parameters
threads.emplace_back( [ & solver , & errors , & stop ]( ) {
int iteration = 0;
while( ! stop ) {
try {
solver.lock();
solver.set_par( ScenarioReductionSolver::intAlgorithm , iteration % 4 );
solver.unlock();
iteration++;
}
catch( ... ) { errors++; }
}
} );
// Thread 2: Continuously read parameters
threads.emplace_back( [ & solver , & errors , & stop ]( ) {
while( ! stop ) {
try {
solver.lock();
solver.get_int_par( ScenarioReductionSolver::intAlgorithm );
solver.unlock();
}
catch( ... ) { errors++; }
}
} );
// Thread 3: Periodically compute
threads.emplace_back( [ & solver , & block , & errors , & stop ]( ) {
while( ! stop ) {
try {
solver.lock();
solver.compute();
solver.unlock();
std::this_thread::sleep_for( std::chrono::milliseconds( 50 ) );
}
catch( ... ) { errors++; }
}
} );
// Let threads run for a short time
std::this_thread::sleep_for( std::chrono::milliseconds( 500 ) );
stop = true;
// Wait for all threads
for( auto & t : threads ) {
t.join();
}
delete block;
if( errors > 0 ) {
return {
false , "Stress test had " + std::to_string( errors ) + " errors"
};
}
}
return { true , "All thread safety tests passed" };
}
catch( const std::exception & e ) {
return { false , std::string( "Exception: " ) + e.what() };
}
}