Sleipnir C++ API
Loading...
Searching...
No Matches
print_diagnostics.hpp
1// Copyright (c) Sleipnir contributors
2
3#pragma once
4
5#include <stdint.h>
6
7#include <algorithm>
8#include <array>
9#include <chrono>
10#include <cmath>
11#include <ranges>
12#include <string>
13#include <utility>
14
15#include <Eigen/Core>
16#include <gch/small_vector.hpp>
17
18#include "sleipnir/util/print.hpp"
19#include "sleipnir/util/profiler.hpp"
20
21namespace slp {
22
24enum class IterationType : uint8_t {
26 NORMAL,
28 SECOND_ORDER_CORRECTION,
30 FEASIBILITY_RESTORATION
31};
32
35template <typename Rep, typename Period = std::ratio<1>>
36constexpr double to_ms(const std::chrono::duration<Rep, Period>& duration) {
37 using std::chrono::duration_cast;
38 using std::chrono::microseconds;
39 return duration_cast<microseconds>(duration).count() / 1e3;
40}
41
46template <typename Scalar>
47std::string power_of_10(Scalar value) {
48 if (value == Scalar(0)) {
49 return " 0";
50 } else {
51 using std::log10;
52 int exponent = static_cast<int>(log10(value));
53
54 if (exponent == 0) {
55 return " 1";
56 } else if (exponent == 1) {
57 return "10";
58 } else {
59 // Gather exponent digits
60 int n = std::abs(exponent);
61 gch::small_vector<int> digits;
62 do {
63 digits.emplace_back(n % 10);
64 n /= 10;
65 } while (n > 0);
66
67 std::string output = "10";
68
69 // Append exponent
70 if (exponent < 0) {
71 output += "⁻";
72 }
73 constexpr std::array strs{"⁰", "¹", "²", "³", "⁴",
74 "⁵", "⁶", "⁷", "⁸", "⁹"};
75 for (const auto& digit : digits | std::views::reverse) {
76 output += strs[digit];
77 }
78
79 return output;
80 }
81 }
82}
83
84#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
90template <typename Scalar>
91void print_too_few_dofs_error(
92 const Eigen::Vector<Scalar, Eigen::Dynamic>& c_e) {
93 slp::println("The problem has too few degrees of freedom.");
94 slp::println("Violated constraints (cₑ(x) = 0) in order of declaration:");
95 for (int row = 0; row < c_e.rows(); ++row) {
96 if (c_e[row] < Scalar(0)) {
97 slp::println(" {}/{}: {} = 0", row + 1, c_e.rows(), c_e[row]);
98 }
99 }
100}
101#else
102#define print_too_few_dofs_error(...)
103#endif
104
105#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
111template <typename Scalar>
112void print_c_e_local_infeasibility_error(
113 const Eigen::Vector<Scalar, Eigen::Dynamic>& c_e) {
114 slp::println(
115 "The problem is locally infeasible due to violated equality "
116 "constraints.");
117 slp::println("Violated constraints (cₑ(x) = 0) in order of declaration:");
118 for (int row = 0; row < c_e.rows(); ++row) {
119 if (c_e[row] < Scalar(0)) {
120 slp::println(" {}/{}: {} = 0", row + 1, c_e.rows(), c_e[row]);
121 }
122 }
123}
124#else
125#define print_c_e_local_infeasibility_error(...)
126#endif
127
128#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
134template <typename Scalar>
135void print_c_i_local_infeasibility_error(
136 const Eigen::Vector<Scalar, Eigen::Dynamic>& c_i) {
137 slp::println(
138 "The problem is locally infeasible due to violated inequality "
139 "constraints.");
140 slp::println("Violated constraints (cᵢ(x) ≥ 0) in order of declaration:");
141 for (int row = 0; row < c_i.rows(); ++row) {
142 if (c_i[row] < Scalar(0)) {
143 slp::println(" {}/{}: {} ≥ 0", row + 1, c_i.rows(), c_i[row]);
144 }
145 }
146}
147#else
148#define print_c_i_local_infeasibility_error(...)
149#endif
150
151#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
152inline void print_bound_constraint_global_infeasibility_error(
153 const std::span<const std::pair<Eigen::Index, Eigen::Index>>
154 conflicting_lower_upper_bound_indices) {
155 slp::println(
156 "The problem is globally infeasible due to conflicting bound "
157 "constraints:");
158 for (const auto& [lower_bound_idx, upper_bound_idx] :
159 conflicting_lower_upper_bound_indices) {
160 slp::println(
161 " Inequality constraint {} gives a lower bound that is greater than "
162 "the upper bound given by inequality constraint {}",
163 lower_bound_idx, upper_bound_idx);
164 }
165}
166#else
167#define print_bound_constraint_global_infeasibility_error(...)
168#endif
169
170#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
191template <typename Scalar, typename Rep, typename Period = std::ratio<1>>
192void print_iteration_diagnostics(int iterations, IterationType type,
193 const std::chrono::duration<Rep, Period>& time,
194 Scalar error, Scalar cost,
195 Scalar infeasibility, Scalar complementarity,
196 Scalar μ, Scalar δ, Scalar γ,
197 Scalar full_primal_step_inf_norm,
198 Scalar full_dual_step_inf_norm,
199 Scalar primal_α, Scalar primal_α_max,
200 Scalar α_reduction_factor, Scalar dual_α) {
201 if (iterations % 20 == 0) {
202 if (iterations == 0) {
203 slp::println("┏{:━^119}┓", "");
204 } else {
205 slp::println("┢{:━^119}┪", "");
206 }
207 slp::println(
208 "┃{:^4} {:^9} {:^10} {:^11} {:^10} {:^8} {:^8} {:^5} {:^5} {:^8} "
209 "{:^8} {:^8} {:^8} {:^2}┃",
210 "iter", "duration", "error", "cost", "infeas.", "complem.", "μ", "δ",
211 "γ", "|p_pr|", "|p_du|", "α_pr", "α_du", "↩");
212 slp::println("┡{:━^119}┩", "");
213 }
214
215 // For the number of backtracks, we want x such that:
216 //
217 // αᵐᵃˣrˣ = α
218 //
219 // where r ∈ (0, 1) is the reduction factor.
220 //
221 // rˣ = α/αᵐᵃˣ
222 // ln(rˣ) = ln(α/αᵐᵃˣ)
223 // x ln(r) = ln(α/αᵐᵃˣ)
224 // x = ln(α/αᵐᵃˣ)/ln(r)
225 using std::log;
226 int backtracks =
227 static_cast<int>(log(primal_α / primal_α_max) / log(α_reduction_factor));
228
229 constexpr std::array ITERATION_TYPES{" ", "s", "r"};
230 slp::println(
231 "│{:4} {:1} {:9.3f} {:.4e} {:11.4e} {:.4e} {:.2e} {:.2e} {:<5} {:<5} "
232 "{:.2e} {:.2e} {:.2e} {:.2e} {:2d}│",
233 iterations, ITERATION_TYPES[std::to_underlying(type)], to_ms(time), error,
234 cost, infeasibility, complementarity, μ, power_of_10(δ), power_of_10(γ),
235 full_primal_step_inf_norm, full_dual_step_inf_norm, primal_α, dual_α,
236 backtracks);
237}
238#else
239#define print_iteration_diagnostics(...)
240#endif
241
242#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
244inline void print_bottom_iteration_diagnostics() {
245 slp::println("└{:─^119}┘", "");
246}
247#else
248#define print_bottom_iteration_diagnostics(...)
249#endif
250
255template <int Width>
256 requires(Width > 0)
257std::string histogram(double value) {
258 value = std::clamp(value, 0.0, 1.0);
259
260 double ipart;
261 int fpart = static_cast<int>(std::modf(value * Width, &ipart) * 8);
262
263 constexpr std::array strs{" ", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█"};
264 std::string hist;
265
266 int index = 0;
267 while (index < ipart) {
268 hist += strs[8];
269 ++index;
270 }
271 if (fpart > 0) {
272 hist += strs[fpart];
273 ++index;
274 }
275 while (index < Width) {
276 hist += strs[0];
277 ++index;
278 }
279
280 return hist;
281}
282
283#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
287inline void print_solver_diagnostics(
288 const gch::small_vector<SolveProfiler>& solve_profilers) {
289 auto solve_duration = to_ms(solve_profilers[0].total_duration());
290
291 slp::println("┏{:━^66}┓", "");
292 slp::println("┃{:^21} {:^18} {:^10} {:^9} {:^4}┃", "time trace", "percentage",
293 "total", "each", "runs");
294 slp::println("┡{:━^66}┩", "");
295
296 for (auto& profiler : solve_profilers) {
297 double norm = solve_duration == 0.0
298 ? (&profiler == &solve_profilers[0] ? 1.0 : 0.0)
299 : to_ms(profiler.total_duration()) / solve_duration;
300 slp::println("│{:<21} {:>6.2f}%▕{}▏ {:>10.3f} {:>9.3f} {:>4}│",
301 profiler.name(), norm * 100.0, histogram<9>(norm),
302 to_ms(profiler.total_duration()),
303 to_ms(profiler.average_duration()), profiler.num_solves());
304 }
305
306 slp::println("└{:─^66}┘", "");
307}
308#else
309#define print_solver_diagnostics(...)
310#endif
311
312#ifndef SLEIPNIR_DISABLE_DIAGNOSTICS
316inline void print_setup_diagnostics(
317 const gch::small_vector<SetupProfiler>& setup_profilers) {
318 auto setup_duration = to_ms(setup_profilers[0].duration());
319
320 // Print link to diagnostic output description
321 slp::println(
322 "See https://sleipnirgroup.github.io/Sleipnir/md_usage.html#output for "
323 "diagnostic output description.\n");
324
325 // Print heading
326 slp::println("┏{:━^50}┓", "");
327 slp::println("┃{:^21} {:^18} {:^9}┃", "time trace", "percentage", "duration");
328 slp::println("┡{:━^50}┩", "");
329
330 // Print setup profilers
331 for (auto& profiler : setup_profilers) {
332 double norm = setup_duration == 0.0
333 ? (&profiler == &setup_profilers[0] ? 1.0 : 0.0)
334 : to_ms(profiler.duration()) / setup_duration;
335 slp::println("│{:<21} {:>6.2f}%▕{}▏ {:>9.3f}│", profiler.name(),
336 norm * 100.0, histogram<9>(norm), to_ms(profiler.duration()));
337 }
338
339 slp::println("└{:─^50}┘", "");
340}
341#else
342#define print_setup_diagnostics(...)
343#endif
344
345} // namespace slp