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