fix warning
[oweals/gnunet.git] / src / ats / gnunet-service-ats-solver_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/gnunet-service-ats-solver_ril.c
23  * @brief ATS reinforcement learning solver
24  * @author Fabian Oehlmann
25  * @author Matthias Wachs
26  */
27 #include "platform.h"
28 #include "float.h"
29 #include "gnunet_util_lib.h"
30 #include "gnunet-service-ats_addresses.h"
31 #include "gnunet_statistics_service.h"
32
33 #define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)
34
35 #define RIL_ACTION_INVALID -1
36 #define RIL_FEATURES_ADDRESS_COUNT (3 + GNUNET_ATS_QualityPropertiesCount)
37 #define RIL_FEATURES_NETWORK_COUNT 4
38
39 #define RIL_DEFAULT_STEP_TIME GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 3000)
40 #define RIL_DEFAULT_ALGORITHM RIL_ALGO_Q
41 #define RIL_DEFAULT_DISCOUNT_FACTOR 0.5
42 #define RIL_DEFAULT_GRADIENT_STEP_SIZE 0.4
43 #define RIL_DEFAULT_TRACE_DECAY 0.6
44 #define RIL_EXPLORE_RATIO 0.1
45
46 /**
47  * ATS reinforcement learning solver
48  *
49  * General description
50  */
51
52 /**
53  * TODO! implement reward calculation 1 and 2 (i.e. meeting preferences and taking scores)
54  */
55
56 enum RIL_Action_Type
57 {
58   RIL_ACTION_NOTHING = 0,
59   RIL_ACTION_BW_IN_DBL = 1,
60   RIL_ACTION_BW_IN_HLV = 2,
61   RIL_ACTION_BW_IN_INC = 3,
62   RIL_ACTION_BW_IN_DEC = 4,
63   RIL_ACTION_BW_OUT_DBL = 5,
64   RIL_ACTION_BW_OUT_HLV = 6,
65   RIL_ACTION_BW_OUT_INC = 7,
66   RIL_ACTION_BW_OUT_DEC = 8,
67   RIL_ACTION_TYPE_NUM = 9
68 };
69
70 enum RIL_Algorithm
71 {
72   RIL_ALGO_SARSA = 0,
73   RIL_ALGO_Q = 1
74 };
75
76 enum RIL_E_Modification
77 {
78   RIL_E_SET,
79   RIL_E_ZERO,
80   RIL_E_ACCUMULATE,
81   RIL_E_REPLACE
82 };
83
84 /**
85  * Global learning parameters
86  */
87 struct RIL_Learning_Parameters
88 {
89   /**
90    * The TD-algorithm to use
91    */
92   enum RIL_Algorithm algorithm;
93
94   /**
95    * Learning discount factor in the TD-update
96    */
97   float gamma;
98
99   /**
100    * Gradient-descent step-size
101    */
102   float alpha;
103
104   /**
105    * Trace-decay factor for eligibility traces
106    */
107   float lambda;
108 };
109
110 /**
111  * Wrapper for addresses to store them in agent's linked list
112  */
113 struct RIL_Address_Wrapped
114 {
115   /**
116    * Next in DLL
117    */
118   struct RIL_Address_Wrapped *next;
119
120   /**
121    * Previous in DLL
122    */
123   struct RIL_Address_Wrapped *prev;
124
125   /**
126    * The address
127    */
128   struct ATS_Address *address_naked;
129 };
130
131 struct RIL_Peer_Agent
132 {
133   /**
134    * Next agent in solver's linked list
135    */
136   struct RIL_Peer_Agent *next;
137
138   /**
139    * Previous agent in solver's linked list
140    */
141   struct RIL_Peer_Agent *prev;
142
143   /**
144    * Environment handle
145    */
146   struct GAS_RIL_Handle *envi;
147
148   /**
149    * Peer ID
150    */
151   struct GNUNET_PeerIdentity peer;
152
153   /**
154    * Whether the agent is active or not
155    */
156   int active; //TODO? rename into "requested", since it rather depicts whether there is a request pending for it
157
158   /**
159    * Number of performed time-steps
160    */
161   unsigned long long step_count;
162
163   /**
164    * Experience matrix W
165    */
166   double ** W;
167
168   /**
169    * Number of rows of W / Number of state-vector features
170    */
171   unsigned int m;
172
173   /**
174    * Number of columns of W / Number of actions
175    */
176   unsigned int n;
177
178   /**
179    * Last perceived state feature vector
180    */
181   double * s_old;
182
183   /**
184    * Last chosen action
185    */
186   int a_old;
187
188   /**
189    * Eligibility trace vector
190    */
191   double * e;
192
193   /**
194    * Address in use
195    */
196   struct ATS_Address * address_inuse;
197
198   /**
199    * Head of addresses DLL
200    */
201   struct RIL_Address_Wrapped * addresses_head;
202
203   /**
204    * Tail of addresses DLL
205    */
206   struct RIL_Address_Wrapped * addresses_tail;
207
208   /**
209    * Inbound bandwidth assigned by the agent
210    */
211   unsigned long long bw_in;
212
213   /**
214    * Outbound bandwidth assigned by the agent
215    */
216   unsigned long long bw_out;
217 };
218
219 struct RIL_Network
220 {
221   /**
222    * ATS network type
223    */
224   enum GNUNET_ATS_Network_Type type;
225
226   /**
227    * Total available inbound bandwidth
228    */
229   unsigned long long bw_in_available;
230
231   /**
232    * Total assigned outbound bandwidth
233    */
234   unsigned long long bw_in_assigned;
235
236   /**
237    * Total available outbound bandwidth
238    */
239   unsigned long long bw_out_available;
240
241   /**
242    * Total assigned outbound bandwidth
243    */
244   unsigned long long bw_out_assigned;
245 };
246
247 struct RIL_Callbacks
248 {
249   /**
250    * Bandwidth changed callback
251    */
252   GAS_bandwidth_changed_cb bw_changed;
253
254   /**
255    * Bandwidth changed callback cls
256    */
257   void *bw_changed_cls;
258
259   /**
260    * ATS function to get preferences
261    */
262   GAS_get_preferences get_preferences;
263
264   /**
265    * Closure for ATS function to get preferences
266    */
267   void *get_preferences_cls;
268
269   /**
270    * ATS function to get properties
271    */
272   GAS_get_properties get_properties;
273
274   /**
275    * Closure for ATS function to get properties
276    */
277   void *get_properties_cls;
278 };
279
280 /**
281  * A handle for the reinforcement learning solver
282  */
283 struct GAS_RIL_Handle
284 {
285   /**
286    * Statistics handle
287    */
288   struct GNUNET_STATISTICS_Handle *stats;
289
290   /**
291    * Hashmap containing all valid addresses
292    */
293   const struct GNUNET_CONTAINER_MultiPeerMap *addresses;
294
295   /**
296    * Callbacks for the solver
297    */
298   struct RIL_Callbacks *callbacks;
299
300   /**
301    * Bulk lock
302    */
303   int bulk_lock;
304
305   /**
306    * Number of changes while solver was locked
307    */
308   int bulk_requests;
309
310   /**
311    * Number of performed time-steps
312    */
313   unsigned long long step_count;
314
315   /**
316    * Interval time between steps in milliseconds //TODO? put in agent
317    */
318   struct GNUNET_TIME_Relative step_time;
319
320   /**
321    * Task identifier of the next time-step to be executed //TODO? put in agent
322    */
323   GNUNET_SCHEDULER_TaskIdentifier next_step;
324
325   /**
326    * Learning parameters
327    */
328   struct RIL_Learning_Parameters parameters;
329
330   /**
331    * Array of networks with global assignment state
332    */
333   struct RIL_Network * network_entries;
334
335   /**
336    * Networks count
337    */
338   unsigned int networks_count;
339
340   /**
341    * List of active peer-agents
342    */
343   struct RIL_Peer_Agent * agents_head;
344   struct RIL_Peer_Agent * agents_tail;
345 };
346
347 /**
348  *  Private functions
349  *  ---------------------------
350  */
351
352 /**
353  * Estimate the current action-value for state s and action a
354  * @param agent agent performing the estimation
355  * @param state s
356  * @param action a
357  * @return estimation value
358  */
359 static double
360 agent_estimate_q (struct RIL_Peer_Agent *agent, double *state, int action)
361 {
362   int i;
363   double result = 0;
364
365   for (i = 0; i < agent->m; i++)
366   {
367     result += state[i] * agent->W[action][i];
368   }
369
370   return result;
371 }
372
373 /**
374  * Decide whether to do exploration (i.e. taking a new action) or exploitation (i.e. taking the
375  * currently estimated best action) in the current step
376  * @param agent agent performing the step
377  * @return yes, if exploring
378  */
379 static int
380 agent_decide_exploration (struct RIL_Peer_Agent *agent)
381 {
382   double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
383       UINT32_MAX) / (double) UINT32_MAX;
384
385 if  (r < RIL_EXPLORE_RATIO)
386   {
387     return GNUNET_YES;
388   }
389   return GNUNET_NO;
390 }
391
392 static int
393 agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
394 {
395   int i;
396   struct RIL_Address_Wrapped *cur;
397
398   i = -1;
399   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
400   {
401     i++;
402     if (cur->address_naked == address)
403     {
404       return i;
405     }
406   }
407
408   return i;
409 }
410
411 static struct RIL_Address_Wrapped *
412 agent_address_get (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
413 {
414   struct RIL_Address_Wrapped *cur;
415
416   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
417   {
418     if (cur->address_naked == address)
419     {
420       return cur;
421     }
422   }
423
424   return NULL ;
425 }
426
427 /**
428  * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
429  * most reward in the future)
430  * @param agent agent performing the calculation
431  * @param state the state from which to take the action
432  * @return the action promising most future reward
433  */
434 static int
435 agent_get_action_best (struct RIL_Peer_Agent *agent, double *state)
436 {
437   int i;
438   int max_i = RIL_ACTION_INVALID;
439   double cur_q;
440   double max_q = -DBL_MAX;
441
442   for (i = 0; i < agent->n; i++)
443   {
444     cur_q = agent_estimate_q (agent, state, i);
445     if (cur_q > max_q)
446     {
447       max_q = cur_q;
448       max_i = i;
449     }
450   }
451
452   GNUNET_assert(RIL_ACTION_INVALID != max_i);
453
454   return max_i;
455 }
456
457 /**
458  * Gets any action, to explore the action space from that state
459  * @param agent agent performing the calculation
460  * @param state the state from which to take the action
461  * @return any action
462  */
463 static int
464 agent_get_action_explore (struct RIL_Peer_Agent *agent, double *state)
465 {
466   return GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, agent->n);
467 }
468
469 /**
470  * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
471  * @param agent the agent performing the update
472  * @param reward the reward received for the last action
473  * @param s_next the new state, the last step got the agent into
474  * @param a_prime the new
475  */
476 static void
477 agent_update_weights (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
478 {
479   int i;
480   double delta;
481   double *theta = agent->W[agent->a_old];
482
483   delta = reward + agent_estimate_q (agent, s_next, a_prime)
484       - agent_estimate_q (agent, agent->s_old, agent->a_old);
485   for (i = 0; i < agent->m; i++)
486   {
487     theta[i] += agent->envi->parameters.alpha * delta * (agent->e)[i];
488   }
489 }
490
491 /**
492  * Changes the eligibility trace vector e in various manners:
493  * RIL_E_ACCUMULATE - adds 1 to each component as in accumulating eligibility traces
494  * RIL_E_REPLACE - resets each component to 1 as in replacing traces
495  * RIL_E_SET - multiplies e with gamma and lambda as in the update rule
496  * RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
497  * @param agent
498  * @param mod
499  */
500 static void
501 agent_modify_eligibility (struct RIL_Peer_Agent *agent, enum RIL_E_Modification mod)
502 {
503   int i;
504   double *e = agent->e;
505   double gamma = agent->envi->parameters.gamma;
506   double lambda = agent->envi->parameters.lambda;
507
508   for (i = 0; i < agent->m; i++)
509   {
510     switch (mod)
511     {
512     case RIL_E_ACCUMULATE:
513       e[i] += 1;
514       break;
515     case RIL_E_REPLACE:
516       e[i] = 1;
517       break;
518     case RIL_E_SET:
519       e[i] = gamma * lambda;
520       break;
521     case RIL_E_ZERO:
522       e[i] = 0;
523       break;
524     }
525   }
526 }
527
528 static void
529 envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
530     struct RIL_Peer_Agent *agent,
531     struct ATS_Address *new_address,
532     unsigned long long new_bw_in,
533     unsigned long long new_bw_out,
534     int silent)
535 {
536   int notify = GNUNET_NO;
537
538   LOG (GNUNET_ERROR_TYPE_DEBUG, "set_active_suggestion()\n");
539
540   //address change
541   if (agent->address_inuse != new_address)
542   {
543     if (NULL != agent->address_inuse)
544     {
545       agent->address_inuse->active = GNUNET_NO;
546       agent->address_inuse->assigned_bw_in.value__ = htonl (0);
547       agent->address_inuse->assigned_bw_out.value__ = htonl (0);
548     }
549     if (NULL != new_address)
550     {
551       LOG (GNUNET_ERROR_TYPE_DEBUG, "set address active: %s\n", agent->active ? "yes" : "no");
552       new_address->active = agent->active;
553       new_address->assigned_bw_in.value__ = htonl (agent->bw_in);
554       new_address->assigned_bw_out.value__ = htonl (agent->bw_out);
555     }
556     notify |= GNUNET_YES;
557   }
558
559   if (new_address)
560   {
561     //activity change
562     if (new_address->active != agent->active)
563     {
564       new_address->active = agent->active;
565     }
566
567     //bw change
568     if (agent->bw_in != new_bw_in)
569     {
570       agent->bw_in = new_bw_in;
571       new_address->assigned_bw_in.value__ = htonl (new_bw_out);
572       notify |= GNUNET_YES;
573     }
574     if (agent->bw_out != new_bw_out)
575     {
576       agent->bw_out = new_bw_out;
577       new_address->assigned_bw_out.value__ = htonl (new_bw_out);
578       notify |= GNUNET_YES;
579     }
580   }
581
582   if (notify && agent->active && (GNUNET_NO == silent))
583   {
584     if (new_address)
585     {
586       solver->callbacks->bw_changed (solver->callbacks->bw_changed_cls, new_address);
587     }
588     else
589     {
590       GNUNET_assert (0 == ntohl(agent->address_inuse->assigned_bw_in.value__));
591       GNUNET_assert (0 == ntohl(agent->address_inuse->assigned_bw_out.value__));
592       agent->bw_in = 0;
593       agent->bw_out = 0;
594       //disconnect
595       solver->callbacks->bw_changed (solver->callbacks->bw_changed_cls, agent->address_inuse);
596     }
597   }
598   agent->address_inuse = new_address;
599 }
600
601 /**
602  * Allocates a state vector and fills it with the features present
603  * @param solver the solver handle
604  * @return pointer to the state vector
605  */
606 static double *
607 envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
608 {
609   int i;
610   int k;
611   struct RIL_Network *net;
612   double *state = GNUNET_malloc (sizeof (double) * agent->m);
613   struct RIL_Address_Wrapped *cur_address;
614   const double *properties;
615
616   for (i = 0; i < solver->networks_count; i++)
617   {
618     net = &solver->network_entries[i];
619     state[i * RIL_FEATURES_NETWORK_COUNT + 0] = (double) net->bw_in_assigned;
620     state[i * RIL_FEATURES_NETWORK_COUNT + 1] = (double) net->bw_in_available;
621     state[i * RIL_FEATURES_NETWORK_COUNT + 2] = (double) net->bw_out_assigned;
622     state[i * RIL_FEATURES_NETWORK_COUNT + 3] = (double) net->bw_out_available;
623   }
624
625   i = i * RIL_FEATURES_NETWORK_COUNT; //first address feature
626
627   for (cur_address = agent->addresses_head; NULL != cur_address; cur_address = cur_address->next)
628   {
629     state[i++] = cur_address->address_naked->active;
630     state[i++] = cur_address->address_naked->active ? agent->bw_in : 0;
631     state[i++] = cur_address->address_naked->active ? agent->bw_out : 0;
632     properties = solver->callbacks->get_properties (solver->callbacks->get_properties_cls, cur_address->address_naked);
633     for (k = 0; k < GNUNET_ATS_QualityPropertiesCount; k++)
634     {
635       state[i++] = properties[k];
636     }
637   }
638
639   return state;
640 }
641
642 /**
643  * Gets the reward of the last performed step
644  * @param solver solver handle
645  * @return the reward
646  */
647 static double
648 envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
649 {
650   //TODO! implement reward calculation
651
652   return (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, UINT32_MAX)
653       / (double) UINT32_MAX;
654 }
655
656 static void
657 envi_action_bw_double (struct GAS_RIL_Handle *solver,
658     struct RIL_Peer_Agent *agent,
659     int direction_in)
660 {
661   if (direction_in)
662   {
663     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in * 2,
664         agent->bw_out, GNUNET_NO);
665   }
666   else
667   {
668     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
669         agent->bw_out * 2, GNUNET_NO);
670   }
671 }
672
673 static void
674 envi_action_bw_halven (struct GAS_RIL_Handle *solver,
675     struct RIL_Peer_Agent *agent,
676     int direction_in)
677 {
678   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
679   unsigned long long new_bw;
680
681   if (direction_in)
682   {
683     new_bw = agent->bw_in / 2;
684     if (new_bw < min_bw)
685       new_bw = min_bw;
686     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out, GNUNET_NO);
687   }
688   else
689   {
690     new_bw = agent->bw_out / 2;
691     if (new_bw < min_bw)
692       new_bw = min_bw;
693     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw, GNUNET_NO);
694   }
695 }
696
697 static void
698 envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
699 {
700   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
701
702   if (direction_in)
703   {
704     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in + (5 * min_bw),
705         agent->bw_out, GNUNET_NO);
706   }
707   else
708   {
709     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
710         agent->bw_out + (5 * min_bw), GNUNET_NO);
711   }
712 }
713
714 static void
715 envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
716 {
717   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
718   unsigned long long new_bw;
719
720   if (direction_in)
721   {
722     new_bw = agent->bw_in - (5 * min_bw);
723     if (new_bw < min_bw)
724       new_bw = min_bw;
725     envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out, GNUNET_NO);
726   }
727   else
728   {
729     new_bw = agent->bw_out - (5 * min_bw);
730     if (new_bw < min_bw)
731       new_bw = min_bw;
732     envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw, GNUNET_NO);
733   }
734 }
735
736 static void
737 envi_action_address_switch (struct GAS_RIL_Handle *solver,
738     struct RIL_Peer_Agent *agent,
739     unsigned int address_index)
740 {
741   struct RIL_Address_Wrapped *cur;
742   int i = 0;
743
744   for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
745   {
746     if (i == address_index)
747     {
748       envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out, GNUNET_NO);
749       return;
750     }
751
752     i++;
753   }
754
755   //no address with address_index exists
756   GNUNET_assert(GNUNET_NO);
757 }
758
759 /**
760  * Puts the action into effect
761  * @param solver solver handle
762  * @param action action to perform by the solver
763  */
764 static void
765 envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
766 {
767   unsigned int address_index;
768
769   switch (action)
770   {
771   case RIL_ACTION_NOTHING:
772     break;
773   case RIL_ACTION_BW_IN_DBL:
774     envi_action_bw_double (solver, agent, GNUNET_YES);
775     break;
776   case RIL_ACTION_BW_IN_HLV:
777     envi_action_bw_halven (solver, agent, GNUNET_YES);
778     break;
779   case RIL_ACTION_BW_IN_INC:
780     envi_action_bw_inc (solver, agent, GNUNET_YES);
781     break;
782   case RIL_ACTION_BW_IN_DEC:
783     envi_action_bw_dec (solver, agent, GNUNET_YES);
784     break;
785   case RIL_ACTION_BW_OUT_DBL:
786     envi_action_bw_double (solver, agent, GNUNET_NO);
787     break;
788   case RIL_ACTION_BW_OUT_HLV:
789     envi_action_bw_halven (solver, agent, GNUNET_NO);
790     break;
791   case RIL_ACTION_BW_OUT_INC:
792     envi_action_bw_inc (solver, agent, GNUNET_NO);
793     break;
794   case RIL_ACTION_BW_OUT_DEC:
795     envi_action_bw_dec (solver, agent, GNUNET_NO);
796     break;
797   default:
798     if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n))
799     {
800       address_index = agent->n - RIL_ACTION_TYPE_NUM;
801
802       GNUNET_assert(address_index >= 0);
803       GNUNET_assert(
804           address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));
805
806       envi_action_address_switch (solver, agent, address_index);
807       break;
808     }
809     // error - action does not exist
810     GNUNET_assert(GNUNET_NO);
811   }
812 }
813
814 /**
815  * Performs one step of the Markov Decision Process. Other than in the literature the step starts
816  * after having done the last action a_old. It observes the new state s_next and the reward
817  * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
818  * next action is put into effect.
819  * @param agent the agent performing the step
820  */
821 static void
822 agent_step (struct RIL_Peer_Agent *agent)
823 {
824   int a_next = RIL_ACTION_INVALID;
825   double *s_next;
826   double reward;
827
828   s_next = envi_get_state (agent->envi, agent);
829   reward = envi_get_reward (agent->envi, agent);
830
831   LOG(GNUNET_ERROR_TYPE_DEBUG, "agent_step() with algorithm %s\n",
832       agent->envi->parameters.algorithm ? "Q" : "SARSA");
833
834   switch (agent->envi->parameters.algorithm)
835   {
836   case RIL_ALGO_SARSA:
837     agent_modify_eligibility (agent, RIL_E_SET);
838     if (agent_decide_exploration (agent))
839     {
840       a_next = agent_get_action_explore (agent, s_next);
841     }
842     else
843     {
844       a_next = agent_get_action_best (agent, s_next);
845     }
846     if (RIL_ACTION_INVALID != agent->a_old)
847     {
848       //updates weights with selected action (on-policy), if not first step
849       agent_update_weights (agent, reward, s_next, a_next);
850     }
851     break;
852
853   case RIL_ALGO_Q:
854     a_next = agent_get_action_best (agent, s_next);
855     if (RIL_ACTION_INVALID != agent->a_old)
856     {
857       //updates weights with best action, disregarding actually selected action (off-policy), if not first step
858       agent_update_weights (agent, reward, s_next, a_next);
859     }
860     if (agent_decide_exploration (agent))
861     {
862       a_next = agent_get_action_explore (agent, s_next);
863       agent_modify_eligibility (agent, RIL_E_ZERO);
864     }
865     else
866     {
867       a_next = agent_get_action_best (agent, s_next);
868       agent_modify_eligibility (agent, RIL_E_SET);
869     }
870     break;
871   }
872
873   GNUNET_assert(RIL_ACTION_INVALID != a_next);
874
875   agent_modify_eligibility (agent, RIL_E_ACCUMULATE);
876
877   envi_do_action (agent->envi, agent, a_next);
878
879   GNUNET_free(agent->s_old);
880   agent->s_old = s_next;
881   agent->a_old = a_next;
882
883   agent->step_count += 1;
884 }
885
886 /**
887  * Cycles through all agents and lets the active ones do a step. Schedules the next step.
888  * @param solver the solver handle
889  * @param tc task context for the scheduler
890  */
891 static void
892 ril_periodic_step (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
893 {
894   struct GAS_RIL_Handle *solver = cls;
895   struct RIL_Peer_Agent *cur;
896
897   LOG(GNUNET_ERROR_TYPE_DEBUG, "RIL step number %d\n", solver->step_count);
898
899   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
900   {
901     if (cur->active && cur->address_inuse)
902     {
903       agent_step (cur);
904     }
905   }
906
907   solver->step_count += 1;
908   solver->next_step = GNUNET_SCHEDULER_add_delayed (solver->step_time, &ril_periodic_step, solver);
909 }
910
911 /**
912  * Initialize an agent without addresses and its knowledge base
913  * @param s ril solver
914  * @param peer the one in question
915  * @return handle to the new agent
916  */
917 static struct RIL_Peer_Agent *
918 agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
919 {
920   int i;
921   struct GAS_RIL_Handle * solver = s;
922   struct RIL_Peer_Agent * agent = GNUNET_malloc (sizeof (struct RIL_Peer_Agent));
923
924   agent->envi = solver;
925   agent->peer = *peer;
926   agent->step_count = 0;
927   agent->active = GNUNET_NO;
928   agent->n = RIL_ACTION_TYPE_NUM;
929   agent->m = solver->networks_count * RIL_FEATURES_NETWORK_COUNT;
930   agent->W = (double **) GNUNET_malloc (sizeof (double) * agent->n);
931   for (i = 0; i < agent->n; i++)
932   {
933     agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
934   }
935   agent->a_old = RIL_ACTION_INVALID;
936   agent->s_old = envi_get_state (solver, agent);
937   agent->e = (double *) GNUNET_malloc (sizeof (double) * agent->m);
938   agent_modify_eligibility (agent, RIL_E_ZERO);
939
940   GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, agent);
941
942   return agent;
943 }
944
945 /**
946  * Deallocate agent
947  * @param s solver handle
948  * @param agent the agent to retire
949  */
950 static void
951 agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
952 {
953   int i;
954
955   for (i = 0; i < agent->n; i++)
956   {
957     GNUNET_free(agent->W[i]);
958   }
959   GNUNET_free(agent->W);
960   GNUNET_free(agent->e);
961   GNUNET_free(agent->s_old);
962   GNUNET_free(agent);
963 }
964
965 /**
966  * Returns the agent for a peer
967  * @param s solver handle
968  * @param peer identity of the peer
969  * @param create whether to create an agent if none is allocated yet
970  * @return agent
971  */
972 static struct RIL_Peer_Agent *
973 ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
974 {
975   struct RIL_Peer_Agent *cur;
976
977   for (cur = solver->agents_head; NULL != cur; cur = cur->next)
978   {
979     if (0 == memcmp (peer, 
980                      &cur->peer,
981                      sizeof (struct GNUNET_PeerIdentity)))
982     {
983       return cur;
984     }
985   }
986
987   if (create)
988   {
989     return agent_init (solver, peer);
990   }
991   return NULL ;
992 }
993
994 /**
995  * Lookup network struct by type
996  *
997  * @param s the solver handle
998  * @param type the network type
999  * @return the network struct
1000  */
1001 static struct RIL_Network *
1002 ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
1003 {
1004   int i;
1005
1006   for (i = 0; i < s->networks_count; i++)
1007   {
1008     if (s->network_entries[i].type == type)
1009     {
1010       return &s->network_entries[i];
1011     }
1012   }
1013   return NULL ;
1014 }
1015
1016 static int
1017 ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
1018 {
1019   struct RIL_Network *net;
1020   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1021
1022   net = ril_get_network (solver, network);
1023   if (net->bw_out_available < min_bw)
1024     return GNUNET_NO;
1025   return GNUNET_YES;
1026 }
1027
1028 static void
1029 ril_cut_from_vector (void **old,
1030     size_t element_size,
1031     unsigned int hole_start,
1032     unsigned int hole_length,
1033     unsigned int old_length)
1034 {
1035   char *tmpptr;
1036   char *oldptr = (char *) *old;
1037   size_t size;
1038   unsigned int bytes_before;
1039   unsigned int bytes_hole;
1040   unsigned int bytes_after;
1041
1042
1043   GNUNET_assert(old_length > hole_length);
1044   GNUNET_assert(old_length >= (hole_start + hole_length));
1045
1046   size = element_size * (old_length - hole_length);
1047
1048   bytes_before = element_size * hole_start;
1049   bytes_hole = element_size * hole_length;
1050   bytes_after = element_size * (old_length - hole_start - hole_length);
1051
1052   if (0 == size)
1053   {
1054     tmpptr = NULL;
1055   }
1056   else
1057   {
1058 //    LOG(GNUNET_ERROR_TYPE_DEBUG, "hole_start = %d, hole_length = %d, old_length = %d\n", hole_start, hole_length, old_length);
1059 //    LOG(GNUNET_ERROR_TYPE_DEBUG, "bytes_before = %d, bytes_hole = %d, bytes_after = %d\n", bytes_before, bytes_hole, bytes_after);
1060 //    LOG(GNUNET_ERROR_TYPE_DEBUG, "element_size = %d, bytes_old = %d, bytes_new = %d\n", element_size, old_length * element_size, size);
1061
1062     tmpptr = GNUNET_malloc (size);
1063 //    LOG(GNUNET_ERROR_TYPE_DEBUG, "first\n");
1064     memcpy (tmpptr, oldptr, bytes_before);
1065 //    LOG(GNUNET_ERROR_TYPE_DEBUG, "second\n");
1066     memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
1067   }
1068   if (NULL != *old)
1069   {
1070     GNUNET_free(*old);
1071   }
1072   *old = (void *) tmpptr;
1073 }
1074
1075 /**
1076  *  Solver API functions
1077  *  ---------------------------
1078  */
1079
1080 /**
1081  * Changes the preferences for a peer in the problem
1082  *
1083  * @param solver the solver handle
1084  * @param peer the peer to change the preference for
1085  * @param kind the kind to change the preference
1086  * @param pref_rel the normalized preference value for this kind over all clients
1087  */
1088 void
1089 GAS_ril_address_change_preference (void *s,
1090     const struct GNUNET_PeerIdentity *peer,
1091     enum GNUNET_ATS_PreferenceKind kind,
1092     double pref_rel)
1093 {
1094   LOG(GNUNET_ERROR_TYPE_DEBUG,
1095       "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
1096       GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);
1097   /*
1098    * Nothing to do here. Preferences are considered during reward calculation.
1099    */
1100 }
1101
1102 /**
1103  * Init the reinforcement learning problem solver
1104  *
1105  * Quotas:
1106  * network[i] contains the network type as type GNUNET_ATS_NetworkType[i]
1107  * out_quota[i] contains outbound quota for network type i
1108  * in_quota[i] contains inbound quota for network type i
1109  *
1110  * Example
1111  * network = {GNUNET_ATS_NET_UNSPECIFIED, GNUNET_ATS_NET_LOOPBACK, GNUNET_ATS_NET_LAN, GNUNET_ATS_NET_WAN, GNUNET_ATS_NET_WLAN}
1112  * network[2]   == GNUNET_ATS_NET_LAN
1113  * out_quota[2] == 65353
1114  * in_quota[2]  == 65353
1115  *
1116  * @param cfg configuration handle
1117  * @param stats the GNUNET_STATISTICS handle
1118  * @param network array of GNUNET_ATS_NetworkType with length dest_length
1119  * @param addresses hashmap containing all addresses
1120  * @param out_quota array of outbound quotas
1121  * @param in_quota array of outbound quota
1122  * @param dest_length array length for quota arrays
1123  * @param bw_changed_cb callback for changed bandwidth amounts
1124  * @param bw_changed_cb_cls cls for callback
1125  * @param get_preference callback to get relative preferences for a peer
1126  * @param get_preference_cls cls for callback to get relative preferences
1127  * @param get_properties_cls for callback to get relative properties
1128  * @param get_properties_cls cls for callback to get relative properties
1129  * @return handle for the solver on success, NULL on fail
1130  */
1131 void *
1132 GAS_ril_init (const struct GNUNET_CONFIGURATION_Handle *cfg,
1133     const struct GNUNET_STATISTICS_Handle *stats,
1134     const struct GNUNET_CONTAINER_MultiPeerMap *addresses,
1135     int *network,
1136     unsigned long long *out_quota,
1137     unsigned long long *in_quota,
1138     int dest_length,
1139     GAS_bandwidth_changed_cb bw_changed_cb,
1140     void *bw_changed_cb_cls,
1141     GAS_get_preferences get_preference,
1142     void *get_preference_cls,
1143     GAS_get_properties get_properties,
1144     void *get_properties_cls)
1145 {
1146   int c;
1147   unsigned long long tmp;
1148   char *string;
1149   struct RIL_Network * cur;
1150   struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
1151
1152   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_init() Initializing RIL solver\n");
1153
1154   GNUNET_assert(NULL != cfg);
1155   GNUNET_assert(NULL != stats);
1156   GNUNET_assert(NULL != network);
1157   GNUNET_assert(NULL != bw_changed_cb);
1158   GNUNET_assert(NULL != get_preference);
1159   GNUNET_assert(NULL != get_properties);
1160
1161   if (GNUNET_OK
1162       != GNUNET_CONFIGURATION_get_value_time (cfg, "ats", "RIL_STEP_TIME", &solver->step_time))
1163   {
1164     solver->step_time = RIL_DEFAULT_STEP_TIME;
1165   }
1166   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (cfg, "ats", "RIL_ALGORITHM", &string)
1167       && NULL != string && 0 == strcmp (string, "SARSA"))
1168   {
1169     solver->parameters.algorithm = RIL_ALGO_SARSA;
1170   }
1171   else
1172   {
1173     solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
1174   }
1175   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats", "RIL_DISCOUNT_FACTOR", &tmp))
1176   {
1177     solver->parameters.gamma = (double) tmp / 100;
1178   }
1179   else
1180   {
1181     solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_FACTOR;
1182   }
1183   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats", "RIL_GRADIENT_STEP_SIZE", &tmp))
1184   {
1185     solver->parameters.alpha = (double) tmp / 100;
1186   }
1187   else
1188   {
1189     solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
1190   }
1191   if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_size (cfg, "ats", "RIL_TRACE_DECAY", &tmp))
1192   {
1193     solver->parameters.lambda = (double) tmp / 100;
1194   }
1195   else
1196   {
1197     solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
1198   }
1199
1200   solver->stats = (struct GNUNET_STATISTICS_Handle *) stats;
1201   solver->callbacks = GNUNET_malloc (sizeof (struct RIL_Callbacks));
1202   solver->callbacks->bw_changed = bw_changed_cb;
1203   solver->callbacks->bw_changed_cls = bw_changed_cb_cls;
1204   solver->callbacks->get_preferences = get_preference;
1205   solver->callbacks->get_preferences_cls = get_preference_cls;
1206   solver->callbacks->get_properties = get_properties;
1207   solver->callbacks->get_properties_cls = get_properties_cls;
1208   solver->networks_count = dest_length;
1209   solver->network_entries = GNUNET_malloc (dest_length * sizeof (struct RIL_Network));
1210   solver->bulk_lock = GNUNET_NO;
1211   solver->addresses = addresses;
1212   solver->step_count = 0;
1213
1214   for (c = 0; c < dest_length; c++)
1215   {
1216     cur = &solver->network_entries[c];
1217     cur->type = network[c];
1218     cur->bw_in_available = in_quota[c];
1219     cur->bw_in_assigned = 0;
1220     cur->bw_out_available = out_quota[c];
1221     cur->bw_out_assigned = 0;
1222   }
1223
1224   solver->next_step = GNUNET_SCHEDULER_add_delayed (
1225       GNUNET_TIME_relative_multiply (GNUNET_TIME_relative_get_millisecond_ (), 1000),
1226       &ril_periodic_step, solver);
1227
1228   return solver;
1229 }
1230
1231 /**
1232  * Shutdown the reinforcement learning problem solver
1233  *
1234  * @param solver the respective handle to shutdown
1235  */
1236 void
1237 GAS_ril_done (void * solver)
1238 {
1239   struct GAS_RIL_Handle *s = solver;
1240   struct RIL_Peer_Agent *cur_agent;
1241   struct RIL_Peer_Agent *next_agent;
1242
1243   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");
1244
1245   cur_agent = s->agents_head;
1246   while (NULL != cur_agent)
1247   {
1248     next_agent = cur_agent->next;
1249     GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
1250     agent_die (s, cur_agent);
1251     cur_agent = next_agent;
1252   }
1253
1254   GNUNET_SCHEDULER_cancel (s->next_step);
1255   GNUNET_free(s->callbacks);
1256   GNUNET_free(s->network_entries);
1257   GNUNET_free(s);
1258 }
1259
1260 /**
1261  * Add a single address within a network to the solver
1262  *
1263  * @param solver the solver Handle
1264  * @param address the address to add
1265  * @param network network type of this address
1266  */
1267 void
1268 GAS_ril_address_add (void *solver, struct ATS_Address *address, uint32_t network)
1269 {
1270   struct GAS_RIL_Handle *s = solver;
1271   struct RIL_Peer_Agent *agent;
1272   struct RIL_Address_Wrapped *address_wrapped;
1273   unsigned int m_new;
1274   unsigned int m_old;
1275   unsigned int n_new;
1276   unsigned int n_old;
1277   int i;
1278   unsigned int zero;
1279   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1280
1281   address->solver_information = ril_get_network (s, network);
1282
1283   if (!ril_network_is_active (s, network))
1284   {
1285     LOG(GNUNET_ERROR_TYPE_DEBUG,
1286         "API_address_add() Did not add %s address %p for peer '%s', network does not have enough bandwidth\n",
1287         address->plugin, address->addr, GNUNET_i2s (&address->peer));
1288     return;
1289   }
1290
1291   agent = ril_get_agent (s, &address->peer, GNUNET_YES);
1292
1293   //add address
1294   address_wrapped = GNUNET_malloc (sizeof (struct RIL_Address_Wrapped));
1295   address_wrapped->address_naked = address;
1296   GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);
1297
1298   //increase size of W
1299   m_new = agent->m + RIL_FEATURES_ADDRESS_COUNT;
1300   m_old = agent->m;
1301   n_new = agent->n + 1;
1302   n_old = agent->n;
1303
1304   GNUNET_array_grow(agent->W, agent->n, n_new);
1305   for (i = 0; i < n_new; i++)
1306   {
1307     if (i < n_old)
1308     {
1309       agent->m = m_old;
1310       GNUNET_array_grow(agent->W[i], agent->m, m_new);
1311     }
1312     else
1313     {
1314       zero = 0;
1315       GNUNET_array_grow(agent->W[i], zero, m_new);
1316     }
1317   }
1318
1319   //increase size of old state vector
1320   agent->m = m_old;
1321   GNUNET_array_grow(agent->s_old, agent->m, m_new); //TODO initialize new state features?
1322
1323   agent->m = m_old;
1324   GNUNET_array_grow(agent->e, agent->m, m_new);
1325
1326   if (NULL == agent->address_inuse)
1327   {
1328     envi_set_active_suggestion (s, agent, address, min_bw, min_bw, GNUNET_NO);
1329   }
1330
1331   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %p for peer '%s'\n",
1332       address->active ? "active" : "inactive",
1333       address->plugin, address->addr, GNUNET_i2s (&address->peer));
1334 }
1335
1336 /**
1337  * Remove an address from the solver
1338  *
1339  * @param solver the solver handle
1340  * @param address the address to remove
1341  * @param session_only delete only session not whole address
1342  */
1343 void
1344 GAS_ril_address_delete (void *solver, struct ATS_Address *address, int session_only)
1345 {
1346   //TODO! delete session only
1347   struct GAS_RIL_Handle *s = solver;
1348   struct RIL_Peer_Agent *agent;
1349   struct RIL_Address_Wrapped *address_wrapped;
1350   int address_was_used = address->active;
1351   int address_index;
1352   unsigned int m_new;
1353   unsigned int n_new;
1354   int i;
1355   struct RIL_Network *net;
1356   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1357
1358   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_delete() Delete %s%s %s address %p for peer '%s'\n",
1359       session_only ? "session for " : "", address->active ? "active" : "inactive", address->plugin,
1360       address->addr, GNUNET_i2s (&address->peer));
1361
1362   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1363   if (NULL == agent)
1364   {
1365     net = address->solver_information;
1366     GNUNET_assert(!ril_network_is_active (s, net->type));
1367     LOG(GNUNET_ERROR_TYPE_DEBUG,
1368         "No agent allocated for peer yet, since address was in inactive network\n");
1369     return;
1370   }
1371
1372   address_index = agent_address_get_index (agent, address);
1373   address_wrapped = agent_address_get (agent, address);
1374
1375   if (NULL == address_wrapped)
1376   {
1377     net = address->solver_information;
1378     GNUNET_assert(!ril_network_is_active (s, net->type));
1379     LOG(GNUNET_ERROR_TYPE_DEBUG,
1380         "Address not considered by agent, address was in inactive network\n");
1381     return;
1382   }
1383
1384   GNUNET_CONTAINER_DLL_remove(agent->addresses_head, agent->addresses_tail, address_wrapped);
1385   GNUNET_free(address_wrapped);
1386
1387   //decrease W
1388   m_new = agent->m - RIL_FEATURES_ADDRESS_COUNT;
1389   n_new = agent->n - 1;
1390
1391   for (i = 0; i < agent->n; i++)
1392   {
1393 //    LOG (GNUNET_ERROR_TYPE_DEBUG, "first - cut vectors in W\n");
1394     ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
1395         ((s->networks_count * RIL_FEATURES_NETWORK_COUNT) + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1396   }
1397 //  LOG (GNUNET_ERROR_TYPE_DEBUG, "second - cut action vector out of W\n");
1398   GNUNET_free (agent->W[RIL_ACTION_TYPE_NUM + address_index]);
1399   ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
1400       1, agent->n);
1401   //correct last action
1402   if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
1403   {
1404     agent->a_old -= 1;
1405   }
1406   else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
1407   {
1408     agent->a_old = RIL_ACTION_INVALID;
1409   }
1410   //decrease old state vector and eligibility vector
1411 //  LOG (GNUNET_ERROR_TYPE_DEBUG, "third - cut state vector\n");
1412   ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
1413       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT) + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1414 //  LOG (GNUNET_ERROR_TYPE_DEBUG, "fourth - cut eligibility vector\n");
1415   ril_cut_from_vector ((void **) &agent->e, sizeof(double),
1416       ((s->networks_count * RIL_FEATURES_NETWORK_COUNT) + (address_index * RIL_FEATURES_ADDRESS_COUNT)), RIL_FEATURES_ADDRESS_COUNT, agent->m);
1417   agent->m = m_new;
1418   agent->n = n_new;
1419
1420   LOG (GNUNET_ERROR_TYPE_DEBUG, "address was used: %s\n", address_was_used ? "yes" : "no");
1421
1422   if (address_was_used)
1423   {
1424     net = address->solver_information;
1425     net->bw_in_assigned -= agent->bw_in;
1426     net->bw_out_assigned -= agent->bw_out;
1427
1428     if (NULL != agent->addresses_head) //if peer has an address left, use it
1429     {
1430       LOG (GNUNET_ERROR_TYPE_DEBUG, "address left: %p\n", agent->addresses_head->address_naked->addr);
1431       //TODO? check if network/bandwidth update can be done more clever/elegant at different function
1432       envi_set_active_suggestion (s, agent, agent->addresses_head->address_naked, min_bw, min_bw, GNUNET_NO);
1433       net = agent->addresses_head->address_naked->solver_information;
1434       net->bw_in_assigned -= min_bw;
1435       net->bw_out_assigned -= min_bw;
1436     }
1437     else
1438     {
1439       LOG (GNUNET_ERROR_TYPE_DEBUG, "no address left => disconnect\n");
1440
1441       envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
1442     }
1443   }
1444
1445   LOG(GNUNET_ERROR_TYPE_DEBUG, "Address deleted\n");
1446 }
1447
1448 /**
1449  * Transport properties for this address have changed
1450  *
1451  * @param solver solver handle
1452  * @param address the address
1453  * @param type the ATSI type in HBO
1454  * @param abs_value the absolute value of the property
1455  * @param rel_value the normalized value
1456  */
1457 void
1458 GAS_ril_address_property_changed (void *solver,
1459     struct ATS_Address *address,
1460     uint32_t type,
1461     uint32_t abs_value,
1462     double rel_value)
1463 {
1464   LOG(GNUNET_ERROR_TYPE_DEBUG,
1465       "API_address_property_changed() Property '%s' for peer '%s' address %p changed "
1466           "to %.2f \n", GNUNET_ATS_print_property_type (type), GNUNET_i2s (&address->peer),
1467       address->addr, rel_value);
1468   /*
1469    * Nothing to do here, properties are considered in every reward calculation
1470    */
1471 }
1472
1473 /**
1474  * Transport session for this address has changed
1475  *
1476  * NOTE: values in addresses are already updated
1477  *
1478  * @param solver solver handle
1479  * @param address the address
1480  * @param cur_session the current session
1481  * @param new_session the new session
1482  */
1483 void
1484 GAS_ril_address_session_changed (void *solver,
1485     struct ATS_Address *address,
1486     uint32_t cur_session,
1487     uint32_t new_session)
1488 {
1489   //TODO? consider session changed in solver behaviour
1490   /*
1491    * Potentially add session activity as a feature in state vector
1492    */
1493   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_session_changed()\n");
1494 }
1495
1496 /**
1497  * Usage for this address has changed
1498  *
1499  * NOTE: values in addresses are already updated
1500  *
1501  * @param solver solver handle
1502  * @param address the address
1503  * @param in_use usage state
1504  */
1505 void
1506 GAS_ril_address_inuse_changed (void *solver, struct ATS_Address *address, int in_use)
1507 {
1508   //TODO! consider address_inuse_changed according to matthias' email
1509   /**
1510    * See matthias' email
1511    */
1512   LOG(GNUNET_ERROR_TYPE_DEBUG,
1513       "API_address_inuse_changed() Usage for %s address of peer '%s' changed to %s\n",
1514       address->plugin, GNUNET_i2s (&address->peer), (GNUNET_YES == in_use) ? "USED" : "UNUSED");
1515 }
1516
1517 /**
1518  * Network scope for this address has changed
1519  *
1520  * NOTE: values in addresses are already updated
1521  *
1522  * @param solver solver handle
1523  * @param address the address
1524  * @param current_network the current network
1525  * @param new_network the new network
1526  */
1527 void
1528 GAS_ril_address_change_network (void *solver,
1529     struct ATS_Address *address,
1530     uint32_t current_network,
1531     uint32_t new_network)
1532 {
1533   struct GAS_RIL_Handle *s = solver;
1534   struct RIL_Peer_Agent *agent;
1535   struct RIL_Network *net;
1536   uint32_t min_bw = ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__);
1537
1538   LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_change_network() Network type changed, moving "
1539       "%s address of peer %s from '%s' to '%s'\n",
1540       (GNUNET_YES == address->active) ? "active" : "inactive", GNUNET_i2s (&address->peer),
1541       GNUNET_ATS_print_network_type (current_network), GNUNET_ATS_print_network_type (new_network));
1542
1543   if (address->active && !ril_network_is_active (solver, new_network))
1544   {
1545     GAS_ril_address_delete (solver, address, GNUNET_NO);
1546     return;
1547   }
1548
1549   agent = ril_get_agent (s, &address->peer, GNUNET_NO);
1550   if (NULL == agent)
1551   {
1552     //no agent there yet, so add as if address is new
1553     address->solver_information = ril_get_network (s, new_network);
1554     GAS_ril_address_add (s, address, new_network);
1555     return;
1556   }
1557
1558   net = ril_get_network (s, current_network);
1559   net->bw_in_assigned -= agent->bw_in;
1560   net->bw_out_assigned -= agent->bw_out;
1561
1562   net = ril_get_network (s, new_network);
1563   net->bw_in_assigned -= min_bw;
1564   net->bw_out_assigned -= min_bw;
1565   address->solver_information = net;
1566 }
1567
1568 /**
1569  * Get application feedback for a peer
1570  *
1571  * @param solver the solver handle
1572  * @param application the application
1573  * @param peer the peer to change the preference for
1574  * @param scope the time interval for this feedback: [now - scope .. now]
1575  * @param kind the kind to change the preference
1576  * @param score the score
1577  */
1578 void
1579 GAS_ril_address_preference_feedback (void *solver,
1580     void *application,
1581     const struct GNUNET_PeerIdentity *peer,
1582     const struct GNUNET_TIME_Relative scope,
1583     enum GNUNET_ATS_PreferenceKind kind,
1584     double score)
1585 {
1586   //TODO! collect reward until next reward calculation
1587   LOG(GNUNET_ERROR_TYPE_DEBUG,
1588       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
1589           "preference %s for %d seconds\n", GNUNET_i2s (peer), "UNKNOWN",
1590       GNUNET_ATS_print_preference_type (kind), scope.rel_value_us / 1000000);
1591 }
1592
1593 /**
1594  * Start a bulk operation
1595  *
1596  * @param solver the solver
1597  */
1598 void
1599 GAS_ril_bulk_start (void *solver)
1600 {
1601   //TODO? consideration: keep bulk counter and stop agents during bulk
1602   /*
1603    * bulk counter up, but not really relevant, because there is no complete calculation of the
1604    * bandwidth assignment triggered anyway. Therefore, changes to addresses can come and go as
1605    * they want. Consideration: Step-pause during bulk-start-stop period...
1606    */
1607
1608   //LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_start()\n");
1609 }
1610
1611 /**
1612  * Bulk operation done
1613  */
1614 void
1615 GAS_ril_bulk_stop (void *solver)
1616 {
1617   //TODO? consideration: keep bulk counter and stop agents during bulk
1618   /*
1619    * bulk counter down, see bulk_start()
1620    */
1621
1622   //LOG(GNUNET_ERROR_TYPE_DEBUG, "API_bulk_stop()\n");
1623 }
1624
1625 /**
1626  * Get the preferred address for a specific peer
1627  *
1628  * @param solver the solver handle
1629  * @param peer the identity of the peer
1630  */
1631 const struct ATS_Address *
1632 GAS_ril_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
1633 {
1634   /*
1635    * activate agent, return currently chosen address
1636    */
1637   struct GAS_RIL_Handle *s = solver;
1638   struct RIL_Peer_Agent *agent;
1639
1640   agent = ril_get_agent (s, peer, GNUNET_YES);
1641
1642   agent->active = GNUNET_YES;
1643
1644   envi_set_active_suggestion(s, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);
1645
1646   if (agent->address_inuse)
1647   {
1648     LOG(GNUNET_ERROR_TYPE_DEBUG,
1649         "API_get_preferred_address() Activated agent for peer '%s' with %s address %p\n",
1650         GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
1651   }
1652   else
1653   {
1654     LOG(GNUNET_ERROR_TYPE_DEBUG,
1655             "API_get_preferred_address() Activated agent for peer '%s', but no address available\n", GNUNET_i2s (peer));
1656   }
1657
1658   return agent->address_inuse;
1659 }
1660
1661 /**
1662  * Stop notifying about address and bandwidth changes for this peer
1663  *
1664  * @param solver the solver handle
1665  * @param peer the peer
1666  */
1667 void
1668 GAS_ril_stop_get_preferred_address (void *solver, const struct GNUNET_PeerIdentity *peer)
1669 {
1670   struct GAS_RIL_Handle *s = solver;
1671   struct RIL_Peer_Agent *agent;
1672
1673   agent = ril_get_agent (s, peer, GNUNET_NO);
1674
1675   if (NULL == agent)
1676   {
1677     GNUNET_break(0);
1678     return;
1679   }
1680   if (GNUNET_NO == agent->active)
1681   {
1682     GNUNET_break(0);
1683     return;
1684   }
1685
1686   agent->active = GNUNET_NO;
1687   envi_set_active_suggestion(s, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);
1688
1689   LOG(GNUNET_ERROR_TYPE_DEBUG,
1690       "API_stop_get_preferred_address() Paused agent for peer '%s' with %s address\n",
1691       GNUNET_i2s (peer), agent->address_inuse->plugin);
1692 }
1693
1694 /* end of gnunet-service-ats-solver_ril.c */