RsBundle  Diff

Differences From Artifact [1655b8b820]:

  • File src/solver/sync.rs — part of check-in [58e0a3a21e] at 2019-12-25 10:26:00 on branch async — Merge trunk (user: fifr size: 31495) [more...]

To Artifact [872eede716]:

  • File src/solver/sync.rs — part of check-in [9cc08eda25] at 2020-02-26 14:12:32 on branch async — Merge trunk (user: fifr size: 31705) [more...]

13
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
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>
 */

//! An asynchronous parallel bundle solver.





use crossbeam::channel::{select, unbounded as channel, Receiver, RecvError, Sender};
use log::{debug, info, warn};
use num_cpus;
use num_traits::Float;
use std::sync::Arc;
use std::time::Instant;
use threadpool::ThreadPool;

use crate::{DVector, Real};

use super::channels::{ChannelSender, ChannelUpdateSender, ClientMessage, EvalResult, Update};


use super::masterprocess::{self, MasterConfig, MasterProcess, MasterResponse};
use crate::master::{Builder as MasterBuilder, MasterProblem};
use crate::problem::{FirstOrderProblem, UpdateState};
use crate::terminator::{StandardTerminatable, StandardTerminator, Terminator};
use crate::weighter::{HKWeightable, HKWeighter, Weighter};

/// The default iteration limit.
pub const DEFAULT_ITERATION_LIMIT: usize = 10_000;







>
>
>
>
|









|
>
>
|







13
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
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see  <http://www.gnu.org/licenses/>
 */

//! An asynchronous parallel bundle solver.

#[cfg(feature = "crossbeam")]
use rs_crossbeam::channel::{unbounded as channel, RecvError};
#[cfg(not(feature = "crossbeam"))]
use std::sync::mpsc::{channel, RecvError};

use log::{debug, info, warn};
use num_cpus;
use num_traits::Float;
use std::sync::Arc;
use std::time::Instant;
use threadpool::ThreadPool;

use crate::{DVector, Real};

use super::channels::{
    ChannelResultSender, ChannelUpdateSender, ClientReceiver, ClientSender, EvalResult, Message, Update,
};
use super::masterprocess::{self, MasterConfig, MasterProcess, MasterResponse, Response};
use crate::master::{Builder as MasterBuilder, MasterProblem};
use crate::problem::{FirstOrderProblem, UpdateState};
use crate::terminator::{StandardTerminatable, StandardTerminator, Terminator};
use crate::weighter::{HKWeightable, HKWeighter, Weighter};

/// The default iteration limit.
pub const DEFAULT_ITERATION_LIMIT: usize = 10_000;
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170

impl<MErr, PErr> From<RecvError> for Error<MErr, PErr> {
    fn from(err: RecvError) -> Error<MErr, PErr> {
        Error::Process(err)
    }
}

type ClientSender<P> = Sender<ClientMessage<usize, <P as FirstOrderProblem>::Primal, <P as FirstOrderProblem>::Err>>;

type ClientReceiver<P> =
    Receiver<ClientMessage<usize, <P as FirstOrderProblem>::Primal, <P as FirstOrderProblem>::Err>>;

/// Parameters for tuning the solver.
#[derive(Debug, Clone)]
pub struct Parameters {
    /// The descent step acceptance factors, must be in (0,1).
    ///
    /// The default value is 0.1.
    acceptance_factor: Real,
}







<
<
<
<
<
<







157
158
159
160
161
162
163






164
165
166
167
168
169
170

impl<MErr, PErr> From<RecvError> for Error<MErr, PErr> {
    fn from(err: RecvError) -> Error<MErr, PErr> {
        Error::Process(err)
    }
}







#[derive(Debug, Clone)]
pub struct Parameters {
    /// The descent step acceptance factors, must be in (0,1).
    ///
    /// The default value is 0.1.
    acceptance_factor: Real,
}
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    /// The algorithm data.
    data: SolverData,

    /// The master problem process.
    master_proc: Option<MasterProcess<P, M::MasterProblem>>,

    /// The channel to receive the evaluation results from subproblems.
    client_tx: Option<ClientSender<P>>,

    /// The channel to receive the evaluation results from subproblems.
    client_rx: Option<ClientReceiver<P>>,

    /// Number of descent steps.
    cnt_descent: usize,

    /// Number of null steps.
    cnt_null: usize,








|


