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