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