Logo AND Algorithmique Numérique Distribuée

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