120 template <
typename T>
128 {
return lower_bound == -std::numeric_limits<T>::infinity(); }
131 {
return upper_bound == std::numeric_limits<T>::infinity(); }
277 template <
typename T>
301 std::unique_ptr<DynMatrix<T>>
m;
387 return std::abs(a - b) <=
eps * std::max(
T{1}, std::abs(b));
401 for (
size_t j = 0; j < M; ++j)
402 if (
m->read(0, j) < -tol)
403 return static_cast<int>(j);
409 for (
size_t j = 0; j < M; ++j)
411 const T & c =
m->read(0, j);
417 q =
static_cast<int>(j);
421 q =
static_cast<int>(j);
439 for (
size_t i = 1; i <=
num_rest; ++i)
441 const T den =
m->read(i, q);
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)))
448 p =
static_cast<int>(i);
455 p =
static_cast<int>(i);
471 const size_t cols = M + 1;
472 const T pivot =
m->read(p, q);
473 const T inv_pivot =
T{1} / pivot;
482 for (
size_t j = 0; j <= M; ++j)
486 for (
size_t j = 0; j <= M; ++j)
493 for (
size_t j = 0; j <= M; ++j)
499 for (
size_t i = 0; i <=
num_rest; ++i)
503 for (
size_t i = 0; i <=
num_rest; ++i)
512 for (
size_t j = 0; j <= M; ++j)
514 m->write(i, j,
T{0});
525 template <
class Hook>
554 hook(
static_cast<size_t>(p),
static_cast<size_t>(q),
false);
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);
568 std::vector<T> cost(
cols,
T{0});
569 for (
size_t i = 1; i <=
num_rest; ++i)
571 for (
size_t j = 0; j <
cols; ++j)
573 cost[j] -=
m->read(i, j);
575 for (
size_t j = 0; j <
cols; ++j)
576 m->write(0, j, cost[j]);
579 for (
size_t j = 0; j <
num_var; ++j)
588 for (
size_t j = 0; j <=
rhs_col(); ++j)
597 template <
class Hook>
602 for (
size_t i = 1; i <=
num_rest; ++i)
607 m->write(i, rhs,
T{0});
611 for (
size_t j = 0; j < M; ++j)
612 if (
const T a = std::abs(
m->read(i, j)); a > largest)
620 for (
size_t j = 0; j < M; ++j)
621 m->write(i, j,
T{0});
634 template <
class Hook>
638 stats.bland_rule_used = pivot_rule == PivotRule::Bland;
639 const auto start_time = std::chrono::high_resolution_clock::now();
642 if (num_artificial > 0)
646 const T scale =
T(num_artificial);
647 (void) iterate(tol_coef * scale, hook);
650 if (-
m->read(0, rhs_col()) > tol_rhs * scale)
654 drive_out_artificials(hook);
662 if (state == Solving)
663 state = iterate(tol_cost, hook);
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();
674 std::ostringstream s;
675 s << std::fixed << std::setprecision(d) <<
value;
684 <<
"Variable index " << i <<
" out of range [0, " << num_var <<
")";
692 <<
"Restriction index " << i <<
" out of range [0, " << num_rest <<
")";
698 static T *
allocate(
const size_t n,
const size_t spare = 0)
701 <<
"Simplex: the bytes of " << n <<
" coefficients do not fit in a size_t";
711 <<
"A restriction cannot be added after prepare_linear_program()";
714 rest_list.append(ptr);
715 rest_types.append(type);
717 for (
size_t i = 0; i <= num_var; ++i)
727 if (not (magnitude >= std::numeric_limits<T>::min()) or not std::isfinite(magnitude))
730 (void) std::frexp(magnitude, &e);
731 return std::ldexp(
T{1}, -e);
741 std::vector<ConstraintType> type;
742 type.reserve(num_rest);
743 row_sign.assign(num_rest, 1);
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())
750 if (it.get_curr()[num_var] <
T{0})
752 row_sign[type.size()] = -1;
767 row_scale.assign(num_rest,
T{1});
768 col_scale.assign(num_var,
T{0});
771 for (
auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
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);
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]);
783 for (
size_t j = 0; j < num_var; ++j)
785 col_scale[j] = scale_of(col_scale[j]);
786 largest = std::max(largest, std::abs(objetive[j]) * col_scale[j]);
788 obj_scale = scale_of(largest);
794 const size_t total_cols = num_var + num_rest + num_artificial + 1;
795 std::unique_ptr<DynMatrix<T>> tableau(
797 basic_vars.assign(num_rest, 0);
798 unit_col.assign(num_rest, 0);
802 size_t artificial_col = num_var + num_rest;
804 for (
auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++
row)
806 const T *rest = it.get_curr();
807 const T sign =
T(row_sign[
row - 1]) * row_scale[
row - 1];
810 for (
size_t j = 0; j < num_var; ++j)
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));
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));
823 const size_t slack_col = num_var +
row - 1;
824 switch (type[
row - 1])
827 tableau->write(
row, slack_col,
T{1});
828 unit_col[
row - 1] = slack_col;
831 tableau->write(
row, slack_col,
T{-1});
832 tableau->write(
row, artificial_col,
T{1});
833 unit_col[
row - 1] = artificial_col++;
836 tableau->write(
row, artificial_col,
T{1});
837 unit_col[
row - 1] = artificial_col++;
840 basic_vars[
row - 1] =
static_cast<int>(unit_col[
row - 1]);
848 phase2_cost.resize(num_var);
849 for (
size_t j = 0; j < num_var; ++j)
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]));
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);
860 m = std::move(tableau);
867 for (
auto it = rest_list.get_it(); it.has_curr(); it.next_ne(), ++i)
869 return it.get_curr();
876 :
m(
nullptr), num_var(0), num_rest(0), num_artificial(0), state(Not_Solved),
878 eps(
std::numeric_limits<
T>::epsilon() * 100)
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)
903 <<
"Number of variables must be greater than zero";
906 for (
size_t i = 0; i < n; ++i)
907 objetive[i] = solution[i] =
T{0};
916 rest_list.for_each([](
auto ptr) {
delete[] ptr; });
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);
1034 pivot_rule = PivotRule::Bland;
1035 stats.bland_rule_used =
true;
1074 verify_var_index(i);
1087 verify_var_index(i);
1097 for (
size_t i = 0; i < num_var; ++i)
1098 objetive[i] = coefs[i];
1107 for (
size_t i = 0; i < num_var; ++i)
1108 objetive[i] = coefs[i];
1135 T *rest = create_restriction(type);
1137 if (coefs ==
nullptr)
1140 for (
size_t i = 0; i <= num_var; ++i)
1191 T *rest = create_restriction(type);
1193 for (
size_t i = 0; i <= num_var; ++i)
1208 verify_rest_index(rest_num);
1209 return restriction(rest_num);
1236 return objetive.get();
1245 return objetive.get();
1258 verify_var_index(idx);
1259 return get_restriction(rest_num)[idx];
1272 get_restriction_coef(rest_num, idx) = coef;
1290 <<
"Cannot prepare linear program without constraints";
1314 ah_logic_error_if(
m ==
nullptr) <<
"prepare_linear_program() must be called before solve()";
1316 auto no_hook = [] (size_t, size_t, bool) { };
1317 return run(no_hook);
1339 for (
size_t j = 0; j < num_var; ++j)
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);
1362 assert(i < num_var);
1377 for (
size_t i = 0; i < num_var; ++i)
1378 sum += solution[i] * objetive[i];
1395 const T tol = std::max(eps,
T(10000) * std::numeric_limits<T>::epsilon());
1397 for (
size_t j = 0; j < num_var; ++j)
1398 if (solution[j] < -tol * std::max(
T{1}, std::abs(solution[j])))
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())
1405 const T *rest = it.get_curr();
1408 T size = std::abs(rest[num_var]);
1409 for (
size_t j = 0; j < num_var; ++j)
1411 sum += rest[j] * solution[j];
1412 size += std::abs(rest[j] * solution[j]);
1415 const T rhs = rest[num_var];
1416 const T room = tol * std::max(
T{1},
size);
1420 if (
sum > rhs + room)
1424 if (
sum < rhs - room)
1428 if (std::abs(
sum - rhs) > room)
1449 for (
size_t i = 0; i <= num_rest; ++i)
1451 for (
size_t j = 0; j <= rhs_col(); ++j)
1452 std::cout << format_entry(
m->read(i, j), 2) <<
" ";
1454 std::cout << std::endl;
1468 const int p = -1,
const int q = -1)
const
1472 std::ofstream
out(name, std::ios::out);
1474 const size_t cols = rhs_col();
1476 out <<
"$\\left(\\begin{array}{c";
1477 for (
size_t i = 0; i <
cols; ++i)
1479 out <<
"}" << std::endl;
1481 for (
size_t i = 0; i <= num_rest; ++i)
1483 for (
size_t j = 0; j <=
cols; ++j)
1485 if (
static_cast<int>(i) == p
and static_cast<int>(j) == q)
1486 out <<
"\\circled{" << format_entry(
m->read(i, j), d) <<
"}" <<
" ";
1488 out << format_entry(
m->read(i, j), d) <<
" ";
1498 out <<
"\\end{array}\\right)$" << std::endl;
1510 std::ofstream
out(name, std::ios::out);
1511 out <<
"\\begin{equation*}" << std::endl
1516 for (
size_t i = 0; i < num_var; ++i)
1518 if (objetive[i] == 0.0)
1525 if (objetive[i] != 1.0)
1532 <<
"\\end{equation*}" << std::endl
1533 <<
"Subject to:" << std::endl
1534 <<
"\\begin{eqnarray*}" << std::endl;
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())
1539 const T *rest = it.get_curr();
1541 bool first_term =
true;
1542 for (
size_t i = 0; i < num_var; ++i)
1558 switch (type_it.get_curr())
1564 out << rest[num_var];
1566 if (not it.is_in_last())
1571 out <<
"\\end{eqnarray*}" << std::endl;
1590 ah_logic_error_if(
m ==
nullptr) <<
"prepare_linear_program() must be called before solve()";
1592 const std::string base = name ? name :
"simplex";
1593 latex_matrix(base +
"-0.tex");
1596 auto hook = [&] (
size_t p,
size_t q,
bool after)
1599 latex_matrix(base +
"-" + std::to_string(
k++) +
"-after.tex", 2,
1600 static_cast<int>(p),
static_cast<int>(q));
1602 latex_matrix(base +
"-" + std::to_string(
k) +
".tex", 2,
1603 static_cast<int>(p),
static_cast<int>(q));
1605 const State st = run(hook);
1606 latex_matrix(base +
"-" + std::to_string(
k) +
".tex");
1629 return stats.iterations;
1638 return stats.pivots;
1649 return stats.degenerate_pivots;
1658 return stats.elapsed_ms;
1679 verify_var_index(var_idx);
1682 constexpr T inf = std::numeric_limits<T>::infinity();
1688 T lo = -inf, hi = inf;
1690 for (
size_t i = 1; i <= num_rest; ++i)
1691 if (basic_vars[i - 1] ==
static_cast<int>(var_idx))
1695 lo = -std::max(
m->read(0, var_idx),
T{0});
1697 for (
size_t k = 0;
k < first_artificial(); ++
k)
1699 const T a =
m->read(
row,
k);
1700 if (
k == var_idx or std::abs(a) <= tol_coef)
1703 const T ratio = std::max(
m->read(0,
k),
T{0}) / a;
1705 hi = std::min(hi, ratio);
1707 lo = std::max(lo, ratio);
1711 const T unit = col_scale[var_idx] * obj_scale;
1746 verify_rest_index(rest_idx);
1749 constexpr T inf = std::numeric_limits<T>::infinity();
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)
1762 const T a =
m->read(i,
col);
1763 if (std::abs(a) <= tol_coef)
1766 if (is_artificial(
static_cast<size_t>(basic_vars[i - 1])))
1768 lo = std::max(lo,
T{0});
1769 hi = std::min(hi,
T{0});
1773 const T ratio = -std::max(
m->read(i, rhs),
T{0}) / a;
1775 lo = std::max(lo, ratio);
1777 hi = std::min(hi, ratio);
1781 lo /= row_scale[rest_idx];
1782 hi /= row_scale[rest_idx];
1784 if (row_sign[rest_idx] < 0)
1786 const T old_lo = lo;
1814 verify_rest_index(rest_idx);
1815 ah_logic_error_if(state != Solved) <<
"Must solve before computing shadow prices";
1819 T price =
m->read(0, unit_col[rest_idx]);
1824 price = price * row_scale[rest_idx] / obj_scale;
1826 return row_sign[rest_idx] < 0 ? -price : price;
1845 verify_var_index(var_idx);
1846 ah_logic_error_if(state != Solved) <<
"Must solve before computing reduced costs";
1848 T rc =
m->read(0, var_idx);
1855 return rc / (col_scale[var_idx] * obj_scale);
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))
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);
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)
1924 <<
"dual_solve() requires a previously solved problem";
1928 const auto start_time = std::chrono::high_resolution_clock::now();
1929 stats.iterations = 0;
1932 const size_t rhs = rhs_col();
1933 const size_t M = first_artificial();
1936 while (state == Solving)
1939 const bool bland = bland_now();
1944 int leaving_row = -1;
1945 T min_rhs = -tol_rhs;
1946 for (
size_t i = 1; i <= num_rest; ++i)
1948 const T b =
m->read(i, rhs);
1952 if (leaving_row == -1
1953 or (bland ? basic_vars[i - 1] < basic_vars[leaving_row - 1] : b < min_rhs))
1956 leaving_row =
static_cast<int>(i);
1960 if (leaving_row == -1)
1967 int entering_col = -1;
1970 for (
size_t j = 0; j < M; ++j)
1972 const T a =
m->read(leaving_row, j);
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)))
1979 entering_col =
static_cast<int>(j);
1983 else if (same_ratio(ratio, min_ratio)
and not bland
and -a > max_mag)
1985 entering_col =
static_cast<int>(j);
1990 if (entering_col == -1)
1997 stats.bland_rule_used =
true;
2000 if (
m->read(0, entering_col) <= tol_cost)
2002 ++stats.degenerate_pivots;
2009 to_pivot(
static_cast<size_t>(leaving_row),
static_cast<size_t>(entering_col));
2012 if (state == Solving)
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)
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();
2044 verify_rest_index(rest_idx);
2046 <<
"Cannot update RHS without a solved problem";
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;
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)
2057 return dual_solve();
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";
2079 <<
"Must solve before printing sensitivity analysis";
2081 std::cout <<
"=== Sensitivity Analysis ===\n\n";
2083 std::cout <<
"Objective Coefficients:\n";
2084 for (
size_t i = 0; i < num_var; ++i)
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";
2092 std::cout <<
"\nRHS Values (Shadow Prices):\n";
2093 for (
size_t i = 0; i < num_rest; ++i)
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";
2102 std::cout <<
"\nReduced Costs:\n";
2103 for (
size_t i = 0; i < num_var; ++i)
2106 bool basic = is_basic_variable(i);
2107 std::cout <<
" x_" << i <<
": " << rc
2108 << (basic ?
" (basic)" :
" (non-basic)") <<
"\n";
2174 template <
typename T>
2186 std::vector<std::vector<T>>
A;
2193 std::vector<std::vector<T>>
As;
2215 mutable std::vector<T>
pi;
2216 mutable std::vector<T>
d;
2248 for (
size_t i = 0; i <
m; ++i)
2251 for (
size_t i = 0; i <
m; ++i)
2252 col[i] = i == j -
n ?
T{1} :
T{0};
2254 for (
size_t i = 0; i <
m; ++i)
2261 void ftran(
const std::vector<T>& a, std::vector<T>&
y)
const
2263 for (
size_t i = 0; i <
m; ++i)
2266 for (
size_t j = 0; j <
m; ++j)
2275 void btran(
const std::vector<T>& c_B, std::vector<T>& pi_out)
const
2277 for (
size_t j = 0; j <
m; ++j)
2280 for (
size_t i = 0; i <
m; ++i)
2293 for (
size_t i = 0; i <
m; ++i)
2309 std::vector<T> c_B(
m);
2310 for (
size_t i = 0; i <
m; ++i)
2317 for (
size_t j = 0; j <
n +
m; ++j)
2324 entering =
static_cast<int>(j);
2349 for (
size_t i = 0; i <
m; ++i)
2354 const T ratio = std::max(
x_B[i],
T{0}) /
d[i];
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))
2359 leaving =
static_cast<int>(i);
2363 else if (tie
and (bland ?
basic[i] <
basic[leaving] :
d[i] > max_den))
2365 leaving =
static_cast<int>(i);
2371 theta = std::max(
x_B[leaving],
T{0}) /
d[leaving];
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)
2387 for (
size_t i = 0; i <
m; ++i)
2389 if (i ==
r or d_col[i] ==
T{0})
2392 const T factor = d_col[i];
2393 for (
size_t j = 0; j <
m; ++j)
2400 void pivot(
int leaving,
int entering,
const T & theta)
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];
2425 std::vector<std::vector<T>> B(
m, std::vector<T>(
m,
T{0}));
2426 for (
size_t i = 0; i <
m; ++i)
2435 for (
size_t i = 0; i <
m; ++i)
2441 size_t pivot_row =
col;
2442 T max_val = std::abs(B[
col][
col]);
2444 if (std::abs(B[
row][
col]) > max_val)
2446 max_val = std::abs(B[
row][
col]);
2451 if (pivot_row !=
col)
2453 std::swap(B[
col], B[pivot_row]);
2459 for (
size_t j = 0; j <
m; ++j)
2475 for (
size_t j = 0; j <
m; ++j)
2477 B[
row][j] -= factor * B[
col][j];
2518 pivot(leaving, entering, theta);
2529 for (
size_t r = 0;
r <
m; ++
r)
2538 for (
size_t j = 0; j <
n +
m; ++j)
2545 for (
size_t k = 0;
k <
m; ++
k)
2547 if (std::abs(entry) > largest)
2549 largest = std::abs(entry);
2550 entering =
static_cast<int>(j);
2560 pivot(
static_cast<int>(
r), entering,
T{0});
2569 if (not (magnitude >= std::numeric_limits<T>::min()) or not std::isfinite(magnitude))
2572 (void) std::frexp(magnitude, &e);
2573 return std::ldexp(
T{1}, -e);
2583 for (
size_t i = 0; i <
m; ++i)
2586 for (
size_t j = 0; j <
n; ++j)
2587 largest = std::max(largest, std::abs(
A[i][j]));
2590 for (
size_t i = 0; i <
m; ++i)
2591 for (
size_t j = 0; j <
n; ++j)
2594 for (
size_t j = 0; j <
n; ++j)
2597 largest = std::max(largest, std::abs(
c[j]) *
col_scale[j]);
2601 As.assign(
m, std::vector<T>(
n));
2604 for (
size_t i = 0; i <
m; ++i)
2606 for (
size_t j = 0; j <
n; ++j)
2610 for (
size_t j = 0; j <
n; ++j)
2630 :
m(num_constraints),
n(num_vars),
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),
2643 <<
"Number of variables and constraints must be > 0";
2693 std::swap(
m, other.m);
2694 std::swap(
n, other.n);
2704 basic.swap(other.basic);
2707 x_B.swap(other.x_B);
2711 work.swap(other.work);
2712 cost.swap(other.cost);
2713 std::swap(
eps, other.eps);
2717 std::swap(
tol_coef, other.tol_coef);
2718 std::swap(
tol_rhs, other.tol_rhs);
2719 std::swap(
tol_cost, other.tol_cost);
2721 std::swap(
state, other.state);
2722 std::swap(
stats, other.stats);
2744 for (
size_t j = 0; j <
n; ++j)
2759 <<
"Constraint or variable index out of range";
2787 for (
size_t j = 0; j <
n; ++j)
2818 auto start_time = std::chrono::high_resolution_clock::now();
2821 T max_coef =
T{0}, max_rhs =
T{0}, max_cost =
T{0};
2822 for (
size_t i = 0; i <
m; ++i)
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]));
2828 for (
size_t j = 0; j <
n; ++j)
2829 max_cost = std::max(max_cost, std::abs(
cs[j]));
2839 for (
size_t i = 0; i <
m; ++i)
2849 basic[i] =
static_cast<int>(
n + i);
2855 for (
size_t i = 0; i <
m; ++i)
2871 for (
size_t i = 0; i <
m; ++i)
2892 for (
size_t i = 0; i <
m; ++i)
2896 auto end_time = std::chrono::high_resolution_clock::now();
2898 end_time - start_time).count();
2923 for (
size_t j = 0; j <
n; ++j)
2950 const T tol =
T(10) *
eps;
2951 for (
size_t j = 0; j <
n; ++j)
2955 for (
size_t i = 0; i <
m; ++i)
2959 for (
size_t j = 0; j <
n; ++j)
2964 if (lhs >
b[i] + tol * std::max(
T{1},
size))
2973 std::cout <<
"=== Revised Simplex Statistics ===\n"
2974 <<
"Variables: " <<
n <<
", Constraints: " <<
m <<
"\n"
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.
#define ah_overflow_error_if(C)
Throws std::overflow_error if condition holds.
#define ah_logic_error_if(C)
Throws std::logic_error if condition holds.
#define ah_invalid_argument_if(C)
Throws std::invalid_argument if condition holds.
size_t size_t int32_t value
size_t size_t int32_t * out
Dynamic doubly linked list with O(1) size and bidirectional access.
Dynamic matrix with sparse storage.
Revised Simplex algorithm for linear programming.
void set_refactorization_frequency(size_t freq)
Sets refactorization frequency.
void drive_out_artificials()
bool is_artificial(const size_t j) const noexcept
void set_objective(const T *coefs)
Sets all objective coefficients.
void set_objective(size_t j, T coef)
Sets objective coefficient.
RevisedSimplex(RevisedSimplex &&other) noexcept
Takes the program of another solver, which is left as an empty program, without variables nor constra...
State iterate(const T &tol)
size_t get_num_vars() const noexcept
Gets number of variables.
std::vector< T > solution
std::vector< T > col_scale
RevisedSimplex & operator=(const RevisedSimplex &other)=default
Copies the program of another solver.
void print_stats() const
Prints statistics to stdout.
std::vector< bool > is_basic
size_t get_num_constraints() const noexcept
Gets number of constraints.
State
Solution states for the linear program.
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
void update_basis_inverse(int leaving_row, const std::vector< T > &d_col)
size_t refactor_frequency
int select_leaving_variable(int entering, T &theta)
std::vector< std::vector< T > > A
void pivot(int leaving, int entering, const T &theta)
void get_column(size_t j, std::vector< T > &col) const
static T scale_of(const T &magnitude) noexcept
void set_constraint_row(size_t i, const T *coefs, T rhs)
Adds a complete constraint.
RevisedSimplex() noexcept
State get_state() const noexcept
Gets current state.
size_t num_columns() const noexcept
RevisedSimplex(const RevisedSimplex &other)=default
Copies the program of another solver.
T get_solution(size_t j) const
Gets solution value for variable j.
void ftran(const std::vector< T > &a, std::vector< T > &y) const
bool bland_now() const noexcept
std::vector< std::vector< T > > As
void set_constraint(size_t i, size_t j, T coef)
Sets constraint coefficient.
std::vector< std::vector< T > > B_inv_explicit
T objective_value() const
Computes objective function value.
void btran(const std::vector< T > &c_B, std::vector< T > &pi_out) const
RevisedSimplex & operator=(RevisedSimplex &&other) noexcept
Exchanges this solver with another, which is left with the previous program of this one.
void swap(RevisedSimplex &other) noexcept
Exchanges in O(1) this solver and another.
State solve()
Solves the linear program.
std::vector< size_t > art_row
std::vector< T > row_scale
T compute_reduced_cost(size_t j) const
void set_rhs(size_t i, T rhs)
Sets RHS value for a constraint.
bool verify_solution() const
Verifies solution satisfies all constraints.
RevisedSimplex(size_t num_vars, size_t num_constraints)
Constructs a Revised Simplex solver.
int select_entering_variable(const T &tol)
Linear program solver using the Simplex method.
void set_optimization_type(OptimizationType type) noexcept
Sets the optimization type.
size_t rhs_col() const noexcept
SensitivityRange< T > rhs_sensitivity(size_t rest_idx) const
Computes sensitivity range for a RHS value.
void print_matrix() const
Prints the simplex tableau to stdout.
std::vector< T > col_scale
State
Solution states for the linear program.
OptimizationType get_optimization_type() const noexcept
Gets the current optimization type.
int compute_pivot_row(const size_t q) const noexcept
const SimplexStats & get_stats() const noexcept
Gets execution statistics.
T & get_restriction_coef(const size_t rest_num, size_t idx)
Gets a specific coefficient from a constraint.
void set_minimize() noexcept
Sets minimization mode.
std::vector< size_t > unit_col
std::vector< int > basic_vars
bool bland_now() const noexcept
OptimizationType opt_type
std::vector< T > pivot_col_buffer
T objetive_value() const noexcept
Computes and returns the objective function value.
std::vector< T > get_all_reduced_costs() const
Gets all reduced costs as a vector.
bool is_artificial(const size_t j) const noexcept
void print_sensitivity_analysis() const
Prints sensitivity analysis to stdout.
std::vector< T > pivot_row_buffer
std::vector< T > phase2_cost
T * get_restriction(const size_t rest_num)
Gets a pointer to a constraint array.
T * get_objetive_function() noexcept
Gets the objective function coefficients array.
void to_pivot(size_t p, size_t q)
bool verify_solution() const
Verifies that the solution satisfies all constraints.
DynDlist< ConstraintType > rest_types
void verify_rest_index(const size_t i) const
Simplex & operator=(const Simplex &)=delete
T * restriction(const size_t rest_idx) const
SensitivityRange< T > objective_sensitivity(size_t var_idx) const
Computes sensitivity range for an objective coefficient.
void put_restriction_coef(const size_t rest_num, const size_t idx, const T &coef)
Sets a specific coefficient in a constraint.
std::unique_ptr< DynMatrix< T > > m
size_t get_pivot_count() const noexcept
Gets the number of pivot operations.
T * put_restriction(const T *coefs=nullptr, ConstraintType type=ConstraintType::LE)
Adds a constraint to the linear program.
void prepare_linear_program()
Prepares the linear program for solving.
bool same_ratio(const T &a, const T &b) const noexcept
void latex_linear_program(const std::string &name) const
Exports the linear program to a LaTeX file.
static T scale_of(const T &magnitude) noexcept
T shadow_price(size_t rest_idx) const
Gets the shadow price (dual value) for a constraint.
State update_rhs_and_reoptimize(size_t rest_idx, T new_rhs)
Updates RHS value and re-optimizes using dual simplex.
bool is_basic_variable(size_t var_idx) const
Checks if a variable is basic in the optimal solution.
void print_stats() const
Prints a summary of statistics to stdout.
void set_maximize() noexcept
Sets maximization mode.
size_t get_iteration_count() const noexcept
Gets the number of iterations performed.
size_t get_num_restrictions() const noexcept
Gets the number of constraints.
const T & get_solution(size_t i) const noexcept
Gets the solution value for a specific variable.
void swap(Simplex &other) noexcept
Exchanges in O(1) this solver and another.
Simplex(const Simplex &)=delete
DynDlist< T * > rest_list
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.
void put_objetive_function_coef(size_t i, const T &coef)
Sets a coefficient in the objective function.
void set_pivot_rule(PivotRule rule) noexcept
Sets the pivot selection rule.
std::vector< T > tie_cost
void verify_var_index(const size_t i) const
T * put_ge_restriction(const T *coefs)
Adds a ≥ constraint.
T reduced_cost(size_t var_idx) const
Gets the reduced cost for a variable.
void load_solution() noexcept
Loads the solution values into the solution array.
const T * get_objetive_function() const noexcept
Gets the objective function coefficients array (const).
Simplex & operator=(Simplex &&other) noexcept
Exchanges this solver with another, which is left with the previous program of this one.
static std::string format_entry(const T &value, const int d)
Simplex(Simplex &&other) noexcept
Takes the program of another solver, which is left as an empty program, without variables nor restric...
std::vector< int > row_sign
State dual_solve()
Performs dual simplex iteration.
void set_epsilon(T epsilon) noexcept
Sets the floating-point comparison tolerance.
std::unique_ptr< T[]> solution
std::vector< T > row_scale
std::unique_ptr< T[]> objetive
void put_objetive_function(const DynArray< T > &coefs)
Sets all objective function coefficients from a DynArray.
size_t get_num_vars() const noexcept
Gets the number of decision variables.
T * create_restriction(ConstraintType type=ConstraintType::LE)
State get_state() const noexcept
Gets the current state of the solver.
State iterate(const T &cost_tol, Hook &hook)
size_t get_degenerate_pivot_count() const noexcept
Gets the number of degenerate pivots.
T * put_restriction(const DynArray< T > &coefs, ConstraintType type=ConstraintType::LE)
Adds a constraint from a DynArray.
PivotRule
Pivot selection rule.
T * put_eq_restriction(const T *coefs)
Adds an = constraint.
State latex_solve(const char *name=nullptr)
Solves with LaTeX output at each iteration.
void drive_out_artificials(Hook &hook)
void enable_bland_rule() noexcept
Enables Bland's anti-cycling rule.
Simplex(const size_t n, OptimizationType type=OptimizationType::Maximize)
Constructs a Simplex solver for n variables.
State solve()
Solves the linear program.
void put_objetive_function(const T coefs[])
Sets all objective function coefficients from a C array.
std::vector< T > get_all_shadow_prices() const
Gets all shadow prices as a vector.
const T & get_objetive_function_coef(size_t i) const
Gets a coefficient from the objective function.
int compute_pivot_col(const T &tol) const noexcept
static T * allocate(const size_t n, const size_t spare=0)
size_t first_artificial() const noexcept
double get_elapsed_time_ms() const noexcept
Gets the elapsed solving time.
__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)
Main namespace for Aleph-w library functions.
T & swap(T &t1, T &t2)
Generic swap using object's swap method.
size_t size(Node *root) noexcept
See compute_cardinality_rec(Node * root).
std::decay_t< typename HeadC::Item_Type > T
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.
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.
OptimizationType
Optimization direction for linear programming.
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.
Sensitivity analysis result for a coefficient.
T lower_bound
Minimum value before basis change.
T upper_bound
Maximum value before basis change.
bool is_unbounded_below() const noexcept
T current_value
Current coefficient value.
bool is_unbounded_above() const noexcept
Execution statistics for the Simplex algorithm.
bool bland_rule_used
Whether Bland's rule was activated.
double elapsed_ms
Elapsed time in milliseconds.
size_t iterations
Total simplex iterations.
size_t pivots
Total pivot operations.
size_t degenerate_pivots
Pivots with zero improvement.
FooMap m(5, fst_unit_pair_hash, snd_unit_pair_hash)
Dynamic doubly linked list implementation.
Dynamic matrix with lazy allocation.