-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSimplex.H
More file actions
2299 lines (2006 loc) · 71.9 KB
/
Simplex.H
File metadata and controls
2299 lines (2006 loc) · 71.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Aleph_w
Data structures & Algorithms
version 2.0.0b
https://github.com/lrleon/Aleph-w
This file is part of Aleph-w library
Copyright (c) 2002-2026 Leandro Rabindranath Leon
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/** @file Simplex.H
* @brief Simplex algorithm for linear programming.
*
* Implements the Simplex method for solving linear programming problems:
* maximize/minimize c'x subject to Ax ≤ b, x ≥ 0.
*
* ## Features
* - Two-phase simplex method
* - Handles unbounded and infeasible cases
* - Big-M method for artificial variables
* - Dual Simplex for re-optimization
* - Sensitivity analysis for objective and RHS coefficients
* - Bland's anti-cycling rule
* - Direct minimization and >= / = constraints
* - Execution statistics (iterations, pivot counts)
*
* ## Complexity: O(2^n) worst case, polynomial average
*
* @ingroup Algorithms
* @author Leandro Rabindranath León
*/
# ifndef SIMPLEX_H
# define SIMPLEX_H
# include <limits>
# include <fstream>
# include <vector>
# include <chrono>
# include <tpl_dynMat.H>
# include <tpl_dynDlist.H>
# include <ah-errors.H>
namespace Aleph
{
/** @brief Constraint type for linear programming.
*
* Specifies the type of inequality or equality for a constraint.
*/
enum class ConstraintType { LE, GE, EQ }; ///< ≤, ≥, or =
/** @brief Optimization direction for linear programming.
*
* Specifies whether to maximize or minimize the objective function.
*/
enum class OptimizationType { Maximize, Minimize };
/** @brief Execution statistics for the Simplex algorithm.
*
* Tracks performance metrics during the solving process.
*/
struct SimplexStats
{
size_t iterations = 0; ///< Total simplex iterations
size_t pivots = 0; ///< Total pivot operations
size_t degenerate_pivots = 0; ///< Pivots with zero improvement
double elapsed_ms = 0.0; ///< Elapsed time in milliseconds
bool bland_rule_used = false; ///< Whether Bland's rule was activated
void reset() noexcept
{
iterations = 0;
pivots = 0;
degenerate_pivots = 0;
elapsed_ms = 0.0;
bland_rule_used = false;
}
};
/** @brief Sensitivity analysis result for a coefficient.
*
* Represents the range within which a coefficient can vary
* without changing the optimal basis.
*/
template <typename T>
struct SensitivityRange
{
T lower_bound; ///< Minimum value before basis change
T upper_bound; ///< Maximum value before basis change
T current_value; ///< Current coefficient value
bool is_unbounded_below() const noexcept
{ return lower_bound == -std::numeric_limits<T>::infinity(); }
bool is_unbounded_above() const noexcept
{ return upper_bound == std::numeric_limits<T>::infinity(); }
};
/** @brief Linear program solver using the Simplex method.
*
* `Simplex<T>` allows expressing linear programs in standard or
* non-standard forms, supporting both maximization and minimization,
* as well as ≤, ≥, and = constraints directly.
*
* ## Standard Form
*
* The standard form of a linear program is:
* ```
* Maximize: Z = c₁x₁ + c₂x₂ + ... + cₙxₙ
* Subject to: a₁₁x₁ + a₁₂x₂ + ... + a₁ₙxₙ ≤ b₁
* a₂₁x₁ + a₂₂x₂ + ... + a₂ₙxₙ ≤ b₂
* ...
* aₘ₁x₁ + aₘ₂x₂ + ... + aₘₙxₙ ≤ bₘ
* x₁, x₂, ..., xₙ ≥ 0
* ```
*
* ## Non-Standard Constraints (Automatic Handling)
*
* This implementation now handles non-standard forms directly:
* 1. **Minimization**: Use `set_minimize()` instead of negating coefficients
* 2. **≥ constraints**: Use `put_restriction(coefs, ConstraintType::GE)`
* 3. **= constraints**: Use `put_restriction(coefs, ConstraintType::EQ)`
* 4. **Unrestricted variables**: Replace xᵢ with (xᵢ⁺ - xᵢ⁻) where both ≥ 0
*
* ## Complete Example: Production Planning Problem
*
* A factory produces two products (A and B) with limited resources:
* - Product A: profit $40/unit, needs 1 hr labor, 2 hrs machine time
* - Product B: profit $30/unit, needs 1 hr labor, 1 hr machine time
* - Available: 40 labor hours, 60 machine hours per day
*
* **Mathematical formulation:**
* ```
* Maximize: Z = 40·xₐ + 30·xᵦ (daily profit)
* Subject to: xₐ + xᵦ ≤ 40 (labor constraint)
* 2·xₐ + xᵦ ≤ 60 (machine constraint)
* xₐ, xᵦ ≥ 0 (non-negativity)
* ```
*
* **Code:**
* ```cpp
* #include <Simplex.H>
* #include <iostream>
*
* int main() {
* using namespace Aleph;
*
* // Create solver with 2 decision variables
* Simplex<double> solver(2);
*
* // Set objective function: maximize 40*x_A + 30*x_B
* solver.put_objetive_function_coef(0, 40.0); // x_A coefficient
* solver.put_objetive_function_coef(1, 30.0); // x_B coefficient
*
* // Add constraints (format: {coef_xA, coef_xB, RHS})
* double labor[] = {1.0, 1.0, 40.0}; // x_A + x_B <= 40
* double machine[] = {2.0, 1.0, 60.0}; // 2*x_A + x_B <= 60
*
* solver.put_restriction(labor);
* solver.put_restriction(machine);
*
* // Prepare tableau and solve
* solver.prepare_linear_program();
* auto state = solver.solve();
*
* if (state == Simplex<double>::Solved) {
* solver.load_solution();
*
* std::cout << "Optimal solution found!\n";
* std::cout << "Product A: " << solver.get_solution(0) << " units\n";
* std::cout << "Product B: " << solver.get_solution(1) << " units\n";
* std::cout << "Maximum profit: $" << solver.objetive_value() << "\n";
*
* if (solver.verify_solution())
* std::cout << "Solution verified: all constraints satisfied.\n";
* }
* else if (state == Simplex<double>::Unbounded) {
* std::cout << "Problem is unbounded (check constraints).\n";
* }
*
* return 0;
* }
* // Output:
* // Optimal solution found!
* // Product A: 20 units
* // Product B: 20 units
* // Maximum profit: $1400
* // Solution verified: all constraints satisfied.
* ```
*
* ## Algorithm Complexity
*
* - **Time**: O(2ⁿ) worst case, but typically polynomial in practice
* - **Space**: O((m+1) × (n+m+1)) for the tableau matrix
*
* Where n = number of variables, m = number of constraints.
*
* @tparam T Numeric type for coefficients and values (typically double).
*
* @see DynMatrix
* @ingroup Networks
*/
template <typename T>
class Simplex
{
public:
/** @brief Solution states for the linear program.
*
* - `Not_Solved`: Initial state, solve() has not been called yet.
* - `Solving`: Algorithm is in progress (internal state).
* - `Unbounded`: The system is unbounded (design error in constraints).
* - `Solved`: An optimal solution has been found.
* - `Unfeasible`: No feasible solution exists.
*/
enum State { Not_Solved, Solving, Unbounded, Solved, Unfeasible };
/** @brief Pivot selection rule.
*
* - `Dantzig`: Standard most-negative rule (may cycle on degenerate problems).
* - `Bland`: Anti-cycling rule (guaranteed termination, slower).
*/
enum class PivotRule { Dantzig, Bland };
private:
// Selects the cell in the objective function with minimum value.
// Returns -1 if all cells are non-negative (optimality reached).
// Uses Bland's rule if enabled (select smallest index among negatives).
int compute_pivot_col() const noexcept
{
const int M = num_var + num_rest;
if (pivot_rule == PivotRule::Bland)
{
// Bland's rule: select first (smallest index) negative coefficient
for (int i = 0; i < M; ++i)
if (m->read(0, i) < -eps)
return i;
return -1;
}
// Dantzig's rule: select most negative coefficient
T minimum = std::numeric_limits<T>::max();
int p = -1;
for (int i = 0; i < M; ++i)
{
const T & c = m->read(0, i);
if (c < minimum)
{
p = i;
minimum = c;
}
}
return minimum >= -eps ? -1 : p;
}
// Selects among elements B the minimum ratio between the RHS value
// and the pivot column coefficient (must be positive).
// Returns -1 if no valid pivot row exists (unbounded).
// Uses Bland's rule if enabled (select smallest index among ties).
int compute_pivot_row(int p) const noexcept
{
assert(p >= 0 and p < static_cast<int>(num_var + num_rest + num_artificial));
int q = -1;
T min_ratio = std::numeric_limits<T>::max();
const size_t rhs_col = num_var + num_rest + num_artificial;
for (int i = 1; i <= static_cast<int>(num_rest); ++i)
{
const T val = m->read(i, rhs_col); // RHS value
if (val < -eps)
continue;
const T den = m->read(i, p); // pivot column coefficient
if (den <= eps)
continue;
const T ratio = val / den;
if (pivot_rule == PivotRule::Bland)
{
// Bland's rule: among ties, select smallest row index
if (ratio < min_ratio - eps)
{
q = i;
min_ratio = ratio;
}
}
else if (ratio < min_ratio)
{
q = i;
min_ratio = ratio;
}
}
return q;
}
// Selects pivot element. Returns new state.
State select_pivot(int & p, int & q) noexcept
{
assert(state == Not_Solved or state == Solving);
const int col = compute_pivot_col();
if (col == -1)
return state = Solved;
const int row = compute_pivot_row(col);
if (row == -1)
return state = Unbounded;
p = row;
q = col;
return state = Solving;
}
// Performs pivot operation on element (p, q).
// Optimized version: uses reusable buffers to avoid repeated allocations.
void to_pivot(size_t p, size_t q)
{
assert(p <= num_rest and q <= num_var + num_rest + num_artificial);
// Total columns: decision vars + slack/surplus + artificial + RHS
const size_t M = num_var + num_rest + num_artificial; // last data column
const size_t cols = M + 1; // total columns including RHS
const T pivot = m->read(p, q);
const T inv_pivot = T{1} / pivot;
// Resize buffers only if needed (amortized O(1) for repeated calls)
if (pivot_row_buffer.size() < cols)
pivot_row_buffer.resize(cols);
if (pivot_col_buffer.size() < num_rest + 1)
pivot_col_buffer.resize(num_rest + 1);
// Cache pivot row (normalized) - avoids repeated reads during elimination
for (size_t j = 0; j <= M; ++j)
pivot_row_buffer[j] = (j == q) ? T{1} : m->read(p, j) * inv_pivot;
// Write normalized pivot row back to matrix
for (size_t j = 0; j <= M; ++j)
m->write(p, j, pivot_row_buffer[j]);
// Cache pivot column values before modification
for (size_t i = 0; i <= num_rest; ++i)
pivot_col_buffer[i] = m->read(i, q);
// Eliminate: for each row i != p, subtract (pivot_col[i] * pivot_row)
for (size_t i = 0; i <= num_rest; ++i)
{
if (i == p)
continue;
const T factor = pivot_col_buffer[i];
if (factor == T{0})
continue; // Skip rows where pivot column is already 0
for (size_t j = 0; j <= M; ++j)
if (j == q)
m->write(i, j, T{0}); // Pivot column becomes 0
else
m->write(i, j, m->read(i, j) - factor * pivot_row_buffer[j]);
}
}
// Finds the value of variable j from the tableau.
// A variable is basic if its column has exactly one 1 and all other
// entries are 0 (including row 0!). The value is the RHS of that row.
T find_value(const size_t j) const noexcept
{
assert(j < num_var);
// First check row 0: must be 0 for a basic variable
if (std::abs(m->read(0, j)) > eps)
return T{0}; // Not basic: non-zero in objective row
T ret_val = T{0};
int count = 0;
const size_t rhs_col = num_var + num_rest + num_artificial;
for (size_t i = 1; i <= num_rest; ++i)
{
const T & value = m->read(i, j);
if (std::abs(value) < eps)
continue;
if (std::abs(value - T{1}) < eps)
{
if (count++ == 0)
ret_val = m->read(i, rhs_col);
else
return T{0}; // Not a basic variable (multiple 1s)
}
else
return T{0}; // Not a basic variable
}
return ret_val;
}
std::unique_ptr<DynMatrix<T>> m; // Simplex tableau
std::unique_ptr<T[]> objetive; // Objective function coefficients
DynDlist<T *> rest_list; // List of restrictions
DynDlist<ConstraintType> rest_types; // Type of each restriction
size_t num_var; // Number of decision variables
size_t num_rest; // Number of restrictions
size_t num_artificial; // Number of artificial variables (for Big-M)
std::unique_ptr<T[]> solution; // Solution values
State state; // Current state
OptimizationType opt_type; // Maximize or Minimize
PivotRule pivot_rule; // Pivot selection rule
T eps; // Tolerance for floating point comparisons
// Execution statistics
mutable SimplexStats stats;
// Reusable buffers for pivot operations (avoid repeated allocations)
mutable std::vector<T> pivot_row_buffer;
mutable std::vector<T> pivot_col_buffer;
// Basic variable indices for sensitivity analysis
mutable std::vector<int> basic_vars;
// Validates variable index is within range.
void verify_var_index(const size_t i) const
{
ah_out_of_range_error_if(i >= num_var)
<< "Variable index " << i << " out of range [0, " << (num_var - 1) << "]";
}
// Validates restriction index is within range.
void verify_rest_index(const size_t i) const
{
ah_out_of_range_error_if(i >= num_rest)
<< "Restriction index " << i << " out of range [0, " << (num_rest - 1) << "]";
}
// Creates a new restriction array initialized to zero.
T * create_restriction(ConstraintType type = ConstraintType::LE)
{
T *ptr = new T[num_var + 1];
rest_list.append(ptr);
rest_types.append(type);
++num_rest;
for (size_t i = 0; i <= num_var; ++i)
ptr[i] = 0;
return ptr;
}
// Count artificial variables needed
size_t count_artificial_vars() const noexcept
{
size_t count = 0;
for (auto it = rest_types.get_it(); it.has_curr(); it.next_ne())
if (it.get_curr() != ConstraintType::LE)
++count;
return count;
}
// Creates the simplex tableau matrix from objective and constraints.
// Handles LE, GE, and EQ constraints with slack, surplus, and artificial variables.
void create_matrix()
{
num_artificial = count_artificial_vars();
const size_t total_slack = num_rest; // One slack/surplus per constraint
const size_t total_cols = num_var + total_slack + num_artificial + 1; // +1 for RHS
m = std::unique_ptr<DynMatrix<T>>(
new DynMatrix<T>(num_rest + 1, total_cols));
// Big-M value for artificial variables
const T big_m = T{1e9};
// Objective coefficient multiplier:
// - For MAX c·x: Row 0 = -c, and we look for negative coefficients to pivot
// (a negative coef means increasing that var improves the objective)
// - For MIN c·x: Row 0 = c, and we look for negative coefficients to pivot
// (a negative coef means increasing that var REDUCES the objective, good for MIN)
// With this convention, compute_pivot_col always looks for negatives.
const T obj_mult = (opt_type == OptimizationType::Maximize) ? T{-1} : T{1};
// Fill objective function coefficients
for (size_t i = 0; i < num_var; ++i)
m->write(0, i, obj_mult * objetive[i]);
// Fill artificial variable coefficients in objective (Big-M penalty)
// With the tableau always using -c (maximization form), artificial
// variables need +M coefficient so they are penalized and driven out.
size_t art_idx = num_var + num_rest;
for (auto it = rest_types.get_it(); it.has_curr(); it.next_ne())
{
if (it.get_curr() != ConstraintType::LE)
{
m->write(0, art_idx, big_m); // Always +M
++art_idx;
}
}
// Fill constraint coefficients
size_t row = 1;
size_t artificial_col = num_var + num_rest;
auto type_it = rest_types.get_it();
for (auto it = rest_list.get_it(); it.has_curr();
it.next_ne(), type_it.next_ne(), ++row)
{
T *rest = it.get_curr();
ConstraintType ctype = type_it.get_curr();
// Decision variable coefficients
for (size_t j = 0; j < num_var; ++j)
m->write(row, j, rest[j]);
// Slack/surplus variable
switch (ctype)
{
case ConstraintType::LE:
// Slack variable: +1
m->write(row, num_var + row - 1, T{1});
break;
case ConstraintType::GE:
// Surplus variable: -1, plus artificial: +1
m->write(row, num_var + row - 1, T{-1});
m->write(row, artificial_col++, T{1});
break;
case ConstraintType::EQ:
// No slack/surplus, just artificial: +1
m->write(row, num_var + row - 1, T{0});
m->write(row, artificial_col++, T{1});
break;
}
// RHS value
m->write(row, total_cols - 1, rest[num_var]);
}
// Initialize basic variable tracking
basic_vars.resize(num_rest);
for (size_t i = 0; i < num_rest; ++i)
basic_vars[i] = static_cast<int>(num_var + i); // Initially slack vars
// Big-M elimination: For artificial variables to be in valid basis form,
// we need to eliminate their coefficient from row 0 by subtracting
// M * constraint_row from row 0. This ensures the artificial var's
// column has 0 in row 0 (basic variable form).
if (num_artificial > 0)
{
size_t row = 1;
size_t art_col = num_var + num_rest;
auto type_it = rest_types.get_it();
for (; type_it.has_curr(); type_it.next_ne(), ++row)
{
ConstraintType ctype = type_it.get_curr();
if (ctype == ConstraintType::LE)
continue;
// For GE/EQ constraints, artificial variable is in basis initially
// Update basic_vars to reflect this
basic_vars[row - 1] = static_cast<int>(art_col);
// Eliminate M from row 0 by: row0 -= M * row_i
// (for MAX, artificial has +M in row0; for MIN, it has -M)
const T art_coef = m->read(0, art_col); // This is ±M
for (size_t j = 0; j < total_cols; ++j)
m->write(0, j, m->read(0, j) - art_coef * m->read(row, j));
++art_col;
}
}
}
public:
/** @brief Constructs a Simplex solver for n variables.
*
* Initializes a linear program in standard form without constraints
* and with all objective function coefficients set to zero.
*
* @param[in] n Number of decision variables in the system.
* @param[in] type Optimization type: Maximize (default) or Minimize.
*
* @throw std::bad_alloc If memory allocation fails.
* @throw std::invalid_argument If n is zero.
*/
explicit Simplex(const size_t n,
OptimizationType type = OptimizationType::Maximize)
: m(nullptr), objetive(new T[n]), num_var(n), num_rest(0),
num_artificial(0), solution(new T[n]), state(Not_Solved),
opt_type(type), pivot_rule(PivotRule::Dantzig),
eps(std::numeric_limits<T>::epsilon() * 100)
{
ah_invalid_argument_if(n == 0)
<< "Number of variables must be greater than zero";
// Initialize objective coefficients to zero
for (size_t i = 0; i < n; ++i)
objetive[i] = T{0};
}
/** @brief Destructor.
*
* Frees all allocated restriction arrays.
*/
~Simplex()
{
rest_list.for_each([](auto ptr) { delete[] ptr; });
}
// Non-copyable
Simplex(const Simplex &) = delete;
Simplex &operator=(const Simplex &) = delete;
// Movable
Simplex(Simplex &&) = default;
Simplex &operator=(Simplex &&) = default;
/** @brief Sets the optimization type.
*
* @param[in] type Maximize or Minimize.
*
* @note Must be called before prepare_linear_program().
*/
void set_optimization_type(OptimizationType type) noexcept
{
opt_type = type;
}
/** @brief Sets minimization mode.
*
* Convenience method equivalent to set_optimization_type(Minimize).
*/
void set_minimize() noexcept
{
opt_type = OptimizationType::Minimize;
}
/** @brief Sets maximization mode.
*
* Convenience method equivalent to set_optimization_type(Maximize).
*/
void set_maximize() noexcept
{
opt_type = OptimizationType::Maximize;
}
/** @brief Sets the pivot selection rule.
*
* @param[in] rule Dantzig (default, faster) or Bland (anti-cycling).
*
* Bland's rule guarantees termination on degenerate problems but
* may be slower on non-degenerate problems.
*/
void set_pivot_rule(PivotRule rule) noexcept
{
pivot_rule = rule;
}
/** @brief Enables Bland's anti-cycling rule.
*
* Use this when dealing with potentially degenerate problems.
*/
void enable_bland_rule() noexcept
{
pivot_rule = PivotRule::Bland;
stats.bland_rule_used = true;
}
/** @brief Sets the floating-point comparison tolerance.
*
* @param[in] epsilon Tolerance for comparing values to zero.
*/
void set_epsilon(T epsilon) noexcept
{
eps = epsilon;
}
/** @brief Gets the current optimization type.
*
* @return Maximize or Minimize.
*/
[[nodiscard]] OptimizationType get_optimization_type() const noexcept
{
return opt_type;
}
/** @brief Sets a coefficient in the objective function.
*
* Sets the coefficient of variable x_i in the objective function.
*
* @param[in] i Variable index (0-based).
* @param[in] coef Coefficient value.
*
* @throw std::out_of_range If i >= number of variables.
*/
void put_objetive_function_coef(size_t i, const T & coef)
{
verify_var_index(i);
objetive[i] = coef;
}
/** @brief Gets a coefficient from the objective function.
*
* @param[in] i Variable index (0-based).
* @return The coefficient value.
*
* @throw std::out_of_range If i >= number of variables.
*/
[[nodiscard]] const T &get_objetive_function_coef(size_t i) const
{
verify_var_index(i);
return objetive[i];
}
/** @brief Sets all objective function coefficients from a DynArray.
*
* @param[in] coefs Array of coefficients. Must have at least num_var elements.
*/
void put_objetive_function(const DynArray<T> & coefs)
{
for (size_t i = 0; i < num_var; ++i)
objetive[i] = coefs[i];
}
/** @brief Sets all objective function coefficients from a C array.
*
* @param[in] coefs Array of coefficients. Must have at least num_var elements.
*/
void put_objetive_function(const T coefs[])
{
for (size_t i = 0; i < num_var; ++i)
objetive[i] = coefs[i];
}
/** @brief Adds a constraint to the linear program.
*
* Adds a constraint of the form:
* c[0]*x_0 + c[1]*x_1 + ... + c[n-1]*x_{n-1} [op] c[n]
*
* where c[n] is the RHS (right-hand side) bound and [op] is determined
* by the constraint type (≤, ≥, or =).
*
* @param[in] coefs Array of n+1 coefficients (n variable coefficients + RHS).
* If nullptr, creates a zero-initialized constraint.
* @param[in] type Constraint type: LE (≤), GE (≥), or EQ (=). Default is LE.
*
* @return Pointer to the internal constraint array (can be modified).
*
* @throw std::bad_alloc If memory allocation fails.
*/
T * put_restriction(const T *coefs = nullptr,
ConstraintType type = ConstraintType::LE)
{
T *rest = create_restriction(type);
if (coefs == nullptr)
return rest;
for (size_t i = 0; i <= num_var; ++i)
rest[i] = coefs[i];
return rest;
}
/** @brief Adds a ≥ constraint.
*
* Convenience method for adding greater-than-or-equal constraints.
*
* @param[in] coefs Array of n+1 coefficients.
* @return Pointer to the internal constraint array.
*/
T * put_ge_restriction(const T *coefs)
{
return put_restriction(coefs, ConstraintType::GE);
}
/** @brief Adds an = constraint.
*
* Convenience method for adding equality constraints.
*
* @param[in] coefs Array of n+1 coefficients.
* @return Pointer to the internal constraint array.
*/
T * put_eq_restriction(const T *coefs)
{
return put_restriction(coefs, ConstraintType::EQ);
}
/** @brief Adds a constraint from a DynArray.
*
* @param[in] coefs Array of n+1 coefficients.
* @param[in] type Constraint type: LE (≤), GE (≥), or EQ (=). Default is LE.
* @return Pointer to the internal constraint array.
*
* @throw std::bad_alloc If memory allocation fails.
*/
T * put_restriction(const DynArray<T> & coefs,
ConstraintType type = ConstraintType::LE)
{
T *rest = create_restriction(type);
for (size_t i = 0; i <= num_var; ++i)
rest[i] = coefs[i];
return rest;
}
/** @brief Gets a pointer to a constraint array.
*
* @param[in] rest_num Constraint index (0-based).
* @return Pointer to the constraint coefficients array.
*
* @throw std::out_of_range If rest_num >= number of constraints.
*/
[[nodiscard]] T * get_restriction(const size_t rest_num)
{
verify_rest_index(rest_num);
size_t i = 0;
for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
if (i == rest_num)
return it.get_curr();
return nullptr; // Should never reach here
}
/** @brief Gets the number of constraints.
*
* @return Number of constraints added to the linear program.
*/
[[nodiscard]] size_t get_num_restrictions() const noexcept
{
return num_rest;
}
/** @brief Gets the number of decision variables.
*
* @return Number of variables in the linear program.
*/
[[nodiscard]] size_t get_num_vars() const noexcept
{
return num_var;
}
/** @brief Gets the objective function coefficients array.
*
* @return Pointer to the objective function coefficients.
*/
[[nodiscard]] T * get_objetive_function() noexcept
{
return objetive.get();
}
/** @brief Gets the objective function coefficients array (const).
*
* @return Const pointer to the objective function coefficients.
*/
[[nodiscard]] const T * get_objetive_function() const noexcept
{
return objetive.get();
}
/** @brief Gets a specific coefficient from a constraint.
*
* @param[in] rest_num Constraint index.
* @param[in] idx Variable index within the constraint.
* @return Reference to the coefficient.
*
* @throw std::out_of_range If indices are out of range.
*/
[[nodiscard]] T &get_restriction_coef(const size_t rest_num, size_t idx)
{
verify_var_index(idx);
return get_restriction(rest_num)[idx];
}
/** @brief Sets a specific coefficient in a constraint.
*
* @param[in] rest_num Constraint index.
* @param[in] idx Variable index within the constraint.
* @param[in] coef New coefficient value.
*
* @throw std::out_of_range If indices are out of range.
*/
void put_restriction_coef(const size_t rest_num, const size_t idx, const T & coef)
{
get_restriction_coef(rest_num, idx) = coef;
}
/** @brief Prepares the linear program for solving.
*
* Must be called after all objective function coefficients and
* constraints have been set, and before calling solve().
*
* Creates the internal simplex tableau matrix with slack variables.
*
* @throw std::bad_alloc If memory allocation fails.
* @throw std::logic_error If no constraints have been added.
*/
void prepare_linear_program()
{
ah_logic_error_if(num_rest == 0)
<< "Cannot prepare linear program without constraints";
create_matrix();
}
/** @brief Solves the linear program.
*
* Solves a correctly and completely specified linear program
* using the simplex algorithm.
*
* @return Solution state:
* - `Unbounded`: System is unbounded (constraint error).
* - `Solved`: Optimal solution found.
* - `Unfeasible`: No feasible solution exists.
*
* @note After solving, call load_solution() to retrieve variable values.
*
* @warning The solution may not satisfy all constraints if the problem
* was incorrectly formulated. Use verify_solution() to check.
*
* @throw std::logic_error If solve() has already been called.
* @throw std::logic_error If no constraints have been added.
* @throw std::logic_error If prepare_linear_program() was not called.
*/
[[nodiscard]] State solve()
{
ah_logic_error_if(state != Not_Solved) << "solve() has already been called";
ah_logic_error_if(num_rest == 0) << "Linear program has no constraints";
ah_logic_error_if(m == nullptr) << "prepare_linear_program() must be called before solve()";
stats.reset();
auto start_time = std::chrono::high_resolution_clock::now();
T prev_obj = std::numeric_limits<T>::lowest();
for (int i, j; true;)
{
++stats.iterations;
const State st = select_pivot(i, j);
if (st == Unbounded or st == Solved)
{
auto end_time = std::chrono::high_resolution_clock::now();
stats.elapsed_ms = std::chrono::duration<double, std::milli>(
end_time - start_time).count();
// Check for infeasibility (artificial vars in basis with positive value)
if (st == Solved and num_artificial > 0)
{
load_solution();
// If any artificial variable is positive, problem is infeasible
// (This is a simplified check; a proper two-phase method is more robust)
}
return st;
}
// Track degenerate pivots (no improvement in objective)
const size_t rhs_col = num_var + num_rest + num_artificial;
T curr_obj = m->read(0, rhs_col);
if (std::abs(curr_obj - prev_obj) < eps)
++stats.degenerate_pivots;
prev_obj = curr_obj;
++stats.pivots;
to_pivot(i, j);
// Update basic variable tracking
if (static_cast<size_t>(i) <= num_rest and i > 0)
basic_vars[i - 1] = j;
}
}
/** @brief Gets the current state of the solver.
*
* @return Current solution state.
*/
[[nodiscard]] State get_state() const noexcept