|







417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
    /// The algorithm data.
    data: SolverData,

    /// The master problem process.
    master_proc: Option<MasterProcess<P, M::MasterProblem>>,

    /// The channel to receive the evaluation results from subproblems.
    client_tx: Option<ClientSender<usize, P, M::MasterProblem>>,

    /// The channel to receive the evaluation results from subproblems.
    client_rx: Option<ClientReceiver<usize, P, M::MasterProblem>>,

    /// Number of descent steps.
    cnt_descent: usize,

    /// Number of null steps.
    cnt_null: usize,

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

        self.data.init(dvec![0.0; n]);
        self.cnt_descent = 0;
        self.cnt_null = 0;
        self.cnt_evals = 0;

        let (tx, rx) = channel();
        self.client_tx = Some(tx);
        self.client_rx = Some(rx);

        let master_config = MasterConfig {
            num_subproblems: m,
            num_vars: n,
            lower_bounds: self.problem.lower_bounds().map(DVector),
            upper_bounds: self.problem.upper_bounds().map(DVector),







|







523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

        self.data.init(dvec![0.0; n]);
        self.cnt_descent = 0;
        self.cnt_null = 0;
        self.cnt_evals = 0;

        let (tx, rx) = channel();
        self.client_tx = Some(tx.clone());
        self.client_rx = Some(rx);

        let master_config = MasterConfig {
            num_subproblems: m,
            num_vars: n,
            lower_bounds: self.problem.lower_bounds().map(DVector),
            upper_bounds: self.problem.upper_bounds().map(DVector),
554
555
556
557
558
559
560

561
562
563
564
565
566
567
568



569

570
571
572
573
574
575
576
            return Err(Error::Dimension("upper bounds".to_string()));
        }

        debug!("Start master process");
        self.master_proc = Some(MasterProcess::start(
            self.master.build().map_err(Error::BuildMaster)?,
            master_config,

            &mut self.threadpool,
        ));

        debug!("Initial problem evaluation");
        // We need an initial evaluation of all oracles for the first center.
        let y = Arc::new(self.data.cur_y.clone());
        for i in 0..m {
            self.problem



                .evaluate(i, y.clone(), ChannelSender::new(i, self.client_tx.clone().unwrap()))

                .map_err(Error::Evaluation)?;
        }

        debug!("Initialization complete");

        self.start_time = Instant::now();








>








>
>
>
|
>







554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
            return Err(Error::Dimension("upper bounds".to_string()));
        }

        debug!("Start master process");
        self.master_proc = Some(MasterProcess::start(
            self.master.build().map_err(Error::BuildMaster)?,
            master_config,
            tx,
            &mut self.threadpool,
        ));

        debug!("Initial problem evaluation");
        // We need an initial evaluation of all oracles for the first center.
        let y = Arc::new(self.data.cur_y.clone());
        for i in 0..m {
            self.problem
                .evaluate(
                    i,
                    y.clone(),
                    ChannelResultSender::new(i, self.client_tx.clone().unwrap()),
                )
                .map_err(Error::Evaluation)?;
        }

        debug!("Initialization complete");

        self.start_time = Instant::now();

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
652
    /// continued from the previous point. Because of this one *must*
    /// call `init()` before the first call to this function.
    pub fn solve_iter(&mut self, niter: usize) -> Result<bool, P, M> {
        debug!("Start solving up to {} iterations", niter);

        self.reset_iteration_data(niter);
        loop {
            select! {
                recv(self.client_rx.as_ref().ok_or(Error::NotInitialized)?) -> msg => {
                    match msg? {
                        ClientMessage::Eval(m) =>
                            if self.handle_client_response(m)? {
                                return Ok(false);
                            },
                        ClientMessage::Update(_) => {
                            warn!("Ignore unexpected problem update message from client")
                        }
                    }
                },
                recv(self.master_proc.as_ref().ok_or(Error::NotInitialized)?.rx) -> msg => {


                    debug!("Receive master response");
                    // Receive result (new candidate) from the master
                    if self.handle_master_response(msg??)? {
                        return Ok(true);
                    }
                },

            }
        }
    }

    /// Handle a response from a subproblem evaluation.
    ///
    /// The function returns `Ok(true)` if the final iteration count has been reached.







<
|
|
|
|
|
<
<
<
|
|
<
<
>
>


|


