-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathsolve.rs
More file actions
273 lines (250 loc) · 9.57 KB
/
solve.rs
File metadata and controls
273 lines (250 loc) · 9.57 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
use crate::dispatch::{load_problem, read_input, BundleReplay, ProblemJson, ReductionBundle};
use crate::output::OutputConfig;
use anyhow::{Context, Result};
use std::path::Path;
use std::time::Duration;
/// Input can be either a problem JSON or a reduction bundle JSON.
enum SolveInput {
/// A plain problem file (from `pred create`).
Problem(ProblemJson),
/// A reduction bundle (from `pred reduce`) with source, target, and path.
Bundle(ReductionBundle),
}
fn parse_input(path: &Path) -> Result<SolveInput> {
let content = read_input(path)?;
let json: serde_json::Value = serde_json::from_str(&content).context("Failed to parse JSON")?;
// Reduction bundles have "source", "target", and "path" fields
if json.get("source").is_some() && json.get("target").is_some() && json.get("path").is_some() {
let bundle: ReductionBundle =
serde_json::from_value(json).context("Failed to parse reduction bundle")?;
Ok(SolveInput::Bundle(bundle))
} else {
let problem: ProblemJson =
serde_json::from_value(json).context("Failed to parse problem JSON")?;
Ok(SolveInput::Problem(problem))
}
}
fn solve_result_text(problem: &str, solver: &str, result: &crate::dispatch::SolveResult) -> String {
let mut text = format!("Problem: {}\nSolver: {}", problem, solver);
if let Some(config) = &result.config {
text.push_str(&format!("\nSolution: {:?}", config));
}
text.push_str(&format!("\nEvaluation: {}", result.evaluation));
text
}
fn solve_result_json(
problem: &str,
solver: &str,
result: &crate::dispatch::SolveResult,
) -> serde_json::Value {
let mut json = serde_json::json!({
"problem": problem,
"solver": solver,
"evaluation": result.evaluation,
});
if let Some(config) = &result.config {
json["solution"] = serde_json::json!(config);
}
json
}
fn plain_problem_output(
problem: &str,
solver: &str,
result: &crate::dispatch::SolveResult,
) -> (String, serde_json::Value) {
(
solve_result_text(problem, solver, result),
solve_result_json(problem, solver, result),
)
}
pub fn solve(input: &Path, solver_name: &str, timeout: u64, out: &OutputConfig) -> Result<()> {
if solver_name != "brute-force" && solver_name != "ilp" && solver_name != "customized" {
anyhow::bail!(
"Unknown solver: {}. Available solvers: brute-force, ilp, customized",
solver_name
);
}
let parsed = parse_input(input)?;
if timeout > 0 {
let solver_name = solver_name.to_string();
let out = out.clone();
let (tx, rx) = std::sync::mpsc::channel();
std::thread::spawn(move || {
let result = match parsed {
SolveInput::Problem(pj) => {
solve_problem(&pj.problem_type, &pj.variant, pj.data, &solver_name, &out)
}
SolveInput::Bundle(b) => solve_bundle(b, &solver_name, &out),
};
tx.send(result).ok();
});
match rx.recv_timeout(Duration::from_secs(timeout)) {
Ok(result) => result,
Err(_) => anyhow::bail!("Solve timed out after {} seconds", timeout),
}
} else {
match parsed {
SolveInput::Problem(pj) => {
solve_problem(&pj.problem_type, &pj.variant, pj.data, solver_name, out)
}
SolveInput::Bundle(b) => solve_bundle(b, solver_name, out),
}
}
}
/// Solve a plain problem file directly.
fn solve_problem(
problem_type: &str,
variant: &std::collections::BTreeMap<String, String>,
data: serde_json::Value,
solver_name: &str,
out: &OutputConfig,
) -> Result<()> {
let problem = load_problem(problem_type, variant, data)?;
let name = problem.problem_name();
match solver_name {
"brute-force" => {
let result = problem.solve_brute_force();
let (text, json) = plain_problem_output(name, "brute-force", &result);
let result = out.emit_with_default_name("", &text, &json);
if out.output.is_none() && crate::output::stderr_is_tty() {
out.info("\nHint: use -o to save full solution details as JSON.");
}
result
}
"ilp" => {
let result = problem.solve_with_ilp().map_err(add_ilp_solver_hint)?;
let solver_desc = if name == "ILP" {
"ilp".to_string()
} else {
"ilp (via ILP)".to_string()
};
let result = crate::dispatch::SolveResult {
config: Some(result.config),
evaluation: result.evaluation,
};
let text = solve_result_text(name, &solver_desc, &result);
let mut json = solve_result_json(name, "ilp", &result);
if name != "ILP" {
json["reduced_to"] = serde_json::json!("ILP");
}
let result = out.emit_with_default_name("", &text, &json);
if out.output.is_none() && crate::output::stderr_is_tty() {
out.info("\nHint: use -o to save full solution details as JSON.");
}
result
}
"customized" => {
let result = problem
.solve_with_customized()
.map_err(add_customized_solver_hint)?;
let result = crate::dispatch::SolveResult {
config: Some(result.config),
evaluation: result.evaluation,
};
let (text, json) = plain_problem_output(name, "customized", &result);
let result = out.emit_with_default_name("", &text, &json);
if out.output.is_none() && crate::output::stderr_is_tty() {
out.info("\nHint: use -o to save full solution details as JSON.");
}
result
}
_ => unreachable!(),
}
}
/// Solve a reduction bundle: solve the target problem, then map the solution back.
fn solve_bundle(bundle: ReductionBundle, solver_name: &str, out: &OutputConfig) -> Result<()> {
let replay = BundleReplay::prepare(&bundle)?;
let target_result = match solver_name {
"brute-force" => replay.target.solve_brute_force_witness().ok_or_else(|| {
anyhow::anyhow!(
"Bundle solving requires a witness-capable target problem and witness-capable reduction path; {} only supports aggregate-value solving.",
replay.target_name
)
})?,
"ilp" => replay.target.solve_with_ilp().map_err(add_ilp_solver_hint)?,
"customized" => replay
.target
.solve_with_customized()
.map_err(add_customized_solver_hint)?,
_ => unreachable!(),
};
let (source_config, source_eval) = replay.extract(&target_result.config);
let solver_desc = format!("{} (via {})", solver_name, replay.target_name);
let text = format!(
"Problem: {}\nSolver: {}\nSolution: {:?}\nEvaluation: {}",
replay.source_name, solver_desc, source_config, source_eval,
);
let json = serde_json::json!({
"problem": replay.source_name,
"solver": solver_name,
"reduced_to": replay.target_name,
"solution": source_config,
"evaluation": source_eval,
"intermediate": {
"problem": replay.target_name,
"solution": target_result.config,
"evaluation": target_result.evaluation,
},
});
let result = out.emit_with_default_name("", &text, &json);
if out.output.is_none() && crate::output::stderr_is_tty() {
out.info("\nHint: use -o to save full solution details (including intermediate results) as JSON.");
}
result
}
fn add_customized_solver_hint(err: anyhow::Error) -> anyhow::Error {
let message = err.to_string();
if message.contains("unsupported by customized solver") {
anyhow::anyhow!(
"{message}\n\nHint: the customized solver only supports select problems (FD-based models, PartialFeedbackEdgeSet, RootedTreeArrangement).\nTry `--solver brute-force` or `--solver ilp` instead."
)
} else {
err
}
}
fn add_ilp_solver_hint(err: anyhow::Error) -> anyhow::Error {
let message = err.to_string();
if (message.starts_with("No reduction path from ") && message.ends_with(" to ILP"))
|| message.contains("witness-capable")
{
anyhow::anyhow!(
"{message}\n\nHint: try `--solver brute-force` for direct exhaustive search on small instances."
)
} else {
err
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::dispatch::SolveResult;
use crate::output::OutputConfig;
use crate::test_support::aggregate_bundle;
#[test]
fn test_solve_value_only_problem_omits_solution() {
let result = SolveResult {
config: None,
evaluation: "Sum(56)".to_string(),
};
let (text, json) =
plain_problem_output("CliTestAggregateValueSource", "brute-force", &result);
assert!(text.contains("Evaluation: Sum(56)"), "{text}");
assert!(!text.contains("Solution:"), "{text}");
assert!(json.get("solution").is_none(), "{json}");
}
#[test]
fn test_solve_bundle_rejects_aggregate_only_path() {
let bundle = aggregate_bundle();
let out = OutputConfig {
output: None,
quiet: true,
json: false,
auto_json: false,
};
let err = solve_bundle(bundle, "brute-force", &out).unwrap_err();
assert!(
err.to_string().contains("witness"),
"unexpected error: {err}"
);
}
}