Logo AND Algorithmique Numérique Distribuée

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