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