Logo AND Algorithmique Numérique Distribuée

Public GIT Repository
66408e415fbc2e17c380847401d210c618ef5332
[simgrid.git] / src / kernel / lmm / System.cpp
1 /* Copyright (c) 2004-2022. 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/fair_bottleneck.hpp"
7 #include "src/kernel/lmm/maxmin.hpp"
8 #if SIMGRID_HAVE_EIGEN3
9 #include "src/kernel/lmm/bmf.hpp"
10 #endif
11 #include <boost/core/demangle.hpp>
12 #include <typeinfo>
13
14 XBT_LOG_NEW_DEFAULT_SUBCATEGORY(ker_lmm, kernel, "Kernel Linear Max-Min solver");
15
16 double sg_maxmin_precision = 1E-5; /* Change this with --cfg=maxmin/precision:VALUE */
17 double sg_surf_precision   = 1E-9; /* Change this with --cfg=surf/precision:VALUE */
18 int sg_concurrency_limit   = -1;      /* Change this with --cfg=maxmin/concurrency-limit:VALUE */
19
20 namespace simgrid {
21 namespace kernel {
22 namespace lmm {
23
24 int Variable::next_rank_   = 1;
25 int Constraint::next_rank_ = 1;
26
27 Element::Element(Constraint* constraint, Variable* variable, double cweight)
28     : constraint(constraint), variable(variable), consumption_weight(cweight), max_consumption_weight(cweight)
29 {
30 }
31
32 int Element::get_concurrency() const
33 {
34   // Ignore element with weight less than one (e.g. cross-traffic)
35   return (consumption_weight >= 1) ? 1 : 0;
36   // There are other alternatives, but they will change the behavior of the model..
37   // So do not use it unless you want to make a new model.
38   // If you do, remember to change the variables concurrency share to reflect it.
39   // Potential examples are:
40   // return (elem->weight>0)?1:0;//Include element as soon  as weight is non-zero
41   // return (int)ceil(elem->weight);//Include element as the rounded-up integer value of the element weight
42 }
43
44 void Element::decrease_concurrency()
45 {
46   xbt_assert(constraint->concurrency_current_ >= get_concurrency());
47   constraint->concurrency_current_ -= get_concurrency();
48 }
49
50 void Element::increase_concurrency()
51 {
52   constraint->concurrency_current_ += get_concurrency();
53
54   if (constraint->concurrency_current_ > constraint->concurrency_maximum_)
55     constraint->concurrency_maximum_ = constraint->concurrency_current_;
56
57   xbt_assert(constraint->get_concurrency_limit() < 0 ||
58                  constraint->concurrency_current_ <= constraint->get_concurrency_limit(),
59              "Concurrency limit overflow!");
60 }
61
62 System* System::build(const std::string& solver_name, bool selective_update)
63 {
64   System* system = nullptr;
65   if (solver_name == "bmf") {
66 #if SIMGRID_HAVE_EIGEN3
67     system = new BmfSystem(selective_update);
68 #endif
69   } else if (solver_name == "fairbottleneck") {
70     system = new FairBottleneck(selective_update);
71   } else {
72     system = new MaxMin(selective_update);
73   }
74   return system;
75 }
76
77 void System::validate_solver(const std::string& solver_name)
78 {
79   static const std::vector<std::string> opts{"bmf", "maxmin", "fairbottleneck"};
80   if (solver_name == "bmf") {
81 #if !SIMGRID_HAVE_EIGEN3
82     xbt_die("Cannot use the BMF solver without installing Eigen3.");
83 #endif
84   }
85   if (std::find(opts.begin(), opts.end(), solver_name) == std::end(opts)) {
86     xbt_die("Invalid system solver, it should be one of: \"maxmin\", \"fairbottleneck\" or \"bmf\"");
87   }
88 }
89
90 void System::check_concurrency() const
91 {
92   // These checks are very expensive, so do them only if we want to debug SURF LMM
93   if (not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug))
94     return;
95
96   for (Constraint const& cnst : constraint_set) {
97     int concurrency       = 0;
98     for (Element const& elem : cnst.enabled_element_set_) {
99       xbt_assert(elem.variable->sharing_penalty_ > 0);
100       concurrency += elem.get_concurrency();
101     }
102
103     for (Element const& elem : cnst.disabled_element_set_) {
104       // We should have staged variables only if concurrency is reached in some constraint
105       xbt_assert(cnst.get_concurrency_limit() < 0 || elem.variable->staged_penalty_ == 0 ||
106                      elem.variable->get_min_concurrency_slack() < elem.variable->concurrency_share_,
107                  "should not have staged variable!");
108     }
109
110     xbt_assert(cnst.get_concurrency_limit() < 0 || cnst.get_concurrency_limit() >= concurrency,
111                "concurrency check failed!");
112     xbt_assert(cnst.concurrency_current_ == concurrency, "concurrency_current is out-of-date!");
113   }
114
115   // Check that for each variable, all corresponding elements are in the same state (i.e. same element sets)
116   for (Variable const& var : variable_set) {
117     if (var.cnsts_.empty())
118       continue;
119
120     const Element& elem    = var.cnsts_[0];
121     bool belong_to_enabled  = elem.enabled_element_set_hook.is_linked();
122     bool belong_to_disabled = elem.disabled_element_set_hook.is_linked();
123     bool belong_to_active   = elem.active_element_set_hook.is_linked();
124
125     for (Element const& elem2 : var.cnsts_) {
126       xbt_assert(belong_to_enabled == elem2.enabled_element_set_hook.is_linked(),
127                  "Variable inconsistency (1): enabled_element_set");
128       xbt_assert(belong_to_disabled == elem2.disabled_element_set_hook.is_linked(),
129                  "Variable inconsistency (2): disabled_element_set");
130       xbt_assert(belong_to_active == elem2.active_element_set_hook.is_linked(),
131                  "Variable inconsistency (3): active_element_set");
132     }
133   }
134 }
135
136 void System::var_free(Variable* var)
137 {
138   XBT_IN("(sys=%p, var=%p)", this, var);
139   modified_ = true;
140
141   // TODOLATER Can do better than that by leaving only the variable in only one enabled_element_set, call
142   // update_modified_set, and then remove it..
143   update_modified_cnst_set_from_variable(var);
144
145   for (Element& elem : var->cnsts_) {
146     if (var->sharing_penalty_ > 0)
147       elem.decrease_concurrency();
148     if (elem.enabled_element_set_hook.is_linked())
149       simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
150     if (elem.disabled_element_set_hook.is_linked())
151       simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
152     if (elem.active_element_set_hook.is_linked())
153       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
154     if (elem.constraint->enabled_element_set_.empty() && elem.constraint->disabled_element_set_.empty())
155       make_constraint_inactive(elem.constraint);
156     else
157       on_disabled_var(elem.constraint);
158   }
159
160   var->cnsts_.clear();
161
162   check_concurrency();
163
164   xbt_mallocator_release(variable_mallocator_, var);
165   XBT_OUT();
166 }
167
168 System::System(bool selective_update) : selective_update_active(selective_update)
169 {
170   XBT_DEBUG("Setting selective_update_active flag to %d", selective_update_active);
171
172   if (selective_update)
173     modified_set_ = std::make_unique<kernel::resource::Action::ModifiedSet>();
174 }
175
176 System::~System()
177 {
178   while (Variable* var = extract_variable()) {
179     std::string demangled = boost::core::demangle(var->id_ ? typeid(*var->id_).name() : "(unidentified)");
180     XBT_WARN("Probable bug: a %s variable (#%d) not removed before the LMM system destruction.", demangled.c_str(),
181              var->rank_);
182     var_free(var);
183   }
184   while (Constraint* cnst = extract_constraint())
185     cnst_free(cnst);
186
187   xbt_mallocator_free(variable_mallocator_);
188 }
189
190 void System::cnst_free(Constraint* cnst)
191 {
192   make_constraint_inactive(cnst);
193   delete cnst;
194 }
195
196 Constraint::Constraint(resource::Resource* id_value, double bound_value) : bound_(bound_value), id_(id_value)
197 {
198   rank_ = next_rank_++;
199 }
200
201 Constraint* System::constraint_new(resource::Resource* id, double bound_value)
202 {
203   auto* cnst = new Constraint(id, bound_value);
204   insert_constraint(cnst);
205   return cnst;
206 }
207
208 void* System::variable_mallocator_new_f()
209 {
210   return new Variable;
211 }
212
213 void System::variable_mallocator_free_f(void* var)
214 {
215   delete static_cast<Variable*>(var);
216 }
217
218 Variable* System::variable_new(resource::Action* id, double sharing_penalty, double bound, size_t number_of_constraints)
219 {
220   XBT_IN("(sys=%p, id=%p, penalty=%f, bound=%f, num_cons =%zu)", this, id, sharing_penalty, bound,
221          number_of_constraints);
222
223   auto* var = static_cast<Variable*>(xbt_mallocator_get(variable_mallocator_));
224   var->initialize(id, sharing_penalty, bound, number_of_constraints, visited_counter_ - 1);
225   if (sharing_penalty > 0)
226     variable_set.push_front(*var);
227   else
228     variable_set.push_back(*var);
229
230   XBT_OUT(" returns %p", var);
231   return var;
232 }
233
234 void System::variable_free(Variable* var)
235 {
236   remove_variable(var);
237   var_free(var);
238 }
239
240 void System::variable_free_all()
241 {
242   while (Variable* var = extract_variable())
243     variable_free(var);
244 }
245
246 void System::expand(Constraint* cnst, Variable* var, double consumption_weight)
247 {
248   modified_ = true;
249
250   // Check if this variable already has an active element in this constraint
251   // If it does, subtract it from the required slack
252   int current_share = 0;
253   if (var->concurrency_share_ > 1) {
254     for (const Element& elem : var->cnsts_) {
255       if (elem.constraint == cnst && elem.enabled_element_set_hook.is_linked())
256         current_share += elem.get_concurrency();
257     }
258   }
259
260   // Check if we need to disable the variable
261   if (var->sharing_penalty_ > 0 && var->concurrency_share_ - current_share > cnst->get_concurrency_slack()) {
262     double penalty = var->sharing_penalty_;
263     disable_var(var);
264     for (Element const& elem : var->cnsts_)
265       on_disabled_var(elem.constraint);
266     consumption_weight = 0;
267     var->staged_penalty_ = penalty;
268     xbt_assert(not var->sharing_penalty_);
269   }
270
271   xbt_assert(var->cnsts_.size() < var->cnsts_.capacity(), "Too much constraints");
272
273   var->cnsts_.emplace_back(cnst, var, consumption_weight);
274   Element& elem = var->cnsts_.back();
275
276   if (var->sharing_penalty_ != 0.0) {
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_penalty_ > 0) {
285     make_constraint_active(cnst);
286     update_modified_cnst_set(cnst);
287     // TODOLATER: Why do we need this second call?
288     if (var->cnsts_.size() > 1)
289       update_modified_cnst_set(var->cnsts_[0].constraint);
290   }
291
292   check_concurrency();
293 }
294
295 void System::expand_add(Constraint* cnst, Variable* 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 =
303       std::find_if(begin(var->cnsts_), end(var->cnsts_), [&cnst](Element const& x) { return x.constraint == cnst; });
304   if (elem_it != end(var->cnsts_)) {
305     Element& elem = *elem_it;
306     if (var->sharing_penalty_ != 0.0)
307       elem.decrease_concurrency();
308
309     elem.max_consumption_weight = std::max(elem.max_consumption_weight, value);
310     if (cnst->sharing_policy_ != Constraint::SharingPolicy::FATPIPE)
311       elem.consumption_weight += value;
312     else
313       elem.consumption_weight = std::max(elem.consumption_weight, value);
314
315     // We need to check that increasing value of the element does not cross the concurrency limit
316     if (var->sharing_penalty_ != 0.0) {
317       if (cnst->get_concurrency_slack() < elem.get_concurrency()) {
318         double penalty = var->sharing_penalty_;
319         disable_var(var);
320         for (Element const& elem2 : var->cnsts_)
321           on_disabled_var(elem2.constraint);
322         var->staged_penalty_ = penalty;
323         xbt_assert(not var->sharing_penalty_);
324       }
325       elem.increase_concurrency();
326     }
327     update_modified_cnst_set(cnst);
328   } else
329     expand(cnst, var, value);
330
331   check_concurrency();
332 }
333
334 Variable* Constraint::get_variable(const Element** elem) const
335 {
336   if (*elem == nullptr) {
337     // That is the first call, pick the first element among enabled_element_set (or disabled_element_set if
338     // enabled_element_set is empty)
339     if (not enabled_element_set_.empty())
340       *elem = &enabled_element_set_.front();
341     else if (not disabled_element_set_.empty())
342       *elem = &disabled_element_set_.front();
343     else
344       *elem = nullptr;
345   } else {
346     // elem is not null, so we carry on
347     if ((*elem)->enabled_element_set_hook.is_linked()) {
348       // Look at enabled_element_set, and jump to disabled_element_set when finished
349       auto iter = std::next(enabled_element_set_.iterator_to(**elem));
350       if (iter != std::end(enabled_element_set_))
351         *elem = &*iter;
352       else if (not disabled_element_set_.empty())
353         *elem = &disabled_element_set_.front();
354       else
355         *elem = nullptr;
356     } else {
357       auto iter = std::next(disabled_element_set_.iterator_to(**elem));
358       *elem     = iter != std::end(disabled_element_set_) ? &*iter : nullptr;
359     }
360   }
361   if (*elem)
362     return (*elem)->variable;
363   else
364     return nullptr;
365 }
366
367 // if we modify the list between calls, normal version may loop forever
368 // this safe version ensures that we browse the list elements only once
369 Variable* Constraint::get_variable_safe(const Element** elem, const Element** nextelem, size_t* 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 template <class ElemList>
407 static void format_element_list(const ElemList& elem_list, Constraint::SharingPolicy sharing_policy, double& sum,
408                                 std::string& buf)
409 {
410   for (Element const& elem : elem_list) {
411     buf += std::to_string(elem.consumption_weight) + ".'" + std::to_string(elem.variable->rank_) + "'(" +
412            std::to_string(elem.variable->value_) + ")" +
413            (sharing_policy != Constraint::SharingPolicy::FATPIPE ? " + " : " , ");
414     if (sharing_policy != Constraint::SharingPolicy::FATPIPE)
415       sum += elem.consumption_weight * elem.variable->value_;
416     else
417       sum = std::max(sum, elem.consumption_weight * elem.variable->value_);
418   }
419 }
420
421 void System::print() const
422 {
423   std::string buf = "MAX-MIN ( ";
424
425   /* Printing Objective */
426   for (Variable const& var : variable_set)
427     buf += "'" + std::to_string(var.rank_) + "'(" + std::to_string(var.sharing_penalty_) + ") ";
428   buf += ")";
429   XBT_DEBUG("%20s", buf.c_str());
430   buf.clear();
431
432   XBT_DEBUG("Constraints");
433   /* Printing Constraints */
434   for (Constraint const& cnst : active_constraint_set) {
435     double sum            = 0.0;
436     // Show  the enabled variables
437     buf += "\t";
438     buf += cnst.sharing_policy_ != Constraint::SharingPolicy::FATPIPE ? "(" : "max(";
439     format_element_list(cnst.enabled_element_set_, cnst.sharing_policy_, sum, buf);
440     // TODO: Adding disabled elements only for test compatibility, but do we really want them to be printed?
441     format_element_list(cnst.disabled_element_set_, cnst.sharing_policy_, sum, buf);
442
443     buf += "0) <= " + std::to_string(cnst.bound_) + " ('" + std::to_string(cnst.rank_) + "')";
444
445     if (cnst.sharing_policy_ == Constraint::SharingPolicy::FATPIPE) {
446       buf += " [MAX-Constraint]";
447     }
448     XBT_DEBUG("%s", buf.c_str());
449     buf.clear();
450     xbt_assert(not double_positive(sum - cnst.bound_, cnst.bound_ * sg_maxmin_precision),
451                "Incorrect value (%f is not smaller than %f): %g", sum, cnst.bound_, sum - cnst.bound_);
452   }
453
454   XBT_DEBUG("Variables");
455   /* Printing Result */
456   for (Variable const& var : variable_set) {
457     if (var.bound_ > 0) {
458       XBT_DEBUG("'%d'(%f) : %f (<=%f)", var.rank_, var.sharing_penalty_, var.value_, var.bound_);
459       xbt_assert(not double_positive(var.value_ - var.bound_, var.bound_ * sg_maxmin_precision),
460                  "Incorrect value (%f is not smaller than %f", var.value_, var.bound_);
461     } else {
462       XBT_DEBUG("'%d'(%f) : %f", var.rank_, var.sharing_penalty_, var.value_);
463     }
464   }
465 }
466
467 resource::Action::ModifiedSet* System::get_modified_action_set() const
468 {
469   return modified_set_.get();
470 }
471
472 void System::solve()
473 {
474   if (not modified_)
475     return;
476
477   do_solve();
478
479   modified_ = false;
480   if (selective_update_active) {
481     /* update list of modified variables */
482     for (const Constraint& cnst : modified_constraint_set) {
483       for (const Element& elem : cnst.enabled_element_set_) {
484         if (elem.consumption_weight > 0) {
485           resource::Action* action = elem.variable->id_;
486           if (not action->is_within_modified_set())
487             modified_set_->push_back(*action);
488         }
489       }
490     }
491     /* clear list of modified constraint */
492     remove_all_modified_cnst_set();
493   }
494
495   if (XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug)) {
496     print();
497   }
498
499   check_concurrency();
500 }
501
502 /** @brief Attribute the value bound to var->bound.
503  *
504  *  @param var the Variable*
505  *  @param bound the new bound to associate with var
506  *
507  *  Makes var->bound equal to bound. Whenever this function is called a change is  signed in the system. To
508  *  avoid false system changing detection it is a good idea to test (bound != 0) before calling it.
509  */
510 void System::update_variable_bound(Variable* var, double bound)
511 {
512   modified_  = true;
513   var->bound_ = bound;
514
515   if (not var->cnsts_.empty()) {
516     for (Element const& elem : var->cnsts_) {
517       update_modified_cnst_set(elem.constraint);
518     }
519   }
520 }
521
522 void Variable::initialize(resource::Action* id_value, double sharing_penalty, double bound_value,
523                           size_t number_of_constraints, unsigned visited_value)
524 {
525   id_     = id_value;
526   rank_   = next_rank_++;
527   cnsts_.reserve(number_of_constraints);
528   sharing_penalty_   = sharing_penalty;
529   staged_penalty_    = 0.0;
530   bound_             = bound_value;
531   concurrency_share_ = 1;
532   value_             = 0.0;
533   visited_           = visited_value;
534   mu_                = 0.0;
535
536   xbt_assert(not variable_set_hook_.is_linked());
537   xbt_assert(not saturated_variable_set_hook_.is_linked());
538 }
539
540 int Variable::get_min_concurrency_slack() const
541 {
542   int minslack = std::numeric_limits<int>::max();
543   for (Element const& elem : cnsts_) {
544     int slack = elem.constraint->get_concurrency_slack();
545     if (slack < minslack) {
546       // This is only an optimization, to avoid looking at more constraints when slack is already zero
547       if (slack == 0)
548         return 0;
549       minslack = slack;
550     }
551   }
552   return minslack;
553 }
554
555 // Small remark: In this implementation of System::enable_var() and System::disable_var(), we will meet multiple times
556 // with var when running System::update_modified_cnst_set().
557 // A priori not a big performance issue, but we might do better by calling System::update_modified_cnst_set() within the
558 // for loops (after doing the first for enabling==1, and before doing the last for disabling==1)
559 void System::enable_var(Variable* var)
560 {
561   xbt_assert(not XBT_LOG_ISENABLED(ker_lmm, xbt_log_priority_debug) || var->can_enable());
562
563   var->sharing_penalty_ = var->staged_penalty_;
564   var->staged_penalty_  = 0;
565
566   // Enabling the variable, move var to list head. Subtlety is: here, we need to call update_modified_cnst_set AFTER
567   // moving at least one element of var.
568
569   simgrid::xbt::intrusive_erase(variable_set, *var);
570   variable_set.push_front(*var);
571   for (Element& elem : var->cnsts_) {
572     simgrid::xbt::intrusive_erase(elem.constraint->disabled_element_set_, elem);
573     elem.constraint->enabled_element_set_.push_front(elem);
574     elem.increase_concurrency();
575   }
576   update_modified_cnst_set_from_variable(var);
577
578   // When used within on_disabled_var, we would get an assertion fail, because transiently there can be variables
579   // that are staged and could be activated.
580   // Anyway, caller functions all call check_concurrency() in the end.
581 }
582
583 void System::disable_var(Variable* var)
584 {
585   xbt_assert(not var->staged_penalty_, "Staged penalty should have been cleared");
586   // Disabling the variable, move to var to list tail. Subtlety is: here, we need to call update_modified_cnst_set
587   // BEFORE moving the last element of var.
588   simgrid::xbt::intrusive_erase(variable_set, *var);
589   variable_set.push_back(*var);
590   update_modified_cnst_set_from_variable(var);
591   for (Element& elem : var->cnsts_) {
592     simgrid::xbt::intrusive_erase(elem.constraint->enabled_element_set_, elem);
593     elem.constraint->disabled_element_set_.push_back(elem);
594     if (elem.active_element_set_hook.is_linked())
595       simgrid::xbt::intrusive_erase(elem.constraint->active_element_set_, elem);
596     elem.decrease_concurrency();
597   }
598
599   var->sharing_penalty_ = 0.0;
600   var->staged_penalty_  = 0.0;
601   var->value_          = 0.0;
602   check_concurrency();
603 }
604
605 /* /brief Find variables that can be enabled and enable them.
606  *
607  * Assuming that the variable has already been removed from non-zero penalties
608  * Can we find a staged variable to add?
609  * If yes, check that none of the constraints that this variable is involved in is at the limit of its concurrency
610  * And then add it to enabled variables
611  */
612 void System::on_disabled_var(Constraint* cnstr)
613 {
614   if (cnstr->get_concurrency_limit() < 0)
615     return;
616
617   size_t numelem = cnstr->disabled_element_set_.size();
618   if (numelem == 0)
619     return;
620
621   Element* elem = &cnstr->disabled_element_set_.front();
622
623   // Cannot use foreach loop, because System::enable_var() will modify disabled_element_set.. within the loop
624   while (numelem-- && elem) {
625     Element* nextelem;
626     if (elem->disabled_element_set_hook.is_linked()) {
627       auto iter = std::next(cnstr->disabled_element_set_.iterator_to(*elem));
628       nextelem  = iter != std::end(cnstr->disabled_element_set_) ? &*iter : nullptr;
629     } else {
630       nextelem = nullptr;
631     }
632
633     if (elem->variable->staged_penalty_ > 0 && elem->variable->can_enable()) {
634       // Found a staged variable
635       // TODOLATER: Add random timing function to model reservation protocol fuzziness? Then how to make sure that
636       // staged variables will eventually be called?
637       enable_var(elem->variable);
638     }
639
640     xbt_assert(cnstr->concurrency_current_ <= cnstr->get_concurrency_limit(), "Concurrency overflow!");
641     if (cnstr->concurrency_current_ == cnstr->get_concurrency_limit())
642       break;
643
644     elem = nextelem;
645   }
646
647   // We could get an assertion fail, because transiently there can be variables that are staged and could be activated.
648   // And we need to go through all constraints of the disabled var before getting back a coherent state.
649   // Anyway, caller functions all call check_concurrency() in the end.
650 }
651
652 /** @brief update the penalty of a variable (disable it by passing 0 as a penalty) */
653 void System::update_variable_penalty(Variable* var, double penalty)
654 {
655   xbt_assert(penalty >= 0, "Variable penalty should not be negative!");
656   if (penalty == var->sharing_penalty_)
657     return;
658
659   bool enabling_var  = (penalty > 0 && var->sharing_penalty_ <= 0);
660   bool disabling_var = (penalty <= 0 && var->sharing_penalty_ > 0);
661
662   XBT_IN("(sys=%p, var=%p, var->sharing_penalty = %f, penalty=%f)", this, var, var->sharing_penalty_, penalty);
663
664   modified_ = true;
665
666   // Are we enabling this variable?
667   if (enabling_var) {
668     var->staged_penalty_ = penalty;
669     int minslack       = var->get_min_concurrency_slack();
670     if (minslack < var->concurrency_share_) {
671       XBT_DEBUG("Staging var (instead of enabling) because min concurrency slack %i, with penalty %f and concurrency"
672                 " share %i",
673                 minslack, penalty, var->concurrency_share_);
674       return;
675     }
676     XBT_DEBUG("Enabling var with min concurrency slack %i", minslack);
677     enable_var(var);
678   } else if (disabling_var) {
679     disable_var(var);
680   } else {
681     var->sharing_penalty_ = penalty;
682     update_modified_cnst_set_from_variable(var);
683   }
684
685   check_concurrency();
686
687   XBT_OUT();
688 }
689
690 void System::update_constraint_bound(Constraint* cnst, double bound)
691 {
692   modified_ = true;
693   update_modified_cnst_set(cnst);
694   cnst->bound_ = bound;
695 }
696
697 /** @brief Update the constraint set propagating recursively to other constraints so the system should not be entirely
698  *  computed.
699  *
700  *  @param cnst the Constraint* affected by the change
701  *
702  *  A recursive algorithm to optimize the system recalculation selecting only constraints that have changed. Each
703  *  constraint change is propagated to the list of constraints for each variable.
704  */
705 void System::update_modified_cnst_set_rec(const Constraint* cnst)
706 {
707   for (Element const& elem : cnst->enabled_element_set_) {
708     Variable* var = elem.variable;
709     for (Element const& elem2 : var->cnsts_) {
710       if (var->visited_ == visited_counter_)
711         break;
712       if (elem2.constraint != cnst && not elem2.constraint->modified_constraint_set_hook_.is_linked()) {
713         modified_constraint_set.push_back(*elem2.constraint);
714         update_modified_cnst_set_rec(elem2.constraint);
715       }
716     }
717     // var will be ignored in later visits as long as sys->visited_counter does not move
718     var->visited_ = visited_counter_;
719   }
720 }
721
722 void System::update_modified_cnst_set_from_variable(const Variable* var)
723 {
724   /* nothing to update in these cases:
725    * - selective update not active, all variables are active
726    * - variable doesn't use any constraint
727    * - variable is disabled (sharing penalty <= 0): we iterate only through the enabled_variables in
728    * update_modified_cnst_set_rec */
729   if (not selective_update_active || var->cnsts_.empty() || var->sharing_penalty_ <= 0)
730     return;
731
732   /* Normally, if the conditions above are true, specially variable is enabled, we can call
733    * modified_set over the first contraint only, since the recursion in update_modified_cnst_set_rec
734    * will iterate over the other constraints of this variable */
735   update_modified_cnst_set(var->cnsts_[0].constraint);
736 }
737
738 void System::update_modified_cnst_set(Constraint* cnst)
739 {
740   /* nothing to do if selective update isn't active */
741   if (selective_update_active && not cnst->modified_constraint_set_hook_.is_linked()) {
742     modified_constraint_set.push_back(*cnst);
743     update_modified_cnst_set_rec(cnst);
744   }
745 }
746
747 void System::remove_all_modified_cnst_set()
748 {
749   // We cleverly un-flag all variables just by incrementing visited_counter
750   // In effect, the var->visited value will no more be equal to visited counter
751   // To be clean, when visited counter has wrapped around, we force these var->visited values so that variables that
752   // were in the modified a long long time ago are not wrongly skipped here, which would lead to very nasty bugs
753   // (i.e. not readily reproducible, and requiring a lot of run time before happening).
754   if (++visited_counter_ == 1) {
755     /* the counter wrapped around, reset each variable->visited */
756     for (Variable& var : variable_set)
757       var.visited_ = 0;
758   }
759   modified_constraint_set.clear();
760 }
761
762 /**
763  * Returns resource load (in flop per second, or byte per second, or similar)
764  *
765  * If the resource is shared (the default case), the load is sum of resource usage made by
766  * every variables located on this resource.
767  *
768  * If the resource is not shared (ie in FATPIPE mode), then the load is the max (not the sum)
769  * of all resource usages located on this resource.
770  */
771 double Constraint::get_usage() const
772 {
773   double result              = 0.0;
774   if (sharing_policy_ != SharingPolicy::FATPIPE) {
775     for (Element const& elem : enabled_element_set_)
776       if (elem.consumption_weight > 0)
777         result += elem.consumption_weight * elem.variable->value_;
778   } else {
779     for (Element const& elem : enabled_element_set_)
780       if (elem.consumption_weight > 0)
781         result = std::max(result, elem.consumption_weight * elem.variable->value_);
782   }
783   return result;
784 }
785
786 int Constraint::get_variable_amount() const
787 {
788   return static_cast<int>(std::count_if(std::begin(enabled_element_set_), std::end(enabled_element_set_),
789                                         [](const Element& elem) { return elem.consumption_weight > 0; }));
790 }
791
792 void Constraint::set_sharing_policy(SharingPolicy policy, const s4u::NonLinearResourceCb& cb)
793 {
794   xbt_assert(policy == SharingPolicy::NONLINEAR || not cb,
795              "Invalid sharing policy for constraint. Callback should be used with NONLINEAR sharing policy");
796   sharing_policy_    = policy;
797   dyn_constraint_cb_ = cb;
798 }
799
800 } // namespace lmm
801 } // namespace kernel
802 } // namespace simgrid