Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Simplex_test.cc
Go to the documentation of this file.
1
2/*
3 Aleph_w
4
5 Data structures & Algorithms
6 version 2.0.0b
7 https://github.com/lrleon/Aleph-w
8
9 This file is part of Aleph-w library
10
11 Copyright (c) 2002-2026 Leandro Rabindranath Leon
12
13 Permission is hereby granted, free of charge, to any person obtaining a copy
14 of this software and associated documentation files (the "Software"), to deal
15 in the Software without restriction, including without limitation the rights
16 to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
17 copies of the Software, and to permit persons to whom the Software is
18 furnished to do so, subject to the following conditions:
19
20 The above copyright notice and this permission notice shall be included in all
21 copies or substantial portions of the Software.
22
23 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
24 IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25 FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
26 AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27 LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
28 OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
29 SOFTWARE.
30*/
31
32
51#include <gtest/gtest.h>
52#include <Simplex.H>
53#include <algorithm>
54#include <cmath>
55#include <filesystem>
56#include <fstream>
57#include <random>
58#include <sstream>
59#include <string>
60#include <utility>
61#include <vector>
62
63using namespace Aleph;
64
65//==============================================================================
66// Test Fixture
67//==============================================================================
68
69class SimplexTest : public ::testing::Test
70{
71protected:
72 static constexpr double EPSILON = 1e-6;
73
74 bool nearly_equal(double a, double b, double eps = EPSILON)
75 {
76 return std::fabs(a - b) < eps;
77 }
78};
79
80//==============================================================================
81// Constructor Tests
82//==============================================================================
83
84TEST_F(SimplexTest, ConstructorBasic)
85{
86 Simplex<double> simplex(3);
87
88 EXPECT_EQ(simplex.get_num_vars(), 3);
89 EXPECT_EQ(simplex.get_num_restrictions(), 0);
90 EXPECT_EQ(simplex.get_state(), Simplex<double>::Not_Solved);
91}
92
93TEST_F(SimplexTest, ConstructorZeroVariablesThrows)
94{
95 EXPECT_THROW(Simplex<double>(0), std::invalid_argument);
96}
97
98TEST_F(SimplexTest, ConstructorSingleVariable)
99{
100 Simplex<double> simplex(1);
101 EXPECT_EQ(simplex.get_num_vars(), 1);
102}
103
104TEST_F(SimplexTest, ConstructorLargeNumber)
105{
106 Simplex<double> simplex(100);
107 EXPECT_EQ(simplex.get_num_vars(), 100);
108}
109
110//==============================================================================
111// Objective Function Tests
112//==============================================================================
113
114TEST_F(SimplexTest, SetObjectiveCoefficient)
115{
116 Simplex<double> simplex(3);
117
118 simplex.put_objetive_function_coef(0, 3.0);
119 simplex.put_objetive_function_coef(1, 2.0);
120 simplex.put_objetive_function_coef(2, 1.0);
121
122 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(0), 3.0);
123 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(1), 2.0);
124 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(2), 1.0);
125}
126
127TEST_F(SimplexTest, SetObjectiveCoefficientOutOfRangeThrows)
128{
129 Simplex<double> simplex(3);
130
131 EXPECT_THROW(simplex.put_objetive_function_coef(3, 1.0), std::out_of_range);
132 EXPECT_THROW(simplex.put_objetive_function_coef(100, 1.0), std::out_of_range);
133}
134
135TEST_F(SimplexTest, GetObjectiveCoefficientOutOfRangeThrows)
136{
137 Simplex<double> simplex(3);
138
139 EXPECT_THROW(simplex.get_objetive_function_coef(3), std::out_of_range);
140}
141
142TEST_F(SimplexTest, SetObjectiveFunctionFromArray)
143{
144 Simplex<double> simplex(3);
145 double coefs[] = {5.0, 4.0, 3.0};
146
147 simplex.put_objetive_function(coefs);
148
149 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(0), 5.0);
150 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(1), 4.0);
151 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(2), 3.0);
152}
153
154TEST_F(SimplexTest, SetObjectiveFunctionFromDynArray)
155{
156 Simplex<double> simplex(3);
157 DynArray<double> coefs;
158 coefs[0] = 5.0;
159 coefs[1] = 4.0;
160 coefs[2] = 3.0;
161
162 simplex.put_objetive_function(coefs);
163
164 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(0), 5.0);
165 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(1), 4.0);
166 EXPECT_DOUBLE_EQ(simplex.get_objetive_function_coef(2), 3.0);
167}
168
169TEST_F(SimplexTest, GetObjectiveFunctionPointer)
170{
171 Simplex<double> simplex(3);
172 simplex.put_objetive_function_coef(0, 7.0);
173
174 double* ptr = simplex.get_objetive_function();
175 ASSERT_NE(ptr, nullptr);
176 EXPECT_DOUBLE_EQ(ptr[0], 7.0);
177}
178
179//==============================================================================
180// Restriction Tests
181//==============================================================================
182
183TEST_F(SimplexTest, AddRestrictionFromArray)
184{
185 Simplex<double> simplex(2);
186 double rest[] = {1.0, 2.0, 10.0};
187
188 simplex.put_restriction(rest);
189
190 EXPECT_EQ(simplex.get_num_restrictions(), 1);
191}
192
193TEST_F(SimplexTest, AddMultipleRestrictions)
194{
195 Simplex<double> simplex(2);
196 double r1[] = {1.0, 1.0, 4.0};
197 double r2[] = {2.0, 1.0, 5.0};
198 double r3[] = {1.0, 2.0, 6.0};
199
200 simplex.put_restriction(r1);
201 simplex.put_restriction(r2);
202 simplex.put_restriction(r3);
203
204 EXPECT_EQ(simplex.get_num_restrictions(), 3);
205}
206
207TEST_F(SimplexTest, AddEmptyRestriction)
208{
209 Simplex<double> simplex(2);
210
211 double* rest = simplex.put_restriction(nullptr);
212
213 ASSERT_NE(rest, nullptr);
214 EXPECT_EQ(simplex.get_num_restrictions(), 1);
215
216 // Should be initialized to zero
217 EXPECT_DOUBLE_EQ(rest[0], 0.0);
218 EXPECT_DOUBLE_EQ(rest[1], 0.0);
219 EXPECT_DOUBLE_EQ(rest[2], 0.0);
220}
221
222TEST_F(SimplexTest, ModifyRestrictionAfterAdd)
223{
224 Simplex<double> simplex(2);
225
226 double* rest = simplex.put_restriction(nullptr);
227 rest[0] = 3.0;
228 rest[1] = 4.0;
229 rest[2] = 12.0;
230
231 double* retrieved = simplex.get_restriction(0);
232 EXPECT_DOUBLE_EQ(retrieved[0], 3.0);
233 EXPECT_DOUBLE_EQ(retrieved[1], 4.0);
234 EXPECT_DOUBLE_EQ(retrieved[2], 12.0);
235}
236
237TEST_F(SimplexTest, GetRestrictionOutOfRangeThrows)
238{
239 Simplex<double> simplex(2);
240 double rest[] = {1.0, 1.0, 4.0};
241 simplex.put_restriction(rest);
242
243 EXPECT_THROW(simplex.get_restriction(1), std::out_of_range);
244 EXPECT_THROW(simplex.get_restriction(100), std::out_of_range);
245}
246
247TEST_F(SimplexTest, GetRestrictionCoef)
248{
249 Simplex<double> simplex(3);
250 double rest[] = {1.0, 2.0, 3.0, 10.0};
251 simplex.put_restriction(rest);
252
253 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 0), 1.0);
254 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 1), 2.0);
255 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 2), 3.0);
256}
257
258TEST_F(SimplexTest, PutRestrictionCoef)
259{
260 Simplex<double> simplex(2);
261 simplex.put_restriction(nullptr);
262
263 simplex.put_restriction_coef(0, 0, 5.0);
264 simplex.put_restriction_coef(0, 1, 6.0);
265
266 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 0), 5.0);
267 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 1), 6.0);
268}
269
270TEST_F(SimplexTest, AddRestrictionFromDynArray)
271{
272 Simplex<double> simplex(2);
273 DynArray<double> coefs;
274 coefs[0] = 1.0;
275 coefs[1] = 2.0;
276 coefs[2] = 8.0;
277
278 simplex.put_restriction(coefs);
279
280 EXPECT_EQ(simplex.get_num_restrictions(), 1);
281 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 0), 1.0);
282 EXPECT_DOUBLE_EQ(simplex.get_restriction_coef(0, 1), 2.0);
283}
284
285//==============================================================================
286// Solve Error Handling Tests
287//==============================================================================
288
289TEST_F(SimplexTest, SolveWithoutRestrictionThrows)
290{
291 Simplex<double> simplex(2);
292 simplex.put_objetive_function_coef(0, 3.0);
293 simplex.put_objetive_function_coef(1, 2.0);
294
295 EXPECT_THROW(simplex.prepare_linear_program(), std::logic_error);
296}
297
298TEST_F(SimplexTest, SolveWithoutPrepareThrows)
299{
300 Simplex<double> simplex(2);
301 simplex.put_objetive_function_coef(0, 3.0);
302 simplex.put_objetive_function_coef(1, 2.0);
303 double rest[] = {1.0, 1.0, 4.0};
304 simplex.put_restriction(rest);
305
306 EXPECT_THROW(simplex.solve(), std::logic_error);
307}
308
309TEST_F(SimplexTest, SolveTwiceThrows)
310{
311 Simplex<double> simplex(2);
312 simplex.put_objetive_function_coef(0, 3.0);
313 simplex.put_objetive_function_coef(1, 2.0);
314 double rest[] = {1.0, 1.0, 4.0};
315 simplex.put_restriction(rest);
316
317 simplex.prepare_linear_program();
318 simplex.solve();
319
320 EXPECT_THROW(simplex.solve(), std::logic_error);
321}
322
323// A restriction added after prepare_linear_program() grew the count of
324// restrictions but not the tableau: solve() and load_solution() then read
325// past it inside noexcept, and the program ended. Now it throws, before
326// and after solve(), and the program is left as it was.
327TEST_F(SimplexTest, PutRestrictionAfterPrepareThrowsAndKeepsTheProgram)
328{
329 Simplex<double> simplex(2);
330 simplex.put_objetive_function_coef(0, 40.0);
331 simplex.put_objetive_function_coef(1, 30.0);
332 double labor[] = {1.0, 1.0, 40.0}; // x + y <= 40
333 double machine[] = {2.0, 1.0, 60.0}; // 2x + y <= 60
334 double extra[] = {1.0, 0.0, 30.0};
335 DynArray<double> extra_array;
336 for (size_t i = 0; i < 3; ++i)
337 extra_array[i] = extra[i];
338 simplex.put_restriction(labor);
339 simplex.put_restriction(machine);
340 simplex.prepare_linear_program();
341
342 auto expect_no_restriction_is_added = [&]
343 {
344 EXPECT_THROW(simplex.put_restriction(extra), std::logic_error);
345 EXPECT_THROW(simplex.put_restriction(nullptr), std::logic_error);
346 EXPECT_THROW(simplex.put_restriction(extra_array), std::logic_error);
347 EXPECT_THROW(simplex.put_ge_restriction(extra), std::logic_error);
348 EXPECT_THROW(simplex.put_eq_restriction(extra), std::logic_error);
349 EXPECT_EQ(simplex.get_num_restrictions(), 2u);
350 };
351
352 expect_no_restriction_is_added();
353 ASSERT_EQ(simplex.solve(), Simplex<double>::Solved);
354 expect_no_restriction_is_added();
355
356 simplex.load_solution(); // x = y = 20
357 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 20.0));
358 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 20.0));
359 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 1400.0));
360 EXPECT_TRUE(simplex.verify_solution());
361}
362
363// The messages of the index checks gave the range as [0, n - 1], which
364// wraps when n is 0, as for a solver without restrictions or a moved-from
365// one: the range is now half open
366TEST_F(SimplexTest, IndexErrorsGiveTheRangeHalfOpen)
367{
368 auto message_of = [](auto && op) -> std::string
369 {
370 try
371 {
372 op();
373 }
374 catch (const std::out_of_range & e)
375 {
376 return e.what();
377 }
378 return "";
379 };
380
381 Simplex<double> simplex(2);
382 EXPECT_NE(message_of([&] { (void) simplex.get_objetive_function_coef(2); })
383 .find("Variable index 2 out of range [0, 2)"), std::string::npos);
384 EXPECT_NE(message_of([&] { (void) simplex.get_restriction(0); })
385 .find("Restriction index 0 out of range [0, 0)"), std::string::npos);
386
387 Simplex<double> taken(std::move(simplex)); // simplex has no variables now
388 EXPECT_NE(message_of([&] { (void) simplex.get_objetive_function_coef(0); })
389 .find("Variable index 0 out of range [0, 0)"), std::string::npos);
390}
391
392//==============================================================================
393// Classic Linear Programming Problems
394//==============================================================================
395
396TEST_F(SimplexTest, SimpleMaximization)
397{
398 // Maximize Z = 3x + 2y
399 // Subject to:
400 // x + y <= 4
401 // x <= 2
402 // y <= 3
403 // x, y >= 0
404 // Expected solution: x=2, y=2, Z=10
405
406 Simplex<double> simplex(2);
407 simplex.put_objetive_function_coef(0, 3.0); // x coefficient
408 simplex.put_objetive_function_coef(1, 2.0); // y coefficient
409
410 double c1[] = {1.0, 1.0, 4.0};
411 double c2[] = {1.0, 0.0, 2.0};
412 double c3[] = {0.0, 1.0, 3.0};
413
414 simplex.put_restriction(c1);
415 simplex.put_restriction(c2);
416 simplex.put_restriction(c3);
417
418 simplex.prepare_linear_program();
419 auto state = simplex.solve();
420
421 EXPECT_EQ(state, Simplex<double>::Solved);
422
423 simplex.load_solution();
424
425 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 2.0));
426 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 2.0));
427 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 10.0));
428 EXPECT_TRUE(simplex.verify_solution());
429}
430
431TEST_F(SimplexTest, ThreeVariableProblem)
432{
433 // Maximize Z = 5x1 + 4x2 + 3x3
434 // Subject to:
435 // 2x1 + 3x2 + x3 <= 5
436 // 4x1 + 2x2 + 3x3 <= 11
437 // 3x1 + 4x2 + 2x3 <= 8
438 // x1, x2, x3 >= 0
439
440 Simplex<double> simplex(3);
441 simplex.put_objetive_function_coef(0, 5.0);
442 simplex.put_objetive_function_coef(1, 4.0);
443 simplex.put_objetive_function_coef(2, 3.0);
444
445 double c1[] = {2.0, 3.0, 1.0, 5.0};
446 double c2[] = {4.0, 2.0, 3.0, 11.0};
447 double c3[] = {3.0, 4.0, 2.0, 8.0};
448
449 simplex.put_restriction(c1);
450 simplex.put_restriction(c2);
451 simplex.put_restriction(c3);
452
453 simplex.prepare_linear_program();
454 auto state = simplex.solve();
455
456 EXPECT_EQ(state, Simplex<double>::Solved);
457
458 simplex.load_solution();
459 EXPECT_TRUE(simplex.verify_solution());
460
461 // Objective value should be positive and bounded
462 EXPECT_GT(simplex.objetive_value(), 0.0);
463}
464
465TEST_F(SimplexTest, ProductMixProblem)
466{
467 // Classic product mix problem
468 // Maximize Z = 40x1 + 30x2 (profit)
469 // Subject to:
470 // x1 + x2 <= 40 (labor hours)
471 // 2x1 + x2 <= 60 (machine hours)
472 // x1, x2 >= 0
473 // Expected: x1=20, x2=20, Z=1400
474
475 Simplex<double> simplex(2);
476 simplex.put_objetive_function_coef(0, 40.0);
477 simplex.put_objetive_function_coef(1, 30.0);
478
479 double c1[] = {1.0, 1.0, 40.0};
480 double c2[] = {2.0, 1.0, 60.0};
481
482 simplex.put_restriction(c1);
483 simplex.put_restriction(c2);
484
485 simplex.prepare_linear_program();
486 auto state = simplex.solve();
487
488 EXPECT_EQ(state, Simplex<double>::Solved);
489
490 simplex.load_solution();
491
492 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 20.0));
493 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 20.0));
494 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 1400.0));
495 EXPECT_TRUE(simplex.verify_solution());
496}
497
498TEST_F(SimplexTest, DietProblem)
499{
500 // Simplified diet problem (but maximizing nutrition here)
501 // Maximize Z = 10x1 + 15x2 + 12x3 (nutrition value)
502 // Subject to:
503 // x1 + x2 + x3 <= 10 (total servings)
504 // 2x1 + x2 + 3x3 <= 18 (cost constraint)
505 // x1, x2, x3 >= 0
506
507 Simplex<double> simplex(3);
508 simplex.put_objetive_function_coef(0, 10.0);
509 simplex.put_objetive_function_coef(1, 15.0);
510 simplex.put_objetive_function_coef(2, 12.0);
511
512 double c1[] = {1.0, 1.0, 1.0, 10.0};
513 double c2[] = {2.0, 1.0, 3.0, 18.0};
514
515 simplex.put_restriction(c1);
516 simplex.put_restriction(c2);
517
518 simplex.prepare_linear_program();
519 auto state = simplex.solve();
520
521 EXPECT_EQ(state, Simplex<double>::Solved);
522
523 simplex.load_solution();
524 EXPECT_TRUE(simplex.verify_solution());
525 EXPECT_GT(simplex.objetive_value(), 0.0);
526}
527
528TEST_F(SimplexTest, TransportationVariant)
529{
530 // Maximize Z = 2x1 + 3x2 + x3 + 4x4
531 // Subject to:
532 // x1 + x2 <= 4
533 // x3 + x4 <= 6
534 // x1 + x3 <= 5
535 // x2 + x4 <= 5
536
537 Simplex<double> simplex(4);
538 simplex.put_objetive_function_coef(0, 2.0);
539 simplex.put_objetive_function_coef(1, 3.0);
540 simplex.put_objetive_function_coef(2, 1.0);
541 simplex.put_objetive_function_coef(3, 4.0);
542
543 double c1[] = {1.0, 1.0, 0.0, 0.0, 4.0};
544 double c2[] = {0.0, 0.0, 1.0, 1.0, 6.0};
545 double c3[] = {1.0, 0.0, 1.0, 0.0, 5.0};
546 double c4[] = {0.0, 1.0, 0.0, 1.0, 5.0};
547
548 simplex.put_restriction(c1);
549 simplex.put_restriction(c2);
550 simplex.put_restriction(c3);
551 simplex.put_restriction(c4);
552
553 simplex.prepare_linear_program();
554 auto state = simplex.solve();
555
556 EXPECT_EQ(state, Simplex<double>::Solved);
557
558 simplex.load_solution();
559 EXPECT_TRUE(simplex.verify_solution());
560}
561
562//==============================================================================
563// Edge Cases
564//==============================================================================
565
566TEST_F(SimplexTest, SingleVariableSingleConstraint)
567{
568 // Maximize Z = 5x
569 // Subject to: x <= 10
570 // Expected: x=10, Z=50
571
572 Simplex<double> simplex(1);
573 simplex.put_objetive_function_coef(0, 5.0);
574
575 double c1[] = {1.0, 10.0};
576 simplex.put_restriction(c1);
577
578 simplex.prepare_linear_program();
579 auto state = simplex.solve();
580
581 EXPECT_EQ(state, Simplex<double>::Solved);
582
583 simplex.load_solution();
584 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 10.0));
585 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 50.0));
586 EXPECT_TRUE(simplex.verify_solution());
587}
588
589TEST_F(SimplexTest, ZeroObjectiveCoefficient)
590{
591 // Maximize Z = 0*x + 5*y
592 // Subject to:
593 // x + y <= 10
594 // y <= 10 (explicit bound on y)
595 // x, y >= 0
596 // Expected: y=10, x=0, Z=50
597
598 Simplex<double> simplex(2);
599 simplex.put_objetive_function_coef(0, 0.0);
600 simplex.put_objetive_function_coef(1, 5.0);
601
602 double c1[] = {1.0, 1.0, 10.0};
603 double c2[] = {0.0, 1.0, 10.0};
604 simplex.put_restriction(c1);
605 simplex.put_restriction(c2);
606
607 simplex.prepare_linear_program();
608 auto state = simplex.solve();
609
610 EXPECT_EQ(state, Simplex<double>::Solved);
611
612 simplex.load_solution();
613 // Solution should maximize y within constraints
614 EXPECT_GE(simplex.objetive_value(), 0.0);
615}
616
617TEST_F(SimplexTest, TightConstraints)
618{
619 // Maximize Z = x + y
620 // Subject to:
621 // x <= 5
622 // y <= 5
623 // x + y <= 10
624 // Expected: x=5, y=5, Z=10
625
626 Simplex<double> simplex(2);
627 simplex.put_objetive_function_coef(0, 1.0);
628 simplex.put_objetive_function_coef(1, 1.0);
629
630 double c1[] = {1.0, 0.0, 5.0};
631 double c2[] = {0.0, 1.0, 5.0};
632 double c3[] = {1.0, 1.0, 10.0};
633
634 simplex.put_restriction(c1);
635 simplex.put_restriction(c2);
636 simplex.put_restriction(c3);
637
638 simplex.prepare_linear_program();
639 auto state = simplex.solve();
640
641 EXPECT_EQ(state, Simplex<double>::Solved);
642
643 simplex.load_solution();
644 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 5.0));
645 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 5.0));
646 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 10.0));
647 EXPECT_TRUE(simplex.verify_solution());
648}
649
650TEST_F(SimplexTest, RedundantConstraint)
651{
652 // Maximize Z = x + y
653 // Subject to:
654 // x + y <= 10
655 // x <= 5
656 // y <= 5
657 // x, y >= 0
658
659 Simplex<double> simplex(2);
660 simplex.put_objetive_function_coef(0, 1.0);
661 simplex.put_objetive_function_coef(1, 1.0);
662
663 double c1[] = {1.0, 1.0, 10.0};
664 double c2[] = {1.0, 0.0, 5.0};
665 double c3[] = {0.0, 1.0, 5.0};
666
667 simplex.put_restriction(c1);
668 simplex.put_restriction(c2);
669 simplex.put_restriction(c3);
670
671 simplex.prepare_linear_program();
672 auto state = simplex.solve();
673
674 EXPECT_EQ(state, Simplex<double>::Solved);
675
676 simplex.load_solution();
677 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 10.0));
678 EXPECT_TRUE(simplex.verify_solution());
679}
680
681TEST_F(SimplexTest, FractionalSolution)
682{
683 // Maximize Z = 3x + 5y
684 // Subject to:
685 // x + y <= 4
686 // 2x + 3y <= 9
687 // x <= 4
688 // y <= 4
689 // Optimal: x=3, y=1, Z=14
690
691 Simplex<double> simplex(2);
692 simplex.put_objetive_function_coef(0, 3.0);
693 simplex.put_objetive_function_coef(1, 5.0);
694
695 double c1[] = {1.0, 1.0, 4.0};
696 double c2[] = {2.0, 3.0, 9.0};
697 double c3[] = {1.0, 0.0, 4.0};
698 double c4[] = {0.0, 1.0, 4.0};
699
700 simplex.put_restriction(c1);
701 simplex.put_restriction(c2);
702 simplex.put_restriction(c3);
703 simplex.put_restriction(c4);
704
705 simplex.prepare_linear_program();
706 auto state = simplex.solve();
707
708 EXPECT_EQ(state, Simplex<double>::Solved);
709
710 simplex.load_solution();
711 EXPECT_TRUE(simplex.verify_solution());
712
713 // Optimal value should be around 14
714 EXPECT_GT(simplex.objetive_value(), 10.0);
715}
716
717//==============================================================================
718// Float Type Tests
719//==============================================================================
720
722{
723 // Same problem but with float instead of double
724 Simplex<float> simplex(2);
725 simplex.put_objetive_function_coef(0, 3.0f);
726 simplex.put_objetive_function_coef(1, 2.0f);
727
728 float c1[] = {1.0f, 1.0f, 4.0f};
729 float c2[] = {1.0f, 0.0f, 2.0f};
730
731 simplex.put_restriction(c1);
732 simplex.put_restriction(c2);
733
734 simplex.prepare_linear_program();
735 auto state = simplex.solve();
736
737 EXPECT_EQ(state, Simplex<float>::Solved);
738
739 simplex.load_solution();
740 EXPECT_TRUE(simplex.verify_solution());
741}
742
743//==============================================================================
744// State Transition Tests
745//==============================================================================
746
747TEST_F(SimplexTest, StateTransitions)
748{
749 Simplex<double> simplex(2);
750 EXPECT_EQ(simplex.get_state(), Simplex<double>::Not_Solved);
751
752 simplex.put_objetive_function_coef(0, 1.0);
753 simplex.put_objetive_function_coef(1, 1.0);
754
755 double c1[] = {1.0, 1.0, 10.0};
756 simplex.put_restriction(c1);
757
758 simplex.prepare_linear_program();
759 EXPECT_EQ(simplex.get_state(), Simplex<double>::Not_Solved);
760
761 auto state = simplex.solve();
762
763 EXPECT_EQ(state, Simplex<double>::Solved);
764 EXPECT_EQ(simplex.get_state(), Simplex<double>::Solved);
765}
766
767//==============================================================================
768// Verify Solution Tests
769//==============================================================================
770
771TEST_F(SimplexTest, VerifySolutionTrue)
772{
773 Simplex<double> simplex(2);
774 simplex.put_objetive_function_coef(0, 1.0);
775 simplex.put_objetive_function_coef(1, 1.0);
776
777 double c1[] = {1.0, 0.0, 5.0};
778 double c2[] = {0.0, 1.0, 5.0};
779
780 simplex.put_restriction(c1);
781 simplex.put_restriction(c2);
782
783 simplex.prepare_linear_program();
784 simplex.solve();
785 simplex.load_solution();
786
787 EXPECT_TRUE(simplex.verify_solution());
788}
789
790//==============================================================================
791// Accessor Tests
792//==============================================================================
793
794TEST_F(SimplexTest, GetNumVars)
795{
796 Simplex<double> simplex(5);
797 EXPECT_EQ(simplex.get_num_vars(), 5);
798}
799
800TEST_F(SimplexTest, GetNumRestrictions)
801{
802 Simplex<double> simplex(2);
803 EXPECT_EQ(simplex.get_num_restrictions(), 0);
804
805 double c1[] = {1.0, 1.0, 4.0};
806 simplex.put_restriction(c1);
807 EXPECT_EQ(simplex.get_num_restrictions(), 1);
808
809 double c2[] = {2.0, 1.0, 6.0};
810 simplex.put_restriction(c2);
811 EXPECT_EQ(simplex.get_num_restrictions(), 2);
812}
813
814//==============================================================================
815// Large Problem Tests
816//==============================================================================
817
818TEST_F(SimplexTest, MediumSizeProblem)
819{
820 // 5 variables, 5 constraints - each variable bounded
821 const int n = 5;
822
823 Simplex<double> simplex(n);
824
825 // Set objective: maximize sum of all variables
826 for (int i = 0; i < n; ++i)
827 simplex.put_objetive_function_coef(i, 1.0);
828
829 // Add constraints: each variable <= 1
830 for (int j = 0; j < n; ++j)
831 {
832 double* rest = simplex.put_restriction(nullptr);
833 for (int i = 0; i < n; ++i)
834 rest[i] = (i == j) ? 1.0 : 0.0;
835 rest[n] = 1.0; // RHS
836 }
837
838 simplex.prepare_linear_program();
839 auto state = simplex.solve();
840
841 EXPECT_EQ(state, Simplex<double>::Solved);
842
843 simplex.load_solution();
844 EXPECT_TRUE(simplex.verify_solution());
845 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 5.0));
846}
847
848//==============================================================================
849// Numerical Stability Tests
850//==============================================================================
851
852TEST_F(SimplexTest, SmallCoefficients)
853{
854 Simplex<double> simplex(2);
855 simplex.put_objetive_function_coef(0, 0.001);
856 simplex.put_objetive_function_coef(1, 0.002);
857
858 double c1[] = {0.001, 0.001, 0.01};
859 double c2[] = {0.001, 0.0, 0.005};
860 double c3[] = {0.0, 0.001, 0.005};
861 simplex.put_restriction(c1);
862 simplex.put_restriction(c2);
863 simplex.put_restriction(c3);
864
865 simplex.prepare_linear_program();
866 auto state = simplex.solve();
867
868 EXPECT_EQ(state, Simplex<double>::Solved);
869
870 simplex.load_solution();
871 // Just verify we get a valid solution
872 EXPECT_GE(simplex.objetive_value(), 0.0);
873}
874
875TEST_F(SimplexTest, LargeCoefficients)
876{
877 Simplex<double> simplex(2);
878 simplex.put_objetive_function_coef(0, 1000.0);
879 simplex.put_objetive_function_coef(1, 2000.0);
880
881 double c1[] = {1000.0, 1000.0, 10000.0};
882 double c2[] = {1000.0, 0.0, 5000.0};
883 double c3[] = {0.0, 1000.0, 5000.0};
884 simplex.put_restriction(c1);
885 simplex.put_restriction(c2);
886 simplex.put_restriction(c3);
887
888 simplex.prepare_linear_program();
889 auto state = simplex.solve();
890
891 EXPECT_EQ(state, Simplex<double>::Solved);
892
893 simplex.load_solution();
894 EXPECT_TRUE(simplex.verify_solution());
895 // x=5, y=5, Z=15000
896 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 15000.0));
897}
898
899//==============================================================================
900// New Features Tests: Optimization Types, Constraints, Statistics
901//==============================================================================
902
903TEST_F(SimplexTest, MinimizationModeAPI)
904{
905 // Test that minimization mode is properly set and affects optimization
906 // Standard maximization problem for comparison
907 Simplex<double> simplex_max(2, OptimizationType::Maximize);
908 simplex_max.put_objetive_function_coef(0, 40.0);
909 simplex_max.put_objetive_function_coef(1, 30.0);
910
911 double c1[] = {1.0, 1.0, 40.0};
912 double c2[] = {2.0, 1.0, 60.0};
913 simplex_max.put_restriction(c1);
914 simplex_max.put_restriction(c2);
915
916 simplex_max.prepare_linear_program();
917 auto state_max = simplex_max.solve();
918 EXPECT_EQ(state_max, Simplex<double>::Solved);
919
920 simplex_max.load_solution();
921 double max_value = simplex_max.objetive_value();
922
923 // Same problem but with minimization constructor
924 Simplex<double> simplex_min(2, OptimizationType::Minimize);
925 simplex_min.put_objetive_function_coef(0, 40.0);
926 simplex_min.put_objetive_function_coef(1, 30.0);
927
928 simplex_min.put_restriction(c1);
929 simplex_min.put_restriction(c2);
930
931 simplex_min.prepare_linear_program();
932 auto state_min = simplex_min.solve();
933 EXPECT_EQ(state_min, Simplex<double>::Solved);
934
935 simplex_min.load_solution();
936 double min_value = simplex_min.objetive_value();
937
938 // The minimization should find a value <= maximization value
939 // (In this bounded problem, min is at origin: 0)
940 EXPECT_LE(min_value, max_value);
941
942 // Verify optimization types are correctly reported
943 EXPECT_EQ(simplex_max.get_optimization_type(), OptimizationType::Maximize);
944 EXPECT_EQ(simplex_min.get_optimization_type(), OptimizationType::Minimize);
945}
946
947TEST_F(SimplexTest, EqualityConstraintSimulated)
948{
949 // Maximize Z = 5x + 4y
950 // s.t. x + y = 10 (simulated with x + y <= 10 and -x - y <= -10)
951 // x <= 6
952 // y <= 8
953 // x, y >= 0
954 //
955 // Note: True equality constraints require Big-M or two-phase simplex.
956 // Here we test by using tight upper/lower bounds on the sum.
957
958 Simplex<double> simplex(2);
959 simplex.put_objetive_function_coef(0, 5.0);
960 simplex.put_objetive_function_coef(1, 4.0);
961
962 double c1[] = {1.0, 1.0, 10.0}; // x + y <= 10
963 double c2[] = {1.0, 0.0, 6.0}; // x <= 6
964 double c3[] = {0.0, 1.0, 8.0}; // y <= 8
965
966 simplex.put_restriction(c1);
967 simplex.put_restriction(c2);
968 simplex.put_restriction(c3);
969
970 simplex.prepare_linear_program();
971 auto state = simplex.solve();
972
973 EXPECT_EQ(state, Simplex<double>::Solved);
974
975 simplex.load_solution();
976
977 // With x + y <= 10, maximize 5x + 4y
978 // Optimal: x=6, y=4, Z=46 (using full capacity of sum constraint)
979 EXPECT_NEAR(simplex.objetive_value(), 46.0, 0.1);
980}
981
982TEST_F(SimplexTest, ConstraintTypesAPI)
983{
984 // Test that constraint types are properly stored
985 // Maximize Z = 2x + 3y with standard LE constraints
986
987 Simplex<double> simplex(2);
988 simplex.put_objetive_function_coef(0, 2.0);
989 simplex.put_objetive_function_coef(1, 3.0);
990
991 double c1[] = {1.0, 1.0, 10.0}; // x + y <= 10
992 double c2[] = {1.0, 0.0, 8.0}; // x <= 8
993 double c3[] = {0.0, 1.0, 6.0}; // y <= 6
994
995 simplex.put_restriction(c1, ConstraintType::LE);
996 simplex.put_restriction(c2, ConstraintType::LE);
997 simplex.put_restriction(c3, ConstraintType::LE);
998
999 simplex.prepare_linear_program();
1000 auto state = simplex.solve();
1001
1002 EXPECT_EQ(state, Simplex<double>::Solved);
1003
1004 simplex.load_solution();
1005
1006 // Optimal: x=4, y=6, Z=8+18=26 (limited by x+y<=10 and y<=6)
1007 EXPECT_NEAR(simplex.objetive_value(), 26.0, 0.1);
1008 EXPECT_LE(simplex.get_solution(0) + simplex.get_solution(1), 10.1);
1009}
1010
1011TEST_F(SimplexTest, StatisticsTracking)
1012{
1013 Simplex<double> simplex(2);
1014 simplex.put_objetive_function_coef(0, 40.0);
1015 simplex.put_objetive_function_coef(1, 30.0);
1016
1017 double c1[] = {1.0, 1.0, 40.0};
1018 double c2[] = {2.0, 1.0, 60.0};
1019 simplex.put_restriction(c1);
1020 simplex.put_restriction(c2);
1021
1022 simplex.prepare_linear_program();
1023 simplex.solve();
1024
1025 auto stats = simplex.get_stats();
1026
1027 EXPECT_GT(stats.iterations, 0u);
1028 EXPECT_GT(stats.pivots, 0u);
1029 EXPECT_GE(stats.elapsed_ms, 0.0);
1030}
1031
1032TEST_F(SimplexTest, BlandRuleEnabled)
1033{
1034 // Test that Bland's rule can be enabled and affects pivot selection
1035 Simplex<double> simplex(3);
1036 simplex.enable_bland_rule();
1037
1038 simplex.put_objetive_function_coef(0, 100.0);
1039 simplex.put_objetive_function_coef(1, 10.0);
1040 simplex.put_objetive_function_coef(2, 1.0);
1041
1042 double c1[] = {1.0, 0.0, 0.0, 1.0};
1043 double c2[] = {20.0, 1.0, 0.0, 100.0};
1044 double c3[] = {200.0, 20.0, 1.0, 10000.0};
1045
1046 simplex.put_restriction(c1);
1047 simplex.put_restriction(c2);
1048 simplex.put_restriction(c3);
1049
1050 simplex.prepare_linear_program();
1051 auto state = simplex.solve();
1052
1053 EXPECT_EQ(state, Simplex<double>::Solved);
1054
1055 // Verify solution is valid
1056 simplex.load_solution();
1057 EXPECT_TRUE(simplex.verify_solution());
1058
1059 // Optimal is x1=1, x2=80, x3=9800, Z=100+800+9800=10700
1060 EXPECT_GT(simplex.objetive_value(), 0.0);
1061}
1062
1063TEST_F(SimplexTest, SensitivityAnalysisObjective)
1064{
1065 Simplex<double> simplex(2);
1066 simplex.put_objetive_function_coef(0, 40.0);
1067 simplex.put_objetive_function_coef(1, 30.0);
1068
1069 double c1[] = {1.0, 1.0, 40.0};
1070 double c2[] = {2.0, 1.0, 60.0};
1071 simplex.put_restriction(c1);
1072 simplex.put_restriction(c2);
1073
1074 simplex.prepare_linear_program();
1075 simplex.solve();
1076 simplex.load_solution();
1077
1078 auto range = simplex.objective_sensitivity(0);
1079
1080 EXPECT_EQ(range.current_value, 40.0);
1081
1082 // x = y = 20 stays optimal while 40/30 lies between the slopes 1 and 2
1083 // of the constraints: c_0 in [30, 60], c_1 in [20, 40]
1084 EXPECT_NEAR(range.lower_bound, 30.0, 1e-9);
1085 EXPECT_NEAR(range.upper_bound, 60.0, 1e-9);
1086 range = simplex.objective_sensitivity(1);
1087 EXPECT_NEAR(range.lower_bound, 20.0, 1e-9);
1088 EXPECT_NEAR(range.upper_bound, 40.0, 1e-9);
1089
1090 // b_0 in [30, 60] and b_1 in [40, 80] keep x and y basic and >= 0
1091 range = simplex.rhs_sensitivity(0);
1092 EXPECT_EQ(range.current_value, 40.0);
1093 EXPECT_NEAR(range.lower_bound, 30.0, 1e-9);
1094 EXPECT_NEAR(range.upper_bound, 60.0, 1e-9);
1095 range = simplex.rhs_sensitivity(1);
1096 EXPECT_NEAR(range.lower_bound, 40.0, 1e-9);
1097 EXPECT_NEAR(range.upper_bound, 80.0, 1e-9);
1098}
1099
1100TEST_F(SimplexTest, ShadowPrices)
1101{
1102 Simplex<double> simplex(2);
1103 simplex.put_objetive_function_coef(0, 40.0);
1104 simplex.put_objetive_function_coef(1, 30.0);
1105
1106 double c1[] = {1.0, 1.0, 40.0};
1107 double c2[] = {2.0, 1.0, 60.0};
1108 simplex.put_restriction(c1);
1109 simplex.put_restriction(c2);
1110
1111 simplex.prepare_linear_program();
1112 simplex.solve();
1113 simplex.load_solution();
1114
1115 auto prices = simplex.get_all_shadow_prices();
1116
1117 EXPECT_EQ(prices.size(), 2u);
1118
1119 // The optimal dual solution: y_0 + 2 y_1 = 40 and y_0 + y_1 = 30, so
1120 // that 40 y_0 + 60 y_1 = 1400, the optimal value; >= 0, since they are
1121 // of <= constraints in a maximization
1122 EXPECT_NEAR(prices[0], 20.0, 1e-9);
1123 EXPECT_NEAR(prices[1], 10.0, 1e-9);
1124}
1125
1126TEST_F(SimplexTest, ReducedCosts)
1127{
1128 Simplex<double> simplex(2);
1129 simplex.put_objetive_function_coef(0, 40.0);
1130 simplex.put_objetive_function_coef(1, 30.0);
1131
1132 double c1[] = {1.0, 1.0, 40.0};
1133 double c2[] = {2.0, 1.0, 60.0};
1134 simplex.put_restriction(c1);
1135 simplex.put_restriction(c2);
1136
1137 simplex.prepare_linear_program();
1138 simplex.solve();
1139 simplex.load_solution();
1140
1141 auto costs = simplex.get_all_reduced_costs();
1142
1143 EXPECT_EQ(costs.size(), 2u);
1144
1145 // Both variables are basic
1146 EXPECT_NEAR(costs[0], 0.0, 1e-9);
1147 EXPECT_NEAR(costs[1], 0.0, 1e-9);
1148 EXPECT_TRUE(simplex.is_basic_variable(0));
1149 EXPECT_TRUE(simplex.is_basic_variable(1));
1150}
1151
1152TEST_F(SimplexTest, DualSimplexReoptimize)
1153{
1154 Simplex<double> simplex(2);
1155 simplex.put_objetive_function_coef(0, 40.0);
1156 simplex.put_objetive_function_coef(1, 30.0);
1157
1158 double c1[] = {1.0, 1.0, 40.0};
1159 double c2[] = {2.0, 1.0, 60.0};
1160 simplex.put_restriction(c1);
1161 simplex.put_restriction(c2);
1162
1163 simplex.prepare_linear_program();
1164 auto state1 = simplex.solve();
1165 EXPECT_EQ(state1, Simplex<double>::Solved);
1166
1167 simplex.load_solution();
1168 double original_obj = simplex.objetive_value();
1169
1170 // Update RHS of first constraint and reoptimize
1171 auto state2 = simplex.update_rhs_and_reoptimize(0, 50.0);
1172
1173 // 50 is within [30, 60], the range of b_0: x = 60 - 50, y = 2 * 50 - 60,
1174 // and the value grows by the shadow price 20 per unit
1175 ASSERT_EQ(state2, Simplex<double>::Solved);
1176 simplex.load_solution();
1177 EXPECT_NEAR(simplex.get_solution(0), 10.0, 1e-9);
1178 EXPECT_NEAR(simplex.get_solution(1), 40.0, 1e-9);
1179 EXPECT_NEAR(simplex.objetive_value(), original_obj + 20.0 * 10, 1e-9);
1180 EXPECT_TRUE(simplex.verify_solution());
1181}
1182
1183TEST_F(SimplexTest, LargeDegenerateProblem)
1184{
1185 // Create a problem with many constraints that may have degenerate solutions
1186 const size_t n = 10;
1187 Simplex<double> simplex(n);
1188 simplex.enable_bland_rule(); // Prevent cycling
1189
1190 // Objective: maximize sum of xi
1191 for (size_t i = 0; i < n; ++i)
1192 simplex.put_objetive_function_coef(i, 1.0);
1193
1194 // Constraints: each xi <= 1
1195 for (size_t i = 0; i < n; ++i)
1196 {
1197 DynArray<double> c(n + 1);
1198 for (size_t j = 0; j <= n; ++j)
1199 c[j] = 0.0;
1200 c[i] = 1.0;
1201 c[n] = 1.0;
1202 simplex.put_restriction(c);
1203 }
1204
1205 // Sum constraint: sum <= n/2
1206 DynArray<double> sum_c(n + 1);
1207 for (size_t i = 0; i < n; ++i)
1208 sum_c[i] = 1.0;
1209 sum_c[n] = static_cast<double>(n) / 2.0;
1210 simplex.put_restriction(sum_c);
1211
1212 simplex.prepare_linear_program();
1213 auto state = simplex.solve();
1214
1215 EXPECT_EQ(state, Simplex<double>::Solved);
1216
1217 simplex.load_solution();
1218 EXPECT_NEAR(simplex.objetive_value(), static_cast<double>(n) / 2.0, 0.1);
1219
1220 // Check for degenerate pivots
1221 auto stats = simplex.get_stats();
1222 // Some degenerate pivots are expected in this problem
1223 (void)stats; // Just check it doesn't crash
1224}
1225
1226TEST_F(SimplexTest, SetMinimizeMaximize)
1227{
1228 Simplex<double> simplex(2);
1229
1230 EXPECT_EQ(simplex.get_optimization_type(), OptimizationType::Maximize);
1231
1232 simplex.set_minimize();
1233 EXPECT_EQ(simplex.get_optimization_type(), OptimizationType::Minimize);
1234
1235 simplex.set_maximize();
1236 EXPECT_EQ(simplex.get_optimization_type(), OptimizationType::Maximize);
1237}
1238
1239TEST_F(SimplexTest, IsBasicVariable)
1240{
1241 Simplex<double> simplex(2);
1242 simplex.put_objetive_function_coef(0, 40.0);
1243 simplex.put_objetive_function_coef(1, 30.0);
1244
1245 double c1[] = {1.0, 1.0, 40.0};
1246 double c2[] = {2.0, 1.0, 60.0};
1247 simplex.put_restriction(c1);
1248 simplex.put_restriction(c2);
1249
1250 simplex.prepare_linear_program();
1251 simplex.solve();
1252 simplex.load_solution();
1253
1254 // At least one variable should be basic
1255 bool has_basic = simplex.is_basic_variable(0) || simplex.is_basic_variable(1);
1256 EXPECT_TRUE(has_basic);
1257}
1258
1259//==============================================================================
1260// Revised Simplex Tests
1261//==============================================================================
1262
1263class RevisedSimplexTest : public ::testing::Test
1264{
1265protected:
1266 static constexpr double EPSILON = 1e-6;
1267
1268 bool nearly_equal(double a, double b, double eps = EPSILON)
1269 {
1270 return std::fabs(a - b) < eps;
1271 }
1272};
1273
1274TEST_F(RevisedSimplexTest, BasicConstructor)
1275{
1276 RevisedSimplex<double> simplex(3, 2);
1277
1278 EXPECT_EQ(simplex.get_num_vars(), 3);
1279 EXPECT_EQ(simplex.get_num_constraints(), 2);
1280 EXPECT_EQ(simplex.get_state(), RevisedSimplex<double>::Not_Solved);
1281}
1282
1283TEST_F(RevisedSimplexTest, SimpleMaximization)
1284{
1285 // Maximize Z = 40x + 30y
1286 // s.t. x + y <= 40
1287 // 2x + y <= 60
1288
1289 RevisedSimplex<double> simplex(2, 2);
1290
1291 // Objective
1292 simplex.set_objective(0, 40.0);
1293 simplex.set_objective(1, 30.0);
1294
1295 // Constraints
1296 double c1[] = {1.0, 1.0};
1297 double c2[] = {2.0, 1.0};
1298 simplex.set_constraint_row(0, c1, 40.0);
1299 simplex.set_constraint_row(1, c2, 60.0);
1300
1301 auto state = simplex.solve();
1302
1303 EXPECT_EQ(state, RevisedSimplex<double>::Solved);
1304
1305 // Optimal: x=20, y=20, Z=1400
1306 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 20.0, 0.1));
1307 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 20.0, 0.1));
1308 EXPECT_TRUE(nearly_equal(simplex.objective_value(), 1400.0, 0.1));
1309
1310 EXPECT_TRUE(simplex.verify_solution());
1311}
1312
1314{
1315 // Maximize Z = 5x + 4y + 3z
1316 // s.t. 2x + 3y + z <= 5
1317 // 4x + 2y + 3z <= 11
1318 // 3x + 4y + 2z <= 8
1319
1320 RevisedSimplex<double> simplex(3, 3);
1321
1322 simplex.set_objective(0, 5.0);
1323 simplex.set_objective(1, 4.0);
1324 simplex.set_objective(2, 3.0);
1325
1326 double c1[] = {2.0, 3.0, 1.0};
1327 double c2[] = {4.0, 2.0, 3.0};
1328 double c3[] = {3.0, 4.0, 2.0};
1329
1330 simplex.set_constraint_row(0, c1, 5.0);
1331 simplex.set_constraint_row(1, c2, 11.0);
1332 simplex.set_constraint_row(2, c3, 8.0);
1333
1334 auto state = simplex.solve();
1335
1336 EXPECT_EQ(state, RevisedSimplex<double>::Solved);
1337 EXPECT_TRUE(simplex.verify_solution());
1338 EXPECT_GT(simplex.objective_value(), 0.0);
1339}
1340
1341TEST_F(RevisedSimplexTest, CompareWithStandardSimplex)
1342{
1343 // Same problem solved by both algorithms
1344 // Maximize Z = 3x + 2y + 4z
1345 // s.t. x + y + 2z <= 4
1346 // 2x + y + z <= 5
1347
1348 // Standard Simplex
1349 Simplex<double> std_simplex(3);
1350 std_simplex.put_objetive_function_coef(0, 3.0);
1351 std_simplex.put_objetive_function_coef(1, 2.0);
1352 std_simplex.put_objetive_function_coef(2, 4.0);
1353
1354 double c1[] = {1.0, 1.0, 2.0, 4.0};
1355 double c2[] = {2.0, 1.0, 1.0, 5.0};
1356 std_simplex.put_restriction(c1);
1357 std_simplex.put_restriction(c2);
1358
1359 std_simplex.prepare_linear_program();
1360 std_simplex.solve();
1361 std_simplex.load_solution();
1362 double std_obj = std_simplex.objetive_value();
1363
1364 // Revised Simplex
1365 RevisedSimplex<double> rev_simplex(3, 2);
1366 rev_simplex.set_objective(0, 3.0);
1367 rev_simplex.set_objective(1, 2.0);
1368 rev_simplex.set_objective(2, 4.0);
1369
1370 double r1[] = {1.0, 1.0, 2.0};
1371 double r2[] = {2.0, 1.0, 1.0};
1372 rev_simplex.set_constraint_row(0, r1, 4.0);
1373 rev_simplex.set_constraint_row(1, r2, 5.0);
1374
1375 rev_simplex.solve();
1376 double rev_obj = rev_simplex.objective_value();
1377
1378 // Both should find same optimal value
1379 EXPECT_NEAR(std_obj, rev_obj, 0.1);
1380}
1381
1382TEST_F(RevisedSimplexTest, MediumSizeProblem)
1383{
1384 // 10 variables, 5 constraints
1385 const size_t n = 10;
1386 const size_t m = 5;
1387
1388 RevisedSimplex<double> simplex(n, m);
1389
1390 // Random but consistent coefficients
1391 for (size_t j = 0; j < n; ++j)
1392 simplex.set_objective(j, static_cast<double>((j + 1) * 3 % 7 + 1));
1393
1394 for (size_t i = 0; i < m; ++i)
1395 {
1396 for (size_t j = 0; j < n; ++j)
1397 simplex.set_constraint(i, j, static_cast<double>((i + j + 1) % 5 + 1));
1398 simplex.set_rhs(i, static_cast<double>((i + 1) * 20));
1399 }
1400
1401 auto state = simplex.solve();
1402
1403 EXPECT_EQ(state, RevisedSimplex<double>::Solved);
1404 EXPECT_TRUE(simplex.verify_solution());
1405 EXPECT_GT(simplex.objective_value(), 0.0);
1406}
1407
1408TEST_F(RevisedSimplexTest, StatisticsTracking)
1409{
1410 RevisedSimplex<double> simplex(2, 2);
1411
1412 simplex.set_objective(0, 40.0);
1413 simplex.set_objective(1, 30.0);
1414
1415 double c1[] = {1.0, 1.0};
1416 double c2[] = {2.0, 1.0};
1417 simplex.set_constraint_row(0, c1, 40.0);
1418 simplex.set_constraint_row(1, c2, 60.0);
1419
1420 simplex.solve();
1421
1422 auto stats = simplex.get_stats();
1423
1424 EXPECT_GT(stats.iterations, 0u);
1425 EXPECT_GT(stats.pivots, 0u);
1426 EXPECT_GE(stats.elapsed_ms, 0.0);
1427}
1428
1429TEST_F(RevisedSimplexTest, PerformanceBenchmark)
1430{
1431 // Compare performance on a moderate problem with well-defined coefficients
1432 const size_t n = 20; // 20 variables
1433 const size_t m = 10; // 10 constraints
1434
1435 // Setup problem with bounded coefficients
1436 std::vector<double> obj(n);
1437 std::vector<std::vector<double>> A(m, std::vector<double>(n));
1438 std::vector<double> b(m);
1439
1440 for (size_t j = 0; j < n; ++j)
1441 obj[j] = static_cast<double>(j % 5 + 1); // 1-5
1442
1443 for (size_t i = 0; i < m; ++i)
1444 {
1445 double row_sum = 0;
1446 for (size_t j = 0; j < n; ++j)
1447 {
1448 A[i][j] = static_cast<double>((i + j) % 3 + 1); // 1-3
1449 row_sum += A[i][j];
1450 }
1451 b[i] = row_sum * 2; // Ensure feasible region
1452 }
1453
1454 // Standard Simplex
1455 Simplex<double> std_simplex(n);
1456 for (size_t j = 0; j < n; ++j)
1457 std_simplex.put_objetive_function_coef(j, obj[j]);
1458
1459 for (size_t i = 0; i < m; ++i)
1460 {
1461 DynArray<double> row(n + 1);
1462 for (size_t j = 0; j < n; ++j)
1463 row[j] = A[i][j];
1464 row[n] = b[i];
1465 std_simplex.put_restriction(row);
1466 }
1467
1468 std_simplex.prepare_linear_program();
1469 auto std_state = std_simplex.solve();
1470 std_simplex.load_solution();
1471 auto std_stats = std_simplex.get_stats();
1472 double std_obj = std_simplex.objetive_value();
1473
1474 // Revised Simplex
1475 RevisedSimplex<double> rev_simplex(n, m);
1476 rev_simplex.set_objective(obj.data());
1477 for (size_t i = 0; i < m; ++i)
1478 rev_simplex.set_constraint_row(i, A[i].data(), b[i]);
1479
1480 auto rev_state = rev_simplex.solve();
1481 auto rev_stats = rev_simplex.get_stats();
1482 double rev_obj = rev_simplex.objective_value();
1483
1484 // Both should solve successfully
1485 EXPECT_EQ(std_state, Simplex<double>::Solved);
1486 EXPECT_EQ(rev_state, RevisedSimplex<double>::Solved);
1487
1488 // Both should find good solutions
1489 EXPECT_GT(std_obj, 0.0);
1490 EXPECT_GT(rev_obj, 0.0);
1491
1492 std::cout << "\n=== Performance Comparison (n=" << n << ", m=" << m << ") ===\n"
1493 << "Standard Simplex: " << std_stats.elapsed_ms << " ms, "
1494 << std_stats.pivots << " pivots, obj=" << std_obj << "\n"
1495 << "Revised Simplex: " << rev_stats.elapsed_ms << " ms, "
1496 << rev_stats.pivots << " pivots, obj=" << rev_obj << "\n";
1497}
1498
1499//==============================================================================
1500// Non-Standard Constraints Tests (>=, ==)
1501//==============================================================================
1502
1503class NonStandardConstraintsTest : public ::testing::Test
1504{
1505protected:
1506 static constexpr double EPSILON = 1e-6;
1507
1508 bool nearly_equal(double a, double b, double eps = EPSILON)
1509 {
1510 return std::fabs(a - b) < eps;
1511 }
1512};
1513
1514TEST_F(NonStandardConstraintsTest, GreaterThanOrEqualConstraints)
1515{
1516 // Maximize Z = 3x + 2y
1517 // Subject to:
1518 // x + y >= 4 (GE constraint)
1519 // x <= 6 (LE constraint)
1520 // y <= 5 (LE constraint)
1521 // x, y >= 0
1522 // Expected: x=6, y=5 (maximize on corner), but wait, that gives 28
1523 // Actually with x + y >= 4, we want to maximize, so push to upper bounds
1524 // x=6, y=5 satisfies x+y >= 4 (11 >= 4), x <= 6, y <= 5
1525 // Z = 3*6 + 2*5 = 18 + 10 = 28
1526
1527 Simplex<double> simplex(2);
1528 simplex.put_objetive_function_coef(0, 3.0);
1529 simplex.put_objetive_function_coef(1, 2.0);
1530
1531 // GE constraint: x + y >= 4
1532 double c1[] = {1.0, 1.0, 4.0};
1533 simplex.put_restriction(c1, ConstraintType::GE);
1534
1535 // LE constraints
1536 double c2[] = {1.0, 0.0, 6.0};
1537 double c3[] = {0.0, 1.0, 5.0};
1538 simplex.put_restriction(c2, ConstraintType::LE);
1539 simplex.put_restriction(c3, ConstraintType::LE);
1540
1541 simplex.prepare_linear_program();
1542 auto state = simplex.solve();
1543
1544 EXPECT_EQ(state, Simplex<double>::Solved);
1545
1546 simplex.load_solution();
1547
1548 // Should maximize to x=6, y=5, Z=28
1549 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 6.0, 0.1));
1550 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 5.0, 0.1));
1551 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 28.0, 0.1));
1552 EXPECT_TRUE(simplex.verify_solution());
1553}
1554
1556{
1557 // Maximize Z = 5x + 4y
1558 // Subject to:
1559 // x + y = 10 (EQ constraint)
1560 // x <= 6 (LE constraint)
1561 // y <= 8 (LE constraint)
1562 // x, y >= 0
1563 // With x + y = 10, to maximize 5x + 4y, we want x as large as possible
1564 // x = 6 (bounded), then y = 4
1565 // Z = 5*6 + 4*4 = 30 + 16 = 46
1566
1567 Simplex<double> simplex(2);
1568 simplex.put_objetive_function_coef(0, 5.0);
1569 simplex.put_objetive_function_coef(1, 4.0);
1570
1571 // EQ constraint: x + y = 10
1572 double c1[] = {1.0, 1.0, 10.0};
1573 simplex.put_restriction(c1, ConstraintType::EQ);
1574
1575 // LE constraints
1576 double c2[] = {1.0, 0.0, 6.0};
1577 double c3[] = {0.0, 1.0, 8.0};
1578 simplex.put_restriction(c2, ConstraintType::LE);
1579 simplex.put_restriction(c3, ConstraintType::LE);
1580
1581 simplex.prepare_linear_program();
1582 auto state = simplex.solve();
1583
1584 EXPECT_EQ(state, Simplex<double>::Solved);
1585
1586 simplex.load_solution();
1587
1588 // Optimal: x=6, y=4, Z=46
1589 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 6.0, 0.1));
1590 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 4.0, 0.1));
1591 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 46.0, 0.1));
1592 EXPECT_TRUE(simplex.verify_solution());
1593
1594 // Verify equality constraint is satisfied
1595 double sum = simplex.get_solution(0) + simplex.get_solution(1);
1596 EXPECT_TRUE(nearly_equal(sum, 10.0, 0.1));
1597}
1598
1600{
1601 // Maximize Z = 2x + 3y + z
1602 // Subject to:
1603 // x + y + z >= 5 (GE)
1604 // x + 2y <= 10 (LE)
1605 // 2x + y = 8 (EQ)
1606 // z <= 20 (LE) - Added to bound z
1607 // x, y, z >= 0
1608 //
1609 // Analysis: From 2x + y = 8, we get y = 8 - 2x
1610 // For y >= 0: x <= 4
1611 // For x >= 0: x >= 0
1612 // Substituting in x + 2y <= 10: x + 2(8-2x) <= 10 => x >= 2
1613 // So x ∈ [2, 4]
1614 // At x=2: y=4, then z >= 5 - 2 - 4 = -1, so z can be 0 to 20
1615 // Maximize: 2(2) + 3(4) + z = 16 + z, max at z=20 => Z = 36
1616
1617 Simplex<double> simplex(3);
1618 simplex.put_objetive_function_coef(0, 2.0);
1619 simplex.put_objetive_function_coef(1, 3.0);
1620 simplex.put_objetive_function_coef(2, 1.0);
1621
1622 double c1[] = {1.0, 1.0, 1.0, 5.0}; // GE
1623 double c2[] = {1.0, 2.0, 0.0, 10.0}; // LE
1624 double c3[] = {2.0, 1.0, 0.0, 8.0}; // EQ
1625 double c4[] = {0.0, 0.0, 1.0, 20.0}; // z <= 20 (bound z)
1626
1627 simplex.put_restriction(c1, ConstraintType::GE);
1628 simplex.put_restriction(c2, ConstraintType::LE);
1629 simplex.put_restriction(c3, ConstraintType::EQ);
1630 simplex.put_restriction(c4, ConstraintType::LE);
1631
1632 simplex.prepare_linear_program();
1633 auto state = simplex.solve();
1634
1635 EXPECT_EQ(state, Simplex<double>::Solved);
1636
1637 simplex.load_solution();
1638 EXPECT_TRUE(simplex.verify_solution());
1639 EXPECT_GT(simplex.objetive_value(), 0.0);
1640}
1641
1642TEST_F(NonStandardConstraintsTest, MultipleEqualityConstraints)
1643{
1644 // Maximize Z = x + y + z
1645 // Subject to:
1646 // x + y = 5
1647 // y + z = 6
1648 // x, y, z >= 0
1649 // From eq1: x = 5 - y
1650 // From eq2: z = 6 - y
1651 // Z = (5-y) + y + (6-y) = 11 - y
1652 // To maximize, we want y as small as possible (y=0)
1653 // But we need x, z >= 0: x = 5-y >= 0 => y <= 5
1654 // z = 6-y >= 0 => y <= 6
1655 // So y can be 0, giving x=5, z=6, Z=11
1656
1657 Simplex<double> simplex(3);
1658 simplex.put_objetive_function_coef(0, 1.0);
1659 simplex.put_objetive_function_coef(1, 1.0);
1660 simplex.put_objetive_function_coef(2, 1.0);
1661
1662 double c1[] = {1.0, 1.0, 0.0, 5.0};
1663 double c2[] = {0.0, 1.0, 1.0, 6.0};
1664
1665 simplex.put_restriction(c1, ConstraintType::EQ);
1666 simplex.put_restriction(c2, ConstraintType::EQ);
1667
1668 simplex.prepare_linear_program();
1669 auto state = simplex.solve();
1670
1671 EXPECT_EQ(state, Simplex<double>::Solved);
1672
1673 simplex.load_solution();
1674
1675 double x = simplex.get_solution(0);
1676 double y = simplex.get_solution(1);
1677 double z = simplex.get_solution(2);
1678
1679 // Verify equality constraints
1680 EXPECT_TRUE(nearly_equal(x + y, 5.0, 0.1));
1681 EXPECT_TRUE(nearly_equal(y + z, 6.0, 0.1));
1682
1683 EXPECT_TRUE(simplex.verify_solution());
1684}
1685
1686TEST_F(NonStandardConstraintsTest, InfeasibleWithGEConstraints)
1687{
1688 // Maximize Z = x + y
1689 // Subject to:
1690 // x + y >= 10 (GE)
1691 // x <= 3 (LE)
1692 // y <= 4 (LE)
1693 // x, y >= 0
1694 // This is infeasible: x + y >= 10 but x <= 3 and y <= 4 => x + y <= 7
1695 //
1696 // NOTE: This tests whether the Simplex correctly detects infeasibility
1697 // with mixed GE/LE constraints. If the implementation doesn't detect
1698 // infeasibility correctly with GE constraints via Big-M method,
1699 // verify_solution() should still fail.
1700
1701 Simplex<double> simplex(2);
1702 simplex.put_objetive_function_coef(0, 1.0);
1703 simplex.put_objetive_function_coef(1, 1.0);
1704
1705 double c1[] = {1.0, 1.0, 10.0};
1706 double c2[] = {1.0, 0.0, 3.0};
1707 double c3[] = {0.0, 1.0, 4.0};
1708
1709 simplex.put_restriction(c1, ConstraintType::GE);
1710 simplex.put_restriction(c2, ConstraintType::LE);
1711 simplex.put_restriction(c3, ConstraintType::LE);
1712
1713 simplex.prepare_linear_program();
1714 auto state = simplex.solve();
1715
1716 // The problem is infeasible: x + y >= 10, x <= 3 and y <= 4. Simplex
1717 // reported it as solved, with a point that broke a constraint.
1718 EXPECT_EQ(state, Simplex<double>::Unfeasible);
1719}
1720
1721//==============================================================================
1722// Minimization Tests
1723//==============================================================================
1724
1725class MinimizationTest : public ::testing::Test
1726{
1727protected:
1728 static constexpr double EPSILON = 1e-6;
1729
1730 bool nearly_equal(double a, double b, double eps = EPSILON)
1731 {
1732 return std::fabs(a - b) < eps;
1733 }
1734};
1735
1736TEST_F(MinimizationTest, BasicMinimization)
1737{
1738 // Minimize Z = 2x + 3y
1739 // Subject to:
1740 // x + y >= 4
1741 // x + 2y >= 6
1742 // x, y >= 0
1743 // To minimize cost, find the corner of feasible region closest to origin
1744 // Corners: intersection of x+y=4 and x+2y=6
1745 // From eq1: x = 4 - y
1746 // Substitute: (4-y) + 2y = 6 => 4 + y = 6 => y = 2, x = 2
1747 // Z = 2*2 + 3*2 = 4 + 6 = 10
1748
1749 Simplex<double> simplex(2, OptimizationType::Minimize);
1750 simplex.put_objetive_function_coef(0, 2.0);
1751 simplex.put_objetive_function_coef(1, 3.0);
1752
1753 double c1[] = {1.0, 1.0, 4.0};
1754 double c2[] = {1.0, 2.0, 6.0};
1755
1756 simplex.put_restriction(c1, ConstraintType::GE);
1757 simplex.put_restriction(c2, ConstraintType::GE);
1758
1759 simplex.prepare_linear_program();
1760 auto state = simplex.solve();
1761
1762 EXPECT_EQ(state, Simplex<double>::Solved);
1763
1764 simplex.load_solution();
1765
1766 EXPECT_TRUE(nearly_equal(simplex.get_solution(0), 2.0, 0.1));
1767 EXPECT_TRUE(nearly_equal(simplex.get_solution(1), 2.0, 0.1));
1768 EXPECT_TRUE(nearly_equal(simplex.objetive_value(), 10.0, 0.1));
1769 EXPECT_TRUE(simplex.verify_solution());
1770}
1771
1773{
1774 // Classic diet problem (minimize cost)
1775 // Minimize Z = 3x + 5y (cost per serving)
1776 // Subject to:
1777 // 2x + y >= 10 (protein requirement)
1778 // x + 2y >= 8 (vitamin requirement)
1779 // x, y >= 0
1780
1781 Simplex<double> simplex(2, OptimizationType::Minimize);
1782 simplex.put_objetive_function_coef(0, 3.0);
1783 simplex.put_objetive_function_coef(1, 5.0);
1784
1785 double c1[] = {2.0, 1.0, 10.0};
1786 double c2[] = {1.0, 2.0, 8.0};
1787
1788 simplex.put_restriction(c1, ConstraintType::GE);
1789 simplex.put_restriction(c2, ConstraintType::GE);
1790
1791 simplex.prepare_linear_program();
1792 auto state = simplex.solve();
1793
1794 EXPECT_EQ(state, Simplex<double>::Solved);
1795
1796 simplex.load_solution();
1797
1798 double x = simplex.get_solution(0);
1799 double y = simplex.get_solution(1);
1800
1801 // Verify constraints are satisfied
1802 EXPECT_GE(2*x + y, 10.0 - EPSILON);
1803 EXPECT_GE(x + 2*y, 8.0 - EPSILON);
1804
1805 EXPECT_TRUE(simplex.verify_solution());
1806 EXPECT_GT(simplex.objetive_value(), 0.0);
1807}
1808
1809TEST_F(MinimizationTest, TransportationCostMinimization)
1810{
1811 // Minimize Z = 4x1 + 2x2 + 3x3 + x4
1812 // Subject to:
1813 // x1 + x2 >= 10 (demand at location 1)
1814 // x3 + x4 >= 15 (demand at location 2)
1815 // x1 + x3 <= 20 (supply from warehouse 1)
1816 // x2 + x4 <= 20 (supply from warehouse 2)
1817 // all xi >= 0
1818
1819 Simplex<double> simplex(4, OptimizationType::Minimize);
1820 simplex.put_objetive_function_coef(0, 4.0);
1821 simplex.put_objetive_function_coef(1, 2.0);
1822 simplex.put_objetive_function_coef(2, 3.0);
1823 simplex.put_objetive_function_coef(3, 1.0);
1824
1825 double c1[] = {1.0, 1.0, 0.0, 0.0, 10.0}; // GE
1826 double c2[] = {0.0, 0.0, 1.0, 1.0, 15.0}; // GE
1827 double c3[] = {1.0, 0.0, 1.0, 0.0, 20.0}; // LE
1828 double c4[] = {0.0, 1.0, 0.0, 1.0, 20.0}; // LE
1829
1830 simplex.put_restriction(c1, ConstraintType::GE);
1831 simplex.put_restriction(c2, ConstraintType::GE);
1832 simplex.put_restriction(c3, ConstraintType::LE);
1833 simplex.put_restriction(c4, ConstraintType::LE);
1834
1835 simplex.prepare_linear_program();
1836 auto state = simplex.solve();
1837
1838 EXPECT_EQ(state, Simplex<double>::Solved);
1839
1840 simplex.load_solution();
1841 EXPECT_TRUE(simplex.verify_solution());
1842
1843 // Cost should be minimized (use cheaper routes)
1844 double cost = simplex.objetive_value();
1845 EXPECT_GT(cost, 0.0);
1846 EXPECT_LT(cost, 100.0); // Should be reasonable
1847}
1848
1849TEST_F(MinimizationTest, SetMinimizeMethod)
1850{
1851 // Test using set_minimize() method
1852 Simplex<double> simplex(2); // Default is Maximize
1853
1854 simplex.set_minimize();
1855 EXPECT_EQ(simplex.get_optimization_type(), OptimizationType::Minimize);
1856
1857 simplex.put_objetive_function_coef(0, 5.0);
1858 simplex.put_objetive_function_coef(1, 4.0);
1859
1860 double c1[] = {1.0, 1.0, 8.0};
1861 simplex.put_restriction(c1, ConstraintType::GE);
1862
1863 simplex.prepare_linear_program();
1864 auto state = simplex.solve();
1865
1866 EXPECT_EQ(state, Simplex<double>::Solved);
1867 simplex.load_solution();
1868
1869 // Should minimize to a corner satisfying x + y >= 8
1870 // Optimal would be on the line x + y = 8, minimizing 5x + 4y
1871 // To minimize, we want more of y (cheaper): x=0, y=8 gives Z=32
1872 double x = simplex.get_solution(0);
1873 double y = simplex.get_solution(1);
1874
1875 EXPECT_GE(x + y, 8.0 - EPSILON);
1876 EXPECT_TRUE(simplex.verify_solution());
1877}
1878
1879TEST_F(MinimizationTest, MinimizationWithEquality)
1880{
1881 // Minimize Z = x + 2y + 3z
1882 // Subject to:
1883 // x + y + z = 10
1884 // x + z >= 4
1885 // y >= 2
1886
1887 Simplex<double> simplex(3, OptimizationType::Minimize);
1888 simplex.put_objetive_function_coef(0, 1.0);
1889 simplex.put_objetive_function_coef(1, 2.0);
1890 simplex.put_objetive_function_coef(2, 3.0);
1891
1892 double c1[] = {1.0, 1.0, 1.0, 10.0};
1893 double c2[] = {1.0, 0.0, 1.0, 4.0};
1894 double c3[] = {0.0, 1.0, 0.0, 2.0};
1895
1896 simplex.put_restriction(c1, ConstraintType::EQ);
1897 simplex.put_restriction(c2, ConstraintType::GE);
1898 simplex.put_restriction(c3, ConstraintType::GE);
1899
1900 simplex.prepare_linear_program();
1901 auto state = simplex.solve();
1902
1903 EXPECT_EQ(state, Simplex<double>::Solved);
1904
1905 simplex.load_solution();
1906
1907 double x = simplex.get_solution(0);
1908 double y = simplex.get_solution(1);
1909 double z = simplex.get_solution(2);
1910
1911 // Verify constraints
1912 EXPECT_TRUE(nearly_equal(x + y + z, 10.0, 0.1));
1913 EXPECT_GE(x + z, 4.0 - EPSILON);
1914 EXPECT_GE(y, 2.0 - EPSILON);
1915
1916 EXPECT_TRUE(simplex.verify_solution());
1917}
1918
1919TEST_F(MinimizationTest, CompareMinimizeVsNegatedMaximize)
1920{
1921 // Verify that Minimize(c·x) = -Maximize(-c·x)
1922
1923 // Problem: Minimize 3x + 2y subject to x + y >= 5, x,y >= 0
1924 Simplex<double> simplex_min(2, OptimizationType::Minimize);
1925 simplex_min.put_objetive_function_coef(0, 3.0);
1926 simplex_min.put_objetive_function_coef(1, 2.0);
1927
1928 double c1[] = {1.0, 1.0, 5.0};
1929 simplex_min.put_restriction(c1, ConstraintType::GE);
1930
1931 simplex_min.prepare_linear_program();
1932 simplex_min.solve();
1933 simplex_min.load_solution();
1934
1935 double min_value = simplex_min.objetive_value();
1936
1937 // Same problem as maximization with negated coefficients
1938 Simplex<double> simplex_max(2, OptimizationType::Maximize);
1939 simplex_max.put_objetive_function_coef(0, -3.0);
1940 simplex_max.put_objetive_function_coef(1, -2.0);
1941
1942 simplex_max.put_restriction(c1, ConstraintType::GE);
1943
1944 simplex_max.prepare_linear_program();
1945 simplex_max.solve();
1946 simplex_max.load_solution();
1947
1948 double max_value = simplex_max.objetive_value();
1949
1950 // They should be negatives of each other
1951 EXPECT_TRUE(nearly_equal(min_value, -max_value, 0.1));
1952}
1953
1954//==============================================================================
1955// The defects of the Big-M version, and the classic hard programs
1956//==============================================================================
1957
1958namespace
1959{
1960 using Rows = std::initializer_list<std::pair<std::vector<double>, ConstraintType>>;
1961
1962 // Adds the rows to lp and prepares it
1963 void add_rows(Simplex<double> & lp, Rows rows)
1964 {
1965 for (const auto & [row, type] : rows)
1966 lp.put_restriction(row.data(), type);
1968 }
1969
1970 // A file name in the temporary directory, unused
1971 std::string temp_name(const std::string & stem)
1972 {
1973 return (std::filesystem::temp_directory_path()
1974 / (stem + "_" + std::to_string(std::random_device{}()))).string();
1975 }
1976
1977 std::string read_file(const std::string & name)
1978 {
1979 std::ifstream in(name);
1980 std::ostringstream s;
1981 s << in.rdbuf();
1982 return s.str();
1983 }
1984}
1985
1986TEST(SimplexDefects, AnInfeasibleProgramIsReported)
1987{
1988 // x <= 0 and x >= 1: Simplex reported it as solved
1989 Simplex<double> lp(1);
1991 add_rows(lp, {{{1, 0}, ConstraintType::LE}, {{1, 1}, ConstraintType::GE}});
1992
1993 EXPECT_EQ(lp.solve(), Simplex<double>::Unfeasible);
1994 EXPECT_EQ(lp.get_state(), Simplex<double>::Unfeasible);
1995 EXPECT_THROW((void) lp.shadow_price(0), std::logic_error);
1996 EXPECT_THROW((void) lp.update_rhs_and_reoptimize(0, 2), std::logic_error);
1997}
1998
1999TEST(SimplexDefects, ColumnsWithTheSameUnitVectorAreNotBothBasic)
2000{
2001 // max x + y, x + y <= 1: at the optimum both columns are the same unit
2002 // vector of cost zero, and the solution was read as x = y = 1
2003 Simplex<double> lp(2);
2006 add_rows(lp, {{{1, 1, 1}, ConstraintType::LE}});
2007
2008 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2009 lp.load_solution();
2010 EXPECT_NEAR(lp.get_solution(0) + lp.get_solution(1), 1.0, 1e-12);
2011 EXPECT_NEAR(lp.objetive_value(), 1.0, 1e-12);
2012 EXPECT_TRUE(lp.verify_solution());
2013 EXPECT_NE(lp.is_basic_variable(0), lp.is_basic_variable(1));
2014}
2015
2016TEST(SimplexDefects, ANegativeRightHandSideIsNotIgnored)
2017{
2018 {
2019 // max -x, -x <= -1, x <= 3: the first row was skipped, which gave x = 0
2020 Simplex<double> lp(1);
2022 add_rows(lp, {{{-1, -1}, ConstraintType::LE}, {{1, 3}, ConstraintType::LE}});
2023 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2024 lp.load_solution();
2025 EXPECT_NEAR(lp.get_solution(0), 1.0, 1e-12);
2026 EXPECT_NEAR(lp.objetive_value(), -1.0, 1e-12);
2027 EXPECT_TRUE(lp.verify_solution());
2028 // the shadow price of -x <= -1 when maximizing -x: raising b by one
2029 // lowers x by one, and raises the objective by one
2030 EXPECT_NEAR(lp.shadow_price(0), 1.0, 1e-12);
2031 }
2032 {
2033 // min x + y, x - y = -1: (0, 1)
2034 Simplex<double> lp(2, OptimizationType::Minimize);
2037 add_rows(lp, {{{1, -1, -1}, ConstraintType::EQ}});
2038 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2039 lp.load_solution();
2040 EXPECT_NEAR(lp.get_solution(0), 0.0, 1e-12);
2041 EXPECT_NEAR(lp.get_solution(1), 1.0, 1e-12);
2042 }
2043 {
2044 // max -x - y, x - y >= -2, which holds at 0: (0, 0)
2045 Simplex<double> lp(2);
2048 add_rows(lp, {{{1, -1, -2}, ConstraintType::GE}});
2049 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2050 lp.load_solution();
2051 EXPECT_NEAR(lp.objetive_value(), 0.0, 1e-12);
2052 }
2053 {
2054 // x + y <= 5 and x + y >= 10 written as -x - y <= -10: infeasible
2055 Simplex<double> lp(2);
2058 add_rows(lp, {{{1, 1, 5}, ConstraintType::LE}, {{-1, -1, -10}, ConstraintType::LE}});
2059 EXPECT_EQ(lp.solve(), Simplex<double>::Unfeasible);
2060 }
2061}
2062
2063TEST(SimplexDefects, AnObjectiveAboveTheBigMOfBefore)
2064{
2065 // min 1e12 x, x >= 1: with an artificial variable of cost 1e9, keeping it
2066 // in the basis was cheaper than x, and that was the solution
2067 Simplex<double> lp(1, OptimizationType::Minimize);
2068 lp.put_objetive_function_coef(0, 1e12);
2069 add_rows(lp, {{{1, 1}, ConstraintType::GE}});
2070 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2071 lp.load_solution();
2072 EXPECT_NEAR(lp.get_solution(0), 1.0, 1e-12);
2073 EXPECT_NEAR(lp.objetive_value(), 1e12, 1e-3);
2074}
2075
2076TEST(SimplexDefects, SensitivityOfEqualitiesAndOfGreaterOrEqual)
2077{
2078 {
2079 // max x, x = 2: the shadow price of an = was 0
2080 Simplex<double> lp(1);
2082 add_rows(lp, {{{1, 2}, ConstraintType::EQ}});
2083 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2084 EXPECT_NEAR(lp.shadow_price(0), 1.0, 1e-12);
2085 }
2086 {
2087 // min x + y, x + y = 3, x - y = 1: (2, 1); the dual y_0 + y_1 = 1,
2088 // y_0 - y_1 = 1 gives (1, 0)
2089 Simplex<double> lp(2, OptimizationType::Minimize);
2092 add_rows(lp, {{{1, 1, 3}, ConstraintType::EQ}, {{1, -1, 1}, ConstraintType::EQ}});
2093 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2094 lp.load_solution();
2095 EXPECT_NEAR(lp.get_solution(0), 2.0, 1e-12);
2096 EXPECT_NEAR(lp.get_solution(1), 1.0, 1e-12);
2097 EXPECT_NEAR(lp.shadow_price(0), 1.0, 1e-12);
2098 EXPECT_NEAR(lp.shadow_price(1), 0.0, 1e-12);
2099 }
2100 {
2101 // min 2x + 3y, x + y >= 4, x + 3y >= 6: (3, 1), z = 9; the duals 1.5
2102 // and 0.5; x = (3 b_0 - b_1) / 2 and y = (b_1 - b_0) / 2 give b_0 in
2103 // [2, 6] and b_1 in [4, 12]; c_x / c_y in [1/3, 1] gives c_x in [1, 3]
2104 // and c_y in [2, 6]
2105 Simplex<double> lp(2, OptimizationType::Minimize);
2108 add_rows(lp, {{{1, 1, 4}, ConstraintType::GE}, {{1, 3, 6}, ConstraintType::GE}});
2109 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2110 lp.load_solution();
2111 EXPECT_NEAR(lp.objetive_value(), 9.0, 1e-12);
2112 EXPECT_NEAR(lp.shadow_price(0), 1.5, 1e-12);
2113 EXPECT_NEAR(lp.shadow_price(1), 0.5, 1e-12);
2114
2115 auto r = lp.rhs_sensitivity(0);
2116 EXPECT_NEAR(r.lower_bound, 2.0, 1e-12);
2117 EXPECT_NEAR(r.upper_bound, 6.0, 1e-12);
2118 r = lp.rhs_sensitivity(1);
2119 EXPECT_NEAR(r.lower_bound, 4.0, 1e-12);
2120 EXPECT_NEAR(r.upper_bound, 12.0, 1e-12);
2121 r = lp.objective_sensitivity(0);
2122 EXPECT_NEAR(r.lower_bound, 1.0, 1e-12);
2123 EXPECT_NEAR(r.upper_bound, 3.0, 1e-12);
2124 r = lp.objective_sensitivity(1);
2125 EXPECT_NEAR(r.lower_bound, 2.0, 1e-12);
2126 EXPECT_NEAR(r.upper_bound, 6.0, 1e-12);
2127 }
2128 {
2129 // A non-basic variable: max x, x <= 3, x + y <= 5 has y = 0, and it
2130 // stays so while its cost is <= 0
2131 Simplex<double> lp(2);
2133 add_rows(lp, {{{1, 0, 3}, ConstraintType::LE}, {{1, 1, 5}, ConstraintType::LE}});
2134 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2135 lp.load_solution();
2136 if (not lp.is_basic_variable(1))
2137 {
2138 const auto r = lp.objective_sensitivity(1);
2139 EXPECT_TRUE(r.is_unbounded_below());
2140 EXPECT_NEAR(r.upper_bound, 0.0, 1e-12);
2141 }
2142 }
2143}
2144
2145TEST(SimplexDefects, ReoptimizationOfEqualitiesAndOfGreaterOrEqual)
2146{
2147 {
2148 // max x, x = 2, x <= 10; x = 5: the change of an = was lost
2149 Simplex<double> lp(1);
2151 add_rows(lp, {{{1, 2}, ConstraintType::EQ}, {{1, 10}, ConstraintType::LE}});
2152 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2154 lp.load_solution();
2155 EXPECT_NEAR(lp.get_solution(0), 5.0, 1e-12);
2156 // beyond the <= : infeasible
2158 EXPECT_THROW((void) lp.update_rhs_and_reoptimize(0, 1), std::logic_error);
2159 }
2160 {
2161 // min x + y, x + y >= 2, x - y = 0: (1, 1); x + y >= 4: (2, 2)
2162 Simplex<double> lp(2, OptimizationType::Minimize);
2165 add_rows(lp, {{{1, 1, 2}, ConstraintType::GE}, {{1, -1, 0}, ConstraintType::EQ}});
2166 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2168 lp.load_solution();
2169 EXPECT_NEAR(lp.get_solution(0), 2.0, 1e-12);
2170 EXPECT_NEAR(lp.get_solution(1), 2.0, 1e-12);
2171 // x - y = 2 too: (3, 1)
2173 lp.load_solution();
2174 EXPECT_NEAR(lp.get_solution(0), 3.0, 1e-12);
2175 EXPECT_NEAR(lp.get_solution(1), 1.0, 1e-12);
2176 EXPECT_TRUE(lp.verify_solution());
2177 }
2178 {
2179 // max -x, -x <= -1, whose row was multiplied by -1, and x <= 3: x = 1;
2180 // -x <= 2 always holds: x = 0; x <= -1 cannot hold
2181 Simplex<double> lp(1);
2183 add_rows(lp, {{{-1, -1}, ConstraintType::LE}, {{1, 3}, ConstraintType::LE}});
2184 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2186 lp.load_solution();
2187 EXPECT_NEAR(lp.get_solution(0), 0.0, 1e-12);
2189 }
2190 {
2191 // x + y = 1 twice: the second row is redundant; x + y = 2 in it makes
2192 // the program infeasible
2193 Simplex<double> lp(2);
2195 add_rows(lp, {{{1, 1, 1}, ConstraintType::EQ}, {{1, 1, 1}, ConstraintType::EQ}});
2196 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2197 lp.load_solution();
2198 EXPECT_NEAR(lp.objetive_value(), 1.0, 1e-12);
2199 // the duals are not unique, but they add up to the value
2200 EXPECT_NEAR(lp.shadow_price(0) + lp.shadow_price(1), 1.0, 1e-12);
2202 }
2203}
2204
2205TEST(SimplexDefects, PrintAndLatexOutput)
2206{
2207 // print_matrix(), latex_matrix() and so latex_solve() did not compile
2208 Simplex<double> lp(2, OptimizationType::Minimize);
2211 add_rows(lp, {{{1, 1, 4}, ConstraintType::GE}, {{1, 3, 6}, ConstraintType::EQ},
2212 {{1, 0, 9}, ConstraintType::LE}});
2213
2214 testing::internal::CaptureStdout();
2215 lp.print_matrix();
2216 const std::string out = testing::internal::GetCapturedStdout();
2217 // row 0 and three rows, of the scaled program, whose slack and
2218 // artificial variables have unit columns
2219 EXPECT_EQ(std::count(out.begin(), out.end(), '\n'), 4);
2220 EXPECT_NE(out.find("1.00"), std::string::npos);
2221
2222 const std::string program = temp_name("aleph_simplex_program") + ".tex";
2223 lp.latex_linear_program(program);
2224 const std::string text = read_file(program);
2225 EXPECT_NE(text.find("\\min"), std::string::npos);
2226 EXPECT_NE(text.find("\\geq"), std::string::npos);
2227 EXPECT_NE(text.find(" = "), std::string::npos);
2228 EXPECT_NE(text.find("\\leq"), std::string::npos);
2229 std::filesystem::remove(program);
2230
2231 const std::string base = temp_name("aleph_simplex_steps");
2232 ASSERT_EQ(lp.latex_solve(base.c_str()), Simplex<double>::Solved);
2233 EXPECT_NE(read_file(base + "-1.tex").find("\\circled"), std::string::npos);
2234 for (size_t k = 0; k <= lp.get_pivot_count() + 1; ++k)
2235 {
2236 std::filesystem::remove(base + "-" + std::to_string(k) + ".tex");
2237 std::filesystem::remove(base + "-" + std::to_string(k) + "-after.tex");
2238 }
2239 lp.load_solution();
2240 EXPECT_NEAR(lp.objetive_value(), 9.0, 1e-12);
2241
2242 Simplex<double> unprepared(1);
2243 EXPECT_THROW(unprepared.print_matrix(), std::logic_error);
2244}
2245
2246TEST(SimplexDefects, LargeCoefficientsDoNotHideTheLeavingRow)
2247{
2248 // max 4x + 2y, 2e8 x - 1e8 y <= 2e8, 5e8 x + 1e8 y <= 8e8: (0, 8), z =
2249 // 16. With a tolerance of the size of the coefficients, 1e-5, the
2250 // entries of order 1e-9 of the column of a slack looked like zeros, and
2251 // the program unbounded (found by Codex)
2252 Simplex<double> lp(2);
2255 add_rows(lp, {{{2e8, -1e8, 2e8}, ConstraintType::LE}, {{5e8, 1e8, 8e8}, ConstraintType::LE}});
2256 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2257 lp.load_solution();
2258 EXPECT_NEAR(lp.get_solution(0), 0.0, 1e-12);
2259 EXPECT_NEAR(lp.get_solution(1), 8.0, 1e-12);
2260 EXPECT_NEAR(lp.objetive_value(), 16.0, 1e-12);
2261}
2262
2263TEST(SimplexDefects, SmallDataDoNotMakeAPivot)
2264{
2265 // Three unbounded programs, with their data multiplied by 1e-6 (found by
2266 // the CI, whose libc++ made them). With a tolerance that did not go
2267 // below eps for data below 1, a zero of the tableau came out as a
2268 // rounding error above it, which looked like a pivot, and the programs
2269 // as solved, with optima near -1e11. The products are not the literals
2270 // in their last bits (5 * 1e-6 is not 5e-6), and the literals do not
2271 // show the defect
2272 using C = ConstraintType;
2273 struct Program
2274 {
2275 std::vector<double> c;
2276 std::vector<std::pair<std::vector<double>, ConstraintType>> rows;
2277 };
2278 const Program programs[] = {
2279 {{-5, 2, -4},
2280 {{{5, -3, -2, 10}, C::LE}, {{3, 1, 0, 7}, C::LE}, {{0, -1, 0, -1}, C::GE},
2281 {{0, 0, 2, -1}, C::GE}}},
2282 {{-4, 0}, {{{0, -3, -9}, C::EQ}, {{-4, 5, 4}, C::LE}, {{0, 0, 0}, C::EQ}, {{0, 0, 3}, C::LE}}},
2283 {{3, -4, -2},
2284 {{{0, -2, 5, 2}, C::LE}, {{0, -1, 4, 4}, C::LE}, {{0, 0, -3, 6}, C::LE},
2285 {{0, 0, 2, 3}, C::EQ}}}};
2286 const double u = 1e-6;
2287 for (const auto & p : programs)
2288 {
2289 Simplex<double> lp(p.c.size(), OptimizationType::Minimize);
2290 for (size_t j = 0; j < p.c.size(); ++j)
2291 lp.put_objetive_function_coef(j, p.c[j] * u);
2292 for (auto [row, type] : p.rows)
2293 {
2294 for (double & x : row)
2295 x *= u;
2296 lp.put_restriction(row.data(), type);
2297 }
2299 EXPECT_EQ(lp.solve(), Simplex<double>::Unbounded) << "program " << &p - programs;
2300 }
2301}
2302
2303TEST(SimplexScaling, TheSensitivityInOtherUnits)
2304{
2305 // The sensitivity of the textbook program, in other units: the prices
2306 // and the ranges scale with them, though the solver scales the program
2307 Simplex<double> lp(2);
2308 lp.put_objetive_function_coef(0, 40e-3);
2309 lp.put_objetive_function_coef(1, 30e-3);
2310 add_rows(lp, {{{1e5, 1e5, 40e5}, ConstraintType::LE}, {{2e5, 1e5, 60e5}, ConstraintType::LE}});
2311 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2312 EXPECT_NEAR(lp.shadow_price(0), 20e-3 / 1e5, 1e-15);
2313 EXPECT_NEAR(lp.shadow_price(1), 10e-3 / 1e5, 1e-15);
2314 auto r = lp.rhs_sensitivity(0);
2315 EXPECT_NEAR(r.lower_bound, 30e5, 1e-6);
2316 EXPECT_NEAR(r.upper_bound, 60e5, 1e-6);
2317 r = lp.objective_sensitivity(0);
2318 EXPECT_NEAR(r.lower_bound, 30e-3, 1e-15);
2319 EXPECT_NEAR(r.upper_bound, 60e-3, 1e-15);
2320 ASSERT_EQ(lp.update_rhs_and_reoptimize(0, 50e5), Simplex<double>::Solved);
2321 lp.load_solution();
2322 EXPECT_NEAR(lp.get_solution(0), 10.0, 1e-9);
2323 EXPECT_NEAR(lp.get_solution(1), 40.0, 1e-9);
2324}
2325
2326TEST(SimplexScaling, SubnormalMagnitudesAreNotScaled)
2327{
2328 // max x, t x <= 1, x <= 5, with t = 2^-1032, subnormal: x = 5. The
2329 // power of two that would take t into [1/2, 1) overflows: the row stays
2330 // as it is, and its coefficient, below the tolerance, counts as zero, as
2331 // it did before the scaling
2332 const double t = std::ldexp(1.0, -1032);
2333 Simplex<double> lp(1);
2335 add_rows(lp, {{{t, 1}, ConstraintType::LE}, {{1, 5}, ConstraintType::LE}});
2336 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2337 lp.load_solution();
2338 EXPECT_DOUBLE_EQ(lp.get_solution(0), 5.0);
2339 EXPECT_TRUE(lp.verify_solution());
2340
2341 RevisedSimplex<double> rs(1, 2);
2342 rs.set_objective(0, 1);
2343 const double r1[] = {t}, r2[] = {1};
2344 rs.set_constraint_row(0, r1, 1);
2345 rs.set_constraint_row(1, r2, 5);
2346 ASSERT_EQ(rs.solve(), RevisedSimplex<double>::Solved);
2347 EXPECT_DOUBLE_EQ(rs.objective_value(), 5.0);
2348 EXPECT_TRUE(rs.verify_solution());
2349
2350 // float, whose subnormals are below 2^-126
2351 Simplex<float> lf(1);
2353 float f1[] = {std::ldexp(1.0f, -140), 1}, f2[] = {1, 5};
2354 lf.put_restriction(f1, ConstraintType::LE);
2355 lf.put_restriction(f2, ConstraintType::LE);
2357 ASSERT_EQ(lf.solve(), Simplex<float>::Solved);
2358 lf.load_solution();
2359 EXPECT_FLOAT_EQ(lf.get_solution(0), 5.0f);
2360
2361 // an objective of subnormals: zero, so that any feasible point is optimal
2362 Simplex<double> lo(1);
2364 add_rows(lo, {{{1, 5}, ConstraintType::LE}});
2365 ASSERT_EQ(lo.solve(), Simplex<double>::Solved);
2366 lo.load_solution();
2367 EXPECT_TRUE(lo.verify_solution());
2368 EXPECT_LE(std::abs(lo.objetive_value()), 1e-300);
2369
2370 // a column of subnormals: x can grow beyond the largest double
2371 Simplex<double> lc(2);
2374 add_rows(lc, {{{t, 0, 1}, ConstraintType::LE}, {{0, 1, 2}, ConstraintType::LE}});
2375 EXPECT_EQ(lc.solve(), Simplex<double>::Unbounded);
2376}
2377
2378TEST(SimplexClassic, BealesCyclingProgramEnds)
2379{
2380 // Beale (1955): a degenerate program on which the most negative cost
2381 // with ties broken by the least index cycles; the optimum is 1/20 at
2382 // x = (1/25, 0, 1, 0)
2383 for (bool bland : {false, true})
2384 {
2385 Simplex<double> lp(4);
2386 lp.put_objetive_function_coef(0, 0.75);
2387 lp.put_objetive_function_coef(1, -150);
2388 lp.put_objetive_function_coef(2, 0.02);
2390 if (bland)
2391 lp.enable_bland_rule();
2392 add_rows(lp, {{{0.25, -60, -0.04, 9, 0}, ConstraintType::LE},
2393 {{0.5, -90, -0.02, 3, 0}, ConstraintType::LE},
2394 {{0, 0, 1, 0, 1}, ConstraintType::LE}});
2395 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2396 lp.load_solution();
2397 EXPECT_NEAR(lp.objetive_value(), 0.05, 1e-12);
2398 EXPECT_NEAR(lp.get_solution(0), 0.04, 1e-12);
2399 EXPECT_NEAR(lp.get_solution(2), 1.0, 1e-12);
2400 EXPECT_TRUE(lp.verify_solution());
2401
2402 const auto & st = lp.get_stats();
2403 EXPECT_GE(st.iterations, st.pivots);
2404 EXPECT_GE(st.pivots, st.degenerate_pivots);
2405 EXPECT_GT(st.degenerate_pivots, 0u);
2406 }
2407}
2408
2409TEST(SimplexClassic, KleeMintyCube)
2410{
2411 // max sum 2^(n-j) x_j, sum_{j<i} 2^(i-j+1) x_j + x_i <= 5^i: on the
2412 // program as it is, the most negative cost visits every vertex; on the
2413 // scaled one that the solver works on, it takes x_n first. The optimum is
2414 // x_n = 5^n.
2415 const size_t n = 8;
2416 for (bool bland : {false, true})
2417 {
2418 Simplex<double> lp(n);
2419 for (size_t j = 0; j < n; ++j)
2420 lp.put_objetive_function_coef(j, std::pow(2.0, double(n - 1 - j)));
2421 if (bland)
2422 lp.enable_bland_rule();
2423 for (size_t i = 0; i < n; ++i)
2424 {
2425 std::vector<double> row(n + 1, 0.0);
2426 for (size_t j = 0; j < i; ++j)
2427 row[j] = std::pow(2.0, double(i - j + 1));
2428 row[i] = 1;
2429 row[n] = std::pow(5.0, double(i + 1));
2430 lp.put_restriction(row.data());
2431 }
2433 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2434 lp.load_solution();
2435 EXPECT_NEAR(lp.objetive_value(), std::pow(5.0, double(n)), 1e-6);
2436 EXPECT_NEAR(lp.get_solution(n - 1), std::pow(5.0, double(n)), 1e-6);
2437 EXPECT_TRUE(lp.verify_solution());
2438 }
2439}
2440
2441TEST(SimplexClassic, ZeroRowsAndZeroObjective)
2442{
2443 {
2444 // 0 <= 5 always holds, 0 >= -5 too
2445 Simplex<double> lp(1);
2447 add_rows(lp, {{{0, 5}, ConstraintType::LE}, {{0, -5}, ConstraintType::GE},
2448 {{1, 3}, ConstraintType::LE}});
2449 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2450 lp.load_solution();
2451 EXPECT_NEAR(lp.get_solution(0), 3.0, 1e-12);
2452 }
2453 for (auto [rhs, type] : {std::pair{5.0, ConstraintType::GE}, std::pair{3.0, ConstraintType::EQ},
2454 std::pair{-1.0, ConstraintType::LE}})
2455 {
2456 // 0 >= 5, 0 = 3 and 0 <= -1 never hold
2457 Simplex<double> lp(1);
2459 double row[] = {0, rhs};
2460 lp.put_restriction(row, type);
2462 EXPECT_EQ(lp.solve(), Simplex<double>::Unfeasible);
2463 }
2464 {
2465 // 0 = 0 is redundant
2466 Simplex<double> lp(1);
2468 add_rows(lp, {{{0, 0}, ConstraintType::EQ}, {{1, 2}, ConstraintType::LE}});
2469 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2470 lp.load_solution();
2471 EXPECT_NEAR(lp.get_solution(0), 2.0, 1e-12);
2472 }
2473 {
2474 // a zero objective: any feasible point, of value 0
2475 Simplex<double> lp(2);
2476 add_rows(lp, {{{1, 1, 4}, ConstraintType::LE}, {{1, 0, 1}, ConstraintType::GE}});
2477 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2478 lp.load_solution();
2479 EXPECT_NEAR(lp.objetive_value(), 0.0, 1e-12);
2480 EXPECT_TRUE(lp.verify_solution());
2481 }
2482}
2483
2484TEST(SimplexClassic, InconsistentEqualities)
2485{
2486 Simplex<double> lp(2);
2488 add_rows(lp, {{{1, 1, 1}, ConstraintType::EQ}, {{1, 1, 2}, ConstraintType::EQ}});
2489 EXPECT_EQ(lp.solve(), Simplex<double>::Unfeasible);
2490}
2491
2492TEST(SimplexClassic, AMovedSolverSolves)
2493{
2494 Simplex<double> lp(2);
2497 add_rows(lp, {{{1, 1, 40}, ConstraintType::LE}, {{2, 1, 60}, ConstraintType::LE}});
2498
2499 Simplex<double> moved(std::move(lp));
2500 ASSERT_EQ(moved.solve(), Simplex<double>::Solved);
2501 moved.load_solution();
2502 EXPECT_NEAR(moved.objetive_value(), 1400.0, 1e-9);
2503
2504 Simplex<double> assigned(1);
2505 assigned = std::move(moved);
2506 EXPECT_NEAR(assigned.shadow_price(0), 20.0, 1e-9);
2507}
2508
2509TEST(SimplexClassic, StateErrors)
2510{
2511 Simplex<double> lp(1);
2513 EXPECT_THROW(lp.prepare_linear_program(), std::logic_error);
2514 add_rows(lp, {{{1, 1}, ConstraintType::LE}});
2515 EXPECT_THROW((void) lp.shadow_price(0), std::logic_error);
2516 EXPECT_THROW((void) lp.reduced_cost(0), std::logic_error);
2517 EXPECT_THROW((void) lp.rhs_sensitivity(0), std::logic_error);
2518 EXPECT_THROW((void) lp.objective_sensitivity(0), std::logic_error);
2519 EXPECT_THROW((void) lp.dual_solve(), std::logic_error);
2520 EXPECT_THROW((void) lp.update_rhs_and_reoptimize(0, 1), std::logic_error);
2521 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2522 EXPECT_THROW((void) lp.solve(), std::logic_error);
2523 EXPECT_THROW((void) lp.latex_solve(), std::logic_error);
2524 EXPECT_THROW((void) lp.shadow_price(1), std::out_of_range);
2525 EXPECT_THROW((void) lp.objective_sensitivity(1), std::out_of_range);
2526 EXPECT_NO_THROW(lp.print_sensitivity_analysis());
2527}
2528
2529TEST(RevisedSimplexDefects, ANegativeRightHandSideNeedsTheFirstPhase)
2530{
2531 // max -x, -x <= -1, x <= 3: the slack of the first row started at -1
2532 RevisedSimplex<double> rs(1, 2);
2533 rs.set_objective(0, -1);
2534 rs.set_constraint(0, 0, -1);
2535 rs.set_rhs(0, -1);
2536 rs.set_constraint(1, 0, 1);
2537 rs.set_rhs(1, 3);
2538 ASSERT_EQ(rs.solve(), RevisedSimplex<double>::Solved);
2539 EXPECT_NEAR(rs.get_solution(0), 1.0, 1e-12);
2540 EXPECT_NEAR(rs.objective_value(), -1.0, 1e-12);
2541 EXPECT_TRUE(rs.verify_solution());
2542}
2543
2544TEST(RevisedSimplexDefects, InfeasibleAndUnbounded)
2545{
2546 {
2547 // x <= -1 with x >= 0
2548 RevisedSimplex<double> rs(1, 1);
2549 rs.set_objective(0, 1);
2550 rs.set_constraint(0, 0, 1);
2551 rs.set_rhs(0, -1);
2553 }
2554 {
2555 // max x, x - y <= 1
2556 RevisedSimplex<double> rs(2, 1);
2557 rs.set_objective(0, 1);
2558 const double row[] = {1, -1};
2559 rs.set_constraint_row(0, row, 1);
2561 }
2562}
2563
2564TEST(RevisedSimplexDefects, RefactorizationEveryPivotGivesTheSame)
2565{
2566 // the Klee-Minty cube of 6 dimensions, with B^-1 computed again after
2567 // each pivot and never
2568 const size_t n = 6;
2569 double value[2];
2570 for (size_t f : {size_t(1), size_t(1000)})
2571 {
2572 RevisedSimplex<double> rs(n, n);
2573 for (size_t j = 0; j < n; ++j)
2574 rs.set_objective(j, std::pow(2.0, double(n - 1 - j)));
2575 for (size_t i = 0; i < n; ++i)
2576 {
2577 for (size_t j = 0; j < i; ++j)
2578 rs.set_constraint(i, j, std::pow(2.0, double(i - j + 1)));
2579 rs.set_constraint(i, i, 1);
2580 rs.set_rhs(i, std::pow(5.0, double(i + 1)));
2581 }
2583 ASSERT_EQ(rs.solve(), RevisedSimplex<double>::Solved);
2584 value[f == 1 ? 0 : 1] = rs.objective_value();
2585 }
2586 EXPECT_NEAR(value[0], std::pow(5.0, double(n)), 1e-6);
2587 EXPECT_NEAR(value[1], std::pow(5.0, double(n)), 1e-6);
2588
2589 RevisedSimplex<double> rs(1, 1);
2590 EXPECT_THROW(rs.set_refactorization_frequency(0), std::invalid_argument);
2591}
2592
2593TEST(RevisedSimplexDefects, LargeCoefficientsDoNotHideTheLeavingRow)
2594{
2595 // The program of the test of the same name of Simplex, on which the
2596 // ratio test of RevisedSimplex skipped every row too
2597 RevisedSimplex<double> rs(2, 2);
2598 rs.set_objective(0, 4);
2599 rs.set_objective(1, 2);
2600 const double r1[] = {2e8, -1e8}, r2[] = {5e8, 1e8};
2601 rs.set_constraint_row(0, r1, 2e8);
2602 rs.set_constraint_row(1, r2, 8e8);
2603 ASSERT_EQ(rs.solve(), RevisedSimplex<double>::Solved);
2604 EXPECT_NEAR(rs.objective_value(), 16.0, 1e-12);
2605}
2606
2607TEST(SimplexClassic, TheRestOfTheInterface)
2608{
2609 // min 2x + 3y, x + y >= 4 by put_ge_restriction(), x + 3y = 6 by
2610 // put_eq_restriction(): (3, 1), z = 9
2611 Simplex<double> lp(2);
2612 lp.set_optimization_type(OptimizationType::Minimize);
2613 EXPECT_EQ(lp.get_optimization_type(), OptimizationType::Minimize);
2616 lp.set_epsilon(1e-12);
2619 const double ge[] = {1, 1, 4}, eq[] = {1, 3, 6};
2620 lp.put_ge_restriction(ge);
2623 ASSERT_EQ(lp.solve(), Simplex<double>::Solved);
2624 lp.load_solution();
2625 EXPECT_NEAR(lp.get_solution(0), 3.0, 1e-12);
2626 EXPECT_NEAR(lp.get_solution(1), 1.0, 1e-12);
2627
2628 EXPECT_GE(lp.get_iteration_count(), lp.get_pivot_count());
2629 EXPECT_LE(lp.get_degenerate_pivot_count(), lp.get_pivot_count());
2630 EXPECT_GE(lp.get_elapsed_time_ms(), 0.0);
2631 EXPECT_FALSE(lp.get_stats().bland_rule_used);
2632
2633 // nothing to restore: no pivot
2634 ASSERT_EQ(lp.dual_solve(), Simplex<double>::Solved);
2635 EXPECT_EQ(lp.get_pivot_count(), 0u);
2636
2637 testing::internal::CaptureStdout();
2638 lp.print_stats();
2640 const std::string out = testing::internal::GetCapturedStdout();
2641 EXPECT_NE(out.find("Pivots:"), std::string::npos);
2642 EXPECT_NE(out.find("shadow price"), std::string::npos);
2643
2644 const std::string name = temp_name("aleph_simplex_matrix") + ".tex";
2645 lp.latex_matrix(name, 3, 1, 0);
2646 EXPECT_NE(read_file(name).find("\\circled{"), std::string::npos);
2647 std::filesystem::remove(name);
2648
2649 RevisedSimplex<double> rs(1, 1);
2650 rs.set_objective(0, 1);
2651 rs.set_constraint(0, 0, 1);
2652 rs.set_rhs(0, 2);
2653 ASSERT_EQ(rs.solve(), RevisedSimplex<double>::Solved);
2654 EXPECT_EQ(rs.get_num_vars(), 1u);
2655 EXPECT_EQ(rs.get_num_constraints(), 1u);
2656 EXPECT_EQ(rs.get_stats().pivots, 1u);
2657 testing::internal::CaptureStdout();
2658 rs.print_stats();
2659 EXPECT_NE(testing::internal::GetCapturedStdout().find("Refactorizations: 0"),
2660 std::string::npos);
2661}
2662
2663//==============================================================================
2664// Main
2665//==============================================================================
2666
2667int main(int argc, char **argv)
2668{
2669 ::testing::InitGoogleTest(&argc, argv);
2670 return RUN_ALL_TESTS();
2671}
Simplex algorithm for linear programming.
TEST_F(SimplexTest, ConstructorBasic)
int main()
size_t size_t int32_t value
Definition ca-c-api.h:116
size_t size_t int32_t * out
Definition ca-c-api.h:120
size_t row
Definition ca-c-api.h:115
size_t * rows
Definition ca-c-api.h:112
Revised Simplex algorithm for linear programming.
Definition Simplex.H:2176
void set_refactorization_frequency(size_t freq)
Sets refactorization frequency.
Definition Simplex.H:2801
void set_objective(size_t j, T coef)
Sets objective coefficient.
Definition Simplex.H:2732
size_t get_num_vars() const noexcept
Gets number of variables.
Definition Simplex.H:2935
void print_stats() const
Prints statistics to stdout.
Definition Simplex.H:2971
size_t get_num_constraints() const noexcept
Gets number of constraints.
Definition Simplex.H:2938
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
Definition Simplex.H:2932
void set_constraint_row(size_t i, const T *coefs, T rhs)
Adds a complete constraint.
Definition Simplex.H:2784
State get_state() const noexcept
Gets current state.
Definition Simplex.H:2929
T get_solution(size_t j) const
Gets solution value for variable j.
Definition Simplex.H:2910
void set_constraint(size_t i, size_t j, T coef)
Sets constraint coefficient.
Definition Simplex.H:2756
T objective_value() const
Computes objective function value.
Definition Simplex.H:2920
State solve()
Solves the linear program.
Definition Simplex.H:2813
void set_rhs(size_t i, T rhs)
Sets RHS value for a constraint.
Definition Simplex.H:2770
bool verify_solution() const
Verifies solution satisfies all constraints.
Definition Simplex.H:2948
Linear program solver using the Simplex method.
Definition Simplex.H:279
void set_optimization_type(OptimizationType type) noexcept
Sets the optimization type.
Definition Simplex.H:992
SensitivityRange< T > rhs_sensitivity(size_t rest_idx) const
Computes sensitivity range for a RHS value.
Definition Simplex.H:1744
void print_matrix() const
Prints the simplex tableau to stdout.
Definition Simplex.H:1445
OptimizationType get_optimization_type() const noexcept
Gets the current optimization type.
Definition Simplex.H:1058
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
Definition Simplex.H:1618
T & get_restriction_coef(const size_t rest_num, size_t idx)
Gets a specific coefficient from a constraint.
Definition Simplex.H:1256
void set_minimize() noexcept
Sets minimization mode.
Definition Simplex.H:1001
T objetive_value() const noexcept
Computes and returns the objective function value.
Definition Simplex.H:1374
std::vector< T > get_all_reduced_costs() const
Gets all reduced costs as a vector.
Definition Simplex.H:1895
void print_sensitivity_analysis() const
Prints sensitivity analysis to stdout.
Definition Simplex.H:2076
T * get_restriction(const size_t rest_num)
Gets a pointer to a constraint array.
Definition Simplex.H:1206
T * get_objetive_function() noexcept
Gets the objective function coefficients array.
Definition Simplex.H:1234
bool verify_solution() const
Verifies that the solution satisfies all constraints.
Definition Simplex.H:1393
SensitivityRange< T > objective_sensitivity(size_t var_idx) const
Computes sensitivity range for an objective coefficient.
Definition Simplex.H:1677
void put_restriction_coef(const size_t rest_num, const size_t idx, const T &coef)
Sets a specific coefficient in a constraint.
Definition Simplex.H:1270
size_t get_pivot_count() const noexcept
Gets the number of pivot operations.
Definition Simplex.H:1636
T * put_restriction(const T *coefs=nullptr, ConstraintType type=ConstraintType::LE)
Adds a constraint to the linear program.
Definition Simplex.H:1132
void prepare_linear_program()
Prepares the linear program for solving.
Definition Simplex.H:1287
void latex_linear_program(const std::string &name) const
Exports the linear program to a LaTeX file.
Definition Simplex.H:1508
T shadow_price(size_t rest_idx) const
Gets the shadow price (dual value) for a constraint.
Definition Simplex.H:1812
State update_rhs_and_reoptimize(size_t rest_idx, T new_rhs)
Updates RHS value and re-optimizes using dual simplex.
Definition Simplex.H:2042
bool is_basic_variable(size_t var_idx) const
Checks if a variable is basic in the optimal solution.
Definition Simplex.H:1865
void print_stats() const
Prints a summary of statistics to stdout.
Definition Simplex.H:2062
void set_maximize() noexcept
Sets maximization mode.
Definition Simplex.H:1010
size_t get_iteration_count() const noexcept
Gets the number of iterations performed.
Definition Simplex.H:1627
size_t get_num_restrictions() const noexcept
Gets the number of constraints.
Definition Simplex.H:1216
const T & get_solution(size_t i) const noexcept
Gets the solution value for a specific variable.
Definition Simplex.H:1360
void latex_matrix(const std::string &name, const int d=2, const int p=-1, const int q=-1) const
Exports the simplex tableau to a LaTeX file.
Definition Simplex.H:1467
void put_objetive_function_coef(size_t i, const T &coef)
Sets a coefficient in the objective function.
Definition Simplex.H:1072
void set_pivot_rule(PivotRule rule) noexcept
Sets the pivot selection rule.
Definition Simplex.H:1023
T * put_ge_restriction(const T *coefs)
Adds a ≥ constraint.
Definition Simplex.H:1157
T reduced_cost(size_t var_idx) const
Gets the reduced cost for a variable.
Definition Simplex.H:1843
void load_solution() noexcept
Loads the solution values into the solution array.
Definition Simplex.H:1337
State dual_solve()
Performs dual simplex iteration.
Definition Simplex.H:1921
void set_epsilon(T epsilon) noexcept
Sets the floating-point comparison tolerance.
Definition Simplex.H:1049
void put_objetive_function(const DynArray< T > &coefs)
Sets all objective function coefficients from a DynArray.
Definition Simplex.H:1095
size_t get_num_vars() const noexcept
Gets the number of decision variables.
Definition Simplex.H:1225
State get_state() const noexcept
Gets the current state of the solver.
Definition Simplex.H:1324
size_t get_degenerate_pivot_count() const noexcept
Gets the number of degenerate pivots.
Definition Simplex.H:1647
T * put_eq_restriction(const T *coefs)
Adds an = constraint.
Definition Simplex.H:1173
State latex_solve(const char *name=nullptr)
Solves with LaTeX output at each iteration.
Definition Simplex.H:1586
void enable_bland_rule() noexcept
Enables Bland's anti-cycling rule.
Definition Simplex.H:1032
State solve()
Solves the linear program.
Definition Simplex.H:1310
std::vector< T > get_all_shadow_prices() const
Gets all shadow prices as a vector.
Definition Simplex.H:1880
const T & get_objetive_function_coef(size_t i) const
Gets a coefficient from the objective function.
Definition Simplex.H:1085
double get_elapsed_time_ms() const noexcept
Gets the elapsed solving time.
Definition Simplex.H:1656
bool nearly_equal(double a, double b, double eps=EPSILON)
static constexpr double EPSILON
bool nearly_equal(double a, double b, double eps=EPSILON)
static constexpr double EPSILON
static constexpr double EPSILON
bool nearly_equal(double a, double b, double eps=EPSILON)
bool nearly_equal(double a, double b, double eps=EPSILON)
static constexpr double EPSILON
#define TEST(name)
constexpr double EPSILON
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
bool eq(const C1 &c1, const C2 &c2, Eq e=Eq())
Check equality of two containers using a predicate.
Itor find(const Itor &beg, const Itor &end, const T &value)
Find the first element equal to a value.
Definition ahAlgo.H:230
auto min_value(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute minimum value.
Definition stat_utils.H:272
Container< T > range(const T start, const T end, const T step=1)
Generate a range of values [start, end] with a given step.
ConstraintType
Constraint type for linear programming.
Definition Simplex.H:85
auto max_value(const Container &data) -> std::decay_t< decltype(*std::begin(data))>
Compute maximum value.
Definition stat_utils.H:294
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
bool bland_rule_used
Whether Bland's rule was activated.
Definition Simplex.H:103
size_t pivots
Total pivot operations.
Definition Simplex.H:100
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r