RsBundle  Check-in [39420cd8e3]

Many hyperlinks are disabled.
Use anonymous login to enable hyperlinks.

Overview
Comment:Implement computation of aggregated primals.
Downloads: Tarball | ZIP archive
Timelines: family | ancestors | descendants | both | trunk
Files: files | file ages | folders
SHA1: 39420cd8e30552360350de9e058e69e8a80df19c
User & Date: fifr 2016-10-01 20:03:46.363
Context
2016-10-01
20:44
Make `aggregate_primals` take ownership of minorants. check-in: 1318918860 user: fifr tags: trunk
20:03
Implement computation of aggregated primals. check-in: 39420cd8e3 user: fifr tags: trunk
18:44
mmcf: Implement `aggregate_primals` check-in: 44f8c93bc4 user: fifr tags: trunk
Changes
Unified Diff Ignore Whitespace Patch
Changes to examples/mmcf.rs.
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 */

extern crate bundle;
#[macro_use]
extern crate log;
extern crate env_logger;

use bundle::{Solver, SolverParams, StandardTerminator};
use bundle::mcf;
use std::env;

fn main() {
    env_logger::init().unwrap();

    let mut args = env::args();







|







16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 */

extern crate bundle;
#[macro_use]
extern crate log;
extern crate env_logger;

use bundle::{Solver, SolverParams, StandardTerminator, FirstOrderProblem};
use bundle::mcf;
use std::env;

fn main() {
    env_logger::init().unwrap();

    let mut args = env::args();
41
42
43
44
45
46
47






48
49
50
51
            max_weight: 100.0,
            ..Default::default()
        }).unwrap();
        solver.terminator = Box::new(StandardTerminator{
            termination_precision: 1e-6
        });
        solver.solve().unwrap();






    } else {
        panic!("Usage: {} FILENAME", program);
    }
}







>
>
>
>
>
>




41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
            max_weight: 100.0,
            ..Default::default()
        }).unwrap();
        solver.terminator = Box::new(StandardTerminator{
            termination_precision: 1e-6
        });
        solver.solve().unwrap();

        let costs : f64 = (0..solver.problem().num_subproblems()).map(|i| {
            let primals = solver.aggregated_primals(i);
            solver.problem().get_primal_costs(i, &primals)
        }).sum();
        info!("Primal costs: {}", costs);
    } else {
        panic!("Usage: {} FILENAME", program);
    }
}
Changes to examples/quadratic.rs.
72
73
74
75
76
77
78





79
80
81
82
83
84
85
                (Minorant {
                    constant: objective,
                    linear: g,
                },())
            ],
        })
    }





}

fn main() {
    env_logger::init().unwrap();

    let f = QuadraticProblem::new();
    let mut solver = Solver::new_params(f, SolverParams {







>
>
>
>
>







72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
                (Minorant {
                    constant: objective,
                    linear: g,
                },())
            ],
        })
    }

    #[allow(unused_variables)]
    fn aggregate_primals(&mut self, coeffs: &[Real], primals: &[&Self::Primal]) -> Self::Primal {
        ()
    }
}

fn main() {
    env_logger::init().unwrap();

    let f = QuadraticProblem::new();
    let mut solver = Solver::new_params(f, SolverParams {
Changes to src/firstorderproblem.rs.
137
138
139
140
141
142
143
144
145
146
147
148
    ///
    /// The function must return the new aggregated primal.
    ///
    /// The default implementation does nothing and simply returns the
    /// last primal. This should work if the implementing problem does
    /// not provide primal information, e.g. if `Self::Primal = ()`.
    #[allow(unused_variables)]
    fn aggregate_primals(&mut self, coeffs: &[Real], primals: Vec<Self::Primal>) -> Self::Primal {
        let mut primals = primals;
        primals.pop().unwrap()
    }
}







|
<
<
<

137
138
139
140
141
142
143
144



145
    ///
    /// The function must return the new aggregated primal.
    ///
    /// The default implementation does nothing and simply returns the
    /// last primal. This should work if the implementing problem does
    /// not provide primal information, e.g. if `Self::Primal = ()`.
    #[allow(unused_variables)]
    fn aggregate_primals(&mut self, coeffs: &[Real], primals: &[&Self::Primal]) -> Self::Primal;



}
Changes to src/mcf/problem.rs.
167
168
169
170
171
172
173















174
175
176
177
178
179
180
            lhs: lhs,
            rhs: rhs,
            rhsval : 0.0,
            cbase: cbase,
            c: vec![dvec![]; ncom],
        })
    }















}

