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