Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Comment: | Simplify error handling (again) by using boxed errors |
|---|---|
| Downloads: | Tarball | ZIP archive |
| Timelines: | family | ancestors | descendants | both | async |
| Files: | files | file ages | folders |
| SHA1: |
b6b5c1ec21b4c3551d5b9a0795b65908 |
| User & Date: | fifr 2019-07-17 15:38:30.292 |
Context
|
2019-07-17
| ||
| 15:38 | Fix error handling in cflp example check-in: 4964ff1e06 user: fifr tags: async | |
| 15:38 | Simplify error handling (again) by using boxed errors check-in: b6b5c1ec21 user: fifr tags: async | |
| 14:41 | solver: make master problem a type argument check-in: 6186a4f7ed user: fifr tags: async | |
Changes
Changes to src/master/base.rs.
| ︙ | ︙ | |||
18 19 20 21 22 23 24 | use std::error::Error; use std::fmt; use std::result; /// Error type for master problems. #[derive(Debug)] | | | | < < < | < < < | | | > < < < | | < < < | < < | | | | | < < < < | < < < < | | 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 |
use std::error::Error;
use std::fmt;
use std::result;
/// Error type for master problems.
#[derive(Debug)]
pub enum MasterProblemError {
/// Extension of the subgradient failed with some user error.
SubgradientExtension(Box<dyn Error + Send + Sync>),
/// No minorants available when solving the master problem
NoMinorants,
/// An error in the solver backend occurred.
Solver(Box<dyn Error + Send + Sync>),
/// A custom error (specific to the master problem solver) occurred.
Custom(Box<dyn Error + Send + Sync>),
}
impl fmt::Display for MasterProblemError {
fn fmt(&self, fmt: &mut fmt::Formatter) -> result::Result<(), fmt::Error> {
use self::MasterProblemError::*;
match self {
SubgradientExtension(err) => write!(fmt, "Subgradient extension failed: {}", err),
NoMinorants => write!(fmt, "No minorants when solving the master problem"),
Solver(err) => write!(fmt, "Solver error: {}", err),
Custom(err) => err.fmt(fmt),
}
}
}
impl Error for MasterProblemError {
fn source(&self) -> Option<&(dyn Error + 'static)> {
use self::MasterProblemError::*;
match self {
SubgradientExtension(err) => Some(err.as_ref()),
Solver(err) | Custom(err) => Some(err.as_ref()),
NoMinorants => None,
}
}
}
/// Result type of master problems.
pub type Result<T> = result::Result<T, MasterProblemError>;
/// Callback for subgradient extensions.
pub type SubgradientExtension<'a, I> =
FnMut(usize, I, &[usize]) -> result::Result<DVector, Box<dyn Error + Send + Sync + 'static>> + 'a;
pub trait MasterProblem {
/// Unique index for a minorant.
type MinorantIndex: Copy + Eq;
/// Create a new master problem.
fn new() -> Result<Self>
where
Self: Sized;
/// Set the number of subproblems.
fn set_num_subproblems(&mut self, n: usize) -> Result<()>;
/// Set the lower and upper bounds of the variables.
fn set_vars(&mut self, nvars: usize, lb: Option<DVector>, ub: Option<DVector>) -> Result<()>;
/// Return the current number of minorants of subproblem `fidx`.
fn num_minorants(&self, fidx: usize) -> usize;
/// Return the current weight of the quadratic term.
fn weight(&self) -> Real;
/// Set the weight of the quadratic term, must be > 0.
fn set_weight(&mut self, weight: Real) -> Result<()>;
/// Set the maximal number of inner iterations.
fn set_max_updates(&mut self, max_updates: usize) -> Result<()>;
/// Return the current number of inner iterations.
fn cnt_updates(&self) -> usize;
/// Add or move some variables with bounds.
///
/// If an index is specified, existing variables are moved,
/// otherwise new variables are generated.
fn add_vars(
&mut self,
bounds: &[(Option<usize>, Real, Real)],
extend_subgradient: &mut SubgradientExtension<Self::MinorantIndex>,
) -> Result<()>;
/// Add a new minorant to the model.
///
/// The function returns a unique (among all minorants of all
/// subproblems) index of the minorant. This index must remain
/// valid until the minorant is aggregated.
fn add_minorant(&mut self, fidx: usize, minorant: Minorant) -> Result<Self::MinorantIndex>;
/// Solve the master problem.
fn solve(&mut self, cur_value: Real) -> Result<()>;
/// Aggregate the given minorants according to the current
/// solution.
///
/// The (indices of the) minorants to be aggregated get invalid
/// after this operation. The function returns the index of the
/// aggregated minorant along with the coefficients of the convex
/// combination. The index of the new aggregated minorant might or
/// might not be one of indices of the original minorants.
///
/// # Error The indices of the minorants `mins` must belong to
/// subproblem `fidx`.
fn aggregate(&mut self, fidx: usize, mins: &[usize]) -> Result<(Self::MinorantIndex, DVector)>;
/// Return the (primal) optimal solution $\\|d\^*\\|$.
fn get_primopt(&self) -> DVector;
/// Return the value of the linear model in the optimal solution.
///
/// This is the term $\langle g\^*, d\^* \rangle$ where $g^\*$ is
|
| ︙ | ︙ |
Changes to src/master/boxed.rs.
| ︙ | ︙ | |||
76 77 78 79 80 81 82 |
max_updates: 100,
cnt_updates: 0,
need_new_candidate: true,
master,
}
}
| | | 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
max_updates: 100,
cnt_updates: 0,
need_new_candidate: true,
master,
}
}
pub fn set_max_updates(&mut self, max_updates: usize) -> Result<()> {
assert!(max_updates > 0);
self.max_updates = max_updates;
Ok(())
}
/**
* Update box multipliers $\eta$.
|
| ︙ | ︙ | |||
181 182 183 184 185 186 187 |
impl<M> MasterProblem for BoxedMasterProblem<M>
where
M: UnconstrainedMasterProblem,
{
type MinorantIndex = M::MinorantIndex;
| < < | | < < < | < < | < < < < | | | | | 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 |
impl<M> MasterProblem for BoxedMasterProblem<M>
where
M: UnconstrainedMasterProblem,
{
type MinorantIndex = M::MinorantIndex;
fn new() -> Result<Self> {
M::new().map(BoxedMasterProblem::with_master)
}
fn set_num_subproblems(&mut self, n: usize) -> Result<()> {
self.master.set_num_subproblems(n)
}
fn set_vars(&mut self, n: usize, lb: Option<DVector>, ub: Option<DVector>) -> Result<()> {
assert_eq!(lb.as_ref().map(|x| x.len()).unwrap_or(n), n);
assert_eq!(ub.as_ref().map(|x| x.len()).unwrap_or(n), n);
self.lb = lb.unwrap_or_else(|| dvec![NEG_INFINITY; n]);
self.ub = ub.unwrap_or_else(|| dvec![INFINITY; n]);
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.master.num_minorants(fidx)
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant) -> Result<Self::MinorantIndex> {
self.master.add_minorant(fidx, minorant)
}
fn weight(&self) -> Real {
self.master.weight()
}
fn set_weight(&mut self, weight: Real) -> Result<()> {
self.master.set_weight(weight)
}
fn add_vars(
&mut self,
bounds: &[(Option<usize>, Real, Real)],
extend_subgradient: &mut SubgradientExtension<Self::MinorantIndex>,
) -> Result<()> {
if !bounds.is_empty() {
for (index, l, u) in bounds.iter().filter_map(|v| v.0.map(|i| (i, v.1, v.2))) {
self.lb[index] = l;
self.ub[index] = u;
}
self.lb.extend(bounds.iter().filter(|v| v.0.is_none()).map(|x| x.1));
self.ub.extend(bounds.iter().filter(|v| v.0.is_none()).map(|x| x.2));
self.eta.resize(self.lb.len(), 0.0);
self.need_new_candidate = true;
let nnew = bounds.iter().filter(|v| v.0.is_none()).count();
let changed = bounds.iter().filter_map(|v| v.0).collect::<Vec<_>>();
self.master.add_vars(nnew, &changed, extend_subgradient)
} else {
Ok(())
}
}
#[allow(clippy::cognitive_complexity)]
fn solve(&mut self, center_value: Real) -> Result<()> {
debug!("Solve Master");
debug!(" lb ={}", self.lb);
debug!(" ub ={}", self.ub);
if self.need_new_candidate {
self.compute_candidate();
}
|
| ︙ | ︙ | |||
324 325 326 327 328 329 330 |
debug!(" dualopt={}", self.master.dualopt());
debug!(" etaopt={}", self.eta);
debug!(" primoptval={}", self.primoptval);
Ok(())
}
| < < < < | | 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 |
debug!(" dualopt={}", self.master.dualopt());
debug!(" etaopt={}", self.eta);
debug!(" primoptval={}", self.primoptval);
Ok(())
}
fn aggregate(&mut self, fidx: usize, mins: &[usize]) -> Result<(Self::MinorantIndex, DVector)> {
self.master.aggregate(fidx, mins)
}
fn get_primopt(&self) -> DVector {
self.primopt.clone()
}
|
| ︙ | ︙ | |||
355 356 357 358 359 360 361 |
fn move_center(&mut self, alpha: Real, d: &DVector) {
self.need_new_candidate = true;
self.master.move_center(alpha, d);
self.lb.add_scaled(-alpha, d);
self.ub.add_scaled(-alpha, d);
}
| | | 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 |
fn move_center(&mut self, alpha: Real, d: &DVector) {
self.need_new_candidate = true;
self.master.move_center(alpha, d);
self.lb.add_scaled(-alpha, d);
self.ub.add_scaled(-alpha, d);
}
fn set_max_updates(&mut self, max_updates: usize) -> Result<()> {
BoxedMasterProblem::set_max_updates(self, max_updates)
}
fn cnt_updates(&self) -> usize {
self.cnt_updates
}
}
|
Changes to src/master/cpx.rs.
| ︙ | ︙ | |||
26 27 28 29 30 31 32 |
use c_str_macro::c_str;
use cplex_sys as cpx;
use cplex_sys::trycpx;
use log::debug;
use std;
use std::f64::{self, NEG_INFINITY};
| < | | | | 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
use c_str_macro::c_str;
use cplex_sys as cpx;
use cplex_sys::trycpx;
use log::debug;
use std;
use std::f64::{self, NEG_INFINITY};
use std::os::raw::{c_char, c_int};
use std::ptr;
impl From<cpx::CplexError> for MasterProblemError {
fn from(err: cpx::CplexError) -> MasterProblemError {
MasterProblemError::Solver(Box::new(err))
}
}
pub struct CplexMaster {
lp: *mut cpx::Lp,
/// True if the QP must be updated.
force_update: bool,
/// List of free minorant indices.
freeinds: Vec<usize>,
|
| ︙ | ︙ | |||
66 67 68 69 70 71 72 |
/// The minorants for each subproblem in the model.
minorants: Vec<Vec<Minorant>>,
/// Optimal multipliers for each subproblem in the model.
opt_mults: Vec<DVector>,
/// Optimal aggregated minorant.
opt_minorant: Minorant,
| | < | < | | < < | < | | | | 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 |
/// The minorants for each subproblem in the model.
minorants: Vec<Vec<Minorant>>,
/// Optimal multipliers for each subproblem in the model.
opt_mults: Vec<DVector>,
/// Optimal aggregated minorant.
opt_minorant: Minorant,
}
impl Drop for CplexMaster {
fn drop(&mut self) {
unsafe { cpx::freeprob(cpx::env(), &mut self.lp) };
}
}
impl UnconstrainedMasterProblem for CplexMaster {
type MinorantIndex = usize;
fn new() -> Result<CplexMaster> {
Ok(CplexMaster {
lp: ptr::null_mut(),
force_update: true,
freeinds: vec![],
updateinds: vec![],
min2index: vec![],
index2min: vec![],
qterm: vec![],
weight: 1.0,
minorants: vec![],
opt_mults: vec![],
opt_minorant: Minorant::default(),
})
}
fn num_subproblems(&self) -> usize {
self.minorants.len()
}
fn set_num_subproblems(&mut self, n: usize) -> Result<()> {
trycpx!(cpx::setintparam(
cpx::env(),
cpx::Param::Qpmethod.to_c(),
cpx::Alg::Barrier.to_c()
));
trycpx!(cpx::setdblparam(cpx::env(), cpx::Param::Barepcomp.to_c(), 1e-12));
self.min2index = vec![vec![]; n];
self.index2min.clear();
self.freeinds.clear();
self.minorants = vec![vec![]; n];
self.opt_mults = vec![dvec![]; n];
Ok(())
}
fn weight(&self) -> Real {
self.weight
}
fn set_weight(&mut self, weight: Real) -> Result<()> {
assert!(weight > 0.0);
self.weight = weight;
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.minorants[fidx].len()
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant) -> Result<usize> {
debug!("Add minorant");
debug!(" fidx={} index={}: {}", fidx, self.minorants[fidx].len(), minorant);
let min_idx = self.minorants[fidx].len();
self.minorants[fidx].push(minorant);
self.opt_mults[fidx].push(0.0);
|
| ︙ | ︙ | |||
161 162 163 164 165 166 167 |
}
}
fn add_vars(
&mut self,
nnew: usize,
changed: &[usize],
| | | | 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
}
}
fn add_vars(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtension<Self::MinorantIndex>,
) -> Result<()> {
debug_assert!(!self.minorants[0].is_empty());
let noldvars = self.minorants[0][0].linear.len();
let nnewvars = noldvars + nnew;
let mut changedvars = vec![];
changedvars.extend_from_slice(changed);
changedvars.extend(noldvars..nnewvars);
|
| ︙ | ︙ | |||
209 210 211 212 213 214 215 |
// WORST CASE: DO THIS
// self.force_update = true;
Ok(())
}
| | | 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 |
// WORST CASE: DO THIS
// self.force_update = true;
Ok(())
}
fn solve(&mut self, eta: &DVector, _fbound: Real, _augbound: Real, _relprec: Real) -> Result<()> {
if self.force_update || !self.updateinds.is_empty() {
self.init_qp()?;
}
let nvars = unsafe { cpx::getnumcols(cpx::env(), self.lp) as usize };
if nvars == 0 {
return Err(MasterProblemError::NoMinorants);
|
| ︙ | ︙ | |||
283 284 285 286 287 288 289 |
this_val = this_val.max(m.eval(y));
}
result += this_val;
}
result
}
| | | 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 |
this_val = this_val.max(m.eval(y));
}
result += this_val;
}
result
}
fn aggregate(&mut self, fidx: usize, mins: &[usize]) -> Result<(usize, DVector)> {
assert!(!mins.is_empty(), "No minorants specified to be aggregated");
if mins.len() == 1 {
return Ok((mins[0], dvec![1.0]));
}
// scale coefficients
|
| ︙ | ︙ | |||
375 376 377 378 379 380 381 |
for m in mins.iter_mut() {
m.move_center(alpha, d);
}
}
}
}
| | | | 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
for m in mins.iter_mut() {
m.move_center(alpha, d);
}
}
}
}
impl CplexMaster {
fn init_qp(&mut self) -> Result<()> {
if !self.lp.is_null() {
trycpx!(cpx::freeprob(cpx::env(), &mut self.lp));
}
trycpx!({
let mut status = 0;
self.lp = cpx::createprob(cpx::env(), &mut status, c_str!("mastercp").as_ptr());
status
|
| ︙ | ︙ |
Changes to src/master/minimal.rs.
| ︙ | ︙ | |||
20 21 22 23 24 25 26 | use super::Result; use log::debug; use std::error::Error; use std::f64::NEG_INFINITY; use std::fmt; | < | 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
use super::Result;
use log::debug;
use std::error::Error;
use std::f64::NEG_INFINITY;
use std::fmt;
use std::result;
/// Minimal master problem error.
#[derive(Debug)]
pub enum MinimalMasterError {
NumSubproblems { nsubs: usize },
MaxMinorants,
|
| ︙ | ︙ | |||
42 43 44 45 46 47 48 |
MaxMinorants => write!(fmt, "The minimal master problem allows at most two minorants"),
}
}
}
impl Error for MinimalMasterError {}
| | | | < | < < | < | | | | | | | | | 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 |
MaxMinorants => write!(fmt, "The minimal master problem allows at most two minorants"),
}
}
}
impl Error for MinimalMasterError {}
impl From<MinimalMasterError> for MasterProblemError {
fn from(err: MinimalMasterError) -> MasterProblemError {
MasterProblemError::Custom(Box::new(err))
}
}
/**
* A minimal master problem with only two minorants.
*
* This is the simplest possible master problem for bundle methods. It
* has only two minorants and only one function model. The advantage
* is that this model can be solved explicitely and very quickly, but
* it is only a very loose approximation of the objective function.
*
* Because of its properties, it can only be used if the problem to be
* solved has a maximal number of minorants of two and only one
* subproblem.
*/
pub struct MinimalMaster {
/// The weight of the quadratic term.
weight: Real,
/// The minorants in the model.
minorants: Vec<Minorant>,
/// Optimal multipliers.
opt_mult: DVector,
/// Optimal aggregated minorant.
opt_minorant: Minorant,
}
impl UnconstrainedMasterProblem for MinimalMaster {
type MinorantIndex = usize;
fn new() -> Result<MinimalMaster> {
Ok(MinimalMaster {
weight: 1.0,
minorants: vec![],
opt_mult: dvec![],
opt_minorant: Minorant::default(),
})
}
fn num_subproblems(&self) -> usize {
1
}
fn set_num_subproblems(&mut self, n: usize) -> Result<()> {
if n != 1 {
Err(MinimalMasterError::NumSubproblems { nsubs: n }.into())
} else {
Ok(())
}
}
fn weight(&self) -> Real {
self.weight
}
fn set_weight(&mut self, weight: Real) -> Result<()> {
assert!(weight > 0.0);
self.weight = weight;
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
assert_eq!(fidx, 0);
self.minorants.len()
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant) -> Result<usize> {
assert_eq!(fidx, 0);
if self.minorants.len() >= 2 {
return Err(MinimalMasterError::MaxMinorants.into());
}
self.minorants.push(minorant);
self.opt_mult.push(0.0);
Ok(self.minorants.len() - 1)
}
fn add_vars(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtension<Self::MinorantIndex>,
) -> Result<()> {
if !self.minorants.is_empty() {
let noldvars = self.minorants[0].linear.len();
let mut changedvars = vec![];
changedvars.extend_from_slice(changed);
changedvars.extend(noldvars..noldvars + nnew);
for (i, m) in self.minorants.iter_mut().enumerate() {
let new_subg = extend_subgradient(0, i, &changedvars)
.map_err(|e| MasterProblemError::SubgradientExtension(e.into()))?;
for (&j, &g) in changed.iter().zip(new_subg.iter()) {
m.linear[j] = g;
}
m.linear.extend_from_slice(&new_subg[changed.len()..]);
}
}
Ok(())
}
#[allow(unused_variables)]
fn solve(&mut self, eta: &DVector, fbound: Real, augbound: Real, relprec: Real) -> Result<()> {
for (i, m) in self.minorants.iter().enumerate() {
debug!(" {}:min[{},{}] = {}", i, 0, 0, m);
}
if self.minorants.len() == 2 {
let xx = self.minorants[0].linear.dot(&self.minorants[0].linear);
let yy = self.minorants[1].linear.dot(&self.minorants[1].linear);
|
| ︙ | ︙ | |||
210 211 212 213 214 215 216 |
let mut result = NEG_INFINITY;
for m in &self.minorants {
result = result.max(m.eval(y));
}
result
}
| | | 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 |
let mut result = NEG_INFINITY;
for m in &self.minorants {
result = result.max(m.eval(y));
}
result
}
fn aggregate(&mut self, fidx: usize, mins: &[usize]) -> Result<(usize, DVector)> {
assert_eq!(fidx, 0);
if mins.len() == 2 {
debug!("Aggregate");
debug!(" {} * {}", self.opt_mult[0], self.minorants[0]);
debug!(" {} * {}", self.opt_mult[1], self.minorants[1]);
self.minorants[0] = Aggregatable::combine(self.opt_mult.iter().cloned().zip(&self.minorants));
self.minorants.truncate(1);
|
| ︙ | ︙ |
Changes to src/master/unconstrained.rs.
| ︙ | ︙ | |||
42 43 44 45 46 47 48 |
* \\[ \max_{\alpha \in \Delta} \min_{d \in \mathbb{R}\^n}
* \sum_{i=1}\^k \alpha_i \ell_i(d) + \frac{u}{2} \\| d \\|\^2. \\]
*/
pub trait UnconstrainedMasterProblem {
/// Unique index for a minorant.
type MinorantIndex: Copy + Eq;
| < < < | | | | < < < < | | < < < < | < < | 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 |
* \\[ \max_{\alpha \in \Delta} \min_{d \in \mathbb{R}\^n}
* \sum_{i=1}\^k \alpha_i \ell_i(d) + \frac{u}{2} \\| d \\|\^2. \\]
*/
pub trait UnconstrainedMasterProblem {
/// Unique index for a minorant.
type MinorantIndex: Copy + Eq;
/// Return a new instance of the unconstrained master problem.
fn new() -> Result<Self>
where
Self: Sized;
/// Return the number of subproblems.
fn num_subproblems(&self) -> usize;
/// Set the number of subproblems (different function models.)
fn set_num_subproblems(&mut self, n: usize) -> Result<()>;
/// Return the current weight.
fn weight(&self) -> Real;
/// Set the weight of the quadratic term, must be > 0.
fn set_weight(&mut self, weight: Real) -> Result<()>;
/// Return the number of minorants of subproblem `fidx`.
fn num_minorants(&self, fidx: usize) -> usize;
/// Add a new minorant to the model.
fn add_minorant(&mut self, fidx: usize, minorant: Minorant) -> Result<Self::MinorantIndex>;
/// Add or move some variables.
///
/// The variables in `changed` have been changed, so the subgradient
/// information must be updated. Furthermore, `nnew` new variables
/// are added.
fn add_vars(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtension<Self::MinorantIndex>,
) -> Result<()>;
/// Solve the master problem.
fn solve(&mut self, eta: &DVector, fbound: Real, augbound: Real, relprec: Real) -> Result<()>;
/// Return the current dual optimal solution.
fn dualopt(&self) -> &DVector;
/// Return the current dual optimal solution value.
fn dualopt_cutval(&self) -> Real;
|
| ︙ | ︙ | |||
115 116 117 118 119 120 121 |
/// after this operation. The function returns the index of the
/// aggregated minorant along with the coefficients of the convex
/// combination. The index of the new aggregated minorant might or
/// might not be one of indices of the original minorants.
///
/// # Error
/// The indices of the minorants `mins` must belong to subproblem `fidx`.
| < < < < | | 102 103 104 105 106 107 108 109 110 111 112 113 |
/// after this operation. The function returns the index of the
/// aggregated minorant along with the coefficients of the convex
/// combination. The index of the new aggregated minorant might or
/// might not be one of indices of the original minorants.
///
/// # Error
/// The indices of the minorants `mins` must belong to subproblem `fidx`.
fn aggregate(&mut self, fidx: usize, mins: &[usize]) -> Result<(Self::MinorantIndex, DVector)>;
/// Move the center of the master problem along $\alpha \cdot d$.
fn move_center(&mut self, alpha: Real, d: &DVector);
}
|
Changes to src/solver.rs.
| ︙ | ︙ | |||
37 38 39 40 41 42 43 |
#[derive(Debug)]
pub enum SolverError<E> {
/// An error occurred during oracle evaluation.
Evaluation(E),
/// An error occurred during oracle update.
Update(E),
/// An error has been raised by the master problem.
| | | 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
#[derive(Debug)]
pub enum SolverError<E> {
/// An error occurred during oracle evaluation.
Evaluation(E),
/// An error occurred during oracle update.
Update(E),
/// An error has been raised by the master problem.
Master(MasterProblemError),
/// The oracle did not return a minorant.
NoMinorant,
/// The dimension of some data is wrong.
Dimension,
/// Some parameter has an invalid value.
Parameter(ParameterError),
/// The lower bound of a variable is larger than the upper bound.
|
| ︙ | ︙ | |||
78 79 80 81 82 83 84 |
write!(fmt, "Variable index out of bounds, got:{} must be < {}", index, nvars)
}
IterationLimit { limit } => write!(fmt, "The iteration limit of {} has been reached.", limit),
}
}
}
| | < < < | | | | 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 |
write!(fmt, "Variable index out of bounds, got:{} must be < {}", index, nvars)
}
IterationLimit { limit } => write!(fmt, "The iteration limit of {} has been reached.", limit),
}
}
}
impl<E: Error + 'static> Error for SolverError<E> {
fn source(&self) -> Option<&(dyn Error + 'static)> {
match self {
SolverError::Evaluation(err) => Some(err),
SolverError::Update(err) => Some(err),
SolverError::Master(err) => Some(err),
_ => None,
}
}
}
impl<E> From<ParameterError> for SolverError<E> {
fn from(err: ParameterError) -> SolverError<E> {
SolverError::Parameter(err)
}
}
impl<E> From<MasterProblemError> for SolverError<E> {
fn from(err: MasterProblemError) -> SolverError<E> {
SolverError::Master(err)
}
}
/**
* The current state of the bundle method.
*
|
| ︙ | ︙ | |||
382 383 384 385 386 387 388 |
/// This is the last primal generated by the oracle.
pub fn last_primal(&self, fidx: usize) -> Option<&Pr> {
self.minorants[fidx].last().and_then(|m| m.primal.as_ref())
}
}
/// The default bundle solver with general master problem.
| | | | | 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 |
/// This is the last primal generated by the oracle.
pub fn last_primal(&self, fidx: usize) -> Option<&Pr> {
self.minorants[fidx].last().and_then(|m| m.primal.as_ref())
}
}
/// The default bundle solver with general master problem.
pub type DefaultSolver<P> = Solver<P, BoxedMasterProblem<CplexMaster>>;
/// A bundle solver with a minimal cutting plane model.
pub type NoBundleSolver<P> = Solver<P, BoxedMasterProblem<MinimalMaster>>;
/**
* Implementation of a bundle method.
*/
pub struct Solver<P, M = BoxedMasterProblem<CplexMaster>>
where
P: FirstOrderProblem,
{
/// The first order problem description.
problem: P,
/// The solver parameter.
|
| ︙ | ︙ | |||
485 486 487 488 489 490 491 |
/// Accumulated information about the last iteration.
iterinfos: Vec<IterationInfo>,
}
impl<P, M> Solver<P, M>
where
P: FirstOrderProblem,
| | | | 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 |
/// Accumulated information about the last iteration.
iterinfos: Vec<IterationInfo>,
}
impl<P, M> Solver<P, M>
where
P: FirstOrderProblem,
P::Err: Into<Box<std::error::Error + Send + Sync + 'static>>,
M: MasterProblem<MinorantIndex = usize>,
{
/**
* 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
|
| ︙ | ︙ | |||
719 720 721 722 723 724 725 726 727 728 729 730 731 732 |
let minorants = &self.minorants;
self.master.add_vars(
&newvars.iter().map(|v| (v.0, v.1, v.2)).collect::<Vec<_>>(),
&mut |fidx, minidx, vars| {
problem
.extend_subgradient(minorants[fidx][minidx].primal.as_ref().unwrap(), vars)
.map(DVector)
},
)?;
// modify moved variables
for (index, val) in newvars.iter().filter_map(|v| v.0.map(|i| (i, v.3))) {
self.cur_y[index] = val;
self.nxt_y[index] = val;
self.nxt_d[index] = 0.0;
| > | 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 |
let minorants = &self.minorants;
self.master.add_vars(
&newvars.iter().map(|v| (v.0, v.1, v.2)).collect::<Vec<_>>(),
&mut |fidx, minidx, vars| {
problem
.extend_subgradient(minorants[fidx][minidx].primal.as_ref().unwrap(), vars)
.map(DVector)
.map_err(|e| e.into())
},
)?;
// modify moved variables
for (index, val) in newvars.iter().filter_map(|v| v.0.map(|i| (i, v.3))) {
self.cur_y[index] = val;
self.nxt_y[index] = val;
self.nxt_d[index] = 0.0;
|
| ︙ | ︙ |