1
use std::collections::BTreeMap;
2
use std::fmt::Write as _;
3
use std::fs;
4
use std::path::PathBuf;
5
use std::string::ToString;
6
use std::sync::{Arc, RwLock};
7
use std::time::Instant;
8

            
9
use conjure_cp::ast::{Literal, Name};
10
use conjure_cp::context::Context;
11

            
12
use serde_json::{Map, Value as JsonValue};
13

            
14
use itertools::Itertools as _;
15
use tempfile::tempdir;
16

            
17
use crate::utils::json::sort_json_object;
18
use crate::utils::simplified_json::{
19
    domains_from_model, param_model_from_assignments, params_from_simplified_json_str,
20
    solutions_from_simplified_json_str,
21
};
22
use conjure_cp::instantiate::instantiate_model;
23
use conjure_cp::parse::tree_sitter::parse_essence_file_native;
24

            
25
use glob::glob;
26
use uniplate::Uniplate;
27

            
28
#[derive(Clone, Copy, Debug, Default)]
29
pub 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)]
38
pub struct ConjureSolutions {
39
    pub solutions: Vec<BTreeMap<Name, Literal>>,
40
    pub timings: Option<ConjureRunTimings>,
41
}
42

            
43
pub use conjure_cp::solutions::{
44
    SolutionCollectionTimings, get_solutions, get_solutions_with_timings,
45
};
46

            
47
#[derive(Clone, Debug, Default)]
48
pub struct ConjureSolveCaptureOptions {
49
    /// When set, `conjure solve -o` writes models and Minion files here instead of a temp dir.
50
    pub artifact_dir: Option<PathBuf>,
51
    /// Passed to `conjure solve --savilerow-options` (e.g. `-O0`).
52
    pub savilerow_options: Option<String>,
53
}
54

            
55
#[allow(clippy::unwrap_used)]
56
6
pub fn get_solutions_from_conjure(
57
6
    essence_file: &str,
58
6
    param_file: Option<&str>,
59
6
    context: Arc<RwLock<Context<'static>>>,
60
6
) -> Result<Vec<BTreeMap<Name, Literal>>, anyhow::Error> {
61
6
    Ok(get_solutions_from_conjure_with_stats(
62
6
        essence_file,
63
6
        param_file,
64
6
        context,
65
6
        0,
66
6
        ConjureSolveCaptureOptions::default(),
67
6
    )?
68
    .solutions)
69
6
}
70

            
71
#[allow(clippy::unwrap_used)]
72
6
pub fn get_solutions_from_conjure_with_stats(
73
6
    essence_file: &str,
74
6
    param_file: Option<&str>,
75
6
    context: Arc<RwLock<Context<'static>>>,
76
6
    number_of_solutions: i32,
77
6
    capture_options: ConjureSolveCaptureOptions,
78
6
) -> Result<ConjureSolutions, anyhow::Error> {
79
    enum ConjureOutputDir {
80
        Temp(tempfile::TempDir),
81
        Fixed(PathBuf),
82
    }
83

            
84
    impl ConjureOutputDir {
85
18
        fn path(&self) -> &std::path::Path {
86
18
            match self {
87
18
                Self::Temp(dir) => dir.path(),
88
                Self::Fixed(path) => path,
89
            }
90
18
        }
91
    }
92

            
93
6
    let output_dir = match &capture_options.artifact_dir {
94
        Some(path) => {
95
            // A failed run leaves its diagnostics behind. Conjure may reuse files in an existing
96
            // output directory, and the glob below would also read stale solution files, so each
97
            // invocation must start with an empty artifact directory.
98
            if path.exists() {
99
                fs::remove_dir_all(path)?;
100
            }
101
            fs::create_dir_all(path)?;
102
            ConjureOutputDir::Fixed(path.clone())
103
        }
104
6
        None => ConjureOutputDir::Temp(tempdir()?),
105
    };
106

            
107
6
    let mut cmd = std::process::Command::new("conjure");
108
6
    let number_of_solutions_arg = if number_of_solutions == 0 {
109
6
        "all".to_string()
110
    } else {
111
        number_of_solutions.to_string()
112
    };
113

            
114
6
    cmd.arg("solve")
115
6
        .arg(format!("--number-of-solutions={number_of_solutions_arg}"))
116
6
        .arg("--copy-solutions=no")
117
6
        .arg("--solutions-in-one-file")
118
6
        .arg("--output-format=json")
119
6
        .arg("-o")
120
6
        .arg(output_dir.path());
121

            
122
6
    if let Some(options) = &capture_options.savilerow_options {
123
        cmd.arg(format!("--savilerow-options={options}"));
124
6
    }
125

            
126
6
    cmd.arg(essence_file);
127

            
128
6
    if let Some(file) = param_file {
129
2
        cmd.arg(file);
130
4
    }
131

            
132
6
    let conjure_solve_start = Instant::now();
133
6
    let output = cmd.output()?;
134
6
    let conjure_solve_wall_time_s = conjure_solve_start.elapsed().as_secs_f64();
135

            
136
6
    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
6
    }