impl<'a> FirstOrderProblem<'a> for MMCFProblem {
    type Error = Error;

    type Primal = Vec<DVector>;








>
>
>
>
>
>
>
>
>
>
>
>
>
>
>







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
            lhs: lhs,
            rhs: rhs,
            rhsval : 0.0,
            cbase: cbase,
            c: vec![dvec![]; ncom],
        })
    }

    /// Compute costs for a primal solution.
    pub fn get_primal_costs(&self, fidx : usize, primals: &Vec<DVector>) -> Real {
        if self.multimodel {
            primals[0].iter().enumerate().map(|(i,x)| x * self.cbase[fidx][i]).sum()
        } else {
            let mut sum = 0.0;
            for (fidx, p) in primals.iter().enumerate() {
                for (i, x) in p.iter().enumerate() {
                    sum += x * self.cbase[fidx][i];
                }
            }
            sum
        }
    }
}

impl<'a> FirstOrderProblem<'a> for MMCFProblem {
    type Error = Error;

    type Primal = Vec<DVector>;

269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
            Ok(SimpleEvaluation {
                objective: objective,
                minorants: vec![(Minorant { constant: objective, linear: subg }, sols)],
            })
        }
    }

    fn aggregate_primals(&mut self, coeffs: &[Real], primals: Vec<Vec<DVector>>) -> Vec<DVector> {
        let mut aggr = primals[0].iter().map(|x| {
            let mut r = dvec![];
            r.scal(coeffs[0], x);
            r
        }).collect::<Vec<_>>();

        for i in 1..primals.len() {







|







284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
            Ok(SimpleEvaluation {
                objective: objective,
                minorants: vec![(Minorant { constant: objective, linear: subg }, sols)],
            })
        }
    }

    fn aggregate_primals(&mut self, coeffs: &[Real], primals: &[&Vec<DVector>]) -> Vec<DVector> {
        let mut aggr = primals[0].iter().map(|x| {
            let mut r = dvec![];
            r.scal(coeffs[0], x);
            r
        }).collect::<Vec<_>>();

        for i in 1..primals.len() {
Changes to src/solver.rs.
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

/// Information about a minorant.
#[derive(Debug, Clone)]
struct MinorantInfo<Pr> {
    /// The minorant's index in the master problem
    index: usize,
    /// Current multiplier.
    multiplier: usize,
    /// Primal associated with this minorant.
    primal: Option<Pr>,
}

/**
 * Implementation of a bundle method.
 */







|







277
278
279
280
281
282
283
284
285
286
287
288
289
290
291

/// 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>,
}

/**
 * Implementation of a bundle method.
 */
484
485
486
487
488
489
490













491
492
493
494
495
496
497
            self.show_info(term);
            if term == Step::Term {
                break;
            }
        }
        Ok(())
    }














    fn show_info(&self, step: Step) {
        let time = self.start_time.elapsed();
        info!("{} {:0>2}:{:0>2}:{:0>2}.{:0>2} {:4} {:4} {:4}{:1}  {:9.4} {:9.4} {:12.6e}({:12.6e}) {:12.6e}",
              if step == Step::Term { "_endit" } else { "endit " },
              time.as_secs() / 3600,
              (time.as_secs() / 60) % 60,







>
>
>
>
>
>
>
>
>
>
>
>
>







484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
            self.show_info(term);
            if term == Step::Term {
                break;
            }
        }
        Ok(())
    }

    /// Return the current aggregated primal information for a subproblem.
    ///
    /// This function returns all currently used minorants $x_i$ along
    /// with their coefficients $\alpha_i$. The aggregated primal can
    /// be computed by combining the minorants $\bar{x} =
    /// \sum_{i=1}\^m \alpha_i x_i$.
    pub fn aggregated_primals(&mut self, subproblem : usize) -> Pr {
        let (coeffs, primals) : (Vec<_>, Vec<_>) = self.minorants[subproblem].iter().map(|m| {
            (m.multiplier, m.primal.as_ref().unwrap())
        }).unzip();
        self.problem.aggregate_primals(&coeffs, &primals)
    }

    fn show_info(&self, step: Step) {
        let time = self.start_time.elapsed();
        info!("{} {:0>2}:{:0>2}:{:0>2}.{:0>2} {:4} {:4} {:4}{:1}  {:9.4} {:9.4} {:12.6e}({:12.6e}) {:12.6e}",
              if step == Step::Term { "_endit" } else { "endit " },
              time.as_secs() / 3600,
              (time.as_secs() / 60) % 60,
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567

            let mut minorants = result.into_iter();
            if let Some((minorant, primal)) = minorants.next() {
                self.cur_mods[i] = minorant.constant;
                self.cur_mod += self.cur_mods[i];
                self.minorants[i].push(MinorantInfo {
                    index: try!(self.master.add_minorant(i, minorant)),
                    multiplier: 0,
                    primal: Some(primal),
                });
            } else {
                return Err(Error::NoMinorant);
            }
        }








|







566
567
568
569
570
571
572
573
574
575
576
577
578
579
580

            let mut minorants = result.into_iter();
            if let Some((minorant, primal)) = minorants.next() {
                self.cur_mods[i] = minorant.constant;
                self.cur_mod += self.cur_mods[i];
                self.minorants[i].push(MinorantInfo {
                    index: try!(self.master.add_minorant(i, minorant)),
                    multiplier: 0.0,
                    primal: Some(primal),
                });
            } else {
                return Err(Error::NoMinorant);
            }
        }

