Logo AND Algorithmique Numérique Distribuée

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