1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
// Copyright 2020 Xavier Gillard
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//! This module provides the implementation of a sequential mdd solver. That is
//! a solver that will solve the problem using one single thread of execution.
//!
//! This is usually not the implementation you will want to use if you are
//! after solving a hard problem efficiently. However, in those cases where
//! you would be using a constrained environment (e.g. a python interpreter)
//! where multithreading is not an option; then you might want to use this
//! implementation instead.
use std::clone::Clone;
use std::{sync::Arc, hash::Hash};
use crate::{Fringe, Decision, Problem, Relaxation, StateRanking, WidthHeuristic, Cutoff, SubProblem, DecisionDiagram, CompilationInput, CompilationType, Solver, Solution, Completion, Reason, Barrier, EmptyBarrier, DefaultMDDLEL};
/// The workload a thread can get from the shared state
enum WorkLoad<T> {
/// There is no work left to be done: you can safely terminate
Complete,
/// The work must stop because of an external cutoff
Aborted,
/// The item to process
WorkItem { node: SubProblem<T> },
}
/// This is the structure implementing an single-threaded MDD solver.
///
/// # Example Usage
/// ```
/// # use ddo::*;
/// #
/// # #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
/// # struct KnapsackState {
/// # depth: usize,
/// # capacity: usize
/// # }
/// #
/// # struct Knapsack {
/// # capacity: usize,
/// # profit: Vec<usize>,
/// # weight: Vec<usize>,
/// # }
/// #
/// # const TAKE_IT: isize = 1;
/// # const LEAVE_IT_OUT: isize = 0;
/// #
/// # impl Problem for Knapsack {
/// # type State = KnapsackState;
/// # fn nb_variables(&self) -> usize {
/// # self.profit.len()
/// # }
/// # fn initial_state(&self) -> Self::State {
/// # KnapsackState{ depth: 0, capacity: self.capacity }
/// # }
/// # fn initial_value(&self) -> isize {
/// # 0
/// # }
/// # fn transition(&self, state: &Self::State, dec: Decision) -> Self::State {
/// # let mut ret = state.clone();
/// # ret.depth += 1;
/// # if dec.value == TAKE_IT {
/// # ret.capacity -= self.weight[dec.variable.id()]
/// # }
/// # ret
/// # }
/// # fn transition_cost(&self, _state: &Self::State, dec: Decision) -> isize {
/// # self.profit[dec.variable.id()] as isize * dec.value
/// # }
/// # fn next_variable(&self, depth: usize, _: &mut dyn Iterator<Item = &Self::State>) -> Option<Variable> {
/// # let n = self.nb_variables();
/// # if depth < n {
/// # Some(Variable(depth))
/// # } else {
/// # None
/// # }
/// # }
/// # fn for_each_in_domain(&self, variable: Variable, state: &Self::State, f: &mut dyn DecisionCallback)
/// # {
/// # if state.capacity >= self.weight[variable.id()] {
/// # f.apply(Decision { variable, value: TAKE_IT });
/// # f.apply(Decision { variable, value: LEAVE_IT_OUT });
/// # } else {
/// # f.apply(Decision { variable, value: LEAVE_IT_OUT });
/// # }
/// # }
/// # }
/// # struct KPRelax<'a>{pb: &'a Knapsack}
/// # impl Relaxation for KPRelax<'_> {
/// # type State = KnapsackState;
/// #
/// # fn merge(&self, states: &mut dyn Iterator<Item = &Self::State>) -> Self::State {
/// # states.max_by_key(|node| node.capacity).copied().unwrap()
/// # }
/// # fn relax(&self, _source: &Self::State, _dest: &Self::State, _merged: &Self::State, _decision: Decision, cost: isize) -> isize {
/// # cost
/// # }
/// # }
/// #
/// # struct KPRanking;
/// # impl StateRanking for KPRanking {
/// # type State = KnapsackState;
/// #
/// # fn compare(&self, a: &Self::State, b: &Self::State) -> std::cmp::Ordering {
/// # a.capacity.cmp(&b.capacity)
/// # }
/// # }
///
/// // To create a new solver, you need to be able to provide it with a problem instance, a relaxation
/// // and the various required heuristic. This example assumes the existence of the Knapsack structure
/// // and relaxation.
///
/// // 1. Create an instance of our knapsack problem
/// let problem = Knapsack {
/// capacity: 50,
/// profit : vec![60, 100, 120],
/// weight : vec![10, 20, 30]
/// };
///
/// // 2. Create a relaxation of the problem
/// let relaxation = KPRelax{pb: &problem};
///
/// // 3. Create a ranking to discriminate the promising and uninteresting states
/// let heuristic = KPRanking;
///
/// // 4. Define the policy you will want to use regarding the maximum width of the DD
/// let width = FixedWidth(100); // here we mean max 100 nodes per layer
///
/// // 5. Decide of a cutoff heuristic (if you dont want to let the solver run for ever)
/// let cutoff = NoCutoff; // might as well be a TimeBudget (or something else)
///
/// // 5. Create the solver fringe
/// let mut fringe = SimpleFringe::new(MaxUB::new(&heuristic));
///
/// // 6. Instanciate your solver
/// let mut solver = DefaultSolver::new(
/// &problem,
/// &relaxation,
/// &heuristic,
/// &width,
/// &cutoff,
/// &mut fringe);
///
/// // 7. Maximize your objective function
/// // the outcome provides the value of the best solution that was found for
/// // the problem (if one was found) along with a flag indicating whether or
/// // not the solution was proven optimal. Hence an unsatisfiable problem
/// // would have `outcome.best_value == None` and `outcome.is_exact` true.
/// // The `is_exact` flag will only be false if you explicitly decide to stop
/// // searching with an arbitrary cutoff.
/// let outcome = solver.maximize();
/// // The best solution (if one exist) is retrieved with
/// let solution = solver.best_solution();
///
/// // 8. Do whatever you like with the optimal solution.
/// assert_eq!(Some(220), outcome.best_value);
/// println!("Solution");
/// for decision in solution.unwrap().iter() {
/// if decision.value == 1 {
/// println!("{}", decision.variable.id());
/// }
/// }
/// ```
pub struct SequentialSolver<'a, State, D = DefaultMDDLEL<State>, B = EmptyBarrier<State>>
where D: DecisionDiagram<State = State> + Default,
B: Barrier<State = State> + Default,
{
/// A reference to the problem being solved with branch-and-bound MDD
problem: &'a (dyn Problem<State = State>),
/// The relaxation used when a DD layer grows too large
relaxation: &'a (dyn Relaxation<State = State>),
/// The ranking heuristic used to discriminate the most promising from
/// the least promising states
ranking: &'a (dyn StateRanking<State = State>),
/// The maximum width heuristic used to enforce a given maximum memory
/// usage when compiling mdds
width_heu: &'a (dyn WidthHeuristic<State>),
/// A cutoff heuristic meant to decide when to stop the resolution of
/// a given problem.
cutoff: &'a (dyn Cutoff),
/// This is the fringe: the set of nodes that must still be explored before
/// the problem can be considered 'solved'.
///
/// # Note:
/// This fringe orders the nodes by upper bound (so the highest ub is going
/// to pop first). So, it is guaranteed that the upper bound of the first
/// node being popped is an upper bound on the value reachable by exploring
/// any of the nodes remaining on the fringe. As a consequence, the
/// exploration can be stopped as soon as a node with an ub <= current best
/// lower bound is popped.
fringe: &'a mut (dyn Fringe<State = State>),
/// This is a counter that tracks the number of nodes that have effectively
/// been explored. That is, the number of nodes that have been popped from
/// the fringe, and for which a restricted and relaxed mdd have been developed.
explored: usize,
/// This is a counter of the number of nodes in the fringe, for each level of the model
open_by_layer: Vec<usize>,
/// This is the index of the first level above which there are no nodes in the fringe
first_active_layer: usize,
/// This is the value of the best known lower bound.
best_lb: isize,
/// This is the value of the best known upper bound.
best_ub: isize,
/// If set, this keeps the info about the best solution so far.
best_sol: Option<Vec<Decision>>,
/// If we decide not to go through a complete proof of optimality, this is
/// the reason why we took that decision.
abort_proof: Option<Reason>,
/// This is just a marker that allows us to remember the exact type of the
/// mdds to be instanciated.
mdd: D,
/// Data structure containing info about past compilations used to prune the search
barrier: B,
}
impl<'a, State, D, B> SequentialSolver<'a, State, D, B>
where
State: Eq + Hash + Clone,
D: DecisionDiagram<State = State> + Default,
B: Barrier<State = State> + Default,
{
pub fn new(
problem: &'a (dyn Problem<State = State>),
relaxation: &'a (dyn Relaxation<State = State>),
ranking: &'a (dyn StateRanking<State = State>),
width: &'a (dyn WidthHeuristic<State>),
cutoff: &'a (dyn Cutoff),
fringe: &'a mut (dyn Fringe<State = State>),
) -> Self {
Self::custom(problem, relaxation, ranking, width, cutoff, fringe)
}
pub fn custom(
problem: &'a (dyn Problem<State = State>),
relaxation: &'a (dyn Relaxation<State = State>),
ranking: &'a (dyn StateRanking<State = State>),
width_heu: &'a (dyn WidthHeuristic<State>),
cutoff: &'a (dyn Cutoff),
fringe: &'a mut (dyn Fringe<State = State>),
) -> Self {
SequentialSolver {
problem,
relaxation,
ranking,
width_heu,
cutoff,
//
best_sol: None,
best_lb: isize::MIN,
best_ub: isize::MAX,
fringe,
explored: 0,
open_by_layer: vec![0; problem.nb_variables() + 1],
first_active_layer: 0,
abort_proof: None,
mdd: D::default(),
barrier: B::default(),
}
}
/// This method initializes the problem resolution. Put more simply, this
/// method posts the root node of the mdd onto the fringe so that a thread
/// can pick it up and the processing can be bootstrapped.
fn initialize(&mut self) {
let root = self.root_node();
self.barrier.initialize(self.problem);
self.fringe.push(root);
self.open_by_layer[0] += 1;
}
fn root_node(&self) -> SubProblem<State> {
SubProblem {
state: Arc::new(self.problem.initial_state()),
value: self.problem.initial_value(),
path: vec![],
ub: isize::MAX,
depth: 0,
}
}
/// This method processes the given `node`. To do so, it reads the current
/// best lower bound from the critical data. Then it expands a restricted
/// and possibly a relaxed mdd rooted in `node`. If that is necessary,
/// it stores cutset nodes onto the fringe for further parallel processing.
fn process_one_node(
&mut self,
node: SubProblem<State>,
) -> Result<(), Reason> {
// 1. RESTRICTION
let node_ub = node.ub;
let best_lb = self.best_lb;
if node_ub <= best_lb {
return Ok(());
}
if !self.barrier.must_explore(&node) {
return Ok(());
}
let width = self.width_heu.max_width(&node);
let compilation = CompilationInput {
comp_type: CompilationType::Restricted,
max_width: width,
problem: self.problem,
relaxation: self.relaxation,
ranking: self.ranking,
cutoff: self.cutoff,
barrier: &self.barrier,
residual: &node,
//
best_lb,
};
let Completion{is_exact, ..} = self.mdd.compile(&compilation)?;
self.maybe_update_best();
if is_exact {
return Ok(());
}
// 2. RELAXATION
let best_lb = self.best_lb;
let compilation = CompilationInput {
comp_type: CompilationType::Relaxed,
max_width: width,
problem: self.problem,
relaxation: self.relaxation,
ranking: self.ranking,
cutoff: self.cutoff,
barrier: &self.barrier,
residual: &node,
//
best_lb,
};
let Completion{is_exact, ..} = self.mdd.compile(&compilation)?;
self.maybe_update_best();
if !is_exact {
self.enqueue_cutset(node_ub);
}
Ok(())
}
/// This private method updates the shared best known node and lower bound in
/// case the best value of the current `mdd` expansion improves the current
/// bounds.
fn maybe_update_best(&mut self) {
let dd_best_value = self.mdd.best_exact_value().unwrap_or(isize::MIN);
if dd_best_value > self.best_lb {
self.best_lb = dd_best_value;
self.best_sol = self.mdd.best_exact_solution();
}
}
/// If necessary, thightens the bound of nodes in the cutset of `mdd` and
/// then add the relevant nodes to the shared fringe.
fn enqueue_cutset(&mut self, ub: isize) {
let best_lb = self.best_lb;
let fringe = &mut self.fringe;
self.mdd.drain_cutset(|mut cutset_node| {
cutset_node.ub = ub.min(cutset_node.ub);
if cutset_node.ub > best_lb {
let depth = cutset_node.depth;
let before = fringe.len();
fringe.push(cutset_node);
let after = fringe.len();
self.open_by_layer[depth] += after - before;
}
});
}
fn abort_search(&mut self, reason: Reason) {
self.abort_proof = Some(reason);
self.fringe.clear();
self.barrier.clear();
}
/// Consults the shared state to fetch a workload. Depending on the current
/// state, the workload can either be:
///
/// + Complete, when the problem is solved and all threads should stop
/// + Starvation, when there is no subproblem available for processing
/// at the time being (but some subproblem are still being processed
/// and thus the problem cannot be considered solved).
/// + WorkItem, when the thread successfully obtained a subproblem to
/// process.
fn get_workload(&mut self) -> WorkLoad<State>
{
// Can we clean up the barrier?
while self.first_active_layer < self.problem.nb_variables() &&
self.open_by_layer[self.first_active_layer] == 0 {
self.barrier.clear_layer(self.first_active_layer);
self.first_active_layer += 1;
}
// Are we done ?
if self.fringe.is_empty() {
self.best_ub = self.best_lb;
return WorkLoad::Complete;
}
// Do we need to stop
if self.abort_proof.is_some() {
return WorkLoad::Aborted;
}
let nn = self.fringe.pop().unwrap();
// Consume the current node and process it
self.explored += 1;
self.open_by_layer[nn.depth] -= 1;
self.best_ub = nn.ub;
WorkLoad::WorkItem { node: nn }
}
}
impl<'a, State, D, B> Solver for SequentialSolver<'a, State, D, B>
where
State: Eq + PartialEq + Hash + Clone,
D: DecisionDiagram<State = State> + Default,
B: Barrier<State = State> + Default,
{
/// Applies the branch and bound algorithm proposed by Bergman et al. to
/// solve the problem to optimality. To do so, it spawns `nb_threads` workers
/// (long running threads); each of which will continually get a workload
/// and process it until the problem is solved.
fn maximize(&mut self) -> Completion {
self.initialize();
loop {
match self.get_workload() {
WorkLoad::Complete => break,
WorkLoad::Aborted => break, // this one cannot occur
WorkLoad::WorkItem { node } => {
let outcome = self.process_one_node(node);
if let Err(reason) = outcome {
self.abort_search(reason);
break;
}
}
}
}
if let Some(sol) = self.best_sol.as_mut() { sol.sort_unstable_by_key(|d| d.variable.0) }
Completion { is_exact: self.abort_proof.is_none(), best_value: self.best_sol.as_ref().map(|_| self.best_lb) }
}
/// Returns the best solution that has been identified for this problem.
fn best_solution(&self) -> Option<Vec<Decision>> {
self.best_sol.clone()
}
/// Returns the value of the best solution that has been identified for
/// this problem.
fn best_value(&self) -> Option<isize> {
self.best_sol.as_ref().map(|_sol| self.best_lb)
}
/// Returns the value of the best lower bound that has been identified for
/// this problem.
fn best_lower_bound(&self) -> isize {
self.best_lb
}
/// Returns the value of the best upper bound that has been identified for
/// this problem.
fn best_upper_bound(&self) -> isize {
self.best_ub
}
/// Sets a primal (best known value and solution) of the problem.
fn set_primal(&mut self, value: isize, solution: Solution) {
if value > self.best_lb {
self.best_sol = Some(solution);
self.best_lb = value;
}
}
}
// ############################################################################
// #### TESTS #################################################################
// ############################################################################
/// Unlike the rest of the library, the solvers modules are not tested in depth
/// with unit tests (this is way too hard to do even for the sequential module).
/// So we basically unit test the configuration capabilities of the solvers
/// and then resort to the solving of benchmark instances (see examples) with
/// known optimum solution to validate the behavior of the maximize function.
#[cfg(test)]
mod test_solver {
use crate::*;
type SeqSolver<'a, T> = SequentialSolver<'a, T, DefaultMDDLEL<T>, EmptyBarrier<T>>;
type SeqBarrierSolver<'a, T> = SequentialSolver<'a, T, DefaultMDDFC<T>, SimpleBarrier<T>>;
#[test]
fn by_default_best_lb_is_min_infinity() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert_eq!(isize::min_value(), solver.best_lower_bound());
}
#[test]
fn by_default_best_ub_is_plus_infinity() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert_eq!(isize::max_value(), solver.best_upper_bound());
}
#[test]
fn when_the_problem_is_solved_best_lb_is_best_value() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let _ = solver.maximize();
assert_eq!(220, solver.best_lower_bound());
}
#[test]
fn when_the_problem_is_solved_best_ub_is_best_value() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let _ = solver.maximize();
assert_eq!(220, solver.best_upper_bound());
}
#[test]
fn no_solution_before_solving() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert!(solver.best_sol.is_none());
}
#[test]
fn empty_fringe_before_solving() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert!(solver.fringe.is_empty());
}
#[test]
fn default_best_lb_is_neg_infinity() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert_eq!(isize::min_value(), solver.best_lb);
}
#[test]
fn default_best_ub_is_pos_infinity() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert_eq!(isize::max_value(), solver.best_ub);
}
#[test]
fn maximizes_yields_the_optimum_1a() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::custom(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let maximized = solver.maximize();
assert!(maximized.is_exact);
assert_eq!(maximized.best_value, Some(220));
assert!(solver.best_solution().is_some());
let mut sln = solver.best_solution().unwrap();
sln.sort_unstable_by_key(|d| d.variable.id());
assert_eq!(sln, vec![
Decision{variable: Variable(0), value: 0},
Decision{variable: Variable(1), value: 1},
Decision{variable: Variable(2), value: 1},
]);
}
#[test]
fn maximizes_yields_the_optimum_1b() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqBarrierSolver::custom(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let maximized = solver.maximize();
assert!(maximized.is_exact);
assert_eq!(maximized.best_value, Some(220));
assert!(solver.best_solution().is_some());
let mut sln = solver.best_solution().unwrap();
sln.sort_unstable_by_key(|d| d.variable.id());
assert_eq!(sln, vec![
Decision{variable: Variable(0), value: 0},
Decision{variable: Variable(1), value: 1},
Decision{variable: Variable(2), value: 1},
]);
}
#[test]
fn maximizes_yields_the_optimum_2a() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 210, 12, 5, 100, 120, 110],
weight : vec![10, 45, 20, 4, 20, 30, 50]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let maximized = solver.maximize();
assert!(maximized.is_exact);
assert_eq!(maximized.best_value, Some(220));
assert!(solver.best_solution().is_some());
let mut sln = solver.best_solution().unwrap();
sln.sort_unstable_by_key(|d| d.variable.id());
assert_eq!(sln, vec![
Decision { variable: Variable(0), value: 0 },
Decision { variable: Variable(1), value: 0 },
Decision { variable: Variable(2), value: 0 },
Decision { variable: Variable(3), value: 0 },
Decision { variable: Variable(4), value: 1 },
Decision { variable: Variable(5), value: 1 },
Decision { variable: Variable(6), value: 0 }
]);
}
#[test]
fn maximizes_yields_the_optimum_2b() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 210, 12, 5, 100, 120, 110],
weight : vec![10, 45, 20, 4, 20, 30, 50]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqBarrierSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let maximized = solver.maximize();
assert!(maximized.is_exact);
assert_eq!(maximized.best_value, Some(220));
assert!(solver.best_solution().is_some());
let mut sln = solver.best_solution().unwrap();
sln.sort_unstable_by_key(|d| d.variable.id());
assert_eq!(sln, vec![
Decision { variable: Variable(0), value: 0 },
Decision { variable: Variable(1), value: 0 },
Decision { variable: Variable(2), value: 0 },
Decision { variable: Variable(3), value: 0 },
Decision { variable: Variable(4), value: 1 },
Decision { variable: Variable(5), value: 1 },
Decision { variable: Variable(6), value: 0 }
]);
}
#[test]
fn set_primal_overwrites_best_value_and_sol_if_it_improves() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let d1 = Decision{variable: Variable(0), value: 10};
let sol = vec![d1];
solver.set_primal(10, sol.clone());
assert!(solver.best_sol.is_some());
assert_eq!(10, solver.best_lb);
// in this case, it wont update because there is no improvement
solver.set_primal(5, sol.clone());
assert!(solver.best_sol.is_some());
assert_eq!(10, solver.best_lb);
// but here, it will update as it improves the best known sol
solver.set_primal(10000, sol);
assert!(solver.best_sol.is_some());
assert_eq!(10000, solver.best_lb);
// it wont do much as the primal is better than the actual feasible solution
let maximized = solver.maximize();
assert!(maximized.is_exact);
assert_eq!(maximized.best_value, Some(10000));
assert!(solver.best_solution().is_some());
}
#[test]
fn when_no_solution_is_found_the_gap_is_one() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
assert_eq!(1.0, solver.gap());
}
#[test]
fn when_optimum_solution_is_found_the_gap_is_zero() {
let problem = Knapsack {
capacity: 50,
profit : vec![60, 100, 120],
weight : vec![10, 20, 30]
};
let relax = KPRelax {pb: &problem};
let ranking = KPRanking;
let cutoff = NoCutoff;
let width = NbUnassignedWitdh(problem.nb_variables());
let mut fringe = SimpleFringe::new(MaxUB::new(&ranking));
let mut solver = SeqSolver::new(
&problem,
&relax,
&ranking,
&width,
&cutoff,
&mut fringe,
);
let Completion{is_exact, best_value} = solver.maximize();
assert!(is_exact);
assert!(best_value.is_some());
assert_eq!(0.0, solver.gap());
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct KnapsackState {
depth: usize,
capacity: usize
}
struct Knapsack {
capacity: usize,
profit: Vec<usize>,
weight: Vec<usize>,
}
const TAKE_IT: isize = 1;
const LEAVE_IT_OUT: isize = 0;
impl Problem for Knapsack {
type State = KnapsackState;
fn nb_variables(&self) -> usize {
self.profit.len()
}
fn initial_state(&self) -> Self::State {
KnapsackState{ depth: 0, capacity: self.capacity }
}
fn initial_value(&self) -> isize {
0
}
fn transition(&self, state: &Self::State, dec: Decision) -> Self::State {
let mut ret = *state;
ret.depth += 1;
if dec.value == TAKE_IT {
ret.capacity -= self.weight[dec.variable.id()]
}
ret
}
fn transition_cost(&self, _state: &Self::State, dec: Decision) -> isize {
self.profit[dec.variable.id()] as isize * dec.value
}
fn next_variable(&self, depth: usize, _: &mut dyn Iterator<Item = &Self::State>) -> Option<Variable> {
let n = self.nb_variables();
if depth < n {
Some(Variable(depth))
} else {
None
}
}
fn for_each_in_domain(&self, variable: Variable, state: &Self::State, f: &mut dyn DecisionCallback)
{
if state.capacity >= self.weight[variable.id()] {
f.apply(Decision { variable, value: TAKE_IT });
f.apply(Decision { variable, value: LEAVE_IT_OUT });
} else {
f.apply(Decision { variable, value: LEAVE_IT_OUT });
}
}
}
struct KPRelax<'a>{pb: &'a Knapsack}
impl Relaxation for KPRelax<'_> {
type State = KnapsackState;
fn merge(&self, states: &mut dyn Iterator<Item = &Self::State>) -> Self::State {
states.max_by_key(|node| node.capacity).copied().unwrap()
}
fn relax(&self, _source: &Self::State, _dest: &Self::State, _merged: &Self::State, _decision: Decision, cost: isize) -> isize {
cost
}
fn fast_upper_bound(&self, state: &Self::State) -> isize {
let mut tot = 0;
for var in state.depth..self.pb.nb_variables() {
if self.pb.weight[var] <= state.capacity {
tot += self.pb.profit[var];
}
}
tot as isize
}
}
struct KPRanking;
impl StateRanking for KPRanking {
type State = KnapsackState;
fn compare(&self, a: &Self::State, b: &Self::State) -> std::cmp::Ordering {
a.capacity.cmp(&b.capacity)
}
}
}