144

            
145
6
    let domains = domains_for_conjure_solutions(essence_file, param_file, Arc::clone(&context))?;
146

            
147
    let solutions_files: Vec<_> =
148
6
        glob(&format!("{}/*.solutions.json", output_dir.path().display()))?.collect();
149
6
    if solutions_files.is_empty() {
150
        // Unsatisfiable / no solutions: Conjure may omit the solutions file.
151
        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
6
    }
157

            
158
6
    let mut solutions_set = Vec::new();
159
6
    for solutions_file in solutions_files {
160
6
        let solutions_file = solutions_file?;
161
6
        let text = fs::read_to_string(&solutions_file)?;
162
6
        solutions_set.extend(solutions_from_simplified_json_str(&text, &domains)?);
163
    }
164

            
165
6
    let timings = read_conjure_timings(output_dir.path(), conjure_solve_wall_time_s)?;
166

            
167
6
    Ok(ConjureSolutions {
168
6
        solutions: solutions_set,
169
6
        timings,
170
6
    })
171
6
}
172

            
173
6
fn domains_for_conjure_solutions(
174
6
    essence_file: &str,
175
6
    param_file: Option<&str>,
176
6
    context: Arc<RwLock<Context<'static>>>,
177
6
) -> Result<BTreeMap<Name, conjure_cp::ast::DomainPtr>, anyhow::Error> {
178
6
    let problem = parse_essence_file_native(essence_file, Arc::clone(&context))?;
179
6
    let unified = match param_file {
180
2
        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
2
            let param_model = parse_essence_file_native(param_path, Arc::clone(&context))?;
190
2
            instantiate_model(problem, param_model)?
191
        }
192
4
        None => problem,
193
    };
194
6
    Ok(domains_from_model(&unified))
