Logo AND Algorithmique Numérique Distribuée

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