<
>







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
652
653
    /// continued from the previous point. Because of this one *must*
    /// call `init()` before the first call to this function.
    pub fn solve_iter(&mut self, niter: usize) -> Result<bool, P, M> {
        debug!("Start solving up to {} iterations", niter);

        self.reset_iteration_data(niter);
        loop {

            let msg = self.client_rx.as_ref().ok_or(Error::NotInitialized)?.recv()?;
            match msg {
                Message::Eval(m) => {
                    if self.handle_client_response(m)? {
                        return Ok(false);



                    }
                }


                Message::Update(_) => warn!("Ignore unexpected problem update message from client"),
                Message::Master(mresponse) => {
                    debug!("Receive master response");
                    // Receive result (new candidate) from the master
                    if self.handle_master_response(mresponse)? {
                        return Ok(true);
                    }

                }
            }
        }
    }

    /// Handle a response from a subproblem evaluation.
    ///
    /// The function returns `Ok(true)` if the final iteration count has been reached.
749
750
751
752
753
754
755
756
757
758








759
760




761
762

763
764
765
766
767
768
769
        // Compute the new candidate. The main loop will wait for the result of
        // this solution process of the master problem.
        self.master_proc.as_mut().unwrap().solve(self.data.cur_val)?;

        Ok(self.data.cnt_iter >= self.data.max_iter)
    }

    fn handle_master_response(&mut self, master_res: MasterResponse) -> Result<bool, P, M> {
        let master = self.master_proc.as_mut().ok_or(Error::NotInitialized)?;









        self.data.nxt_mod = master_res.nxt_mod;
        self.data.sgnorm = master_res.sgnorm;




        self.data.expected_progress = self.data.cur_val - self.data.nxt_mod;
        self.data.cnt_updates = master_res.cnt_updates;


        // If this is the very first solution of the model,
        // we use its result as to make a good guess for the initial weight
        // of the proximal term and resolve.
        if self.data.cur_weight.is_infinite() {
            self.data.cur_weight = self.weighter.initial_weight(&self.data);
            master.set_weight(self.data.cur_weight)?;







|
|
|
>
>
>
>
>
>
>
>
|
|
>
>
>
>

|
>







750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
        // Compute the new candidate. The main loop will wait for the result of
        // this solution process of the master problem.
        self.master_proc.as_mut().unwrap().solve(self.data.cur_val)?;

        Ok(self.data.cnt_iter >= self.data.max_iter)
    }

    fn handle_master_response(&mut self, master_res: MasterResponse<P, M::MasterProblem>) -> Result<bool, P, M> {
        match master_res {
            Response::Error(err) => return Err(err.into()),
            Response::Result {
                nxt_mod,
                sgnorm,
                cnt_updates,
                nxt_d,
                ..
            } => {
                self.data.nxt_d = Arc::new(nxt_d);
                self.data.nxt_mod = nxt_mod;
                self.data.sgnorm = sgnorm;
                self.data.cnt_updates = cnt_updates;
            }
        };

        self.data.expected_progress = self.data.cur_val - self.data.nxt_mod;

        let master = self.master_proc.as_mut().ok_or(Error::NotInitialized)?;

        // If this is the very first solution of the model,
        // we use its result as to make a good guess for the initial weight
        // of the proximal term and resolve.
        if self.data.cur_weight.is_infinite() {
            self.data.cur_weight = self.weighter.initial_weight(&self.data);
            master.set_weight(self.data.cur_weight)?;
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804



805

806
807
808
809
810
811
812
        }

        // Compress bundle
        master.compress()?;

        // Compute new candidate.
        let mut next_y = dvec![];
        self.data.nxt_d = Arc::new(master_res.nxt_d);
        next_y.add(&self.data.cur_y, &self.data.nxt_d);
        self.data.nxt_y = Arc::new(next_y);

        // Reset evaluation data.
        self.data.nxt_ubs.clear();
        self.data
            .nxt_ubs
            .resize(self.problem.num_subproblems(), Real::infinity());
        self.data.cnt_remaining_ubs = self.problem.num_subproblems();
        self.data.nxt_cutvals.clear();
        self.data
            .nxt_cutvals
            .resize(self.problem.num_subproblems(), -Real::infinity());
        self.data.cnt_remaining_mins = self.problem.num_subproblems();

        // Start evaluation of all subproblems at the new candidate.
        let client_tx = self.client_tx.as_ref().ok_or(Error::NotInitialized)?;
        for i in 0..self.problem.num_subproblems() {
            self.problem



                .evaluate(i, self.data.nxt_y.clone(), ChannelSender::new(i, client_tx.clone()))

                .map_err(Error::Evaluation)?;
        }
        Ok(false)
    }

    fn update_problem(&mut self, step: Step) -> Result<bool, P, M> {
        let master_proc = self.master_proc.as_mut().ok_or(Error::NotInitialized)?;







<



















>
>
>
|
>







792
793
794
795
796
797
798

799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
        }

        // Compress bundle
        master.compress()?;

        // Compute new candidate.
        let mut next_y = dvec![];

        next_y.add(&self.data.cur_y, &self.data.nxt_d);
        self.data.nxt_y = Arc::new(next_y);

        // Reset evaluation data.
        self.data.nxt_ubs.clear();
        self.data
            .nxt_ubs
            .resize(self.problem.num_subproblems(), Real::infinity());
        self.data.cnt_remaining_ubs = self.problem.num_subproblems();
        self.data.nxt_cutvals.clear();
        self.data
            .nxt_cutvals
            .resize(self.problem.num_subproblems(), -Real::infinity());
        self.data.cnt_remaining_mins = self.problem.num_subproblems();

        // Start evaluation of all subproblems at the new candidate.
        let client_tx = self.client_tx.as_ref().ok_or(Error::NotInitialized)?;
        for i in 0..self.problem.num_subproblems() {
            self.problem
                .evaluate(
                    i,
                    self.data.nxt_y.clone(),
                    ChannelResultSender::new(i, client_tx.clone()),
                )
                .map_err(Error::Evaluation)?;
        }
        Ok(false)
    }

    fn update_problem(&mut self, step: Step) -> Result<bool, P, M> {
        let master_proc = self.master_proc.as_mut().ok_or(Error::NotInitialized)?;
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
                            master_proc
                                .get_aggregated_primal(i)
                                .map_err(|_| "get_aggregated_primal".to_string())
                                .expect("Cannot get aggregated primal from master process")
                        })
                        .collect(),
                },
                ChannelUpdateSender::new(self.data.cnt_iter, update_tx),
            )
            .map_err(Error::Update)?;

        let mut have_update = false;
        for msg in update_rx {
            if let ClientMessage::Update(update) = msg {
                match update {
                    Update::AddVariables { bounds, sgext, .. } => {
                        have_update = true;
                        let mut newvars = Vec::with_capacity(bounds.len());
                        for (lower, upper) in bounds {
                            if lower > upper {
                                return Err(Error::InvalidBounds { lower, upper });







|





|







839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
                            master_proc
                                .get_aggregated_primal(i)
                                .map_err(|_| "get_aggregated_primal".to_string())
                                .expect("Cannot get aggregated primal from master process")
                        })
                        .collect(),
                },
                ChannelUpdateSender::<_, _, _, M::MasterProblem>::new(self.data.cnt_iter, update_tx),
            )
            .map_err(Error::Update)?;

        let mut have_update = false;
        for msg in update_rx {
            if let Message::Update(update) = msg {
                match update {
                    Update::AddVariables { bounds, sgext, .. } => {
                        have_update = true;
                        let mut newvars = Vec::with_capacity(bounds.len());
                        for (lower, upper) in bounds {
                            if lower > upper {
                                return Err(Error::InvalidBounds { lower, upper });
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
                            master_proc.add_vars(newvars.iter().map(|v| (v.0, v.1, v.2)).collect(), sgext)?;
                        }
                    }
                    Update::Done { .. } => (), // there's nothing to do
                    Update::Error { err, .. } => return Err(Error::Update(err)),
                }
            } else {
                unreachable!("No evaluation result during update");
            }
        }

        Ok(have_update)
    }

    /// Return the bound the function value must be below of to enforce a descent step.







|







882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
                            master_proc.add_vars(newvars.iter().map(|v| (v.0, v.1, v.2)).collect(), sgext)?;
                        }
                    }
                    Update::Done { .. } => (), // there's nothing to do
                    Update::Error { err, .. } => return Err(Error::Update(err)),
                }
            } else {
                unreachable!("Only update results allowed during update");
            }
        }

        Ok(have_update)
    }

    /// Return the bound the function value must be below of to enforce a descent step.