Antares Xpansion
Investment simulations for Antares studies
Loading...
Searching...
No Matches
BendersBase.h
1#pragma once
2
3#include <execution>
4#include <tbb/tbb.h>
5#include <filesystem>
6#include <optional>
7#include <regex>
8
9#include "BendersMathLogger.h"
10#include "BendersStructsDatas.h"
11#include "CriterionComputation.h"
12#include "SimulationOptions.h"
13#include "SubproblemCut.h"
14#include "SubproblemWorker.h"
15#include "Worker.h"
16#include "WorkerMaster.h"
17#include "antares-xpansion/helpers/Timer.h"
18#include "antares-xpansion/xpansion_interfaces/ILogger.h"
19#include "common.h"
25template <class lambda>
26auto selectPolicy(lambda f, bool shouldParallelize) {
27 if (shouldParallelize)
28 return f(std::execution::par_unseq);
29 else
30 return f(std::execution::seq);
31}
33 public:
34 virtual ~BendersBase() = default;
35 BendersBase(const BendersBaseOptions &options, Logger logger, Writer writer,
36 std::shared_ptr<MathLoggerDriver> mathLoggerDriver);
37 virtual void launch() = 0;
38 void set_solver_log_file(const std::filesystem::path &log_file);
39 [[nodiscard]] std::filesystem::path solver_log_file() const {
40 return solver_log_file_;
41 }
42 double execution_time() const;
43 virtual std::string BendersName() const = 0;
44 // TODO rename to be consistent with data that it hold
45 // ref of value?
46 WorkerMasterDataVect AllCuts() const;
47 // BendersCuts CutsBestIteration() const;
48 // void Clean();
49 LogData GetBestIterationData() const;
50 void set_input_map(const CouplingMap &coupling_map);
51 int MasterRowIndex(const std::string &row_name) const;
52 void MasterChangeRhs(int id_row, double val) const;
53 // for test
54 void MasterGetRhs(double &rhs, int id_row) const;
55 const VariableMap &MasterVariables() const { return master_variable_map_; }
56 std::vector<double> MasterObjectiveFunctionCoeffs() const;
57 void MasterRowsCoeffs(std::vector<int> &mstart, std::vector<int> &mclind,
58 std::vector<double> &dmatval, int size,
59 std::vector<int> &nels, int first, int last) const;
60 int MasterGetNElems() const;
61 void MasterAddRows(std::vector<char> const &qrtype_p,
62 std::vector<double> const &rhs_p,
63 std::vector<double> const &range_p,
64 std::vector<int> const &mstart_p,
65 std::vector<int> const &mclind_p,
66 std::vector<double> const &dmatval_p,
67 const std::vector<std::string> &row_names = {}) const;
68 void MasterGetRowType(std::vector<char> &qrtype, int first, int last) const;
69 void ResetMasterFromLastIteration();
70 std::filesystem::path LastMasterPath() const;
71 bool MasterIsEmpty() const;
72 void DoFreeProblems(bool free_problems) { free_problems_ = free_problems; }
73 int MasterGetnrows() const;
74 int MasterGetncols() const;
75 WorkerMasterData BestIterationWorkerMaster() const;
76 void SetMasterObjectiveFunctionCoeffsToZeros() const;
77 void SetMasterObjectiveFunction(const double *coeffs, int first,
78 int last) const;
79 virtual void InitializeProblems() = 0;
80 void SetMaxIteration(int max_iteration) {
81 _options.MAX_ITERATIONS = max_iteration;
82 }
83 BendersBaseOptions Options() const { return _options; }
84 virtual void free() = 0;
85
86 int GetBendersRunNumber() const { return _data.criteria_current_iteration_data.benders_num_run; }
87
88 CurrentIterationData GetCurrentIterationData() const;
89
90 CriteriaCurrentIterationData GetOuterLoopData() const;
91
92 std::vector<double> GetOuterLoopCriterionAtBestBenders() const;
93 virtual void init_data();
94 void init_data(double external_loop_lambda, double external_loop_lambda_min, double external_loop_lambda_max);
95 Output::SolutionData GetOuterLoopSolution() const;
96 void SaveOuterLoopSolutionInOutputFile() const;
97 void SaveCurrentOuterLoopIterationInOutputFile() const;
98 void SetBilevelBestub(double bilevel_best_ub);
99 void UpdateOuterLoopSolution();
100
101 bool isExceptionRaised() const;
102 void UpdateOverallCosts();
103 Logger _logger;
104 Writer _writer;
105 std::shared_ptr<MathLoggerDriver> mathLoggerDriver_;
106 void setCriterionComputationInputs(
107 const Benders::Criterion::CriterionInputData &criterion_input_data);
108
109 protected:
110 bool exception_raised_ = false;
112 WorkerMasterDataVect workerMasterDataVect_;
113 // BendersCuts best_iteration_cuts_;
114 // BendersCuts current_iteration_cuts_;
115 VariableMap master_variable_map_;
116 CouplingMap coupling_map_;
117 BendersRelevantIterationsData relevantIterationData_ = {WorkerMasterData(),
119 bool init_data_ = true;
120 bool init_problems_ = true;
121 bool free_problems_ = true;
122
123 std::vector<std::vector<double> > criteria_vector_for_each_iteration_;
124 bool is_bilevel_check_all_ = false;
125
126 virtual void Run() = 0;
127 void update_best_ub();
128 bool ShouldBendersStop();
129 bool is_initial_relaxation_requested() const;
130 bool SwitchToIntegerMaster(bool is_relaxed) const;
131 virtual void UpdateTrace();
132 virtual void ComputeXCut();
133 void ComputeInvestCost();
134 virtual void compute_ub();
135 virtual void get_master_value();
136 void GetSubproblemCut(SubProblemDataMap &subproblem_data_map);
137 virtual void post_run_actions() const;
138 void BuildCutFull(const SubProblemDataMap &subproblem_data_map);
139 virtual void DeactivateIntegrityConstraints() const;
140 virtual void ActivateIntegrityConstraints() const;
141 virtual void SetDataPreRelaxation();
142 virtual void ResetDataPostRelaxation();
143 [[nodiscard]] std::filesystem::path GetSubproblemPath(
144 std::string const &subproblem_name) const;
145 [[nodiscard]] double SubproblemWeight(int subproblem_count,
146 std::string const &name) const;
147 [[nodiscard]] std::filesystem::path get_master_path() const;
148 [[nodiscard]] std::filesystem::path get_structure_path() const;
149 [[nodiscard]] LogData bendersDataToLogData(
150 const CurrentIterationData &data) const;
151 template <typename T, typename... Args>
152 void reset_master(Args &&...args) {
153 _master = std::make_shared<T>(std::forward<Args>(args)...);
154 master_is_empty_ = false;
155 }
156 void free_master();
157 void free_subproblems();
158 void AddSubproblem(const std::pair<std::string, VariableMap> &kvp);
159 [[nodiscard]] virtual WorkerMasterPtr get_master() const;
160 void MatchProblemToId();
161 void AddSubproblemName(const std::string &name);
162 [[nodiscard]] std::string get_master_name() const;
163 [[nodiscard]] std::string get_solver_name() const;
164 [[nodiscard]] int get_log_level() const;
165 [[nodiscard]] bool is_trace() const;
166 [[nodiscard]] Point get_x_cut() const;
167 void set_x_cut(const Point &x0);
168 [[nodiscard]] Point get_x_out() const;
169 void set_x_out(const Point &x0);
170 [[nodiscard]] double get_timer_master() const;
171 void set_timer_master(const double &timer_master);
172 [[nodiscard]] double GetSubproblemsWalltime() const;
173 void SetSubproblemsWalltime(const double &duration);
174 [[nodiscard]] double GetSubproblemsCpuTime() const;
175 void SetSubproblemsCpuTime(const double &duration);
176 [[nodiscard]] double GetSubproblemsCumulativeCpuTime() const;
177 void SetSubproblemsCumulativeCpuTime(const double &duration);
178 [[nodiscard]] double GetSubproblemCost() const;
179 void SetSubproblemCost(const double &subproblem_cost);
180 bool IsResumeMode() const;
181 std::filesystem::path LastIterationFile() const {
182 return std::filesystem::path(_options.LAST_ITERATION_JSON_FILE);
183 }
184 void UpdateMaxNumberIterationResumeMode(const unsigned nb_iteration_done);
185 void SaveCurrentIterationInOutputFile() const;
186 void SaveSolutionInOutputFile() const;
187 void PrintCurrentIterationCsv();
188 void OpenCsvFile();
189 void CloseCsvFile();
190 void ChecksResumeMode();
191 virtual void SaveCurrentBendersData();
192 void ClearCurrentIterationCutTrace();
193 virtual void EndWritingInOutputFile() const;
194 [[nodiscard]] int GetNumIterationsBeforeRestart() const {
195 return iterations_before_resume;
196 }
197 double GetBendersTime() const;
198 virtual void write_basis() const;
199 // SubproblemsMapPtr GetSubProblemsMapPtr() { return subproblem_map; }
200 SubproblemsMapPtr GetSubProblemMap() const { return subproblem_map; }
201 StrVector GetSubProblemNames() const { return subproblems; }
202 double AbsoluteGap() const { return _options.ABSOLUTE_GAP; }
203 double RelativeGap() const { return _options.RELATIVE_GAP; }
204 double RelaxedGap() const { return _options.RELAXED_GAP; }
205 DblVector GetAlpha_i() const { return _data.single_subpb_costs_under_approx; }
206 void SetAlpha_i(const DblVector &single_subpb_costs_under_approx) {
207 _data.single_subpb_costs_under_approx = single_subpb_costs_under_approx;
208 }
209 int ProblemToId(const std::string &problem_name) const {
210 return _problem_to_id.at(problem_name);
211 }
212 virtual void UpdateStoppingCriterion();
213 virtual bool ShouldRelaxationStop() const;
214 int GetNumOfSubProblemsSolvedBeforeResume() {
215 return cumulative_number_of_subproblem_resolved_before_resume;
216 }
217
218 void BoundSimplexIterations(int subproblem_iteration);
219 void ResetSimplexIterationsBounds();
220
221 SubproblemsMapPtr subproblem_map;
222 SolverLogManager solver_log_manager_;
223
224 virtual void SolveSubproblem(SubProblemDataMap &subproblem_data_map,
225 PlainData::SubProblemData &subproblem_data,
226 const std::string &name,
227 const std::shared_ptr<SubproblemWorker> &worker);
228
229 Benders::Criterion::CriterionComputation criterion_computation_;
239 // Search for variables in sub problems that satisfy patterns
240 // var_indices is a vector(for each patterns p) of vector (var indices related
241 // to p)
243
244 private:
245 void print_master_and_cut(std::ostream &file, int ite,
246 WorkerMasterData &trace, Point const &xopt);
247 void print_master_csv(std::ostream &stream, const WorkerMasterData &trace,
248 Point const &xopt) const;
249 void check_status(const SubProblemDataMap &subproblem_data_map) const;
250 [[nodiscard]] LogData build_log_data_from_data() const;
251 [[nodiscard]] Output::SolutionData solution() const;
252 [[nodiscard]] Output::SolutionData BendersSolution() const;
253 [[nodiscard]] std::string status_from_criterion() const;
254 void compute_cut_aggregate(const SubProblemDataMap &subproblem_data_map);
255 void compute_cut(const SubProblemDataMap &subproblem_data_map);
256 [[nodiscard]] std::map<std::string, int> get_master_variable_map(
257 const std::map<std::string, std::map<std::string, int>> &input_map) const;
258 [[nodiscard]] virtual bool shouldParallelize() const = 0;
259 Output::Iteration iteration(const WorkerMasterData &masterDataPtr_l) const;
260 LogData FinalLogData() const;
261 void FillWorkerMasterData(WorkerMasterData &workerMasterData);
262 bool master_is_empty_ = true;
263 BendersBaseOptions _options;
264 unsigned int _totalNbProblems = 0;
265 std::filesystem::path solver_log_file_ = "";
266 WorkerMasterPtr _master;
267 VariableMap _problem_to_id;
268 StrVector subproblems;
269 std::ofstream _csv_file;
270 std::filesystem::path _csv_file_path;
271 LogData best_iteration_data;
272 int iterations_before_resume = 0;
273 int cumulative_number_of_subproblem_resolved_before_resume = 0;
274 Timer benders_timer;
275 Output::SolutionData outer_loop_solution_data_;
276
277};
278using pBendersBase = std::shared_ptr<BendersBase>;
Definition BendersBase.h:32
virtual void get_master_value()
Solve and get optimal variables of the Master Problem.
Definition BendersBase.cpp:299
void BoundSimplexIterations(int subproblem_iteration)
Update maximum and minimum of simplex iterations.
Definition BendersBase.cpp:843
virtual void UpdateStoppingCriterion()
Update stopping criterion.
Definition BendersBase.cpp:196
void GetSubproblemCut(SubProblemDataMap &subproblem_data_map)
Solve and store optimal variables of all Subproblem Problems.
Definition BendersBase.cpp:368
std::filesystem::path get_structure_path() const
Get path to structure txt file from options.
Definition BendersBase.cpp:710
std::filesystem::path LastMasterPath() const
Get path to last mps file of master problem.
Definition BendersBase.cpp:702
std::filesystem::path GetSubproblemPath(std::string const &subproblem_name) const
Get path to subproblem mps file from options.
Definition BendersBase.cpp:663
void SetSubproblemsVariablesIndices()
Definition BendersBase.cpp:413
virtual void init_data()
Initialize set of data used in the loop.
Definition BendersBase.cpp:30
std::filesystem::path get_master_path() const
Get path to master problem mps file from options.
Definition BendersBase.cpp:690
void set_input_map(const CouplingMap &coupling_map)
set the input
Definition BendersBase.cpp:748
virtual bool ShouldRelaxationStop() const
Check if initial relaxation should stop.
Definition BendersBase.cpp:185
virtual void UpdateTrace()
Update trace of the Benders for the current iteration.
Definition BendersBase.cpp:236
double SubproblemWeight(int subproblem_count, std::string const &name) const
Return subproblem weight value.
Definition BendersBase.cpp:675
void update_best_ub()
Update best upper bound and best optimal variables.
Definition BendersBase.cpp:167
void BuildCutFull(const SubProblemDataMap &subproblem_data_map)
Add cuts in master problem.
Definition BendersBase.cpp:485
Definition CriterionComputation.h:7
this class contains all data read from user input file
Definition CriterionInputDataReader.h:80
Definition SolverAbstract.h:16
Definition Timer.h:10
Class use to store trace information during the algorithm run.
Definition BendersStructsDatas.h:71
Definition launch.py:1
Definition common.h:171
Definition BendersStructsDatas.h:96
Definition BendersStructsDatas.h:8
Definition BendersStructsDatas.h:24
Definition ILogger.h:48
Definition OutputWriter.h:39
struct saves some entries to be later written to the json file
Definition OutputWriter.h:60
Definition SubproblemCut.h:9