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