Logo AND Algorithmique Numérique Distribuée

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