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