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