-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcli.cpp
More file actions
259 lines (228 loc) · 10.8 KB
/
Copy pathcli.cpp
File metadata and controls
259 lines (228 loc) · 10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
/**
* @author popmonkey+jres@gmail.com
* @file cmd/solver/cli.cpp
* @brief An example CLI client for the JRES Solver Library.
*
* This application is an example `JresSolver` library client.
*/
#include <iostream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <sstream>
#include <iomanip>
#include "cxxopts.hpp"
#include "nlohmann/json.hpp"
#include "jres_solver/jres_solver.hpp"
#include "version.h"
using json = nlohmann::json;
/**
* @brief Main entry point for the CLI client.
*/
int main(int argc, char **argv)
{
// --- Parse Command-Line Arguments ---
cxxopts::Options options("solver", "JRES endurance race solver.");
options.add_options()
("i,input", "Path to the race data .json file. Reads from stdin if not provided.", cxxopts::value<std::string>())
("o,output", "Optional. Path to save the schedule as a JSON file.", cxxopts::value<std::string>())
("t,time-limit", "Maximum time in seconds to let the solver run.", cxxopts::value<int>()->default_value("5"))
("q,quiet", "Suppress INFO logs and final schedule print-out.", cxxopts::value<bool>()->default_value("false"))
("s,spotter-mode", "Method for scheduling spotters (none, integrated, sequential).", cxxopts::value<std::string>()->default_value("none"))
("allow-no-spotter", "Allow stints to have no spotter assigned.", cxxopts::value<bool>()->default_value("false"))
("g,optimality-gap", "Solver stops when the gap to optimal is less than this (e.g., 0.2 for 20%).", cxxopts::value<double>()->default_value("0.2"))
("d,diagnose", "Run diagnostics to explain why a schedule is infeasible.", cxxopts::value<bool>()->default_value("false"))
("v,version", "Print version information and exit.")
("h,help", "Print usage.");
auto result = options.parse(argc, argv);
if (result.count("version"))
{
std::cout << "JRES Solver Version: " << JRES_VERSION_STRING << std::endl;
return 0;
}
if (result.count("help"))
{
std::cout << options.help() << std::endl;
return 0;
}
bool quiet = result["quiet"].as<bool>();
bool runDiagnostics = result["diagnose"].as<bool>();
if (!quiet) {
std::cout << "[App] JRES Solver " << JRES_VERSION_STRING << std::endl;
}
// Load Input JSON Data into a std::string
std::string raceDataJsonString;
try
{
if (result.count("input"))
{
std::string inputPath = result["input"].as<std::string>();
if (!quiet)
std::cout << "[App] Loading data from file: " << inputPath << std::endl;
std::ifstream f(inputPath);
if (!f.is_open())
{
throw std::runtime_error("Could not open input file: " + inputPath);
}
std::stringstream buffer;
buffer << f.rdbuf();
raceDataJsonString = buffer.str();
}
else
{
if (!quiet)
std::cout << "[App] Loading data from stdin..." << std::endl;
std::stringstream buffer;
buffer << std::cin.rdbuf();
raceDataJsonString = buffer.str();
}
}
catch (const std::exception &e)
{
std::cerr << "[App] Error: " << e.what() << std::endl;
return 1;
}
// Build Solver Options Struct
JresSolverOptions solverOptions;
solverOptions.timeLimit = result["time-limit"].as<int>();
// --- Translate spotter-mode string to enum ---
std::string spotterModeStr = result["spotter-mode"].as<std::string>();
if (spotterModeStr == "none") {
solverOptions.spotterMode = JRES_SPOTTER_MODE_NONE;
} else if (spotterModeStr == "integrated") {
solverOptions.spotterMode = JRES_SPOTTER_MODE_INTEGRATED;
} else if (spotterModeStr == "sequential") {
solverOptions.spotterMode = JRES_SPOTTER_MODE_SEQUENTIAL;
} else {
std::cerr << "[App] Error: Invalid spotter mode '" << spotterModeStr << "'. Must be 'none', 'integrated', or 'sequential'." << std::endl;
return 1;
}
// --- End translation ---
solverOptions.allowNoSpotter = result["allow-no-spotter"].as<bool>();
solverOptions.optimalityGap = result["optimality-gap"].as<double>();
// Call the Solver Library
char* resultJsonCStr = nullptr;
int resultCode = 0;
if (runDiagnostics) {
if (!quiet) std::cout << "[App] Running in DIAGNOSTIC mode..." << std::endl;
resultCode = diagnose_race_schedule(raceDataJsonString.c_str(), solverOptions, &resultJsonCStr);
} else {
resultCode = solve_race_schedule(raceDataJsonString.c_str(), solverOptions, &resultJsonCStr);
}
// Process Results
if (resultJsonCStr == nullptr) {
std::cerr << "[App] Critical Error: Solver returned no data." << std::endl;
return 1;
}
std::string resultJsonString(resultJsonCStr);
std::string outputPath = result.count("output") ? result["output"].as<std::string>() : "";
try {
json resultJson = json::parse(resultJsonString);
if (runDiagnostics) {
// --- Diagnostic Output Handling ---
if (resultCode == 0) {
// Diagnosis ran successfully (even if constraints were violated)
if (!quiet) {
std::cout << "\n--- ⚠️ Infeasibility Diagnosis ---" << std::endl;
if (resultJson.contains("diagnosis")) {
auto issues = resultJson["diagnosis"];
if (issues.empty()) {
std::cout << "The diagnostic solver found a solution, but no specific constraints were identified as the cause. This implies the schedule might actually be feasible in a relaxed context." << std::endl;
} else {
std::cout << "The solver identified the following blockers:" << std::endl;
for (const auto& issue : issues) {
std::cout << " - " << issue.get<std::string>() << std::endl;
}
}
} else {
std::cout << "Diagnosis completed but no 'diagnosis' key found in result." << std::endl;
}
}
} else {
// Engine failure
std::cerr << "[Solver] Diagnostic Engine Error: " << resultJson.value("error", "Unknown error") << std::endl;
}
}
else {
// --- Standard Schedule Output Handling ---
if (!quiet) {
// Print Metadata / Settings
if (resultJson.contains("metadata")) {
std::cout << "\n--- 🔧 Solver Settings ---" << std::endl;
json meta = resultJson["metadata"];
std::cout << "Time Limit: " << meta.value("timeLimit", 0) << "s | "
<< "Gap: " << meta.value("optimalityGap", 0.0) << " | "
<< "Spotter: " << meta.value("spotterMode", "unknown") << std::endl;
}
// Print Complexity (regardless of success/failure)
if (resultJson.contains("complexity")) {
std::cout << "\n--- 🧠 Complexity ---" << std::endl;
json c = resultJson["complexity"];
std::cout << "Rows: " << c.value("modelRows", 0) << " | "
<< "Cols: " << c.value("modelColumns", 0) << " | "
<< "Nodes: " << c.value("searchNodes", 0) << std::endl;
std::cout << "Big-M Rest Constraints: " << c.value("numRestConstraints", 0) << std::endl;
if (!c["finalGap"].is_null()) {
std::cout << "Final Gap: " << c.value("finalGap", 0.0) << std::endl;
}
}
// Print Timing (regardless of success/failure)
if (resultJson.contains("timing")) {
std::cout << "\n--- ⏱️ Timing Performance ---" << std::endl;
json t = resultJson["timing"];
std::cout << std::fixed << std::setprecision(2);
std::cout << "Setup/Model Build : " << std::setw(8) << t.value("setupMs", 0.0) << " ms" << std::endl;
std::cout << "Driver Solve : " << std::setw(8) << t.value("driverSolveMs", 0.0) << " ms" << std::endl;
if (t.contains("spotterSolveMs")) {
std::cout << "Spotter Solve : " << std::setw(8) << t.value("spotterSolveMs", 0.0) << " ms" << std::endl;
}
std::cout << "Total Wall Time : " << std::setw(8) << t.value("totalSeconds", 0.0) << " s" << std::endl;
}
}
// Check if the solve was successful
if (resultCode == 0) {
// Success
if (!quiet) {
// Print the schedule
std::cout << "\n--- 🏁 Race Schedule ---" << std::endl;
bool hasSpotters = (solverOptions.spotterMode != JRES_SPOTTER_MODE_NONE);
if (resultJson.contains("schedule")) {
for (const auto& entry : resultJson["schedule"]) {
std::stringstream ss;
ss << "Stint " << std::setw(3) << entry["stint"].get<int>()
<< ": Driver: " << std::setw(15) << std::left << entry["driver"].get<std::string>();
if (hasSpotters && entry.contains("spotter")) {
ss << " | Spotter: " << std::setw(15) << std::left << entry["spotter"].get<std::string>();
}
std::cout << ss.str() << std::endl;
}
}
}
} else {
// Failure
std::cerr << "[Solver] Error: " << resultJson.value("error", "Unknown error") << std::endl;
if (!quiet) {
std::cout << "\nTip: Try running with --diagnose to find out why." << std::endl;
}
}
}
// Save to file (Common for both modes)
if (!outputPath.empty()) {
std::ofstream o(outputPath);
o << resultJsonString << std::endl;
if (!quiet) {
std::cout << "\n[App] Result saved to " << outputPath << std::endl;
}
}
} catch (const std::exception& e) {
std::cerr << "[App] Error processing solver result: " << e.what() << std::endl;
std::cerr << "Raw output: " << resultJsonString << std::endl;
}
// Clean up
free_solver_result(resultJsonCStr);
if (!quiet)
{
std::cout << "[App] Solver finished." << std::endl;
}
return (resultCode == 0) ? 0 : 1;
}