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