Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Comment: | Remove explicit lifetime from `FirstOrderOracle` |
|---|---|
| Downloads: | Tarball | ZIP archive |
| Timelines: | family | ancestors | descendants | both | error-handling |
| Files: | files | file ages | folders |
| SHA1: |
0b6fbe2b3049269a9d9c48fda6322ff0 |
| User & Date: | fifr 2018-06-26 13:46:51.775 |
Context
|
2018-06-26
| ||
| 14:42 | Remove failure from Cargo.toml check-in: ea0a95ce11 user: fifr tags: error-handling | |
| 13:46 | Remove explicit lifetime from `FirstOrderOracle` check-in: 0b6fbe2b30 user: fifr tags: error-handling | |
| 13:42 | Reformat sources check-in: e57323235c user: fifr tags: error-handling | |
Changes
Changes to examples/quadratic.rs.
| ︙ | ︙ | |||
37 38 39 40 41 42 43 |
a: [[5.0, 1.0], [1.0, 4.0]],
b: [-12.0, -10.0],
c: 3.0,
}
}
}
| | | | 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 |
a: [[5.0, 1.0], [1.0, 4.0]],
b: [-12.0, -10.0],
c: 3.0,
}
}
}
impl FirstOrderProblem for QuadraticProblem {
type Err = Box<dyn Error>;
type Primal = ();
type EvalResult = SimpleEvaluation<()>;
fn num_variables(&self) -> usize {
2
}
#[allow(unused_variables)]
fn evaluate(
&mut self,
fidx: usize,
x: &[Real],
nullstep_bnd: Real,
relprec: Real,
) -> Result<Self::EvalResult, Self::Err> {
assert_eq!(fidx, 0);
let mut objective = self.c;
|
| ︙ | ︙ |
Changes to src/firstorderproblem.rs.
| ︙ | ︙ | |||
81 82 83 84 85 86 87 |
MoveVariable { index: usize, value: Real },
}
/**
* Trait for implementing a first-order problem description.
*
*/
| | | 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 |
MoveVariable { index: usize, value: Real },
}
/**
* Trait for implementing a first-order problem description.
*
*/
pub trait FirstOrderProblem {
/// Error raised by this oracle.
type Err;
/// The primal information associated with a minorant.
type Primal;
/// Custom evaluation result value.
|
| ︙ | ︙ | |||
143 144 145 146 147 148 149 |
* otherwise the returned objective should be the maximum of all
* linear minorants at $y$.
*
* Note that `nullstep_bound` and `relprec` are usually only
* useful if there is only a `single` subproblem.
*/
fn evaluate(
| | | 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 |
* otherwise the returned objective should be the maximum of all
* linear minorants at $y$.
*
* Note that `nullstep_bound` and `relprec` are usually only
* useful if there is only a `single` subproblem.
*/
fn evaluate(
&mut self,
i: usize,
y: &[Real],
nullstep_bound: Real,
relprec: Real,
) -> Result<Self::EvalResult, Self::Err>;
/// Aggregate primal information.
|
| ︙ | ︙ |
Changes to src/mcf/problem.rs.
| ︙ | ︙ | |||
217 218 219 220 221 222 223 |
}
}
aggr
}
}
| | | 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 |
}
}
aggr
}
}
impl FirstOrderProblem for MMCFProblem {
type Err = Box<dyn Error>;
type Primal = Vec<DVector>;
type EvalResult = SimpleEvaluation<Vec<DVector>>;
fn num_variables(&self) -> usize {
|
| ︙ | ︙ | |||
245 246 247 248 249 250 251 |
self.nets.len()
} else {
1
}
}
#[allow(unused_variables)]
| < < < < < < | | 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 |
self.nets.len()
} else {
1
}
}
#[allow(unused_variables)]
fn evaluate(&mut self, fidx: usize, y: &[Real], nullstep_bound: Real, relprec: Real) -> Result<Self::EvalResult> {
// compute costs
self.rhsval = 0.0;
for i in 0..self.c.len() {
self.c[i].clear();
self.c[i].extend(self.cbase[i].iter());
}
|
| ︙ | ︙ |
Changes to src/solver.rs.
| ︙ | ︙ | |||
371 372 373 374 375 376 377 |
self.minorants[fidx].last().and_then(|m| m.primal.as_ref())
}
}
/**
* Implementation of a bundle method.
*/
| | < < < < | 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 |
self.minorants[fidx].last().and_then(|m| m.primal.as_ref())
}
}
/**
* Implementation of a bundle method.
*/
pub struct Solver<P: FirstOrderProblem> {
/// The first order problem description.
problem: P,
/// The solver parameter.
pub params: SolverParams,
/// Termination predicate.
|
| ︙ | ︙ | |||
458 459 460 461 462 463 464 |
*/
start_time: Instant,
/// The master problem.
master: Box<MasterProblem<MinorantIndex = usize>>,
/// The active minorant indices for each subproblem.
| | < < | < < | | 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 |
*/
start_time: Instant,
/// The master problem.
master: Box<MasterProblem<MinorantIndex = usize>>,
/// The active minorant indices for each subproblem.
minorants: Vec<Vec<MinorantInfo<P::Primal>>>,
/// Accumulated information about the last iteration.
iterinfos: Vec<IterationInfo>,
}
impl<P: FirstOrderProblem> Solver<P> {
/**
* Create a new solver for the given problem.
*
* Note that the solver owns the problem, so you cannot use the
* same problem description elsewhere as long as it is assigned to
* the solver. However, it is possible to get a reference to the
* internally stored problem using `Solver::problem()`.
*/
pub fn new_params(problem: P, params: SolverParams) -> Result<Solver<P>, SolverError<P::Err>> {
Ok(Solver {
problem,
params,
terminator: Box::new(StandardTerminator {
termination_precision: 1e-3,
}),
weighter: Box::new(HKWeighter::new()),
|
| ︙ | ︙ | |||
513 514 515 516 517 518 519 |
)),
minorants: vec![],
iterinfos: vec![],
})
}
/// A new solver with default parameter.
| | | 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 |
)),
minorants: vec![],
iterinfos: vec![],
})
}
/// A new solver with default parameter.
pub fn new(problem: P) -> Result<Solver<P>, SolverError<P::Err>> {
Solver::new_params(problem, SolverParams::default())
}
/**
* Set the first order problem description associated with this
* solver.
*
|
| ︙ | ︙ | |||
536 537 538 539 540 541 542 |
/// Returns a reference to the solver's current problem.
pub fn problem(&self) -> &P {
&self.problem
}
/// Initialize the solver.
| | | 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 |
/// Returns a reference to the solver's current problem.
pub fn problem(&self) -> &P {
&self.problem
}
/// Initialize the solver.
pub fn init(&mut self) -> Result<(), SolverError<P::Err>> {
self.params.check()?;
if self.cur_y.len() != self.problem.num_variables() {
self.cur_valid = false;
self.cur_y.init0(self.problem.num_variables());
}
let lb = self.problem.lower_bounds();
|
| ︙ | ︙ | |||
578 579 580 581 582 583 584 |
self.start_time = Instant::now();
Ok(())
}
/// Solve the problem.
| | | | | 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 |
self.start_time = Instant::now();
Ok(())
}
/// Solve the problem.
pub fn solve(&mut self) -> Result<(), SolverError<P::Err>> {
const LIMIT: usize = 10_000;
if self.solve_iter(LIMIT)? {
Ok(())
} else {
Err(SolverError::IterationLimit { limit: LIMIT })
}
}
/// Solve the problem but stop after `niter` iterations.
///
/// The function returns `Ok(true)` if the termination criterion
/// has been satisfied. Otherwise it returns `Ok(false)` or an
/// error code.
///
/// If this function is called again, the solution process is
/// continued from the previous point. Because of this one must
/// call `init()` before the first call to this function.
pub fn solve_iter(&mut self, niter: usize) -> Result<bool, SolverError<P::Err>> {
for _ in 0..niter {
let mut term = self.step()?;
let changed = self.update_problem(term)?;
// do not stop if the problem has been changed
if changed && term == Step::Term {
term = Step::Null
}
self.show_info(term);
if term == Step::Term {
return Ok(true);
}
}
Ok(false)
}
/// Called to update the problem.
///
/// Calling this function typically triggers the problem to
/// separate new constraints depending on the current solution.
fn update_problem(&mut self, term: Step) -> Result<bool, SolverError<P::Err>> {
let updates = {
let state = UpdateState {
minorants: &self.minorants,
step: term,
iteration_info: &self.iterinfos,
// this is a dirty trick: when updating the center, we
// simply swapped the `cur_*` fields with the `nxt_*`
|
| ︙ | ︙ | |||
720 721 722 723 724 725 726 |
/// Return the current aggregated primal information for a subproblem.
///
/// This function returns all currently used minorants $x_i$ along
/// with their coefficients $\alpha_i$. The aggregated primal can
/// be computed by combining the minorants $\bar{x} =
/// \sum_{i=1}\^m \alpha_i x_i$.
| | | 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 |
/// Return the current aggregated primal information for a subproblem.
///
/// This function returns all currently used minorants $x_i$ along
/// with their coefficients $\alpha_i$. The aggregated primal can
/// be computed by combining the minorants $\bar{x} =
/// \sum_{i=1}\^m \alpha_i x_i$.
pub fn aggregated_primals(&self, subproblem: usize) -> Vec<(Real, &P::Primal)> {
self.minorants[subproblem]
.iter()
.map(|m| (m.multiplier, m.primal.as_ref().unwrap()))
.collect()
}
fn show_info(&self, step: Step) {
|
| ︙ | ︙ | |||
766 767 768 769 770 771 772 |
/**
* Initializes the master problem.
*
* The oracle is evaluated once at the initial center and the
* master problem is initialized with the returned subgradient
* information.
*/
| | | 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 |
/**
* Initializes the master problem.
*
* The oracle is evaluated once at the initial center and the
* master problem is initialized with the returned subgradient
* information.
*/
fn init_master(&mut self) -> Result<(), SolverError<P::Err>> {
let m = self.problem.num_subproblems();
self.master = if m == 1 && self.params.max_bundle_size == 2 {
debug!("Use minimal master problem");
Box::new(BoxedMasterProblem::new(
MinimalMaster::new().map_err(SolverError::Master)?,
))
|
| ︙ | ︙ | |||
857 858 859 860 861 862 863 |
debug!("Init master completed");
Ok(())
}
/// Solve the model (i.e. master problem) to compute the next candidate.
| | | 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 |
debug!("Init master completed");
Ok(())
}
/// Solve the model (i.e. master problem) to compute the next candidate.
fn solve_model(&mut self) -> Result<(), SolverError<P::Err>> {
self.master.solve(self.cur_val).map_err(SolverError::Master)?;
self.nxt_d = self.master.get_primopt();
self.nxt_y.add(&self.cur_y, &self.nxt_d);
self.nxt_mod = self.master.get_primoptval();
self.sgnorm = self.master.get_dualoptnorm2().sqrt();
self.expected_progress = self.cur_val - self.nxt_mod;
|
| ︙ | ︙ | |||
880 881 882 883 884 885 886 |
debug!(" cur_val ={}", self.cur_val);
debug!(" nxt_mod ={}", self.nxt_mod);
debug!(" expected={}", self.expected_progress);
Ok(())
}
/// Reduce size of bundle.
| | | 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 |
debug!(" cur_val ={}", self.cur_val);
debug!(" nxt_mod ={}", self.nxt_mod);
debug!(" expected={}", self.expected_progress);
Ok(())
}
/// Reduce size of bundle.
fn compress_bundle(&mut self) -> Result<(), SolverError<P::Err>> {
for i in 0..self.problem.num_subproblems() {
let n = self.master.num_minorants(i);
if n >= self.params.max_bundle_size {
// aggregate minorants with smallest coefficients
self.minorants[i].sort_by_key(|m| -((1e6 * m.multiplier) as isize));
let aggr = self.minorants[i].split_off(self.params.max_bundle_size - 2);
let aggr_sum = aggr.iter().map(|m| m.multiplier).sum();
|
| ︙ | ︙ | |||
906 907 908 909 910 911 912 |
});
}
}
Ok(())
}
/// Perform a descent step.
| | | | | 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 |
});
}
}
Ok(())
}
/// Perform a descent step.
fn descent_step(&mut self) -> Result<(), SolverError<P::Err>> {
let new_weight = self.weighter.weight(¤t_state!(self, Step::Descent), &self.params);
self.master.set_weight(new_weight).map_err(SolverError::Master)?;
self.cnt_descent += 1;
swap(&mut self.cur_y, &mut self.nxt_y);
swap(&mut self.cur_val, &mut self.nxt_val);
swap(&mut self.cur_mod, &mut self.nxt_mod);
swap(&mut self.cur_vals, &mut self.nxt_vals);
swap(&mut self.cur_mods, &mut self.nxt_mods);
self.master.move_center(1.0, &self.nxt_d);
debug!("Descent Step");
debug!(" dir ={}", self.nxt_d);
debug!(" newy={}", self.cur_y);
Ok(())
}
/// Perform a null step.
fn null_step(&mut self) -> Result<(), SolverError<P::Err>> {
let new_weight = self.weighter.weight(¤t_state!(self, Step::Null), &self.params);
self.master.set_weight(new_weight).map_err(SolverError::Master)?;
self.cnt_null += 1;
debug!("Null Step");
Ok(())
}
/// Perform one bundle iteration.
#[cfg_attr(feature = "cargo-clippy", allow(collapsible_if))]
pub fn step(&mut self) -> Result<Step, SolverError<P::Err>> {
self.iterinfos.clear();
if !self.cur_valid {
// current point needs new evaluation
self.init_master()?;
}
|
| ︙ | ︙ |