Logo AND Algorithmique Numérique Distribuée

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