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