fixing dv plugin
[oweals/gnunet.git] / src / ats / plugin_ats_ril.c
1 /*
2  This file is part of GNUnet.
3  (C) 2011 Christian Grothoff (and other contributing authors)
4
5  GNUnet is free software; you can redistribute it and/or modify
6  it under the terms of the GNU General Public License as published
7  by the Free Software Foundation; either version 3, or (at your
8  option) any later version.
9
10  GNUnet is distributed in the hope that it will be useful, but
11  WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  General Public License for more details.
14
15  You should have received a copy of the GNU General Public License
16  along with GNUnet; see the file COPYING.  If not, write to the
17  Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  Boston, MA 02111-1307, USA.
19  */
20
21 /**
22  * @file ats/plugin_ats_ril.c
23  * @brief ATS reinforcement learning solver
24  * @author Fabian Oehlmann
25  * @author Matthias Wachs
26  */
27 #include "plugin_ats_ril.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
30
31 #define MIN_BW ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__)
32
33 #define RIL_ACTION_INVALID -1
34 #define RIL_INTERVAL_EXPONENT 10
35 #define RIL_UTILITY_MAX (double) GNUNET_ATS_MaxBandwidth
36
37 #define RIL_DEFAULT_STEP_TIME_MIN       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
38 #define RIL_DEFAULT_STEP_TIME_MAX       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 3000)
39 #define RIL_DEFAULT_ALGORITHM           RIL_ALGO_SARSA
40 #define RIL_DEFAULT_SELECT              RIL_SELECT_EGREEDY
41 #define RIL_DEFAULT_DISCOUNT_BETA       1.0
42 #define RIL_DEFAULT_DISCOUNT_GAMMA      0.5
43 #define RIL_DEFAULT_GRADIENT_STEP_SIZE  0.1
44 #define RIL_DEFAULT_TRACE_DECAY         0.5
45 #define RIL_DEFAULT_EXPLORE_RATIO       0.1
46 #define RIL_DEFAULT_RBF_DIVISOR             10
47 #define RIL_DEFAULT_GLOBAL_REWARD_SHARE 0.5
48 #define RIL_DEFAULT_TEMPERATURE         1.0
49
50 #define RIL_INC_DEC_STEP_SIZE           1
51
52 /**
53  * ATS reinforcement learning solver
54  *
55  * General description
56  */
57
58 /**
59  * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
60  * changed for the currently chosen address. Not depicted in the enum are the actions of switching
61  * to a particular address. The action of switching to address with index i is depicted by the
62  * number (RIL_ACTION_TYPE_NUM + i).
63  */
64 enum RIL_Action_Type
65 {
66   RIL_ACTION_NOTHING = 0,
67   RIL_ACTION_BW_IN_DBL = -2, //TODO! put actions back
68   RIL_ACTION_BW_IN_HLV = -3,
69   RIL_ACTION_BW_IN_INC = 1,
70   RIL_ACTION_BW_IN_DEC = 2,
71   RIL_ACTION_BW_OUT_DBL = -4,
72   RIL_ACTION_BW_OUT_HLV = -5,
73   RIL_ACTION_BW_OUT_INC = 3,
74   RIL_ACTION_BW_OUT_DEC = 4,
75   RIL_ACTION_TYPE_NUM = 5
76 };
77
78 enum RIL_Algorithm
79 {
80   RIL_ALGO_SARSA = 0,
81   RIL_ALGO_Q = 1
82 };
83
84 enum RIL_Select
85 {
86   RIL_SELECT_EGREEDY,
87   RIL_SELECT_SOFTMAX
88 };
89
90 enum RIL_E_Modification
91 {
92   RIL_E_DISCOUNT,
93   RIL_E_ZERO,
94   RIL_E_ACCUMULATE,
95   RIL_E_REPLACE
96 };
97
98 /**
99  * Global learning parameters
100  */
101 struct RIL_Learning_Parameters
102 {
103   /**
104    * The TD-algorithm to use
105    */
106   enum RIL_Algorithm algorithm;
107
108   /**
109    * Gradient-descent step-size
110    */
111   double alpha;
112
113   /**
114    * Learning discount variable in the TD-update for semi-MDPs
115    */
116   double beta;
117
118   /**
119    * Learning discount factor in the TD-update for MDPs
120    */
121   double gamma;
122
123   /**
124    * Trace-decay factor for eligibility traces
125    */
126   double lambda;
127
128   /**
129    * Whether to accumulate or replace eligibility traces
130    */
131   enum RIL_E_Modification eligibility_trace_mode;
132
133   /**
134    * Softmax action-selection temperature
135    */
136   double temperature;
137
138   /**
139    * State space divisor
140    */
141   unsigned long long int divisor;
142
143   /**
144    * Action selection strategy;
145    */
146   enum RIL_Select select;
147
148   /**
149    * Ratio, with what probability an agent should explore in the e-greed policy
150    */
151   double explore_ratio;
152
153   /**
154    * How big the share of the global part of the reward signal is
155    */
156   double reward_global_share;
157
158   /**
159    * Minimal interval time between steps in milliseconds
160    */
161   struct GNUNET_TIME_Relative step_time_min;
162
163   /**
164    * Maximum interval time between steps in milliseconds
165    */
166   struct GNUNET_TIME_Relative step_time_max;
167 };
168
169 /**
170  * Wrapper for addresses to store them in agent's linked list
171  */
172 struct RIL_Address_Wrapped
173 {
174   /**
175    * Next in DLL
176    */
177   struct RIL_Address_Wrapped *next;
178
179   /**
180    * Previous in DLL
181    */
182   struct RIL_Address_Wrapped *prev;
183
184   /**
185    * The address
186    */
187   struct ATS_Address *address_naked;
188 };
189
190 struct RIL_Peer_Agent
191 {
192   /**
193    * Next agent in solver's linked list
194    */
195   struct RIL_Peer_Agent *next;
196
197   /**
198    * Previous agent in solver's linked list
199    */
200   struct RIL_Peer_Agent *prev;
201
202   /**
203    * Environment handle
204    */
205   struct GAS_RIL_Handle *envi;
206
207   /**
208    * Peer ID
209    */
210   struct GNUNET_PeerIdentity peer;
211
212   /**
213    * Whether the agent is active or not
214    */
215   int is_active;
216
217   /**
218    * Number of performed time-steps
219    */
220   unsigned long long step_count;
221
222   /**
223    * Experience matrix W
224    */
225   double ** W;
226
227   /**
228    * Number of rows of W / Number of state-vector features
229    */
230   unsigned int m;
231
232   /**
233    * Number of columns of W / Number of actions
234    */
235   unsigned int n;
236
237   /**
238    * Last perceived state feature vector
239    */
240   double * s_old;
241
242   /**
243    * Last chosen action
244    */
245   int a_old;
246
247   /**
248    * Eligibility traces
249    */
250   double ** E;
251
252   /**
253    * Address in use
254    */
255   struct ATS_Address * address_inuse;
256
257   /**
258    * Head of addresses DLL
259    */
260   struct RIL_Address_Wrapped * addresses_head;
261
262   /**
263    * Tail of addresses DLL
264    */
265   struct RIL_Address_Wrapped * addresses_tail;
266
267   /**
268    * Inbound bandwidth assigned by the agent
269    */
270   unsigned long long bw_in;
271
272   /**
273    * Outbound bandwidth assigned by the agent
274    */
275   unsigned long long bw_out;
276
277   /**
278    * Flag whether a suggestion has to be issued
279    */
280   int suggestion_issue;
281
282   /**
283    * The address which has to be issued
284    */
285   struct ATS_Address * suggestion_address;
286 };
287
288 struct RIL_Scope
289 {
290   /**
291    * ATS network type
292    */
293   enum GNUNET_ATS_Network_Type type;
294
295   /**
296    * Total available inbound bandwidth
297    */
298   unsigned long long bw_in_available;
299
300   /**
301    * Bandwidth inbound assigned in network after last step
302    */
303   unsigned long long bw_in_assigned;
304
305   /**
306    * Total available outbound bandwidth
307    */
308   unsigned long long bw_out_available;
309
310   /**
311    * * Bandwidth outbound assigned in network after last step
312    */
313   unsigned long long bw_out_assigned;
314 };
315
316 /**
317  * A handle for the reinforcement learning solver
318  */
319 struct GAS_RIL_Handle
320 {
321   /**
322    * The solver-plugin environment of the solver-plugin API
323    */
324   struct GNUNET_ATS_PluginEnvironment *plugin_envi;
325
326   /**
327    * Statistics handle
328    */
329   struct GNUNET_STATISTICS_Handle *stats;
330
331   /**
332    * Number of performed steps
333    */
334   unsigned long long step_count;
335
336   /**
337    * Timestamp for the last time-step
338    */
339   struct GNUNET_TIME_Absolute step_time_last;
340
341   /**
342    * Task identifier of the next time-step to be executed
343    */
344   GNUNET_SCHEDULER_TaskIdentifier step_next_task_id;
345
346   /**
347    * Variable discount factor, dependent on time between steps
348    */
349   double global_discount_variable;
350
351   /**
352    * Integrated variable discount factor, dependent on time between steps
353    */
354   double global_discount_integrated;
355
356   /**
357    * Lock for bulk operations
358    */
359   int bulk_lock;
360
361   /**
362    * Number of changes during a lock
363    */
364   int bulk_changes;
365
366   /**
367    * Learning parameters
368    */
369   struct RIL_Learning_Parameters parameters;
370
371   /**
372    * Array of networks with global assignment state
373    */
374   struct RIL_Scope * network_entries;
375
376   /**
377    * Networks count
378    */
379   unsigned int networks_count;
380
381   /**
382    * List of active peer-agents
383    */
384   struct RIL_Peer_Agent * agents_head;
385   struct RIL_Peer_Agent * agents_tail;
386
387   /**
388    * Shutdown
389    */
390   int done;
391
392   /**
393    * Simulate steps, i.e. schedule steps immediately
394    */
395   unsigned long long simulate;
396 };
397
398 /*
399  *  Private functions
400  *  ---------------------------
401  */
402
403 static int
404 ril_count_agents(struct GAS_RIL_Handle * solver);
405
406 static double
407 agent_get_utility (struct RIL_Peer_Agent *agent)
408 {
409   //TODO get utilitiy
410   return (double) agent->bw_in;
411 }
412
413 /**
414  * Estimate the current action-value for state s and action a
415  *
416  * @param agent agent performing the estimation
417  * @param state s
418  * @param action a
419  * @return estimation value
420  */
421 static double
422 agent_estimate_q (struct RIL_Peer_Agent *agent, double *state, int action)
423 {
424   int i;
425   double result = 0;
426
427   for (i = 0; i < agent->m; i++)
428   {
429     result += state[i] * agent->W[action][i];
430   }
431
432   GNUNET_assert(!isnan(result));
433
434   //prevent crash when learning diverges
435   if (isinf(result))
436   {
437     return isinf(result) * UINT32_MAX;
438   }
439   return result;
440 }
441
442
443 /**
444  * Get the index of the address in the agent's list.
445  *
446  * @param agent agent handle
447  * @param address address handle
448  * @return the index, starting with zero
449  */
450 static int
451 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
452 {
453   int i;
454   struct RIL_Address_Wrapped *cur;
455
456   i = -1;
457   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
458   {
459     i++;
460     if (cur->address_naked == address)
461       return i;
462   }
463   return i;
464 }
465
466
467 /**
468  * Gets the wrapped address from the agent's list
469  *
470  * @param agent agent handle
471  * @param address address handle
472  * @return wrapped address
473  */
474 static struct RIL_Address_Wrapped *
475 agent_address_get (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
476 {
477   struct RIL_Address_Wrapped *cur;
478
479   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
480     if (cur->address_naked == address)
481       return cur;
482   return NULL;
483 }
484
485
486 /**
487  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
488  * most reward in the future)
489  *
490  * @param agent agent performing the calculation
491  * @param state the state from which to take the action
492  * @return the action promising most future reward
493  */
494 static int
495 agent_get_action_max (struct RIL_Peer_Agent *agent, double *state)
496 {
497   int i;
498   int num_actions;
499   int max_i = RIL_ACTION_INVALID;
500   double cur_q;
501   double max_q = -DBL_MAX;
502
503   num_actions = agent->address_inuse->used ? RIL_ACTION_TYPE_NUM : agent->n;
504
505   for (i = 0; i < num_actions; i++)
506   {
507     cur_q = agent_estimate_q (agent, state, i);
508     if (cur_q > max_q)
509     {
510       max_q = cur_q;
511       max_i = i;
512     }
513   }
514
515   GNUNET_assert(RIL_ACTION_INVALID != max_i);
516
517   return max_i;
518 }
519
520
521 /**
522  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
523  *
524  * @param agent the agent performing the update
525  * @param reward the reward received for the last action
526  * @param s_next the new state, the last step got the agent into
527  * @param a_prime the new
528  */
529 static void
530 agent_update_weights (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
531 {
532   int i;
533   double delta;
534   double *theta = agent->W[agent->a_old];
535
536   delta = agent->envi->global_discount_integrated * reward; //reward
537   delta += agent->envi->global_discount_variable * agent_estimate_q (agent, s_next, a_prime); //discounted future value
538   delta -= agent_estimate_q (agent, agent->s_old, agent->a_old); //one step
539
540 //  LOG(GNUNET_ERROR_TYPE_INFO, "update()   Step# %llu  Q(s,a): %f  a: %f  r: %f  y: %f  Q(s+1,a+1) = %f  delta: %f\n",
541 //      agent->step_count,
542 //      agent_estimate_q (agent, agent->s_old, agent->a_old),
543 //      agent->envi->parameters.alpha,
544 //      reward,
545 //      agent->envi->global_discount_variable,
546 //      agent_estimate_q (agent, s_next, a_prime),
547 //      delta);
548
549   for (i = 0; i < agent->m; i++)
550   {
551 //    LOG(GNUNET_ERROR_TYPE_INFO, "alpha = %f   delta = %f   e[%d] = %f\n",
552 //        agent->envi->parameters.alpha,
553 //        delta,
554 //        i,
555 //        agent->e[i]);
556     theta[i] += agent->envi->parameters.alpha * delta * agent->s_old[i];// * agent->E[a_prime][i];
557   }
558 }
559
560
561 /**
562  * Changes the eligibility trace vector e in various manners:
563  * #RIL_E_ACCUMULATE - adds @a feature to each component as in accumulating eligibility traces
564  * #RIL_E_REPLACE - resets each component to @a feature  as in replacing traces
565  * #RIL_E_SET - multiplies e with discount factor and lambda as in the update rule
566  * #RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
567  *
568  * @param agent the agent handle
569  * @param mod the kind of modification
570  * @param feature the feature vector
571  */
572 static void
573 agent_modify_eligibility (struct RIL_Peer_Agent *agent,
574                           enum RIL_E_Modification mod,
575                           double *feature,
576                           int action)
577 {
578   int i;
579   int k;
580
581   for (i = 0; i < agent->m; i++)
582   {
583     switch (mod)
584     {
585     case RIL_E_ACCUMULATE:
586       agent->E[action][i] += feature[i];
587       break;
588     case RIL_E_REPLACE:
589       agent->E[action][i] =  (agent->envi->global_discount_variable * agent->envi->parameters.lambda * agent->E[action][i]) > feature[i] ? agent->E[action][i] : feature[i];
590       break;
591     case RIL_E_DISCOUNT:
592       agent->E[action][i] *= agent->envi->global_discount_variable * agent->envi->parameters.lambda;
593       break;
594     case RIL_E_ZERO:
595       for (k = 0; k < agent->n; k++)
596       {
597         agent->E[k][i] = 0;
598       }
599       break;
600     }
601   }
602 }
603
604
605 static void
606 ril_inform (struct GAS_RIL_Handle *solver,
607     enum GAS_Solver_Operation op,
608     enum GAS_Solver_Status stat)
609 {
610   if (NULL != solver->plugin_envi->info_cb)
611     solver->plugin_envi->info_cb (solver->plugin_envi->info_cb_cls, op, stat, GAS_INFO_NONE);
612 }
613
614
615 /**
616  * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
617  * notify ATS of its new decision
618  *
619  * @param solver solver handle
620  * @param agent agent handle
621  * @param new_address the address which is to be used
622  * @param new_bw_in the new amount of inbound bandwidth set for this address
623  * @param new_bw_out the new amount of outbound bandwidth set for this address
624  * @param silent disables invocation of the bw_changed callback, if GNUNET_YES
625  */
626 static void
627 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
628     struct RIL_Peer_Agent *agent,
629     struct ATS_Address *new_address,
630     unsigned long long new_bw_in,
631     unsigned long long new_bw_out,
632     int silent)
633 {
634   int notify = GNUNET_NO;
635
636   LOG(GNUNET_ERROR_TYPE_DEBUG, "    set_active_suggestion() for peer '%s'\n", GNUNET_i2s (&agent->peer));
637
638   //address change
639   if (agent->address_inuse != new_address)
640   {
641     if (NULL != agent->address_inuse)
642     {
643       agent->address_inuse->active = GNUNET_NO;
644       agent->address_inuse->assigned_bw_in.value__ = htonl (0);
645       agent->address_inuse->assigned_bw_out.value__ = htonl (0);
646     }
647     if (NULL != new_address)
648     {
649       LOG(GNUNET_ERROR_TYPE_DEBUG, "    set address active: %s\n", agent->is_active ? "yes" : "no");
650       new_address->active = agent->is_active;
651       new_address->assigned_bw_in.value__ = htonl (agent->bw_in);
652       new_address->assigned_bw_out.value__ = htonl (agent->bw_out);
653     }
654     notify |= GNUNET_YES;
655   }
656
657   if (new_address)
658   {
659     //activity change
660     if (new_address->active != agent->is_active)
661     {
662       new_address->active = agent->is_active;
663       notify |= GNUNET_YES;
664     }
665
666     //bw change
667     if (agent->bw_in != new_bw_in)
668     {
669       agent->bw_in = new_bw_in;
670       new_address->assigned_bw_in.value__ = htonl (new_bw_in);
671       notify |= GNUNET_YES;
672     }
673     if (agent->bw_out != new_bw_out)
674     {
675       agent->bw_out = new_bw_out;
676       new_address->assigned_bw_out.value__ = htonl (new_bw_out);
677       notify |= GNUNET_YES;
678     }
679   }
680
681   if (notify && agent->is_active && (GNUNET_NO == silent))
682   {
683     if (new_address)
684     {
685       LOG(GNUNET_ERROR_TYPE_DEBUG, "    envi_set_active_suggestion() notify\n");
686       agent->suggestion_issue = GNUNET_YES;
687       agent->suggestion_address = new_address;
688     }
689     else if (agent->address_inuse)
690     {
691       //disconnect case, no new address
692       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_in.value__));
693       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_out.value__));
694       agent->bw_in = 0;
695       agent->bw_out = 0;
696
697       agent->suggestion_issue = GNUNET_YES;
698       agent->suggestion_address = agent->address_inuse;
699     }
700   }
701   agent->address_inuse = new_address;
702 }
703
704
705 static unsigned long long
706 ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
707 {
708   struct RIL_Peer_Agent *cur;
709   struct RIL_Scope *net;
710   unsigned long long sum = 0;
711
712   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
713   {
714     if (cur->is_active && cur->address_inuse)
715     {
716       net = cur->address_inuse->solver_information;
717       if (net->type == type)
718       {
719         if (direction_in)
720           sum += cur->bw_in;
721         else
722           sum += cur->bw_out;
723       }
724     }
725   }
726
727   return sum;
728 }
729
730 /**
731  * Allocates a state vector and fills it with the features present
732  * @param solver the solver handle
733  * @param agent the agent handle
734  * @return pointer to the state vector
735  */
736 static double *
737 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
738 {
739   double *state;
740   double y[2];
741   double x[2];
742   double d[2];
743   double sigma;
744   double f;
745   int m;
746   int i;
747   int k;
748
749   state = GNUNET_malloc (sizeof(double) * agent->m);
750
751   y[0] = (double) agent->bw_out;
752   y[1] = (double) agent->bw_in;
753
754   m = agent_address_get_index (agent, agent->address_inuse) * (solver->parameters.divisor+1) * (solver->parameters.divisor+1);
755   for (i = 0; i <= solver->parameters.divisor; i++)
756   {
757     for (k = 0; k <= solver->parameters.divisor; k++)
758     {
759       x[0] = i * GNUNET_ATS_MaxBandwidth / solver->parameters.divisor;
760       x[1] = k * GNUNET_ATS_MaxBandwidth / solver->parameters.divisor;
761       d[0] = x[0]-y[0];
762       d[1] = x[1]-y[1];
763       sigma = ((double) GNUNET_ATS_MaxBandwidth / 2) * M_SQRT2;
764       f = exp(-((d[0]*d[0] + d[1]*d[1]) / (2 * sigma * sigma)));
765       state[m++] = f;
766     }
767   }
768
769   return state;
770 }
771
772 ///*
773 // * For all networks a peer has an address in, this gets the maximum bandwidth which could
774 // * theoretically be available in one of the networks. This is used for bandwidth normalization.
775 // *
776 // * @param agent the agent handle
777 // * @param direction_in whether the inbound bandwidth should be considered. Returns the maximum outbound bandwidth if GNUNET_NO
778 // */
779 //static unsigned long long
780 //ril_get_max_bw (struct RIL_Peer_Agent *agent, int direction_in)
781 //{
782 //  /*
783 //   * get the maximum bandwidth possible for a peer, e.g. among all addresses which addresses'
784 //   * network could provide the maximum bandwidth if all that bandwidth was used on that one peer.
785 //   */
786 //  unsigned long long max = 0;
787 //  struct RIL_Address_Wrapped *cur;
788 //  struct RIL_Scope *net;
789 //
790 //  for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
791 //  {
792 //    net = cur->address_naked->solver_information;
793 //    if (direction_in)
794 //    {
795 //      if (net->bw_in_available > max)
796 //      {
797 //        max = net->bw_in_available;
798 //      }
799 //    }
800 //    else
801 //    {
802 //      if (net->bw_out_available > max)
803 //      {
804 //        max = net->bw_out_available;
805 //      }
806 //    }
807 //  }
808 //  return max;
809 //}
810
811 ///*
812 // * Get the index of the quality-property in question
813 // *
814 // * @param type the quality property type
815 // * @return the index
816 // */
817 //static int
818 //ril_find_property_index (uint32_t type)
819 //{
820 //  int existing_types[] = GNUNET_ATS_QualityProperties;
821 //  int c;
822 //  for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
823 //    if (existing_types[c] == type)
824 //      return c;
825 //  return GNUNET_SYSERR;
826 //}
827
828 //static int
829 //ril_get_atsi (struct ATS_Address *address, uint32_t type)
830 //{
831 //  int c1;
832 //  GNUNET_assert(NULL != address);
833 //
834 //  if ((NULL == address->atsi) || (0 == address->atsi_count))
835 //    return 0;
836 //
837 //  for (c1 = 0; c1 < address->atsi_count; c1++)
838 //  {
839 //    if (ntohl (address->atsi[c1].type) == type)
840 //      return ntohl (address->atsi[c1].value);
841 //  }
842 //  return 0;
843 //}
844
845 //static double
846 //envi_reward_global (struct GAS_RIL_Handle *solver)
847 //{
848 //  int i;
849 //  struct RIL_Scope net;
850 //  unsigned int sum_in_available = 0;
851 //  unsigned int sum_out_available = 0;
852 //  unsigned int sum_in_assigned = 0;
853 //  unsigned int sum_out_assigned = 0;
854 //  double ratio_in;
855 //  double ratio_out;
856 //
857 //  for (i = 0; i < solver->networks_count; i++)
858 //  {
859 //    net = solver->network_entries[i];
860 //    sum_in_available += net.bw_in_available;
861 //    sum_in_assigned += net.bw_in_assigned;
862 //    sum_out_available += net.bw_out_available;
863 //    sum_out_assigned += net.bw_out_assigned;
864 //  }
865 //
866 //  ratio_in = ((double) sum_in_assigned) / ((double) sum_in_available);
867 //  ratio_out = ((double) sum_out_assigned) / ((double) sum_out_available);
868 //
869 //  // global reward in [1,2]
870 //  return ratio_in +1;
871 //  return ((ratio_in + ratio_out) / 2) + 1;
872 //}
873
874 //static double
875 //envi_reward_local (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
876 //{
877 //  const double *preferences;
878 //  const double *properties;
879 //  int prop_index;
880 //  double pref_match = 0;
881 //  double bw_norm;
882 //  double dl_norm;
883 //
884 //  preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
885 //      &agent->peer);
886 //  properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
887 //      agent->address_inuse);
888 //
889 //  // delay in [0,1]
890 //  prop_index = ril_find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
891 //  dl_norm = 2 - properties[prop_index]; //invert property as we want to maximize for lower latencies
892 //
893 //  // utilization in [0,1]
894 //  bw_norm = (((double) ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_IN)
895 //      / (double) ril_get_max_bw (agent, GNUNET_YES))
896 //      + ((double) ril_get_atsi (agent->address_inuse, GNUNET_ATS_UTILIZATION_OUT)
897 //          / (double) ril_get_max_bw (agent, GNUNET_NO))) / 2;
898 //
899 //  // preference matching in [0,4]
900 //  pref_match += (preferences[GNUNET_ATS_PREFERENCE_LATENCY] * dl_norm);
901 //  pref_match += (preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * bw_norm);
902 //
903 //  // local reward in [1,2]
904 //  return (pref_match / 4) +1;
905 //}
906
907 static double
908 envi_get_collective_utility (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope)
909 {
910   //TODO! add nash product
911   struct RIL_Peer_Agent *cur;
912   double result = RIL_UTILITY_MAX;
913
914   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
915   {
916     if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope))
917     {
918       result = GNUNET_MIN(result, agent_get_utility(cur));
919     }
920   }
921
922   return result;
923 }
924
925 /**
926  * Gets the reward for the last performed step, which is calculated in equal
927  * parts from the local (the peer specific) and the global (for all peers
928  * identical) reward.
929  *
930  * @param solver the solver handle
931  * @param agent the agent handle
932  * @return the reward
933  */
934 static double
935 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
936 {
937   struct RIL_Scope *net;
938
939   unsigned long long objective;
940
941   LOG(GNUNET_ERROR_TYPE_INFO, "address: %x\n", agent->address_inuse);
942   net = agent->address_inuse->solver_information;
943   if (net->bw_in_assigned > net->bw_in_available)
944   {
945     objective = net->bw_in_available - net->bw_in_assigned;
946   }
947   else
948   {
949     objective = envi_get_collective_utility(solver, agent->address_inuse->solver_information);
950   }
951
952   return objective;
953 }
954
955 /**
956  * Doubles the bandwidth for the active address
957  *
958  * @param solver solver handle
959  * @param agent agent handle
960  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
961  */
962 static void
963 envi_action_bw_double (struct GAS_RIL_Handle *solver,
964     struct RIL_Peer_Agent *agent,
965     int direction_in)
966 {
967   unsigned long long new_bw;
968
969   if (direction_in)
970   {
971     new_bw = agent->bw_in * 2;
972     if (new_bw < agent->bw_in || new_bw > GNUNET_ATS_MaxBandwidth)
973       new_bw = GNUNET_ATS_MaxBandwidth;
974     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
975         agent->bw_out, GNUNET_NO);
976   }
977   else
978   {
979     new_bw = agent->bw_out * 2;
980     if (new_bw < agent->bw_out || new_bw > GNUNET_ATS_MaxBandwidth)
981       new_bw = GNUNET_ATS_MaxBandwidth;
982     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
983         new_bw, GNUNET_NO);
984   }
985 }
986
987 /**
988  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
989  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
990  *
991  * @param solver solver handle
992  * @param agent agent handle
993  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
994  * bandwidth
995  */
996 static void
997 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
998     struct RIL_Peer_Agent *agent,
999     int direction_in)
1000 {
1001   unsigned long long new_bw;
1002
1003   if (direction_in)
1004   {
1005     new_bw = agent->bw_in / 2;
1006     if (new_bw < MIN_BW || new_bw > agent->bw_in)
1007       new_bw = MIN_BW;
1008     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1009         GNUNET_NO);
1010   }
1011   else
1012   {
1013     new_bw = agent->bw_out / 2;
1014     if (new_bw < MIN_BW || new_bw > agent->bw_out)
1015       new_bw = MIN_BW;
1016     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
1017         GNUNET_NO);
1018   }
1019 }
1020
1021 /**
1022  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
1023  *
1024  * @param solver solver handle
1025  * @param agent agent handle
1026  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1027  * bandwidth
1028  */
1029 static void
1030 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1031 {
1032   unsigned long long new_bw;
1033
1034   if (direction_in)
1035   {
1036     new_bw = agent->bw_in + (RIL_INC_DEC_STEP_SIZE * MIN_BW);
1037     if (new_bw < agent->bw_in || new_bw > GNUNET_ATS_MaxBandwidth)
1038       new_bw = GNUNET_ATS_MaxBandwidth;
1039     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
1040         agent->bw_out, GNUNET_NO);
1041   }
1042   else
1043   {
1044     new_bw = agent->bw_out + (RIL_INC_DEC_STEP_SIZE * MIN_BW);
1045     if (new_bw < agent->bw_out || new_bw > GNUNET_ATS_MaxBandwidth)
1046       new_bw = GNUNET_ATS_MaxBandwidth;
1047     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
1048         new_bw, GNUNET_NO);
1049   }
1050 }
1051
1052 /**
1053  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
1054  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
1055  *
1056  * @param solver solver handle
1057  * @param agent agent handle
1058  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
1059  * bandwidth
1060  */
1061 static void
1062 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
1063 {
1064   unsigned long long new_bw;
1065
1066   if (direction_in)
1067   {
1068     new_bw = agent->bw_in - (RIL_INC_DEC_STEP_SIZE * MIN_BW);
1069     if (new_bw < MIN_BW || new_bw > agent->bw_in)
1070       new_bw = MIN_BW;
1071     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
1072         GNUNET_NO);
1073   }
1074   else
1075   {
1076     new_bw = agent->bw_out - (RIL_INC_DEC_STEP_SIZE * MIN_BW);
1077     if (new_bw < MIN_BW || new_bw > agent->bw_out)
1078       new_bw = MIN_BW;
1079     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
1080         GNUNET_NO);
1081   }
1082 }
1083
1084 /**
1085  * Switches to the address given by its index
1086  *
1087  * @param solver solver handle
1088  * @param agent agent handle
1089  * @param address_index index of the address as it is saved in the agent's list, starting with zero
1090  */
1091 static void
1092 envi_action_address_switch (struct GAS_RIL_Handle *solver,
1093     struct RIL_Peer_Agent *agent,
1094     unsigned int address_index)
1095 {
1096   struct RIL_Address_Wrapped *cur;
1097   int i = 0;
1098
1099   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
1100   {
1101     if (i == address_index)
1102     {
1103       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
1104           GNUNET_NO);
1105       return;
1106     }
1107
1108     i++;
1109   }
1110
1111   //no address with address_index exists, in this case this action should not be callable
1112   GNUNET_assert(GNUNET_NO);
1113 }
1114
1115 /**
1116  * Puts the action into effect by calling the according function
1117  *
1118  * @param solver the solver handle
1119  * @param agent the action handle
1120  * @param action the action to perform by the solver
1121  */
1122 static void
1123 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
1124 {
1125   int address_index;
1126
1127   switch (action)
1128   {
1129   case RIL_ACTION_NOTHING:
1130     break;
1131   case RIL_ACTION_BW_IN_DBL:
1132     envi_action_bw_double (solver, agent, GNUNET_YES);
1133     break;
1134   case RIL_ACTION_BW_IN_HLV:
1135     envi_action_bw_halven (solver, agent, GNUNET_YES);
1136     break;
1137   case RIL_ACTION_BW_IN_INC:
1138     envi_action_bw_inc (solver, agent, GNUNET_YES);
1139     break;
1140   case RIL_ACTION_BW_IN_DEC:
1141     envi_action_bw_dec (solver, agent, GNUNET_YES);
1142     break;
1143   case RIL_ACTION_BW_OUT_DBL:
1144     envi_action_bw_double (solver, agent, GNUNET_NO);
1145     break;
1146   case RIL_ACTION_BW_OUT_HLV:
1147     envi_action_bw_halven (solver, agent, GNUNET_NO);
1148     break;
1149   case RIL_ACTION_BW_OUT_INC:
1150     envi_action_bw_inc (solver, agent, GNUNET_NO);
1151     break;
1152   case RIL_ACTION_BW_OUT_DEC:
1153     envi_action_bw_dec (solver, agent, GNUNET_NO);
1154     break;
1155   default:
1156     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
1157     {
1158       address_index = action - RIL_ACTION_TYPE_NUM;
1159
1160       GNUNET_assert(address_index >= 0);
1161       GNUNET_assert(
1162           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
1163
1164       envi_action_address_switch (solver, agent, address_index);
1165       break;
1166     }
1167     // error - action does not exist
1168     GNUNET_assert(GNUNET_NO);
1169   }
1170 }
1171
1172 static int
1173 agent_select_egreedy (struct RIL_Peer_Agent *agent, double *state)
1174 {
1175   int action;
1176   int num_actions;
1177   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1178         UINT32_MAX) / (double) UINT32_MAX;
1179
1180   num_actions = agent->address_inuse->used ? RIL_ACTION_TYPE_NUM : agent->n;
1181
1182   if (r < agent->envi->parameters.explore_ratio) //explore
1183   {
1184     action = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, num_actions);
1185     if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
1186     {
1187       agent_modify_eligibility(agent, RIL_E_ZERO, NULL, action);
1188     }
1189     return action;
1190   }
1191   else //exploit
1192   {
1193     action = agent_get_action_max(agent, state);
1194     if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
1195     {
1196       agent_modify_eligibility(agent, RIL_E_DISCOUNT, NULL, action);
1197     }
1198     return action;
1199   }
1200 }
1201
1202 /**
1203  * Selects the next action with a probability corresponding to its value. The
1204  * probability is calculated using a Boltzmann distribution with a temperature
1205  * value. The higher the temperature, the more are the action selection
1206  * probabilities the same. With a temperature of 0, the selection is greedy,
1207  * i.e. always the action with the highest value is chosen.
1208  * @param agent
1209  * @param state
1210  * @return
1211  */
1212 static int
1213 agent_select_softmax (struct RIL_Peer_Agent *agent, double *state)
1214 {
1215   int i;
1216   int a_max;
1217   int num_actions;
1218   double eqt[agent->n];
1219   double p[agent->n];
1220   double sum = 0;
1221   double r;
1222
1223   num_actions = agent->address_inuse->used ? RIL_ACTION_TYPE_NUM : agent->n;
1224
1225   a_max = agent_get_action_max(agent, state);
1226
1227   for (i=0; i<num_actions; i++)
1228   {
1229     eqt[i] = exp(agent_estimate_q(agent,state,i) / agent->envi->parameters.temperature);
1230     sum += eqt[i];
1231   }
1232   for (i=0; i<num_actions; i++)
1233   {
1234     p[i] = eqt[i]/sum;
1235   }
1236   r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
1237       UINT32_MAX) / (double) UINT32_MAX;
1238   sum = 0;
1239   for (i=0; i<num_actions; i++)
1240   {
1241     if (sum + p[i] > r)
1242     {
1243       if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
1244       {
1245         if (i == a_max)
1246           agent_modify_eligibility(agent, RIL_E_DISCOUNT, NULL, i);
1247         else
1248           agent_modify_eligibility(agent, RIL_E_ZERO, NULL, -1);
1249       }
1250       return i;
1251     }
1252     sum += p[i];
1253   }
1254   GNUNET_assert(GNUNET_NO);
1255 }
1256
1257 static int
1258 agent_select_action (struct RIL_Peer_Agent *agent, double *state)
1259 {
1260   if (agent->envi->parameters.select == RIL_SELECT_EGREEDY)
1261   {
1262     return agent_select_egreedy(agent, state);
1263   }
1264   else
1265   {
1266     return agent_select_softmax(agent, state);
1267   }
1268 }
1269
1270 /**
1271  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
1272  * after having done the last action a_old. It observes the new state s_next and the reward
1273  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1274  * next action is put into effect.
1275  *
1276  * @param agent the agent performing the step
1277  */
1278 static void
1279 agent_step (struct RIL_Peer_Agent *agent)
1280 {
1281   int a_next = RIL_ACTION_INVALID;
1282   int a_max;
1283   double *s_next;
1284   double reward;
1285
1286   LOG(GNUNET_ERROR_TYPE_DEBUG, "    agent_step() Peer '%s', algorithm %s\n",
1287       GNUNET_i2s (&agent->peer),
1288       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1289
1290   s_next = envi_get_state (agent->envi, agent);
1291   reward = envi_get_reward (agent->envi, agent);
1292
1293   switch (agent->envi->parameters.algorithm)
1294   {
1295   case RIL_ALGO_SARSA:
1296     a_next = agent_select_action (agent, s_next);
1297     if (RIL_ACTION_INVALID != agent->a_old)
1298     {
1299       //updates weights with selected action (on-policy), if not first step
1300       agent_update_weights (agent, reward, s_next, a_next);
1301     }
1302     agent_modify_eligibility (agent, RIL_E_DISCOUNT, s_next, a_next);
1303     break;
1304
1305   case RIL_ALGO_Q:
1306     a_max = agent_get_action_max (agent, s_next);
1307     if (RIL_ACTION_INVALID != agent->a_old)
1308     {
1309       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1310       agent_update_weights (agent, reward, s_next, a_max);
1311     }
1312     a_next = agent_select_action (agent, s_next);
1313     break;
1314   }
1315
1316   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1317
1318   agent_modify_eligibility (agent, agent->envi->parameters.eligibility_trace_mode, s_next, a_next);
1319
1320 //  GNUNET_log (GNUNET_ERROR_TYPE_INFO, "step()  Step# %llu  R: %f  IN %llu  OUT %llu  A: %d\n",
1321 //        agent->step_count,
1322 //        reward,
1323 //        agent->bw_in/1024,
1324 //        agent->bw_out/1024,
1325 //        a_next);
1326
1327   envi_do_action (agent->envi, agent, a_next);
1328
1329   GNUNET_free(agent->s_old);
1330   agent->s_old = s_next;
1331   agent->a_old = a_next;
1332
1333   agent->step_count += 1;
1334 }
1335
1336 static void
1337 ril_step (struct GAS_RIL_Handle *solver);
1338
1339 /**
1340  * Task for the scheduler, which performs one step and lets the solver know that
1341  * no further step is scheduled.
1342  *
1343  * @param cls the solver handle
1344  * @param tc the task context for the scheduler
1345  */
1346 static void
1347 ril_step_scheduler_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1348 {
1349   struct GAS_RIL_Handle *solver = cls;
1350
1351   solver->step_next_task_id = GNUNET_SCHEDULER_NO_TASK;
1352   ril_step (solver);
1353 }
1354
1355 static double
1356 ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
1357 {
1358   int i;
1359   struct RIL_Scope net;
1360   unsigned long long sum_assigned = 0;
1361   unsigned long long sum_available = 0;
1362   double ratio;
1363
1364   for (i = 0; i < solver->networks_count; i++)
1365   {
1366     net = solver->network_entries[i];
1367     if (net.bw_in_assigned > 0) //only consider scopes where an address is actually active
1368     {
1369       sum_assigned += net.bw_in_assigned;
1370       sum_assigned += net.bw_out_assigned;
1371       sum_available += net.bw_in_available;
1372       sum_available += net.bw_out_available;
1373     }
1374   }
1375   if (sum_available > 0)
1376   {
1377     ratio = ((double) sum_assigned) / ((double) sum_available);
1378   }
1379   else
1380   {
1381     ratio = 0;
1382   }
1383
1384   return ratio > 1 ? 1 : ratio; //overutilization possible, cap at 1
1385 }
1386
1387 /**
1388  * Lookup network struct by type
1389  *
1390  * @param s the solver handle
1391  * @param type the network type
1392  * @return the network struct
1393  */
1394 static struct RIL_Scope *
1395 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1396 {
1397   int i;
1398
1399   for (i = 0; i < s->networks_count; i++)
1400   {
1401     if (s->network_entries[i].type == type)
1402     {
1403       return &s->network_entries[i];
1404     }
1405   }
1406   return NULL ;
1407 }
1408
1409 static int
1410 ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1411 {
1412   struct RIL_Scope *net;
1413   struct RIL_Peer_Agent *agent;
1414   unsigned long long address_count = 0;
1415
1416   for (agent = solver->agents_head; NULL != agent; agent = agent->next)
1417   {
1418     if (agent->address_inuse && agent->is_active)
1419     {
1420       net = agent->address_inuse->solver_information;
1421       if (net->type == network)
1422       {
1423         address_count++;
1424       }
1425     }
1426   }
1427
1428   net = ril_get_network (solver, network);
1429   return (net->bw_in_available > MIN_BW * address_count) && (net->bw_out_available > MIN_BW * address_count);
1430 }
1431
1432 static void
1433 ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent)
1434 {
1435   struct RIL_Address_Wrapped *addr_wrap;
1436   struct RIL_Scope *net;
1437
1438   for (addr_wrap = agent->addresses_head; NULL != addr_wrap; addr_wrap = addr_wrap->next)
1439   {
1440     net = addr_wrap->address_naked->solver_information;
1441     if (ril_network_is_not_full(solver, net->type))
1442     {
1443       if (NULL == agent->address_inuse)
1444         envi_set_active_suggestion (solver, agent, addr_wrap->address_naked, MIN_BW, MIN_BW, silent);
1445       return;
1446     }
1447   }
1448   agent->address_inuse = NULL;
1449 }
1450
1451 static void
1452 ril_calculate_discount (struct GAS_RIL_Handle *solver)
1453 {
1454   struct GNUNET_TIME_Absolute time_now;
1455   struct GNUNET_TIME_Relative time_delta;
1456   double tau;
1457
1458   // MDP case - remove when debugged
1459   if (solver->simulate)
1460   {
1461     solver->global_discount_variable = solver->parameters.gamma;
1462     solver->global_discount_integrated = 1;
1463     return;
1464   }
1465
1466   // semi-MDP case
1467
1468   //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
1469   time_now = GNUNET_TIME_absolute_get ();
1470   time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now);
1471   solver->step_time_last = time_now;
1472   tau = (double) time_delta.rel_value_us
1473       / (double) solver->parameters.step_time_min.rel_value_us;
1474
1475   //calculate reward discounts (once per step for all agents)
1476   solver->global_discount_variable = pow (M_E, ((-1.0) * ((double) solver->parameters.beta) * tau));
1477   solver->global_discount_integrated = (1.0 - solver->global_discount_variable)
1478       / (double) solver->parameters.beta;
1479 }
1480
1481 static void
1482 ril_calculate_assigned_bwnet (struct GAS_RIL_Handle *solver)
1483 {
1484   int c;
1485   struct RIL_Scope *net;
1486
1487   for (c = 0; c < solver->networks_count; c++)
1488   {
1489     net = &solver->network_entries[c];
1490     net->bw_in_assigned = ril_network_get_assigned(solver, net->type, GNUNET_YES);
1491     net->bw_out_assigned = ril_network_get_assigned(solver, net->type, GNUNET_NO);
1492   }
1493 }
1494
1495 /**
1496  * Schedules the next global step in an adaptive way. The more resources are
1497  * left, the earlier the next step is scheduled. This serves the reactivity of
1498  * the solver to changed inputs.
1499  *
1500  * @param solver the solver handle
1501  */
1502 static void
1503 ril_step_schedule_next (struct GAS_RIL_Handle *solver)
1504 {
1505   double used_ratio;
1506   double factor;
1507   double y;
1508   double offset;
1509   struct GNUNET_TIME_Relative time_next;
1510
1511   used_ratio = ril_get_used_resource_ratio (solver);
1512
1513   GNUNET_assert(
1514       solver->parameters.step_time_min.rel_value_us
1515           <= solver->parameters.step_time_max.rel_value_us);
1516
1517   factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max,
1518       solver->parameters.step_time_min).rel_value_us;
1519   offset = (double) solver->parameters.step_time_min.rel_value_us;
1520   y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset;
1521
1522   GNUNET_assert(y <= (double ) solver->parameters.step_time_max.rel_value_us);
1523   GNUNET_assert(y >= (double ) solver->parameters.step_time_min.rel_value_us);
1524
1525   time_next = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned long long) y);
1526
1527   if (solver->simulate)
1528   {
1529     time_next = GNUNET_TIME_UNIT_ZERO;
1530   }
1531
1532   if ((GNUNET_SCHEDULER_NO_TASK == solver->step_next_task_id) && (GNUNET_NO == solver->done))
1533   {
1534     solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task,
1535           solver);
1536   }
1537 }
1538
1539 /**
1540  * Triggers one step per agent
1541  * @param solver
1542  */
1543 static void
1544 ril_step (struct GAS_RIL_Handle *solver)
1545 {
1546   struct RIL_Peer_Agent *cur;
1547
1548   if (GNUNET_YES == solver->bulk_lock)
1549   {
1550     solver->bulk_changes++;
1551     return;
1552   }
1553
1554   ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1555
1556   LOG(GNUNET_ERROR_TYPE_DEBUG, "    RIL step number %d\n", solver->step_count);
1557
1558   if (0 == solver->step_count)
1559   {
1560     solver->step_time_last = GNUNET_TIME_absolute_get ();
1561   }
1562
1563   ril_calculate_discount (solver);
1564   ril_calculate_assigned_bwnet (solver);
1565
1566   //calculate network state vector
1567 //  envi_state_networks(solver);
1568
1569   //trigger one step per active, unblocked agent
1570   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1571   {
1572     if (cur->is_active)
1573     {
1574       if (NULL == cur->address_inuse)
1575       {
1576         ril_try_unblock_agent(solver, cur, GNUNET_NO);
1577       }
1578       if (cur->address_inuse)
1579       {
1580         agent_step (cur);
1581       }
1582     }
1583   }
1584
1585   ril_calculate_assigned_bwnet (solver);
1586
1587   solver->step_count += 1;
1588   ril_step_schedule_next (solver);
1589
1590   ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1591
1592   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS);
1593   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1594   {
1595     if (cur->suggestion_issue) {
1596       solver->plugin_envi->bandwidth_changed_cb(solver->plugin_envi->bw_changed_cb_cls, cur->suggestion_address);
1597       cur->suggestion_issue = GNUNET_NO;
1598     }
1599   }
1600   ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS);
1601 }
1602
1603 static int
1604 ril_count_agents (struct GAS_RIL_Handle *solver)
1605 {
1606   int c = 0;
1607   struct RIL_Peer_Agent *cur_agent;
1608
1609   for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next)
1610   {
1611     c++;
1612   }
1613   return c;
1614 }
1615
1616 static void
1617 agent_w_start (struct RIL_Peer_Agent *agent)
1618 {
1619   int count;
1620   struct RIL_Peer_Agent *other;
1621   int i;
1622   int k;
1623
1624   count = ril_count_agents(agent->envi);
1625
1626   for (i = 0; i < agent->n; i++)
1627   {
1628     for (k = 0; k < agent->m; k++)
1629     {
1630       if (0 == count) {
1631         agent->W[i][k] = agent->envi->parameters.alpha * (1.0 - 2.0*((double) GNUNET_CRYPTO_random_u32(GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX)/(double)UINT32_MAX));
1632       }
1633       else {
1634         for (other = agent->envi->agents_head; NULL != other; other = other->next)
1635         {
1636           agent->W[i][k] += (other->W[i][k] / (double) count);
1637         }
1638       }
1639
1640       GNUNET_assert(!isinf(agent->W[i][k]));
1641     }
1642   }
1643 }
1644
1645 /**
1646  * Initialize an agent without addresses and its knowledge base
1647  *
1648  * @param s ril solver
1649  * @param peer the one in question
1650  * @return handle to the new agent
1651  */
1652 static struct RIL_Peer_Agent *
1653 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1654 {
1655   int i;
1656   struct GAS_RIL_Handle * solver = s;
1657   struct RIL_Peer_Agent * agent = GNUNET_new (struct RIL_Peer_Agent);
1658
1659   agent->envi = solver;
1660   agent->peer = *peer;
1661   agent->step_count = 0;
1662   agent->is_active = GNUNET_NO;
1663   agent->bw_in = MIN_BW;
1664   agent->bw_out = MIN_BW;
1665   agent->suggestion_issue = GNUNET_NO;
1666   agent->n = RIL_ACTION_TYPE_NUM;
1667   agent->m = 0;
1668   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1669   agent->E = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1670   for (i = 0; i < agent->n; i++)
1671   {
1672     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1673     agent->E[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1674   }
1675   agent_w_start(agent);
1676   agent->a_old = RIL_ACTION_INVALID;
1677   agent->s_old = GNUNET_malloc (sizeof (double) * agent->m);
1678   agent->address_inuse = NULL;
1679
1680   return agent;
1681 }
1682
1683 /**
1684  * Deallocate agent
1685  *
1686  * @param solver the solver handle
1687  * @param agent the agent to retire
1688  */
1689 static void
1690 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1691 {
1692   int i;
1693
1694   for (i = 0; i < agent->n; i++)
1695   {
1696     GNUNET_free_non_null(agent->W[i]);
1697     GNUNET_free_non_null(agent->E[i]);
1698   }
1699   GNUNET_free_non_null(agent->W);
1700   GNUNET_free_non_null(agent->E);
1701   GNUNET_free_non_null(agent->s_old);
1702   GNUNET_free(agent);
1703 }
1704
1705 /**
1706  * Returns the agent for a peer
1707  *
1708  * @param solver the solver handle
1709  * @param peer the identity of the peer
1710  * @param create whether or not to create an agent, if none is allocated yet
1711  * @return the agent
1712  */
1713 static struct RIL_Peer_Agent *
1714 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
1715 {
1716   struct RIL_Peer_Agent *cur;
1717
1718   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1719   {
1720     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
1721     {
1722       return cur;
1723     }
1724   }
1725
1726   if (create)
1727   {
1728     cur = agent_init (solver, peer);
1729     GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur);
1730     return cur;
1731   }
1732   return NULL ;
1733 }
1734
1735 /**
1736  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
1737  * considered inactive and not used. Addresses in an inactive network are ignored.
1738  *
1739  * @param solver solver handle
1740  * @param network the network type
1741  * @return whether or not the network is considered active
1742  */
1743 static int
1744 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1745 {
1746   struct RIL_Scope *net;
1747
1748   net = ril_get_network (solver, network);
1749   return net->bw_out_available >= MIN_BW;
1750 }
1751
1752 /**
1753  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
1754  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
1755  * frees the memory of the old vector, and redirects the pointer to the new one.
1756  *
1757  * @param old pointer to the pointer to the first element of the vector
1758  * @param element_size byte size of the vector elements
1759  * @param hole_start the first element to cut out
1760  * @param hole_length the number of elements to cut out
1761  * @param old_length the length of the old vector
1762  */
1763 static void
1764 ril_cut_from_vector (void **old,
1765     size_t element_size,
1766     unsigned int hole_start,
1767     unsigned int hole_length,
1768     unsigned int old_length)
1769 {
1770   char *tmpptr;
1771   char *oldptr = (char *) *old;
1772   size_t size;
1773   unsigned int bytes_before;
1774   unsigned int bytes_hole;
1775   unsigned int bytes_after;
1776
1777   GNUNET_assert(old_length >= hole_length);
1778   GNUNET_assert(old_length >= (hole_start + hole_length));
1779
1780   size = element_size * (old_length - hole_length);
1781
1782   bytes_before = element_size * hole_start;
1783   bytes_hole = element_size * hole_length;
1784   bytes_after = element_size * (old_length - hole_start - hole_length);
1785
1786   if (0 == size)
1787   {
1788     tmpptr = NULL;
1789   }
1790   else
1791   {
1792     tmpptr = GNUNET_malloc (size);
1793     memcpy (tmpptr, oldptr, bytes_before);
1794     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1795   }
1796   if (NULL != *old)
1797   {
1798     GNUNET_free(*old);
1799   }
1800   *old = (void *) tmpptr;
1801 }
1802
1803 /*
1804  *  Solver API functions
1805  *  ---------------------------
1806  */
1807
1808 /**
1809  * Change relative preference for quality in solver
1810  *
1811  * @param solver the solver handle
1812  * @param peer the peer to change the preference for
1813  * @param kind the kind to change the preference
1814  * @param pref_rel the normalized preference value for this kind over all clients
1815  */
1816 void
1817 GAS_ril_address_change_preference (void *solver,
1818     const struct GNUNET_PeerIdentity *peer,
1819     enum GNUNET_ATS_PreferenceKind kind,
1820     double pref_rel)
1821 {
1822   LOG(GNUNET_ERROR_TYPE_DEBUG,
1823       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1824       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1825
1826   ril_step (solver);
1827 }
1828
1829 /**
1830  * Entry point for the plugin
1831  *
1832  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
1833  */
1834 void *
1835 libgnunet_plugin_ats_ril_init (void *cls)
1836 {
1837   struct GNUNET_ATS_PluginEnvironment *env = cls;
1838   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1839   struct RIL_Scope * cur;
1840   int c;
1841   char *string;
1842
1843   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1844
1845   GNUNET_assert(NULL != env);
1846   GNUNET_assert(NULL != env->cfg);
1847   GNUNET_assert(NULL != env->stats);
1848   GNUNET_assert(NULL != env->bandwidth_changed_cb);
1849   GNUNET_assert(NULL != env->get_preferences);
1850   GNUNET_assert(NULL != env->get_property);
1851
1852   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(env->cfg, "ats", "RIL_RBF_DIVISOR", &solver->parameters.divisor))
1853   {
1854     solver->parameters.divisor = RIL_DEFAULT_RBF_DIVISOR;
1855   }
1856   if (GNUNET_OK
1857       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN",
1858           &solver->parameters.step_time_min))
1859   {
1860     solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
1861   }
1862   if (GNUNET_OK
1863       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX",
1864           &solver->parameters.step_time_max))
1865   {
1866     solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
1867   }
1868   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string))
1869   {
1870     solver->parameters.algorithm = !strcmp (string, "SARSA") ? RIL_ALGO_SARSA : RIL_ALGO_Q;
1871     GNUNET_free (string);
1872   }
1873   else
1874   {
1875     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1876   }
1877   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SELECT", &string))
1878   {
1879     solver->parameters.select = !strcmp (string, "EGREEDY") ? RIL_SELECT_EGREEDY : RIL_SELECT_SOFTMAX;
1880     GNUNET_free (string);
1881   }
1882   else
1883   {
1884     solver->parameters.select = RIL_DEFAULT_SELECT;
1885   }
1886   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_DISCOUNT_BETA", &string))
1887   {
1888     solver->parameters.beta = strtod (string, NULL);
1889     GNUNET_free (string);
1890     if (!(solver->parameters.beta > 0))
1891     {
1892       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_DISCOUNT_BETA not configured as positive number. Set to default value of %f instead.\n", RIL_DEFAULT_DISCOUNT_BETA);
1893       solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
1894     }
1895   }
1896   else
1897   {
1898     solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
1899   }
1900   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_DISCOUNT_GAMMA", &string))
1901   {
1902     solver->parameters.gamma = strtod (string, NULL);
1903     GNUNET_free (string);
1904     if (!(solver->parameters.gamma < 1) || (solver->parameters.gamma < 0))
1905     {
1906       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_DISCOUNT_GAMMA not configured in range [0,1[. Set to default value of %f instead.\n", RIL_DEFAULT_DISCOUNT_GAMMA);
1907       solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_GAMMA;
1908     }
1909   }
1910   else
1911   {
1912     solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_GAMMA;
1913   }
1914   if (GNUNET_OK
1915       == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &string))
1916   {
1917     solver->parameters.alpha = strtod (string, NULL);
1918     GNUNET_free (string);
1919     if (!(solver->parameters.alpha > 0) || solver->parameters.alpha > 1)
1920     {
1921       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_GRADIENT_STEP_SIZE not configured in range ]0,1]. Set to default value of %f instead.\n", RIL_DEFAULT_GRADIENT_STEP_SIZE);
1922       solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1923     }
1924   }
1925   else
1926   {
1927     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1928   }
1929   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_TRACE_DECAY", &string))
1930   {
1931     solver->parameters.lambda = strtod (string, NULL);
1932     GNUNET_free (string);
1933     if (solver->parameters.lambda < 0 || solver->parameters.lambda > 1)
1934     {
1935       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_TRACE_DECAY not configured in range [0,1]. Set to default value of %f instead.\n", RIL_DEFAULT_TRACE_DECAY);
1936       solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1937     }
1938   }
1939   else
1940   {
1941     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1942   }
1943   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_EXPLORE_RATIO", &string))
1944   {
1945     solver->parameters.explore_ratio = strtod (string, NULL);
1946     GNUNET_free (string);
1947     if (solver->parameters.explore_ratio < 0 || solver->parameters.explore_ratio > 1)
1948     {
1949       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_EXPLORE_RATIO not configured in range [0,1]. Set to default value of %f instead.\n", RIL_DEFAULT_EXPLORE_RATIO);
1950       solver->parameters.explore_ratio = RIL_DEFAULT_EXPLORE_RATIO;
1951     }
1952   }
1953   else
1954   {
1955     solver->parameters.explore_ratio = RIL_DEFAULT_EXPLORE_RATIO;
1956   }
1957   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_GLOBAL_REWARD_SHARE", &string))
1958   {
1959     solver->parameters.reward_global_share = strtod (string, NULL);
1960     GNUNET_free (string);
1961     if (solver->parameters.reward_global_share < 0 || solver->parameters.reward_global_share > 1)
1962     {
1963       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_GLOBAL_REWARD_SHARE not configured in range [0,1]. Set to default value of %f instead.\n", RIL_DEFAULT_GLOBAL_REWARD_SHARE);
1964       solver->parameters.reward_global_share = RIL_DEFAULT_GLOBAL_REWARD_SHARE;
1965     }
1966   }
1967   else
1968   {
1969     solver->parameters.reward_global_share = RIL_DEFAULT_GLOBAL_REWARD_SHARE;
1970   }
1971   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_TEMPERATURE", &string))
1972   {
1973     solver->parameters.temperature = strtod (string, NULL);
1974     GNUNET_free (string);
1975     if (solver->parameters.temperature <= 0)
1976     {
1977       LOG (GNUNET_ERROR_TYPE_WARNING, "RIL_TEMPERATURE not positive. Set to default value of %f instead.\n", RIL_DEFAULT_TEMPERATURE);
1978       solver->parameters.temperature = RIL_DEFAULT_TEMPERATURE;
1979     }
1980   }
1981   else
1982   {
1983     solver->parameters.temperature = RIL_DEFAULT_TEMPERATURE;
1984   }
1985   if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "ats", "RIL_SIMULATE", &solver->simulate))
1986   {
1987     solver->simulate = GNUNET_NO;
1988   }
1989   if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, "ats", "RIL_REPLACE_TRACES"))
1990   {
1991     solver->parameters.eligibility_trace_mode = RIL_E_REPLACE;
1992   }
1993   else
1994   {
1995     solver->parameters.eligibility_trace_mode = RIL_E_ACCUMULATE;
1996   }
1997
1998   env->sf.s_add = &GAS_ril_address_add;
1999   env->sf.s_address_update_property = &GAS_ril_address_property_changed;
2000   env->sf.s_address_update_session = &GAS_ril_address_session_changed;
2001   env->sf.s_address_update_inuse = &GAS_ril_address_inuse_changed;
2002   env->sf.s_address_update_network = &GAS_ril_address_change_network;
2003   env->sf.s_get = &GAS_ril_get_preferred_address;
2004   env->sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
2005   env->sf.s_pref = &GAS_ril_address_change_preference;
2006   env->sf.s_feedback = &GAS_ril_address_preference_feedback;
2007   env->sf.s_del = &GAS_ril_address_delete;
2008   env->sf.s_bulk_start = &GAS_ril_bulk_start;
2009   env->sf.s_bulk_stop = &GAS_ril_bulk_stop;
2010
2011   solver->plugin_envi = env;
2012   solver->networks_count = env->network_count;
2013   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Scope));
2014   solver->step_count = 0;
2015   solver->done = GNUNET_NO;
2016
2017   for (c = 0; c < env->network_count; c++)
2018   {
2019     cur = &solver->network_entries[c];
2020     cur->type = env->networks[c];
2021     cur->bw_in_available = env->in_quota[c];
2022     cur->bw_out_available = env->out_quota[c];
2023     LOG(GNUNET_ERROR_TYPE_INFO, "init()  Quotas for %s network:  IN %llu - OUT %llu\n", GNUNET_ATS_print_network_type(cur->type), cur->bw_in_available/1024, cur->bw_out_available/1024);
2024   }
2025
2026   LOG(GNUNET_ERROR_TYPE_INFO, "init()  Parameters:\n");
2027   LOG(GNUNET_ERROR_TYPE_INFO, "init()  Algorithm = %s, alpha = %f, beta = %f, lambda = %f\n",
2028       solver->parameters.algorithm ? "Q" : "SARSA",
2029       solver->parameters.alpha,
2030       solver->parameters.beta,
2031       solver->parameters.lambda);
2032   LOG(GNUNET_ERROR_TYPE_INFO, "init()  explore = %f, global_share = %f\n",
2033       solver->parameters.explore_ratio,
2034       solver->parameters.reward_global_share);
2035
2036   return solver;
2037 }
2038
2039 /**
2040  * Exit point for the plugin
2041  *
2042  * @param cls the solver handle
2043  */
2044 void *
2045 libgnunet_plugin_ats_ril_done (void *cls)
2046 {
2047   struct GAS_RIL_Handle *s = cls;
2048   struct RIL_Peer_Agent *cur_agent;
2049   struct RIL_Peer_Agent *next_agent;
2050
2051   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
2052
2053   s->done = GNUNET_YES;
2054
2055   cur_agent = s->agents_head;
2056   while (NULL != cur_agent)
2057   {
2058     next_agent = cur_agent->next;
2059     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
2060     agent_die (s, cur_agent);
2061     cur_agent = next_agent;
2062   }
2063
2064   if (GNUNET_SCHEDULER_NO_TASK != s->step_next_task_id)
2065   {
2066     GNUNET_SCHEDULER_cancel (s->step_next_task_id);
2067   }
2068   GNUNET_free(s->network_entries);
2069   GNUNET_free(s);
2070
2071   return NULL;
2072 }
2073
2074 /**
2075  * Add a new address for a peer to the solver
2076  *
2077  * The address is already contained in the addresses hashmap!
2078  *
2079  * @param solver the solver Handle
2080  * @param address the address to add
2081  * @param network network type of this address
2082  */
2083 void
2084 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
2085 {
2086   struct GAS_RIL_Handle *s = solver;
2087   struct RIL_Peer_Agent *agent;
2088   struct RIL_Address_Wrapped *address_wrapped;
2089   struct RIL_Scope *net;
2090   unsigned int m_new;
2091   unsigned int m_old;
2092   unsigned int n_new;
2093   unsigned int n_old;
2094   int i;
2095   unsigned int zero;
2096
2097   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_address_add()\n");
2098
2099   net = ril_get_network (s, network);
2100   address->solver_information = net;
2101
2102   if (!ril_network_is_active (s, network))
2103   {
2104     LOG(GNUNET_ERROR_TYPE_DEBUG,
2105         "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n",
2106         address->plugin, address->addr, GNUNET_i2s (&address->peer));
2107     return;
2108   }
2109
2110   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
2111
2112   //add address
2113   address_wrapped = GNUNET_new (struct RIL_Address_Wrapped);
2114   address_wrapped->address_naked = address;
2115   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
2116
2117   //increase size of W
2118   m_new = agent->m + ((s->parameters.divisor+1) * (s->parameters.divisor+1));
2119   m_old = agent->m;
2120   n_new = agent->n + 1;
2121   n_old = agent->n;
2122
2123   GNUNET_array_grow(agent->W, agent->n, n_new);
2124   agent->n = n_old;
2125   GNUNET_array_grow(agent->E, agent->n, n_new);
2126   for (i = 0; i < n_new; i++)
2127   {
2128     if (i < n_old)
2129     {
2130       agent->m = m_old;
2131       GNUNET_array_grow(agent->W[i], agent->m, m_new);
2132       agent->m = m_old;
2133       GNUNET_array_grow(agent->E[i], agent->m, m_new);
2134     }
2135     else
2136     {
2137       zero = 0;
2138       GNUNET_array_grow(agent->W[i], zero, m_new);
2139       zero = 0;
2140       GNUNET_array_grow(agent->E[i], zero, m_new);
2141     }
2142   }
2143
2144   //increase size of old state vector
2145   agent->m = m_old;
2146   GNUNET_array_grow(agent->s_old, agent->m, m_new);
2147
2148   ril_try_unblock_agent(s, agent, GNUNET_NO);
2149
2150   ril_step (s);
2151
2152   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n",
2153       address->active ? "active" : "inactive", address->plugin, address->addr,
2154       GNUNET_i2s (&address->peer));
2155 }
2156
2157 /**
2158  * Delete an address in the solver
2159  *
2160  * The address is not contained in the address hashmap anymore!
2161  *
2162  * @param solver the solver handle
2163  * @param address the address to remove
2164  * @param session_only delete only session not whole address
2165  */
2166 void
2167 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
2168 {
2169   struct GAS_RIL_Handle *s = solver;
2170   struct RIL_Peer_Agent *agent;
2171   struct RIL_Address_Wrapped *address_wrapped;
2172   int address_was_used = address->active;
2173   int address_index;
2174   unsigned int m_new;
2175   unsigned int n_new;
2176   int i;
2177   struct RIL_Scope *net;
2178
2179   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %s for peer '%s'\n",
2180       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
2181       address->addr, GNUNET_i2s (&address->peer));
2182
2183   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
2184   if (NULL == agent)
2185   {
2186     net = address->solver_information;
2187     GNUNET_assert(!ril_network_is_active (s, net->type));
2188     LOG(GNUNET_ERROR_TYPE_DEBUG,
2189         "No agent allocated for peer yet, since address was in inactive network\n");
2190     return;
2191   }
2192
2193   address_index = agent_address_get_index (agent, address);
2194   address_wrapped = agent_address_get (agent, address);
2195
2196   if (NULL == address_wrapped)
2197   {
2198     net = address->solver_information;
2199     GNUNET_assert(!ril_network_is_active (s, net->type));
2200     LOG(GNUNET_ERROR_TYPE_DEBUG,
2201         "Address not considered by agent, address was in inactive network\n");
2202     return;
2203   }
2204
2205   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
2206   GNUNET_free(address_wrapped);
2207
2208   //decrease W
2209   m_new = agent->m - ((s->parameters.divisor+1) * (s->parameters.divisor+1));
2210   n_new = agent->n - 1;
2211
2212   for (i = 0; i < agent->n; i++)
2213   {
2214     LOG(GNUNET_ERROR_TYPE_DEBUG, "first\n");
2215     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
2216         address_index * ((s->parameters.divisor+1) * (s->parameters.divisor+1)),
2217         ((s->parameters.divisor+1) * (s->parameters.divisor+1)), agent->m);
2218     LOG(GNUNET_ERROR_TYPE_DEBUG, "sec\n");
2219     ril_cut_from_vector ((void **) &agent->E[i], sizeof(double),
2220         address_index * ((s->parameters.divisor+1) * (s->parameters.divisor+1)),
2221         ((s->parameters.divisor+1) * (s->parameters.divisor+1)), agent->m);
2222   }
2223   GNUNET_free_non_null(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
2224   GNUNET_free_non_null(agent->E[RIL_ACTION_TYPE_NUM + address_index]);
2225   LOG(GNUNET_ERROR_TYPE_DEBUG, "third\n");
2226   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
2227       1, agent->n);
2228   LOG(GNUNET_ERROR_TYPE_DEBUG, "fourth\n");
2229   ril_cut_from_vector ((void **) &agent->E, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
2230       1, agent->n);
2231   //correct last action
2232   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
2233   {
2234     agent->a_old -= 1;
2235   }
2236   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
2237   {
2238     agent->a_old = RIL_ACTION_INVALID;
2239   }
2240   //decrease old state vector
2241   LOG(GNUNET_ERROR_TYPE_DEBUG, "fifth\n");
2242   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
2243       address_index * ((s->parameters.divisor+1) * (s->parameters.divisor+1)),
2244       ((s->parameters.divisor+1) * (s->parameters.divisor+1)), agent->m);
2245   agent->m = m_new;
2246   agent->n = n_new;
2247
2248   if (address_was_used)
2249   {
2250     if (NULL != agent->addresses_head) //if peer has an address left, use it
2251     {
2252       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, MIN_BW, MIN_BW,
2253           GNUNET_NO);
2254     }
2255     else
2256     {
2257       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
2258     }
2259   }
2260
2261   ril_step (solver);
2262 }
2263
2264 /**
2265  * Update the properties of an address in the solver
2266  *
2267  * @param solver solver handle
2268  * @param address the address
2269  * @param type the ATSI type in HBO
2270  * @param abs_value the absolute value of the property
2271  * @param rel_value the normalized value
2272  */
2273 void
2274 GAS_ril_address_property_changed (void *solver,
2275     struct ATS_Address *address,
2276     uint32_t type,
2277     uint32_t abs_value,
2278     double rel_value)
2279 {
2280   LOG(GNUNET_ERROR_TYPE_DEBUG,
2281       "API_address_property_changed() Property '%s' for peer '%s' address %s changed "
2282           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
2283       address->addr, rel_value);
2284
2285   ril_step (solver);
2286 }
2287
2288 /**
2289  * Update the session of an address in the solver
2290  *
2291  * NOTE: values in addresses are already updated
2292  *
2293  * @param solver solver handle
2294  * @param address the address
2295  * @param cur_session the current session
2296  * @param new_session the new session
2297  */
2298 void
2299 GAS_ril_address_session_changed (void *solver,
2300     struct ATS_Address *address,
2301     uint32_t cur_session,
2302     uint32_t new_session)
2303 {
2304   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
2305 }
2306
2307 /**
2308  * Notify the solver that an address is (not) actively used by transport
2309  * to communicate with a remote peer
2310  *
2311  * NOTE: values in addresses are already updated
2312  *
2313  * @param solver solver handle
2314  * @param address the address
2315  * @param in_use usage state
2316  */
2317 void
2318 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
2319 {
2320   LOG(GNUNET_ERROR_TYPE_DEBUG,
2321       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
2322       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
2323 }
2324
2325 /**
2326  * Notify solver that the network an address is located in has changed
2327  *
2328  * NOTE: values in addresses are already updated
2329  *
2330  * @param solver solver handle
2331  * @param address the address
2332  * @param current_network the current network
2333  * @param new_network the new network
2334  */
2335 void
2336 GAS_ril_address_change_network (void *solver,
2337     struct ATS_Address *address,
2338     uint32_t current_network,
2339     uint32_t new_network)
2340 {
2341   struct GAS_RIL_Handle *s = solver;
2342   struct RIL_Peer_Agent *agent;
2343
2344   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
2345       "%s address of peer %s from '%s' to '%s'\n",
2346       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
2347       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
2348
2349   if (address->active && !ril_network_is_active (solver, new_network))
2350   {
2351     GAS_ril_address_delete (solver, address, GNUNET_NO);
2352     return;
2353   }
2354
2355   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
2356   if (NULL == agent)
2357   {
2358     GNUNET_assert(!ril_network_is_active (solver, current_network));
2359
2360     GAS_ril_address_add (s, address, new_network);
2361     return;
2362   }
2363
2364   address->solver_information = ril_get_network(solver, new_network);
2365 }
2366
2367 /**
2368  * Give feedback about the current assignment
2369  *
2370  * @param solver the solver handle
2371  * @param application the application
2372  * @param peer the peer to change the preference for
2373  * @param scope the time interval for this feedback: [now - scope .. now]
2374  * @param kind the kind to change the preference
2375  * @param score the score
2376  */
2377 void
2378 GAS_ril_address_preference_feedback (void *solver,
2379     void *application,
2380     const struct GNUNET_PeerIdentity *peer,
2381     const struct GNUNET_TIME_Relative scope,
2382     enum GNUNET_ATS_PreferenceKind kind,
2383     double score)
2384 {
2385   LOG(GNUNET_ERROR_TYPE_DEBUG,
2386       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
2387           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
2388       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
2389 }
2390
2391 /**
2392  * Start a bulk operation
2393  *
2394  * @param solver the solver
2395  */
2396 void
2397 GAS_ril_bulk_start (void *solver)
2398 {
2399   struct GAS_RIL_Handle *s = solver;
2400
2401   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start() lock: %d\n", s->bulk_lock+1);
2402
2403   s->bulk_lock++;
2404 }
2405
2406 /**
2407  * Bulk operation done
2408  *
2409  * @param solver the solver handle
2410  */
2411 void
2412 GAS_ril_bulk_stop (void *solver)
2413 {
2414   struct GAS_RIL_Handle *s = solver;
2415
2416   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop() lock: %d\n", s->bulk_lock-1);
2417
2418   if (s->bulk_lock < 1)
2419   {
2420     GNUNET_break(0);
2421     return;
2422   }
2423   s->bulk_lock--;
2424
2425   if (0 < s->bulk_changes)
2426   {
2427     ril_step (solver);
2428     s->bulk_changes = 0;
2429   }
2430 }
2431
2432 /**
2433  * Tell solver to notify ATS if the address to use changes for a specific
2434  * peer using the bandwidth changed callback
2435  *
2436  * The solver must only notify about changes for peers with pending address
2437  * requests!
2438  *
2439  * @param solver the solver handle
2440  * @param peer the identity of the peer
2441  */
2442 const struct ATS_Address *
2443 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2444 {
2445   /*
2446    * activate agent, return currently chosen address
2447    */
2448   struct GAS_RIL_Handle *s = solver;
2449   struct RIL_Peer_Agent *agent;
2450
2451   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n");
2452
2453   agent = ril_get_agent (s, peer, GNUNET_YES);
2454
2455   agent->is_active = GNUNET_YES;
2456   envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);
2457
2458   ril_try_unblock_agent(solver, agent, GNUNET_YES);
2459
2460   if (agent->address_inuse)
2461   {
2462     LOG(GNUNET_ERROR_TYPE_DEBUG,
2463         "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n",
2464         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
2465   }
2466   else
2467   {
2468     LOG(GNUNET_ERROR_TYPE_DEBUG,
2469         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
2470         GNUNET_i2s (peer));
2471   }
2472
2473   return agent->address_inuse;
2474 }
2475
2476 /**
2477  * Tell solver stop notifying ATS about changes for this peers
2478  *
2479  * The solver must only notify about changes for peers with pending address
2480  * requests!
2481  *
2482  * @param solver the solver handle
2483  * @param peer the peer
2484  */
2485 void
2486 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2487 {
2488   struct GAS_RIL_Handle *s = solver;
2489   struct RIL_Peer_Agent *agent;
2490
2491   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_stop_get_preferred_address()");
2492
2493   agent = ril_get_agent (s, peer, GNUNET_NO);
2494
2495   if (NULL == agent)
2496   {
2497     GNUNET_break(0);
2498     return;
2499   }
2500   if (GNUNET_NO == agent->is_active)
2501   {
2502     GNUNET_break(0);
2503     return;
2504   }
2505
2506   agent->is_active = GNUNET_NO;
2507
2508   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2509       GNUNET_YES);
2510
2511   ril_step (s);
2512
2513   LOG(GNUNET_ERROR_TYPE_DEBUG,
2514       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
2515       GNUNET_i2s (peer), agent->address_inuse->plugin);
2516 }
2517
2518 /* end of plugin_ats_ril.c */