Logo AND Algorithmique Numérique Distribuée

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