1
//! Collect solver results and reconstruct high-level Essence values.
2

            
3
use std::collections::{BTreeMap, HashMap};
4
use std::path::PathBuf;
5
use std::sync::{Arc, Mutex};
6
use std::time::Instant;
7

            
8
use crate::Model;
9
use crate::ast::categories::{Category, CategoryOf};
10
use crate::ast::{Atom, DeclarationPtr, Expression, GroundDomain, Literal, Metadata, Name};
11
use crate::bug_assert;
12
use crate::representation::util::try_up;
13
use crate::settings::{configured_rule_trace_enabled, rule_trace_enabled, set_rule_trace_enabled};
14
use crate::solver::{SearchStatus, Solver};
15
use uniplate::Uniplate;
16

            
17
struct RuleTraceGuard(bool);
18

            
19
impl Drop for RuleTraceGuard {
20
628518
    fn drop(&mut self) {
21
628518
        set_rule_trace_enabled(self.0);
22
628518
    }
23
}
24

            
25
/// Coerces a literal into the type expected by a reference domain when possible.
26
///
27
/// This is currently used to turn `0`/`1` solver outputs back into boolean
28
/// literals before substituting them into dominance expressions.
29
18300364
fn literal_for_reference_domain(
30
18300364
    reference_domain: Option<GroundDomain>,
31
18300364
    value: &Literal,
32
18300364
) -> Option<Literal> {
33
18300364
    if matches!(reference_domain, Some(GroundDomain::Bool)) {
34
15598804
        return match value {
35
15598800
            Literal::Bool(x) => Some(Literal::Bool(*x)),
36
2
            Literal::Int(1) => Some(Literal::Bool(true)),
37
2
            Literal::Int(0) => Some(Literal::Bool(false)),
38
            _ => None,
39
        };
40
2701560
    }
41

            
42
2701560
    Some(value.clone())
43
18300364
}
44

            
45
/// Replaces `fromSolution(x)` occurrences with the value of `x` from a previous solution.
46
58836216
fn substitute_from_solution(
47
58836216
    expr: &Expression,
48
58836216
    previous_solution: &BTreeMap<Name, Literal>,
49
58836216
) -> Option<Expression> {
50
58836216
    match expr {
51
        Expression::FromSolution(_, atom_expr) => {
52
9150182
            let Atom::Reference(reference) = atom_expr.as_ref() else {
53
                return Some(expr.clone());
54
            };
55

            
56
9150182
            let name = reference.name();
57
9150182
            let value = previous_solution.get(&name)?;
58
9150182
            let reference_domain = reference.resolved_domain().map(|x| x.as_ref().clone());
59
9150182
            let value = literal_for_reference_domain(reference_domain, value)?;
60
9150182
            Some(Expression::Atomic(Metadata::new(), Atom::Literal(value)))
61
        }
62
49686034
        _ => Some(expr.clone()),
63
    }
64
58836216
}
65

            
66
/// Replaces direct variable references with values from the candidate solution.
67
58836216
fn substitute_current_solution_refs(
68
58836216
    expr: &Expression,
69
58836216
    candidate_solution: &BTreeMap<Name, Literal>,
70
58836216
) -> Option<Expression> {
71
58836216
    match expr {
72
        Expression::Atomic(_, Atom::Reference(reference)) => {
73
9150182
            let name = reference.name();
74
9150182
            let value = candidate_solution.get(&name)?;
75
9150182
            let reference_domain = reference.resolved_domain().map(|x| x.as_ref().clone());
76
9150182
            let value = literal_for_reference_domain(reference_domain, value)?;
77
9150182
            Some(Expression::Atomic(Metadata::new(), Atom::Literal(value)))
78
        }
79
49686034
        _ => Some(expr.clone()),
80
    }
81
58836216
}
82

            
83
/// Evaluates whether `candidate_solution` dominates `previous_solution`.
84
///
85
/// The dominance expression is instantiated with values from both solutions and
86
/// then constant-folded to a boolean result.
87
873167
fn does_solution_dominate(
88
873167
    dominance_expression: &Expression,
89
873167
    candidate_solution: &BTreeMap<Name, Literal>,
90
873167
    previous_solution: &BTreeMap<Name, Literal>,
91
873167
) -> bool {
92
873167
    let expr = dominance_expression
93
58836216
        .rewrite(&|e| substitute_from_solution(&e, previous_solution))
94
58836216
        .rewrite(&|e| substitute_current_solution_refs(&e, candidate_solution));
95

            
96
873167
    matches!(
97
873167
        crate::ast::eval::eval_constant(&expr),
98
        Some(Literal::Bool(true))
99
    )
100
873167
}
101

            
102
/// Removes solutions that are dominated by another solution in the result set.
103
9286
fn retroactively_prune_dominated(
104
9286
    solutions: Vec<BTreeMap<Name, Literal>>,
105
9286
    dominance_expression: &Expression,
106
9286
) -> Vec<BTreeMap<Name, Literal>> {
107
9286
    solutions
108
9286
        .iter()
109
9286
        .enumerate()
110
70397
        .filter_map(|(i, solution)| {
111
943564
            let dominated = solutions.iter().enumerate().any(|(j, candidate)| {
112
943564
                i != j && does_solution_dominate(dominance_expression, candidate, solution)
113
943564
            });
114

            
115
70397
            if dominated {
116
22276
                None
117
            } else {
118
48121
                Some(solution.clone())
119
            }
120
70397
        })
121
        .collect()
122
9286
}
123

            
124
628518
fn validate_solution_collection_options(model: &Model, num_sols: i32) -> Result<(), anyhow::Error> {
125
628518
    if model.objective.is_some() && num_sols != 1 {
126
15
        let got = if num_sols == 0 {
127
15
            "all".to_string()
128
        } else {
129
            num_sols.to_string()
130
        };
131
15
        return Err(anyhow::anyhow!(
132
15
            "optimisation problems require number-of-solutions=1 (got {got})"
133
15
        ));
134
628503
    }
135
628503
    Ok(())
136
628518
}
137

            
138
/// Options for collecting high-level solutions from a rewritten model.
139
#[derive(Clone, Debug)]
140
pub struct SolutionOptions {
141
    /// Positive solution limit, or zero to enumerate all solutions.
142
    /// Optimisation requires a limit of one.
143
    pub number_of_solutions: i32,
144
    /// Retain every improving optimisation solution instead of only the optimum.
145
    pub keep_intermediate_solutions: bool,
146
    /// Write the solver's native input format to this path before searching.
147
    pub solver_input_file: Option<PathBuf>,
148
    /// Include solver-time constraint dominance rewrites in configured rule traces.
149
    pub rule_trace_cdp: bool,
150
}
151

            
152
impl Default for SolutionOptions {
153
342
    fn default() -> Self {
154
342
        Self {
155
342
            number_of_solutions: 1,
156
342
            keep_intermediate_solutions: false,
157
342
            solver_input_file: None,
158
342
            rule_trace_cdp: false,
159
342
        }
160
342
    }
161
}
162

            
163
/// Wall-clock phases of collecting solutions from a compiled model.
164
#[derive(Clone, Copy, Debug, Default)]
165
pub struct SolutionCollectionTimings {
166
    /// Time spent loading the rewritten model into the solver.
167
    pub backend_time_s: f64,
168
    /// Time inside the solver call, including solution callbacks and solver-time rewrites.
169
    pub search_time_s: f64,
170
    /// Time spent reconstructing values and pruning dominated solutions.
171
    pub solution_processing_time_s: f64,
172
}
173

            
174
/// Collect and reconstruct model solutions.
175
///
176
/// `num_sols` is a positive limit, or zero to enumerate all solutions. Optimisation
177
/// requires a limit of one and retains the optimum unless intermediate solutions are requested.
178
pub fn get_solutions(
179
    solver: Solver,
180
    model: Model,
181
    num_sols: i32,
182
    keep_intermediate_solutions: bool,
183
    solver_input_file: &Option<PathBuf>,
184
    rule_trace_cdp: bool,
185
) -> Result<Vec<BTreeMap<Name, Literal>>, anyhow::Error> {
186
    get_solutions_with_timings(
187
        solver,
188
        model,
189
        num_sols,
190
        keep_intermediate_solutions,
191
        solver_input_file,
192
        rule_trace_cdp,
193
    )
194
    .map(|(solutions, _)| solutions)
195
}
196

            
197
/// Collect solutions together with measured backend, search and reconstruction times.
198
628518
pub fn get_solutions_with_timings(
199
628518
    solver: Solver,
200
628518
    model: Model,
201
628518
    num_sols: i32,
202
628518
    keep_intermediate_solutions: bool,
203
628518
    solver_input_file: &Option<PathBuf>,
204
628518
    rule_trace_cdp: bool,
205
628518
) -> Result<(Vec<BTreeMap<Name, Literal>>, SolutionCollectionTimings), anyhow::Error> {
206
628518
    let _rule_trace = RuleTraceGuard(rule_trace_enabled());
207
628518
    set_rule_trace_enabled(rule_trace_cdp && configured_rule_trace_enabled());
208

            
209
628518
    validate_solution_collection_options(&model, num_sols)?;
210

            
211
628503
    let is_optimisation = model.objective.is_some();
212

            
213
628503
    let dominance_expression = model.dominance.as_ref().map(|expr| match expr {
214
9285
        Expression::DominanceRelation(_, inner) => inner.as_ref().clone(),
215
        _ => expr.clone(),
216
9285
    });
217

            
218
628503
    let adaptor_name = solver.get_name();
219

            
220
628503
    tracing::info!(target: "conjure::stage", adaptor = adaptor_name, "building solver model");
221

            
222
    // Create for later since we consume the model when loading it
223
628503
    let symbols_ptr = model.symbols_ptr_unchecked().clone();
224

            
225
628503
    let backend_started_at = Instant::now();
226
628503
    let solver = solver.load_model(model)?;
227
628503
    let backend_time_s = backend_started_at.elapsed().as_secs_f64();
228

            
229
628503
    if let Some(solver_input_file) = solver_input_file {
230
15
        tracing::info!(target: "conjure::stage",
231
            "Writing solver input file to {}",
232
            solver_input_file.display()
233
        );
234
15
        let file = Box::new(std::fs::File::create(solver_input_file)?);
235
15
        solver.write_solver_input_file(&mut (file as Box<dyn std::io::Write>))?;
236
628488
    }
237

            
238
628503
    tracing::info!(target: "conjure::stage", adaptor = adaptor_name, "running solver");
239

            
240
    // Create two arcs, one to pass into the solver callback, one to get solutions out later
241
628503
    let all_solutions_ref = Arc::new(Mutex::<Vec<BTreeMap<Name, Literal>>>::new(vec![]));
242
628503
    let all_solutions_ref_2 = all_solutions_ref.clone();
243

            
244
628503
    let search_started_at = Instant::now();
245
628503
    let solver = if is_optimisation {
246
11028
        solver
247
19571
            .solve(Box::new(move |sols| {
248
19571
                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
249
19571
                let solution = sols.into_iter().collect();
250
19571
                if keep_intermediate_solutions {
251
2235
                    all_solutions.push(solution);
252
                } else {
253
17336
                    all_solutions.clear();
254
17336
                    all_solutions.push(solution);
255
                }
256
19571
                true
257
19571
            }))
258
            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
259
617475
    } else if num_sols > 0 {
260
        // Get num_sols solutions
261
2356
        let sols_left = Mutex::new(num_sols);
262

            
263
2356
        solver
264
2356
            .solve(Box::new(move |sols| {
265
2344
                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
266
2344
                all_solutions.push(sols.into_iter().collect());
267
2344
                let mut sols_left = sols_left.lock().unwrap();
268
2344
                *sols_left -= 1;
269

            
270
2344
                *sols_left != 0
271
2344
            }))
272
            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
273
    } else {
274
        // Get all solutions
275
615119
        solver
276
7278856
            .solve(Box::new(move |sols| {
277
7278856
                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
278
7278856
                all_solutions.push(sols.into_iter().collect());
279
7278856
                true
280
7278856
            }))
281
            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
282
    };
283

            
284
628503
    let search_time_s = search_started_at.elapsed().as_secs_f64();
285
628503
    let processing_started_at = Instant::now();
286
628503
    let search_status = solver.search_status();
287
628503
    solver.save_stats_to_context();
288

            
289
    // Get the collections of solutions and model symbols
290
    #[allow(clippy::unwrap_used)]
291
628503
    let mut sols_guard = (*all_solutions_ref).lock().unwrap();
292
628503
    let sols = &mut *sols_guard;
293

            
294
    // Stopping after a requested finite number of satisfaction solutions is intentional. Every
295
    // other incomplete search -- notably a solver timeout or interrupt while proving UNSAT -- must
296
    // not be accepted as a complete (possibly empty) solution set.
297
628503
    let requested_limit_reached = !is_optimisation
298
617475
        && num_sols > 0
299
2356
        && sols.len() >= usize::try_from(num_sols).unwrap_or(usize::MAX);
300
628503
    if let SearchStatus::Incomplete(reason) = search_status
301
2344
        && !requested_limit_reached
302
    {
303
        return Err(anyhow::anyhow!("solver search incomplete: {reason:?}"));
304
628503
    }
305

            
306
628503
    let symbols = symbols_ptr.read();
307

            
308
    // Get the representations for each variable by name, since some variables are
309
    // divided into multiple auxiliary variables(see crate::representation::Representation)
310
324030520
    let names = symbols.clone().into_iter().map(|x| x.0).collect::<Vec<_>>();
311
628503
    let representations = names
312
628503
        .into_iter()
313
324030520
        .filter_map(|x| symbols.representations_for(&x).map(|repr| (x, repr)))
314
323498439
        .filter_map(|(name, reprs)| {
315
323498439
            if reprs.is_empty() {
316
323498439
                return None;
317
            }
318
            bug_assert!(
319
                reprs.len() <= 1,
320
                "multiple representations for a variable is not yet implemented"
321
            );
322

            
323
            assert_eq!(
324
                reprs[0].len(),
325
                1,
326
                "nested representations are not yet implemented"
327
            );
328
            Some((name, reprs[0][0].clone()))
329
323498439
        })
330
        .collect::<Vec<_>>();
331

            
332
628503
    let structured_declarations: Vec<DeclarationPtr> = symbols
333
628503
        .iter_local()
334
324030520
        .filter(|(name, declaration)| {
335
            // `category_of` follows a value letting into its body, and from there into every
336
            // letting that body names. Those declarations have no representations, so skip them
337
            // before walking the chain.
338
324030520
            matches!(name, Name::User(_))
339
1673940
                && !declaration.reprs().is_empty()
340
1122987
                && declaration.category_of() >= Category::Decision
341
324030520
        })
342
1093956
        .map(|(_, declaration)| declaration.clone())
343
        .collect();
344

            
345
628503
    for sol in sols.iter_mut() {
346
        // Get the value of complex variables using their auxiliary variables
347
7292243
        for (name, representation) in representations.iter() {
348
            if sol.contains_key(name) {
349
                continue;
350
            }
351

            
352
            let value = representation.value_up(sol).map_err(|err| {
353
                anyhow::anyhow!(
354
                    "failed to reconstruct value for variable {name} from solver solution: {err}"
355
                )
356
            })?;
357
            sol.insert(name.clone(), value);
358
        }
359

            
360
7292243
        let raw_assignment: HashMap<Name, Literal> = sol.clone().into_iter().collect();
361
7292243
        for declaration in &structured_declarations {
362
17241863
            let value = try_up(declaration.clone(), &raw_assignment).map_err(|err| {
363
                anyhow::anyhow!(
364
                    "failed to reconstruct value for variable {}: {err}",
365
                    declaration.name()
366
                )
367
            })?;
368
17241863
            sol.insert(declaration.name().clone(), value);
369
        }
370

            
371
        // Minion represents native booleans as integers; return the declared Essence type.
372
7292243
        for (name, value) in sol.iter_mut() {
373
168094963
            let is_bool = symbols
374
168094963
                .lookup(name)
375
168094963
                .and_then(|declaration| declaration.domain())
376
168094963
                .is_some_and(|domain| matches!(domain.as_ground(), Some(GroundDomain::Bool)));
377
168094963
            if is_bool {
378
147938514
                match value {
379
114894742
                    Literal::Int(0) => *value = Literal::Bool(false),
380
32953403
                    Literal::Int(1) => *value = Literal::Bool(true),
381
90369
                    _ => {}
382
                }
383
20156449
            }
384
        }
385

            
386
        // Remove auxiliary variables since we've found the value of the
387
        // variable they represent
388
7292243
        *sol = sol
389
7292243
            .clone()
390
7292243
            .into_iter()
391
168094963
            .filter(|(name, _)| {
392
168094963
                !matches!(name, Name::Represented(_)) && !matches!(name, Name::Machine(_))
393
168094963
            })
394
            .collect();
395
    }
396

            
397
628503
    if let Some(dominance_expression) = dominance_expression.as_ref() {
398
9285
        let pre_prune_len = sols.len();
399
9285
        let pruned = retroactively_prune_dominated(sols.clone(), dominance_expression);
400
9285
        let post_prune_len = pruned.len();
401

            
402
9285
        tracing::info!(
403
            target: "conjure::stage",
404
            retained = post_prune_len,
405
            considered = pre_prune_len,
406
            "pruned dominated solutions"
407
        );
408

            
409
9285
        *sols = pruned;
410
619218
    }
411

            
412
628503
    let solutions = sols.clone();
413
628503
    Ok((
414
628503
        solutions,
415
628503
        SolutionCollectionTimings {
416
628503
            backend_time_s,
417
628503
            search_time_s,
418
628503
            solution_processing_time_s: processing_started_at.elapsed().as_secs_f64(),
419
628503
        },
420
628503
    ))
421
628518
}
422

            
423
#[cfg(test)]
424
mod tests {
425
    use super::*;
426
    use crate::ast::{Domain, Moo, Reference};
427

            
428
    #[test]
429
1
    fn retroactive_pruning_removes_dominated_prior_solution() {
430
1
        let x = Name::User("x".into());
431
1
        let x_ref = Expression::Atomic(
432
1
            Metadata::new(),
433
1
            Atom::Reference(Reference::new(DeclarationPtr::new_find(
434
1
                x.clone(),
435
1
                Domain::bool(),
436
1
            ))),
437
1
        );
438
1
        let dominance_expression = Expression::Imply(
439
1
            Metadata::new(),
440
1
            Moo::new(x_ref),
441
1
            Moo::new(Expression::FromSolution(
442
1
                Metadata::new(),
443
1
                Moo::new(Atom::Reference(Reference::new(DeclarationPtr::new_find(
444
1
                    x.clone(),
445
1
                    Domain::bool(),
446
1
                )))),
447
1
            )),
448
1
        );
449

            
450
1
        let mut sol_true = BTreeMap::new();
451
1
        sol_true.insert(x.clone(), Literal::Int(1));
452
1
        let mut sol_false = BTreeMap::new();
453
1
        sol_false.insert(x, Literal::Int(0));
454

            
455
        let pruned =
456
1
            retroactively_prune_dominated(vec![sol_true, sol_false.clone()], &dominance_expression);
457

            
458
1
        assert_eq!(pruned, vec![sol_false]);
459
1
    }
460
}