added adaptive step-intervals
[oweals/gnunet.git] / src / ats / libgnunet_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/libgnunet_plugin_ats_ril.c
23  * @brief ATS reinforcement learning solver
24  * @author Fabian Oehlmann
25  * @author Matthias Wachs
26  */
27 #include "libgnunet_plugin_ats_ril.h"
28
29 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
30
31 #define RIL_ACTION_INVALID -1
32 #define RIL_FEATURES_ADDRESS_COUNT (3 + GNUNET_ATS_QualityPropertiesCount)
33 #define RIL_FEATURES_NETWORK_COUNT 4
34
35 #define RIL_DEFAULT_STEP_TIME_MIN GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 500)
36 #define RIL_DEFAULT_STEP_TIME_MAX GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 3000)
37 #define RIL_DEFAULT_ALGORITHM RIL_ALGO_Q
38 #define RIL_DEFAULT_DISCOUNT_BETA 0.7
39 #define RIL_DEFAULT_GRADIENT_STEP_SIZE 0.4
40 #define RIL_DEFAULT_TRACE_DECAY 0.6
41 #define RIL_EXPLORE_RATIO 0.1
42
43 /**
44  * ATS reinforcement learning solver
45  *
46  * General description
47  */
48
49 /**
50  * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
51  * changed for the currently chosen address. Not depicted in the enum are the actions of switching
52  * to a particular address. The action of switching to address with index i is depicted by the
53  * number (RIL_ACTION_TYPE_NUM + i).
54  */
55 enum RIL_Action_Type
56 {
57   RIL_ACTION_NOTHING = 0,
58   RIL_ACTION_BW_IN_DBL = 1,
59   RIL_ACTION_BW_IN_HLV = 2,
60   RIL_ACTION_BW_IN_INC = 3,
61   RIL_ACTION_BW_IN_DEC = 4,
62   RIL_ACTION_BW_OUT_DBL = 5,
63   RIL_ACTION_BW_OUT_HLV = 6,
64   RIL_ACTION_BW_OUT_INC = 7,
65   RIL_ACTION_BW_OUT_DEC = 8,
66   RIL_ACTION_TYPE_NUM = 9
67 };
68
69 enum RIL_Algorithm
70 {
71   RIL_ALGO_SARSA = 0,
72   RIL_ALGO_Q = 1
73 };
74
75 enum RIL_E_Modification
76 {
77   RIL_E_SET,
78   RIL_E_ZERO,
79   RIL_E_ACCUMULATE,
80   RIL_E_REPLACE
81 };
82
83 /**
84  * Global learning parameters
85  */
86 struct RIL_Learning_Parameters
87 {
88   /**
89    * The TD-algorithm to use
90    */
91   enum RIL_Algorithm algorithm;
92
93   /**
94    * Learning discount factor in the TD-update
95    */
96   float beta;
97
98   /**
99    * Gradient-descent step-size
100    */
101   float alpha;
102
103   /**
104    * Trace-decay factor for eligibility traces
105    */
106   float lambda;
107
108   /**
109    * Minimal interval time between steps in milliseconds
110    */
111   struct GNUNET_TIME_Relative step_time_min;
112
113   /**
114    * Maximum interval time between steps in milliseconds
115    */
116   struct GNUNET_TIME_Relative step_time_max;
117 };
118
119 /**
120  * Wrapper for addresses to store them in agent's linked list
121  */
122 struct RIL_Address_Wrapped
123 {
124   /**
125    * Next in DLL
126    */
127   struct RIL_Address_Wrapped *next;
128
129   /**
130    * Previous in DLL
131    */
132   struct RIL_Address_Wrapped *prev;
133
134   /**
135    * The address
136    */
137   struct ATS_Address *address_naked;
138 };
139
140 struct RIL_Peer_Agent
141 {
142   /**
143    * Next agent in solver's linked list
144    */
145   struct RIL_Peer_Agent *next;
146
147   /**
148    * Previous agent in solver's linked list
149    */
150   struct RIL_Peer_Agent *prev;
151
152   /**
153    * Environment handle
154    */
155   struct GAS_RIL_Handle *envi;
156
157   /**
158    * Peer ID
159    */
160   struct GNUNET_PeerIdentity peer;
161
162   /**
163    * Whether the agent is active or not
164    */
165   int is_active;
166
167   /**
168    * Number of performed time-steps
169    */
170   unsigned long long step_count;
171
172   /**
173    * Experience matrix W
174    */
175   double ** W;
176
177   /**
178    * Number of rows of W / Number of state-vector features
179    */
180   unsigned int m;
181
182   /**
183    * Number of columns of W / Number of actions
184    */
185   unsigned int n;
186
187   /**
188    * Last perceived state feature vector
189    */
190   double * s_old;
191
192   /**
193    * Last chosen action
194    */
195   int a_old;
196
197   /**
198    * Eligibility trace vector
199    */
200   double * e;
201
202   /**
203    * Address in use
204    */
205   struct ATS_Address * address_inuse;
206
207   /**
208    * Head of addresses DLL
209    */
210   struct RIL_Address_Wrapped * addresses_head;
211
212   /**
213    * Tail of addresses DLL
214    */
215   struct RIL_Address_Wrapped * addresses_tail;
216
217   /**
218    * Inbound bandwidth assigned by the agent
219    */
220   unsigned long long bw_in;
221
222   /**
223    * Outbound bandwidth assigned by the agent
224    */
225   unsigned long long bw_out;
226 };
227
228 struct RIL_Network
229 {
230   /**
231    * ATS network type
232    */
233   enum GNUNET_ATS_Network_Type type;
234
235   /**
236    * Total available inbound bandwidth
237    */
238   unsigned long long bw_in_available;
239
240   /**
241    * Total assigned outbound bandwidth
242    */
243   unsigned long long bw_in_assigned;
244
245   /**
246    * Total available outbound bandwidth
247    */
248   unsigned long long bw_out_available;
249
250   /**
251    * Total assigned outbound bandwidth
252    */
253   unsigned long long bw_out_assigned;
254 };
255
256 /**
257  * A handle for the reinforcement learning solver
258  */
259 struct GAS_RIL_Handle
260 {
261   /**
262    * The solver-plugin environment of the solver-plugin API
263    */
264   struct GNUNET_ATS_PluginEnvironment *plugin_envi;
265
266   /**
267    * Statistics handle
268    */
269   struct GNUNET_STATISTICS_Handle *stats;
270
271   /**
272    * Number of performed steps
273    */
274   unsigned long long step_count;
275
276   /**
277    * Timestamp for the last time-step
278    */
279   struct GNUNET_TIME_Absolute step_time_last;
280
281   /**
282    * Task identifier of the next time-step to be executed
283    */
284   GNUNET_SCHEDULER_TaskIdentifier step_next_task_id;
285
286   /**
287    * Whether a step is already scheduled
288    */
289   int task_pending;
290
291   /**
292    * Variable discount factor, dependent on time between steps
293    */
294   double discount_variable;
295
296   /**
297    * Integrated variable discount factor, dependent on time between steps
298    */
299   double discount_integrated;
300
301   /**
302    * Lock for bulk operations
303    */
304   int bulk_lock;
305
306   /**
307    * Number of changes during a lock
308    */
309   int bulk_changes;
310
311   /**
312    * Learning parameters
313    */
314   struct RIL_Learning_Parameters parameters;
315
316   /**
317    * Array of networks with global assignment state
318    */
319   struct RIL_Network * network_entries;
320
321   /**
322    * Networks count
323    */
324   unsigned int networks_count;
325
326   /**
327    * List of active peer-agents
328    */
329   struct RIL_Peer_Agent * agents_head;
330   struct RIL_Peer_Agent * agents_tail;
331 };
332
333 /*
334  *  Private functions
335  *  ---------------------------
336  */
337
338 /**
339  * Estimate the current action-value for state s and action a
340  *
341  * @param agent agent performing the estimation
342  * @param state s
343  * @param action a
344  * @return estimation value
345  */
346 static double
347 agent_estimate_q (struct RIL_Peer_Agent *agent, double *state, int action)
348 {
349   int i;
350   double result = 0;
351
352   for (i = 0; i < agent->m; i++)
353   {
354     result += state[i] * agent->W[action][i];
355   }
356
357   return result;
358 }
359
360 /**
361  * Decide whether to do exploration (i.e. taking a new action) or exploitation (i.e. taking the
362  * currently estimated best action) in the current step
363  *
364  * @param agent agent performing the step
365  * @return yes, if exploring
366  */
367 static int
368 agent_decide_exploration (struct RIL_Peer_Agent *agent)
369 {
370   //TODO? Future Work: Improve exploration/exploitation trade-off by different mechanisms than e-greedy
371   /*
372    * An e-greedy replacement could be based on the accuracy of the prediction of the Q-value
373    */
374   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
375       UINT32_MAX) / (double) UINT32_MAX;
376
377 if  (r < RIL_EXPLORE_RATIO)
378   {
379     return GNUNET_YES;
380   }
381   return GNUNET_NO;
382 }
383
384   /**
385    * Get the index of the address in the agent's list.
386    *
387    * @param agent agent handle
388    * @param address address handle
389    * @return the index, starting with zero
390    */
391 static int
392 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
393 {
394   int i;
395   struct RIL_Address_Wrapped *cur;
396
397   i = -1;
398   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
399   {
400     i++;
401     if (cur->address_naked == address)
402     {
403       return i;
404     }
405   }
406
407   return i;
408 }
409
410 /**
411  * Gets the wrapped address from the agent's list
412  *
413  * @param agent agent handle
414  * @param address address handle
415  * @return wrapped address
416  */
417 static struct RIL_Address_Wrapped *
418 agent_address_get (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
419 {
420   struct RIL_Address_Wrapped *cur;
421
422   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
423   {
424     if (cur->address_naked == address)
425     {
426       return cur;
427     }
428   }
429
430   return NULL ;
431 }
432
433 /**
434  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
435  * most reward in the future)
436  *
437  * @param agent agent performing the calculation
438  * @param state the state from which to take the action
439  * @return the action promising most future reward
440  */
441 static int
442 agent_get_action_best (struct RIL_Peer_Agent *agent, double *state)
443 {
444   int i;
445   int max_i = RIL_ACTION_INVALID;
446   double cur_q;
447   double max_q = -DBL_MAX;
448
449   for (i = 0; i < agent->n; i++)
450   {
451     cur_q = agent_estimate_q (agent, state, i);
452     if (cur_q > max_q)
453     {
454       max_q = cur_q;
455       max_i = i;
456     }
457   }
458
459   GNUNET_assert(RIL_ACTION_INVALID != max_i);
460
461   return max_i;
462 }
463
464 /**
465  * Gets any action, to explore the action space from that state
466  *
467  * @param agent agent performing the calculation
468  * @param state the state from which to take the action
469  * @return any action
470  */
471 static int
472 agent_get_action_explore (struct RIL_Peer_Agent *agent, double *state)
473 {
474   // TODO?: Future Work: Choose the action for exploration, which has been explored the least in this state
475   return GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, agent->n);
476 }
477
478 /**
479  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
480  *
481  * @param agent the agent performing the update
482  * @param reward the reward received for the last action
483  * @param s_next the new state, the last step got the agent into
484  * @param a_prime the new
485  */
486 static void
487 agent_update_weights (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
488 {
489   int i;
490   double delta;
491   double *theta = agent->W[agent->a_old];
492
493   delta = agent->envi->discount_integrated * reward; //reward
494   delta += agent->envi->discount_variable * agent_estimate_q (agent, s_next, a_prime); //discounted future value
495   delta -= agent_estimate_q (agent, agent->s_old, agent->a_old); //one step
496   for (i = 0; i < agent->m; i++)
497   {
498     theta[i] += agent->envi->parameters.alpha * delta * agent->e[i];
499   }
500 }
501
502 /**
503  * Changes the eligibility trace vector e in various manners:
504  * RIL_E_ACCUMULATE - adds 1 to each component as in accumulating eligibility traces
505  * RIL_E_REPLACE - resets each component to 1 as in replacing traces
506  * RIL_E_SET - multiplies e with discount factor and lambda as in the update rule
507  * RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
508  *
509  * @param agent the agent handle
510  * @param mod the kind of modification
511  */
512 static void
513 agent_modify_eligibility (struct RIL_Peer_Agent *agent, enum RIL_E_Modification mod)
514 {
515   int i;
516   double *e = agent->e;
517
518   for (i = 0; i < agent->m; i++)
519   {
520     switch (mod)
521     {
522     case RIL_E_ACCUMULATE:
523       e[i] += 1;
524       break;
525     case RIL_E_REPLACE:
526       e[i] = 1;
527       break;
528     case RIL_E_SET:
529       e[i] = agent->envi->discount_variable * agent->envi->parameters.lambda;
530       break;
531     case RIL_E_ZERO:
532       e[i] = 0;
533       break;
534     }
535   }
536 }
537
538 static void ril_inform (struct GAS_RIL_Handle *solver,
539     enum GAS_Solver_Operation op, enum GAS_Solver_Status stat)
540 {
541   if (NULL != solver->plugin_envi->info_cb)
542     solver->plugin_envi->info_cb (solver->plugin_envi->info_cb_cls, op, stat, GAS_INFO_NONE);
543 }
544
545 /**
546  * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
547  * notify ATS of its new decision
548  *
549  * @param solver solver handle
550  * @param agent agent handle
551  * @param new_address the address which is to be used
552  * @param new_bw_in the new amount of inbound bandwidth set for this address
553  * @param new_bw_out the new amount of outbound bandwidth set for this address
554  * @param silent disables invocation of the bw_changed callback, if GNUNET_YES
555  */
556 static void
557 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
558     struct RIL_Peer_Agent *agent,
559     struct ATS_Address *new_address,
560     unsigned long long new_bw_in,
561     unsigned long long new_bw_out,
562     int silent)
563 {
564   int notify = GNUNET_NO;
565
566   LOG(GNUNET_ERROR_TYPE_DEBUG, "set_active_suggestion()\n");
567
568   //address change
569   if (agent->address_inuse != new_address)
570   {
571     if (NULL != agent->address_inuse)
572     {
573       agent->address_inuse->active = GNUNET_NO;
574       agent->address_inuse->assigned_bw_in.value__ = htonl (0);
575       agent->address_inuse->assigned_bw_out.value__ = htonl (0);
576     }
577     if (NULL != new_address)
578     {
579       LOG(GNUNET_ERROR_TYPE_DEBUG, "set address active: %s\n", agent->is_active ? "yes" : "no");
580       new_address->active = agent->is_active;
581       new_address->assigned_bw_in.value__ = htonl (agent->bw_in);
582       new_address->assigned_bw_out.value__ = htonl (agent->bw_out);
583     }
584     notify |= GNUNET_YES;
585   }
586
587   if (new_address)
588   {
589     //activity change
590     if (new_address->active != agent->is_active)
591     {
592       new_address->active = agent->is_active;
593     }
594
595     //bw change
596     if (agent->bw_in != new_bw_in)
597     {
598       agent->bw_in = new_bw_in;
599       new_address->assigned_bw_in.value__ = htonl (new_bw_out);
600       notify |= GNUNET_YES;
601     }
602     if (agent->bw_out != new_bw_out)
603     {
604       agent->bw_out = new_bw_out;
605       new_address->assigned_bw_out.value__ = htonl (new_bw_out);
606       notify |= GNUNET_YES;
607     }
608   }
609
610   if (notify && agent->is_active && (GNUNET_NO == silent))
611   {
612     if (new_address)
613     {
614       solver->plugin_envi->bandwidth_changed_cb (solver->plugin_envi->bw_changed_cb_cls,
615           new_address);
616     }
617     else if (agent->address_inuse)
618     {
619       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_in.value__));
620       GNUNET_assert(0 == ntohl (agent->address_inuse->assigned_bw_out.value__));
621       agent->bw_in = 0;
622       agent->bw_out = 0;
623       //disconnect
624       solver->plugin_envi->bandwidth_changed_cb (solver->plugin_envi->bw_changed_cb_cls,
625           agent->address_inuse);
626     }
627   }
628   agent->address_inuse = new_address;
629 }
630
631 /**
632  * Allocates a state vector and fills it with the features present
633  * @param solver the solver handle
634  * @param agent the agent handle
635  * @return pointer to the state vector
636  */
637 static double *
638 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
639 {
640   int i;
641   int k;
642   struct RIL_Network *net;
643   double *state = GNUNET_malloc (sizeof (double) * agent->m);
644   struct RIL_Address_Wrapped *cur_address;
645   const double *properties;
646
647   for (i = 0; i < solver->networks_count; i++)
648   {
649     net = &solver->network_entries[i];
650     state[i * RIL_FEATURES_NETWORK_COUNT + 0] = (double) net->bw_in_assigned;
651     state[i * RIL_FEATURES_NETWORK_COUNT + 1] = (double) net->bw_in_available;
652     state[i * RIL_FEATURES_NETWORK_COUNT + 2] = (double) net->bw_out_assigned;
653     state[i * RIL_FEATURES_NETWORK_COUNT + 3] = (double) net->bw_out_available;
654   }
655
656   i = i * RIL_FEATURES_NETWORK_COUNT; //first address feature
657
658   for (cur_address = agent->addresses_head; NULL != cur_address; cur_address = cur_address->next)
659   {
660     state[i++] = cur_address->address_naked->active;
661     state[i++] = cur_address->address_naked->active ? agent->bw_in : 0;
662     state[i++] = cur_address->address_naked->active ? agent->bw_out : 0;
663     properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
664         cur_address->address_naked);
665     for (k = 0; k < GNUNET_ATS_QualityPropertiesCount; k++)
666     {
667       state[i++] = properties[k];
668     }
669   }
670
671   return state;
672 }
673
674 /**
675  * For all networks a peer has an address in, this gets the maximum bandwidth which could
676  * theoretically be available in one of the networks. This is used for bandwidth normalization.
677  *
678  * @param agent the agent handle
679  * @param direction_in whether the inbound bandwidth should be considered. Returns the maximum outbound bandwidth if GNUNET_NO
680  */
681 static long long unsigned
682 ril_get_max_bw (struct RIL_Peer_Agent *agent, int direction_in)
683 {
684   /*
685    * get the maximum bandwidth possible for a peer, e.g. among all addresses which addresses'
686    * network could provide the maximum bandwidth if all that bandwidth was used on that one peer.
687    */
688   int max = 0;
689   struct RIL_Address_Wrapped *cur;
690   struct RIL_Network *net;
691
692   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
693   {
694     net = cur->address_naked->solver_information;
695     if (direction_in)
696     {
697       if (net->bw_in_available > max)
698       {
699         max = net->bw_in_available;
700       }
701     }
702     else
703     {
704       if (net->bw_out_available > max)
705       {
706         max = net->bw_out_available;
707       }
708     }
709   }
710   return max;
711 }
712
713 /**
714  * Get the index of the quality-property in question
715  *
716  * @param type the quality property type
717  * @return the index
718  */
719 static int
720 ril_find_property_index (uint32_t type)
721 {
722   int existing_types[] = GNUNET_ATS_QualityProperties;
723   int c;
724   for (c = 0; c < GNUNET_ATS_QualityPropertiesCount; c++)
725     if (existing_types[c] == type)
726       return c;
727   return GNUNET_SYSERR;
728 }
729
730 static double
731 envi_reward_global (struct GAS_RIL_Handle *solver)
732 {
733   int i;
734   unsigned int in_available = 0;
735   unsigned int out_available = 0;
736   unsigned int in_assigned = 0;
737   unsigned int out_assigned = 0;
738   double ratio_in;
739   double ratio_out;
740
741   for (i = 0; i < solver->networks_count; i++)
742   {
743     in_available += solver->network_entries[i].bw_in_available;
744     in_assigned += solver->network_entries[i].bw_in_assigned;
745     out_available += solver->network_entries[i].bw_out_available;
746     out_assigned += solver->network_entries[i].bw_out_assigned;
747   }
748
749   ratio_in = ((double) in_assigned) / ((double) in_available);
750   ratio_out = ((double) out_assigned) / ((double) out_available);
751
752   return ((ratio_in + ratio_out) * 0.5) + 1;
753 }
754
755 static double
756 envi_reward_local (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
757 {
758   //TODO! add utilization
759
760   const double *preferences;
761   const double *properties;
762   int prop_index;
763   double pref_match = 0;
764   double bw_norm;
765
766   preferences = solver->plugin_envi->get_preferences (solver->plugin_envi->get_preference_cls,
767       &agent->peer);
768   properties = solver->plugin_envi->get_property (solver->plugin_envi->get_property_cls,
769       agent->address_inuse);
770
771   //preference matching from latency and bandwidth
772   prop_index = ril_find_property_index (GNUNET_ATS_QUALITY_NET_DELAY);
773   pref_match += 1 - (preferences[GNUNET_ATS_PREFERENCE_LATENCY] * (3 - properties[prop_index])); //invert property as we want to maximize for lower latencies
774   bw_norm = GNUNET_MAX(2, (((
775                     ((double) agent->bw_in / (double) ril_get_max_bw(agent, GNUNET_YES)) +
776                     ((double) agent->bw_out / (double) ril_get_max_bw(agent, GNUNET_NO))
777                 ) / 2
778             ) + 1));
779
780   pref_match += 1 - (preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] * bw_norm);
781
782   return pref_match * 0.5;
783 }
784
785 /**
786  * Gets the reward for the last performed step, which is calculated in equal
787  * parts from the local (the peer specific) and the global (for all peers
788  * identical) reward.
789  *
790  * @param solver the solver handle
791  * @param agent the agent handle
792  * @return the reward
793  */
794 static double
795 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
796 {
797   struct RIL_Network *net;
798   double reward = 0;
799
800   //punish overutilization
801   net = agent->address_inuse->solver_information;
802   if ((net->bw_in_assigned > net->bw_in_available) || (net->bw_out_assigned > net->bw_out_available))
803   {
804     return -1;
805   }
806
807   reward += envi_reward_global (solver);
808   reward += envi_reward_local (solver, agent);
809   return reward * 0.5;
810 }
811
812 /**
813  * Doubles the bandwidth for the active address
814  *
815  * @param solver solver handle
816  * @param agent agent handle
817  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
818  */
819 static void
820 envi_action_bw_double (struct GAS_RIL_Handle *solver,
821     struct RIL_Peer_Agent *agent,
822     int direction_in)
823 {
824   if (direction_in)
825   {
826     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in * 2,
827         agent->bw_out, GNUNET_NO);
828   }
829   else
830   {
831     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
832         agent->bw_out * 2, GNUNET_NO);
833   }
834 }
835
836 /**
837  * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
838  * the minimum bandwidth for a peer, in order to not invoke a disconnect.
839  *
840  * @param solver solver handle
841  * @param agent agent handle
842  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
843  * bandwidth
844  */
845 static void
846 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
847     struct RIL_Peer_Agent *agent,
848     int direction_in)
849 {
850   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
851   unsigned long long new_bw;
852
853   if (direction_in)
854   {
855     new_bw = agent->bw_in / 2;
856     if (new_bw < min_bw)
857       new_bw = min_bw;
858     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
859         GNUNET_NO);
860   }
861   else
862   {
863     new_bw = agent->bw_out / 2;
864     if (new_bw < min_bw)
865       new_bw = min_bw;
866     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
867         GNUNET_NO);
868   }
869 }
870
871 /**
872  * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
873  *
874  * @param solver solver handle
875  * @param agent agent handle
876  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
877  * bandwidth
878  */
879 static void
880 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
881 {
882   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
883
884   if (direction_in)
885   {
886     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in + (5 * min_bw),
887         agent->bw_out, GNUNET_NO);
888   }
889   else
890   {
891     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
892         agent->bw_out + (5 * min_bw), GNUNET_NO);
893   }
894 }
895
896 /**
897  * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
898  * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
899  *
900  * @param solver solver handle
901  * @param agent agent handle
902  * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
903  * bandwidth
904  */
905 static void
906 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
907 {
908   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
909   unsigned long long new_bw;
910
911   if (direction_in)
912   {
913     new_bw = agent->bw_in - (5 * min_bw);
914     if (new_bw < min_bw)
915       new_bw = min_bw;
916     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
917         GNUNET_NO);
918   }
919   else
920   {
921     new_bw = agent->bw_out - (5 * min_bw);
922     if (new_bw < min_bw)
923       new_bw = min_bw;
924     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
925         GNUNET_NO);
926   }
927 }
928
929 /**
930  * Switches to the address given by its index
931  *
932  * @param solver solver handle
933  * @param agent agent handle
934  * @param address_index index of the address as it is saved in the agent's list, starting with zero
935  */
936 static void
937 envi_action_address_switch (struct GAS_RIL_Handle *solver,
938     struct RIL_Peer_Agent *agent,
939     unsigned int address_index)
940 {
941   struct RIL_Address_Wrapped *cur;
942   int i = 0;
943
944   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
945   {
946     if (i == address_index)
947     {
948       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
949           GNUNET_NO);
950       return;
951     }
952
953     i++;
954   }
955
956   //no address with address_index exists, in this case this action should not be callable
957   GNUNET_assert(GNUNET_NO);
958 }
959
960 /**
961  * Puts the action into effect by calling the according function
962  *
963  * @param solver the solver handle
964  * @param agent the action handle
965  * @param action the action to perform by the solver
966  */
967 static void
968 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
969 {
970   int address_index;
971
972   switch (action)
973   {
974   case RIL_ACTION_NOTHING:
975     break;
976   case RIL_ACTION_BW_IN_DBL:
977     envi_action_bw_double (solver, agent, GNUNET_YES);
978     break;
979   case RIL_ACTION_BW_IN_HLV:
980     envi_action_bw_halven (solver, agent, GNUNET_YES);
981     break;
982   case RIL_ACTION_BW_IN_INC:
983     envi_action_bw_inc (solver, agent, GNUNET_YES);
984     break;
985   case RIL_ACTION_BW_IN_DEC:
986     envi_action_bw_dec (solver, agent, GNUNET_YES);
987     break;
988   case RIL_ACTION_BW_OUT_DBL:
989     envi_action_bw_double (solver, agent, GNUNET_NO);
990     break;
991   case RIL_ACTION_BW_OUT_HLV:
992     envi_action_bw_halven (solver, agent, GNUNET_NO);
993     break;
994   case RIL_ACTION_BW_OUT_INC:
995     envi_action_bw_inc (solver, agent, GNUNET_NO);
996     break;
997   case RIL_ACTION_BW_OUT_DEC:
998     envi_action_bw_dec (solver, agent, GNUNET_NO);
999     break;
1000   default:
1001     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
1002     {
1003       address_index = action - RIL_ACTION_TYPE_NUM;
1004
1005       GNUNET_assert(address_index >= 0);
1006       GNUNET_assert(
1007           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
1008
1009       envi_action_address_switch (solver, agent, address_index);
1010       break;
1011     }
1012     // error - action does not exist
1013     GNUNET_assert(GNUNET_NO);
1014   }
1015 }
1016
1017 /**
1018  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
1019  * after having done the last action a_old. It observes the new state s_next and the reward
1020  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
1021  * next action is put into effect.
1022  *
1023  * @param agent the agent performing the step
1024  */
1025 static void
1026 agent_step (struct RIL_Peer_Agent *agent)
1027 {
1028   int a_next = RIL_ACTION_INVALID;
1029   double *s_next;
1030   double reward;
1031
1032   s_next = envi_get_state (agent->envi, agent);
1033   reward = envi_get_reward (agent->envi, agent);
1034
1035   LOG(GNUNET_ERROR_TYPE_DEBUG, "agent_step() with algorithm %s\n",
1036       agent->envi->parameters.algorithm ? "Q" : "SARSA");
1037
1038   switch (agent->envi->parameters.algorithm)
1039   {
1040   case RIL_ALGO_SARSA:
1041     agent_modify_eligibility (agent, RIL_E_SET);
1042     if (agent_decide_exploration (agent))
1043     {
1044       a_next = agent_get_action_explore (agent, s_next);
1045     }
1046     else
1047     {
1048       a_next = agent_get_action_best (agent, s_next);
1049     }
1050     if (RIL_ACTION_INVALID != agent->a_old)
1051     {
1052       //updates weights with selected action (on-policy), if not first step
1053       agent_update_weights (agent, reward, s_next, a_next);
1054     }
1055     break;
1056
1057   case RIL_ALGO_Q:
1058     a_next = agent_get_action_best (agent, s_next);
1059     if (RIL_ACTION_INVALID != agent->a_old)
1060     {
1061       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
1062       agent_update_weights (agent, reward, s_next, a_next);
1063     }
1064     if (agent_decide_exploration (agent))
1065     {
1066       a_next = agent_get_action_explore (agent, s_next);
1067       agent_modify_eligibility (agent, RIL_E_ZERO);
1068     }
1069     else
1070     {
1071       a_next = agent_get_action_best (agent, s_next);
1072       agent_modify_eligibility (agent, RIL_E_SET);
1073     }
1074     break;
1075   }
1076
1077   GNUNET_assert(RIL_ACTION_INVALID != a_next);
1078
1079   agent_modify_eligibility (agent, RIL_E_ACCUMULATE);
1080
1081   envi_do_action (agent->envi, agent, a_next);
1082
1083   GNUNET_free(agent->s_old);
1084   agent->s_old = s_next;
1085   agent->a_old = a_next;
1086
1087   agent->step_count += 1;
1088 }
1089
1090 static int ril_step (struct GAS_RIL_Handle *solver);
1091
1092 /**
1093  * Task for the scheduler, which performs one step and lets the solver know that
1094  * no further step is scheduled.
1095  *
1096  * @param cls the solver handle
1097  * @param tc the task context for the scheduler
1098  */
1099 static void
1100 ril_step_scheduler_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
1101 {
1102   struct GAS_RIL_Handle *solver = cls;
1103
1104   solver->task_pending = GNUNET_NO;
1105   ril_step(solver);
1106 }
1107
1108 static double
1109 ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
1110 {
1111   int i;
1112   struct RIL_Network net;
1113   unsigned long long sum_assigned = 0;
1114   unsigned long long sum_available = 0;
1115   double ratio;
1116
1117   for (i = 0; i < solver->networks_count; i++)
1118   {
1119     net = solver->network_entries[i];
1120     if (net.bw_in_assigned > 0) //only consider scopes with an active address
1121     {
1122       sum_assigned += net.bw_in_assigned;
1123       sum_assigned += net.bw_out_assigned;
1124       sum_available += net.bw_in_available;
1125       sum_available += net.bw_out_available;
1126     }
1127   }
1128   if (sum_available > 0) {
1129     ratio = ((double) sum_assigned) / ((double) sum_available);
1130   }
1131   else
1132   {
1133     ratio = 0;
1134   }
1135
1136   return ratio > 1? 1 : ratio; //overutilization possible, cap at 1
1137 }
1138
1139 /**
1140  * Schedules the next global step in an adaptive way. The more resources are
1141  * left, the earlier the next step is scheduled. This serves the reactivity of
1142  * the solver to changed inputs.
1143  *
1144  * @param solver the solver handle
1145  */
1146 static void
1147 ril_step_schedule_next (struct GAS_RIL_Handle *solver)
1148 {
1149   double used_ratio;
1150   double factor;
1151   double y;
1152   double offset;
1153   struct GNUNET_TIME_Relative time_next;
1154
1155   if (solver->task_pending)
1156   {
1157     GNUNET_SCHEDULER_cancel(solver->step_next_task_id);
1158   }
1159
1160   used_ratio = ril_get_used_resource_ratio(solver);
1161
1162   GNUNET_assert(solver->parameters.step_time_min.rel_value_us < solver->parameters.step_time_max.rel_value_us);
1163
1164   factor = (double) GNUNET_TIME_relative_subtract(solver->parameters.step_time_max, solver->parameters.step_time_min).rel_value_us;
1165   offset = (double) solver->parameters.step_time_min.rel_value_us;
1166   y = factor * pow(used_ratio, 10) + offset;
1167
1168   //LOG (GNUNET_ERROR_TYPE_INFO, "used = %f, min = %f, max = %f\n", used_ratio, (double)solver->parameters.step_time_min.rel_value_us, (double)solver->parameters.step_time_max.rel_value_us);
1169   //LOG (GNUNET_ERROR_TYPE_INFO, "factor = %f, offset = %f, y = %f\n", factor, offset, y);
1170
1171   GNUNET_assert(y <= (double) solver->parameters.step_time_max.rel_value_us);
1172   GNUNET_assert(y >= (double) solver->parameters.step_time_min.rel_value_us);
1173
1174   time_next = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned int) y);
1175
1176   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed(time_next, &ril_step_scheduler_task, solver);
1177   solver->task_pending = GNUNET_YES;
1178 }
1179
1180 /**
1181  * Triggers one step per agent
1182  * @param solver
1183  */
1184 static int
1185 ril_step (struct GAS_RIL_Handle *solver)
1186 {
1187   struct RIL_Peer_Agent *cur;
1188   struct GNUNET_TIME_Absolute time_now;
1189   struct GNUNET_TIME_Relative time_delta;
1190   double tau;
1191
1192   if (GNUNET_YES == solver->bulk_lock)
1193   {
1194     solver->bulk_changes ++;
1195     return GNUNET_NO;
1196   }
1197
1198   ril_inform(solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);
1199
1200   LOG(GNUNET_ERROR_TYPE_DEBUG, "RIL step number %d\n", solver->step_count);
1201
1202   if (0 == solver->step_count) {
1203     solver->step_time_last = GNUNET_TIME_absolute_get ();
1204   }
1205
1206   //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
1207   time_now = GNUNET_TIME_absolute_get ();
1208   time_delta = GNUNET_TIME_absolute_get_difference(solver->step_time_last, time_now);
1209   tau = ((double) time_delta.rel_value_us) / ((double) solver->parameters.step_time_min.rel_value_us);
1210   solver->step_time_last = time_now;
1211
1212   //calculate reward discounts (once per step for all agents)
1213   solver->discount_variable = pow(M_E, ((-1.) * ((double) solver->parameters.beta) * tau));
1214   solver->discount_integrated = (1 - solver->discount_variable) / ((double) solver->parameters.beta);
1215
1216   //trigger one step per active agent
1217   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1218   {
1219     if (cur->is_active && cur->address_inuse)
1220     {
1221       agent_step (cur);
1222     }
1223   }
1224
1225   solver->step_count += 1;
1226   ril_step_schedule_next(solver);
1227
1228   ril_inform(solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);
1229
1230   return GNUNET_YES;
1231 }
1232
1233 /**
1234  * Initialize an agent without addresses and its knowledge base
1235  *
1236  * @param s ril solver
1237  * @param peer the one in question
1238  * @return handle to the new agent
1239  */
1240 static struct RIL_Peer_Agent *
1241 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
1242 {
1243   int i;
1244   struct GAS_RIL_Handle * solver = s;
1245   struct RIL_Peer_Agent * agent = GNUNET_malloc (sizeof (struct RIL_Peer_Agent));
1246
1247   agent->envi = solver;
1248   agent->peer = *peer;
1249   agent->step_count = 0;
1250   agent->is_active = GNUNET_NO;
1251   agent->n = RIL_ACTION_TYPE_NUM;
1252   agent->m = solver->networks_count * RIL_FEATURES_NETWORK_COUNT;
1253   agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
1254   for (i = 0; i < agent->n; i++)
1255   {
1256     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1257   }
1258   agent->a_old = RIL_ACTION_INVALID;
1259   agent->s_old = envi_get_state (solver, agent);
1260   agent->e = (double *) GNUNET_malloc (sizeof (double) * agent->m);
1261   agent_modify_eligibility (agent, RIL_E_ZERO);
1262
1263   GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, agent);
1264
1265   return agent;
1266 }
1267
1268 /**
1269  * Deallocate agent
1270  *
1271  * @param solver the solver handle
1272  * @param agent the agent to retire
1273  */
1274 static void
1275 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
1276 {
1277   int i;
1278
1279   for (i = 0; i < agent->n; i++)
1280   {
1281     GNUNET_free(agent->W[i]);
1282   }
1283   GNUNET_free(agent->W);
1284   GNUNET_free(agent->e);
1285   GNUNET_free(agent->s_old);
1286   GNUNET_free(agent);
1287 }
1288
1289 /**
1290  * Returns the agent for a peer
1291  *
1292  * @param solver the solver handle
1293  * @param peer the identity of the peer
1294  * @param create whether or not to create an agent, if none is allocated yet
1295  * @return the agent
1296  */
1297 static struct RIL_Peer_Agent *
1298 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
1299 {
1300   struct RIL_Peer_Agent *cur;
1301
1302   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
1303   {
1304     if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
1305     {
1306       return cur;
1307     }
1308   }
1309
1310   if (create)
1311   {
1312     return agent_init (solver, peer);
1313   }
1314   return NULL ;
1315 }
1316
1317 /**
1318  * Lookup network struct by type
1319  *
1320  * @param s the solver handle
1321  * @param type the network type
1322  * @return the network struct
1323  */
1324 static struct RIL_Network *
1325 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1326 {
1327   int i;
1328
1329   for (i = 0; i < s->networks_count; i++)
1330   {
1331     if (s->network_entries[i].type == type)
1332     {
1333       return &s->network_entries[i];
1334     }
1335   }
1336   return NULL ;
1337 }
1338
1339 /**
1340  * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
1341  * considered inactive and not used. Addresses in an inactive network are ignored.
1342  *
1343  * @param solver solver handle
1344  * @param network the network type
1345  * @return whether or not the network is considered active
1346  */
1347 static int
1348 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1349 {
1350   struct RIL_Network *net;
1351   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1352
1353   net = ril_get_network (solver, network);
1354   if (net->bw_out_available < min_bw)
1355     return GNUNET_NO;
1356   return GNUNET_YES;
1357 }
1358
1359 /**
1360  * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
1361  * the reward function approximation. It copies the memory, which is not cut, to the new vector,
1362  * frees the memory of the old vector, and redirects the pointer to the new one.
1363  *
1364  * @param old pointer to the pointer to the first element of the vector
1365  * @param element_size byte size of the vector elements
1366  * @param hole_start the first element to cut out
1367  * @param hole_length the number of elements to cut out
1368  * @param old_length the length of the old vector
1369  */
1370 static void
1371 ril_cut_from_vector (void **old,
1372     size_t element_size,
1373     unsigned int hole_start,
1374     unsigned int hole_length,
1375     unsigned int old_length)
1376 {
1377   char *tmpptr;
1378   char *oldptr = (char *) *old;
1379   size_t size;
1380   unsigned int bytes_before;
1381   unsigned int bytes_hole;
1382   unsigned int bytes_after;
1383
1384   GNUNET_assert(old_length > hole_length);
1385   GNUNET_assert(old_length >= (hole_start + hole_length));
1386
1387   size = element_size * (old_length - hole_length);
1388
1389   bytes_before = element_size * hole_start;
1390   bytes_hole = element_size * hole_length;
1391   bytes_after = element_size * (old_length - hole_start - hole_length);
1392
1393   if (0 == size)
1394   {
1395     tmpptr = NULL;
1396   }
1397   else
1398   {
1399     tmpptr = GNUNET_malloc (size);
1400     memcpy (tmpptr, oldptr, bytes_before);
1401     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1402   }
1403   if (NULL != *old)
1404   {
1405     GNUNET_free(*old);
1406   }
1407   *old = (void *) tmpptr;
1408 }
1409
1410 /*
1411  *  Solver API functions
1412  *  ---------------------------
1413  */
1414
1415 /**
1416  * Change relative preference for quality in solver
1417  *
1418  * @param solver the solver handle
1419  * @param peer the peer to change the preference for
1420  * @param kind the kind to change the preference
1421  * @param pref_rel the normalized preference value for this kind over all clients
1422  */
1423 void
1424 GAS_ril_address_change_preference (void *solver,
1425     const struct GNUNET_PeerIdentity *peer,
1426     enum GNUNET_ATS_PreferenceKind kind,
1427     double pref_rel)
1428 {
1429   LOG(GNUNET_ERROR_TYPE_DEBUG,
1430       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1431       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1432
1433   ril_step(solver);
1434 }
1435
1436 /**
1437  * Entry point for the plugin
1438  *
1439  * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
1440  */
1441 void *
1442 libgnunet_plugin_ats_ril_init (void *cls)
1443 {
1444   struct GNUNET_ATS_PluginEnvironment *env = cls;
1445   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1446   struct RIL_Network * cur;
1447   int c;
1448   unsigned long long tmp;
1449   char *string;
1450
1451   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1452
1453   GNUNET_assert(NULL != env);
1454   GNUNET_assert(NULL != env->cfg);
1455   GNUNET_assert(NULL != env->stats);
1456   GNUNET_assert(NULL != env->bandwidth_changed_cb);
1457   GNUNET_assert(NULL != env->get_preferences);
1458   GNUNET_assert(NULL != env->get_property);
1459
1460   if (GNUNET_OK
1461       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN", &solver->parameters.step_time_min))
1462   {
1463     solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
1464   }
1465   if (GNUNET_OK
1466       != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX", &solver->parameters.step_time_max))
1467   {
1468     solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
1469   }
1470   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string)
1471       && NULL != string && 0 == strcmp (string, "SARSA"))
1472   {
1473     solver->parameters.algorithm = RIL_ALGO_SARSA;
1474   }
1475   else
1476   {
1477     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1478   }
1479   if (GNUNET_OK
1480       == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_DISCOUNT_BETA", &tmp))
1481   {
1482     solver->parameters.beta = (double) tmp / 100;
1483   }
1484   else
1485   {
1486     solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
1487   }
1488   if (GNUNET_OK
1489       == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &tmp))
1490   {
1491     solver->parameters.alpha = (double) tmp / 100;
1492   }
1493   else
1494   {
1495     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1496   }
1497   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (env->cfg, "ats", "RIL_TRACE_DECAY", &tmp))
1498   {
1499     solver->parameters.lambda = (double) tmp / 100;
1500   }
1501   else
1502   {
1503     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1504   }
1505
1506   env->sf.s_add = &GAS_ril_address_add;
1507   env->sf.s_address_update_property = &GAS_ril_address_property_changed;
1508   env->sf.s_address_update_session = &GAS_ril_address_session_changed;
1509   env->sf.s_address_update_inuse = &GAS_ril_address_inuse_changed;
1510   env->sf.s_address_update_network = &GAS_ril_address_change_network;
1511   env->sf.s_get = &GAS_ril_get_preferred_address;
1512   env->sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
1513   env->sf.s_pref = &GAS_ril_address_change_preference;
1514   env->sf.s_feedback = &GAS_ril_address_preference_feedback;
1515   env->sf.s_del = &GAS_ril_address_delete;
1516   env->sf.s_bulk_start = &GAS_ril_bulk_start;
1517   env->sf.s_bulk_stop = &GAS_ril_bulk_stop;
1518
1519   solver->plugin_envi = env;
1520   solver->networks_count = env->network_count;
1521   solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Network));
1522   solver->step_count = 0;
1523
1524   for (c = 0; c < env->network_count; c++)
1525   {
1526     cur = &solver->network_entries[c];
1527     cur->type = env->networks[c];
1528     cur->bw_in_available = env->in_quota[c];
1529     cur->bw_in_assigned = 0;
1530     cur->bw_out_available = env->out_quota[c];
1531     cur->bw_out_assigned = 0;
1532   }
1533
1534   solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (
1535       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_millisecond_ (), 1000),
1536       &ril_step_scheduler_task, solver);
1537   solver->task_pending = GNUNET_YES;
1538
1539   return solver;
1540 }
1541
1542 /**
1543  * Exit point for the plugin
1544  *
1545  * @param cls the solver handle
1546  */
1547 void *
1548 libgnunet_plugin_ats_ril_done (void *cls)
1549 {
1550   struct GAS_RIL_Handle *s = cls;
1551   struct RIL_Peer_Agent *cur_agent;
1552   struct RIL_Peer_Agent *next_agent;
1553
1554   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
1555
1556   cur_agent = s->agents_head;
1557   while (NULL != cur_agent)
1558   {
1559     next_agent = cur_agent->next;
1560     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
1561     agent_die (s, cur_agent);
1562     cur_agent = next_agent;
1563   }
1564
1565   if (s->task_pending)
1566   {
1567     GNUNET_SCHEDULER_cancel (s->step_next_task_id);
1568   }
1569   GNUNET_free(s->network_entries);
1570   GNUNET_free(s);
1571
1572   return NULL ;
1573 }
1574
1575 /**
1576  * Add a new address for a peer to the solver
1577  *
1578  * The address is already contained in the addresses hashmap!
1579  *
1580  * @param solver the solver Handle
1581  * @param address the address to add
1582  * @param network network type of this address
1583  */
1584 void
1585 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
1586 {
1587   struct GAS_RIL_Handle *s = solver;
1588   struct RIL_Peer_Agent *agent;
1589   struct RIL_Address_Wrapped *address_wrapped;
1590   struct RIL_Network *net;
1591   unsigned int m_new;
1592   unsigned int m_old;
1593   unsigned int n_new;
1594   unsigned int n_old;
1595   int i;
1596   unsigned int zero;
1597   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1598
1599   net = ril_get_network (s, network);
1600   address->solver_information = net;
1601
1602   if (!ril_network_is_active (s, network))
1603   {
1604     LOG(GNUNET_ERROR_TYPE_DEBUG,
1605         "API_address_add() Did not add %s address %p for peer '%s', network does not have enough bandwidth\n",
1606         address->plugin, address->addr, GNUNET_i2s (&address->peer));
1607     return;
1608   }
1609
1610   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
1611
1612   //add address
1613   address_wrapped = GNUNET_malloc (sizeof (struct RIL_Address_Wrapped));
1614   address_wrapped->address_naked = address;
1615   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
1616
1617   //increase size of W
1618   m_new = agent->m + RIL_FEATURES_ADDRESS_COUNT;
1619   m_old = agent->m;
1620   n_new = agent->n + 1;
1621   n_old = agent->n;
1622
1623   GNUNET_array_grow(agent->W, agent->n, n_new);
1624   for (i = 0; i < n_new; i++)
1625   {
1626     if (i < n_old)
1627     {
1628       agent->m = m_old;
1629       GNUNET_array_grow(agent->W[i], agent->m, m_new);
1630     }
1631     else
1632     {
1633       zero = 0;
1634       GNUNET_array_grow(agent->W[i], zero, m_new);
1635     }
1636   }
1637
1638   //increase size of old state vector
1639   agent->m = m_old;
1640   GNUNET_array_grow(agent->s_old, agent->m, m_new);
1641
1642   agent->m = m_old;
1643   GNUNET_array_grow(agent->e, agent->m, m_new);
1644
1645   if (NULL == agent->address_inuse)
1646   {
1647     net->bw_in_assigned += min_bw;
1648     net->bw_out_assigned += min_bw;
1649     envi_set_active_suggestion (s, agent, address, min_bw, min_bw, GNUNET_NO);
1650   }
1651
1652   ril_step(s);
1653
1654   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %p for peer '%s'\n",
1655       address->active ? "active" : "inactive", address->plugin, address->addr,
1656       GNUNET_i2s (&address->peer));
1657 }
1658
1659 /**
1660  * Delete an address in the solver
1661  *
1662  * The address is not contained in the address hashmap anymore!
1663  *
1664  * @param solver the solver handle
1665  * @param address the address to remove
1666  * @param session_only delete only session not whole address
1667  */
1668 void
1669 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
1670 {
1671   struct GAS_RIL_Handle *s = solver;
1672   struct RIL_Peer_Agent *agent;
1673   struct RIL_Address_Wrapped *address_wrapped;
1674   int address_was_used = address->active;
1675   int address_index;
1676   unsigned int m_new;
1677   unsigned int n_new;
1678   int i;
1679   struct RIL_Network *net;
1680   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1681
1682   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %p for peer '%s'\n",
1683       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
1684       address->addr, GNUNET_i2s (&address->peer));
1685
1686   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1687   if (NULL == agent)
1688   {
1689     net = address->solver_information;
1690     GNUNET_assert(!ril_network_is_active (s, net->type));
1691     LOG(GNUNET_ERROR_TYPE_DEBUG,
1692         "No agent allocated for peer yet, since address was in inactive network\n");
1693     return;
1694   }
1695
1696   address_index = agent_address_get_index (agent, address);
1697   address_wrapped = agent_address_get (agent, address);
1698
1699   if (NULL == address_wrapped)
1700   {
1701     net = address->solver_information;
1702     GNUNET_assert(!ril_network_is_active (s, net->type));
1703     LOG(GNUNET_ERROR_TYPE_DEBUG,
1704         "Address not considered by agent, address was in inactive network\n");
1705     return;
1706   }
1707
1708   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
1709   GNUNET_free(address_wrapped);
1710
1711   //decrease W
1712   m_new = agent->m - RIL_FEATURES_ADDRESS_COUNT;
1713   n_new = agent->n - 1;
1714
1715   for (i = 0; i < agent->n; i++)
1716   {
1717     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
1718         ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1719             + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1720   }
1721   GNUNET_free(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
1722   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
1723       1, agent->n);
1724   //correct last action
1725   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
1726   {
1727     agent->a_old -= 1;
1728   }
1729   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
1730   {
1731     agent->a_old = RIL_ACTION_INVALID;
1732   }
1733   //decrease old state vector and eligibility vector
1734   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
1735       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1736           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1737   ril_cut_from_vector ((void **) &agent->e, sizeof(double),
1738       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT)
1739           + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1740   agent->m = m_new;
1741   agent->n = n_new;
1742
1743   LOG(GNUNET_ERROR_TYPE_DEBUG, "address was used: %s\n", address_was_used ? "yes" : "no");
1744
1745   if (address_was_used)
1746   {
1747     net = address->solver_information;
1748     net->bw_in_assigned -= agent->bw_in;
1749     net->bw_out_assigned -= agent->bw_out;
1750
1751     if (NULL != agent->addresses_head) //if peer has an address left, use it
1752     {
1753       LOG(GNUNET_ERROR_TYPE_DEBUG, "address left: %p\n",
1754           agent->addresses_head->address_naked->addr);
1755       //TODO? check if network/bandwidth update can be done more clever/elegant at different function
1756       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, min_bw, min_bw,
1757           GNUNET_NO);
1758       net = agent->addresses_head->address_naked->solver_information;
1759       net->bw_in_assigned -= min_bw;
1760       net->bw_out_assigned -= min_bw;
1761     }
1762     else
1763     {
1764       LOG(GNUNET_ERROR_TYPE_DEBUG, "no address left => disconnect\n");
1765
1766       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
1767     }
1768   }
1769
1770   ril_step(solver);
1771
1772   LOG(GNUNET_ERROR_TYPE_DEBUG, "Address deleted\n");
1773 }
1774
1775 /**
1776  * Update the properties of an address in the solver
1777  *
1778  * @param solver solver handle
1779  * @param address the address
1780  * @param type the ATSI type in HBO
1781  * @param abs_value the absolute value of the property
1782  * @param rel_value the normalized value
1783  */
1784 void
1785 GAS_ril_address_property_changed (void *solver,
1786     struct ATS_Address *address,
1787     uint32_t type,
1788     uint32_t abs_value,
1789     double rel_value)
1790 {
1791   LOG(GNUNET_ERROR_TYPE_DEBUG,
1792       "API_address_property_changed() Property '%s' for peer '%s' address %p changed "
1793           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1794       address->addr, rel_value);
1795
1796   ril_step(solver);
1797 }
1798
1799 /**
1800  * Update the session of an address in the solver
1801  *
1802  * NOTE: values in addresses are already updated
1803  *
1804  * @param solver solver handle
1805  * @param address the address
1806  * @param cur_session the current session
1807  * @param new_session the new session
1808  */
1809 void
1810 GAS_ril_address_session_changed (void *solver,
1811     struct ATS_Address *address,
1812     uint32_t cur_session,
1813     uint32_t new_session)
1814 {
1815   /*
1816    * TODO? Future Work: Potentially add session activity as a feature in state vector
1817    */
1818   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
1819 }
1820
1821 /**
1822  * Notify the solver that an address is (not) actively used by transport
1823  * to communicate with a remote peer
1824  *
1825  * NOTE: values in addresses are already updated
1826  *
1827  * @param solver solver handle
1828  * @param address the address
1829  * @param in_use usage state
1830  */
1831 void
1832 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
1833 {
1834   /* Nothing to do here.
1835    * Possible TODO? Future Work: Potentially add usage variable to state vector
1836    */
1837   LOG(GNUNET_ERROR_TYPE_DEBUG,
1838       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
1839       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
1840 }
1841
1842 /**
1843  * Notify solver that the network an address is located in has changed
1844  *
1845  * NOTE: values in addresses are already updated
1846  *
1847  * @param solver solver handle
1848  * @param address the address
1849  * @param current_network the current network
1850  * @param new_network the new network
1851  */
1852 void
1853 GAS_ril_address_change_network (void *solver,
1854     struct ATS_Address *address,
1855     uint32_t current_network,
1856     uint32_t new_network)
1857 {
1858   struct GAS_RIL_Handle *s = solver;
1859   struct RIL_Peer_Agent *agent;
1860   struct RIL_Network *net;
1861   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1862
1863   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
1864       "%s address of peer %s from '%s' to '%s'\n",
1865       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
1866       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
1867
1868   if (address->active && !ril_network_is_active (solver, new_network))
1869   {
1870     GAS_ril_address_delete (solver, address, GNUNET_NO);
1871     return;
1872   }
1873
1874   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1875   if (NULL == agent)
1876   {
1877     GNUNET_assert(!ril_network_is_active (solver, current_network));
1878
1879     GAS_ril_address_add (s, address, new_network);
1880     return;
1881   }
1882
1883   net = ril_get_network (s, current_network);
1884   net->bw_in_assigned -= agent->bw_in;
1885   net->bw_out_assigned -= agent->bw_out;
1886
1887   net = ril_get_network (s, new_network);
1888   net->bw_in_assigned -= min_bw;
1889   net->bw_out_assigned -= min_bw;
1890   address->solver_information = net;
1891 }
1892
1893 /**
1894  * Give feedback about the current assignment
1895  *
1896  * @param solver the solver handle
1897  * @param application the application
1898  * @param peer the peer to change the preference for
1899  * @param scope the time interval for this feedback: [now - scope .. now]
1900  * @param kind the kind to change the preference
1901  * @param score the score
1902  */
1903 void
1904 GAS_ril_address_preference_feedback (void *solver,
1905     void *application,
1906     const struct GNUNET_PeerIdentity *peer,
1907     const struct GNUNET_TIME_Relative scope,
1908     enum GNUNET_ATS_PreferenceKind kind,
1909     double score)
1910 {
1911   LOG(GNUNET_ERROR_TYPE_DEBUG,
1912       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
1913           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
1914       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
1915 }
1916
1917 /**
1918  * Start a bulk operation
1919  *
1920  * @param solver the solver
1921  */
1922 void
1923 GAS_ril_bulk_start (void *solver)
1924 {
1925   struct GAS_RIL_Handle *s = solver;
1926
1927   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start() Locking solver for bulk operation ...\n");
1928
1929   s->bulk_lock++;
1930 }
1931
1932 /**
1933  * Bulk operation done
1934  *
1935  * @param solver the solver handle
1936  */
1937 void
1938 GAS_ril_bulk_stop (void *solver)
1939 {
1940   struct GAS_RIL_Handle *s = solver;
1941
1942   LOG (GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop() Releasing solver from bulk operation ...\n");
1943
1944   if (s->bulk_lock < 1)
1945   {
1946     GNUNET_break (0);
1947     return;
1948   }
1949   s->bulk_lock--;
1950
1951   if (0 < s->bulk_changes)
1952   {
1953     ril_step (solver);
1954     s->bulk_changes = 0;
1955   }
1956 }
1957
1958 /**
1959  * Tell solver to notify ATS if the address to use changes for a specific
1960  * peer using the bandwidth changed callback
1961  *
1962  * The solver must only notify about changes for peers with pending address
1963  * requests!
1964  *
1965  * @param solver the solver handle
1966  * @param peer the identity of the peer
1967  */
1968 const struct ATS_Address *
1969 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
1970 {
1971   /*
1972    * activate agent, return currently chosen address
1973    */
1974   struct GAS_RIL_Handle *s = solver;
1975   struct RIL_Peer_Agent *agent;
1976   struct RIL_Network *net;
1977
1978   agent = ril_get_agent (s, peer, GNUNET_YES);
1979
1980   agent->is_active = GNUNET_YES;
1981
1982   if (agent->address_inuse)
1983   {
1984     net = agent->address_inuse->solver_information;
1985     net->bw_in_assigned += agent->bw_in;
1986     net->bw_out_assigned += agent->bw_out;
1987   }
1988   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
1989       GNUNET_YES);
1990
1991   if (agent->address_inuse)
1992   {
1993     LOG(GNUNET_ERROR_TYPE_DEBUG,
1994         "API_get_preferred_address() Activated agent for peer '%s' with %s address %p\n",
1995         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
1996   }
1997   else
1998   {
1999     LOG(GNUNET_ERROR_TYPE_DEBUG,
2000         "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
2001         GNUNET_i2s (peer));
2002   }
2003
2004   ril_step(s);
2005
2006   return agent->address_inuse;
2007 }
2008
2009 /**
2010  * Tell solver stop notifying ATS about changes for this peers
2011  *
2012  * The solver must only notify about changes for peers with pending address
2013  * requests!
2014  *
2015  * @param solver the solver handle
2016  * @param peer the peer
2017  */
2018 void
2019 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
2020 {
2021   struct GAS_RIL_Handle *s = solver;
2022   struct RIL_Peer_Agent *agent;
2023   struct RIL_Network *net;
2024
2025   agent = ril_get_agent (s, peer, GNUNET_NO);
2026
2027   if (NULL == agent)
2028   {
2029     GNUNET_break(0);
2030     return;
2031   }
2032   if (GNUNET_NO == agent->is_active)
2033   {
2034     GNUNET_break(0);
2035     return;
2036   }
2037
2038   agent->is_active = GNUNET_NO;
2039   if (agent->address_inuse)
2040   {
2041     net = agent->address_inuse->solver_information;
2042     net->bw_in_assigned -= agent->bw_in;
2043     net->bw_out_assigned -= agent->bw_out;
2044   }
2045   envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
2046       GNUNET_YES);
2047
2048   ril_step(s);
2049
2050   LOG(GNUNET_ERROR_TYPE_DEBUG,
2051       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
2052       GNUNET_i2s (peer), agent->address_inuse->plugin);
2053 }
2054
2055 /* end of libgnunet_plugin_ats_ril.c */