Logo AND Algorithmique Numérique Distribuée

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