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