Logo AND Algorithmique Numérique Distribuée

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