-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsolver_diagnostics.cpp
More file actions
312 lines (272 loc) · 13 KB
/
solver_diagnostics.cpp
File metadata and controls
312 lines (272 loc) · 13 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
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
#include "solver_diagnostics.hpp"
#include "capacity_analyzer.hpp"
#include "../utils/date_utils.hpp"
#include <sstream>
#include <iomanip>
#include <set>
#include <chrono>
#include <algorithm>
#include <cmath>
#include <tuple>
namespace jres::analysis {
std::string explain_assignment_failure(
int stintIndex,
const std::string& violationDriver,
const jres::internal::SolverInput& input,
const std::vector<jres::internal::TeamMember>& driverPool,
const std::map<std::pair<std::string, int>, int>& driverWorkVars,
const std::vector<double>& colValues)
{
using namespace jres::internal;
std::ostringstream ss;
// Time points for the target stint
auto tStart = TimeHelpers::stringToTimePoint(input.stints[stintIndex].startTime);
auto tEnd = TimeHelpers::stringToTimePoint(input.stints[stintIndex].endTime);
// Identify which drivers are assigned to which stints in the CURRENT solution
std::map<std::string, std::set<int>> driverAssignments;
for (size_t s = 0; s < input.stints.size(); ++s) {
for (const auto& p : driverPool) {
if (driverWorkVars.count({p.name, (int)s})) {
int idx = driverWorkVars.at({p.name, (int)s});
if (idx < (int)colValues.size() && colValues[idx] > 0.5) {
driverAssignments[p.name].insert((int)s);
}
}
}
}
// Helper: Get stint duration in hours
auto getDuration = [&](int sIdx) {
auto s = TimeHelpers::stringToTimePoint(input.stints[sIdx].startTime);
auto e = TimeHelpers::stringToTimePoint(input.stints[sIdx].endTime);
return std::chrono::duration<double, std::ratio<3600>>(e - s).count();
};
ss << " Alternatives Analysis:";
for (const auto& candidate : driverPool) {
if (candidate.name == violationDriver) continue;
ss << "\n - " << candidate.name << ": ";
std::vector<std::string> reasons;
// Check Availability
bool isUnavailable = false;
auto it = input.availability.find(candidate.name);
if (it != input.availability.end()) {
auto cursor = tStart;
while (cursor < tEnd) {
std::string key = TimeHelpers::timePointToKey(cursor);
if (it->second.count(key) && it->second.at(key) == Availability::Unavailable) {
isUnavailable = true;
break;
}
cursor += std::chrono::hours(1);
}
}
if (isUnavailable) {
reasons.push_back("Also Unavailable");
}
// Check Consecutive Stints
int consecutiveCount = 1;
for (int k = stintIndex - 1; k >= 0; --k) {
if (driverAssignments[candidate.name].count(k)) consecutiveCount++;
else break;
}
for (size_t k = stintIndex + 1; k < input.stints.size(); ++k) {
if (driverAssignments[candidate.name].count((int)k)) consecutiveCount++;
else break;
}
if (consecutiveCount > input.consecutiveStints) {
reasons.push_back("Max Consecutive Limit (" + std::to_string(consecutiveCount) + "/" + std::to_string(input.consecutiveStints) + ")");
}
// Check Minimum Rest
if (input.minimumRestHours > 0) {
double minRestSec = input.minimumRestHours * 3600.0;
for (int assignedS : driverAssignments[candidate.name]) {
auto s1_start = TimeHelpers::stringToTimePoint(input.stints[stintIndex].startTime);
auto s1_end = TimeHelpers::stringToTimePoint(input.stints[stintIndex].endTime);
auto s2_start = TimeHelpers::stringToTimePoint(input.stints[assignedS].startTime);
auto s2_end = TimeHelpers::stringToTimePoint(input.stints[assignedS].endTime);
double gap = 0.0;
if (s1_end <= s2_start) gap = std::chrono::duration<double>(s2_start - s1_end).count();
else if (s2_end <= s1_start) gap = std::chrono::duration<double>(s1_start - s2_end).count();
else gap = -1.0;
if (gap < minRestSec - 1.0) {
double needed = (minRestSec - gap) / 3600.0;
std::ostringstream rss;
rss << std::fixed << std::setprecision(1) << " Needs " << needed << "h more rest";
reasons.push_back(rss.str());
break;
}
}
}
// Check Max Busy Time
if (input.maximumBusyHours > 0) {
double busyDuration = getDuration(stintIndex);
for (int k = stintIndex - 1; k >= 0; --k) {
if (driverAssignments[candidate.name].count(k)) busyDuration += getDuration(k);
else break;
}
for (size_t k = stintIndex + 1; k < input.stints.size(); ++k) {
if (driverAssignments[candidate.name].count((int)k)) busyDuration += getDuration(k);
else break;
}
if (busyDuration > input.maximumBusyHours) {
reasons.push_back("Max Busy Time Exceeded (" + std::to_string(busyDuration) + "h > " + std::to_string(input.maximumBusyHours) + "h)");
}
}
if (reasons.empty()) {
ss << "Available (Unknown constraint or softer optimization preference)";
} else {
for (size_t i=0; i<reasons.size(); ++i) {
if (i > 0) ss << ", ";
ss << reasons[i];
}
}
}
return ss.str();
}
/**
* @brief Helper to format a list of stint indices into a human-readable string using IDs.
*/
std::string formatStintList(const std::vector<int>& indices, const jres::internal::SolverInput& input) {
if (indices.empty()) return "";
std::vector<int> sorted = indices;
std::sort(sorted.begin(), sorted.end());
std::ostringstream ss;
for (size_t i = 0; i < sorted.size(); ++i) {
int startIdx = sorted[i];
int endIdx = startIdx;
while (i + 1 < sorted.size() && sorted[i + 1] == endIdx + 1) {
endIdx = sorted[++i];
}
if (ss.tellp() > 0) ss << ", ";
if (startIdx == endIdx) ss << input.stints[startIdx].id;
else ss << input.stints[startIdx].id << "-" << input.stints[endIdx].id;
}
return ss.str();
}
std::vector<std::string> formatHumanDiagnostic(
const std::map<int, jres::internal::SlackInfo>& slackInfo,
const std::set<int>& unavailableVars,
const std::map<std::pair<std::string, int>, int>& driverWorkVars,
const std::map<std::pair<std::string, int>, int>& spotterWorkVars,
const std::vector<double>& colValues,
const jres::internal::SolverInput& input,
const std::vector<jres::internal::TeamMember>& driverPool,
const std::vector<jres::internal::TeamMember>& spotterPool)
{
using namespace jres::internal;
std::vector<std::string> report;
// --- Roster Health Check (Drivers) ---
if (!driverPool.empty()) {
auto cap = CapacityAnalyzer::calculate_max_potential_capacity(driverPool, input);
if (cap.totalCapacity < (int)input.stints.size()) {
std::ostringstream ss;
ss << "Driver Roster Understaffed: You have " << cap.totalCapacity
<< " stints of coverage for a " << input.stints.size() << " stint race.";
report.push_back(ss.str());
}
}
// --- Collect Violations per Stint ---
struct ViolationKey {
int priority;
std::string reason;
std::string member;
bool operator<(const ViolationKey& other) const {
return std::tie(priority, reason, member) < std::tie(other.priority, other.reason, other.member);
}
};
std::map<ViolationKey, std::vector<int>> groupedViolations;
std::vector<std::string> globalViolations;
// Build reverse map for variable index -> (Member, Stint, Role)
std::map<int, std::tuple<std::string, int, std::string>> varToInfo;
for(const auto& [key, varIdx] : driverWorkVars) {
varToInfo[varIdx] = std::make_tuple(key.first, key.second, "Driver");
}
for(const auto& [key, varIdx] : spotterWorkVars) {
varToInfo[varIdx] = std::make_tuple(key.first, key.second, "Spotter");
}
// Check Unavailable (Priority 0)
for (int varIdx : unavailableVars) {
if (varIdx < (int)colValues.size() && colValues[varIdx] > 0.5) {
if (varToInfo.count(varIdx)) {
auto [member, stintIdx, role] = varToInfo[varIdx];
std::string reason = std::string("No one could ") + (role == "Spotter" ? "spot" : "drive") +
" without being Unavailable (" + member + ")";
groupedViolations[{0, reason, member}].push_back(stintIdx);
}
}
}
// Check Slack (Rest, Busy, etc)
for (const auto& [varIdx, info] : slackInfo) {
if (varIdx < (int)colValues.size() && colValues[varIdx] > 0.001) {
int priority = 3;
if (info.type.find("Busy") != std::string::npos) priority = 1;
else if (info.type.find("Rest") != std::string::npos) priority = 2;
else if (info.type.find("Fair Share") != std::string::npos) priority = 2;
if (info.stintIndex >= 0) {
std::string reason;
if (priority == 1) reason = "Max Busy Time exceeded (" + info.memberName + ")";
else if (priority == 2) {
if (info.type.find("Fair Share") != std::string::npos) reason = "Fair Share Rules violated (" + info.memberName + ")";
else reason = "Rest Rules violated (" + info.memberName + ")";
}
else reason = info.type + " (" + info.memberName + ")";
groupedViolations[{priority, reason, info.memberName}].push_back(info.stintIndex);
} else {
// Try to attribute global violation to stints
bool assignedAny = false;
for(const auto& [vIdx, tupleInfo] : varToInfo) {
auto [memName, stintIdx, role] = tupleInfo;
if (memName == info.memberName && colValues[vIdx] > 0.5) {
std::string reason;
if (priority == 1) reason = "Max Busy Time exceeded (" + memName + ")";
else if (priority == 2) {
if (info.type.find("Fair Share") != std::string::npos) reason = "Fair Share Rules violated (" + memName + ")";
else reason = "Rest Rules violated (" + memName + ")";
}
else reason = info.type + " (" + memName + ")";
groupedViolations[{priority, reason, memName}].push_back(stintIdx);
assignedAny = true;
}
}
if (!assignedAny) {
std::string reason = info.type;
if (priority == 2) {
if (info.type.find("Fair Share") != std::string::npos)
reason = "Fair Share Rules violated";
else
reason = "Rest Rules violated";
}
globalViolations.push_back(reason + " (" + info.memberName + ")");
}
}
}
}
// --- Sort & Format Grouped Violations ---
std::vector<ViolationKey> sortedKeys;
for(const auto& [key, _] : groupedViolations) sortedKeys.push_back(key);
std::sort(sortedKeys.begin(), sortedKeys.end());
for (const auto& key : sortedKeys) {
const auto& stints = groupedViolations[key];
std::string stintStr = formatStintList(stints, input);
std::ostringstream ss;
if (stints.size() == 1) ss << "Stint " << stintStr << ": " << key.reason;
else ss << "Stints " << stintStr << ": " << key.reason;
report.push_back(ss.str());
// Actionable Advice
if (key.priority == 0) {
report.push_back(" -> Advice: Mark " + key.member + " as Available during this window.");
} else if (key.priority == 1) {
report.push_back(" -> Advice: Increase 'Maximum Busy Hours' (currently " + std::to_string(input.maximumBusyHours) + "h) or add more participants.");
} else if (key.priority == 2) {
if (key.reason.find("Fair Share") != std::string::npos)
report.push_back(" -> Advice: Ensure " + key.member + " is Available for more stints to meet the minimum driving time.");
else
report.push_back(" -> Advice: Reduce 'Minimum Rest Hours' (currently " + std::to_string(input.minimumRestHours) + "h) or increase availability of other participants to cover the gap.");
}
}
// Append Global Violations (Unattributed)
for (const auto& g : globalViolations) {
report.push_back("Global Violation: " + g);
}
return report;
}
} // namespace jres::analysis