Logo AND Algorithmique Numérique Distribuée

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