Logo AND Algorithmique Numérique Distribuée

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