branch_and_bound/lib.rs
1//! This library implements generic branch-and-bound and backtracking solver.
2//!
3//! Branch-and-bound (and backtracking, which is its special case) is the method
4//! of solving an optimization problem by recursively breaking a problem down
5//! to subproblems and then solving them. Unlike brute-force, branch-and-bound
6//! will discard a subproblem if it discovers that the best potentially obtainable
7//! solution to this subproblem is not better than the current best solution
8//! (aka incumbent).
9//!
10//! To use the library, one shell implement a type that represents a problem
11//! (subproblem) and implement the [`Subproblem`] trait for it.
12//!
13//! One can then [`solve`] an instance of problem using one of the predefined
14//! methods (DFS, BFS, BeFS, etc) or use [`solve_with_container`], through
15//! which custom strategies can be implemented.
16
17pub mod bnb_aware_containers;
18
19use bnb_aware_containers::BinaryHeapExt;
20pub use bnb_aware_containers::BnbAwareContainer;
21
22/// Represents the set of subproblems of an intermediate problem
23/// or the value of the objective function of a feasible solution (leaf node).
24pub enum SubproblemResolution<Node: ?Sized, Score> {
25 /// Subproblems of an intermediate problem
26 Branched(Box<dyn Iterator<Item = Node>>),
27 /// The value of the objective function of a feasible solution
28 Solved(Score),
29}
30// TODO: Consider an alternative implementation by making the iterator
31// type a generic variable rather than a `dyn`
32
33/// A problem (subproblem) to be solved with branch-and-bound
34pub trait Subproblem {
35 /// Return type of the boundary and the objective function.
36 /// Higher score is better.
37 type Score: Ord;
38
39 /// Evaluates a problem space.
40 ///
41 /// If the space is to be broken further into subproblems, returns
42 /// a sequence of subproblems (may be empty, which discards
43 /// the current subspace).
44 ///
45 /// If the space consists of just one feasible solution to be solved
46 /// directly, returns the score, which is the value of the objective
47 /// function at the solution. The node is then considered a successful candidate.
48 fn branch_or_evaluate(&mut self) -> SubproblemResolution<Self, Self::Score>;
49
50 /// Value of the boundary function at the problem space.
51 ///
52 /// The boundary function gives an upper-boundary of the best solution
53 /// that could potentially be found in this subproblem space. The value of
54 /// the boundary function must be greater than or equal to every value of
55 /// the objective score of any subproblem reachable through consecutive
56 /// `.branch_or_evaluate` calls.
57 ///
58 /// If at some point in the search process a subproblem's `.bound()` value
59 /// is less than or equal to the current best solution, the subproblem is
60 /// discarded (because no better solution will be found in its subtree).
61 fn bound(&self) -> Self::Score;
62}
63
64/// Solve a problem with branch-and-bound / backtracking using a custom subproblem
65/// container with a custom strategy.
66///
67/// Until the container is empty, a subproblem is popped from the container and evaluated;
68/// when a subproblem is branched, the generated subnodes are put into the container to be
69/// retrieved in the following iterations.
70///
71/// A container is, thus, responsible for the order in which subproblems will be examined,
72/// and can also implement additional features, such as early termination based on
73/// the current best value, early termination based on the number of iterations,
74/// eager or lazy evaluation, etc.
75///
76/// `solve_with_container` should be preferred for advanced use cases (e.g., custom order
77/// or unusual early terination conditions). If you want one of the basic options,
78/// use [`solve`].
79pub fn solve_with_container<Node, Container>(mut container: Container) -> Option<Node>
80where
81 Node: Subproblem,
82 Container: BnbAwareContainer<Node>,
83{
84 // Best candidate: its objective score and the node itself
85 let mut best: Option<(Node::Score, Node)> = None;
86
87 // `container` should initially contain the root node (or even several nodes)
88
89 while let Some(mut candidate) = container.pop_with_incumbent(best.as_ref().map(|x| &x.0)) {
90 match candidate.branch_or_evaluate() {
91 // Intermediate subproblem
92 SubproblemResolution::Branched(subproblems) => {
93 for node in subproblems {
94 container.push_with_incumbent(node, best.as_ref().map(|x| &x.0));
95 }
96 }
97
98 // Leaf node
99 SubproblemResolution::Solved(candidate_score) => {
100 best = match best {
101 None => Some((candidate_score, candidate)),
102 Some((incumbent_score, incumbent)) => {
103 if incumbent_score < candidate_score {
104 // Replace the old (boundary) score with the objective score
105 Some((candidate_score, candidate))
106 } else {
107 Some((incumbent_score, incumbent))
108 }
109 }
110 }
111 }
112 }
113 }
114
115 best.map(|(_, incumbent)| incumbent)
116}
117
118type NodeCmp<Node> = dyn Fn(&Node, &Node) -> std::cmp::Ordering;
119
120/// Order of traversing the subproblem tree with `solve`. See variants' docs for details.
121pub enum TraverseMethod<Node> {
122 /// Depth-first search (DFS): descends into every subtree until reaches the leaf node
123 /// (or determines that a subtree is not worth descending into because the boundary
124 /// value is not better than the incumbent's objective score).
125 ///
126 /// TODO: stabilize and specify the order in which siblings of a certain node are processed,
127 /// so that the user may return nodes in the order of desired processing.
128 ///
129 /// For typical boundary functions, uses significantly less memory compared to best-first
130 /// and breadth-first search.
131 DepthFirst,
132
133 /// Breadth-first search (BFS): Traverses the subproblem tree layer by layer.
134 /// The processing order among nodes on the same layer is unspecified.
135 ///
136 /// For typical boundary functions, behaves similar to best-first search but uses
137 /// a simpler internal data structure to store subproblems to be processed.
138 BreadthFirst,
139
140 /// Best-first search (BeFS): traverses the tree in many directions simultaneously,
141 /// on every iteration selects and evaluates the subproblem with the best value of
142 /// the boundary function. All its children become candidates for the next selection
143 /// (as long as their boundary value is better than the incumbent's objective score).
144 ///
145 /// The processing order among subproblems with the same boundary value is unspecified.
146 ///
147 /// For typical boundary functions, behaves similar to breadth-first search but selects
148 /// subproblems more optimally.
149 BestFirst,
150
151 /// Like best-first search but selects subproblems in the custom order, based on the
152 /// given comparator `.cmp`.
153 ///
154 /// Processes subproblems in the order specified by `.cmp`: subproblems that compare
155 /// *greater* are processed *first*! The processing order among subproblems that
156 /// compare equal is unspecified.
157 ///
158 /// Set `.cmp_superceeds_bound` to `true` only if `.cmp` guarantees that
159 ///
160 /// if `cmp(subproblem_a, subproblem_b) == Ordering::Less`
161 ///
162 /// then `subproblem_a.bound() < subproblem_b.bound()`
163 ///
164 /// (in other words, the order defined by `.cmp` is a specialized order / super-order
165 /// with respect to the order defined by `Subproblem::bound`).
166 ///
167 /// If `.cmp_superceeds_bound` is set, the search will terminate as soon as the candidate
168 /// that is best according to `.cmp` has the boundary value less (i.e., worse) than that of the
169 /// current incumbent.
170 Custom {
171 cmp: Box<NodeCmp<Node>>,
172 cmp_superceeds_bound: bool,
173 },
174}
175
176/// Solve a problem with branch-and-bound / backtracking, using one of the default strategies.
177///
178/// Walks the subproblem tree (`initial` is the root) according to the method specified by `method`.
179///
180/// `solve` should be preferred for simple scenareous (i.e., a single initial node,
181/// one of the default search strategy implementations). For more advanced use cases, use
182/// [`solve_with_container`].
183#[inline]
184pub fn solve<Node: Subproblem>(initial: Node, method: TraverseMethod<Node>) -> Option<Node> {
185 use TraverseMethod::*;
186
187 match method {
188 BestFirst => {
189 let pqueue = BinaryHeapExt {
190 heap: binary_heap_plus::BinaryHeap::from_vec_cmp(
191 vec![initial],
192 |n1: &Node, n2: &Node| n1.bound().cmp(&n2.bound()),
193 ),
194 stop_early: true,
195 };
196 solve_with_container(pqueue)
197 }
198
199 Custom {
200 cmp,
201 cmp_superceeds_bound: stop_early,
202 } => {
203 let pqueue = BinaryHeapExt {
204 heap: binary_heap_plus::BinaryHeap::from_vec_cmp(vec![initial], cmp),
205 stop_early,
206 };
207 solve_with_container(pqueue)
208 }
209
210 BreadthFirst => {
211 let queue = std::collections::VecDeque::from_iter([initial]);
212 solve_with_container(queue)
213 }
214
215 DepthFirst => {
216 let stack = vec![initial];
217 solve_with_container(stack)
218 }
219 }
220}