606
607
608
609
610
611
612
613
614
615
616
617



618
619

620
621
622
623

624
625
626
627
628
629
630
631
632
633
634
        Ok(())
    }


    /// Reduce size of bundle.
    fn compress_bundle(&mut self) -> Result<()> {
        for i in 0..self.problem.num_subproblems() {
            let n = self.master.num_minorants(i);
            if n >= self.params.max_bundle_size {
                for m in self.minorants[i].iter_mut() {
                    m.multiplier = (1e6 * self.master.multiplier(m.index)) as usize;
                }



                self.minorants[i].sort_by_key(|m| -(m.multiplier as isize));
                let aggr = self.minorants[i].split_off(self.params.max_bundle_size-2);

                let (aggr_mins, aggr_primals) : (Vec<_>, Vec<_>) = aggr.into_iter().map(|m| {
                    (m.index, m.primal.unwrap())
                }).unzip();
                let (aggr_min, aggr_coeffs) = try!(self.master.aggregate(i, &aggr_mins));

                self.minorants[i].push(MinorantInfo{
                    index: aggr_min,
                    multiplier: 0,
                    primal: Some(self.problem.aggregate_primals(&aggr_coeffs, aggr_primals)),
                });
            }
        }
        Ok(())
    }

    /// Perform a descent step.







|
<
|
|
|
>
>
>
|

>
|
|


>


|
|







619
620
621
622
623
624
625
626

627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
        Ok(())
    }


    /// Reduce size of bundle.
    fn compress_bundle(&mut self) -> Result<()> {
        for i in 0..self.problem.num_subproblems() {
            // update multiplier from master solution

            for m in self.minorants[i].iter_mut() {
                m.multiplier = self.master.multiplier(m.index);
            }
            let n = self.master.num_minorants(i);
            if n >= self.params.max_bundle_size {
                // aggregate minorants with smallest coefficients
                self.minorants[i].sort_by_key(|m| -((1e6 * m.multiplier) as isize));
                let aggr = self.minorants[i].split_off(self.params.max_bundle_size-2);
                let aggr_sum = aggr.iter().map(|m| m.multiplier).sum();
                let (aggr_mins, aggr_primals) : (Vec<_>, Vec<_>) = aggr.iter().map(|m| {
                    (m.index, m.primal.as_ref().unwrap())
                }).unzip();
                let (aggr_min, aggr_coeffs) = try!(self.master.aggregate(i, &aggr_mins));
                // append aggregated minorant
                self.minorants[i].push(MinorantInfo{
                    index: aggr_min,
                    multiplier: aggr_sum,
                    primal: Some(self.problem.aggregate_primals(&aggr_coeffs, &aggr_primals)),
                });
            }
        }
        Ok(())
    }

    /// Perform a descent step.
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
            self.nxt_vals[fidx] = fun_ub;

            // move center of minorant to cur_y
            nxt_minorant.move_center(-1.0, &self.nxt_d);
            self.new_cutval += nxt_minorant.constant;
            self.minorants[fidx].push(MinorantInfo{
                index: try!(self.master.add_minorant(fidx, nxt_minorant)),
                multiplier: 0,
                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;







|







720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
            self.nxt_vals[fidx] = fun_ub;

            // move center of minorant to cur_y
            nxt_minorant.move_center(-1.0, &self.nxt_d);
            self.new_cutval += nxt_minorant.constant;
            self.minorants[fidx].push(MinorantInfo{
                index: try!(self.master.add_minorant(fidx, nxt_minorant)),
                multiplier: 0.0,
                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;