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