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