Aleph-w 7.10.0
A C++ Library for Data Structures and Algorithms
Loading...
Searching...
No Matches
Simplex.H
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
59# ifndef SIMPLEX_H
60# define SIMPLEX_H
61
62# include <algorithm>
63# include <cassert>
64# include <chrono>
65# include <cmath>
66# include <fstream>
67# include <iomanip>
68# include <iostream>
69# include <limits>
70# include <memory>
71# include <sstream>
72# include <string>
73# include <utility>
74# include <vector>
75# include <tpl_dynMat.H>
76# include <tpl_dynDlist.H>
77# include <ah-errors.H>
78
79namespace Aleph
80{
85 enum class ConstraintType { LE, GE, EQ };
86
92
98 {
99 size_t iterations = 0;
100 size_t pivots = 0;
101 size_t degenerate_pivots = 0;
102 double elapsed_ms = 0.0;
103 bool bland_rule_used = false;
104
105 void reset() noexcept
106 {
107 iterations = 0;
108 pivots = 0;
110 elapsed_ms = 0.0;
111 bland_rule_used = false;
112 }
113 };
114
120 template <typename T>
122 {
126
127 bool is_unbounded_below() const noexcept
128 { return lower_bound == -std::numeric_limits<T>::infinity(); }
129
130 bool is_unbounded_above() const noexcept
131 { return upper_bound == std::numeric_limits<T>::infinity(); }
132 };
133
277 template <typename T>
279 {
280 public:
291
298 enum class PivotRule { Dantzig, Bland };
299
300 private:
301 std::unique_ptr<DynMatrix<T>> m; // Simplex tableau
302 std::unique_ptr<T[]> objetive; // Objective function coefficients
303 DynDlist<T *> rest_list; // List of restrictions
304 DynDlist<ConstraintType> rest_types; // Type of each restriction
305 size_t num_var; // Number of decision variables
306 size_t num_rest; // Number of restrictions
307 size_t num_artificial; // Number of artificial variables
308 std::unique_ptr<T[]> solution; // Solution values
309 State state; // Current state
310 OptimizationType opt_type; // Maximize or Minimize
311 PivotRule pivot_rule; // Pivot selection rule
312 T eps; // Tolerance for floating point comparisons
313
314 // Execution statistics
316
317 // Reusable buffers for pivot operations (avoid repeated allocations)
318 mutable std::vector<T> pivot_row_buffer;
319 mutable std::vector<T> pivot_col_buffer;
320
321 // The column of the basic variable of each row, the row i + 1 of the
322 // tableau
323 mutable std::vector<int> basic_vars;
324
325 // Of each restriction: -1 if its row was multiplied by -1, so that its
326 // right-hand side is >= 0; else 1
327 std::vector<int> row_sign;
328
329 // Of each restriction: the column that was the unit vector of its row
330 // in the first tableau, its slack or its artificial variable, which
331 // pivoting turns into the column of the inverse of the basis
332 std::vector<size_t> unit_col;
333
334 // The costs that the second phase minimizes: -c to maximize, c to
335 // minimize, as prepare_linear_program() found them, scaled
336 std::vector<T> phase2_cost;
337
338 // The powers of two by which prepare_linear_program() multiplies each
339 // row, each column and the objective, so that the largest magnitude of
340 // each is in [1/2, 1): the solver works on the scaled program, whose
341 // tolerances so do not depend on the units of the data, and the
342 // results are scaled back
343 std::vector<T> row_scale;
344 std::vector<T> col_scale;
346
347 // The tolerances of eps, on the scaled program: times the largest
348 // magnitude of its coefficients, of its right-hand sides and of its
349 // objective, at least 1 each
351 T tol_rhs = T{0};
353
354 // The degenerate pivots in a row; past num_var + num_rest, Bland's rule
355 size_t degenerate_run = 0;
356
357 // During the first phase, the costs of the second one in terms of the
358 // variables that are not basic. They break the ties of Dantzig's rule,
359 // as a Big-M did: among the columns that lower the sum of the
360 // artificial variables the most, the one that improves the objective
361 // the most enters, which saves pivots to the second phase.
362 std::vector<T> tie_cost;
363 bool in_phase1 = false;
364
365 // The columns of the tableau: the num_var decision variables, a slack
366 // or surplus variable of each restriction (an = one has an empty
367 // column), the artificial variables and the right-hand side
368 size_t first_artificial() const noexcept { return num_var + num_rest; }
369
370 size_t rhs_col() const noexcept { return num_var + num_rest + num_artificial; }
371
372 bool is_artificial(const size_t j) const noexcept
373 {
374 return j >= first_artificial() and j < rhs_col();
375 }
376
377 // Whether the next pivot follows Bland's rule: always with it, and with
378 // Dantzig's after a run of degenerate pivots
379 bool bland_now() const noexcept
380 {
382 }
383
384 // Whether two ratios of a ratio test are taken as equal
385 bool same_ratio(const T & a, const T & b) const noexcept
386 {
387 return std::abs(a - b) <= eps * std::max(T{1}, std::abs(b));
388 }
389
390 // The column that enters the basis: one whose cost in row 0 is below
391 // -tol, the most negative one with Dantzig's rule and the first one
392 // with Bland's; -1 if there is none, which is optimal. In the first
393 // phase, Dantzig's rule breaks its ties by tie_cost. An artificial
394 // variable never enters.
395 int compute_pivot_col(const T & tol) const noexcept
396 {
397 const size_t M = first_artificial();
398
399 if (bland_now())
400 {
401 for (size_t j = 0; j < M; ++j)
402 if (m->read(0, j) < -tol)
403 return static_cast<int>(j);
404 return -1;
405 }
406
407 int q = -1;
408 T minimum = T{0};
409 for (size_t j = 0; j < M; ++j)
410 {
411 const T & c = m->read(0, j);
412 if (c >= -tol)
413 continue;
414
415 if (q == -1 or (c < minimum and not same_ratio(c, minimum)))
416 {
417 q = static_cast<int>(j);
418 minimum = c;
419 }
420 else if (in_phase1 and same_ratio(c, minimum) and tie_cost[j] < tie_cost[q])
421 q = static_cast<int>(j);
422 }
423 return q;
424 }
425
426 // The row whose basic variable leaves the basis when the column q
427 // enters: the least ratio of its right-hand side to its entry in q,
428 // among the positive entries. Among ties, Bland's rule takes the row
429 // whose basic variable has the least index, and Dantzig's the largest
430 // entry. -1 if no entry is positive, which is unbounded.
431 int compute_pivot_row(const size_t q) const noexcept
432 {
433 const size_t rhs = rhs_col();
434 const bool bland = bland_now();
435
436 int p = -1;
437 T min_ratio = T{0};
438 T max_den = T{0};
439 for (size_t i = 1; i <= num_rest; ++i)
440 {
441 const T den = m->read(i, q);
442 if (den <= tol_coef)
443 continue;
444
445 const T ratio = std::max(m->read(i, rhs), T{0}) / den;
446 if (p == -1 or (ratio < min_ratio and not same_ratio(ratio, min_ratio)))
447 {
448 p = static_cast<int>(i);
449 min_ratio = ratio;
450 max_den = den;
451 }
452 else if (same_ratio(ratio, min_ratio)
453 and (bland ? basic_vars[i - 1] < basic_vars[p - 1] : den > max_den))
454 {
455 p = static_cast<int>(i);
456 max_den = den;
457 }
458 }
459 return p;
460 }
461
462 // Performs pivot operation on element (p, q), whose variable becomes
463 // the basic one of the row p.
464 // Optimized version: uses reusable buffers to avoid repeated allocations.
465 void to_pivot(size_t p, size_t q)
466 {
467 assert(p >= 1 and p <= num_rest and q < rhs_col());
468
469 // Total columns: decision vars + slack/surplus + artificial + RHS
470 const size_t M = rhs_col(); // last data column
471 const size_t cols = M + 1; // total columns including RHS
472 const T pivot = m->read(p, q);
473 const T inv_pivot = T{1} / pivot;
474
475 // Resize buffers only if needed (amortized O(1) for repeated calls)
476 if (pivot_row_buffer.size() < cols)
477 pivot_row_buffer.resize(cols);
478 if (pivot_col_buffer.size() < num_rest + 1)
479 pivot_col_buffer.resize(num_rest + 1);
480
481 // Cache pivot row (normalized) - avoids repeated reads during elimination
482 for (size_t j = 0; j <= M; ++j)
483 pivot_row_buffer[j] = (j == q) ? T{1} : m->read(p, j) * inv_pivot;
484
485 // Write normalized pivot row back to matrix
486 for (size_t j = 0; j <= M; ++j)
487 m->write(p, j, pivot_row_buffer[j]);
488
489 // The costs that break the ties of the first phase
490 if (in_phase1)
491 if (const T f = tie_cost[q]; f != T{0})
492 {
493 for (size_t j = 0; j <= M; ++j)
494 tie_cost[j] -= f * pivot_row_buffer[j];
495 tie_cost[q] = T{0};
496 }
497
498 // Cache pivot column values before modification
499 for (size_t i = 0; i <= num_rest; ++i)
500 pivot_col_buffer[i] = m->read(i, q);
501
502 // Eliminate: for each row i != p, subtract (pivot_col[i] * pivot_row)
503 for (size_t i = 0; i <= num_rest; ++i)
504 {
505 if (i == p)
506 continue;
507
508 const T factor = pivot_col_buffer[i];
509 if (factor == T{0})
510 continue; // Skip rows where pivot column is already 0
511
512 for (size_t j = 0; j <= M; ++j)
513 if (j == q)
514 m->write(i, j, T{0}); // Pivot column becomes 0
515 else
516 m->write(i, j, m->read(i, j) - factor * pivot_row_buffer[j]);
517 }
518
519 basic_vars[p - 1] = static_cast<int>(q);
520 }
521
522 // Pivots until row 0 has no cost below -cost_tol, which is optimal, or
523 // the entering column has no positive entry, which is unbounded.
524 // Before and after each pivot it calls hook(p, q, after).
525 template <class Hook>
526 State iterate(const T & cost_tol, Hook & hook)
527 {
528 const size_t rhs = rhs_col();
529 degenerate_run = 0;
530 while (true)
531 {
533 const int q = compute_pivot_col(cost_tol);
534 if (q < 0)
535 return Solved;
536
537 const int p = compute_pivot_row(static_cast<size_t>(q));
538 if (p < 0)
539 return Unbounded;
540
541 if (bland_now())
542 stats.bland_rule_used = true;
543
544 // A degenerate pivot leaves the vertex, and the objective, as
545 // they were
546 if (m->read(p, rhs) <= tol_rhs)
547 {
550 }
551 else
552 degenerate_run = 0;
553
554 hook(static_cast<size_t>(p), static_cast<size_t>(q), false);
555 ++stats.pivots;
556 to_pivot(static_cast<size_t>(p), static_cast<size_t>(q));
557 hook(static_cast<size_t>(p), static_cast<size_t>(q), true);
558 }
559 }
560
561 // Sets row 0 to the costs of the first phase, the sum of the
562 // artificial variables to minimize, as all of them are basic, and
563 // tie_cost to the costs of the second phase, as the first basis costs
564 // nothing
566 {
567 const size_t cols = rhs_col() + 1;
568 std::vector<T> cost(cols, T{0});
569 for (size_t i = 1; i <= num_rest; ++i)
570 if (is_artificial(static_cast<size_t>(basic_vars[i - 1])))
571 for (size_t j = 0; j < cols; ++j)
572 if (not is_artificial(j))
573 cost[j] -= m->read(i, j);
574
575 for (size_t j = 0; j < cols; ++j)
576 m->write(0, j, cost[j]);
577
578 tie_cost.assign(cols, T{0});
579 for (size_t j = 0; j < num_var; ++j)
580 tie_cost[j] = phase2_cost[j];
581 }
582
583 // Sets row 0 to the costs of the second phase, in terms of the
584 // variables that are not basic, which the pivots of the first phase
585 // kept in tie_cost
587 {
588 for (size_t j = 0; j <= rhs_col(); ++j)
589 m->write(0, j, tie_cost[j]);
590 }
591
592 // After the first phase, the artificial variables that are still basic,
593 // at zero, leave the basis by a pivot on the largest entry of their row
594 // in a column that is not artificial. A row without such an entry is a
595 // combination of others: its artificial variable stays basic, at zero,
596 // since no pivot changes the row.
597 template <class Hook>
598 void drive_out_artificials(Hook & hook)
599 {
600 const size_t M = first_artificial();
601 const size_t rhs = rhs_col();
602 for (size_t i = 1; i <= num_rest; ++i)
603 {
604 if (not is_artificial(static_cast<size_t>(basic_vars[i - 1])))
605 continue;
606
607 m->write(i, rhs, T{0}); // at most a rounding above zero
608
609 size_t q = M;
610 T largest = tol_coef;
611 for (size_t j = 0; j < M; ++j)
612 if (const T a = std::abs(m->read(i, j)); a > largest)
613 {
614 q = j;
615 largest = a;
616 }
617
618 if (q == M) // what is left in the row is rounding
619 {
620 for (size_t j = 0; j < M; ++j)
621 m->write(i, j, T{0});
622 continue;
623 }
624
625 hook(i, q, false);
626 ++stats.pivots;
628 to_pivot(i, q);
629 hook(i, q, true);
630 }
631 }
632
633 // The two phases, with hook as in iterate()
634 template <class Hook>
635 State run(Hook & hook)
636 {
637 stats.reset();
638 stats.bland_rule_used = pivot_rule == PivotRule::Bland;
639 const auto start_time = std::chrono::high_resolution_clock::now();
640 state = Solving;
641
642 if (num_artificial > 0)
643 {
644 load_phase1_costs();
645 in_phase1 = true;
646 const T scale = T(num_artificial);
647 (void) iterate(tol_coef * scale, hook); // bounded below by zero
648
649 // the sum of the artificial variables, which is >= 0
650 if (-m->read(0, rhs_col()) > tol_rhs * scale)
651 state = Unfeasible;
652 else
653 {
654 drive_out_artificials(hook);
655 load_phase2_costs();
656 }
657 in_phase1 = false;
658 }
659
660 // Row 0 has the costs of the second phase: those of create_matrix(),
661 // or those that the first phase left
662 if (state == Solving)
663 state = iterate(tol_cost, hook);
664
665 const auto end_time = std::chrono::high_resolution_clock::now();
666 stats.elapsed_ms = std::chrono::duration<double, std::milli>(end_time - start_time).count();
667
668 return state;
669 }
670
671 // value in fixed notation with d decimals
672 static std::string format_entry(const T & value, const int d)
673 {
674 std::ostringstream s;
675 s << std::fixed << std::setprecision(d) << value;
676 return s.str();
677 }
678
679 // Validates variable index is within range; the range is half open, as
680 // [0, n - 1] wraps when there are no variables
681 void verify_var_index(const size_t i) const
682 {
683 ah_out_of_range_error_if(i >= num_var)
684 << "Variable index " << i << " out of range [0, " << num_var << ")";
685 }
686
687 // Validates restriction index is within range; the range is half open,
688 // as [0, n - 1] wraps when there are no restrictions
689 void verify_rest_index(const size_t i) const
690 {
691 ah_out_of_range_error_if(i >= num_rest)
692 << "Restriction index " << i << " out of range [0, " << num_rest << ")";
693 }
694
695 // An array of `n` coefficients, with room in a size_t for the bytes of
696 // `spare` more. Before new[]: for a count whose bytes do not fit in a
697 // size_t, what new[] asks of the allocator depends on the compiler
698 static T * allocate(const size_t n, const size_t spare = 0)
699 {
700 ah_overflow_error_if(n > std::numeric_limits<size_t>::max() / sizeof(T) - spare)
701 << "Simplex: the bytes of " << n << " coefficients do not fit in a size_t";
702 return new T[n];
703 }
704
705 // Creates a new restriction array initialized to zero. The tableau,
706 // once built, does not grow: a restriction added after it would make
707 // the solver read past it
709 {
710 ah_logic_error_if(m != nullptr)
711 << "A restriction cannot be added after prepare_linear_program()";
712
713 T *ptr = allocate(num_var + 1);
714 rest_list.append(ptr);
715 rest_types.append(type);
716 ++num_rest;
717 for (size_t i = 0; i <= num_var; ++i)
718 ptr[i] = 0;
719 return ptr;
720 }
721
722 // The power of two that takes magnitude into [1/2, 1); 1 for 0, for a
723 // subnormal magnitude, whose power could overflow, or for a magnitude
724 // that is not finite
725 static T scale_of(const T & magnitude) noexcept
726 {
727 if (not (magnitude >= std::numeric_limits<T>::min()) or not std::isfinite(magnitude))
728 return T{1};
729 int e;
730 (void) std::frexp(magnitude, &e);
731 return std::ldexp(T{1}, -e);
732 }
733
734 // Creates the simplex tableau from the objective and the constraints,
735 // scaled, with the slack, surplus and artificial variables, and takes
736 // the costs of the second phase and the tolerances
738 {
739 // A row whose right-hand side is negative is multiplied by -1, which
740 // swaps <= and >=
741 std::vector<ConstraintType> type;
742 type.reserve(num_rest);
743 row_sign.assign(num_rest, 1);
744 num_artificial = 0;
745 {
746 auto type_it = rest_types.get_it();
747 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), type_it.next_ne())
748 {
749 ConstraintType t = type_it.get_curr();
750 if (it.get_curr()[num_var] < T{0})
751 {
752 row_sign[type.size()] = -1;
753 if (t == ConstraintType::LE)
755 else if (t == ConstraintType::GE)
757 }
758 if (t != ConstraintType::LE)
759 ++num_artificial;
760 type.push_back(t);
761 }
762 }
763
764 // The scales: of each row, by its largest coefficient; of each
765 // column, by its largest coefficient once the rows are scaled; and of
766 // the objective, by its largest coefficient once the columns are
767 row_scale.assign(num_rest, T{1});
768 col_scale.assign(num_var, T{0});
769 {
770 size_t i = 0;
771 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
772 {
773 T largest = T{0};
774 for (size_t j = 0; j < num_var; ++j)
775 largest = std::max(largest, std::abs(it.get_curr()[j]));
776 row_scale[i] = scale_of(largest);
777 }
778 i = 0;
779 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
780 for (size_t j = 0; j < num_var; ++j)
781 col_scale[j] = std::max(col_scale[j], std::abs(it.get_curr()[j]) * row_scale[i]);
782 T largest = T{0};
783 for (size_t j = 0; j < num_var; ++j)
784 {
785 col_scale[j] = scale_of(col_scale[j]);
786 largest = std::max(largest, std::abs(objetive[j]) * col_scale[j]);
787 }
788 obj_scale = scale_of(largest);
789 }
790
791 // The tableau is built aside and kept only once it is complete: if
792 // building it throws, as std::bad_alloc, the program has no tableau
793 // yet, and so it still takes restrictions
794 const size_t total_cols = num_var + num_rest + num_artificial + 1; // +1 for RHS
795 std::unique_ptr<DynMatrix<T>> tableau(
796 new DynMatrix<T>(num_rest + 1, total_cols));
797 basic_vars.assign(num_rest, 0);
798 unit_col.assign(num_rest, 0);
799
800 T max_coef = T{0};
801 T max_rhs = T{0};
802 size_t artificial_col = num_var + num_rest;
803 size_t row = 1;
804 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++row)
805 {
806 const T *rest = it.get_curr();
807 const T sign = T(row_sign[row - 1]) * row_scale[row - 1];
808
809 // Decision variable coefficients
810 for (size_t j = 0; j < num_var; ++j)
811 {
812 const T a = sign * rest[j] * col_scale[j];
813 tableau->write(row, j, a);
814 max_coef = std::max(max_coef, std::abs(a));
815 }
816
817 // RHS value, which is >= 0
818 const T b = sign * rest[num_var];
819 tableau->write(row, total_cols - 1, b);
820 max_rhs = std::max(max_rhs, std::abs(b));
821
822 // Slack/surplus and artificial variables
823 const size_t slack_col = num_var + row - 1;
824 switch (type[row - 1])
825 {
826 case ConstraintType::LE: // slack variable: +1, basic
827 tableau->write(row, slack_col, T{1});
828 unit_col[row - 1] = slack_col;
829 break;
830 case ConstraintType::GE: // surplus variable: -1, plus artificial: +1, basic
831 tableau->write(row, slack_col, T{-1});
832 tableau->write(row, artificial_col, T{1});
833 unit_col[row - 1] = artificial_col++;
834 break;
835 case ConstraintType::EQ: // no slack/surplus, just artificial: +1, basic
836 tableau->write(row, artificial_col, T{1});
837 unit_col[row - 1] = artificial_col++;
838 break;
839 }
840 basic_vars[row - 1] = static_cast<int>(unit_col[row - 1]);
841 }
842
843 // The costs of the second phase, which row 0 has until solve():
844 // -c to maximize, c to minimize, so that a negative cost always
845 // improves the objective
846 const T sense = opt_type == OptimizationType::Maximize ? -obj_scale : obj_scale;
847 T max_cost = T{0};
848 phase2_cost.resize(num_var);
849 for (size_t j = 0; j < num_var; ++j)
850 {
851 phase2_cost[j] = sense * objetive[j] * col_scale[j];
852 tableau->write(0, j, phase2_cost[j]);
853 max_cost = std::max(max_cost, std::abs(phase2_cost[j]));
854 }
855
856 tol_coef = eps * std::max(T{1}, max_coef);
857 tol_rhs = eps * std::max(T{1}, max_rhs);
858 tol_cost = eps * std::max(T{1}, max_cost);
859
860 m = std::move(tableau);
861 }
862
863 // The restriction rest_idx
864 T * restriction(const size_t rest_idx) const
865 {
866 size_t i = 0;
867 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
868 if (i == rest_idx)
869 return it.get_curr();
870 return nullptr;
871 }
872
873 // The empty program, without variables nor restrictions, that a move
874 // leaves in its source; the public constructor demands variables
875 Simplex() noexcept
876 : m(nullptr), num_var(0), num_rest(0), num_artificial(0), state(Not_Solved),
877 opt_type(OptimizationType::Maximize), pivot_rule(PivotRule::Dantzig),
878 eps(std::numeric_limits<T>::epsilon() * 100)
879 {}
880
881 public:
895 explicit Simplex(const size_t n,
897 : m(nullptr), objetive(allocate(n, 1)), num_var(n), num_rest(0),
898 num_artificial(0), solution(allocate(n)), state(Not_Solved),
899 opt_type(type), pivot_rule(PivotRule::Dantzig),
900 eps(std::numeric_limits<T>::epsilon() * 100)
901 {
903 << "Number of variables must be greater than zero";
904
905 // Initialize objective coefficients to zero
906 for (size_t i = 0; i < n; ++i)
907 objetive[i] = solution[i] = T{0};
908 }
909
915 {
916 rest_list.for_each([](auto ptr) { delete[] ptr; });
917 }
918
919 // Non-copyable
920 Simplex(const Simplex &) = delete;
921
922 Simplex &operator=(const Simplex &) = delete;
923
933 Simplex(Simplex && other) noexcept : Simplex()
934 {
935 swap(other);
936 }
937
944 Simplex &operator=(Simplex && other) noexcept
945 {
946 swap(other);
947 return *this;
948 }
949
954 void swap(Simplex & other) noexcept
955 {
956 std::swap(m, other.m);
957 std::swap(objetive, other.objetive);
958 rest_list.swap(other.rest_list);
959 rest_types.swap(other.rest_types);
960 std::swap(num_var, other.num_var);
961 std::swap(num_rest, other.num_rest);
962 std::swap(num_artificial, other.num_artificial);
963 std::swap(solution, other.solution);
964 std::swap(state, other.state);
965 std::swap(opt_type, other.opt_type);
966 std::swap(pivot_rule, other.pivot_rule);
967 std::swap(eps, other.eps);
968 std::swap(stats, other.stats);
969 pivot_row_buffer.swap(other.pivot_row_buffer);
970 pivot_col_buffer.swap(other.pivot_col_buffer);
971 basic_vars.swap(other.basic_vars);
972 row_sign.swap(other.row_sign);
973 unit_col.swap(other.unit_col);
974 phase2_cost.swap(other.phase2_cost);
975 row_scale.swap(other.row_scale);
976 col_scale.swap(other.col_scale);
977 std::swap(obj_scale, other.obj_scale);
978 std::swap(tol_coef, other.tol_coef);
979 std::swap(tol_rhs, other.tol_rhs);
980 std::swap(tol_cost, other.tol_cost);
981 std::swap(degenerate_run, other.degenerate_run);
982 tie_cost.swap(other.tie_cost);
983 std::swap(in_phase1, other.in_phase1);
984 }
985
993 {
994 opt_type = type;
995 }
996
1001 void set_minimize() noexcept
1002 {
1003 opt_type = OptimizationType::Minimize;
1004 }
1005
1010 void set_maximize() noexcept
1011 {
1012 opt_type = OptimizationType::Maximize;
1013 }
1014
1023 void set_pivot_rule(PivotRule rule) noexcept
1024 {
1025 pivot_rule = rule;
1026 }
1027
1032 void enable_bland_rule() noexcept
1033 {
1034 pivot_rule = PivotRule::Bland;
1035 stats.bland_rule_used = true;
1036 }
1037
1049 void set_epsilon(T epsilon) noexcept
1050 {
1051 eps = epsilon;
1052 }
1053
1058 [[nodiscard]] OptimizationType get_optimization_type() const noexcept
1059 {
1060 return opt_type;
1061 }
1062
1072 void put_objetive_function_coef(size_t i, const T & coef)
1073 {
1074 verify_var_index(i);
1075 objetive[i] = coef;
1076 }
1077
1085 [[nodiscard]] const T &get_objetive_function_coef(size_t i) const
1086 {
1087 verify_var_index(i);
1088 return objetive[i];
1089 }
1090
1096 {
1097 for (size_t i = 0; i < num_var; ++i)
1098 objetive[i] = coefs[i];
1099 }
1100
1105 void put_objetive_function(const T coefs[])
1106 {
1107 for (size_t i = 0; i < num_var; ++i)
1108 objetive[i] = coefs[i];
1109 }
1110
1132 T * put_restriction(const T *coefs = nullptr,
1134 {
1135 T *rest = create_restriction(type);
1136
1137 if (coefs == nullptr)
1138 return rest;
1139
1140 for (size_t i = 0; i <= num_var; ++i)
1141 rest[i] = coefs[i];
1142
1143 return rest;
1144 }
1145
1157 T * put_ge_restriction(const T *coefs)
1158 {
1159 return put_restriction(coefs, ConstraintType::GE);
1160 }
1161
1173 T * put_eq_restriction(const T *coefs)
1174 {
1175 return put_restriction(coefs, ConstraintType::EQ);
1176 }
1177
1190 {
1191 T *rest = create_restriction(type);
1192
1193 for (size_t i = 0; i <= num_var; ++i)
1194 rest[i] = coefs[i];
1195
1196 return rest;
1197 }
1198
1206 [[nodiscard]] T * get_restriction(const size_t rest_num)
1207 {
1208 verify_rest_index(rest_num);
1209 return restriction(rest_num);
1210 }
1211
1216 [[nodiscard]] size_t get_num_restrictions() const noexcept
1217 {
1218 return num_rest;
1219 }
1220
1225 [[nodiscard]] size_t get_num_vars() const noexcept
1226 {
1227 return num_var;
1228 }
1229
1234 [[nodiscard]] T * get_objetive_function() noexcept
1235 {
1236 return objetive.get();
1237 }
1238
1243 [[nodiscard]] const T * get_objetive_function() const noexcept
1244 {
1245 return objetive.get();
1246 }
1247
1256 [[nodiscard]] T &get_restriction_coef(const size_t rest_num, size_t idx)
1257 {
1258 verify_var_index(idx);
1259 return get_restriction(rest_num)[idx];
1260 }
1261
1270 void put_restriction_coef(const size_t rest_num, const size_t idx, const T & coef)
1271 {
1272 get_restriction_coef(rest_num, idx) = coef;
1273 }
1274
1288 {
1289 ah_logic_error_if(num_rest == 0)
1290 << "Cannot prepare linear program without constraints";
1291 create_matrix();
1292 }
1293
1310 [[nodiscard]] State solve()
1311 {
1312 ah_logic_error_if(state != Not_Solved) << "solve() has already been called";
1313 ah_logic_error_if(num_rest == 0) << "Linear program has no constraints";
1314 ah_logic_error_if(m == nullptr) << "prepare_linear_program() must be called before solve()";
1315
1316 auto no_hook = [] (size_t, size_t, bool) { /* empty */ };
1317 return run(no_hook);
1318 }
1319
1324 [[nodiscard]] State get_state() const noexcept
1325 {
1326 return state;
1327 }
1328
1337 void load_solution() noexcept
1338 {
1339 for (size_t j = 0; j < num_var; ++j)
1340 solution[j] = T{0};
1341
1342 if (m == nullptr)
1343 return;
1344
1345 const size_t rhs = rhs_col();
1346 for (size_t i = 1; i <= num_rest; ++i)
1347 if (const int b = basic_vars[i - 1]; b < static_cast<int>(num_var))
1348 solution[b] = col_scale[b] * m->read(i, rhs);
1349 }
1350
1360 [[nodiscard]] const T &get_solution(size_t i) const noexcept
1361 {
1362 assert(i < num_var);
1363 return solution[i];
1364 }
1365
1374 [[nodiscard]] T objetive_value() const noexcept
1375 {
1376 T sum = 0;
1377 for (size_t i = 0; i < num_var; ++i)
1378 sum += solution[i] * objetive[i];
1379 return sum;
1380 }
1381
1393 [[nodiscard]] bool verify_solution() const
1394 {
1395 const T tol = std::max(eps, T(10000) * std::numeric_limits<T>::epsilon());
1396
1397 for (size_t j = 0; j < num_var; ++j)
1398 if (solution[j] < -tol * std::max(T{1}, std::abs(solution[j])))
1399 return false;
1400
1401 auto type_it = rest_types.get_it();
1402 for (auto it = rest_list.get_it(); it.has_curr();
1403 it.next_ne(), type_it.next_ne())
1404 {
1405 const T *rest = it.get_curr();
1406 ConstraintType ctype = type_it.get_curr();
1407 T sum = 0;
1408 T size = std::abs(rest[num_var]);
1409 for (size_t j = 0; j < num_var; ++j)
1410 {
1411 sum += rest[j] * solution[j];
1412 size += std::abs(rest[j] * solution[j]);
1413 }
1414
1415 const T rhs = rest[num_var];
1416 const T room = tol * std::max(T{1}, size);
1417 switch (ctype)
1418 {
1419 case ConstraintType::LE:
1420 if (sum > rhs + room)
1421 return false;
1422 break;
1423 case ConstraintType::GE:
1424 if (sum < rhs - room)
1425 return false;
1426 break;
1427 case ConstraintType::EQ:
1428 if (std::abs(sum - rhs) > room)
1429 return false;
1430 break;
1431 }
1432 }
1433 return true;
1434 }
1435
1445 void print_matrix() const
1446 {
1447 ah_logic_error_if(m == nullptr) << "prepare_linear_program() must be called first";
1448
1449 for (size_t i = 0; i <= num_rest; ++i)
1450 {
1451 for (size_t j = 0; j <= rhs_col(); ++j)
1452 std::cout << format_entry(m->read(i, j), 2) << " ";
1453
1454 std::cout << std::endl;
1455 }
1456 }
1457
1467 void latex_matrix(const std::string & name, const int d = 2,
1468 const int p = -1, const int q = -1) const
1469 {
1470 ah_logic_error_if(m == nullptr) << "prepare_linear_program() must be called first";
1471
1472 std::ofstream out(name, std::ios::out);
1473
1474 const size_t cols = rhs_col();
1475
1476 out << "$\\left(\\begin{array}{c";
1477 for (size_t i = 0; i < cols; ++i)
1478 out << "c";
1479 out << "}" << std::endl;
1480
1481 for (size_t i = 0; i <= num_rest; ++i)
1482 {
1483 for (size_t j = 0; j <= cols; ++j)
1484 {
1485 if (static_cast<int>(i) == p and static_cast<int>(j) == q)
1486 out << "\\circled{" << format_entry(m->read(i, j), d) << "}" << " ";
1487 else
1488 out << format_entry(m->read(i, j), d) << " ";
1489 if (j != cols)
1490 out << "& ";
1491 }
1492
1493 if (i != num_rest)
1494 out << "\\\\";
1495
1496 out << std::endl;
1497 }
1498 out << "\\end{array}\\right)$" << std::endl;
1499 }
1500
1508 void latex_linear_program(const std::string & name) const
1509 {
1510 std::ofstream out(name, std::ios::out);
1511 out << "\\begin{equation*}" << std::endl
1512 << (opt_type == OptimizationType::Maximize ? "\\max " : "\\min ")
1513 << "Z = ";
1514
1515 bool first = true;
1516 for (size_t i = 0; i < num_var; ++i)
1517 {
1518 if (objetive[i] == 0.0)
1519 continue;
1520
1521 if (not first)
1522 out << " + ";
1523 first = false;
1524
1525 if (objetive[i] != 1.0)
1526 out << objetive[i];
1527 out << "x_" << i;
1528 }
1529 if (first)
1530 out << "0";
1531 out << std::endl
1532 << "\\end{equation*}" << std::endl
1533 << "Subject to:" << std::endl
1534 << "\\begin{eqnarray*}" << std::endl;
1535
1536 auto type_it = rest_types.get_it();
1537 for (auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), type_it.next_ne())
1538 {
1539 const T *rest = it.get_curr();
1540
1541 bool first_term = true;
1542 for (size_t i = 0; i < num_var; ++i)
1543 {
1544 if (rest[i] == 0.0)
1545 continue;
1546
1547 if (not first_term)
1548 out << " + ";
1549 first_term = false;
1550
1551 if (rest[i] != 1.0)
1552 out << rest[i];
1553 out << " x_" << i;
1554 }
1555 if (first_term)
1556 out << "0";
1557
1558 switch (type_it.get_curr())
1559 {
1560 case ConstraintType::LE: out << " & \\leq & "; break;
1561 case ConstraintType::GE: out << " & \\geq & "; break;
1562 case ConstraintType::EQ: out << " & = & "; break;
1563 }
1564 out << rest[num_var];
1565
1566 if (not it.is_in_last())
1567 out << " \\\\";
1568
1569 out << std::endl;
1570 }
1571 out << "\\end{eqnarray*}" << std::endl;
1572 }
1573
1586 State latex_solve(const char *name = nullptr)
1587 {
1588 ah_logic_error_if(state != Not_Solved) << "solve() has already been called";
1589 ah_logic_error_if(num_rest == 0) << "Linear program has no constraints";
1590 ah_logic_error_if(m == nullptr) << "prepare_linear_program() must be called before solve()";
1591
1592 const std::string base = name ? name : "simplex";
1593 latex_matrix(base + "-0.tex");
1594
1595 size_t k = 1;
1596 auto hook = [&] (size_t p, size_t q, bool after)
1597 {
1598 if (after)
1599 latex_matrix(base + "-" + std::to_string(k++) + "-after.tex", 2,
1600 static_cast<int>(p), static_cast<int>(q));
1601 else
1602 latex_matrix(base + "-" + std::to_string(k) + ".tex", 2,
1603 static_cast<int>(p), static_cast<int>(q));
1604 };
1605 const State st = run(hook);
1606 latex_matrix(base + "-" + std::to_string(k) + ".tex");
1607 return st;
1608 }
1609
1610 // ================== Statistics ==================
1611
1618 [[nodiscard]] const SimplexStats & get_stats() const noexcept
1619 {
1620 return stats;
1621 }
1622
1627 [[nodiscard]] size_t get_iteration_count() const noexcept
1628 {
1629 return stats.iterations;
1630 }
1631
1636 [[nodiscard]] size_t get_pivot_count() const noexcept
1637 {
1638 return stats.pivots;
1639 }
1640
1647 [[nodiscard]] size_t get_degenerate_pivot_count() const noexcept
1648 {
1649 return stats.degenerate_pivots;
1650 }
1651
1656 [[nodiscard]] double get_elapsed_time_ms() const noexcept
1657 {
1658 return stats.elapsed_ms;
1659 }
1660
1661 // ================== Sensitivity Analysis ==================
1662
1677 [[nodiscard]] SensitivityRange<T> objective_sensitivity(size_t var_idx) const
1678 {
1679 verify_var_index(var_idx);
1680 ah_logic_error_if(state != Solved) << "Must solve before sensitivity analysis";
1681
1682 constexpr T inf = std::numeric_limits<T>::infinity();
1683 SensitivityRange<T> result;
1684 result.current_value = objetive[var_idx];
1685
1686 // The range [lo, hi] of a change d of the cost that row 0 minimizes
1687 // (-c_j to maximize), for which no cost in row 0 goes below zero
1688 T lo = -inf, hi = inf;
1689 size_t row = 0;
1690 for (size_t i = 1; i <= num_rest; ++i)
1691 if (basic_vars[i - 1] == static_cast<int>(var_idx))
1692 row = i;
1693
1694 if (row == 0) // not basic: only its own cost changes, by d
1695 lo = -std::max(m->read(0, var_idx), T{0});
1696 else // basic: the cost of each column k changes by -d times its entry
1697 for (size_t k = 0; k < first_artificial(); ++k)
1698 {
1699 const T a = m->read(row, k);
1700 if (k == var_idx or std::abs(a) <= tol_coef)
1701 continue;
1702
1703 const T ratio = std::max(m->read(0, k), T{0}) / a;
1704 if (a > 0)
1705 hi = std::min(hi, ratio);
1706 else
1707 lo = std::max(lo, ratio);
1708 }
1709
1710 // d is of the scaled cost: c_j changes by d / its scale
1711 const T unit = col_scale[var_idx] * obj_scale;
1712 lo /= unit;
1713 hi /= unit;
1714
1715 if (opt_type == OptimizationType::Maximize) // c_j changes by -d
1716 {
1717 result.lower_bound = hi == inf ? -inf : result.current_value - hi;
1718 result.upper_bound = lo == -inf ? inf : result.current_value - lo;
1719 }
1720 else
1721 {
1722 result.lower_bound = lo == -inf ? -inf : result.current_value + lo;
1723 result.upper_bound = hi == inf ? inf : result.current_value + hi;
1724 }
1725
1726 return result;
1727 }
1728
1744 [[nodiscard]] SensitivityRange<T> rhs_sensitivity(size_t rest_idx) const
1745 {
1746 verify_rest_index(rest_idx);
1747 ah_logic_error_if(state != Solved) << "Must solve before sensitivity analysis";
1748
1749 constexpr T inf = std::numeric_limits<T>::infinity();
1750 SensitivityRange<T> result;
1751 result.current_value = restriction(rest_idx)[num_var];
1752
1753 // The range [lo, hi] of a change d of the right-hand side of the
1754 // row, which changes the right-hand sides by d times the column of
1755 // the inverse of the basis, for which none of them goes below zero;
1756 // an artificial variable that stays basic must stay at zero
1757 const size_t rhs = rhs_col();
1758 const size_t col = unit_col[rest_idx];
1759 T lo = -inf, hi = inf;
1760 for (size_t i = 1; i <= num_rest; ++i)
1761 {
1762 const T a = m->read(i, col);
1763 if (std::abs(a) <= tol_coef)
1764 continue;
1765
1766 if (is_artificial(static_cast<size_t>(basic_vars[i - 1])))
1767 {
1768 lo = std::max(lo, T{0});
1769 hi = std::min(hi, T{0});
1770 continue;
1771 }
1772
1773 const T ratio = -std::max(m->read(i, rhs), T{0}) / a;
1774 if (a > 0)
1775 lo = std::max(lo, ratio);
1776 else
1777 hi = std::min(hi, ratio);
1778 }
1779
1780 // d is of the scaled row: b_i changes by d / its scale
1781 lo /= row_scale[rest_idx];
1782 hi /= row_scale[rest_idx];
1783
1784 if (row_sign[rest_idx] < 0) // the row was multiplied by -1
1785 {
1786 const T old_lo = lo;
1787 lo = -hi;
1788 hi = -old_lo;
1789 }
1790
1791 result.lower_bound = lo == -inf ? -inf : result.current_value + lo;
1792 result.upper_bound = hi == inf ? inf : result.current_value + hi;
1793
1794 return result;
1795 }
1796
1812 [[nodiscard]] T shadow_price(size_t rest_idx) const
1813 {
1814 verify_rest_index(rest_idx);
1815 ah_logic_error_if(state != Solved) << "Must solve before computing shadow prices";
1816
1817 // The cost in row 0 of the column of the inverse of the basis of the
1818 // row is minus its dual value, in the problem that row 0 minimizes
1819 T price = m->read(0, unit_col[rest_idx]);
1820 if (opt_type == OptimizationType::Minimize)
1821 price = -price;
1822
1823 // that of the scaled row and objective, scaled back
1824 price = price * row_scale[rest_idx] / obj_scale;
1825
1826 return row_sign[rest_idx] < 0 ? -price : price;
1827 }
1828
1843 [[nodiscard]] T reduced_cost(size_t var_idx) const
1844 {
1845 verify_var_index(var_idx);
1846 ah_logic_error_if(state != Solved) << "Must solve before computing reduced costs";
1847
1848 T rc = m->read(0, var_idx);
1849
1850 // Adjust sign for maximization (reduced costs are negated in tableau)
1851 if (opt_type == OptimizationType::Maximize)
1852 rc = -rc;
1853
1854 // that of the scaled column and objective, scaled back
1855 return rc / (col_scale[var_idx] * obj_scale);
1856 }
1857
1865 [[nodiscard]] bool is_basic_variable(size_t var_idx) const
1866 {
1867 verify_var_index(var_idx);
1868 for (size_t i = 0; i < basic_vars.size(); ++i)
1869 if (basic_vars[i] == static_cast<int>(var_idx))
1870 return true;
1871 return false;
1872 }
1873
1880 [[nodiscard]] std::vector<T> get_all_shadow_prices() const
1881 {
1882 ah_logic_error_if(state != Solved) << "Must solve before computing shadow prices";
1883 std::vector<T> prices(num_rest);
1884 for (size_t i = 0; i < num_rest; ++i)
1885 prices[i] = shadow_price(i);
1886 return prices;
1887 }
1888
1895 [[nodiscard]] std::vector<T> get_all_reduced_costs() const
1896 {
1897 ah_logic_error_if(state != Solved) << "Must solve before computing reduced costs";
1898 std::vector<T> costs(num_var);
1899 for (size_t i = 0; i < num_var; ++i)
1900 costs[i] = reduced_cost(i);
1901 return costs;
1902 }
1903
1904 // ================== Dual Simplex ==================
1905
1921 [[nodiscard]] State dual_solve()
1922 {
1923 ah_logic_error_if(state != Solved)
1924 << "dual_solve() requires a previously solved problem";
1925
1926 state = Solving;
1927
1928 const auto start_time = std::chrono::high_resolution_clock::now();
1929 stats.iterations = 0;
1930 stats.pivots = 0;
1931
1932 const size_t rhs = rhs_col();
1933 const size_t M = first_artificial();
1934 degenerate_run = 0;
1935
1936 while (state == Solving)
1937 {
1938 ++stats.iterations;
1939 const bool bland = bland_now();
1940
1941 // Select leaving variable: a row with a negative RHS, the most
1942 // negative one, or with Bland's rule the one whose basic
1943 // variable has the least index
1944 int leaving_row = -1;
1945 T min_rhs = -tol_rhs;
1946 for (size_t i = 1; i <= num_rest; ++i)
1947 {
1948 const T b = m->read(i, rhs);
1949 if (b >= -tol_rhs)
1950 continue;
1951
1952 if (leaving_row == -1
1953 or (bland ? basic_vars[i - 1] < basic_vars[leaving_row - 1] : b < min_rhs))
1954 {
1955 min_rhs = b;
1956 leaving_row = static_cast<int>(i);
1957 }
1958 }
1959
1960 if (leaving_row == -1)
1961 break;
1962
1963 // Select entering variable: a negative entry of the row, not
1964 // artificial, with the least ratio of its cost to its magnitude;
1965 // among ties, the least index with Bland's rule and the largest
1966 // magnitude else
1967 int entering_col = -1;
1968 T min_ratio = T{0};
1969 T max_mag = T{0};
1970 for (size_t j = 0; j < M; ++j)
1971 {
1972 const T a = m->read(leaving_row, j);
1973 if (a >= -tol_coef)
1974 continue; // Must be negative
1975
1976 const T ratio = std::max(m->read(0, j), T{0}) / -a;
1977 if (entering_col == -1 or (ratio < min_ratio and not same_ratio(ratio, min_ratio)))
1978 {
1979 entering_col = static_cast<int>(j);
1980 min_ratio = ratio;
1981 max_mag = -a;
1982 }
1983 else if (same_ratio(ratio, min_ratio) and not bland and -a > max_mag)
1984 {
1985 entering_col = static_cast<int>(j);
1986 max_mag = -a;
1987 }
1988 }
1989
1990 if (entering_col == -1)
1991 {
1992 state = Unfeasible;
1993 break;
1994 }
1995
1996 if (bland)
1997 stats.bland_rule_used = true;
1998
1999 // A degenerate pivot leaves the objective as it was
2000 if (m->read(0, entering_col) <= tol_cost)
2001 {
2002 ++stats.degenerate_pivots;
2003 ++degenerate_run;
2004 }
2005 else
2006 degenerate_run = 0;
2007
2008 ++stats.pivots;
2009 to_pivot(static_cast<size_t>(leaving_row), static_cast<size_t>(entering_col));
2010 }
2011
2012 if (state == Solving)
2013 {
2014 state = Solved;
2015 for (size_t i = 1; i <= num_rest; ++i)
2016 if (is_artificial(static_cast<size_t>(basic_vars[i - 1]))
2017 and m->read(i, rhs) > tol_rhs)
2018 state = Unfeasible;
2019 }
2020
2021 const auto end_time = std::chrono::high_resolution_clock::now();
2022 stats.elapsed_ms = std::chrono::duration<double, std::milli>(end_time - start_time).count();
2023
2024 return state;
2025 }
2026
2042 [[nodiscard]] State update_rhs_and_reoptimize(size_t rest_idx, T new_rhs)
2043 {
2044 verify_rest_index(rest_idx);
2045 ah_logic_error_if(state != Solved)
2046 << "Cannot update RHS without a solved problem";
2047
2048 T *rest = restriction(rest_idx);
2049 const T delta = T(row_sign[rest_idx]) * row_scale[rest_idx] * (new_rhs - rest[num_var]);
2050 rest[num_var] = new_rhs;
2051
2052 const size_t rhs = rhs_col();
2053 const size_t col = unit_col[rest_idx];
2054 for (size_t row = 0; row <= num_rest; ++row)
2055 m->write(row, rhs, m->read(row, rhs) + m->read(row, col) * delta);
2056
2057 return dual_solve();
2058 }
2059
2062 void print_stats() const
2063 {
2064 std::cout << "=== Simplex Statistics ===\n"
2065 << "Iterations: " << stats.iterations << "\n"
2066 << "Pivots: " << stats.pivots << "\n"
2067 << "Degenerate pivots: " << stats.degenerate_pivots << "\n"
2068 << "Elapsed time: " << stats.elapsed_ms << " ms\n"
2069 << "Bland's rule used: " << (stats.bland_rule_used ? "yes" : "no") << "\n";
2070 }
2071
2077 {
2078 ah_logic_error_if(state != Solved)
2079 << "Must solve before printing sensitivity analysis";
2080
2081 std::cout << "=== Sensitivity Analysis ===\n\n";
2082
2083 std::cout << "Objective Coefficients:\n";
2084 for (size_t i = 0; i < num_var; ++i)
2085 {
2086 auto range = objective_sensitivity(i);
2087 std::cout << " x_" << i << ": current=" << range.current_value
2088 << ", range=[" << range.lower_bound << ", "
2089 << range.upper_bound << "]\n";
2090 }
2091
2092 std::cout << "\nRHS Values (Shadow Prices):\n";
2093 for (size_t i = 0; i < num_rest; ++i)
2094 {
2095 auto range = rhs_sensitivity(i);
2096 T sp = shadow_price(i);
2097 std::cout << " Constraint " << i << ": current=" << range.current_value
2098 << ", range=[" << range.lower_bound << ", " << range.upper_bound
2099 << "], shadow price=" << sp << "\n";
2100 }
2101
2102 std::cout << "\nReduced Costs:\n";
2103 for (size_t i = 0; i < num_var; ++i)
2104 {
2105 T rc = reduced_cost(i);
2106 bool basic = is_basic_variable(i);
2107 std::cout << " x_" << i << ": " << rc
2108 << (basic ? " (basic)" : " (non-basic)") << "\n";
2109 }
2110 }
2111 };
2112
2113
2114 // ============================================================================
2115 // REVISED SIMPLEX
2116 // ============================================================================
2117
2174 template <typename T>
2176 {
2177 public:
2180
2181 private:
2182 // Original problem data
2183 size_t m; // Number of constraints
2184 size_t n; // Number of original variables
2185 std::vector<T> c; // Objective coefficients (n)
2186 std::vector<std::vector<T>> A; // Constraint matrix (m × n)
2187 std::vector<T> b; // RHS values (m)
2188
2189 // The scaled program that solve() works on: each row, each column and
2190 // the objective multiplied by a power of two, so that the largest
2191 // magnitude of each is in [1/2, 1), and the tolerances do not depend
2192 // on the units of the data
2193 std::vector<std::vector<T>> As;
2194 std::vector<T> bs;
2195 std::vector<T> cs;
2196 std::vector<T> row_scale;
2197 std::vector<T> col_scale;
2198
2199 // The columns: the n original variables, the m slack variables, of
2200 // columns e_i, and the artificial variables, of columns -e_i for the
2201 // rows art_row
2202 std::vector<size_t> art_row;
2203
2204 // Basis information
2205 std::vector<int> basic; // basic[i] = index of basic variable in row i
2206 std::vector<bool> is_basic; // is_basic[j] = true if variable j is in basis
2207
2208 std::vector<std::vector<T>> B_inv_explicit; // Explicit B⁻¹
2209
2210 // Current solution
2211 std::vector<T> x_B; // Basic variable values (m)
2212 std::vector<T> solution; // Full solution (n + m)
2213
2214 // Working vectors (reused across iterations)
2215 mutable std::vector<T> pi; // Dual prices (m)
2216 mutable std::vector<T> d; // FTRAN result / tableau column (m)
2217 mutable std::vector<T> work; // A column of the problem (m)
2218 std::vector<T> cost; // The costs of the current phase
2219
2220 // Configuration
2222 size_t refactor_frequency; // Refactorize B⁻¹ every N pivots
2224 size_t since_refactor = 0;
2225
2226 // Tolerances: eps times the largest magnitude of the entries of the
2227 // scaled As, bs and cs, at least 1 each
2231
2232 // The degenerate pivots in a row; past n + m, Bland's rule
2233 size_t degenerate_run = 0;
2234
2235 // State and statistics
2238
2239 size_t num_columns() const noexcept { return n + m + art_row.size(); }
2240
2241 bool is_artificial(const size_t j) const noexcept { return j >= n + m; }
2242
2243 // ============ The column j of the problem ============
2244
2245 void get_column(size_t j, std::vector<T>& col) const
2246 {
2247 if (j < n)
2248 for (size_t i = 0; i < m; ++i)
2249 col[i] = As[i][j];
2250 else if (j < n + m)
2251 for (size_t i = 0; i < m; ++i)
2252 col[i] = i == j - n ? T{1} : T{0};
2253 else
2254 for (size_t i = 0; i < m; ++i)
2255 col[i] = i == art_row[j - n - m] ? T{-1} : T{0};
2256 }
2257
2258 // ============ FTRAN: Solve B·y = a (forward transformation) ============
2259 // Computes y = B⁻¹·a
2260
2261 void ftran(const std::vector<T>& a, std::vector<T>& y) const
2262 {
2263 for (size_t i = 0; i < m; ++i)
2264 {
2265 T sum = T{0};
2266 for (size_t j = 0; j < m; ++j)
2267 sum += B_inv_explicit[i][j] * a[j];
2268 y[i] = sum;
2269 }
2270 }
2271
2272 // ============ BTRAN: Solve π·B = c_B (backward transformation) ============
2273 // Computes π = c_B · B⁻¹
2274
2275 void btran(const std::vector<T>& c_B, std::vector<T>& pi_out) const
2276 {
2277 for (size_t j = 0; j < m; ++j)
2278 {
2279 T sum = T{0};
2280 for (size_t i = 0; i < m; ++i)
2281 sum += c_B[i] * B_inv_explicit[i][j];
2282 pi_out[j] = sum;
2283 }
2284 }
2285
2286 // ============ Compute reduced cost for column j ============
2287
2288 T compute_reduced_cost(size_t j) const
2289 {
2290 // c̄_j = c_j - π · a_j
2291 get_column(j, work);
2292 T rc = cost[j];
2293 for (size_t i = 0; i < m; ++i)
2294 rc -= pi[i] * work[i];
2295 return rc;
2296 }
2297
2298 // Whether the next pivot follows Bland's rule: after a run of
2299 // degenerate pivots
2300 bool bland_now() const noexcept { return degenerate_run > n + m; }
2301
2302 // ============ Pricing: Find entering variable ============
2303
2304 // The column that enters the basis: the one of most positive reduced
2305 // cost, or with Bland's rule the first positive one; -1 if there is
2306 // none, which is optimal. An artificial variable never enters.
2308 {
2309 std::vector<T> c_B(m);
2310 for (size_t i = 0; i < m; ++i)
2311 c_B[i] = cost[basic[i]];
2312 btran(c_B, pi);
2313
2314 const bool bland = bland_now();
2315 T max_rc = tol;
2316 int entering = -1;
2317 for (size_t j = 0; j < n + m; ++j)
2318 {
2319 if (is_basic[j])
2320 continue;
2321
2322 if (const T rc = compute_reduced_cost(j); rc > max_rc)
2323 {
2324 entering = static_cast<int>(j);
2325 if (bland)
2326 break;
2327 max_rc = rc;
2328 }
2329 }
2330
2331 return entering;
2332 }
2333
2334 // ============ Ratio test: Find leaving variable ============
2335
2336 // The row whose basic variable leaves the basis: the least ratio of its
2337 // value to its positive entry in d = B⁻¹·a; among ties, with Bland's
2338 // rule the row whose basic variable has the least index, else the
2339 // largest entry. -1 if no entry is positive, which is unbounded.
2340 int select_leaving_variable(int entering, T& theta)
2341 {
2342 get_column(static_cast<size_t>(entering), work);
2343 ftran(work, d);
2344
2345 const bool bland = bland_now();
2346 int leaving = -1;
2347 theta = T{0};
2348 T max_den = T{0};
2349 for (size_t i = 0; i < m; ++i)
2350 {
2351 if (d[i] <= tol_coef)
2352 continue;
2353
2354 const T ratio = std::max(x_B[i], T{0}) / d[i];
2355 const bool tie =
2356 leaving != -1 and std::abs(ratio - theta) <= eps * std::max(T{1}, std::abs(theta));
2357 if (leaving == -1 or (ratio < theta and not tie))
2358 {
2359 leaving = static_cast<int>(i);
2360 theta = ratio;
2361 max_den = d[i];
2362 }
2363 else if (tie and (bland ? basic[i] < basic[leaving] : d[i] > max_den))
2364 {
2365 leaving = static_cast<int>(i);
2366 max_den = d[i];
2367 }
2368 }
2369
2370 if (leaving != -1)
2371 theta = std::max(x_B[leaving], T{0}) / d[leaving];
2372
2373 return leaving;
2374 }
2375
2376 // ============ Update basis inverse after pivot ============
2377 // The row r of B⁻¹ is divided by d_r, and d_i times it is subtracted
2378 // from each other row i, in place
2379
2380 void update_basis_inverse(int leaving_row, const std::vector<T>& d_col)
2381 {
2382 const size_t r = static_cast<size_t>(leaving_row);
2383 const T inv_pivot = T{1} / d_col[r];
2384 for (size_t j = 0; j < m; ++j)
2385 B_inv_explicit[r][j] *= inv_pivot;
2386
2387 for (size_t i = 0; i < m; ++i)
2388 {
2389 if (i == r or d_col[i] == T{0})
2390 continue;
2391
2392 const T factor = d_col[i];
2393 for (size_t j = 0; j < m; ++j)
2394 B_inv_explicit[i][j] -= factor * B_inv_explicit[r][j];
2395 }
2396 }
2397
2398 // The variable of column entering becomes the basic one of the row
2399 // leaving, at the value theta, with d = B⁻¹ times its column
2400 void pivot(int leaving, int entering, const T & theta)
2401 {
2402 const size_t r = static_cast<size_t>(leaving);
2403 for (size_t i = 0; i < m; ++i)
2404 x_B[i] -= theta * d[i];
2405 x_B[r] = theta;
2406
2407 is_basic[basic[r]] = false;
2408 is_basic[entering] = true;
2409 basic[r] = entering;
2410
2411 update_basis_inverse(leaving, d);
2412
2413 ++stats.pivots;
2415 refactorize();
2416 }
2417
2418 // ============ Refactorize B⁻¹ explicitly ============
2419
2420 // B⁻¹ from the columns of the basis, by Gauss-Jordan elimination with
2421 // partial pivoting, and the values of the basic variables, B⁻¹·b
2423 {
2424 // Build explicit B from current basis
2425 std::vector<std::vector<T>> B(m, std::vector<T>(m, T{0}));
2426 for (size_t i = 0; i < m; ++i)
2427 {
2428 get_column(static_cast<size_t>(basic[i]), work);
2429 for (size_t row = 0; row < m; ++row)
2430 B[row][i] = work[row];
2431 }
2432
2433 // Compute B⁻¹ using Gauss-Jordan elimination
2434 B_inv_explicit.assign(m, std::vector<T>(m, T{0}));
2435 for (size_t i = 0; i < m; ++i)
2436 B_inv_explicit[i][i] = T{1};
2437
2438 for (size_t col = 0; col < m; ++col)
2439 {
2440 // Find pivot
2441 size_t pivot_row = col;
2442 T max_val = std::abs(B[col][col]);
2443 for (size_t row = col + 1; row < m; ++row)
2444 if (std::abs(B[row][col]) > max_val)
2445 {
2446 max_val = std::abs(B[row][col]);
2447 pivot_row = row;
2448 }
2449
2450 // Swap rows if needed
2451 if (pivot_row != col)
2452 {
2453 std::swap(B[col], B[pivot_row]);
2454 std::swap(B_inv_explicit[col], B_inv_explicit[pivot_row]);
2455 }
2456
2457 // Scale pivot row
2458 const T pivot = B[col][col];
2459 for (size_t j = 0; j < m; ++j)
2460 {
2461 B[col][j] /= pivot;
2462 B_inv_explicit[col][j] /= pivot;
2463 }
2464
2465 // Eliminate column
2466 for (size_t row = 0; row < m; ++row)
2467 {
2468 if (row == col)
2469 continue;
2470
2471 const T factor = B[row][col];
2472 if (factor == T{0})
2473 continue;
2474
2475 for (size_t j = 0; j < m; ++j)
2476 {
2477 B[row][j] -= factor * B[col][j];
2478 B_inv_explicit[row][j] -= factor * B_inv_explicit[col][j];
2479 }
2480 }
2481 }
2482
2483 ftran(bs, x_B);
2485 since_refactor = 0;
2486 }
2487
2488 // Pivots until no reduced cost is above tol, which is optimal, or the
2489 // entering column has no positive entry in B⁻¹, which is unbounded
2490 State iterate(const T & tol)
2491 {
2492 degenerate_run = 0;
2493 while (true)
2494 {
2495 ++stats.iterations;
2496 const int entering = select_entering_variable(tol);
2497 if (entering < 0)
2498 return Solved;
2499
2500 T theta;
2501 const int leaving = select_leaving_variable(entering, theta);
2502 if (leaving < 0)
2503 return Unbounded;
2504
2505 if (bland_now())
2506 stats.bland_rule_used = true;
2507
2508 // A degenerate pivot leaves the vertex, and the objective, as
2509 // they were
2510 if (x_B[leaving] <= tol_rhs)
2511 {
2514 }
2515 else
2516 degenerate_run = 0;
2517
2518 pivot(leaving, entering, theta);
2519 }
2520 }
2521
2522 // After the first phase, the artificial variables that are still basic,
2523 // at zero, leave the basis by a pivot on the largest entry of their row
2524 // of B⁻¹·a_j, for a column j that is not artificial. A row without such
2525 // an entry is a combination of others: its artificial variable stays
2526 // basic, at zero.
2528 {
2529 for (size_t r = 0; r < m; ++r)
2530 {
2531 if (not is_artificial(static_cast<size_t>(basic[r])))
2532 continue;
2533
2534 x_B[r] = T{0}; // at most a rounding above zero
2535
2536 int entering = -1;
2537 T largest = tol_coef;
2538 for (size_t j = 0; j < n + m; ++j)
2539 {
2540 if (is_basic[j])
2541 continue;
2542
2543 get_column(j, work);
2544 T entry = T{0};
2545 for (size_t k = 0; k < m; ++k)
2546 entry += B_inv_explicit[r][k] * work[k];
2547 if (std::abs(entry) > largest)
2548 {
2549 largest = std::abs(entry);
2550 entering = static_cast<int>(j);
2551 }
2552 }
2553
2554 if (entering == -1)
2555 continue;
2556
2557 get_column(static_cast<size_t>(entering), work);
2558 ftran(work, d);
2560 pivot(static_cast<int>(r), entering, T{0});
2561 }
2562 }
2563
2564 // The power of two that takes magnitude into [1/2, 1); 1 for 0, for a
2565 // subnormal magnitude, whose power could overflow, or for a magnitude
2566 // that is not finite
2567 static T scale_of(const T & magnitude) noexcept
2568 {
2569 if (not (magnitude >= std::numeric_limits<T>::min()) or not std::isfinite(magnitude))
2570 return T{1};
2571 int e;
2572 (void) std::frexp(magnitude, &e);
2573 return std::ldexp(T{1}, -e);
2574 }
2575
2576 // The scaled program: each row by its largest coefficient, each column
2577 // by its largest coefficient once the rows are scaled, and the
2578 // objective by its largest coefficient once the columns are
2579 void scale()
2580 {
2581 row_scale.assign(m, T{1});
2582 col_scale.assign(n, T{0});
2583 for (size_t i = 0; i < m; ++i)
2584 {
2585 T largest = T{0};
2586 for (size_t j = 0; j < n; ++j)
2587 largest = std::max(largest, std::abs(A[i][j]));
2588 row_scale[i] = scale_of(largest);
2589 }
2590 for (size_t i = 0; i < m; ++i)
2591 for (size_t j = 0; j < n; ++j)
2592 col_scale[j] = std::max(col_scale[j], std::abs(A[i][j]) * row_scale[i]);
2593 T largest = T{0};
2594 for (size_t j = 0; j < n; ++j)
2595 {
2596 col_scale[j] = scale_of(col_scale[j]);
2597 largest = std::max(largest, std::abs(c[j]) * col_scale[j]);
2598 }
2599 const T obj_scale = scale_of(largest);
2600
2601 As.assign(m, std::vector<T>(n));
2602 bs.resize(m);
2603 cs.resize(n);
2604 for (size_t i = 0; i < m; ++i)
2605 {
2606 for (size_t j = 0; j < n; ++j)
2607 As[i][j] = A[i][j] * row_scale[i] * col_scale[j];
2608 bs[i] = b[i] * row_scale[i];
2609 }
2610 for (size_t j = 0; j < n; ++j)
2611 cs[j] = c[j] * col_scale[j] * obj_scale;
2612 }
2613
2614 // The empty program, without variables nor constraints, that a move
2615 // leaves in its source; the public constructor demands both
2617 : m(0), n(0), eps(std::numeric_limits<T>::epsilon() * 1000), refactor_frequency(50),
2619 {}
2620
2621 public:
2629 RevisedSimplex(size_t num_vars, size_t num_constraints)
2630 : m(num_constraints), n(num_vars),
2631 c(num_vars, T{0}),
2632 A(num_constraints, std::vector<T>(num_vars, T{0})),
2633 b(num_constraints, T{0}),
2634 basic(num_constraints),
2635 x_B(num_constraints, T{0}),
2636 solution(num_vars + num_constraints, T{0}),
2637 pi(num_constraints), d(num_constraints), work(num_constraints),
2638 eps(std::numeric_limits<T>::epsilon() * 1000),
2639 refactor_frequency(std::max(size_t{50}, num_constraints)),
2641 {
2642 ah_invalid_argument_if(num_vars == 0 || num_constraints == 0)
2643 << "Number of variables and constraints must be > 0";
2644 }
2645
2651 RevisedSimplex(const RevisedSimplex & other) = default;
2652
2663 {
2664 swap(other);
2665 }
2666
2673 RevisedSimplex & operator=(const RevisedSimplex & other) = default;
2674
2682 {
2683 swap(other);
2684 return *this;
2685 }
2686
2691 void swap(RevisedSimplex & other) noexcept
2692 {
2693 std::swap(m, other.m);
2694 std::swap(n, other.n);
2695 c.swap(other.c);
2696 A.swap(other.A);
2697 b.swap(other.b);
2698 As.swap(other.As);
2699 bs.swap(other.bs);
2700 cs.swap(other.cs);
2701 row_scale.swap(other.row_scale);
2702 col_scale.swap(other.col_scale);
2703 art_row.swap(other.art_row);
2704 basic.swap(other.basic);
2705 is_basic.swap(other.is_basic);
2706 B_inv_explicit.swap(other.B_inv_explicit);
2707 x_B.swap(other.x_B);
2708 solution.swap(other.solution);
2709 pi.swap(other.pi);
2710 d.swap(other.d);
2711 work.swap(other.work);
2712 cost.swap(other.cost);
2713 std::swap(eps, other.eps);
2714 std::swap(refactor_frequency, other.refactor_frequency);
2715 std::swap(refactorizations, other.refactorizations);
2716 std::swap(since_refactor, other.since_refactor);
2717 std::swap(tol_coef, other.tol_coef);
2718 std::swap(tol_rhs, other.tol_rhs);
2719 std::swap(tol_cost, other.tol_cost);
2720 std::swap(degenerate_run, other.degenerate_run);
2721 std::swap(state, other.state);
2722 std::swap(stats, other.stats);
2723 }
2724
2732 void set_objective(size_t j, T coef)
2733 {
2734 ah_out_of_range_error_if(j >= n) << "Variable index out of range";
2735 c[j] = coef;
2736 }
2737
2742 void set_objective(const T* coefs)
2743 {
2744 for (size_t j = 0; j < n; ++j)
2745 c[j] = coefs[j];
2746 }
2747
2756 void set_constraint(size_t i, size_t j, T coef)
2757 {
2758 ah_out_of_range_error_if(i >= m || j >= n)
2759 << "Constraint or variable index out of range";
2760 A[i][j] = coef;
2761 }
2762
2770 void set_rhs(size_t i, T rhs)
2771 {
2772 ah_out_of_range_error_if(i >= m) << "Constraint index out of range";
2773 b[i] = rhs;
2774 }
2775
2784 void set_constraint_row(size_t i, const T* coefs, T rhs)
2785 {
2786 ah_out_of_range_error_if(i >= m) << "Constraint index out of range";
2787 for (size_t j = 0; j < n; ++j)
2788 A[i][j] = coefs[j];
2789 b[i] = rhs;
2790 }
2791
2802 {
2803 ah_invalid_argument_if(freq == 0) << "Refactorization frequency must be > 0";
2804 refactor_frequency = freq;
2805 }
2806
2813 [[nodiscard]] State solve()
2814 {
2815 ah_logic_error_if(state != Not_Solved) << "Already solved";
2816
2817 stats.reset();
2818 auto start_time = std::chrono::high_resolution_clock::now();
2819
2820 scale();
2821 T max_coef = T{0}, max_rhs = T{0}, max_cost = T{0};
2822 for (size_t i = 0; i < m; ++i)
2823 {
2824 for (size_t j = 0; j < n; ++j)
2825 max_coef = std::max(max_coef, std::abs(As[i][j]));
2826 max_rhs = std::max(max_rhs, std::abs(bs[i]));
2827 }
2828 for (size_t j = 0; j < n; ++j)
2829 max_cost = std::max(max_cost, std::abs(cs[j]));
2830 tol_coef = eps * std::max(T{1}, max_coef);
2831 tol_rhs = eps * std::max(T{1}, max_rhs);
2832 tol_cost = eps * std::max(T{1}, max_cost);
2833
2834 // The initial basis: the slack variable of each row whose b_i is >=
2835 // 0, and an artificial variable of each other row, at -b_i; B⁻¹ is
2836 // diagonal, of 1 and -1
2837 art_row.clear();
2838 B_inv_explicit.assign(m, std::vector<T>(m, T{0}));
2839 for (size_t i = 0; i < m; ++i)
2840 if (bs[i] < T{0})
2841 {
2842 basic[i] = static_cast<int>(n + m + art_row.size());
2843 art_row.push_back(i);
2844 B_inv_explicit[i][i] = T{-1};
2845 x_B[i] = -bs[i];
2846 }
2847 else
2848 {
2849 basic[i] = static_cast<int>(n + i);
2850 B_inv_explicit[i][i] = T{1};
2851 x_B[i] = bs[i];
2852 }
2853
2854 is_basic.assign(num_columns(), false);
2855 for (size_t i = 0; i < m; ++i)
2856 is_basic[basic[i]] = true;
2857 cost.assign(num_columns(), T{0});
2859
2860 state = Solving;
2861
2862 if (not art_row.empty())
2863 {
2864 // Phase I: maximize minus the sum of the artificial variables
2865 for (size_t j = n + m; j < num_columns(); ++j)
2866 cost[j] = T{-1};
2867 const T scale = T(art_row.size());
2868 (void) iterate(tol_coef * scale); // bounded above by zero
2869
2870 T sum = T{0};
2871 for (size_t i = 0; i < m; ++i)
2872 if (is_artificial(static_cast<size_t>(basic[i])))
2873 sum += x_B[i];
2874
2875 if (sum > tol_rhs * scale)
2876 state = Unfeasible;
2877 else
2879 }
2880
2881 if (state == Solving)
2882 {
2883 // Phase II, on the objective
2884 for (size_t j = 0; j < num_columns(); ++j)
2885 cost[j] = j < n ? cs[j] : T{0};
2887 }
2888
2889 // Load final solution, scaled back: a variable by its column, a
2890 // slack by its row
2891 std::fill(solution.begin(), solution.end(), T{0});
2892 for (size_t i = 0; i < m; ++i)
2893 if (const auto j = static_cast<size_t>(basic[i]); not is_artificial(j))
2894 solution[j] = j < n ? x_B[i] * col_scale[j] : x_B[i] / row_scale[j - n];
2895
2896 auto end_time = std::chrono::high_resolution_clock::now();
2897 stats.elapsed_ms = std::chrono::duration<double, std::milli>(
2898 end_time - start_time).count();
2899
2900 return state;
2901 }
2902
2910 [[nodiscard]] T get_solution(size_t j) const
2911 {
2912 ah_out_of_range_error_if(j >= n) << "Variable index out of range";
2913 return solution[j];
2914 }
2915
2920 [[nodiscard]] T objective_value() const
2921 {
2922 T sum = T{0};
2923 for (size_t j = 0; j < n; ++j)
2924 sum += c[j] * solution[j];
2925 return sum;
2926 }
2927
2929 [[nodiscard]] State get_state() const noexcept { return state; }
2930
2932 [[nodiscard]] const SimplexStats& get_stats() const noexcept { return stats; }
2933
2935 [[nodiscard]] size_t get_num_vars() const noexcept { return n; }
2936
2938 [[nodiscard]] size_t get_num_constraints() const noexcept { return m; }
2939
2948 [[nodiscard]] bool verify_solution() const
2949 {
2950 const T tol = T(10) * eps;
2951 for (size_t j = 0; j < n; ++j)
2952 if (solution[j] < -tol * std::max(T{1}, std::abs(solution[j])))
2953 return false;
2954
2955 for (size_t i = 0; i < m; ++i)
2956 {
2957 T lhs = T{0};
2958 T size = std::abs(b[i]);
2959 for (size_t j = 0; j < n; ++j)
2960 {
2961 lhs += A[i][j] * solution[j];
2962 size += std::abs(A[i][j] * solution[j]);
2963 }
2964 if (lhs > b[i] + tol * std::max(T{1}, size))
2965 return false;
2966 }
2967 return true;
2968 }
2969
2971 void print_stats() const
2972 {
2973 std::cout << "=== Revised Simplex Statistics ===\n"
2974 << "Variables: " << n << ", Constraints: " << m << "\n"
2975 << "Iterations: " << stats.iterations << "\n"
2976 << "Pivots: " << stats.pivots << "\n"
2977 << "Elapsed time: " << stats.elapsed_ms << " ms\n"
2978 << "Refactorizations: " << refactorizations << "\n";
2979 }
2980 };
2981
2982} // end namespace Aleph
2983
2984# endif // SIMPLEX_H
Exception handling system with formatted messages for Aleph-w.
#define ah_out_of_range_error_if(C)
Throws std::out_of_range if condition holds.
Definition ah-errors.H:727
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
Definition ah-errors.H:611
#define ah_logic_error_if(C)
Throws std::logic_error if condition holds.
Definition ah-errors.H:474
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
Definition ah-errors.H:787
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 size_t col
Definition ca-c-api.h:116
size_t cols
Definition ca-c-api.h:105
Dynamic doubly linked list with O(1) size and bidirectional access.
Dynamic matrix with sparse storage.
Definition tpl_dynMat.H:122
Revised Simplex algorithm for linear programming.
Definition Simplex.H:2176
std::vector< T > x_B
Definition Simplex.H:2211
std::vector< T > work
Definition Simplex.H:2217
void set_refactorization_frequency(size_t freq)
Sets refactorization frequency.
Definition Simplex.H:2801
void drive_out_artificials()
Definition Simplex.H:2527
bool is_artificial(const size_t j) const noexcept
Definition Simplex.H:2241
void set_objective(const T *coefs)
Sets all objective coefficients.
Definition Simplex.H:2742
std::vector< T > d
Definition Simplex.H:2216
void set_objective(size_t j, T coef)
Sets objective coefficient.
Definition Simplex.H:2732
RevisedSimplex(RevisedSimplex &&other) noexcept
Takes the program of another solver, which is left as an empty program, without variables nor constra...
Definition Simplex.H:2662
State iterate(const T &tol)
Definition Simplex.H:2490
size_t get_num_vars() const noexcept
Gets number of variables.
Definition Simplex.H:2935
std::vector< T > solution
Definition Simplex.H:2212
std::vector< T > col_scale
Definition Simplex.H:2197
RevisedSimplex & operator=(const RevisedSimplex &other)=default
Copies the program of another solver.
std::vector< int > basic
Definition Simplex.H:2205
void print_stats() const
Prints statistics to stdout.
Definition Simplex.H:2971
std::vector< bool > is_basic
Definition Simplex.H:2206
size_t get_num_constraints() const noexcept
Gets number of constraints.
Definition Simplex.H:2938
State
Solution states for the linear program.
Definition Simplex.H:2179
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
Definition Simplex.H:2932
void update_basis_inverse(int leaving_row, const std::vector< T > &d_col)
Definition Simplex.H:2380
int select_leaving_variable(int entering, T &theta)
Definition Simplex.H:2340
std::vector< std::vector< T > > A
Definition Simplex.H:2186
void pivot(int leaving, int entering, const T &theta)
Definition Simplex.H:2400
void get_column(size_t j, std::vector< T > &col) const
Definition Simplex.H:2245
static T scale_of(const T &magnitude) noexcept
Definition Simplex.H:2567
void set_constraint_row(size_t i, const T *coefs, T rhs)
Adds a complete constraint.
Definition Simplex.H:2784
RevisedSimplex() noexcept
Definition Simplex.H:2616
std::vector< T > pi
Definition Simplex.H:2215
State get_state() const noexcept
Gets current state.
Definition Simplex.H:2929
size_t num_columns() const noexcept
Definition Simplex.H:2239
RevisedSimplex(const RevisedSimplex &other)=default
Copies the program of another solver.
T get_solution(size_t j) const
Gets solution value for variable j.
Definition Simplex.H:2910
void ftran(const std::vector< T > &a, std::vector< T > &y) const
Definition Simplex.H:2261
SimplexStats stats
Definition Simplex.H:2237
std::vector< T > bs
Definition Simplex.H:2194
bool bland_now() const noexcept
Definition Simplex.H:2300
std::vector< std::vector< T > > As
Definition Simplex.H:2193
std::vector< T > c
Definition Simplex.H:2185
void set_constraint(size_t i, size_t j, T coef)
Sets constraint coefficient.
Definition Simplex.H:2756
std::vector< T > cs
Definition Simplex.H:2195
std::vector< T > cost
Definition Simplex.H:2218
std::vector< std::vector< T > > B_inv_explicit
Definition Simplex.H:2208
T objective_value() const
Computes objective function value.
Definition Simplex.H:2920
void btran(const std::vector< T > &c_B, std::vector< T > &pi_out) const
Definition Simplex.H:2275
RevisedSimplex & operator=(RevisedSimplex &&other) noexcept
Exchanges this solver with another, which is left with the previous program of this one.
Definition Simplex.H:2681
void swap(RevisedSimplex &other) noexcept
Exchanges in O(1) this solver and another.
Definition Simplex.H:2691
State solve()
Solves the linear program.
Definition Simplex.H:2813
std::vector< size_t > art_row
Definition Simplex.H:2202
std::vector< T > row_scale
Definition Simplex.H:2196
T compute_reduced_cost(size_t j) const
Definition Simplex.H:2288
void set_rhs(size_t i, T rhs)
Sets RHS value for a constraint.
Definition Simplex.H:2770
std::vector< T > b
Definition Simplex.H:2187
bool verify_solution() const
Verifies solution satisfies all constraints.
Definition Simplex.H:2948
RevisedSimplex(size_t num_vars, size_t num_constraints)
Constructs a Revised Simplex solver.
Definition Simplex.H:2629
int select_entering_variable(const T &tol)
Definition Simplex.H:2307
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
size_t rhs_col() const noexcept
Definition Simplex.H:370
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
std::vector< T > col_scale
Definition Simplex.H:344
State
Solution states for the linear program.
Definition Simplex.H:290
OptimizationType get_optimization_type() const noexcept
Gets the current optimization type.
Definition Simplex.H:1058
int compute_pivot_row(const size_t q) const noexcept
Definition Simplex.H:431
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
size_t degenerate_run
Definition Simplex.H:355
void set_minimize() noexcept
Sets minimization mode.
Definition Simplex.H:1001
std::vector< size_t > unit_col
Definition Simplex.H:332
std::vector< int > basic_vars
Definition Simplex.H:323
size_t num_rest
Definition Simplex.H:306
bool bland_now() const noexcept
Definition Simplex.H:379
OptimizationType opt_type
Definition Simplex.H:310
std::vector< T > pivot_col_buffer
Definition Simplex.H:319
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
bool is_artificial(const size_t j) const noexcept
Definition Simplex.H:372
void print_sensitivity_analysis() const
Prints sensitivity analysis to stdout.
Definition Simplex.H:2076
std::vector< T > pivot_row_buffer
Definition Simplex.H:318
std::vector< T > phase2_cost
Definition Simplex.H:336
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
void to_pivot(size_t p, size_t q)
Definition Simplex.H:465
bool verify_solution() const
Verifies that the solution satisfies all constraints.
Definition Simplex.H:1393
DynDlist< ConstraintType > rest_types
Definition Simplex.H:304
void verify_rest_index(const size_t i) const
Definition Simplex.H:689
void create_matrix()
Definition Simplex.H:737
Simplex & operator=(const Simplex &)=delete
size_t num_var
Definition Simplex.H:305
T * restriction(const size_t rest_idx) const
Definition Simplex.H:864
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
std::unique_ptr< DynMatrix< T > > m
Definition Simplex.H:301
void load_phase2_costs()
Definition Simplex.H:586
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
bool same_ratio(const T &a, const T &b) const noexcept
Definition Simplex.H:385
State run(Hook &hook)
Definition Simplex.H:635
void latex_linear_program(const std::string &name) const
Exports the linear program to a LaTeX file.
Definition Simplex.H:1508
static T scale_of(const T &magnitude) noexcept
Definition Simplex.H:725
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
size_t num_artificial
Definition Simplex.H:307
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 swap(Simplex &other) noexcept
Exchanges in O(1) this solver and another.
Definition Simplex.H:954
Simplex(const Simplex &)=delete
DynDlist< T * > rest_list
Definition Simplex.H:303
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
PivotRule pivot_rule
Definition Simplex.H:311
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
std::vector< T > tie_cost
Definition Simplex.H:362
void load_phase1_costs()
Definition Simplex.H:565
void verify_var_index(const size_t i) const
Definition Simplex.H:681
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
const T * get_objetive_function() const noexcept
Gets the objective function coefficients array (const).
Definition Simplex.H:1243
Simplex & operator=(Simplex &&other) noexcept
Exchanges this solver with another, which is left with the previous program of this one.
Definition Simplex.H:944
static std::string format_entry(const T &value, const int d)
Definition Simplex.H:672
Simplex(Simplex &&other) noexcept
Takes the program of another solver, which is left as an empty program, without variables nor restric...
Definition Simplex.H:933
~Simplex()
Destructor.
Definition Simplex.H:914
std::vector< int > row_sign
Definition Simplex.H:327
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
std::unique_ptr< T[]> solution
Definition Simplex.H:308
std::vector< T > row_scale
Definition Simplex.H:343
std::unique_ptr< T[]> objetive
Definition Simplex.H:302
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
T * create_restriction(ConstraintType type=ConstraintType::LE)
Definition Simplex.H:708
State get_state() const noexcept
Gets the current state of the solver.
Definition Simplex.H:1324
State iterate(const T &cost_tol, Hook &hook)
Definition Simplex.H:526
size_t get_degenerate_pivot_count() const noexcept
Gets the number of degenerate pivots.
Definition Simplex.H:1647
T * put_restriction(const DynArray< T > &coefs, ConstraintType type=ConstraintType::LE)
Adds a constraint from a DynArray.
Definition Simplex.H:1188
PivotRule
Pivot selection rule.
Definition Simplex.H:298
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 drive_out_artificials(Hook &hook)
Definition Simplex.H:598
void enable_bland_rule() noexcept
Enables Bland's anti-cycling rule.
Definition Simplex.H:1032
Simplex(const size_t n, OptimizationType type=OptimizationType::Maximize)
Constructs a Simplex solver for n variables.
Definition Simplex.H:895
SimplexStats stats
Definition Simplex.H:315
State solve()
Solves the linear program.
Definition Simplex.H:1310
void put_objetive_function(const T coefs[])
Sets all objective function coefficients from a C array.
Definition Simplex.H:1105
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
int compute_pivot_col(const T &tol) const noexcept
Definition Simplex.H:395
Simplex() noexcept
Definition Simplex.H:875
static T * allocate(const size_t n, const size_t spare=0)
Definition Simplex.H:698
size_t first_artificial() const noexcept
Definition Simplex.H:368
double get_elapsed_time_ms() const noexcept
Gets the elapsed solving time.
Definition Simplex.H:1656
__gmp_expr< typename __gmp_resolve_expr< T, V >::value_type, __gmp_binary_expr< __gmp_expr< T, U >, __gmp_expr< V, W >, __gmp_max_function > > max(const __gmp_expr< T, U > &expr1, const __gmp_expr< V, W > &expr2)
Definition gmpfrxx.h:4188
static mpfr_t y
Definition mpfr_mul_d.c:3
Main namespace for Aleph-w library functions.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
Definition ahTypes.H:123
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::decay_t< typename HeadC::Item_Type > T
Definition ah-zip.H:152
and
Check uniqueness with explicit hash + equality functors.
@ Maximize
Larger objective values are better.
@ Minimize
Smaller objective values are better.
T * allocate(AhArenaAllocator &arena, Args &&... args)
Allocate and construct an object in an arena.
Definition ah-arena.H:478
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
OptimizationType
Optimization direction for linear programming.
Definition Simplex.H:91
Net::Flow_Type reduced_cost(const Net &net, typename Net::Arc *arc, bool forward)
Compute reduced cost of an arc.
T sum(const Container &container, const T &init=T{})
Compute sum of all elements.
STL namespace.
Sensitivity analysis result for a coefficient.
Definition Simplex.H:122
T lower_bound
Minimum value before basis change.
Definition Simplex.H:123
T upper_bound
Maximum value before basis change.
Definition Simplex.H:124
bool is_unbounded_below() const noexcept
Definition Simplex.H:127
T current_value
Current coefficient value.
Definition Simplex.H:125
bool is_unbounded_above() const noexcept
Definition Simplex.H:130
Execution statistics for the Simplex algorithm.
Definition Simplex.H:98
bool bland_rule_used
Whether Bland's rule was activated.
Definition Simplex.H:103
double elapsed_ms
Elapsed time in milliseconds.
Definition Simplex.H:102
size_t iterations
Total simplex iterations.
Definition Simplex.H:99
void reset() noexcept
Definition Simplex.H:105
size_t pivots
Total pivot operations.
Definition Simplex.H:100
size_t degenerate_pivots
Pivots with zero improvement.
Definition Simplex.H:101
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
static int * k
Gsl_Compatible_Rng r
Dynamic doubly linked list implementation.
Dynamic matrix with lazy allocation.