Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Comment: | Add `primal` field to `Minorant` |
|---|---|
| Downloads: | Tarball | ZIP archive |
| Timelines: | family | ancestors | descendants | both | minorant-primal |
| Files: | files | file ages | folders |
| SHA1: |
be42fa28cde02975a185a0e136578224 |
| User & Date: | fifr 2020-07-18 12:24:34.971 |
Context
|
2020-07-18
| ||
| 12:41 | Move `SubgradientExtender` to `minorant` module check-in: 30a0059850 user: fifr tags: minorant-primal | |
| 12:24 | Add `primal` field to `Minorant` check-in: be42fa28cd user: fifr tags: minorant-primal | |
|
2020-07-15
| ||
| 19:52 | Update ordered-float to version 2.0 check-in: f53f2d0005 user: fifr tags: trunk | |
Changes
Changes to examples/cflp.rs.
1 | /* | | | 1 2 3 4 5 6 7 8 9 | /* * Copyright (c) 2019, 2020 Frank Fischer <frank-fischer@shadow-soft.de> * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but |
| ︙ | ︙ | |||
67 68 69 70 71 72 73 |
impl CFLProblem {
fn new() -> CFLProblem {
CFLProblem { pool: None }
}
}
| | < | > | < | > | 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 |
impl CFLProblem {
fn new() -> CFLProblem {
CFLProblem { pool: None }
}
}
fn solve_facility_problem(j: usize, lambda: &[Real]) -> Result<(Real, Minorant<DVector>), EvalError> {
// facility subproblem max\{-F[j] + CAP[j] * lambda[j] * y[j] | y_j \in \{0,1\}\}
let objective;
let mut subg = dvec![0.0; lambda.len()];
let primal;
if -F[j] + CAP[j] * lambda[j] > 0.0 {
objective = -F[j] + CAP[j] * lambda[j];
subg[j] = CAP[j];
primal = dvec![1.0; 1];
} else {
objective = 0.0;
primal = dvec![0.0; 1];
}
Ok((
objective,
Minorant {
constant: objective,
linear: subg,
primal,
},
))
}
fn solve_customer_problem(i: usize, lambda: &[Real]) -> Result<(Real, Minorant<DVector>), EvalError> {
// customer subproblem
let opt = (0..Nfac)
.map(|j| (j, -DEMAND[i] * C[j][i] - DEMAND[i] * lambda[j]))
.flat_map(|x| NotNan::new(x.1).map(|y| (x.0, y)))
.max_by_key(|x| x.1)
.ok_or(EvalError::Customer(i))?;
let objective = opt.1.into_inner();
let mut subg = dvec![0.0; lambda.len()];
subg[opt.0] = -DEMAND[i];
let mut primal = dvec![0.0; Nfac];
primal[opt.0] = 1.0;
Ok((
objective,
Minorant {
constant: objective,
linear: subg,
primal,
},
))
}
impl ParallelProblem for CFLProblem {
type Err = EvalError;
type Primal = DVector;
|
| ︙ | ︙ | |||
156 157 158 159 160 161 162 |
self.pool.as_ref().unwrap().execute(move || {
let res = if i < Nfac {
solve_facility_problem(i, &y)
} else {
solve_customer_problem(i - Nfac, &y)
};
match res {
| | | | 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 |
self.pool.as_ref().unwrap().execute(move || {
let res = if i < Nfac {
solve_facility_problem(i, &y)
} else {
solve_customer_problem(i - Nfac, &y)
};
match res {
Ok((value, minorant)) => {
if tx.objective(value).is_err() {
return;
}
if tx.minorant(minorant).is_err() {
return;
}
}
Err(err) => if tx.error(err).is_err() {},
};
});
Ok(())
|
| ︙ | ︙ |
Changes to examples/mmcf.rs.
1 | /* | | | 1 2 3 4 5 6 7 8 9 | /* * Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de> * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but |
| ︙ | ︙ | |||
21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
use rustop::opts;
use std::io::Write;
use bundle::master::{Builder, FullMasterBuilder, MasterProblem, MinimalMasterBuilder};
use bundle::mcf::MMCFProblem;
use bundle::solver::asyn::Solver as AsyncSolver;
use bundle::solver::sync::Solver as SyncSolver;
use bundle::{terminator::StandardTerminator, weighter::HKWeighter};
use std::error::Error;
use std::result::Result;
fn solve_parallel<M>(master: M, mmcf: MMCFProblem) -> Result<(), Box<dyn Error>>
where
| > | | | | | 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 |
use rustop::opts;
use std::io::Write;
use bundle::master::{Builder, FullMasterBuilder, MasterProblem, MinimalMasterBuilder};
use bundle::mcf::MMCFProblem;
use bundle::solver::asyn::Solver as AsyncSolver;
use bundle::solver::sync::Solver as SyncSolver;
use bundle::DVector;
use bundle::{terminator::StandardTerminator, weighter::HKWeighter};
use std::error::Error;
use std::result::Result;
fn solve_parallel<M>(master: M, mmcf: MMCFProblem) -> Result<(), Box<dyn Error>>
where
M: Builder<DVector>,
M::MasterProblem: MasterProblem<DVector, MinorantIndex = usize>,
{
let mut slv = AsyncSolver::<_, StandardTerminator, HKWeighter, M>::with_master(mmcf, master);
slv.weighter.set_weight_bounds(1e-1, 100.0);
slv.terminator.termination_precision = 1e-6;
slv.solve()?;
let costs: f64 = (0..slv.problem().num_subproblems())
.map(|i| {
let aggr_primals = slv.aggregated_primal(i).unwrap();
slv.problem().get_primal_costs(i, &[aggr_primals])
})
.sum();
info!("Primal costs: {}", costs);
Ok(())
}
fn solve_sync<M>(master: M, mmcf: MMCFProblem) -> Result<(), Box<dyn Error>>
where
M: Builder<DVector>,
M::MasterProblem: MasterProblem<DVector, MinorantIndex = usize>,
{
let mut slv = SyncSolver::<_, StandardTerminator, HKWeighter, M>::with_master(mmcf, master);
slv.weighter.set_weight_bounds(1e-1, 100.0);
slv.terminator.termination_precision = 1e-6;
slv.solve()?;
let costs: f64 = (0..slv.problem().num_subproblems())
|
| ︙ | ︙ |
Changes to examples/quadratic.rs.
1 | /* | | | 1 2 3 4 5 6 7 8 9 | /* * Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de> * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but |
| ︙ | ︙ | |||
81 82 83 84 85 86 87 |
}
debug!("Evaluation at {:?}", x);
debug!(" objective={}", objective);
debug!(" subgradient={}", g);
tx.objective(objective).unwrap();
| | < | | > | < < | 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 |
}
debug!("Evaluation at {:?}", x);
debug!(" objective={}", objective);
debug!(" subgradient={}", g);
tx.objective(objective).unwrap();
tx.minorant(Minorant {
constant: objective,
linear: g,
primal: (),
})
.unwrap();
});
Ok(())
}
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
| ︙ | ︙ |
Changes to src/data/minorant.rs.
| ︙ | ︙ | |||
26 27 28 29 30 31 32 |
/// A linear minorant of a convex function $f \colon \mathbb{R}\^n \to
/// \mathbb{R}$ is a linear function of the form
///
/// \\[ l \colon \mathbb{R}\^n \to \mathbb{R}, x \mapsto \langle g, x
/// \rangle + c \\]
///
/// such that $l(x) \le f(x)$ for all $x \in \mathbb{R}\^n$.
| > > > > | | | > > | > > > > > > > > | | | > | | > | 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 |
/// A linear minorant of a convex function $f \colon \mathbb{R}\^n \to
/// \mathbb{R}$ is a linear function of the form
///
/// \\[ l \colon \mathbb{R}\^n \to \mathbb{R}, x \mapsto \langle g, x
/// \rangle + c \\]
///
/// such that $l(x) \le f(x)$ for all $x \in \mathbb{R}\^n$.
///
/// Each minorant may have an additional "primal" data, that is
/// linearly combined along with the minorant itself. This data can
/// be used for separation algorithms.
#[derive(Clone)]
pub struct Minorant<P: Aggregatable> {
/// The constant term.
pub constant: Real,
/// The linear term.
pub linear: DVector,
/// The associated primal data.
pub primal: P,
}
impl<P: Aggregatable> fmt::Debug for Minorant<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:?}", (self.constant, &self.linear))?;
Ok(())
}
}
impl<P: Aggregatable> fmt::Display for Minorant<P> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{} + y * {}", self.constant, self.linear)?;
Ok(())
}
}
impl<P: Aggregatable> Default for Minorant<P> {
fn default() -> Minorant<P> {
Minorant {
constant: 0.0,
linear: dvec![],
primal: P::default(),
}
}
}
impl<P: Aggregatable> Minorant<P> {
/// Return a new 0 minorant.
pub fn new(constant: Real, linear: Vec<Real>, primal: P) -> Minorant<P> {
Minorant {
constant,
linear: DVector(linear),
primal,
}
}
/**
* Evaluate minorant at some point.
*
* This function computes $c + \langle g, x \rangle$ for this minorant
|
| ︙ | ︙ | |||
91 92 93 94 95 96 97 |
/// [`move_center`]: Minorant::move_center
pub fn move_center_begin(&mut self, alpha: Real, d: &DVector) {
debug_assert!(self.linear.len() >= d.len());
self.constant += alpha * self.linear.dot_begin(d);
}
}
| | > > | 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 |
/// [`move_center`]: Minorant::move_center
pub fn move_center_begin(&mut self, alpha: Real, d: &DVector) {
debug_assert!(self.linear.len() >= d.len());
self.constant += alpha * self.linear.dot_begin(d);
}
}
impl<P: Aggregatable> Aggregatable for Minorant<P> {
fn new_scaled<A>(alpha: Real, other: A) -> Self
where
A: Borrow<Self>,
{
let m = other.borrow();
Minorant {
constant: alpha * m.constant,
linear: DVector::scaled(&m.linear, alpha),
primal: P::new_scaled(alpha, &m.primal),
}
}
fn add_scaled<A>(&mut self, alpha: Real, other: A)
where
A: Borrow<Self>,
{
let m = other.borrow();
self.constant += alpha * m.constant;
self.linear.add_scaled(alpha, &m.linear);
self.primal.add_scaled(alpha, &m.primal);
}
}
|
Changes to src/master/boxed.rs.
| ︙ | ︙ | |||
14 15 16 17 18 19 20 | // along with this program. If not, see <http://www.gnu.org/licenses/> // pub mod unconstrained; use self::unconstrained::UnconstrainedMasterProblem; use super::MasterProblem; | | | > | | > > > | 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 |
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
pub mod unconstrained;
use self::unconstrained::UnconstrainedMasterProblem;
use super::MasterProblem;
use crate::problem::SubgradientExtender;
use crate::{Aggregatable, DVector, Minorant, Real};
use either::Either;
use log::debug;
use std::f64::{EPSILON, INFINITY, NEG_INFINITY};
use std::marker::PhantomData;
/**
* Turn unconstrained master problem into box-constrained one.
*
* This master problem adds box constraints to an unconstrained
* master problem implementation. The box constraints are enforced by
* an additional outer optimization loop.
*/
pub struct BoxedMasterProblem<P, M>
where
P: Aggregatable,
{
/// The unconstrained master problem solver.
pub master: M,
/// Maximal number of updates of box multipliers.
pub max_updates: usize,
/// Variable lower bounds.
|
| ︙ | ︙ | |||
60 61 62 63 64 65 66 |
/// Model precision.
model_eps: Real,
need_new_candidate: bool,
/// Current number of updates.
cnt_updates: usize,
| | > | > | > | | > | 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 |
/// Model precision.
model_eps: Real,
need_new_candidate: bool,
/// Current number of updates.
cnt_updates: usize,
phantom: PhantomData<P>,
}
impl<P, M> BoxedMasterProblem<P, M>
where
P: Aggregatable,
M: UnconstrainedMasterProblem<P>,
{
pub fn with_master(master: M) -> BoxedMasterProblem<P, M> {
BoxedMasterProblem {
master,
max_updates: 50,
lb: dvec![],
ub: dvec![],
eta: dvec![],
primopt: dvec![],
primoptval: 0.0,
dualoptnorm2: 0.0,
model_eps: 0.6,
cnt_updates: 0,
need_new_candidate: true,
phantom: PhantomData,
}
}
pub fn set_max_updates(&mut self, max_updates: usize) -> Result<(), M::Err> {
assert!(max_updates > 0);
self.max_updates = max_updates;
Ok(())
|
| ︙ | ︙ | |||
179 180 181 182 183 184 185 |
* the current box-multipliers $\eta$.
*/
fn get_norm_subg2(&self) -> Real {
self.eta.dot(self.master.dualopt())
}
}
| | > | | 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 |
* the current box-multipliers $\eta$.
*/
fn get_norm_subg2(&self) -> Real {
self.eta.dot(self.master.dualopt())
}
}
impl<P, M> MasterProblem<P> for BoxedMasterProblem<P, M>
where
P: Aggregatable + Send + 'static,
M: UnconstrainedMasterProblem<P>,
{
type MinorantIndex = M::MinorantIndex;
type Err = M::Err;
fn new() -> Result<Self, Self::Err> {
M::new().map(BoxedMasterProblem::with_master)
|
| ︙ | ︙ | |||
222 223 224 225 226 227 228 |
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.master.num_minorants(fidx)
}
| | | | | < < < | 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 |
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.master.num_minorants(fidx)
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant<P>) -> Result<Self::MinorantIndex, Self::Err> {
self.master.add_minorant(fidx, minorant)
}
fn weight(&self) -> Real {
self.master.weight()
}
fn set_weight(&mut self, weight: Real) -> Result<(), Self::Err> {
self.master.set_weight(weight)
}
fn add_vars<SErr>(
&mut self,
bounds: &[(Option<usize>, Real, Real)],
extend_subgradient: &mut SubgradientExtender<P, SErr>,
) -> Result<(), Either<Self::Err, SErr>> {
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));
|
| ︙ | ︙ | |||
360 361 362 363 364 365 366 367 368 369 370 371 372 373 |
fn multiplier(&self, min: Self::MinorantIndex) -> Real {
self.master.multiplier(min)
}
fn opt_multipliers<'a>(&'a self, fidx: usize) -> Box<dyn Iterator<Item = (Self::MinorantIndex, Real)> + 'a> {
self.master.opt_multipliers(fidx)
}
fn move_center(&mut self, alpha: Real, d: &DVector) {
self.need_new_candidate = true;
self.master.move_center(alpha, d);
self.lb.add_scaled_begin(-alpha, d);
self.ub.add_scaled_begin(-alpha, d);
}
| > > > > | 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 |
fn multiplier(&self, min: Self::MinorantIndex) -> Real {
self.master.multiplier(min)
}
fn opt_multipliers<'a>(&'a self, fidx: usize) -> Box<dyn Iterator<Item = (Self::MinorantIndex, Real)> + 'a> {
self.master.opt_multipliers(fidx)
}
fn aggregated_primal(&self, fidx: usize) -> Result<P, Self::Err> {
self.master.aggregated_primal(fidx)
}
fn move_center(&mut self, alpha: Real, d: &DVector) {
self.need_new_candidate = true;
self.master.move_center(alpha, d);
self.lb.add_scaled_begin(-alpha, d);
self.ub.add_scaled_begin(-alpha, d);
}
|
| ︙ | ︙ | |||
383 384 385 386 387 388 389 | /// Builder for `BoxedMasterProblem`. /// /// `B` is a builder of the underlying `UnconstrainedMasterProblem`. #[derive(Default)] pub struct Builder<B>(B); | | > | | | | | 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 |
/// Builder for `BoxedMasterProblem`.
///
/// `B` is a builder of the underlying `UnconstrainedMasterProblem`.
#[derive(Default)]
pub struct Builder<B>(B);
impl<P, B> super::Builder<P> for Builder<B>
where
P: Aggregatable + Send + 'static,
B: unconstrained::Builder<P>,
B::MasterProblem: UnconstrainedMasterProblem<P>,
{
type MasterProblem = BoxedMasterProblem<P, B::MasterProblem>;
fn build(&mut self) -> Result<Self::MasterProblem, <Self::MasterProblem as MasterProblem<P>>::Err> {
self.0.build().map(BoxedMasterProblem::with_master)
}
}
impl<B> std::ops::Deref for Builder<B> {
type Target = B;
|
| ︙ | ︙ |
Changes to src/master/boxed/unconstrained.rs.
|
| | | | < | 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 |
// Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de>
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
pub mod cpx;
pub mod minimal;
use crate::problem::SubgradientExtender;
use crate::{Aggregatable, DVector, Minorant, Real};
use either::Either;
use std::error::Error;
/**
* Trait for master problems without box constraints.
*
|
| ︙ | ︙ | |||
44 45 46 47 48 49 50 |
* \alpha_i = 1 \right\\}$. Note, the unconstrained solver is expected
* to compute *dual* optimal solutions, i.e. the solver must compute
* optimal coefficients $\bar{\alpha}$ for the dual problem
*
* \\[ \max_{\alpha \in \Delta} \min_{d \in \mathbb{R}\^n}
* \sum_{i=1}\^k \alpha_i \ell_i(d) + \frac{u}{2} \\| d \\|\^2. \\]
*/
| | | 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 |
* \alpha_i = 1 \right\\}$. Note, the unconstrained solver is expected
* to compute *dual* optimal solutions, i.e. the solver must compute
* optimal coefficients $\bar{\alpha}$ for the dual problem
*
* \\[ \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<P: Aggregatable>: Send + 'static {
/// Unique index for a minorant.
type MinorantIndex: Copy + Eq;
/// Error type for this master problem.
type Err: Error + Send + Sync;
/// Return a new instance of the unconstrained master problem.
|
| ︙ | ︙ | |||
81 82 83 84 85 86 87 |
/// coefficients and indices of the compressed minorants and the index of
/// the new minorant. The callback may be called several times.
fn compress<F>(&mut self, f: F) -> Result<(), Self::Err>
where
F: FnMut(Self::MinorantIndex, &mut dyn Iterator<Item = (Self::MinorantIndex, Real)>);
/// Add a new minorant to the model.
| | | | | < < | 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 |
/// coefficients and indices of the compressed minorants and the index of
/// the new minorant. The callback may be called several times.
fn compress<F>(&mut self, f: F) -> Result<(), Self::Err>
where
F: FnMut(Self::MinorantIndex, &mut dyn Iterator<Item = (Self::MinorantIndex, Real)>);
/// Add a new minorant to the model.
fn add_minorant(&mut self, fidx: usize, minorant: Minorant<P>) -> Result<Self::MinorantIndex, Self::Err>;
/// 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<SErr>(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtender<P, SErr>,
) -> Result<(), Either<Self::Err, SErr>>;
/// Solve the master problem.
fn solve(&mut self, eta: &DVector, fbound: Real, augbound: Real, relprec: Real) -> Result<(), Self::Err>;
/// Return the current dual optimal solution.
fn dualopt(&self) -> &DVector;
|
| ︙ | ︙ | |||
127 128 129 130 131 132 133 134 135 136 137 138 |
/// 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), Self::Err>;
/// Move the center of the master problem along $\alpha \cdot d$.
fn move_center(&mut self, alpha: Real, d: &DVector);
}
/// A builder for creating unconstrained master problem solvers.
| > > > | | | | 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 |
/// 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), Self::Err>;
/// Return the aggregated primal.
fn aggregated_primal(&self, fidx: usize) -> Result<P, Self::Err>;
/// Move the center of the master problem along $\alpha \cdot d$.
fn move_center(&mut self, alpha: Real, d: &DVector);
}
/// A builder for creating unconstrained master problem solvers.
pub trait Builder<P: Aggregatable> {
/// The master problem to be build.
type MasterProblem: UnconstrainedMasterProblem<P>;
/// Create a new master problem.
fn build(&mut self) -> Result<Self::MasterProblem, <Self::MasterProblem as UnconstrainedMasterProblem<P>>::Err>;
}
|
Changes to src/master/boxed/unconstrained/cpx.rs.
|
| | | > | 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 |
// Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de>
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
//! Master problem implementation using CPLEX.
#![allow(unused_unsafe)]
use super::UnconstrainedMasterProblem;
use crate::problem::SubgradientExtender;
use crate::{Aggregatable, DVector, Minorant, Real};
use c_str_macro::c_str;
use cplex_sys as cpx;
use cplex_sys::trycpx;
use either::Either;
use log::{debug, warn};
|
| ︙ | ︙ | |||
66 67 68 69 70 71 72 |
CplexMasterError::Cplex(err)
}
}
pub type Result<T> = std::result::Result<T, CplexMasterError>;
/// A minorant and its unique index.
| | | | | | | | | | | | | | 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 |
CplexMasterError::Cplex(err)
}
}
pub type Result<T> = std::result::Result<T, CplexMasterError>;
/// A minorant and its unique index.
struct MinorantInfo<P: Aggregatable> {
minorant: Minorant<P>,
index: usize,
}
impl<P: Aggregatable> Deref for MinorantInfo<P> {
type Target = Minorant<P>;
fn deref(&self) -> &Minorant<P> {
&self.minorant
}
}
impl<P: Aggregatable> DerefMut for MinorantInfo<P> {
fn deref_mut(&mut self) -> &mut Minorant<P> {
&mut self.minorant
}
}
/// Maps a global index to a minorant.
#[derive(Clone, Copy)]
struct MinorantIdx {
/// The function (subproblem) index.
fidx: usize,
/// The minorant index within the subproblem.
idx: usize,
}
/// A submodel.
///
/// A submodel is a list of subproblems being aggregated in that model.
#[derive(Debug, Clone, Default)]
struct SubModel<P: Aggregatable> {
/// The list of subproblems.
subproblems: Vec<usize>,
/// The number of minorants in this subproblem.
///
/// The is the minimal number of minorants in each contained subproblem.
num_mins: usize,
/// The aggregated minorants of this submodel.
///
/// This is just the sum of the corresponding minorants of the single
/// functions contained in this submodel.
minorants: Vec<Minorant<P>>,
}
impl<P: Aggregatable> Deref for SubModel<P> {
type Target = Vec<usize>;
fn deref(&self) -> &Vec<usize> {
&self.subproblems
}
}
impl<P: Aggregatable> DerefMut for SubModel<P> {
fn deref_mut(&mut self) -> &mut Vec<usize> {
&mut self.subproblems
}
}
pub struct CplexMaster<P: Aggregatable> {
env: *mut cpx::Env,
lp: *mut cpx::Lp,
/// True if the QP must be updated.
force_update: bool,
|
| ︙ | ︙ | |||
152 153 154 155 156 157 158 |
/// The additional diagonal term to ensure positive definiteness.
qdiag: Real,
/// The weight of the quadratic term.
weight: Real,
/// The minorants for each subproblem in the model.
| | | | | | | | | 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 |
/// The additional diagonal term to ensure positive definiteness.
qdiag: Real,
/// The weight of the quadratic term.
weight: Real,
/// The minorants for each subproblem in the model.
minorants: Vec<Vec<MinorantInfo<P>>>,
/// The callback for the submodel for each subproblem.
select_model: Arc<dyn Fn(usize) -> usize>,
/// For each submodel the list of subproblems contained in that model.
submodels: Vec<SubModel<P>>,
/// For each subproblem the submodel it is contained in.
in_submodel: Vec<usize>,
/// Optimal multipliers for each subproblem in the model.
opt_mults: Vec<DVector>,
/// Optimal aggregated minorant.
opt_minorant: Minorant<P>,
/// Maximal bundle size.
pub max_bundle_size: usize,
}
unsafe impl<P: Aggregatable> Send for CplexMaster<P> {}
impl<P: Aggregatable> Drop for CplexMaster<P> {
fn drop(&mut self) {
unsafe { cpx::freeprob(self.env, &mut self.lp) };
unsafe { cpx::closeCPLEX(&mut self.env) };
}
}
impl<P: Aggregatable + 'static> UnconstrainedMasterProblem<P> for CplexMaster<P> {
type MinorantIndex = usize;
type Err = CplexMasterError;
fn new() -> Result<CplexMaster<P>> {
let env;
trycpx!({
let mut status = 0;
env = cpx::openCPLEX(&mut status);
status
});
|
| ︙ | ︙ | |||
272 273 274 275 276 277 278 |
let (newindex, coeffs) = self.aggregate(i, &inds)?;
f(newindex, &mut inds.into_iter().zip(coeffs));
}
}
Ok(())
}
| | | 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 |
let (newindex, coeffs) = self.aggregate(i, &inds)?;
f(newindex, &mut inds.into_iter().zip(coeffs));
}
}
Ok(())
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant<P>) -> Result<usize> {
debug!("Add minorant");
debug!(" fidx={} index={}: {}", fidx, self.minorants[fidx].len(), minorant);
debug_assert!(
self.minorants[fidx]
.last()
.map_or(true, |m| m.linear.len() == minorant.linear.len()),
|
| ︙ | ︙ | |||
303 304 305 306 307 308 309 |
// store minorant
self.minorants[fidx].push(MinorantInfo { minorant, index });
self.opt_mults[fidx].push(0.0);
Ok(index)
}
| | | | < < < < < | | 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 |
// store minorant
self.minorants[fidx].push(MinorantInfo { minorant, index });
self.opt_mults[fidx].push(0.0);
Ok(index)
}
fn add_vars<SErr>(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtender<P, SErr>,
) -> std::result::Result<(), Either<CplexMasterError, SErr>> {
debug_assert!(!self.minorants[0].is_empty());
if changed.is_empty() && nnew == 0 {
return Ok(());
}
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);
for (fidx, mins) in self.minorants.iter_mut().enumerate() {
for m in &mut mins[..] {
let new_subg = (extend_subgradient)(fidx, &m.primal, &changedvars).map_err(Either::Right)?;
for (&j, &g) in changed.iter().zip(new_subg.iter()) {
m.linear[j] = g;
}
m.linear.extend_from_slice(&new_subg[changed.len()..]);
}
}
|
| ︙ | ︙ | |||
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 |
}
}
// Finally add the aggregated minorant.
let aggr_idx = self.add_minorant(fidx, aggr)?;
Ok((aggr_idx, aggr_coeffs))
}
fn move_center(&mut self, alpha: Real, d: &DVector) {
for mins in &mut self.minorants {
for m in mins.iter_mut() {
m.move_center_begin(alpha, d);
}
}
for submod in &mut self.submodels {
for m in &mut submod.minorants {
m.move_center_begin(alpha, d);
}
}
}
}
| > > > > > > > > > | | 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 |
}
}
// Finally add the aggregated minorant.
let aggr_idx = self.add_minorant(fidx, aggr)?;
Ok((aggr_idx, aggr_coeffs))
}
fn aggregated_primal(&self, fidx: usize) -> Result<P> {
Ok(P::combine(
self.opt_mults[fidx]
.iter()
.enumerate()
.map(|(i, alpha)| (*alpha, &self.minorants[fidx][i].primal)),
))
}
fn move_center(&mut self, alpha: Real, d: &DVector) {
for mins in &mut self.minorants {
for m in mins.iter_mut() {
m.move_center_begin(alpha, d);
}
}
for submod in &mut self.submodels {
for m in &mut submod.minorants {
m.move_center_begin(alpha, d);
}
}
}
}
impl<P: Aggregatable + 'static> CplexMaster<P> {
/// Set a custom submodel selector.
///
/// For each subproblem index the selector should return a submodel index.
/// All subproblems with the same submodel index are aggregated in a single
/// cutting plane model.
fn set_submodel_selection<F>(&mut self, selector: F)
where
|
| ︙ | ︙ | |||
774 775 776 777 778 779 780 |
Builder {
max_bundle_size: 50,
select_model: Arc::new(|i| i),
}
}
}
| | | | | 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
Builder {
max_bundle_size: 50,
select_model: Arc::new(|i| i),
}
}
}
impl<P: Aggregatable + 'static> super::Builder<P> for Builder {
type MasterProblem = CplexMaster<P>;
fn build(&mut self) -> Result<CplexMaster<P>> {
let mut cpx = CplexMaster::new()?;
cpx.max_bundle_size = self.max_bundle_size;
cpx.select_model = self.select_model.clone();
cpx.update_submodels();
Ok(cpx)
}
}
|
| ︙ | ︙ |
Changes to src/master/boxed/unconstrained/minimal.rs.
|
| | | > | 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 |
// Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de>
//
// This program is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
use super::UnconstrainedMasterProblem;
use crate::problem::SubgradientExtender;
use crate::{Aggregatable, DVector, Minorant, Real};
use either::Either;
use log::debug;
use std::error::Error;
use std::f64::NEG_INFINITY;
|
| ︙ | ︙ | |||
55 56 57 58 59 60 61 | * 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. */ | | | | | | | 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 |
* 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<P: Aggregatable> {
/// The weight of the quadratic term.
weight: Real,
/// The minorants in the model.
///
/// There are up to two minorants, each minorant consists of one part for
/// each subproblem.
///
/// The minorants for the i-th subproblem have the indices `2*i` and
/// `2*i+1`.
minorants: [Vec<Minorant<P>>; 2],
/// The number of minorants. Only the minorants with index less than this
/// number are valid.
num_minorants: usize,
/// The number of minorants for each subproblem.
num_minorants_of: Vec<usize>,
/// The number of subproblems.
num_subproblems: usize,
/// The number of subproblems with at least 1 minorant.
num_subproblems_with_1: usize,
/// The number of subproblems with at least 2 minorants.
num_subproblems_with_2: usize,
/// Optimal multipliers.
opt_mult: [Real; 2],
/// Optimal aggregated minorant.
opt_minorant: Minorant<P>,
}
impl<P: Aggregatable + Send + 'static> UnconstrainedMasterProblem<P> for MinimalMaster<P> {
type MinorantIndex = usize;
type Err = MinimalMasterError;
fn new() -> Result<MinimalMaster<P>, Self::Err> {
Ok(MinimalMaster {
weight: 1.0,
num_minorants: 0,
num_minorants_of: vec![],
num_subproblems: 0,
num_subproblems_with_1: 0,
num_subproblems_with_2: 0,
|
| ︙ | ︙ | |||
113 114 115 116 117 118 119 |
fn set_num_subproblems(&mut self, n: usize) -> Result<(), Self::Err> {
self.num_subproblems = n;
self.num_minorants = 0;
self.num_minorants_of = vec![0; n];
self.num_subproblems_with_1 = 0;
self.num_subproblems_with_2 = 0;
| | > > > | 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 |
fn set_num_subproblems(&mut self, n: usize) -> Result<(), Self::Err> {
self.num_subproblems = n;
self.num_minorants = 0;
self.num_minorants_of = vec![0; n];
self.num_subproblems_with_1 = 0;
self.num_subproblems_with_2 = 0;
self.minorants = [
(0..n).map(|_| Minorant::default()).collect(),
(0..n).map(|_| Minorant::default()).collect(),
];
Ok(())
}
fn compress<F>(&mut self, f: F) -> Result<(), Self::Err>
where
F: FnMut(Self::MinorantIndex, &mut dyn Iterator<Item = (Self::MinorantIndex, Real)>),
{
|
| ︙ | ︙ | |||
164 165 166 167 168 169 170 |
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.num_minorants_of[fidx]
}
| | | 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 |
Ok(())
}
fn num_minorants(&self, fidx: usize) -> usize {
self.num_minorants_of[fidx]
}
fn add_minorant(&mut self, fidx: usize, minorant: Minorant<P>) -> Result<usize, Self::Err> {
if self.num_minorants_of[fidx] >= 2 {
return Err(MinimalMasterError::MaxMinorants { subproblem: fidx });
}
let minidx = self.num_minorants_of[fidx];
self.num_minorants_of[fidx] += 1;
self.minorants[minidx][fidx] = minorant;
|
| ︙ | ︙ | |||
194 195 196 197 198 199 200 |
}
Ok(2 * fidx + 1)
}
_ => unreachable!("Invalid number of minorants in subproblem {}", fidx),
}
}
| | | | < < < | < | | 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 |
}
Ok(2 * fidx + 1)
}
_ => unreachable!("Invalid number of minorants in subproblem {}", fidx),
}
}
fn add_vars<SErr>(
&mut self,
nnew: usize,
changed: &[usize],
extend_subgradient: &mut SubgradientExtender<P, SErr>,
) -> Result<(), Either<Self::Err, SErr>> {
if self.num_subproblems_with_1 == 0 {
return Ok(());
}
let noldvars = self.minorants[0][self
.num_minorants_of
.iter()
.position(|&n| n > 0)
.ok_or(MinimalMasterError::NoMinorants)
.map_err(Either::Left)?]
.linear
.len();
let mut changedvars = vec![];
changedvars.extend_from_slice(changed);
changedvars.extend(noldvars..noldvars + nnew);
for fidx in 0..self.num_subproblems {
for i in 0..self.num_minorants_of[fidx] {
let new_subg =
(extend_subgradient)(fidx, &self.minorants[i][fidx].primal, &changedvars).map_err(Either::Right)?;
let m = &mut self.minorants[i][fidx];
for (&j, &g) in changed.iter().zip(new_subg.iter()) {
m.linear[j] = g;
}
m.linear.extend_from_slice(&new_subg[changed.len()..]);
}
}
|
| ︙ | ︙ | |||
298 299 300 301 302 303 304 305 306 307 308 309 310 311 |
self.opt_mult
.iter()
.take(self.num_minorants_of[fidx])
.enumerate()
.map(move |(i, alpha)| (2 * fidx + i, *alpha)),
)
}
fn eval_model(&self, y: &DVector) -> Real {
let mut result = NEG_INFINITY;
for mins in &self.minorants[0..self.num_minorants] {
result = result.max(mins.iter().map(|m| m.eval(y)).sum());
}
result
| > > > > > > > > > > | 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 |
self.opt_mult
.iter()
.take(self.num_minorants_of[fidx])
.enumerate()
.map(move |(i, alpha)| (2 * fidx + i, *alpha)),
)
}
fn aggregated_primal(&self, fidx: usize) -> Result<P, Self::Err> {
Ok(P::combine(
self.opt_mult
.iter()
.take(self.num_minorants_of[fidx])
.enumerate()
.map(|(i, alpha)| (*alpha, &self.minorants[i][fidx].primal)),
))
}
fn eval_model(&self, y: &DVector) -> Real {
let mut result = NEG_INFINITY;
for mins in &self.minorants[0..self.num_minorants] {
result = result.max(mins.iter().map(|m| m.eval(y)).sum());
}
result
|
| ︙ | ︙ | |||
387 388 389 390 391 392 393 |
impl Default for Builder {
fn default() -> Self {
Builder
}
}
| | | | | 397 398 399 400 401 402 403 404 405 406 407 408 409 410 |
impl Default for Builder {
fn default() -> Self {
Builder
}
}
impl<P: Aggregatable + Send + 'static> super::Builder<P> for Builder {
type MasterProblem = MinimalMaster<P>;
fn build(&mut self) -> Result<MinimalMaster<P>, MinimalMasterError> {
MinimalMaster::new()
}
}
|
Changes to src/master/mod.rs.
|
| | | 1 2 3 4 5 6 7 8 | // Copyright (c) 2016-2020 Frank Fischer <frank-fischer@shadow-soft.de> // // This program is free software: you can redistribute it and/or // modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the // License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, but |
| ︙ | ︙ | |||
35 36 37 38 39 40 41 |
//! * moving the center of the linear functions $\ell_i$ (and the
//! bounds), i.e. replacing $\hat{f}$ by $d \mapsto \hat{f}(d -
//! \hat{d})$ for some given $\hat{d} \in \mathbb{R}\^n$.
pub mod boxed;
pub use self::boxed::BoxedMasterProblem;
| < | | < < < < < < < < < < < < < < < < < < < < < < < < < < < < | | 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 |
//! * moving the center of the linear functions $\ell_i$ (and the
//! bounds), i.e. replacing $\hat{f}$ by $d \mapsto \hat{f}(d -
//! \hat{d})$ for some given $\hat{d} \in \mathbb{R}\^n$.
pub mod boxed;
pub use self::boxed::BoxedMasterProblem;
use crate::problem::SubgradientExtender;
use crate::{Aggregatable, DVector, Minorant, Real};
use either::Either;
use std::error::Error;
use std::result::Result;
/// Trait for master problems of a proximal bundle methods.
///
/// Note that solvers are allowed to create multiple master problems potentially
/// running them in different threads. Because of this they must implement `Send
/// + 'static`, i.e. they must be quite self-contained and independent from
/// everything else.
pub trait MasterProblem<P: Aggregatable>: Send + 'static {
/// Unique index for a minorant.
type MinorantIndex: Copy + Eq;
/// The error returned by the master problem.
type Err: Error + Send + Sync;
/// Create a new master problem.
|
| ︙ | ︙ | |||
119 120 121 122 123 124 125 |
/// 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.
| | | | < < | | 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 |
/// 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<SErr>(
&mut self,
bounds: &[(Option<usize>, Real, Real)],
extend_subgradient: &mut SubgradientExtender<P, SErr>,
) -> Result<(), Either<Self::Err, SErr>>;
/// 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<P>) -> Result<Self::MinorantIndex, Self::Err>;
/// Solve the master problem.
fn solve(&mut self, cur_value: Real) -> Result<(), Self::Err>;
/// Compress the bundle.
///
/// When some minorants are compressed, the callback is called with the
|
| ︙ | ︙ | |||
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 |
/// Return the multiplier associated with a minorant.
fn multiplier(&self, min: Self::MinorantIndex) -> Real;
/// Return the multipliers associated with a subproblem.
fn opt_multipliers<'a>(&'a self, fidx: usize) -> Box<dyn Iterator<Item = (Self::MinorantIndex, Real)> + 'a>;
/// Move the center of the master problem to $\alpha \cdot d$.
///
/// The vector `d` is allowed to be shorter than the current number of
/// variables in the master. The missing elements are assumed to be zero.
fn move_center(&mut self, alpha: Real, d: &DVector);
}
/// A builder for creating a master problem solvers.
| > > > | | | | 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 |
/// Return the multiplier associated with a minorant.
fn multiplier(&self, min: Self::MinorantIndex) -> Real;
/// Return the multipliers associated with a subproblem.
fn opt_multipliers<'a>(&'a self, fidx: usize) -> Box<dyn Iterator<Item = (Self::MinorantIndex, Real)> + 'a>;
/// Return the aggregated primal.
fn aggregated_primal(&self, fidx: usize) -> Result<P, Self::Err>;
/// Move the center of the master problem to $\alpha \cdot d$.
///
/// The vector `d` is allowed to be shorter than the current number of
/// variables in the master. The missing elements are assumed to be zero.
fn move_center(&mut self, alpha: Real, d: &DVector);
}
/// A builder for creating a master problem solvers.
pub trait Builder<P: Aggregatable> {
/// The master problem to be build.
type MasterProblem: MasterProblem<P>;
/// Create a new master problem.
fn build(&mut self) -> Result<Self::MasterProblem, <Self::MasterProblem as MasterProblem<P>>::Err>;
}
/// The full bundle builder.
pub type FullMasterBuilder = boxed::Builder<boxed::unconstrained::cpx::Builder>;
/// The minimal bundle builder.
pub type MinimalMasterBuilder = boxed::Builder<boxed::unconstrained::minimal::Builder>;
|
Deleted src/master/primalmaster.rs.
|
| < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < < |
Changes to src/mcf/problem.rs.
| ︙ | ︙ | |||
458 459 460 461 462 463 464 |
let active_constraints = self.active_constraints.read().unwrap()[0..y.len()].to_vec();
self.pool
.as_ref()
.unwrap()
.execute(move || match sub.write().unwrap().evaluate(&y, active_constraints) {
Ok((objective, subg, primal)) => {
tx.objective(objective).unwrap();
| | < | | < < > | 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 |
let active_constraints = self.active_constraints.read().unwrap()[0..y.len()].to_vec();
self.pool
.as_ref()
.unwrap()
.execute(move || match sub.write().unwrap().evaluate(&y, active_constraints) {
Ok((objective, subg, primal)) => {
tx.objective(objective).unwrap();
tx.minorant(Minorant {
constant: objective,
linear: subg,
primal,
})
.unwrap();
}
Err(err) => tx.error(err).unwrap(),
});
Ok(())
}
|
| ︙ | ︙ |
Changes to src/problem.rs.
| ︙ | ︙ | |||
27 28 29 30 31 32 33 |
{
type Err: std::error::Error + Send;
/// Send a new objective `value`.
fn objective(&self, value: Real) -> Result<(), Self::Err>;
/// Send a new `minorant` with associated `primal`.
| | | 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
{
type Err: std::error::Error + Send;
/// Send a new objective `value`.
fn objective(&self, value: Real) -> Result<(), Self::Err>;
/// Send a new `minorant` with associated `primal`.
fn minorant(&self, minorant: Minorant<P::Primal>) -> Result<(), Self::Err>;
/// Send an error message.
fn error(&self, err: P::Err) -> Result<(), Self::Err>;
}
/// The subgradient extender is a callback used to update existing minorants
/// given their associated primal data.
|
| ︙ | ︙ |
Changes to src/solver/asyn.rs.
1 | /* | | | 1 2 3 4 5 6 7 8 9 | /* * Copyright (c) 2019-2020 Frank Fischer <frank-fischer@shadow-soft.de> * * This program is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but |
| ︙ | ︙ | |||
84 85 86 87 88 89 90 |
/// The result type of the solver.
///
/// - `T` is the value type,
/// - `P` is the `FirstOrderProblem` associated with the solver,
/// - `M` is the `MasterBuilder` associated with the solver.
pub type Result<T, P, M> = std::result::Result<
T,
| > > > > | > | 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
/// The result type of the solver.
///
/// - `T` is the value type,
/// - `P` is the `FirstOrderProblem` associated with the solver,
/// - `M` is the `MasterBuilder` associated with the solver.
pub type Result<T, P, M> = std::result::Result<
T,
Error<
<<M as MasterBuilder<<P as FirstOrderProblem>::Primal>>::MasterProblem as MasterProblem<
<P as FirstOrderProblem>::Primal,
>>::Err,
<P as FirstOrderProblem>::Err,
>,
>;
impl<MErr, PErr> std::fmt::Display for Error<MErr, PErr>
where
MErr: std::fmt::Display,
PErr: std::fmt::Display,
{
|
| ︙ | ︙ | |||
390 391 392 393 394 395 396 |
}
/// Implementation of a parallel bundle method.
pub struct Solver<P, T = StandardTerminator, W = HKWeighter, M = crate::master::FullMasterBuilder>
where
P: FirstOrderProblem,
P::Err: 'static,
| | | 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 |
}
/// Implementation of a parallel bundle method.
pub struct Solver<P, T = StandardTerminator, W = HKWeighter, M = crate::master::FullMasterBuilder>
where
P: FirstOrderProblem,
P::Err: 'static,
M: MasterBuilder<P::Primal>,
{
/// Parameters for the solver.
pub params: Parameters,
/// Termination predicate.
pub terminator: T,
|
| ︙ | ︙ | |||
443 444 445 446 447 448 449 |
impl<P, T, W, M> Solver<P, T, W, M>
where
P: FirstOrderProblem,
P::Err: Send + 'static,
T: Terminator<SolverData> + Default,
W: Weighter<SolverData> + Default,
| | | | 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 |
impl<P, T, W, M> Solver<P, T, W, M>
where
P: FirstOrderProblem,
P::Err: Send + 'static,
T: Terminator<SolverData> + Default,
W: Weighter<SolverData> + Default,
M: MasterBuilder<P::Primal>,
<M::MasterProblem as MasterProblem<P::Primal>>::MinorantIndex: std::hash::Hash,
{
/// Create a new parallel bundle solver.
pub fn new(problem: P) -> Self
where
M: Default,
{
Self::with_master(problem, M::default())
|
| ︙ | ︙ | |||
684 685 686 687 688 689 690 |
EvalResult::ObjectiveValue { index, value } => {
debug!("Receive objective from subproblem {}: {}", index, value);
if self.data.nxt_ubs[index].is_infinite() {
self.data.cnt_remaining_ubs -= 1;
}
self.data.nxt_ubs[index] = self.data.nxt_ubs[index].min(value);
}
| | < < < < | | 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 |
EvalResult::ObjectiveValue { index, value } => {
debug!("Receive objective from subproblem {}: {}", index, value);
if self.data.nxt_ubs[index].is_infinite() {
self.data.cnt_remaining_ubs -= 1;
}
self.data.nxt_ubs[index] = self.data.nxt_ubs[index].min(value);
}
EvalResult::Minorant { index, mut minorant } => {
debug!("Receive minorant from subproblem {}", index);
if self.data.nxt_cutvals[index].is_infinite() {
self.data.cnt_remaining_mins -= 1;
}
// move center of minorant to cur_y
minorant.move_center(-1.0, &self.data.nxt_d);
self.data.nxt_cutvals[index] = self.data.nxt_cutvals[index].max(minorant.constant);
// add minorant to master problem
master.add_minorant(index, minorant)?;
}
EvalResult::Done { .. } => return Ok(false), // currently we do nothing ...
EvalResult::Error { err, .. } => return Err(Error::Evaluation(err)),
}
if self.data.cnt_remaining_ubs > 0 || self.data.cnt_remaining_mins > 0 {
// Haven't received data from all subproblems, yet.
|
| ︙ | ︙ |
Changes to src/solver/channels.rs.
| ︙ | ︙ | |||
16 17 18 19 20 21 22 |
*/
//! Implementation for `ResultSender` using channels.
use super::masterprocess::Response as MasterResponse;
use crate::master::MasterProblem;
use crate::problem::{FirstOrderProblem, ResultSender, SubgradientExtender, UpdateSender};
| | | > > > | > > | > > > > > > | > > > | > > > | | 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 |
*/
//! Implementation for `ResultSender` using channels.
use super::masterprocess::Response as MasterResponse;
use crate::master::MasterProblem;
use crate::problem::{FirstOrderProblem, ResultSender, SubgradientExtender, UpdateSender};
use crate::{Aggregatable, Minorant, Real};
#[cfg(feature = "crossbeam")]
use rs_crossbeam::channel::{Receiver, SendError, Sender};
#[cfg(not(feature = "crossbeam"))]
use std::sync::mpsc::{Receiver, SendError, Sender};
/// A message received from a client.
///
/// The client might be either a subproblem or a master problem process.
///
/// A client may send one of two possible messages: either an evaluation result
/// or a problem update.
pub enum Message<I, P, E, MErr>
where
P: Aggregatable,
{
/// An evaluation result.
Eval(EvalResult<I, P, E>),
/// A problem update.
Update(Update<I, P, E>),
/// A master problem result.
Master(MasterResponse<MErr, E>),
}
/// The sender for client messages.
pub type ClientSender<P, M> = Sender<
Message<
usize,
<P as FirstOrderProblem>::Primal,
<P as FirstOrderProblem>::Err,
<M as MasterProblem<<P as FirstOrderProblem>::Primal>>::Err,
>,
>;
/// The receiver for client messages.
pub type ClientReceiver<P, M> = Receiver<
Message<
usize,
<P as FirstOrderProblem>::Primal,
<P as FirstOrderProblem>::Err,
<M as MasterProblem<<P as FirstOrderProblem>::Primal>>::Err,
>,
>;
/// Parameters for tuning the solver.
/// Evaluation result.
///
/// The result of an evaluation is new information to be made
/// available to the solver and the master problem. There are
/// essentially two types of information:
///
/// 1. The (exact) function value of a sub-function at some point.
/// 2. A minorant of some sub-function.
#[derive(Debug)]
pub enum EvalResult<I, P, E>
where
P: Aggregatable,
{
/// The objective value at some point.
ObjectiveValue { index: I, value: Real },
/// A minorant with an associated primal.
Minorant { index: I, minorant: Minorant<P> },
/// An error occurred.
Error { index: I, err: E },
/// Done, no further message will be received from this evaluation.
Done { index: I },
}
/// Problem update information.
|
| ︙ | ︙ | |||
93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 |
/// Done, no further message will be received from this evaluation.
Done { index: I },
}
pub struct ChannelResultSender<I, P, E, M>
where
I: Clone,
{
index: I,
tx: Sender<Message<I, P, E, M>>,
}
impl<I, P, E, M> ChannelResultSender<I, P, E, M>
where
I: Clone,
{
pub fn new(index: I, tx: Sender<Message<I, P, E, M>>) -> Self {
ChannelResultSender { index, tx }
}
}
impl<I, P, M> ResultSender<P> for ChannelResultSender<I, P::Primal, P::Err, M>
| > > | 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
/// Done, no further message will be received from this evaluation.
Done { index: I },
}
pub struct ChannelResultSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
index: I,
tx: Sender<Message<I, P, E, M>>,
}
impl<I, P, E, M> ChannelResultSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
pub fn new(index: I, tx: Sender<Message<I, P, E, M>>) -> Self {
ChannelResultSender { index, tx }
}
}
impl<I, P, M> ResultSender<P> for ChannelResultSender<I, P::Primal, P::Err, M>
|
| ︙ | ︙ | |||
123 124 125 126 127 128 129 |
fn objective(&self, value: Real) -> Result<(), Self::Err> {
self.tx.send(Message::Eval(EvalResult::ObjectiveValue {
index: self.index.clone(),
value,
}))
}
| | < > > > | 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 |
fn objective(&self, value: Real) -> Result<(), Self::Err> {
self.tx.send(Message::Eval(EvalResult::ObjectiveValue {
index: self.index.clone(),
value,
}))
}
fn minorant(&self, minorant: Minorant<P::Primal>) -> Result<(), Self::Err> {
self.tx.send(Message::Eval(EvalResult::Minorant {
index: self.index.clone(),
minorant,
}))
}
fn error(&self, err: P::Err) -> Result<(), Self::Err> {
self.tx.send(Message::Eval(EvalResult::Error {
index: self.index.clone(),
err,
}))
}
}
impl<I, P, E, M> Drop for ChannelResultSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
fn drop(&mut self) {
self.tx
.send(Message::Eval(EvalResult::Done {
index: self.index.clone(),
}))
.unwrap()
}
}
pub struct ChannelUpdateSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
index: I,
tx: Sender<Message<I, P, E, M>>,
}
impl<I, P, E, M> ChannelUpdateSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
pub fn new(index: I, tx: Sender<Message<I, P, E, M>>) -> Self {
ChannelUpdateSender { index, tx }
}
}
impl<I, P, M> UpdateSender<P> for ChannelUpdateSender<I, P::Primal, P::Err, M>
|
| ︙ | ︙ | |||
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 |
}))
}
}
impl<I, P, E, M> Drop for ChannelUpdateSender<I, P, E, M>
where
I: Clone,
{
fn drop(&mut self) {
self.tx
.send(Message::Update(Update::Done {
index: self.index.clone(),
}))
.unwrap()
}
}
| > | 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 |
}))
}
}
impl<I, P, E, M> Drop for ChannelUpdateSender<I, P, E, M>
where
I: Clone,
P: Aggregatable,
{
fn drop(&mut self) {
self.tx
.send(Message::Update(Update::Done {
index: self.index.clone(),
}))
.unwrap()
}
}
|
Changes to src/solver/masterprocess.rs.
| ︙ | ︙ | |||
24 25 26 27 28 29 30 |
use either::Either;
use log::{debug, warn};
use std::sync::Arc;
use threadpool::ThreadPool;
use super::channels::{ClientSender, Message};
| < | | 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
use either::Either;
use log::{debug, warn};
use std::sync::Arc;
use threadpool::ThreadPool;
use super::channels::{ClientSender, Message};
use crate::master::MasterProblem;
use crate::problem::{FirstOrderProblem, SubgradientExtender};
use crate::{Aggregatable, DVector, Minorant, Real};
#[derive(Debug)]
pub enum Error<MErr, PErr> {
/// The communication channel for sending requests has been disconnected.
DisconnectedSender,
/// The communication channel for sending responds has been disconnected.
DisconnectedReceiver,
|
| ︙ | ︙ | |||
107 108 109 110 111 112 113 |
/// The lower bounds on the variables.
pub upper_bounds: Option<DVector>,
}
/// A task for the master problem.
enum MasterTask<Pr, PErr, M>
where
| | > | | 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 |
/// The lower bounds on the variables.
pub upper_bounds: Option<DVector>,
}
/// A task for the master problem.
enum MasterTask<Pr, PErr, M>
where
M: MasterProblem<Pr>,
Pr: Aggregatable,
{
/// Add new variables to the master problem.
AddVariables(Vec<(Option<usize>, Real, Real)>, Box<SubgradientExtender<Pr, PErr>>),
/// Add a new minorant for a subfunction to the master problem.
AddMinorant(usize, Minorant<Pr>),
/// Move the center of the master problem in the given direction.
MoveCenter(Real, Arc<DVector>),
/// Start a new computation of the master problem.
Solve { center_value: Real },
|
| ︙ | ︙ | |||
151 152 153 154 155 156 157 |
cnt_updates: usize,
},
/// An error occurred.
Error(Error<MErr, PErr>),
}
/// Convenient type for `Response`.
| | > | | | 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 |
cnt_updates: usize,
},
/// An error occurred.
Error(Error<MErr, PErr>),
}
/// Convenient type for `Response`.
pub type MasterResponse<P, M> =
Response<<M as MasterProblem<<P as FirstOrderProblem>::Primal>>::Err, <P as FirstOrderProblem>::Err>;
type ToMasterSender<P, M> = Sender<MasterTask<<P as FirstOrderProblem>::Primal, <P as FirstOrderProblem>::Err, M>>;
type ToMasterReceiver<P, M> = Receiver<MasterTask<<P as FirstOrderProblem>::Primal, <P as FirstOrderProblem>::Err, M>>;
pub struct MasterProcess<P, M>
where
P: FirstOrderProblem,
M: MasterProblem<P::Primal>,
{
/// The channel to transmit new tasks to the master problem.
tx: ToMasterSender<P, M>,
phantom: std::marker::PhantomData<M>,
}
impl<P, M> MasterProcess<P, M>
where
P: FirstOrderProblem,
P::Primal: Send + 'static,
P::Err: Send + 'static,
M: MasterProblem<P::Primal> + Send + 'static,
M::MinorantIndex: std::hash::Hash,
M::Err: Send + 'static,
{
pub fn start(master: M, master_config: MasterConfig, tx: ClientSender<P, M>, threadpool: &mut ThreadPool) -> Self {
// Create a pair of communication channels.
let (to_master_tx, to_master_rx) = channel();
|
| ︙ | ︙ | |||
217 218 219 220 221 222 223 |
Ok(self.tx.send(MasterTask::AddVariables(vars, sgext))?)
}
/// Add a new minorant to the master problem model.
///
/// This adds the specified `minorant` with associated `primal` data to the
/// model of subproblem `i`.
| < < < < < | | | 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
Ok(self.tx.send(MasterTask::AddVariables(vars, sgext))?)
}
/// Add a new minorant to the master problem model.
///
/// This adds the specified `minorant` with associated `primal` data to the
/// model of subproblem `i`.
pub fn add_minorant(&mut self, i: usize, minorant: Minorant<P::Primal>) -> Result<(), Error<M::Err, P::Err>> {
Ok(self.tx.send(MasterTask::AddMinorant(i, minorant))?)
}
/// Move the center of the master problem.
///
/// This moves the master problem's center in direction $\\alpha \\cdot d$.
pub fn move_center(&mut self, alpha: Real, d: Arc<DVector>) -> Result<(), Error<M::Err, P::Err>> {
Ok(self.tx.send(MasterTask::MoveCenter(alpha, d))?)
|
| ︙ | ︙ | |||
267 268 269 270 271 272 273 |
fn master_main(
master: M,
master_config: MasterConfig,
tx: &mut ClientSender<P, M>,
rx: ToMasterReceiver<P, M>,
subgradient_extender: &mut Option<Box<SubgradientExtender<P::Primal, P::Err>>>,
) -> Result<(), Error<M::Err, P::Err>> {
| | | | | | | | 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 |
fn master_main(
master: M,
master_config: MasterConfig,
tx: &mut ClientSender<P, M>,
rx: ToMasterReceiver<P, M>,
subgradient_extender: &mut Option<Box<SubgradientExtender<P::Primal, P::Err>>>,
) -> Result<(), Error<M::Err, P::Err>> {
let mut master = master;
// Initialize the master problem.
master
.set_num_subproblems(master_config.num_subproblems)
.map_err(Error::Master)?;
master
.set_vars(
master_config.num_vars,
master_config.lower_bounds,
master_config.upper_bounds,
)
.map_err(Error::Master)?;
// The main iteration: wait for new tasks.
for m in rx {
match m {
MasterTask::AddVariables(vars, mut sgext) => {
debug!("master: add {} variables to the subproblem", vars.len());
master.add_vars(&vars, &mut sgext).map_err(|err| match err {
Either::Left(err) => Error::Master(err),
Either::Right(err) => Error::SubgradientExtension(err),
})?;
*subgradient_extender = Some(sgext);
}
MasterTask::AddMinorant(i, mut m) => {
debug!("master: add minorant to subproblem {}", i);
// It may happen the number new minorant belongs to an earlier evaluation
// with less variables (i.e. new variables have been added
// after the start of the evaluation but before the new
// minorant is added, i.e. now). In this case we must add
// extend the minorant accordingly.
if m.linear.len() < master.num_variables() {
if let Some(ref mut sgext) = subgradient_extender {
let newinds = (m.linear.len()..master.num_variables()).collect::<Vec<_>>();
let new_subg =
sgext(i, &m.primal, &newinds).map_err(Error::<M::Err, P::Err>::SubgradientExtension)?;
m.linear.extend(new_subg);
}
}
master.add_minorant(i, m).map_err(Error::Master)?;
}
MasterTask::MoveCenter(alpha, d) => {
debug!("master: move center");
master.move_center(alpha, &d);
}
MasterTask::Compress => {
debug!("Compress bundle");
master.compress(|_, _| {}).map_err(Error::Master)?;
}
MasterTask::Solve { center_value } => {
debug!("master: solve with center_value {}", center_value);
master.solve(center_value).map_err(Error::Master)?;
let master_response = Response::Result {
nxt_d: master.get_primopt(),
nxt_mod: master.get_primoptval(),
|
| ︙ | ︙ | |||
339 340 341 342 343 344 345 |
debug!("master: set weight {}", weight);
master.set_weight(weight).map_err(Error::Master)?;
}
MasterTask::GetAggregatedPrimal { subproblem, tx } => {
debug!("master: get aggregated primal for {}", subproblem);
if tx.send(master.aggregated_primal(subproblem)).is_err() {
warn!("Sending of aggregated primal for {} failed", subproblem);
| < > | 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 |
debug!("master: set weight {}", weight);
master.set_weight(weight).map_err(Error::Master)?;
}
MasterTask::GetAggregatedPrimal { subproblem, tx } => {
debug!("master: get aggregated primal for {}", subproblem);
if tx.send(master.aggregated_primal(subproblem)).is_err() {
warn!("Sending of aggregated primal for {} failed", subproblem);
}
}
};
}
Ok(())
}
}
|
Changes to src/solver/sync.rs.
| ︙ | ︙ | |||
83 84 85 86 87 88 89 |
/// The result type of the solver.
///
/// - `T` is the value type,
/// - `P` is the `FirstOrderProblem` associated with the solver,
/// - `M` is the `MasterBuilder` associated with the solver.
pub type Result<T, P, M> = std::result::Result<
T,
| > > > > | > | 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 |
/// The result type of the solver.
///
/// - `T` is the value type,
/// - `P` is the `FirstOrderProblem` associated with the solver,
/// - `M` is the `MasterBuilder` associated with the solver.
pub type Result<T, P, M> = std::result::Result<
T,
Error<
<<M as MasterBuilder<<P as FirstOrderProblem>::Primal>>::MasterProblem as MasterProblem<
<P as FirstOrderProblem>::Primal,
>>::Err,
<P as FirstOrderProblem>::Err,
>,
>;
impl<MErr, PErr> std::fmt::Display for Error<MErr, PErr>
where
MErr: std::fmt::Display,
PErr: std::fmt::Display,
{
|
| ︙ | ︙ | |||
388 389 390 391 392 393 394 |
}
}
/// Implementation of a parallel bundle method.
pub struct Solver<P, T = StandardTerminator, W = HKWeighter, M = crate::master::FullMasterBuilder>
where
P: FirstOrderProblem,
| | | 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 |
}
}
/// Implementation of a parallel bundle method.
pub struct Solver<P, T = StandardTerminator, W = HKWeighter, M = crate::master::FullMasterBuilder>
where
P: FirstOrderProblem,
M: MasterBuilder<P::Primal>,
P::Err: 'static,
{
/// Parameters for the solver.
pub params: Parameters,
/// Termination predicate.
pub terminator: T,
|
| ︙ | ︙ | |||
442 443 444 445 446 447 448 |
impl<P, T, W, M> Solver<P, T, W, M>
where
P: FirstOrderProblem,
P::Err: Send + 'static,
T: Terminator<SolverData> + Default,
W: Weighter<SolverData> + Default,
| | | | 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 |
impl<P, T, W, M> Solver<P, T, W, M>
where
P: FirstOrderProblem,
P::Err: Send + 'static,
T: Terminator<SolverData> + Default,
W: Weighter<SolverData> + Default,
M: MasterBuilder<P::Primal>,
<M::MasterProblem as MasterProblem<P::Primal>>::MinorantIndex: std::hash::Hash,
{
/// Create a new parallel bundle solver.
pub fn new(problem: P) -> Self
where
M: Default,
{
Self::with_master(problem, M::default())
|
| ︙ | ︙ | |||
656 657 658 659 660 661 662 |
EvalResult::ObjectiveValue { index, value } => {
debug!("Receive objective from subproblem {}: {}", index, value);
if self.data.nxt_ubs[index].is_infinite() {
self.data.cnt_remaining_ubs -= 1;
}
self.data.nxt_ubs[index] = self.data.nxt_ubs[index].min(value);
}
| | < < < < | | 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 |
EvalResult::ObjectiveValue { index, value } => {
debug!("Receive objective from subproblem {}: {}", index, value);
if self.data.nxt_ubs[index].is_infinite() {
self.data.cnt_remaining_ubs -= 1;
}
self.data.nxt_ubs[index] = self.data.nxt_ubs[index].min(value);
}
EvalResult::Minorant { index, mut minorant } => {
debug!("Receive minorant from subproblem {}", index);
if self.data.nxt_cutvals[index].is_infinite() {
self.data.cnt_remaining_mins -= 1;
}
// move center of minorant to cur_y
minorant.move_center(-1.0, &self.data.nxt_d);
self.data.nxt_cutvals[index] = self.data.nxt_cutvals[index].max(minorant.constant);
// add minorant to master problem
master.add_minorant(index, minorant)?;
}
EvalResult::Done { .. } => return Ok(false), // nothing to do here
EvalResult::Error { err, .. } => return Err(Error::Evaluation(err)),
}
if self.data.cnt_remaining_ubs > 0 || self.data.cnt_remaining_mins > 0 {
// Haven't received data from all subproblems, yet.
|
| ︙ | ︙ |