1use std::collections::BTreeMap;
2use std::fmt::Write as _;
3use std::fs;
4use std::path::PathBuf;
5use std::string::ToString;
6use std::sync::{Arc, RwLock};
7use std::time::Instant;
8
9use conjure_cp::ast::{Literal, Name};
10use conjure_cp::context::Context;
11
12use serde_json::{Map, Value as JsonValue};
13
14use itertools::Itertools as _;
15use tempfile::tempdir;
16
17use crate::utils::json::sort_json_object;
18use crate::utils::simplified_json::{
19 domains_from_model, param_model_from_assignments, params_from_simplified_json_str,
20 solutions_from_simplified_json_str,
21};
22use conjure_cp::instantiate::instantiate_model;
23use conjure_cp::parse::tree_sitter::parse_essence_file_native;
24
25use glob::glob;
26use uniplate::Uniplate;
27
28#[derive(Clone, Copy, Debug, Default)]
29pub struct ConjureRunTimings {
30 pub wall_clock_time_s: f64,
31 pub translation_time_s: f64,
32 pub conjure_translation_time_s: f64,
33 pub savilerow_translation_time_s: f64,
34 pub solve_time_s: f64,
35}
36
37#[derive(Debug)]
38pub struct ConjureSolutions {
39 pub solutions: Vec<BTreeMap<Name, Literal>>,
40 pub timings: Option<ConjureRunTimings>,
41}
42
43pub use conjure_cp::solutions::{
44 SolutionCollectionTimings, get_solutions, get_solutions_with_timings,
45};
46
47#[derive(Clone, Debug, Default)]
48pub struct ConjureSolveCaptureOptions {
49 pub artifact_dir: Option<PathBuf>,
51 pub savilerow_options: Option<String>,
53}
54
55#[allow(clippy::unwrap_used)]
56pub fn get_solutions_from_conjure(
57 essence_file: &str,
58 param_file: Option<&str>,
59 context: Arc<RwLock<Context<'static>>>,
60) -> Result<Vec<BTreeMap<Name, Literal>>, anyhow::Error> {
61 Ok(get_solutions_from_conjure_with_stats(
62 essence_file,
63 param_file,
64 context,
65 0,
66 ConjureSolveCaptureOptions::default(),
67 )?
68 .solutions)
69}
70
71#[allow(clippy::unwrap_used)]
72pub fn get_solutions_from_conjure_with_stats(
73 essence_file: &str,
74 param_file: Option<&str>,
75 context: Arc<RwLock<Context<'static>>>,
76 number_of_solutions: i32,
77 capture_options: ConjureSolveCaptureOptions,
78) -> Result<ConjureSolutions, anyhow::Error> {
79 enum ConjureOutputDir {
80 Temp(tempfile::TempDir),
81 Fixed(PathBuf),
82 }
83
84 impl ConjureOutputDir {
85 fn path(&self) -> &std::path::Path {
86 match self {
87 Self::Temp(dir) => dir.path(),
88 Self::Fixed(path) => path,
89 }
90 }
91 }
92
93 let output_dir = match &capture_options.artifact_dir {
94 Some(path) => {
95 if path.exists() {
99 fs::remove_dir_all(path)?;
100 }
101 fs::create_dir_all(path)?;
102 ConjureOutputDir::Fixed(path.clone())
103 }
104 None => ConjureOutputDir::Temp(tempdir()?),
105 };
106
107 let mut cmd = std::process::Command::new("conjure");
108 let number_of_solutions_arg = if number_of_solutions == 0 {
109 "all".to_string()
110 } else {
111 number_of_solutions.to_string()
112 };
113
114 cmd.arg("solve")
115 .arg(format!("--number-of-solutions={number_of_solutions_arg}"))
116 .arg("--copy-solutions=no")
117 .arg("--solutions-in-one-file")
118 .arg("--output-format=json")
119 .arg("-o")
120 .arg(output_dir.path());
121
122 if let Some(options) = &capture_options.savilerow_options {
123 cmd.arg(format!("--savilerow-options={options}"));
124 }
125
126 cmd.arg(essence_file);
127
128 if let Some(file) = param_file {
129 cmd.arg(file);
130 }
131
132 let conjure_solve_start = Instant::now();
133 let output = cmd.output()?;
134 let conjure_solve_wall_time_s = conjure_solve_start.elapsed().as_secs_f64();
135
136 if !output.status.success() {
137 let stderr =
138 String::from_utf8(output.stderr).unwrap_or_else(|e| e.utf8_error().to_string());
139 return Err(anyhow::Error::msg(format!(
140 "Error: `conjure solve` exited with code {}; stderr: {}",
141 output.status, stderr
142 )));
143 }
144
145 let domains = domains_for_conjure_solutions(essence_file, param_file, Arc::clone(&context))?;
146
147 let solutions_files: Vec<_> =
148 glob(&format!("{}/*.solutions.json", output_dir.path().display()))?.collect();
149 if solutions_files.is_empty() {
150 let timings = read_conjure_timings(output_dir.path(), conjure_solve_wall_time_s)?;
152 return Ok(ConjureSolutions {
153 solutions: Vec::new(),
154 timings,
155 });
156 }
157
158 let mut solutions_set = Vec::new();
159 for solutions_file in solutions_files {
160 let solutions_file = solutions_file?;
161 let text = fs::read_to_string(&solutions_file)?;
162 solutions_set.extend(solutions_from_simplified_json_str(&text, &domains)?);
163 }
164
165 let timings = read_conjure_timings(output_dir.path(), conjure_solve_wall_time_s)?;
166
167 Ok(ConjureSolutions {
168 solutions: solutions_set,
169 timings,
170 })
171}
172
173fn domains_for_conjure_solutions(
174 essence_file: &str,
175 param_file: Option<&str>,
176 context: Arc<RwLock<Context<'static>>>,
177) -> Result<BTreeMap<Name, conjure_cp::ast::DomainPtr>, anyhow::Error> {
178 let problem = parse_essence_file_native(essence_file, Arc::clone(&context))?;
179 let unified = match param_file {
180 Some(param_path) if param_path.ends_with(".json") => {
181 let given_domains = domains_from_model(&problem);
182 let params =
183 params_from_simplified_json_str(&fs::read_to_string(param_path)?, &given_domains)?;
184 let param_model =
185 param_model_from_assignments(params, &given_domains, Arc::clone(&context));
186 instantiate_model(problem, param_model)?
187 }
188 Some(param_path) => {
189 let param_model = parse_essence_file_native(param_path, Arc::clone(&context))?;
190 instantiate_model(problem, param_model)?
191 }
192 None => problem,
193 };
194 Ok(domains_from_model(&unified))
195}
196
197fn read_conjure_timings(
198 path: &std::path::Path,
199 conjure_solve_wall_time_s: f64,
200) -> Result<Option<ConjureRunTimings>, anyhow::Error> {
201 let stats_files: Vec<_> = glob(&format!("{}/*.stats.json", path.display()))?.collect();
202 if stats_files.is_empty() {
203 return Ok(None);
204 }
205
206 let mut timings = ConjureRunTimings {
207 wall_clock_time_s: conjure_solve_wall_time_s,
208 ..Default::default()
209 };
210 for stats_file in stats_files {
211 let stats_file = stats_file?;
212 let stats: JsonValue = serde_json::from_str(&fs::read_to_string(&stats_file)?)?;
213 let savilerow_total_time = stats
214 .pointer("/savilerowInfo/SavileRowTotalTime")
215 .and_then(JsonValue::as_str)
216 .and_then(|value| value.parse::<f64>().ok())
217 .unwrap_or_default();
218 let solve_time = stats
219 .pointer("/savilerowInfo/SolverTotalTime")
220 .and_then(JsonValue::as_str)
221 .and_then(|value| value.parse::<f64>().ok())
222 .or_else(|| {
223 stats
224 .pointer("/savilerowInfo/SolverSolveTime")
225 .and_then(JsonValue::as_str)
226 .and_then(|value| value.parse::<f64>().ok())
227 })
228 .unwrap_or_default();
229
230 timings.savilerow_translation_time_s += savilerow_total_time;
231 timings.solve_time_s += solve_time;
232 }
233
234 timings.conjure_translation_time_s =
235 (conjure_solve_wall_time_s - timings.savilerow_translation_time_s - timings.solve_time_s)
236 .max(0.0);
237 timings.translation_time_s =
238 timings.conjure_translation_time_s + timings.savilerow_translation_time_s;
239
240 Ok(Some(timings))
241}
242
243pub fn solutions_to_json(solutions: &[BTreeMap<Name, Literal>]) -> JsonValue {
244 let json_solutions = solutions.iter().map(solution_to_json).collect();
245 let ans = JsonValue::Array(json_solutions);
246 sort_json_object(&ans, true)
247}
248
249pub fn solutions_to_essence(solutions: &[BTreeMap<Name, Literal>]) -> String {
251 let mut solutions = solutions.iter().collect::<Vec<_>>();
252 solutions.sort_by(|lhs, rhs| solution_essence_cmp(lhs, rhs));
253
254 let mut output = String::new();
255 for (index, solution) in solutions.iter().enumerate() {
256 writeln!(output, "$ Solution: {:06}", index + 1).unwrap();
257 writeln!(output, "language Essence 1.3\n").unwrap();
258 let mut unnamed_types = BTreeMap::new();
259 for value in solution.values() {
260 for literal in value.universe() {
261 if let Literal::Unnamed(value) = literal {
262 unnamed_types.insert(value.ty.name.clone(), value.ty.size);
263 }
264 }
265 }
266 for (name, size) in unnamed_types {
267 let members = (1..=size).map(|index| format!("{name}_{index}")).join(", ");
268 writeln!(output, "letting {name} be new type enum {{{members}}}").unwrap();
269 }
270 for (name, value) in *solution {
271 writeln!(output, "letting {name} be {value}").unwrap();
272 }
273 output.push_str("\n\n");
274 }
275 output
276}
277
278fn solution_essence_cmp(
279 lhs: &BTreeMap<Name, Literal>,
280 rhs: &BTreeMap<Name, Literal>,
281) -> std::cmp::Ordering {
282 lhs.iter()
283 .zip(rhs)
284 .find_map(|((lhs_name, lhs_value), (rhs_name, rhs_value))| {
285 let ordering = lhs_name.cmp(rhs_name);
286 (ordering != std::cmp::Ordering::Equal)
287 .then_some(ordering)
288 .or_else(|| {
289 let ordering = lhs_value.essence_cmp(rhs_value);
290 (ordering != std::cmp::Ordering::Equal).then_some(ordering)
291 })
292 })
293 .unwrap_or_else(|| lhs.len().cmp(&rhs.len()))
294}
295
296fn solution_to_json(solution: &BTreeMap<Name, Literal>) -> JsonValue {
297 let mut json_solution = Map::new();
298 for (var_name, constant) in solution {
299 let serialized_constant = serde_json::to_value(constant).unwrap();
300 json_solution.insert(var_name.to_string(), serialized_constant);
301 }
302 sort_json_object(&JsonValue::Object(json_solution), false)
303}
304
305#[cfg(test)]
306mod tests {
307 use super::*;
308
309 #[test]
310 fn renders_conjure_multi_solution_essence_format() {
311 let mut first = BTreeMap::new();
312 first.insert(Name::User("b".into()), Literal::Bool(false));
313 first.insert(Name::User("x".into()), Literal::Int(1));
314 let mut second = BTreeMap::new();
315 second.insert(Name::User("b".into()), Literal::Bool(true));
316 second.insert(Name::User("x".into()), Literal::Int(2));
317
318 assert_eq!(
319 solutions_to_essence(&[first, second]),
320 concat!(
321 "$ Solution: 000001\n",
322 "language Essence 1.3\n\n",
323 "letting b be false\n",
324 "letting x be 1\n\n\n",
325 "$ Solution: 000002\n",
326 "language Essence 1.3\n\n",
327 "letting b be true\n",
328 "letting x be 2\n\n\n",
329 )
330 );
331 }
332}