Logo AND Algorithmique Numérique Distribuée

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