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