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