Logo AND Algorithmique Numérique Distribuée

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