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