Logo AND Algorithmique Numérique Distribuée

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