195
6
}
196

            
197
6
fn read_conjure_timings(
198
6
    path: &std::path::Path,
199
6
    conjure_solve_wall_time_s: f64,
200
6
) -> Result<Option<ConjureRunTimings>, anyhow::Error> {
201
6
    let stats_files: Vec<_> = glob(&format!("{}/*.stats.json", path.display()))?.collect();
202
6
    if stats_files.is_empty() {
203
        return Ok(None);
204
6
    }
205

            
206
6
    let mut timings = ConjureRunTimings {
207
6
        wall_clock_time_s: conjure_solve_wall_time_s,
208
6
        ..Default::default()
209
6
    };
210
6
    for stats_file in stats_files {
211
6
        let stats_file = stats_file?;
212
6
        let stats: JsonValue = serde_json::from_str(&fs::read_to_string(&stats_file)?)?;
213
6
        let savilerow_total_time = stats
214
6
            .pointer("/savilerowInfo/SavileRowTotalTime")
215
6
            .and_then(JsonValue::as_str)
216
6
            .and_then(|value| value.parse::<f64>().ok())
217
            .unwrap_or_default();
218
6
        let solve_time = stats
219
6
            .pointer("/savilerowInfo/SolverTotalTime")
220
6
            .and_then(JsonValue::as_str)
221
6
            .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
6
        timings.savilerow_translation_time_s += savilerow_total_time;
231
6
        timings.solve_time_s += solve_time;
232
    }
233

            
234
6
    timings.conjure_translation_time_s =
235
6
        (conjure_solve_wall_time_s - timings.savilerow_translation_time_s - timings.solve_time_s)
236
6
            .max(0.0);
237
6
    timings.translation_time_s =
238
6
        timings.conjure_translation_time_s + timings.savilerow_translation_time_s;
239

            
240
6
    Ok(Some(timings))
241
6
}
242

            
243
120
pub fn solutions_to_json(solutions: &[BTreeMap<Name, Literal>]) -> JsonValue {
244
120
    let json_solutions = solutions.iter().map(solution_to_json).collect();
245
120
    let ans = JsonValue::Array(json_solutions);
246
120
    sort_json_object(&ans, true)
247
120
}
248

            
249
/// Render solutions in the format produced by Conjure's `--solutions-in-one-file` option.
250
331501
pub fn solutions_to_essence(solutions: &[BTreeMap<Name, Literal>]) -> String {
251
331501
    let mut solutions = solutions.iter().collect::<Vec<_>>();
252
19475289
    solutions.sort_by(|lhs, rhs| solution_essence_cmp(lhs, rhs));
253

            
254
331501
    let mut output = String::new();
255
331501
    for (index, solution) in solutions.iter().enumerate() {
256
3847838
        writeln!(output, "$ Solution: {:06}", index + 1).unwrap();
257
3847838
        writeln!(output, "language Essence 1.3\n").unwrap();
258
3847838
        let mut unnamed_types = BTreeMap::new();
259
3847838
        for value in solution.values() {
260
12046370
            for literal in value.universe() {
261
21243324
                if let Literal::Unnamed(value) = literal {
262
4
                    unnamed_types.insert(value.ty.name.clone(), value.ty.size);
263
21243320
                }
264
            }
265
        }
266
3847838
        for (name, size) in unnamed_types {
267
8
            let members = (1..=size).map(|index| format!("{name}_{index}")).join(", ");
268
4
            writeln!(output, "letting {name} be new type enum {{{members}}}").unwrap();
269
        }
270
3847838
        for (name, value) in *solution {
271
12046370
            writeln!(output, "letting {name} be {value}").unwrap();
272
        }
273
3847838
        output.push_str("\n\n");
274
    }
275
331501
    output
276
331501
}
277

            
278
19475241
fn solution_essence_cmp(
279
19475241
    lhs: &BTreeMap<Name, Literal>,
280
19475241
    rhs: &BTreeMap<Name, Literal>,
281
19475241
) -> std::cmp::Ordering {
282
19475241
    lhs.iter()
283
19475241
        .zip(rhs)
284
35497751
        .find_map(|((lhs_name, lhs_value), (rhs_name, rhs_value))| {
285
35497751
            let ordering = lhs_name.cmp(rhs_name);
286
35497751
            (ordering != std::cmp::Ordering::Equal)
287
35497751
                .then_some(ordering)
288
35497751
                .or_else(|| {
289
35497751
                    let ordering = lhs_value.essence_cmp(rhs_value);
290
35497751
                    (ordering != std::cmp::Ordering::Equal).then_some(ordering)
291
35497751
                })
292
35497751
        })
293
26528
        .unwrap_or_else(|| lhs.len().cmp(&rhs.len()))
294
19475241
}
295

            
296
158
fn solution_to_json(solution: &BTreeMap<Name, Literal>) -> JsonValue {
297
158
    let mut json_solution = Map::new();
298
158
    for (var_name, constant) in solution {
299
434
        let serialized_constant = serde_json::to_value(constant).unwrap();
300
434
        json_solution.insert(var_name.to_string(), serialized_constant);
301
    }
302
158
    sort_json_object(&JsonValue::Object(json_solution), false)
303
158
}
304

            
305
#[cfg(test)]
306
mod tests {
307
    use super::*;
308

            
309
    #[test]
310
1
    fn renders_conjure_multi_solution_essence_format() {
311
1
        let mut first = BTreeMap::new();
312
1
        first.insert(Name::User("b".into()), Literal::Bool(false));
313
1
        first.insert(Name::User("x".into()), Literal::Int(1));
314
1
        let mut second = BTreeMap::new();
315
1
        second.insert(Name::User("b".into()), Literal::Bool(true));
316
1
        second.insert(Name::User("x".into()), Literal::Int(2));
317

            
318
1
        assert_eq!(
319
1
            solutions_to_essence(&[first, second]),
320
1
            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
1
    }
332
}