Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
Rename file maxmin to System
[simgrid.git] / src / kernel / lmm / System.cpp
1 /* Copyright (c) 2004-2022. The SimGrid Team. All rights reserved.          */
2
3 /* This program is free software; you can redistribute it and/or modify it
4  * under the terms of the license (GNU LGPL) which comes with this package. */
5
6 #include "src/kernel/lmm/maxmin.hpp"
7 #if SIMGRID_HAVE_EIGEN3
8 #include "src/kernel/lmm/bmf.hpp"
9 #endif
10 #include <boost/core/demangle.hpp>
11 #include <typeinfo>
12
13 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_lmm, kernel, "Kernel Linear Max-Min solver");
14
15 double sg_maxmin_precision = 1E-5; /* Change this with --cfg=maxmin/precision:VALUE */
16 double sg_surf_precision   = 1E-9; /* Change this with --cfg=surf/precision:VALUE */
17 int sg_concurrency_limit   = -1;      /* Change this with --cfg=maxmin/concurrency-limit:VALUE */
18
19 namespace simgrid {
20 namespace kernel {
21 namespace lmm {
22
23 using dyn_light_t = std::vector<int>;
24
25 int Variable::next_rank_   = 1;
26 int Constraint::next_rank_ = 1;
27
28 Element::Element(Constraint* constraint, Variable* variable, double cweight)
29     : constraint(constraint), variable(variable), consumption_weight(cweight), max_consumption_weight(cweight)
30 {
31 }
32
33 int Element::get_concurrency() const
34 {
35   // Ignore element with weight less than one (e.g. cross-traffic)
36   return (consumption_weight >= 1) ? 1 : 0;
37   // There are other alternatives, but they will change the behavior of the model..
38   // So do not use it unless you want to make a new model.
39   // If you do, remember to change the variables concurrency share to reflect it.
40   // Potential examples are:
41   // return (elem->weight>0)?1:0;//Include element as soon  as weight is non-zero
42   // return (int)ceil(elem->weight);//Include element as the rounded-up integer value of the element weight
43 }
44
45 void Element::decrease_concurrency()
46 {
47   xbt_assert(constraint->concurrency_current_ >= get_concurrency());
48   constraint->concurrency_current_ -= get_concurrency();
49 }
50
51 void Element::increase_concurrency()
52 {
53   constraint->concurrency_current_ += get_concurrency();
54
55   if (constraint->concurrency_current_ > constraint->concurrency_maximum_)
56     constraint->concurrency_maximum_ = constraint->concurrency_current_;
57
58   xbt_assert(constraint->get_concurrency_limit() < 0 ||
59                  constraint->concurrency_current_ <= constraint->get_concurrency_limit(),
60              "Concurrency limit overflow!");
61 }
62
63 System* System::build(const std::string& solver_name, bool selective_update)
64 {
65   System* system = nullptr;
66   if (solver_name == "bmf") {
67 #if SIMGRID_HAVE_EIGEN3
68     system = new lmm::BmfSystem(selective_update);
69 #endif
70   } else if (solver_name == "fairbottleneck") {
71     system = new FairBottleneck(selective_update);
72   } else {
73     system = new System(selective_update);
74   }
75   return system;
76 }
77
78 void System::validate_solver(const std::string& solver_name)
79 {
80   static const std::vector<std::string> opts{"bmf", "maxmin", "fairbottleneck"};
81   if (solver_name == "bmf") {
82 #if !SIMGRID_HAVE_EIGEN3
83     xbt_die("Cannot use the BMF solver without installing Eigen3.");
84 #endif
85   }
86   if (std::find(opts.begin(), opts.end(), solver_name) == std::end(opts)) {
87     xbt_die("Invalid system solver, it should be one of: \"maxmin\", \"fairbottleneck\" or \"bmf\"");
88   }
89 }
90
91 void System::check_concurrency() const
92 {
93   // These checks are very expensive, so do them only if we want to debug SURF LMM
94   if (not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug))
95     return;
96
97   for (Constraint const& cnst : constraint_set) {
98     int concurrency       = 0;
99     for (Element const& elem : cnst.enabled_element_set_) {
100       xbt_assert(elem.variable->sharing_penalty_ > 0);
101       concurrency += elem.get_concurrency();
102     }
103
104     for (Element const& elem : cnst.disabled_element_set_) {
105       // We should have staged variables only if concurrency is reached in some constraint
106       xbt_assert(cnst.get_concurrency_limit() < 0 || elem.variable->staged_penalty_ == 0 ||
107                      elem.variable->get_min_concurrency_slack() < elem.variable->concurrency_share_,
108                  "should not have staged variable!");
109     }
110
111     xbt_assert(cnst.get_concurrency_limit() < 0 || cnst.get_concurrency_limit() >= concurrency,
112                "concurrency check failed!");
113     xbt_assert(cnst.concurrency_current_ == concurrency, "concurrency_current is out-of-date!");
114   }
115
116   // Check that for each variable, all corresponding elements are in the same state (i.e. same element sets)
117   for (Variable const& var : variable_set) {
118     if (var.cnsts_.empty())
119       continue;
120
121     const Element& elem    = var.cnsts_[0];
122     bool belong_to_enabled  = elem.enabled_element_set_hook.is_linked();
123     bool belong_to_disabled = elem.disabled_element_set_hook.is_linked();
124     bool belong_to_active   = elem.active_element_set_hook.is_linked();
125
126     for (Element const& elem2 : var.cnsts_) {
127       xbt_assert(belong_to_enabled == elem2.enabled_element_set_hook.is_linked(),
128                  "Variable inconsistency (1): enabled_element_set");
129       xbt_assert(belong_to_disabled == elem2.disabled_element_set_hook.is_linked(),
130                  "Variable inconsistency (2): disabled_element_set");
131       xbt_assert(belong_to_active == elem2.active_element_set_hook.is_linked(),
132                  "Variable inconsistency (3): active_element_set");
133     }
134   }
135 }
136
137 void System::var_free(Variable* var)
138 {
139   XBT_IN("(sys=%p, var=%p)", this, var);
140   modified_ = true;
141
142   // TODOLATER Can do better than that by leaving only the variable in only one enabled_element_set, call
143   // update_modified_set, and then remove it..
144   if (not var->cnsts_.empty())
145     update_modified_set(var->cnsts_[0].constraint);
146
147   for (Element& elem : var->cnsts_) {
148     if (var->sharing_penalty_ > 0)
149       elem.decrease_concurrency();
150     if (elem.enabled_element_set_hook.is_linked())
151       simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
152     if (elem.disabled_element_set_hook.is_linked())
153       simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
154     if (elem.active_element_set_hook.is_linked())
155       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
156     if (elem.constraint->enabled_element_set_.empty() && elem.constraint->disabled_element_set_.empty())
157       make_constraint_inactive(elem.constraint);
158     else
159       on_disabled_var(elem.constraint);
160   }
161
162   var->cnsts_.clear();
163
164   check_concurrency();
165
166   xbt_mallocator_release(variable_mallocator_, var);
167   XBT_OUT();
168 }
169
170 System::System(bool selective_update) : selective_update_active(selective_update)
171 {
172   XBT_DEBUG("Setting selective_update_active flag to %d", selective_update_active);
173
174   if (selective_update)
175     modified_set_ = std::make_unique<kernel::resource::Action::ModifiedSet>();
176 }
177
178 System::~System()
179 {
180   while (Variable* var = extract_variable()) {
181     std::string demangled = boost::core::demangle(var->id_ ? typeid(*var->id_).name() : "(unidentified)");
182     XBT_WARN("Probable bug: a %s variable (#%d) not removed before the LMM system destruction.", demangled.c_str(),
183              var->rank_);
184     var_free(var);
185   }
186   while (Constraint* cnst = extract_constraint())
187     cnst_free(cnst);
188
189   xbt_mallocator_free(variable_mallocator_);
190 }
191
192 void System::cnst_free(Constraint* cnst)
193 {
194   make_constraint_inactive(cnst);
195   delete cnst;
196 }
197
198 Constraint::Constraint(resource::Resource* id_value, double bound_value) : bound_(bound_value), id_(id_value)
199 {
200   rank_ = next_rank_++;
201 }
202
203 Constraint* System::constraint_new(resource::Resource* id, double bound_value)
204 {
205   auto* cnst = new Constraint(id, bound_value);
206   insert_constraint(cnst);
207   return cnst;
208 }
209
210 void* System::variable_mallocator_new_f()
211 {
212   return new Variable;
213 }
214
215 void System::variable_mallocator_free_f(void* var)
216 {
217   delete static_cast<Variable*>(var);
218 }
219
220 Variable* System::variable_new(resource::Action* id, double sharing_penalty, double bound, size_t number_of_constraints)
221 {
222   XBT_IN("(sys=%p, id=%p, penalty=%f, bound=%f, num_cons =%zu)", this, id, sharing_penalty, bound,
223          number_of_constraints);
224
225   auto* var = static_cast<Variable*>(xbt_mallocator_get(variable_mallocator_));
226   var->initialize(id, sharing_penalty, bound, number_of_constraints, visited_counter_ - 1);
227   if (sharing_penalty > 0)
228     variable_set.push_front(*var);
229   else
230     variable_set.push_back(*var);
231
232   XBT_OUT(" returns %p", var);
233   return var;
234 }
235
236 void System::variable_free(Variable* var)
237 {
238   remove_variable(var);
239   var_free(var);
240 }
241
242 void System::variable_free_all()
243 {
244   while (Variable* var = extract_variable())
245     variable_free(var);
246 }
247
248 void System::expand(Constraint* cnst, Variable* var, double consumption_weight)
249 {
250   modified_ = true;
251
252   // Check if this variable already has an active element in this constraint
253   // If it does, subtract it from the required slack
254   int current_share = 0;
255   if (var->concurrency_share_ > 1) {
256     for (const Element& elem : var->cnsts_) {
257       if (elem.constraint == cnst && elem.enabled_element_set_hook.is_linked())
258         current_share += elem.get_concurrency();
259     }
260   }
261
262   // Check if we need to disable the variable
263   if (var->sharing_penalty_ > 0 && var->concurrency_share_ - current_share > cnst->get_concurrency_slack()) {
264     double penalty = var->sharing_penalty_;
265     disable_var(var);
266     for (Element const& elem : var->cnsts_)
267       on_disabled_var(elem.constraint);
268     consumption_weight = 0;
269     var->staged_penalty_ = penalty;
270     xbt_assert(not var->sharing_penalty_);
271   }
272
273   xbt_assert(var->cnsts_.size() < var->cnsts_.capacity(), "Too much constraints");
274
275   var->cnsts_.emplace_back(cnst, var, consumption_weight);
276   Element& elem = var->cnsts_.back();
277
278   if (var->sharing_penalty_ != 0.0) {
279     elem.constraint->enabled_element_set_.push_front(elem);
280     elem.increase_concurrency();
281   } else
282     elem.constraint->disabled_element_set_.push_back(elem);
283
284   if (not selective_update_active) {
285     make_constraint_active(cnst);
286   } else if (elem.consumption_weight > 0 || var->sharing_penalty_ > 0) {
287     make_constraint_active(cnst);
288     update_modified_set(cnst);
289     // TODOLATER: Why do we need this second call?
290     if (var->cnsts_.size() > 1)
291       update_modified_set(var->cnsts_[0].constraint);
292   }
293
294   check_concurrency();
295 }
296
297 void System::expand_add(Constraint* cnst, Variable* var, double value)
298 {
299   modified_ = true;
300
301   check_concurrency();
302
303   // BEWARE: In case you have multiple elements in one constraint, this will always add value to the first element.
304   auto elem_it =
305       std::find_if(begin(var->cnsts_), end(var->cnsts_), [&cnst](Element const& x) { return x.constraint == cnst; });
306   if (elem_it != end(var->cnsts_)) {
307     Element& elem = *elem_it;
308     if (var->sharing_penalty_ != 0.0)
309       elem.decrease_concurrency();
310
311     elem.max_consumption_weight = std::max(elem.max_consumption_weight, value);
312     if (cnst->sharing_policy_ != Constraint::SharingPolicy::FATPIPE)
313       elem.consumption_weight += value;
314     else
315       elem.consumption_weight = std::max(elem.consumption_weight, value);
316
317     // We need to check that increasing value of the element does not cross the concurrency limit
318     if (var->sharing_penalty_ != 0.0) {
319       if (cnst->get_concurrency_slack() < elem.get_concurrency()) {
320         double penalty = var->sharing_penalty_;
321         disable_var(var);
322         for (Element const& elem2 : var->cnsts_)
323           on_disabled_var(elem2.constraint);
324         var->staged_penalty_ = penalty;
325         xbt_assert(not var->sharing_penalty_);
326       }
327       elem.increase_concurrency();
328     }
329     update_modified_set(cnst);
330   } else
331     expand(cnst, var, value);
332
333   check_concurrency();
334 }
335
336 Variable* Constraint::get_variable(const Element** elem) const
337 {
338   if (*elem == nullptr) {
339     // That is the first call, pick the first element among enabled_element_set (or disabled_element_set if
340     // enabled_element_set is empty)
341     if (not enabled_element_set_.empty())
342       *elem = &enabled_element_set_.front();
343     else if (not disabled_element_set_.empty())
344       *elem = &disabled_element_set_.front();
345     else
346       *elem = nullptr;
347   } else {
348     // elem is not null, so we carry on
349     if ((*elem)->enabled_element_set_hook.is_linked()) {
350       // Look at enabled_element_set, and jump to disabled_element_set when finished
351       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
352       if (iter != std::end(enabled_element_set_))
353         *elem = &*iter;
354       else if (not disabled_element_set_.empty())
355         *elem = &disabled_element_set_.front();
356       else
357         *elem = nullptr;
358     } else {
359       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
360       *elem     = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
361     }
362   }
363   if (*elem)
364     return (*elem)->variable;
365   else
366     return nullptr;
367 }
368
369 // if we modify the list between calls, normal version may loop forever
370 // this safe version ensures that we browse the list elements only once
371 Variable* Constraint::get_variable_safe(const Element** elem, const Element** nextelem, size_t* numelem) const
372 {
373   if (*elem == nullptr) {
374     *numelem = enabled_element_set_.size() + disabled_element_set_.size() - 1;
375     if (not enabled_element_set_.empty())
376       *elem = &enabled_element_set_.front();
377     else if (not disabled_element_set_.empty())
378       *elem = &disabled_element_set_.front();
379     else
380       *elem = nullptr;
381   } else {
382     *elem = *nextelem;
383     if (*numelem > 0) {
384       (*numelem)--;
385     } else
386       return nullptr;
387   }
388   if (*elem) {
389     // elem is not null, so we carry on
390     if ((*elem)->enabled_element_set_hook.is_linked()) {
391       // Look at enabled_element_set, and jump to disabled_element_set when finished
392       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
393       if (iter != std::end(enabled_element_set_))
394         *nextelem = &*iter;
395       else if (not disabled_element_set_.empty())
396         *nextelem = &disabled_element_set_.front();
397       else
398         *nextelem = nullptr;
399     } else {
400       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
401       *nextelem = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
402     }
403     return (*elem)->variable;
404   } else
405     return nullptr;
406 }
407
408 static inline void saturated_constraints_update(double usage, int cnst_light_num, dyn_light_t& saturated_constraints,
409                                                 double* min_usage)
410 {
411   xbt_assert(usage > 0, "Impossible");
412
413   if (*min_usage < 0 || *min_usage > usage) {
414     *min_usage = usage;
415     XBT_HERE(" min_usage=%f (cnst->remaining / cnst->usage =%f)", *min_usage, usage);
416     saturated_constraints.assign(1, cnst_light_num);
417   } else if (*min_usage == usage) {
418     saturated_constraints.emplace_back(cnst_light_num);
419   }
420 }
421
422 static inline void saturated_variable_set_update(const ConstraintLight* cnst_light_tab,
423                                                  const dyn_light_t& saturated_constraints, System* sys)
424 {
425   /* Add active variables (i.e. variables that need to be set) from the set of constraints to saturate
426    * (cnst_light_tab)*/
427   for (int const& saturated_cnst : saturated_constraints) {
428     const ConstraintLight& cnst = cnst_light_tab[saturated_cnst];
429     for (Element const& elem : cnst.cnst->active_element_set_) {
430       xbt_assert(elem.variable->sharing_penalty_ > 0); // All elements of active_element_set should be active
431       if (elem.consumption_weight > 0 && not elem.variable->saturated_variable_set_hook_.is_linked())
432         sys->saturated_variable_set.push_back(*elem.variable);
433     }
434   }
435 }
436
437 template <class ElemList>
438 static void format_element_list(const ElemList& elem_list, Constraint::SharingPolicy sharing_policy, double& sum,
439                                 std::string& buf)
440 {
441   for (Element const& elem : elem_list) {
442     buf += std::to_string(elem.consumption_weight) + ".'" + std::to_string(elem.variable->rank_) + "'(" +
443            std::to_string(elem.variable->value_) + ")" +
444            (sharing_policy != Constraint::SharingPolicy::FATPIPE ? " + " : " , ");
445     if (sharing_policy != Constraint::SharingPolicy::FATPIPE)
446       sum += elem.consumption_weight * elem.variable->value_;
447     else
448       sum = std::max(sum, elem.consumption_weight * elem.variable->value_);
449   }
450 }
451
452 void System::print() const
453 {
454   std::string buf = "MAX-MIN ( ";
455
456   /* Printing Objective */
457   for (Variable const& var : variable_set)
458     buf += "'" + std::to_string(var.rank_) + "'(" + std::to_string(var.sharing_penalty_) + ") ";
459   buf += ")";
460   XBT_DEBUG("%20s", buf.c_str());
461   buf.clear();
462
463   XBT_DEBUG("Constraints");
464   /* Printing Constraints */
465   for (Constraint const& cnst : active_constraint_set) {
466     double sum            = 0.0;
467     // Show  the enabled variables
468     buf += "\t";
469     buf += cnst.sharing_policy_ != Constraint::SharingPolicy::FATPIPE ? "(" : "max(";
470     format_element_list(cnst.enabled_element_set_, cnst.sharing_policy_, sum, buf);
471     // TODO: Adding disabled elements only for test compatibility, but do we really want them to be printed?
472     format_element_list(cnst.disabled_element_set_, cnst.sharing_policy_, sum, buf);
473
474     buf += "0) <= " + std::to_string(cnst.bound_) + " ('" + std::to_string(cnst.rank_) + "')";
475
476     if (cnst.sharing_policy_ == Constraint::SharingPolicy::FATPIPE) {
477       buf += " [MAX-Constraint]";
478     }
479     XBT_DEBUG("%s", buf.c_str());
480     buf.clear();
481     xbt_assert(not double_positive(sum - cnst.bound_, cnst.bound_ * sg_maxmin_precision),
482                "Incorrect value (%f is not smaller than %f): %g", sum, cnst.bound_, sum - cnst.bound_);
483   }
484
485   XBT_DEBUG("Variables");
486   /* Printing Result */
487   for (Variable const& var : variable_set) {
488     if (var.bound_ > 0) {
489       XBT_DEBUG("'%d'(%f) : %f (<=%f)", var.rank_, var.sharing_penalty_, var.value_, var.bound_);
490       xbt_assert(not double_positive(var.value_ - var.bound_, var.bound_ * sg_maxmin_precision),
491                  "Incorrect value (%f is not smaller than %f", var.value_, var.bound_);
492     } else {
493       XBT_DEBUG("'%d'(%f) : %f", var.rank_, var.sharing_penalty_, var.value_);
494     }
495   }
496 }
497
498 void System::lmm_solve()
499 {
500   if (modified_) {
501     XBT_IN("(sys=%p)", this);
502     /* Compute Usage and store the variables that reach the maximum. If selective_update_active is true, only
503      * constraints that changed are considered. Otherwise all constraints with active actions are considered.
504      */
505     if (selective_update_active)
506       lmm_solve(modified_constraint_set);
507     else
508       lmm_solve(active_constraint_set);
509     XBT_OUT();
510   }
511 }
512
513 template <class CnstList> void System::lmm_solve(CnstList& cnst_list)
514 {
515   double min_usage = -1;
516   double min_bound = -1;
517
518   XBT_DEBUG("Active constraints : %zu", cnst_list.size());
519   cnst_light_vec.reserve(cnst_list.size());
520   ConstraintLight* cnst_light_tab = cnst_light_vec.data();
521   int cnst_light_num              = 0;
522
523   for (Constraint& cnst : cnst_list) {
524     /* INIT: Collect constraints that actually need to be saturated (i.e remaining  and usage are strictly positive)
525      * into cnst_light_tab. */
526     cnst.dynamic_bound_ = cnst.bound_;
527     if (cnst.get_sharing_policy() == Constraint::SharingPolicy::NONLINEAR && cnst.dyn_constraint_cb_) {
528       cnst.dynamic_bound_ = cnst.dyn_constraint_cb_(cnst.bound_, cnst.concurrency_current_);
529     }
530     cnst.remaining_ = cnst.dynamic_bound_;
531     if (not double_positive(cnst.remaining_, cnst.dynamic_bound_ * sg_maxmin_precision))
532       continue;
533     cnst.usage_ = 0;
534     for (Element& elem : cnst.enabled_element_set_) {
535       xbt_assert(elem.variable->sharing_penalty_ > 0.0);
536       elem.variable->value_ = 0.0;
537       if (elem.consumption_weight > 0) {
538         if (cnst.sharing_policy_ != Constraint::SharingPolicy::FATPIPE)
539           cnst.usage_ += elem.consumption_weight / elem.variable->sharing_penalty_;
540         else if (cnst.usage_ < elem.consumption_weight / elem.variable->sharing_penalty_)
541           cnst.usage_ = elem.consumption_weight / elem.variable->sharing_penalty_;
542
543         elem.make_active();
544         resource::Action* action = elem.variable->id_;
545         if (modified_set_ && not action->is_within_modified_set())
546           modified_set_->push_back(*action);
547       }
548     }
549     XBT_DEBUG("Constraint '%d' usage: %f remaining: %f concurrency: %i<=%i<=%i", cnst.rank_, cnst.usage_,
550               cnst.remaining_, cnst.concurrency_current_, cnst.concurrency_maximum_, cnst.get_concurrency_limit());
551     /* Saturated constraints update */
552
553     if (cnst.usage_ > 0) {
554       cnst_light_tab[cnst_light_num].cnst                 = &cnst;
555       cnst.cnst_light_                                    = &cnst_light_tab[cnst_light_num];
556       cnst_light_tab[cnst_light_num].remaining_over_usage = cnst.remaining_ / cnst.usage_;
557       saturated_constraints_update(cnst_light_tab[cnst_light_num].remaining_over_usage, cnst_light_num,
558                                    saturated_constraints, &min_usage);
559       xbt_assert(not cnst.active_element_set_.empty(),
560                  "There is no sense adding a constraint that has no active element!");
561       cnst_light_num++;
562     }
563   }
564
565   saturated_variable_set_update(cnst_light_tab, saturated_constraints, this);
566
567   /* Saturated variables update */
568   do {
569     /* Fix the variables that have to be */
570     auto& var_list = saturated_variable_set;
571     for (Variable const& var : var_list) {
572       if (var.sharing_penalty_ <= 0.0)
573         DIE_IMPOSSIBLE;
574       /* First check if some of these variables could reach their upper bound and update min_bound accordingly. */
575       XBT_DEBUG("var=%d, var.bound=%f, var.penalty=%f, min_usage=%f, var.bound*var.penalty=%f", var.rank_, var.bound_,
576                 var.sharing_penalty_, min_usage, var.bound_ * var.sharing_penalty_);
577       if ((var.bound_ > 0) && (var.bound_ * var.sharing_penalty_ < min_usage)) {
578         if (min_bound < 0)
579           min_bound = var.bound_ * var.sharing_penalty_;
580         else
581           min_bound = std::min(min_bound, (var.bound_ * var.sharing_penalty_));
582         XBT_DEBUG("Updated min_bound=%f", min_bound);
583       }
584     }
585
586     while (not var_list.empty()) {
587       Variable& var = var_list.front();
588       if (min_bound < 0) {
589         // If no variable could reach its bound, deal iteratively the constraints usage ( at worst one constraint is
590         // saturated at each cycle)
591         var.value_ = min_usage / var.sharing_penalty_;
592         XBT_DEBUG("Setting var (%d) value to %f\n", var.rank_, var.value_);
593       } else {
594         // If there exist a variable that can reach its bound, only update it (and other with the same bound) for now.
595         if (double_equals(min_bound, var.bound_ * var.sharing_penalty_, sg_maxmin_precision)) {
596           var.value_ = var.bound_;
597           XBT_DEBUG("Setting %p (%d) value to %f\n", &var, var.rank_, var.value_);
598         } else {
599           // Variables which bound is different are not considered for this cycle, but they will be afterwards.
600           XBT_DEBUG("Do not consider %p (%d)\n", &var, var.rank_);
601           var_list.pop_front();
602           continue;
603         }
604       }
605       XBT_DEBUG("Min usage: %f, Var(%d).penalty: %f, Var(%d).value: %f", min_usage, var.rank_, var.sharing_penalty_,
606                 var.rank_, var.value_);
607
608       /* Update the usage of constraints where this variable is involved */
609       for (Element& elem : var.cnsts_) {
610         Constraint* cnst = elem.constraint;
611         if (cnst->sharing_policy_ != Constraint::SharingPolicy::FATPIPE) {
612           // Remember: shared constraints require that sum(elem.value * var.value) < cnst->bound
613           double_update(&(cnst->remaining_), elem.consumption_weight * var.value_,
614                         cnst->dynamic_bound_ * sg_maxmin_precision);
615           double_update(&(cnst->usage_), elem.consumption_weight / var.sharing_penalty_, sg_maxmin_precision);
616           // If the constraint is saturated, remove it from the set of active constraints (light_tab)
617           if (not double_positive(cnst->usage_, sg_maxmin_precision) ||
618               not double_positive(cnst->remaining_, cnst->dynamic_bound_ * sg_maxmin_precision)) {
619             if (cnst->cnst_light_) {
620               size_t index = (cnst->cnst_light_ - cnst_light_tab);
621               XBT_DEBUG("index: %zu \t cnst_light_num: %d \t || usage: %f remaining: %f bound: %f", index,
622                         cnst_light_num, cnst->usage_, cnst->remaining_, cnst->dynamic_bound_);
623               cnst_light_tab[index]                  = cnst_light_tab[cnst_light_num - 1];
624               cnst_light_tab[index].cnst->cnst_light_ = &cnst_light_tab[index];
625               cnst_light_num--;
626               cnst->cnst_light_ = nullptr;
627             }
628           } else {
629             if (cnst->cnst_light_) {
630               cnst->cnst_light_->remaining_over_usage = cnst->remaining_ / cnst->usage_;
631             }
632           }
633           elem.make_inactive();
634         } else {
635           // Remember: non-shared constraints only require that max(elem.value * var.value) < cnst->bound
636           cnst->usage_ = 0.0;
637           elem.make_inactive();
638           for (const Element& elem2 : cnst->enabled_element_set_) {
639             xbt_assert(elem2.variable->sharing_penalty_ > 0);
640             if (elem2.variable->value_ > 0)
641               continue;
642             if (elem2.consumption_weight > 0)
643               cnst->usage_ = std::max(cnst->usage_, elem2.consumption_weight / elem2.variable->sharing_penalty_);
644           }
645           // If the constraint is saturated, remove it from the set of active constraints (light_tab)
646           if (not double_positive(cnst->usage_, sg_maxmin_precision) ||
647               not double_positive(cnst->remaining_, cnst->dynamic_bound_ * sg_maxmin_precision)) {
648             if (cnst->cnst_light_) {
649               size_t index = (cnst->cnst_light_ - cnst_light_tab);
650               XBT_DEBUG("index: %zu \t cnst_light_num: %d \t || \t cnst: %p \t cnst->cnst_light: %p "
651                         "\t cnst_light_tab: %p usage: %f remaining: %f bound: %f",
652                         index, cnst_light_num, cnst, cnst->cnst_light_, cnst_light_tab, cnst->usage_, cnst->remaining_,
653                         cnst->dynamic_bound_);
654               cnst_light_tab[index]                  = cnst_light_tab[cnst_light_num - 1];
655               cnst_light_tab[index].cnst->cnst_light_ = &cnst_light_tab[index];
656               cnst_light_num--;
657               cnst->cnst_light_ = nullptr;
658             }
659           } else {
660             if (cnst->cnst_light_) {
661               cnst->cnst_light_->remaining_over_usage = cnst->remaining_ / cnst->usage_;
662               xbt_assert(not cnst->active_element_set_.empty(),
663                          "Should not keep a maximum constraint that has no active"
664                          " element! You want to check the maxmin precision and possible rounding effects.");
665             }
666           }
667         }
668       }
669       var_list.pop_front();
670     }
671
672     /* Find out which variables reach the maximum */
673     min_usage = -1;
674     min_bound = -1;
675     saturated_constraints.clear();
676     for (int pos = 0; pos < cnst_light_num; pos++) {
677       xbt_assert(not cnst_light_tab[pos].cnst->active_element_set_.empty(),
678                  "Cannot saturate more a constraint that has"
679                  " no active element! You may want to change the maxmin precision (--cfg=maxmin/precision:<new_value>)"
680                  " because of possible rounding effects.\n\tFor the record, the usage of this constraint is %g while "
681                  "the maxmin precision to which it is compared is %g.\n\tThe usage of the previous constraint is %g.",
682                  cnst_light_tab[pos].cnst->usage_, sg_maxmin_precision, cnst_light_tab[pos - 1].cnst->usage_);
683       saturated_constraints_update(cnst_light_tab[pos].remaining_over_usage, pos, saturated_constraints, &min_usage);
684     }
685
686     saturated_variable_set_update(cnst_light_tab, saturated_constraints, this);
687   } while (cnst_light_num > 0);
688
689   modified_ = false;
690   if (selective_update_active)
691     remove_all_modified_set();
692
693   if (XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug)) {
694     print();
695   }
696
697   check_concurrency();
698 }
699
700 /** @brief Attribute the value bound to var->bound.
701  *
702  *  @param var the Variable*
703  *  @param bound the new bound to associate with var
704  *
705  *  Makes var->bound equal to bound. Whenever this function is called a change is  signed in the system. To
706  *  avoid false system changing detection it is a good idea to test (bound != 0) before calling it.
707  */
708 void System::update_variable_bound(Variable* var, double bound)
709 {
710   modified_  = true;
711   var->bound_ = bound;
712
713   if (not var->cnsts_.empty())
714     update_modified_set(var->cnsts_[0].constraint);
715 }
716
717 void Variable::initialize(resource::Action* id_value, double sharing_penalty, double bound_value,
718                           size_t number_of_constraints, unsigned visited_value)
719 {
720   id_     = id_value;
721   rank_   = next_rank_++;
722   cnsts_.reserve(number_of_constraints);
723   sharing_penalty_   = sharing_penalty;
724   staged_penalty_    = 0.0;
725   bound_             = bound_value;
726   concurrency_share_ = 1;
727   value_             = 0.0;
728   visited_           = visited_value;
729   mu_                = 0.0;
730
731   xbt_assert(not variable_set_hook_.is_linked());
732   xbt_assert(not saturated_variable_set_hook_.is_linked());
733 }
734
735 int Variable::get_min_concurrency_slack() const
736 {
737   int minslack = std::numeric_limits<int>::max();
738   for (Element const& elem : cnsts_) {
739     int slack = elem.constraint->get_concurrency_slack();
740     if (slack < minslack) {
741       // This is only an optimization, to avoid looking at more constraints when slack is already zero
742       if (slack == 0)
743         return 0;
744       minslack = slack;
745     }
746   }
747   return minslack;
748 }
749
750 // Small remark: In this implementation of System::enable_var() and System::disable_var(), we will meet multiple times
751 // with var when running System::update_modified_set().
752 // A priori not a big performance issue, but we might do better by calling System::update_modified_set() within the for
753 // loops (after doing the first for enabling==1, and before doing the last for disabling==1)
754 void System::enable_var(Variable* var)
755 {
756   xbt_assert(not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug) || var->can_enable());
757
758   var->sharing_penalty_ = var->staged_penalty_;
759   var->staged_penalty_  = 0;
760
761   // Enabling the variable, move var to list head. Subtlety is: here, we need to call update_modified_set AFTER
762   // moving at least one element of var.
763
764   simgrid::xbt::intrusive_erase(variable_set, *var);
765   variable_set.push_front(*var);
766   for (Element& elem : var->cnsts_) {
767     simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
768     elem.constraint->enabled_element_set_.push_front(elem);
769     elem.increase_concurrency();
770   }
771   if (not var->cnsts_.empty())
772     update_modified_set(var->cnsts_[0].constraint);
773
774   // When used within on_disabled_var, we would get an assertion fail, because transiently there can be variables
775   // that are staged and could be activated.
776   // Anyway, caller functions all call check_concurrency() in the end.
777 }
778
779 void System::disable_var(Variable* var)
780 {
781   xbt_assert(not var->staged_penalty_, "Staged penalty should have been cleared");
782   // Disabling the variable, move to var to list tail. Subtlety is: here, we need to call update_modified_set
783   // BEFORE moving the last element of var.
784   simgrid::xbt::intrusive_erase(variable_set, *var);
785   variable_set.push_back(*var);
786   if (not var->cnsts_.empty())
787     update_modified_set(var->cnsts_[0].constraint);
788   for (Element& elem : var->cnsts_) {
789     simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
790     elem.constraint->disabled_element_set_.push_back(elem);
791     if (elem.active_element_set_hook.is_linked())
792       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
793     elem.decrease_concurrency();
794   }
795
796   var->sharing_penalty_ = 0.0;
797   var->staged_penalty_  = 0.0;
798   var->value_          = 0.0;
799   check_concurrency();
800 }
801
802 /* /brief Find variables that can be enabled and enable them.
803  *
804  * Assuming that the variable has already been removed from non-zero penalties
805  * Can we find a staged variable to add?
806  * If yes, check that none of the constraints that this variable is involved in is at the limit of its concurrency
807  * And then add it to enabled variables
808  */
809 void System::on_disabled_var(Constraint* cnstr)
810 {
811   if (cnstr->get_concurrency_limit() < 0)
812     return;
813
814   size_t numelem = cnstr->disabled_element_set_.size();
815   if (numelem == 0)
816     return;
817
818   Element* elem = &cnstr->disabled_element_set_.front();
819
820   // Cannot use foreach loop, because System::enable_var() will modify disabled_element_set.. within the loop
821   while (numelem-- && elem) {
822     Element* nextelem;
823     if (elem->disabled_element_set_hook.is_linked()) {
824       auto iter = std::next(cnstr->disabled_element_set_.iterator_to(*elem));
825       nextelem  = iter != std::end(cnstr->disabled_element_set_) ? &*iter : nullptr;
826     } else {
827       nextelem = nullptr;
828     }
829
830     if (elem->variable->staged_penalty_ > 0 && elem->variable->can_enable()) {
831       // Found a staged variable
832       // TODOLATER: Add random timing function to model reservation protocol fuzziness? Then how to make sure that
833       // staged variables will eventually be called?
834       enable_var(elem->variable);
835     }
836
837     xbt_assert(cnstr->concurrency_current_ <= cnstr->get_concurrency_limit(), "Concurrency overflow!");
838     if (cnstr->concurrency_current_ == cnstr->get_concurrency_limit())
839       break;
840
841     elem = nextelem;
842   }
843
844   // We could get an assertion fail, because transiently there can be variables that are staged and could be activated.
845   // And we need to go through all constraints of the disabled var before getting back a coherent state.
846   // Anyway, caller functions all call check_concurrency() in the end.
847 }
848
849 /** @brief update the penalty of a variable (disable it by passing 0 as a penalty) */
850 void System::update_variable_penalty(Variable* var, double penalty)
851 {
852   xbt_assert(penalty >= 0, "Variable penalty should not be negative!");
853   if (penalty == var->sharing_penalty_)
854     return;
855
856   bool enabling_var  = (penalty > 0 && var->sharing_penalty_ <= 0);
857   bool disabling_var = (penalty <= 0 && var->sharing_penalty_ > 0);
858
859   XBT_IN("(sys=%p, var=%p, var->sharing_penalty = %f, penalty=%f)", this, var, var->sharing_penalty_, penalty);
860
861   modified_ = true;
862
863   // Are we enabling this variable?
864   if (enabling_var) {
865     var->staged_penalty_ = penalty;
866     int minslack       = var->get_min_concurrency_slack();
867     if (minslack < var->concurrency_share_) {
868       XBT_DEBUG("Staging var (instead of enabling) because min concurrency slack %i, with penalty %f and concurrency"
869                 " share %i",
870                 minslack, penalty, var->concurrency_share_);
871       return;
872     }
873     XBT_DEBUG("Enabling var with min concurrency slack %i", minslack);
874     enable_var(var);
875   } else if (disabling_var) {
876     disable_var(var);
877   } else {
878     var->sharing_penalty_ = penalty;
879     if (not var->cnsts_.empty())
880       update_modified_set(var->cnsts_[0].constraint);
881   }
882
883   check_concurrency();
884
885   XBT_OUT();
886 }
887
888 void System::update_constraint_bound(Constraint* cnst, double bound)
889 {
890   modified_ = true;
891   update_modified_set(cnst);
892   cnst->bound_ = bound;
893 }
894
895 /** @brief Update the constraint set propagating recursively to other constraints so the system should not be entirely
896  *  computed.
897  *
898  *  @param cnst the Constraint* affected by the change
899  *
900  *  A recursive algorithm to optimize the system recalculation selecting only constraints that have changed. Each
901  *  constraint change is propagated to the list of constraints for each variable.
902  */
903 void System::update_modified_set_rec(const Constraint* cnst)
904 {
905   for (Element const& elem : cnst->enabled_element_set_) {
906     Variable* var = elem.variable;
907     for (Element const& elem2 : var->cnsts_) {
908       if (var->visited_ == visited_counter_)
909         break;
910       if (elem2.constraint != cnst && not elem2.constraint->modified_constraint_set_hook_.is_linked()) {
911         modified_constraint_set.push_back(*elem2.constraint);
912         update_modified_set_rec(elem2.constraint);
913       }
914     }
915     // var will be ignored in later visits as long as sys->visited_counter does not move
916     var->visited_ = visited_counter_;
917   }
918 }
919
920 void System::update_modified_set(Constraint* cnst)
921 {
922   /* nothing to do if selective update isn't active */
923   if (selective_update_active && not cnst->modified_constraint_set_hook_.is_linked()) {
924     modified_constraint_set.push_back(*cnst);
925     update_modified_set_rec(cnst);
926   }
927 }
928
929 void System::remove_all_modified_set()
930 {
931   // We cleverly un-flag all variables just by incrementing visited_counter
932   // In effect, the var->visited value will no more be equal to visited counter
933   // To be clean, when visited counter has wrapped around, we force these var->visited values so that variables that
934   // were in the modified a long long time ago are not wrongly skipped here, which would lead to very nasty bugs
935   // (i.e. not readily reproducible, and requiring a lot of run time before happening).
936   if (++visited_counter_ == 1) {
937     /* the counter wrapped around, reset each variable->visited */
938     for (Variable& var : variable_set)
939       var.visited_ = 0;
940   }
941   modified_constraint_set.clear();
942 }
943
944 /**
945  * Returns resource load (in flop per second, or byte per second, or similar)
946  *
947  * If the resource is shared (the default case), the load is sum of resource usage made by
948  * every variables located on this resource.
949  *
950  * If the resource is not shared (ie in FATPIPE mode), then the load is the max (not the sum)
951  * of all resource usages located on this resource.
952  */
953 double Constraint::get_usage() const
954 {
955   double result              = 0.0;
956   if (sharing_policy_ != SharingPolicy::FATPIPE) {
957     for (Element const& elem : enabled_element_set_)
958       if (elem.consumption_weight > 0)
959         result += elem.consumption_weight * elem.variable->value_;
960   } else {
961     for (Element const& elem : enabled_element_set_)
962       if (elem.consumption_weight > 0)
963         result = std::max(result, elem.consumption_weight * elem.variable->value_);
964   }
965   return result;
966 }
967
968 int Constraint::get_variable_amount() const
969 {
970   return static_cast<int>(std::count_if(std::begin(enabled_element_set_), std::end(enabled_element_set_),
971                                         [](const Element& elem) { return elem.consumption_weight > 0; }));
972 }
973
974 void Constraint::set_sharing_policy(SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
975 {
976   xbt_assert(policy == SharingPolicy::NONLINEAR || not cb,
977              "Invalid sharing policy for constraint. Callback should be used with NONLINEAR sharing policy");
978   sharing_policy_    = policy;
979   dyn_constraint_cb_ = cb;
980 }
981
982 } // namespace lmm
983 } // namespace kernel
984 } // namespace simgrid