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