Many hyperlinks are disabled.
Use anonymous login
to enable hyperlinks.
Overview
| Comment: | Remove empty lines |
|---|---|
| Downloads: | Tarball | ZIP archive |
| Timelines: | family | ancestors | descendants | both | trunk |
| Files: | files | file ages | folders |
| SHA1: |
25714ffdeaf19d7a452d53dbb40187d0 |
| User & Date: | fifr 2017-12-13 22:48:48.598 |
Context
|
2017-12-28
| ||
| 23:07 | Update dependency on log to v0.4 check-in: 39f7398b3e user: fifr tags: trunk | |
|
2017-12-13
| ||
| 22:48 | Remove empty lines check-in: 25714ffdea user: fifr tags: trunk | |
|
2017-11-21
| ||
| 20:55 | Use `c_str_macro` instead of `const-cstr` check-in: 7d4dd3e3ac user: fifr tags: trunk | |
Changes
Changes to src/firstorderproblem.rs.
| ︙ | ︙ | |||
32 33 34 35 36 37 38 |
* The subgradients (linear minorants) can be obtained by iterating over the result. The
* subgradients are centered around the point of evaluation.
*/
pub trait Evaluation<P>: IntoIterator<Item = (Minorant, P)> {
/// Return the function value at the point of evaluation.
fn objective(&self) -> Real;
}
| < | 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
* The subgradients (linear minorants) can be obtained by iterating over the result. The
* subgradients are centered around the point of evaluation.
*/
pub trait Evaluation<P>: IntoIterator<Item = (Minorant, P)> {
/// Return the function value at the point of evaluation.
fn objective(&self) -> Real;
}
/**
* Simple standard evaluation result.
*
* This result consists of the function value and a list of one or
* more minorants and associated primal information.
*/
|
| ︙ | ︙ |
Changes to src/hkweighter.rs.
| ︙ | ︙ | |||
10 11 12 13 14 15 16 | // 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/> // | < | 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | // 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/> // //! Weight updating rule according to Helmberg and Kiwiel. //! //! The procedure is described in //! //! > Helmberg, C. and Kiwiel, K.C. (2002): A spectral bundle method //! > with bounds, Math. Programming A 93, 173--194 //! |
| ︙ | ︙ | |||
109 110 111 112 113 114 115 |
self.iter = -1
} else {
self.iter = min(self.iter - 1, -1);
}
debug!(
" sgnorm={} cur_val={} new_cutval={} lin_err={} eps_weight={}",
| < < | < < | 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
self.iter = -1
} else {
self.iter = min(self.iter - 1, -1);
}
debug!(
" sgnorm={} cur_val={} new_cutval={} lin_err={} eps_weight={}",
sgnorm, state.cur_val, state.new_cutval, lin_err, self.eps_weight
);
debug!(" new_weight={}", new_weight);
new_weight
} else {
self.model_max = self.model_max.max(state.nxt_mod);
let new_weight = if self.iter > 0 && cur_nxt > self.m_r * cur_mod {
|
| ︙ | ︙ |
Changes to src/master/base.rs.
| ︙ | ︙ | |||
49 50 51 52 53 54 55 |
/// 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 FnMut(usize, Self::MinorantIndex, &[usize]) -> DVector,
) -> Result<(), Error>;
| < | 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
/// 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 FnMut(usize, Self::MinorantIndex, &[usize]) -> DVector,
) -> Result<(), Error>;
/// 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, Error>;
|
| ︙ | ︙ |
Changes to src/master/boxed.rs.
| ︙ | ︙ | |||
55 56 57 58 59 60 61 |
/// Current number of updates.
cnt_updates: usize,
/// The unconstrained master problem solver.
master: M,
}
| < | 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
/// Current number of updates.
cnt_updates: usize,
/// The unconstrained master problem solver.
master: M,
}
impl<M: UnconstrainedMasterProblem> BoxedMasterProblem<M> {
pub fn new(master: M) -> BoxedMasterProblem<M> {
BoxedMasterProblem {
lb: dvec![],
ub: dvec![],
eta: dvec![],
primopt: dvec![],
|
| ︙ | ︙ | |||
178 179 180 181 182 183 184 |
.iter()
.zip(self.eta.iter())
.map(|(x, y)| x * y)
.sum()
}
}
| < | 177 178 179 180 181 182 183 184 185 186 187 188 189 190 |
.iter()
.zip(self.eta.iter())
.map(|(x, y)| x * y)
.sum()
}
}
impl<M: UnconstrainedMasterProblem> MasterProblem for BoxedMasterProblem<M> {
type MinorantIndex = M::MinorantIndex;
fn set_num_subproblems(&mut self, n: usize) -> Result<(), Error> {
self.master.set_num_subproblems(n)
}
|
| ︙ | ︙ | |||
292 293 294 295 296 297 298 |
debug!(
" cut-lin={} < eps*(cur-lin)={}",
cutval - linval,
self.model_eps * (curval - linval)
);
debug!(
" cnt_update={} max_updates={}",
| | < | 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 |
debug!(
" cut-lin={} < eps*(cur-lin)={}",
cutval - linval,
self.model_eps * (curval - linval)
);
debug!(
" cnt_update={} max_updates={}",
cnt_updates, self.max_updates
);
self.primoptval = linval;
if augval < old_augval + 1e-10 || cutval - linval < self.model_eps * (curval - linval)
|| cnt_updates >= self.max_updates
{
|
| ︙ | ︙ |
Changes to src/master/cpx.rs.
| ︙ | ︙ | |||
70 71 72 73 74 75 76 |
impl Drop for CplexMaster {
fn drop(&mut self) {
unsafe { cpx::freeprob(cpx::env(), &mut self.lp) };
}
}
| < | 70 71 72 73 74 75 76 77 78 79 80 81 82 83 |
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, Error> {
Ok(CplexMaster {
lp: ptr::null_mut(),
force_update: true,
|
| ︙ | ︙ | |||
383 384 385 386 387 388 389 |
for mins in &mut self.minorants {
for m in mins.iter_mut() {
m.move_center(alpha, d);
}
}
}
}
| < | 382 383 384 385 386 387 388 389 390 391 392 393 394 395 |
for mins in &mut self.minorants {
for m in mins.iter_mut() {
m.move_center(alpha, d);
}
}
}
}
impl CplexMaster {
fn init_qp(&mut self) -> Result<(), Error> {
if !self.lp.is_null() {
trycpx!(cpx::freeprob(cpx::env(), &mut self.lp));
}
trycpx!({
|
| ︙ | ︙ |
Changes to src/master/minimal.rs.
| ︙ | ︙ | |||
18 19 20 21 22 23 24 | use master::UnconstrainedMasterProblem; use std::f64::NEG_INFINITY; use std::result::Result; use failure::Error; | < | 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
use master::UnconstrainedMasterProblem;
use std::f64::NEG_INFINITY;
use std::result::Result;
use failure::Error;
/// Minimal master problem error.
#[derive(Debug, Fail)]
pub enum MinimalMasterError {
#[fail(display = "Solver Error: too many subproblems (got: {} must be <= 2)", nsubs)]
NumSubproblems {
nsubs: usize,
},
|
| ︙ | ︙ | |||
53 54 55 56 57 58 59 |
/// The minorants in the model.
minorants: Vec<Minorant>,
/// Optimal multipliers.
opt_mult: DVector,
/// Optimal aggregated minorant.
opt_minorant: Minorant,
}
| < | 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
/// 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, Error> {
Ok(MinimalMaster {
weight: 1.0,
|
| ︙ | ︙ |
Changes to src/mcf/problem.rs.
| ︙ | ︙ | |||
64 65 66 67 68 69 70 |
}
let fnod = buffer
.split_whitespace()
.map(|x| x.parse::<usize>().unwrap())
.collect::<Vec<_>>();
if fnod.len() != 4 {
| | < | | | | | | < | 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
}
let fnod = buffer
.split_whitespace()
.map(|x| x.parse::<usize>().unwrap())
.collect::<Vec<_>>();
if fnod.len() != 4 {
return Err(MCFFormatError {
msg: format!(
"Expected 4 numbers in {}.nod, but got {}",
basename,
fnod.len()
),
}.into());
}
let ncom = fnod[0];
let nnodes = fnod[1];
let narcs = fnod[2];
let ncaps = fnod[3];
|
| ︙ | ︙ | |||
134 135 136 137 138 139 140 |
let coeff = arcmap[com].len();
arcmap[com].push(ArcInfo {
arc: arc + 1,
src: src + 1,
snk: snk + 1,
});
// add arc
| | < < < < < | 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 |
let coeff = arcmap[com].len();
arcmap[com].push(ArcInfo {
arc: arc + 1,
src: src + 1,
snk: snk + 1,
});
// add arc
try!(nets[com].add_arc(src, snk, cost, if cap < 0.0 { INFINITY } else { cap }));
// set objective
cbase[com].push(cost); // + 1e-6 * coeff
// add to mutual capacity constraint
if mt >= 0 {
lhsidx[mt as usize][com].push(coeff);
}
}
|
| ︙ | ︙ |
Changes to src/mcf/solver.rs.
| ︙ | ︙ | |||
30 31 32 33 34 35 36 |
use failure::{err_msg, Error};
pub struct Solver {
net: *mut cpx::Net,
logfile: *mut cpx::File,
}
| < | 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
use failure::{err_msg, Error};
pub struct Solver {
net: *mut cpx::Net,
logfile: *mut cpx::File,
}
impl Drop for Solver {
fn drop(&mut self) {
unsafe {
cpx::NETfreeprob(cpx::env(), &mut self.net);
cpx::fclose(self.logfile);
}
}
|
| ︙ | ︙ | |||
80 81 82 83 84 85 86 |
if status != 0 {
let msg = CString::new(vec![0; cpx::MESSAGE_BUF_SIZE])
.unwrap()
.into_raw();
cpx::geterrorstring(cpx::env(), status, msg);
cpx::NETfreeprob(cpx::env(), &mut net);
cpx::fclose(logfile);
| | < | | | < | 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 |
if status != 0 {
let msg = CString::new(vec![0; cpx::MESSAGE_BUF_SIZE])
.unwrap()
.into_raw();
cpx::geterrorstring(cpx::env(), status, msg);
cpx::NETfreeprob(cpx::env(), &mut net);
cpx::fclose(logfile);
return Err(cpx::CplexError {
code: status,
msg: CString::from_raw(msg).to_string_lossy().into_owned(),
}.into());
}
}
Ok(Solver {
net: net,
logfile: logfile,
})
|
| ︙ | ︙ |
Changes to src/minorant.rs.
| ︙ | ︙ | |||
35 36 37 38 39 40 41 |
pub struct Minorant {
/// The constant term.
pub constant: Real,
/// The linear term.
pub linear: DVector,
}
| < < | 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
pub struct Minorant {
/// The constant term.
pub constant: Real,
/// The linear term.
pub linear: DVector,
}
impl fmt::Display for Minorant {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
try!(write!(f, "{} + y * {}", self.constant, self.linear));
Ok(())
}
}
|
| ︙ | ︙ |
Changes to src/solver.rs.
| ︙ | ︙ | |||
138 139 140 141 142 143 144 |
* whether the solution process should be stopped.
*/
pub trait Terminator {
/// Return true if the method should stop.
fn terminate(&mut self, state: &BundleState, params: &SolverParams) -> bool;
}
| < | 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
* whether the solution process should be stopped.
*/
pub trait Terminator {
/// Return true if the method should stop.
fn terminate(&mut self, state: &BundleState, params: &SolverParams) -> bool;
}
/**
* Terminates if expected progress is small enough.
*/
pub struct StandardTerminator {
pub termination_precision: Real,
}
|
| ︙ | ︙ | |||
229 230 231 232 233 234 235 |
Err(SolverError::Parameter(format!(
"acceptance_factor must be in (0,1) (got: {})",
self.acceptance_factor
)))
} else if self.nullstep_factor <= 0.0 || self.nullstep_factor > self.acceptance_factor {
Err(SolverError::Parameter(format!(
"nullstep_factor must be in (0,acceptance_factor] (got: {}, acceptance_factor:{})",
| | < | < | 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 |
Err(SolverError::Parameter(format!(
"acceptance_factor must be in (0,1) (got: {})",
self.acceptance_factor
)))
} else if self.nullstep_factor <= 0.0 || self.nullstep_factor > self.acceptance_factor {
Err(SolverError::Parameter(format!(
"nullstep_factor must be in (0,acceptance_factor] (got: {}, acceptance_factor:{})",
self.nullstep_factor, self.acceptance_factor
)))
} else if self.min_weight <= 0.0 {
Err(SolverError::Parameter(format!(
"min_weight must be in > 0 (got: {})",
self.min_weight
)))
} else if self.max_weight < self.min_weight {
Err(SolverError::Parameter(format!(
"max_weight must be in >= min_weight (got: {}, min_weight: {})",
self.max_weight, self.min_weight
)))
} else if self.max_updates == 0 {
Err(SolverError::Parameter(format!(
"max_updates must be in > 0 (got: {})",
self.max_updates
)))
} else {
|
| ︙ | ︙ | |||
270 271 272 273 274 275 276 |
max_weight: 1000.0,
max_updates: 50,
}
}
}
| < < < | 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 |
max_weight: 1000.0,
max_updates: 50,
}
}
}
/// The step type that has been performed.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum Step {
/// A null step has been performed.
Null,
/// A descent step has been performed.
Descent,
/// No step but the algorithm has been terminated.
Term,
}
/// Information about a minorant.
#[derive(Debug, Clone)]
struct MinorantInfo<Pr> {
/// The minorant's index in the master problem
index: usize,
/// Current multiplier.
multiplier: Real,
/// Primal associated with this minorant.
primal: Option<Pr>,
}
/// Information about the last iteration.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum IterationInfo {
NewMinorantTooHigh { new: Real, old: Real },
UpperBoundNullStep,
ShallowCut,
}
/// State information for the update callback.
pub struct UpdateState<'a, Pr: 'a> {
/// Current model minorants.
minorants: &'a [Vec<MinorantInfo<Pr>>],
/// The last step type.
pub step: Step,
|
| ︙ | ︙ | |||
431 432 433 434 435 436 437 |
/// The active minorant indices for each subproblem.
minorants: Vec<Vec<MinorantInfo<Pr>>>,
/// Accumulated information about the last iteration.
iterinfos: Vec<IterationInfo>,
}
| < | 425 426 427 428 429 430 431 432 433 434 435 436 437 438 |
/// The active minorant indices for each subproblem.
minorants: Vec<Vec<MinorantInfo<Pr>>>,
/// Accumulated information about the last iteration.
iterinfos: Vec<IterationInfo>,
}
impl<P, Pr, E> Solver<P, Pr, E>
where
P: for<'a> FirstOrderProblem<'a, Primal = Pr, EvalResult = E>,
E: Evaluation<Pr>,
{
/**
* Create a new solver for the given problem.
|
| ︙ | ︙ | |||
472 473 474 475 476 477 478 |
nxt_mods: dvec![],
new_cutval: 0.0,
sgnorm: 0.0,
expected_progress: 0.0,
cnt_descent: 0,
cnt_null: 0,
start_time: Instant::now(),
| | | < | 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 |
nxt_mods: dvec![],
new_cutval: 0.0,
sgnorm: 0.0,
expected_progress: 0.0,
cnt_descent: 0,
cnt_null: 0,
start_time: Instant::now(),
master: Box::new(BoxedMasterProblem::new(MinimalMaster::new()
.map_err(SolverError::Master)?)),
minorants: vec![],
iterinfos: vec![],
})
}
/// A new solver with default parameter.
pub fn new(problem: P) -> Result<Solver<P, Pr, E>, SolverError> {
|
| ︙ | ︙ | |||
756 757 758 759 760 761 762 |
* information.
*/
fn init_master(&mut self) -> Result<(), SolverError> {
let m = self.problem.num_subproblems();
self.master = if m == 1 && self.params.max_bundle_size == 2 {
debug!("Use minimal master problem");
| | | < | | < | 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 |
* information.
*/
fn init_master(&mut self) -> Result<(), SolverError> {
let m = self.problem.num_subproblems();
self.master = if m == 1 && self.params.max_bundle_size == 2 {
debug!("Use minimal master problem");
Box::new(BoxedMasterProblem::new(MinimalMaster::new()
.map_err(SolverError::Master)?))
} else {
debug!("Use CPLEX master problem");
Box::new(BoxedMasterProblem::new(CplexMaster::new()
.map_err(SolverError::Master)?))
};
let lb = self.problem.lower_bounds().map(DVector);
let ub = self.problem.upper_bounds().map(DVector);
if lb.as_ref()
.map(|lb| lb.len() != self.problem.num_variables())
|
| ︙ | ︙ | |||
846 847 848 849 850 851 852 |
.map_err(SolverError::Master)?;
debug!("Init master completed");
Ok(())
}
| < | 836 837 838 839 840 841 842 843 844 845 846 847 848 849 |
.map_err(SolverError::Master)?;
debug!("Init master completed");
Ok(())
}
/// Solve the model (i.e. master problem) to compute the next candidate.
fn solve_model(&mut self) -> Result<(), SolverError> {
self.master
.solve(self.cur_val)
.map_err(SolverError::Master)?;
self.nxt_d = self.master.get_primopt();
self.nxt_y.add(&self.cur_y, &self.nxt_d);
|
| ︙ | ︙ | |||
871 872 873 874 875 876 877 |
debug!("Model result");
debug!(" cur_val ={}", self.cur_val);
debug!(" nxt_mod ={}", self.nxt_mod);
debug!(" expected={}", self.expected_progress);
Ok(())
}
| < | 860 861 862 863 864 865 866 867 868 869 870 871 872 873 |
debug!("Model result");
debug!(" cur_val ={}", self.cur_val);
debug!(" nxt_mod ={}", self.nxt_mod);
debug!(" expected={}", self.expected_progress);
Ok(())
}
/// Reduce size of bundle.
fn compress_bundle(&mut self) -> Result<(), SolverError> {
for i in 0..self.problem.num_subproblems() {
let n = self.master.num_minorants(i);
if n >= self.params.max_bundle_size {
// aggregate minorants with smallest coefficients
|
| ︙ | ︙ | |||
1010 1011 1012 1013 1014 1015 1016 |
primal: Some(nxt_primal),
});
}
if self.new_cutval > self.cur_val + 1e-3 {
warn!(
"New minorant has higher value in center new:{} old:{}",
| | < | 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 |
primal: Some(nxt_primal),
});
}
if self.new_cutval > self.cur_val + 1e-3 {
warn!(
"New minorant has higher value in center new:{} old:{}",
self.new_cutval, self.cur_val
);
self.cur_val = self.new_cutval;
self.iterinfos.push(IterationInfo::NewMinorantTooHigh {
new: self.new_cutval,
old: self.cur_val,
});
}
|
| ︙ | ︙ | |||
1070 1071 1072 1073 1074 1075 1076 |
* This value is $f(\hat{y}) + \varrho' \cdot \Delta$ where
* $\Delta = f(\hat{y}) - \hat{f}(\bar{y})$ is the expected
* progress and $\varrho'$ is the `nullstep_factor`.
*/
fn get_nullstep_bound(&self) -> Real {
self.cur_val - self.params.nullstep_factor * (self.cur_val - self.nxt_mod)
}
| < | 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 |
* This value is $f(\hat{y}) + \varrho' \cdot \Delta$ where
* $\Delta = f(\hat{y}) - \hat{f}(\bar{y})$ is the expected
* progress and $\varrho'$ is the `nullstep_factor`.
*/
fn get_nullstep_bound(&self) -> Real {
self.cur_val - self.params.nullstep_factor * (self.cur_val - self.nxt_mod)
}
/**
* Return the bound the function value must be below of to enforce a descent step.
*
* If the oracle guarantees that $f(\bar{y}) \le$ this bound, the
* bundle method will perform a descent step.
*
|
| ︙ | ︙ |
Changes to src/vector.rs.
| ︙ | ︙ | |||
84 85 86 87 88 89 90 |
*/
Sparse {
size: usize,
elems: Vec<(usize, Real)>,
},
}
| < < | 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 |
*/
Sparse {
size: usize,
elems: Vec<(usize, Real)>,
},
}
impl fmt::Display for Vector {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
Vector::Dense(ref v) => write!(f, "{}", v),
Vector::Sparse { size, ref elems } => {
let mut it = elems.iter();
try!(write!(f, "{}:(", size));
if let Some(&(i, x)) = it.next() {
try!(write!(f, "{}:{}", i, x));
for &(i, x) in it {
try!(write!(f, ", {}:{}", i, x));
}
}
write!(f, ")")
}
}
}
}
impl DVector {
/// Set all elements to 0.
pub fn init0(&mut self, size: usize) {
self.clear();
self.extend((0..size).map(|_| 0.0));
// let n = self.len();
|
| ︙ | ︙ | |||
202 203 204 205 206 207 208 |
// self.resize(y.len(), 0.0);
// }
// for i in 0..y.len() {
// unsafe { *self.get_unchecked_mut(i) += alpha * *y.get_unchecked(i) };
// }
}
| < < < | 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 |
// self.resize(y.len(), 0.0);
// }
// for i in 0..y.len() {
// unsafe { *self.get_unchecked_mut(i) += alpha * *y.get_unchecked(i) };
// }
}
/// Combines this vector with another vector.
pub fn combine(&self, self_factor: Real, other_factor: Real, other: &DVector) -> DVector {
assert_eq!(self.len(), other.len());
let mut result = vec![];
result.extend(
self.iter()
.zip(other.iter())
.map(|(a, b)| self_factor * a + other_factor * b),
);
DVector(result)
// let mut result = DVector(Vec::with_capacity(self.len()));
// for i in 0..self.len() {
// result.push(unsafe {
// self_factor * *self.get_unchecked(i) +
// other_factor * *other.get_unchecked(i)
// });
// }
// result
}
/// Return the 2-norm of this vector.
pub fn norm2(&self) -> Real {
self.iter().map(|x| x * x).sum::<Real>().sqrt()
// let mut norm = 0.0;
// for x in self.iter() {
// norm += x * x
// }
// norm.sqrt()
}
}
impl Vector {
/**
* Return a sparse vector with the given non-zeros.
*/
pub fn new_sparse(n: usize, indices: &[usize], values: &[Real]) -> Vector {
assert_eq!(indices.len(), values.len());
|
| ︙ | ︙ |