Skip to main content

conjure_cp/
solutions.rs

1//! Collect solver results and reconstruct high-level Essence values.
2
3use std::collections::{BTreeMap, HashMap};
4use std::path::PathBuf;
5use std::sync::{Arc, Mutex};
6use std::time::Instant;
7
8use crate::Model;
9use crate::ast::categories::{Category, CategoryOf};
10use crate::ast::{Atom, DeclarationPtr, Expression, GroundDomain, Literal, Metadata, Name};
11use crate::bug_assert;
12use crate::representation::util::try_up;
13use crate::settings::{configured_rule_trace_enabled, rule_trace_enabled, set_rule_trace_enabled};
14use crate::solver::{SearchStatus, Solver};
15use uniplate::Uniplate;
16
17struct RuleTraceGuard(bool);
18
19impl Drop for RuleTraceGuard {
20    fn drop(&mut self) {
21        set_rule_trace_enabled(self.0);
22    }
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.
29fn literal_for_reference_domain(
30    reference_domain: Option<GroundDomain>,
31    value: &Literal,
32) -> Option<Literal> {
33    if matches!(reference_domain, Some(GroundDomain::Bool)) {
34        return match value {
35            Literal::Bool(x) => Some(Literal::Bool(*x)),
36            Literal::Int(1) => Some(Literal::Bool(true)),
37            Literal::Int(0) => Some(Literal::Bool(false)),
38            _ => None,
39        };
40    }
41
42    Some(value.clone())
43}
44
45/// Replaces `fromSolution(x)` occurrences with the value of `x` from a previous solution.
46fn substitute_from_solution(
47    expr: &Expression,
48    previous_solution: &BTreeMap<Name, Literal>,
49) -> Option<Expression> {
50    match expr {
51        Expression::FromSolution(_, atom_expr) => {
52            let Atom::Reference(reference) = atom_expr.as_ref() else {
53                return Some(expr.clone());
54            };
55
56            let name = reference.name();
57            let value = previous_solution.get(&name)?;
58            let reference_domain = reference.resolved_domain().map(|x| x.as_ref().clone());
59            let value = literal_for_reference_domain(reference_domain, value)?;
60            Some(Expression::Atomic(Metadata::new(), Atom::Literal(value)))
61        }
62        _ => Some(expr.clone()),
63    }
64}
65
66/// Replaces direct variable references with values from the candidate solution.
67fn substitute_current_solution_refs(
68    expr: &Expression,
69    candidate_solution: &BTreeMap<Name, Literal>,
70) -> Option<Expression> {
71    match expr {
72        Expression::Atomic(_, Atom::Reference(reference)) => {
73            let name = reference.name();
74            let value = candidate_solution.get(&name)?;
75            let reference_domain = reference.resolved_domain().map(|x| x.as_ref().clone());
76            let value = literal_for_reference_domain(reference_domain, value)?;
77            Some(Expression::Atomic(Metadata::new(), Atom::Literal(value)))
78        }
79        _ => Some(expr.clone()),
80    }
81}
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.
87fn does_solution_dominate(
88    dominance_expression: &Expression,
89    candidate_solution: &BTreeMap<Name, Literal>,
90    previous_solution: &BTreeMap<Name, Literal>,
91) -> bool {
92    let expr = dominance_expression
93        .rewrite(&|e| substitute_from_solution(&e, previous_solution))
94        .rewrite(&|e| substitute_current_solution_refs(&e, candidate_solution));
95
96    matches!(
97        crate::ast::eval::eval_constant(&expr),
98        Some(Literal::Bool(true))
99    )
100}
101
102/// Removes solutions that are dominated by another solution in the result set.
103fn retroactively_prune_dominated(
104    solutions: Vec<BTreeMap<Name, Literal>>,
105    dominance_expression: &Expression,
106) -> Vec<BTreeMap<Name, Literal>> {
107    solutions
108        .iter()
109        .enumerate()
110        .filter_map(|(i, solution)| {
111            let dominated = solutions.iter().enumerate().any(|(j, candidate)| {
112                i != j && does_solution_dominate(dominance_expression, candidate, solution)
113            });
114
115            if dominated {
116                None
117            } else {
118                Some(solution.clone())
119            }
120        })
121        .collect()
122}
123
124fn validate_solution_collection_options(model: &Model, num_sols: i32) -> Result<(), anyhow::Error> {
125    if model.objective.is_some() && num_sols != 1 {
126        let got = if num_sols == 0 {
127            "all".to_string()
128        } else {
129            num_sols.to_string()
130        };
131        return Err(anyhow::anyhow!(
132            "optimisation problems require number-of-solutions=1 (got {got})"
133        ));
134    }
135    Ok(())
136}
137
138/// Options for collecting high-level solutions from a rewritten model.
139#[derive(Clone, Debug)]
140pub 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
152impl Default for SolutionOptions {
153    fn default() -> Self {
154        Self {
155            number_of_solutions: 1,
156            keep_intermediate_solutions: false,
157            solver_input_file: None,
158            rule_trace_cdp: false,
159        }
160    }
161}
162
163/// Wall-clock phases of collecting solutions from a compiled model.
164#[derive(Clone, Copy, Debug, Default)]
165pub 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.
178pub 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.
198pub fn get_solutions_with_timings(
199    solver: Solver,
200    model: Model,
201    num_sols: i32,
202    keep_intermediate_solutions: bool,
203    solver_input_file: &Option<PathBuf>,
204    rule_trace_cdp: bool,
205) -> Result<(Vec<BTreeMap<Name, Literal>>, SolutionCollectionTimings), anyhow::Error> {
206    let _rule_trace = RuleTraceGuard(rule_trace_enabled());
207    set_rule_trace_enabled(rule_trace_cdp && configured_rule_trace_enabled());
208
209    validate_solution_collection_options(&model, num_sols)?;
210
211    let is_optimisation = model.objective.is_some();
212
213    let dominance_expression = model.dominance.as_ref().map(|expr| match expr {
214        Expression::DominanceRelation(_, inner) => inner.as_ref().clone(),
215        _ => expr.clone(),
216    });
217
218    let adaptor_name = solver.get_name();
219
220    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    let symbols_ptr = model.symbols_ptr_unchecked().clone();
224
225    let backend_started_at = Instant::now();
226    let solver = solver.load_model(model)?;
227    let backend_time_s = backend_started_at.elapsed().as_secs_f64();
228
229    if let Some(solver_input_file) = solver_input_file {
230        tracing::info!(target: "conjure::stage",
231            "Writing solver input file to {}",
232            solver_input_file.display()
233        );
234        let file = Box::new(std::fs::File::create(solver_input_file)?);
235        solver.write_solver_input_file(&mut (file as Box<dyn std::io::Write>))?;
236    }
237
238    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    let all_solutions_ref = Arc::new(Mutex::<Vec<BTreeMap<Name, Literal>>>::new(vec![]));
242    let all_solutions_ref_2 = all_solutions_ref.clone();
243
244    let search_started_at = Instant::now();
245    let solver = if is_optimisation {
246        solver
247            .solve(Box::new(move |sols| {
248                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
249                let solution = sols.into_iter().collect();
250                if keep_intermediate_solutions {
251                    all_solutions.push(solution);
252                } else {
253                    all_solutions.clear();
254                    all_solutions.push(solution);
255                }
256                true
257            }))
258            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
259    } else if num_sols > 0 {
260        // Get num_sols solutions
261        let sols_left = Mutex::new(num_sols);
262
263        solver
264            .solve(Box::new(move |sols| {
265                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
266                all_solutions.push(sols.into_iter().collect());
267                let mut sols_left = sols_left.lock().unwrap();
268                *sols_left -= 1;
269
270                *sols_left != 0
271            }))
272            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
273    } else {
274        // Get all solutions
275        solver
276            .solve(Box::new(move |sols| {
277                let mut all_solutions = (*all_solutions_ref_2).lock().unwrap();
278                all_solutions.push(sols.into_iter().collect());
279                true
280            }))
281            .map_err(|err| anyhow::anyhow!("solver failed while collecting solutions: {err}"))?
282    };
283
284    let search_time_s = search_started_at.elapsed().as_secs_f64();
285    let processing_started_at = Instant::now();
286    let search_status = solver.search_status();
287    solver.save_stats_to_context();
288
289    // Get the collections of solutions and model symbols
290    #[allow(clippy::unwrap_used)]
291    let mut sols_guard = (*all_solutions_ref).lock().unwrap();
292    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    let requested_limit_reached = !is_optimisation
298        && num_sols > 0
299        && sols.len() >= usize::try_from(num_sols).unwrap_or(usize::MAX);
300    if let SearchStatus::Incomplete(reason) = search_status
301        && !requested_limit_reached
302    {
303        return Err(anyhow::anyhow!("solver search incomplete: {reason:?}"));
304    }
305
306    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    let names = symbols.clone().into_iter().map(|x| x.0).collect::<Vec<_>>();
311    let representations = names
312        .into_iter()
313        .filter_map(|x| symbols.representations_for(&x).map(|repr| (x, repr)))
314        .filter_map(|(name, reprs)| {
315            if reprs.is_empty() {
316                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        })
330        .collect::<Vec<_>>();
331
332    let structured_declarations: Vec<DeclarationPtr> = symbols
333        .iter_local()
334        .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            matches!(name, Name::User(_))
339                && !declaration.reprs().is_empty()
340                && declaration.category_of() >= Category::Decision
341        })
342        .map(|(_, declaration)| declaration.clone())
343        .collect();
344
345    for sol in sols.iter_mut() {
346        // Get the value of complex variables using their auxiliary variables
347        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        let raw_assignment: HashMap<Name, Literal> = sol.clone().into_iter().collect();
361        for declaration in &structured_declarations {
362            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            sol.insert(declaration.name().clone(), value);
369        }
370
371        // Minion represents native booleans as integers; return the declared Essence type.
372        for (name, value) in sol.iter_mut() {
373            let is_bool = symbols
374                .lookup(name)
375                .and_then(|declaration| declaration.domain())
376                .is_some_and(|domain| matches!(domain.as_ground(), Some(GroundDomain::Bool)));
377            if is_bool {
378                match value {
379                    Literal::Int(0) => *value = Literal::Bool(false),
380                    Literal::Int(1) => *value = Literal::Bool(true),
381                    _ => {}
382                }
383            }
384        }
385
386        // Remove auxiliary variables since we've found the value of the
387        // variable they represent
388        *sol = sol
389            .clone()
390            .into_iter()
391            .filter(|(name, _)| {
392                !matches!(name, Name::Represented(_)) && !matches!(name, Name::Machine(_))
393            })
394            .collect();
395    }
396
397    if let Some(dominance_expression) = dominance_expression.as_ref() {
398        let pre_prune_len = sols.len();
399        let pruned = retroactively_prune_dominated(sols.clone(), dominance_expression);
400        let post_prune_len = pruned.len();
401
402        tracing::info!(
403            target: "conjure::stage",
404            retained = post_prune_len,
405            considered = pre_prune_len,
406            "pruned dominated solutions"
407        );
408
409        *sols = pruned;
410    }
411
412    let solutions = sols.clone();
413    Ok((
414        solutions,
415        SolutionCollectionTimings {
416            backend_time_s,
417            search_time_s,
418            solution_processing_time_s: processing_started_at.elapsed().as_secs_f64(),
419        },
420    ))
421}
422
423#[cfg(test)]
424mod tests {
425    use super::*;
426    use crate::ast::{Domain, Moo, Reference};
427
428    #[test]
429    fn retroactive_pruning_removes_dominated_prior_solution() {
430        let x = Name::User("x".into());
431        let x_ref = Expression::Atomic(
432            Metadata::new(),
433            Atom::Reference(Reference::new(DeclarationPtr::new_find(
434                x.clone(),
435                Domain::bool(),
436            ))),
437        );
438        let dominance_expression = Expression::Imply(
439            Metadata::new(),
440            Moo::new(x_ref),
441            Moo::new(Expression::FromSolution(
442                Metadata::new(),
443                Moo::new(Atom::Reference(Reference::new(DeclarationPtr::new_find(
444                    x.clone(),
445                    Domain::bool(),
446                )))),
447            )),
448        );
449
450        let mut sol_true = BTreeMap::new();
451        sol_true.insert(x.clone(), Literal::Int(1));
452        let mut sol_false = BTreeMap::new();
453        sol_false.insert(x, Literal::Int(0));
454
455        let pruned =
456            retroactively_prune_dominated(vec![sol_true, sol_false.clone()], &dominance_expression);
457
458        assert_eq!(pruned, vec![sol_false]);
459    }
460}