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