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