conjure_core/solver/
mod.rs

1//! A high-level API for interacting with constraints solvers.
2//!
3//! This module provides a consistent, solver-independent API for interacting with constraints
4//! solvers. It also provides incremental solving support, and the returning of run stats from
5//! solvers.
6//!
7//! -----
8//!
9//! - [Solver<Adaptor>] provides the API for interacting with constraints solvers.
10//!
11//! - The [SolverAdaptor] trait controls how solving actually occurs and handles translation
12//!   between the [Solver] type and a specific solver.
13//!
14//! - [adaptors] contains all implemented solver adaptors.
15//!
16//! - The [model_modifier] submodule defines types to help with incremental solving / changing a
17//!   model during search. The entrypoint for incremental solving is the [Solver<A,ModelLoaded>::solve_mut]
18//!   function.
19//!
20//! # Examples
21//!
22//! ## A Successful Minion Model
23//!
24//! Note: this example constructs a basic Minion-compatible model instead of using the rewriter.
25//! For a full end-to-end example, see conjure_oxide/examples/solver_hello_minion.rs
26//!
27//! ```rust
28//! use std::sync::{Arc,Mutex};
29//! use conjure_core::parse::get_example_model;
30//! use conjure_core::rule_engine::resolve_rule_sets;
31//! use conjure_core::rule_engine::rewrite_naive;
32//! use conjure_core::solver::{adaptors, Solver, SolverAdaptor};
33//! use conjure_core::solver::states::ModelLoaded;
34//! use conjure_core::Model;
35//! use conjure_core::ast::Domain;
36//! use conjure_core::ast::Declaration;
37//! use conjure_core::solver::SolverFamily;
38//! use conjure_core::context::Context;
39//! use conjure_essence_macros::essence_expr;
40//!
41//! // Define a model for minion.
42//! let context = Context::<'static>::new_ptr_empty(SolverFamily::Minion);
43//! let mut model = Model::new(context);
44//! model.as_submodel_mut().add_symbol(Declaration::new_var("x".into(), Domain::Bool));
45//! model.as_submodel_mut().add_symbol(Declaration::new_var("y".into(), Domain::Bool));
46//! model.as_submodel_mut().add_constraint(essence_expr!{x != y});
47//!
48//! // Solve using Minion.
49//! let solver = Solver::new(adaptors::Minion::new());
50//! let solver: Solver<adaptors::Minion,ModelLoaded> = solver.load_model(model).unwrap();
51//!
52//! // In this example, we will count solutions.
53//! //
54//! // The solver interface is designed to allow adaptors to use multiple-threads / processes if
55//! // necessary. Therefore, the callback type requires all variables inside it to have a static
56//! // lifetime and to implement Send (i.e. the variable can be safely shared between theads).
57//! //
58//! // We use Arc<Mutex<T>> to create multiple references to a threadsafe mutable
59//! // variable of type T.
60//! //
61//! // Using the move |x| ... closure syntax, we move one of these references into the closure.
62//! // Note that a normal closure borrow variables from the parent so is not
63//! // thread-safe.
64//!
65//! let counter_ref = Arc::new(Mutex::new(0));
66//! let counter_ref_2 = counter_ref.clone();
67//! solver.solve(Box::new(move |_| {
68//!   let mut counter = (*counter_ref_2).lock().unwrap();
69//!   *counter += 1;
70//!   true
71//!   }));
72//!
73//! let mut counter = (*counter_ref).lock().unwrap();
74//! assert_eq!(*counter,2);
75//! ```
76//!
77//! # The Solver callback function
78//!
79//! The callback function given to `solve` is called whenever a solution is found by the solver.
80//!
81//! Its return value can be used to control how many solutions the solver finds:
82//!
83//! * If the callback function returns `true`, solver execution continues.
84//! * If the callback function returns `false`, the solver is terminated.
85//!
86
87// # Implementing Solver interfaces
88//
89// Solver interfaces can only be implemented inside this module, due to the SolverAdaptor crate
90// being sealed.
91//
92// To add support for a solver, implement the `SolverAdaptor` trait in a submodule.
93//
94// If incremental solving support is required, also implement a new `ModelModifier`. If this is not
95// required, all `ModelModifier` instances required by the SolverAdaptor trait can be replaced with
96// NotModifiable.
97//
98// For more details, see the docstrings for SolverAdaptor, ModelModifier, and NotModifiable.
99
100#![allow(dead_code)]
101#![allow(unused)]
102#![allow(clippy::manual_non_exhaustive)]
103
104use std::any::Any;
105use std::cell::OnceCell;
106use std::collections::HashMap;
107use std::error::Error;
108use std::fmt::{Debug, Display};
109use std::io::Write;
110use std::rc::Rc;
111use std::sync::{Arc, RwLock};
112use std::time::Instant;
113
114use schemars::JsonSchema;
115use serde::{Deserialize, Serialize};
116use strum_macros::{Display, EnumIter, EnumString};
117use thiserror::Error;
118
119use crate::ast::{Literal, Name};
120use crate::context::Context;
121use crate::stats::SolverStats;
122use crate::Model;
123
124use self::model_modifier::ModelModifier;
125use self::states::{ExecutionSuccess, Init, ModelLoaded, SolverState};
126
127pub mod adaptors;
128pub mod model_modifier;
129
130#[doc(hidden)]
131mod private;
132
133pub mod states;
134
135#[derive(
136    Debug,
137    EnumString,
138    EnumIter,
139    Display,
140    PartialEq,
141    Eq,
142    Hash,
143    Clone,
144    Copy,
145    Serialize,
146    Deserialize,
147    JsonSchema,
148)]
149pub enum SolverFamily {
150    Sat,
151    Minion,
152}
153
154/// The type for user-defined callbacks for use with [Solver].
155///
156/// Note that this enforces thread safety
157pub type SolverCallback = Box<dyn Fn(HashMap<Name, Literal>) -> bool + Send>;
158pub type SolverMutCallback =
159    Box<dyn Fn(HashMap<Name, Literal>, Box<dyn ModelModifier>) -> bool + Send>;
160
161/// A common interface for calling underlying solver APIs inside a [`Solver`].
162///
163/// Implementations of this trait aren't directly callable and should be used through [`Solver`] .
164///
165/// The below documentation lists the formal requirements that all implementations of
166/// [`SolverAdaptor`] should follow - **see the top level module documentation and [`Solver`] for
167/// usage details.**
168///
169/// # Encapsulation
170///
171///  The [`SolverAdaptor`] trait **must** only be implemented inside a submodule of this one,
172///  and **should** only be called through [`Solver`].
173///
174/// The `private::Sealed` trait and `private::Internal` type enforce these requirements by only
175/// allowing trait implementations and calling of methods of SolverAdaptor to occur inside this
176/// module.
177///
178/// # Thread Safety
179///
180/// Multiple instances of [`Solver`] can be run in parallel across multiple threads.
181///
182/// [`Solver`] provides no concurrency control or thread-safety; therefore, adaptors **must**
183/// ensure that multiple instances of themselves can be ran in parallel. This applies to all
184/// stages of solving including having two active `solve()` calls happening at a time, loading
185/// a model while another is mid-solve, loading two models at once, etc.
186///
187/// A [SolverAdaptor] **may** use whatever threading or process model it likes underneath the hood,
188/// as long as it obeys the above.
189///
190/// Method calls **should** block instead of erroring where possible.
191///
192/// Underlying solvers that only have one instance per process (such as Minion) **should** block
193/// (eg. using a [`Mutex<()>`](`std::sync::Mutex`)) to run calls to
194/// [`Solver<A,ModelLoaded>::solve()`] and [`Solver<A,ModelLoaded>::solve_mut()`] sequentially.
195pub trait SolverAdaptor: private::Sealed + Any {
196    /// Runs the solver on the given model.
197    ///
198    /// Implementations of this function **must** call the user provided callback whenever a solution
199    /// is found. If the user callback returns `true`, search should continue, if the user callback
200    /// returns `false`, search should terminate.
201    ///
202    /// # Returns
203    ///
204    /// If the solver terminates without crashing a [SolveSuccess] struct **must** returned. The
205    /// value of [SearchStatus] can be used to denote whether the underlying solver completed its
206    /// search or not. The latter case covers most non-crashing "failure" cases including user
207    /// termination, timeouts, etc.
208    ///
209    /// To help populate [SearchStatus], it may be helpful to implement counters that track if the
210    /// user callback has been called yet, and its return value. This information makes it is
211    /// possible to distinguish between the most common search statuses:
212    /// [SearchComplete::HasSolutions], [SearchComplete::NoSolutions], and
213    /// [SearchIncomplete::UserTerminated].
214    fn solve(
215        &mut self,
216        callback: SolverCallback,
217        _: private::Internal,
218    ) -> Result<SolveSuccess, SolverError>;
219
220    /// Runs the solver on the given model, allowing modification of the model through a
221    /// [`ModelModifier`].
222    ///
223    /// Implementations of this function **must** return [`OpNotSupported`](`ModificationFailure::OpNotSupported`)
224    /// if modifying the model mid-search is not supported.
225    ///
226    /// Otherwise, this should work in the same way as [`solve`](SolverAdaptor::solve).
227    fn solve_mut(
228        &mut self,
229        callback: SolverMutCallback,
230        _: private::Internal,
231    ) -> Result<SolveSuccess, SolverError>;
232    fn load_model(&mut self, model: Model, _: private::Internal) -> Result<(), SolverError>;
233    fn init_solver(&mut self, _: private::Internal) {}
234
235    /// Get the solver family that this solver adaptor belongs to
236    fn get_family(&self) -> SolverFamily;
237
238    /// Gets the name of the solver adaptor for pretty printing.
239    fn get_name(&self) -> Option<String> {
240        None
241    }
242
243    /// Adds the solver adaptor name and family (if they exist) to the given stats object.
244    fn add_adaptor_info_to_stats(&self, stats: SolverStats) -> SolverStats {
245        SolverStats {
246            solver_adaptor: self.get_name(),
247            solver_family: Some(self.get_family()),
248            ..stats
249        }
250    }
251
252    /// Writes a solver input file to the given writer.
253    ///
254    /// This method is for debugging use only, and there are no plans to make the solutions
255    /// obtained by running this file through the solver translatable back into high-level Essence.
256    ///
257    /// This file is runnable using the solvers command line interface. E.g. for Minion, this
258    /// outputs a valid .minion file.
259    ///
260    ///
261    /// # Implementation
262    /// + It can be helpful for this file to contain comments linking constraints and variables to
263    ///   their original essence, but this is not required.
264    ///
265    /// + This function is ran after model loading but before solving - therefore, it is safe for
266    ///   solving to mutate the model object.
267    fn write_solver_input_file(&self, writer: &mut impl Write) -> Result<(), std::io::Error>;
268}
269
270/// An abstract representation of a constraints solver.
271///
272/// [Solver] provides a common interface for interacting with a constraint solver. It also
273/// abstracts over solver-specific datatypes, handling the translation to/from [conjure_core::ast]
274/// types for a model and its solutions.
275///
276/// Details of how a model is solved is specified by the [SolverAdaptor]. This includes: the
277/// underlying solver used, the translation of the model to a solver compatible form, how solutions
278/// are translated back to [conjure_core::ast] types, and how incremental solving is implemented.
279/// As such, there may be multiple [SolverAdaptor] implementations for a single underlying solver:
280/// e.g. one adaptor may give solutions in a representation close to the solvers, while another may
281/// attempt to rewrite it back into Essence.
282///
283#[derive(Clone)]
284pub struct Solver<A: SolverAdaptor, State: SolverState = Init> {
285    state: State,
286    adaptor: A,
287    context: Option<Arc<RwLock<Context<'static>>>>,
288}
289
290impl<Adaptor: SolverAdaptor> Solver<Adaptor> {
291    pub fn new(solver_adaptor: Adaptor) -> Solver<Adaptor> {
292        let mut solver = Solver {
293            state: Init,
294            adaptor: solver_adaptor,
295            context: None,
296        };
297
298        solver.adaptor.init_solver(private::Internal);
299        solver
300    }
301
302    pub fn get_family(&self) -> SolverFamily {
303        self.adaptor.get_family()
304    }
305}
306
307impl<A: SolverAdaptor> Solver<A, Init> {
308    pub fn load_model(mut self, model: Model) -> Result<Solver<A, ModelLoaded>, SolverError> {
309        let solver_model = &mut self.adaptor.load_model(model.clone(), private::Internal)?;
310        Ok(Solver {
311            state: ModelLoaded,
312            adaptor: self.adaptor,
313            context: Some(model.context.clone()),
314        })
315    }
316}
317
318impl<A: SolverAdaptor> Solver<A, ModelLoaded> {
319    pub fn solve(
320        mut self,
321        callback: SolverCallback,
322    ) -> Result<Solver<A, ExecutionSuccess>, SolverError> {
323        #[allow(clippy::unwrap_used)]
324        let start_time = Instant::now();
325
326        #[allow(clippy::unwrap_used)]
327        let result = self.adaptor.solve(callback, private::Internal);
328
329        let duration = start_time.elapsed();
330
331        match result {
332            Ok(x) => {
333                let stats = self
334                    .adaptor
335                    .add_adaptor_info_to_stats(x.stats)
336                    .with_timings(duration.as_secs_f64());
337
338                Ok(Solver {
339                    adaptor: self.adaptor,
340                    state: ExecutionSuccess {
341                        stats,
342                        status: x.status,
343                        _sealed: private::Internal,
344                    },
345                    context: self.context,
346                })
347            }
348            Err(x) => Err(x),
349        }
350    }
351
352    pub fn solve_mut(
353        mut self,
354        callback: SolverMutCallback,
355    ) -> Result<Solver<A, ExecutionSuccess>, SolverError> {
356        #[allow(clippy::unwrap_used)]
357        let start_time = Instant::now();
358
359        #[allow(clippy::unwrap_used)]
360        let result = self.adaptor.solve_mut(callback, private::Internal);
361
362        let duration = start_time.elapsed();
363
364        match result {
365            Ok(x) => {
366                let stats = self
367                    .adaptor
368                    .add_adaptor_info_to_stats(x.stats)
369                    .with_timings(duration.as_secs_f64());
370
371                Ok(Solver {
372                    adaptor: self.adaptor,
373                    state: ExecutionSuccess {
374                        stats,
375                        status: x.status,
376                        _sealed: private::Internal,
377                    },
378                    context: self.context,
379                })
380            }
381            Err(x) => Err(x),
382        }
383    }
384
385    /// Writes a solver input file to the given writer.
386    ///
387    /// This method is for debugging use only, and there are no plans to make the solutions
388    /// obtained by running this file through the solver translatable back into high-level Essence.
389    ///
390    /// This file is runnable using the solvers command line interface. E.g. for Minion, this
391    /// outputs a valid .minion file.
392    ///
393    /// This function is only available in the `ModelLoaded` state as solvers are allowed to edit
394    /// the model in place.
395    pub fn write_solver_input_file(&self, writer: &mut impl Write) -> Result<(), std::io::Error> {
396        self.adaptor.write_solver_input_file(writer)
397    }
398}
399
400impl<A: SolverAdaptor> Solver<A, ExecutionSuccess> {
401    pub fn stats(&self) -> SolverStats {
402        self.state.stats.clone()
403    }
404
405    // Saves this solvers stats to the global context as a "solver run"
406    pub fn save_stats_to_context(&self) {
407        #[allow(clippy::unwrap_used)]
408        #[allow(clippy::expect_used)]
409        self.context
410            .as_ref()
411            .expect("")
412            .write()
413            .unwrap()
414            .stats
415            .add_solver_run(self.stats());
416    }
417
418    pub fn wall_time_s(&self) -> f64 {
419        self.stats().conjure_solver_wall_time_s
420    }
421}
422
423/// Errors returned by [Solver] on failure.
424#[non_exhaustive]
425#[derive(Debug, Error, Clone)]
426pub enum SolverError {
427    #[error("operation not implemented yet: {0}")]
428    OpNotImplemented(String),
429
430    #[error("operation not supported: {0}")]
431    OpNotSupported(String),
432
433    #[error("model feature not supported: {0}")]
434    ModelFeatureNotSupported(String),
435
436    #[error("model feature not implemented yet: {0}")]
437    ModelFeatureNotImplemented(String),
438
439    // use for semantics / type errors, use the above for syntax
440    #[error("model invalid: {0}")]
441    ModelInvalid(String),
442
443    #[error("error during solver execution: not implemented: {0}")]
444    RuntimeNotImplemented(String),
445
446    #[error("error during solver execution: {0}")]
447    Runtime(String),
448}
449
450/// Returned from [SolverAdaptor] when solving is successful.
451pub struct SolveSuccess {
452    stats: SolverStats,
453    status: SearchStatus,
454}
455
456pub enum SearchStatus {
457    /// The search was complete (i.e. the solver found all possible solutions)
458    Complete(SearchComplete),
459    /// The search was incomplete (i.e. it was terminated before all solutions were found)
460    Incomplete(SearchIncomplete),
461}
462
463#[non_exhaustive]
464pub enum SearchIncomplete {
465    Timeout,
466    UserTerminated,
467    #[doc(hidden)]
468    /// This variant should not be matched - it exists to simulate non-exhaustiveness of this enum.
469    __NonExhaustive,
470}
471
472#[non_exhaustive]
473pub enum SearchComplete {
474    HasSolutions,
475    NoSolutions,
476    #[doc(hidden)]
477    /// This variant should not be matched - it exists to simulate non-exhaustiveness of this enum.
478    __NonExhaustive,
479}