aboutsummaryrefslogtreecommitdiff
path: root/src/ats/plugin_ats_ril.c
blob: eac62c4404ada32af30847b08b4e4cf1c368b461 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
/*
 This file is part of GNUnet.
 Copyright (C) 2011-2014 GNUnet e.V.

 GNUnet is free software; you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published
 by the Free Software Foundation; either version 3, or (at your
 option) any later version.

 GNUnet is distributed in the hope that it will be useful, but
 WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with GNUnet; see the file COPYING.  If not, write to the
 Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 Boston, MA 02110-1301, USA.
 */

/**
 * @file ats/plugin_ats_ril.c
 * @brief ATS reinforcement learning solver
 * @author Fabian Oehlmann
 * @author Matthias Wachs
 */
#include "platform.h"
#include <float.h>
#include <math.h>
#include "gnunet_ats_plugin.h"
#include "gnunet-service-ats_addresses.h"



#define LOG(kind,...) GNUNET_log_from (kind, "ats-ril",__VA_ARGS__)

#define RIL_MIN_BW                      (5 * ntohl (GNUNET_CONSTANTS_DEFAULT_BW_IN_OUT.value__))
#define RIL_MAX_BW                      GNUNET_ATS_MaxBandwidth

#define RIL_ACTION_INVALID              -1
#define RIL_INTERVAL_EXPONENT           10
#define RIL_UTILITY_DELAY_MAX           1000

#define RIL_DEFAULT_STEP_TIME_MIN       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 200)
#define RIL_DEFAULT_STEP_TIME_MAX       GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MILLISECONDS, 2000)
#define RIL_DEFAULT_ALGORITHM           RIL_ALGO_SARSA
#define RIL_DEFAULT_SELECT              RIL_SELECT_SOFTMAX
#define RIL_DEFAULT_WELFARE             RIL_WELFARE_NASH
#define RIL_DEFAULT_DISCOUNT_BETA       0.6
#define RIL_DEFAULT_DISCOUNT_GAMMA      0.5
#define RIL_DEFAULT_GRADIENT_STEP_SIZE  0.01
#define RIL_DEFAULT_TRACE_DECAY         0.5
#define RIL_DEFAULT_EXPLORE_RATIO       1
#define RIL_DEFAULT_EXPLORE_DECAY       0.95
#define RIL_DEFAULT_RBF_DIVISOR         50
#define RIL_DEFAULT_TEMPERATURE         0.1
#define RIL_DEFAULT_TEMPERATURE_DECAY   1

#define RIL_INC_DEC_STEP_SIZE           1
#define RIL_NOP_DECAY                   0.5

/**
 * ATS reinforcement learning solver
 *
 * General description
 */

/**
 * The actions, how an agent can manipulate the current assignment. I.e. how the bandwidth can be
 * changed for the currently chosen address. Not depicted in the enum are the actions of switching
 * to a particular address. The action of switching to address with index i is depicted by the
 * number (RIL_ACTION_TYPE_NUM + i).
 */
enum RIL_Action_Type
{
  RIL_ACTION_NOTHING = 0,
  RIL_ACTION_BW_IN_DBL = -2, //TODO? Potentially add more actions
  RIL_ACTION_BW_IN_HLV = -3,
  RIL_ACTION_BW_IN_INC = 1,
  RIL_ACTION_BW_IN_DEC = 2,
  RIL_ACTION_BW_OUT_DBL = -4,
  RIL_ACTION_BW_OUT_HLV = -5,
  RIL_ACTION_BW_OUT_INC = 3,
  RIL_ACTION_BW_OUT_DEC = 4,
  RIL_ACTION_TYPE_NUM = 5
};

enum RIL_Algorithm
{
  RIL_ALGO_SARSA = 0,
  RIL_ALGO_Q = 1
};

enum RIL_Select
{
  RIL_SELECT_SOFTMAX = 0,
  RIL_SELECT_EGREEDY = 1
};

enum RIL_Welfare
{
  RIL_WELFARE_NASH,
  RIL_WELFARE_EGALITARIAN
};

enum RIL_E_Modification
{
  RIL_E_DECAY,
  RIL_E_ZERO,
  RIL_E_ACCUMULATE,
  RIL_E_REPLACE
};

/**
 * Global learning parameters
 */
struct RIL_Learning_Parameters
{
  /**
   * The TD-algorithm to use
   */
  enum RIL_Algorithm algorithm;

  /**
   * Gradient-descent step-size
   */
  double alpha;

  /**
   * Learning discount variable in the TD-update for semi-MDPs
   */
  double beta;

  /**
   * Learning discount factor in the TD-update for MDPs
   */
  double gamma;

  /**
   * Trace-decay factor for eligibility traces
   */
  double lambda;

  /**
   * Whether to accumulate or replace eligibility traces
   */
  enum RIL_E_Modification eligibility_trace_mode;

  /**
   * Initial softmax action-selection temperature
   */
  double temperature_init;

  /**
   * Softmax action-selection temperature
   */
  double temperature;

  /**
   * Decay factor of the temperature value
   */
  double temperature_decay;

  /**
   * Which measure of social welfare should be used
   */
  enum RIL_Welfare social_welfare;

  /**
   * State space divisor
   */
  unsigned long long rbf_divisor;

  /**
   * Action selection strategy;
   */
  enum RIL_Select select;

  /**
   * Initial exploration ratio value
   */
  double epsilon_init;

  /**
   * Ratio, with what probability an agent should explore in the e-greed policy
   */
  double epsilon;

  /**
   * Decay factor of the explore ratio
   */
  double epsilon_decay;

  /**
   * Minimal interval time between steps in milliseconds
   */
  struct GNUNET_TIME_Relative step_time_min;

  /**
   * Maximum interval time between steps in milliseconds
   */
  struct GNUNET_TIME_Relative step_time_max;
};

/**
 * Wrapper for addresses to store them in agent's linked list
 */
struct RIL_Address_Wrapped
{
  /**
   * Next in DLL
   */
  struct RIL_Address_Wrapped *next;

  /**
   * Previous in DLL
   */
  struct RIL_Address_Wrapped *prev;

  /**
   * The address
   */
  struct ATS_Address *address_naked;
};


struct RIL_Peer_Agent
{
  /**
   * Next agent in solver's linked list
   */
  struct RIL_Peer_Agent *next;

  /**
   * Previous agent in solver's linked list
   */
  struct RIL_Peer_Agent *prev;

  /**
   * Environment handle
   */
  struct GAS_RIL_Handle *envi;

  /**
   * Peer ID
   */
  struct GNUNET_PeerIdentity peer;

  /**
   * Whether the agent is active or not
   */
  int is_active;

  /**
   * Number of performed time-steps
   */
  unsigned long long step_count;

  /**
   * Experience matrix W
   */
  double ** W;

  /**
   * Number of rows of W / Number of state-vector features
   */
  unsigned int m;

  /**
   * Number of columns of W / Number of actions
   */
  unsigned int n;

  /**
   * Last perceived state feature vector
   */
  double *s_old;

  /**
   * Last chosen action
   */
  int a_old;

  /**
   * Eligibility traces
   */
  double ** E;

  /**
   * Whether to reset the eligibility traces to 0 after a Q-exploration step
   */
  int eligibility_reset;

  /**
   * Address in use
   */
  struct ATS_Address *address_inuse;

  /**
   * Head of addresses DLL
   */
  struct RIL_Address_Wrapped *addresses_head;

  /**
   * Tail of addresses DLL
   */
  struct RIL_Address_Wrapped *addresses_tail;

  /**
   * Inbound bandwidth assigned by the agent
   */
  uint32_t bw_in;

  /**
   * Outbound bandwidth assigned by the agent
   */
  uint32_t bw_out;

  /**
   * Flag whether a suggestion has to be issued
   */
  int suggestion_issue;

  /**
   * The address which has to be issued
   */
  struct ATS_Address *suggestion_address;

  /**
   * The agent's last objective value
   */
  double objective_old;

  /**
   * NOP bonus
   */
  double nop_bonus;
};

struct RIL_Scope
{
  /**
   * ATS network type
   */
  enum GNUNET_ATS_Network_Type type;

  /**
   * Total available inbound bandwidth
   */
  uint32_t bw_in_available;

  /**
   * Bandwidth inbound assigned in network after last step
   */
  uint32_t bw_in_assigned;

  /**
   * Bandwidth inbound actually utilized in the network
   */
  uint32_t bw_in_utilized;

  /**
   * Total available outbound bandwidth
   */
  uint32_t bw_out_available;

  /**
   * Bandwidth outbound assigned in network after last step
   */
  unsigned long long bw_out_assigned;

  /**
   * Bandwidth outbound actually utilized in the network
   */
  unsigned long long bw_out_utilized;

  /**
   * Number of active agents in scope
   */
  unsigned int active_agent_count;

  /**
   * The social welfare achieved in the scope
   */
  double social_welfare;
};

/**
 * A handle for the reinforcement learning solver
 */
struct GAS_RIL_Handle
{
  /**
   * The solver-plugin environment of the solver-plugin API
   */
  struct GNUNET_ATS_PluginEnvironment *env;

  /**
   * Number of performed steps
   */
  unsigned long long step_count;

  /**
   * Timestamp for the last time-step
   */
  struct GNUNET_TIME_Absolute step_time_last;

  /**
   * Task identifier of the next time-step to be executed
   */
  struct GNUNET_SCHEDULER_Task * step_next_task_id;

  /**
   * Variable discount factor, dependent on time between steps
   */
  double global_discount_variable;

  /**
   * Integrated variable discount factor, dependent on time between steps
   */
  double global_discount_integrated;

  /**
   * Lock for bulk operations
   */
  int bulk_lock;

  /**
   * Number of changes during a lock
   */
  int bulk_changes;

  /**
   * Learning parameters
   */
  struct RIL_Learning_Parameters parameters;

  /**
   * Array of networks with global assignment state
   */
  struct RIL_Scope * network_entries;

  /**
   * Networks count
   */
  unsigned int networks_count;

  /**
   * List of active peer-agents
   */
  struct RIL_Peer_Agent * agents_head;
  struct RIL_Peer_Agent * agents_tail;

  /**
   * Shutdown
   */
  int done;

  /**
   * Simulate steps, i.e. schedule steps immediately
   */
  unsigned long long simulate;
};

/*
 *  "Private" functions
 *  ---------------------------
 */

/**
 * Estimate the current action-value for state s and action a
 *
 * @param agent agent performing the estimation
 * @param state s
 * @param action a
 * @return estimation value
 */
static double
agent_q (struct RIL_Peer_Agent *agent,
         const double *state,
         int action)
{
  unsigned int i;
  double result = 0.0;

  for (i = 0; i < agent->m; i++)
    result += state[i] * agent->W[action][i];

  /* prevent crashes if learning diverges */
  if (isnan(result))
      return isnan(result) * UINT32_MAX;
  if (isinf(result))
    return isinf(result) * UINT32_MAX;
  return result;
}


/**
 * Get the index of the address in the agent's list.
 *
 * @param agent agent handle
 * @param address address handle
 * @return the index, starting with zero
 */
static int
agent_address_get_index (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
{
  int i;
  struct RIL_Address_Wrapped *cur;

  i = -1;
  for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
  {
    i++;
    if (cur->address_naked == address)
      return i;
  }
  return i;
}


/**
 * Gets the wrapped address from the agent's list
 *
 * @param agent agent handle
 * @param address address handle
 * @return wrapped address
 */
static struct RIL_Address_Wrapped *
agent_address_get_wrapped (struct RIL_Peer_Agent *agent, struct ATS_Address *address)
{
  struct RIL_Address_Wrapped *cur;

  for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
    if (cur->address_naked == address)
      return cur;
  return NULL;
}


static int
agent_action_is_possible (struct RIL_Peer_Agent *agent, int action)
{
  int address_index;

  switch (action)
  {
  case RIL_ACTION_NOTHING:
    return GNUNET_YES;
    break;
  case RIL_ACTION_BW_IN_INC:
  case RIL_ACTION_BW_IN_DBL:
    if (agent->bw_in >= RIL_MAX_BW)
      return GNUNET_NO;
    else
      return GNUNET_YES;
    break;
  case RIL_ACTION_BW_IN_DEC:
  case RIL_ACTION_BW_IN_HLV:
    if (agent->bw_in <= 0)
      return GNUNET_NO;
    else
      return GNUNET_YES;
    break;
  case RIL_ACTION_BW_OUT_INC:
  case RIL_ACTION_BW_OUT_DBL:
    if (agent->bw_out >= RIL_MAX_BW)
      return GNUNET_NO;
    else
      return GNUNET_YES;
    break;
  case RIL_ACTION_BW_OUT_DEC:
  case RIL_ACTION_BW_OUT_HLV:
    if (agent->bw_out <= 0)
      return GNUNET_NO;
    else
      return GNUNET_YES;
    break;
  default:
    if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
    {
      address_index = action - RIL_ACTION_TYPE_NUM;

      GNUNET_assert(address_index >= 0);
      GNUNET_assert(
          address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));

      if ((agent_address_get_index(agent, agent->address_inuse) == address_index) ||
          agent->address_inuse->active)
        return GNUNET_NO;
      else
        return GNUNET_YES;
      break;
    }
    // error - action does not exist
    GNUNET_assert(GNUNET_NO);
  }
}


/**
 * Gets the action, with the maximal estimated Q-value (i.e. the one currently estimated to bring the
 * most reward in the future)
 *
 * @param agent agent performing the calculation
 * @param state the state from which to take the action
 * @return the action promising most future reward
 */
static int
agent_get_action_max (struct RIL_Peer_Agent *agent, double *state)
{
  int i;
  int max_i = RIL_ACTION_INVALID;
  double cur_q;
  double max_q = -DBL_MAX;

  for (i = 0; i < agent->n; i++)
  {
    if (agent_action_is_possible(agent, i))
    {
      cur_q = agent_q (agent, state, i);
      if (cur_q > max_q)
      {
        max_q = cur_q;
        max_i = i;
      }
    }
  }

  GNUNET_assert(RIL_ACTION_INVALID != max_i);

  return max_i;
}

/**
 * Chooses a random action from the set of possible ones
 *
 * @param agent the agent performing the action
 * @return the action index
 */
static int
agent_get_action_random (struct RIL_Peer_Agent *agent)
{
  int i;
  int is_possible[agent->n];
  int sum = 0;
  int r;

  for (i = 0; i<agent->n; i++)
  {
    if (agent_action_is_possible(agent, i))
    {
      is_possible[i] = GNUNET_YES;
      sum++;
    }
    else
    {
      is_possible[i] = GNUNET_NO;
    }
  }

  r = GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK, sum);

  sum = -1;
  for (i = 0; i<agent->n; i++)
  {
    if (is_possible[i])
    {
      sum++;
      if (sum == r)
        return i;
    }
  }

  GNUNET_assert(GNUNET_NO);
  return RIL_ACTION_INVALID;
}


/**
 * Updates the weights (i.e. coefficients) of the weight vector in matrix W for action a
 *
 * @param agent the agent performing the update
 * @param reward the reward received for the last action
 * @param s_next the new state, the last step got the agent into
 * @param a_prime the new
 */
static void
agent_update (struct RIL_Peer_Agent *agent, double reward, double *s_next, int a_prime)
{
  int i;
  int k;
  double delta;
  double **theta = agent->W;

  delta = agent->envi->global_discount_integrated * reward; //reward
  delta += agent->envi->global_discount_variable * agent_q (agent, s_next, a_prime); //discounted future value
  delta -= agent_q (agent, agent->s_old, agent->a_old); //one step

//  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",
//      agent->step_count,
//      agent_q (agent, agent->s_old, agent->a_old),
//      agent->envi->parameters.alpha,
//      reward,
//      agent->envi->global_discount_variable,
//      agent_q (agent, s_next, a_prime),
//      delta);

  for (k = 0; k < agent->n; k++)
  {
    for (i = 0; i < agent->m; i++)
    {
  //    LOG(GNUNET_ERROR_TYPE_INFO, "alpha = %f   delta = %f   e[%d] = %f\n",
  //        agent->envi->parameters.alpha,
  //        delta,
  //        i,
  //        agent->e[i]);
      theta[k][i] += agent->envi->parameters.alpha * delta * agent->E[k][i];
    }
  }
}


/**
 * Changes the eligibility trace vector e in various manners:
 * #RIL_E_ACCUMULATE - adds @a feature to each component as in accumulating eligibility traces
 * #RIL_E_REPLACE - resets each component to @a feature  as in replacing traces
 * #RIL_E_DECAY - multiplies e with discount factor and lambda as in the update rule
 * #RIL_E_ZERO - sets e to 0 as in Watkin's Q-learning algorithm when exploring and when initializing
 *
 * @param agent the agent handle
 * @param mod the kind of modification
 * @param feature the feature vector
 * @param action the action to take
 */
static void
agent_modify_eligibility (struct RIL_Peer_Agent *agent,
                          enum RIL_E_Modification mod,
                          double *feature,
                          int action)
{
  int i;
  int k;

  for (i = 0; i < agent->m; i++)
  {
    switch (mod)
    {
    case RIL_E_ACCUMULATE:
      agent->E[action][i] += feature[i];
      break;
    case RIL_E_REPLACE:
      agent->E[action][i] = agent->E[action][i] > feature[i] ? agent->E[action][i] : feature[i];
      break;
    case RIL_E_DECAY:
      for (k = 0; k < agent->n; k++)
      {
        agent->E[k][i] *= agent->envi->global_discount_variable * agent->envi->parameters.lambda;
      }
      break;
    case RIL_E_ZERO:
      for (k = 0; k < agent->n; k++)
      {
        agent->E[k][i] = 0;
      }
      break;
    }
  }
}

/**
 * Informs the environment about the status of the solver
 *
 * @param solver
 * @param op
 * @param stat
 */
static void
ril_inform (struct GAS_RIL_Handle *solver,
            enum GAS_Solver_Operation op,
            enum GAS_Solver_Status stat)
{
  solver->env->info_cb (solver->env->cls,
                        op,
                        stat,
                        GAS_INFO_NONE);
}

/**
 * Calculates the maximum bandwidth an agent can assign in a network scope
 *
 * @param net
 */
static unsigned long long
ril_get_max_bw (struct RIL_Scope *net)
{
  return GNUNET_MIN(2 * GNUNET_MAX(net->bw_in_available, net->bw_out_available), GNUNET_ATS_MaxBandwidth);
}

/**
 * Changes the active assignment suggestion of the handler and invokes the bw_changed callback to
 * notify ATS of its new decision
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param new_address the address which is to be used
 * @param new_bw_in the new amount of inbound bandwidth set for this address
 * @param new_bw_out the new amount of outbound bandwidth set for this address
 * @param silent disables invocation of the bw_changed callback, if #GNUNET_YES
 */
static void
envi_set_active_suggestion (struct GAS_RIL_Handle *solver,
    struct RIL_Peer_Agent *agent,
    struct ATS_Address *new_address,
    unsigned long long new_bw_in,
    unsigned long long new_bw_out,
    int silent)
{
  int notify = GNUNET_NO;

  LOG(GNUNET_ERROR_TYPE_DEBUG,
      "    set_active_suggestion() for peer '%s'\n",
      GNUNET_i2s (&agent->peer));

  //address change
  if (agent->address_inuse != new_address)
  {
    if (NULL != agent->address_inuse)
    {
      agent->address_inuse->active = GNUNET_NO;
      agent->address_inuse->assigned_bw_in = 0;
      agent->address_inuse->assigned_bw_out = 0;
    }
    if (NULL != new_address)
    {
      LOG(GNUNET_ERROR_TYPE_DEBUG, "    set address active: %s\n", agent->is_active ? "yes" : "no");
      new_address->active = agent->is_active;
      new_address->assigned_bw_in = agent->bw_in;
      new_address->assigned_bw_out = agent->bw_out;
    }
    notify |= GNUNET_YES;
  }

  if (new_address)
  {
    //activity change
    if (new_address->active != agent->is_active)
    {
      new_address->active = agent->is_active;
      notify |= GNUNET_YES;
    }

    //bw change
    if (agent->bw_in != new_bw_in)
    {
      agent->bw_in = new_bw_in;
      new_address->assigned_bw_in = new_bw_in;
      notify |= GNUNET_YES;
    }
    if (agent->bw_out != new_bw_out)
    {
      agent->bw_out = new_bw_out;
      new_address->assigned_bw_out = new_bw_out;
      notify |= GNUNET_YES;
    }
  }

  if (notify && agent->is_active && (GNUNET_NO == silent))
  {
    if (new_address)
    {
      LOG(GNUNET_ERROR_TYPE_DEBUG, "    envi_set_active_suggestion() notify\n");
      agent->suggestion_issue = GNUNET_YES;
      agent->suggestion_address = new_address;
    }
    else if (agent->address_inuse)
    {
      /* disconnect case, no new address */
      GNUNET_assert(0 ==  agent->address_inuse->assigned_bw_in);
      GNUNET_assert(0 == agent->address_inuse->assigned_bw_out);
      agent->bw_in = 0;
      agent->bw_out = 0;

      agent->suggestion_issue = GNUNET_YES;
      agent->suggestion_address = agent->address_inuse;
    }
  }
  agent->address_inuse = new_address;
}


/**
 * Allocates a state vector and fills it with the features present
 * @param solver the solver handle
 * @param agent the agent handle
 * @return pointer to the state vector
 */
static double *
envi_get_state (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
{
  double *state;
  double y[2];
  double x[2];
  double d[2];
  double sigma;
  double f;
  int m;
  int i;
  int k;
  unsigned long long max_bw;

  state = GNUNET_malloc (sizeof(double) * agent->m);

  max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);

  y[0] = (double) agent->bw_out;
  y[1] = (double) agent->bw_in;

  m = agent_address_get_index (agent, agent->address_inuse) * (solver->parameters.rbf_divisor+1) * (solver->parameters.rbf_divisor+1);
  for (i = 0; i <= solver->parameters.rbf_divisor; i++)
  {
    for (k = 0; k <= solver->parameters.rbf_divisor; k++)
    {
      x[0] = (double) i * (double) max_bw / (double) solver->parameters.rbf_divisor;
      x[1] = (double) k * (double) max_bw / (double) solver->parameters.rbf_divisor;
      d[0] = x[0]-y[0];
      d[1] = x[1]-y[1];
      sigma = (((double) max_bw / ((double) solver->parameters.rbf_divisor + 1)) * 0.5);
      f = exp(-((d[0]*d[0] + d[1]*d[1]) / (2 * sigma * sigma)));
      state[m++] = f;
    }
  }

  return state;
}


/**
 * Returns the utility value of the connection an agent manages
 *
 * @param agent the agent in question
 * @return the utility value
 */
static double
agent_get_utility (struct RIL_Peer_Agent *agent)
{
  const double *preferences;
  double delay_atsi;
  double delay_norm;
  double pref_match;

  preferences = agent->envi->env->get_preferences (agent->envi->env->cls,
                                                   &agent->peer);

  delay_atsi = agent->address_inuse->norm_delay.norm;
  delay_norm = RIL_UTILITY_DELAY_MAX*exp(-delay_atsi*0.00001);

  pref_match = preferences[GNUNET_ATS_PREFERENCE_LATENCY] * delay_norm;
  pref_match += preferences[GNUNET_ATS_PREFERENCE_BANDWIDTH] *
      sqrt((double) (agent->bw_in/RIL_MIN_BW) * (double) (agent->bw_out/RIL_MIN_BW));
  return pref_match;
}

/**
 * Calculates the social welfare within a network scope according to what social
 * welfare measure is set in the configuration.
 *
 * @param solver the solver handle
 * @param scope the network scope in question
 * @return the social welfare value
 */
static double
ril_network_get_social_welfare (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope)
{
  struct RIL_Peer_Agent *cur;
  double result;

  switch (solver->parameters.social_welfare)
  {
  case RIL_WELFARE_EGALITARIAN:
    result = DBL_MAX;
    for (cur = solver->agents_head; NULL != cur; cur = cur->next)
    {
      if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope))
      {
        result = GNUNET_MIN(result, agent_get_utility(cur));
      }
    }
    return result;

  case RIL_WELFARE_NASH:
    result = 0;
    for (cur = solver->agents_head; NULL != cur; cur = cur->next)
    {
      if (cur->is_active && cur->address_inuse && (cur->address_inuse->solver_information == scope))
      {
        result *= pow(agent_get_utility(cur), 1.0 / (double) scope->active_agent_count);
      }
    }
    return result;
  }
  GNUNET_assert(GNUNET_NO);
  return 1;
}

static double
envi_get_penalty (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
{
  struct RIL_Scope *net;
  unsigned long long over_max;
  unsigned long long over_in = 0;
  unsigned long long over_out = 0;

  net = agent->address_inuse->solver_information;

  if (net->bw_in_utilized > net->bw_in_available)
  {
    over_in = net->bw_in_utilized - net->bw_in_available;
    if (RIL_ACTION_BW_IN_INC == agent->a_old)
    {
      /* increase quadratically */
      over_in *= over_in;
    }
  }
  if (net->bw_out_utilized > net->bw_out_available)
  {
    over_out = net->bw_out_utilized - net->bw_out_available;
    if (RIL_ACTION_BW_OUT_INC == agent->a_old)
    {
      /* increase quadratically */
      over_out *= over_out;
    }
  }
  over_max = (over_in + over_out) / (RIL_MIN_BW * RIL_MIN_BW);

  return -1.0 * (double) over_max;
}

/**
 * Gets the reward for the last performed step, which is calculated in equal
 * parts from the local (the peer specific) and the global (for all peers
 * identical) reward.
 *
 * @param solver the solver handle
 * @param agent the agent handle
 * @return the reward
 */
static double
envi_get_reward (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
{
  struct RIL_Scope *net;
  double objective;
  double delta;
  double steady;
  double penalty;
  double reward;

  net = agent->address_inuse->solver_information;

  penalty = envi_get_penalty(solver, agent);
  objective = (agent_get_utility (agent) + net->social_welfare) / 2;
  delta = objective - agent->objective_old;
  agent->objective_old = objective;

  if (delta != 0 && penalty == 0)
  {
    agent->nop_bonus = delta * RIL_NOP_DECAY;
  }
  else
  {
    agent->nop_bonus *= RIL_NOP_DECAY;
  }

  steady = (RIL_ACTION_NOTHING == agent->a_old) ? agent->nop_bonus : 0;

  reward = delta + steady;
  return reward + penalty;
}

/**
 * Doubles the bandwidth for the active address
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise the outbound bandwidth
 */
static void
envi_action_bw_double (struct GAS_RIL_Handle *solver,
    struct RIL_Peer_Agent *agent,
    int direction_in)
{
  unsigned long long new_bw;
  unsigned long long max_bw;

  max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);

  if (direction_in)
  {
    new_bw = agent->bw_in * 2;
    if (new_bw < agent->bw_in || new_bw > max_bw)
      new_bw = max_bw;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
        agent->bw_out, GNUNET_NO);
  }
  else
  {
    new_bw = agent->bw_out * 2;
    if (new_bw < agent->bw_out || new_bw > max_bw)
      new_bw = max_bw;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
        new_bw, GNUNET_NO);
  }
}

/**
 * Cuts the bandwidth for the active address in half. The least amount of bandwidth suggested, is
 * the minimum bandwidth for a peer, in order to not invoke a disconnect.
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
 * bandwidth
 */
static void
envi_action_bw_halven (struct GAS_RIL_Handle *solver,
    struct RIL_Peer_Agent *agent,
    int direction_in)
{
  unsigned long long new_bw;

  if (direction_in)
  {
    new_bw = agent->bw_in / 2;
    if (new_bw <= 0 || new_bw > agent->bw_in)
      new_bw = 0;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
        GNUNET_NO);
  }
  else
  {
    new_bw = agent->bw_out / 2;
    if (new_bw <= 0 || new_bw > agent->bw_out)
      new_bw = 0;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
        GNUNET_NO);
  }
}

/**
 * Increases the bandwidth by 5 times the minimum bandwidth for the active address.
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
 * bandwidth
 */
static void
envi_action_bw_inc (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
{
  unsigned long long new_bw;
  unsigned long long max_bw;

  max_bw = ril_get_max_bw((struct RIL_Scope *) agent->address_inuse->solver_information);

  if (direction_in)
  {
    new_bw = agent->bw_in + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
    if (new_bw < agent->bw_in || new_bw > max_bw)
      new_bw = max_bw;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw,
        agent->bw_out, GNUNET_NO);
  }
  else
  {
    new_bw = agent->bw_out + (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
    if (new_bw < agent->bw_out || new_bw > max_bw)
      new_bw = max_bw;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in,
        new_bw, GNUNET_NO);
  }
}

/**
 * Decreases the bandwidth by 5 times the minimum bandwidth for the active address. The least amount
 * of bandwidth suggested, is the minimum bandwidth for a peer, in order to not invoke a disconnect.
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param direction_in if GNUNET_YES, change inbound bandwidth, otherwise change the outbound
 * bandwidth
 */
static void
envi_action_bw_dec (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int direction_in)
{
  unsigned long long new_bw;

  if (direction_in)
  {
    new_bw = agent->bw_in - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
    if (new_bw <= 0 || new_bw > agent->bw_in)
      new_bw = 0;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, new_bw, agent->bw_out,
        GNUNET_NO);
  }
  else
  {
    new_bw = agent->bw_out - (RIL_INC_DEC_STEP_SIZE * RIL_MIN_BW);
    if (new_bw <= 0 || new_bw > agent->bw_out)
      new_bw = 0;
    envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, new_bw,
        GNUNET_NO);
  }
}

/**
 * Switches to the address given by its index
 *
 * @param solver solver handle
 * @param agent agent handle
 * @param address_index index of the address as it is saved in the agent's list, starting with zero
 */
static void
envi_action_address_switch (struct GAS_RIL_Handle *solver,
    struct RIL_Peer_Agent *agent,
    unsigned int address_index)
{
  struct RIL_Address_Wrapped *cur;
  int i = 0;

  //cur = agent_address_get_wrapped(agent, agent->address_inuse);

  for (cur = agent->addresses_head; NULL != cur; cur = cur->next)
  {
    if (i == address_index)
    {
      envi_set_active_suggestion (solver, agent, cur->address_naked, agent->bw_in, agent->bw_out,
          GNUNET_NO);
      return;
    }

    i++;
  }

  //no address with address_index exists, in this case this action should not be callable
  GNUNET_assert(GNUNET_NO);
}

/**
 * Puts the action into effect by calling the according function
 *
 * @param solver the solver handle
 * @param agent the action handle
 * @param action the action to perform by the solver
 */
static void
envi_do_action (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int action)
{
  int address_index;

  switch (action)
  {
  case RIL_ACTION_NOTHING:
    break;
  case RIL_ACTION_BW_IN_DBL:
    envi_action_bw_double (solver, agent, GNUNET_YES);
    break;
  case RIL_ACTION_BW_IN_HLV:
    envi_action_bw_halven (solver, agent, GNUNET_YES);
    break;
  case RIL_ACTION_BW_IN_INC:
    envi_action_bw_inc (solver, agent, GNUNET_YES);
    break;
  case RIL_ACTION_BW_IN_DEC:
    envi_action_bw_dec (solver, agent, GNUNET_YES);
    break;
  case RIL_ACTION_BW_OUT_DBL:
    envi_action_bw_double (solver, agent, GNUNET_NO);
    break;
  case RIL_ACTION_BW_OUT_HLV:
    envi_action_bw_halven (solver, agent, GNUNET_NO);
    break;
  case RIL_ACTION_BW_OUT_INC:
    envi_action_bw_inc (solver, agent, GNUNET_NO);
    break;
  case RIL_ACTION_BW_OUT_DEC:
    envi_action_bw_dec (solver, agent, GNUNET_NO);
    break;
  default:
    if ((action >= RIL_ACTION_TYPE_NUM) && (action < agent->n)) //switch address action
    {
      address_index = action - RIL_ACTION_TYPE_NUM;

      GNUNET_assert(address_index >= 0);
      GNUNET_assert(
          address_index <= agent_address_get_index (agent, agent->addresses_tail->address_naked));

      envi_action_address_switch (solver, agent, address_index);
      break;
    }
    // error - action does not exist
    GNUNET_assert(GNUNET_NO);
  }
}

/**
 * Selects the next action using the e-greedy strategy. I.e. with a probability
 * of (1-e) the action with the maximum expected return will be chosen
 * (=> exploitation) and with probability (e) a random action will be chosen.
 * In case the Q-learning rule is set, the function also resets the eligibility
 * traces in the exploration case (after Watkin's Q-learning).
 *
 * @param agent the agent selecting an action
 * @param state the current state-feature vector
 * @return the action index
 */
static int
agent_select_egreedy (struct RIL_Peer_Agent *agent, double *state)
{
  int action;
  double r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
        UINT32_MAX) / (double) UINT32_MAX;

  if (r < agent->envi->parameters.epsilon) //explore
  {
    action = agent_get_action_random(agent);
    if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
    {
      agent->eligibility_reset = GNUNET_YES;
    }
    agent->envi->parameters.epsilon *= agent->envi->parameters.epsilon_decay;
    return action;
  }
  else //exploit
  {
    action = agent_get_action_max(agent, state);
    return action;
  }
}

/**
 * Selects the next action with a probability corresponding to its value. The
 * probability is calculated using a Boltzmann distribution with a temperature
 * value. The higher the temperature, the more are the action selection
 * probabilities the same. With a temperature of 0, the selection is greedy,
 * i.e. always the action with the highest value is chosen.
 * @param agent
 * @param state
 * @return
 */
static int
agent_select_softmax (struct RIL_Peer_Agent *agent, double *state)
{
  int i;
  int a_max;
  double eqt[agent->n];
  double p[agent->n];
  double sum = 0;
  double r;

  a_max = agent_get_action_max(agent, state);

  for (i=0; i<agent->n; i++)
  {
    if (agent_action_is_possible(agent, i))
    {
      eqt[i] = exp(agent_q(agent,state,i) / agent->envi->parameters.temperature);
      if (isinf (eqt[i]))
        eqt[i] = isinf(eqt[i]) * UINT32_MAX;
      sum += eqt[i];
    }
  }
  for (i=0; i<agent->n; i++)
  {
    if (agent_action_is_possible(agent, i))
    {
      p[i] = eqt[i]/sum;
    }
    else
    {
      p[i] = 0;
    }
  }
  r = (double) GNUNET_CRYPTO_random_u32 (GNUNET_CRYPTO_QUALITY_WEAK,
      UINT32_MAX) / (double) UINT32_MAX;
  sum = 0;
  for (i=0; i<agent->n; i++)
  {
    if (sum + p[i] > r)
    {
      if (i != a_max)
      {
        if (RIL_ALGO_Q == agent->envi->parameters.algorithm)
          agent->eligibility_reset = GNUNET_YES;
        agent->envi->parameters.temperature *= agent->envi->parameters.temperature_decay;
      }
      return i;
    }
    sum += p[i];
  }
  GNUNET_assert(GNUNET_NO);
  return RIL_ACTION_INVALID;
}

/**
 * Select the next action of an agent either according to the e-greedy strategy
 * or the softmax strategy.
 *
 * @param agent the agent in question
 * @param state the current state-feature vector
 * @return the action index
 */
static int
agent_select_action (struct RIL_Peer_Agent *agent, double *state)
{
  if (agent->envi->parameters.select == RIL_SELECT_EGREEDY)
  {
    return agent_select_egreedy(agent, state);
  }
  else
  {
    return agent_select_softmax(agent, state);
  }
}

/**
 * Performs one step of the Markov Decision Process. Other than in the literature the step starts
 * after having done the last action a_old. It observes the new state s_next and the reward
 * received. Then the coefficient update is done according to the SARSA or Q-learning method. The
 * next action is put into effect.
 *
 * @param agent the agent performing the step
 */
static void
agent_step (struct RIL_Peer_Agent *agent)
{
  int a_next = RIL_ACTION_INVALID;
  int a_max;
  double *s_next;
  double reward;

  LOG(GNUNET_ERROR_TYPE_DEBUG, "    agent_step() Peer '%s', algorithm %s\n",
      GNUNET_i2s (&agent->peer),
      agent->envi->parameters.algorithm ? "Q" : "SARSA");

  s_next = envi_get_state (agent->envi, agent);
  reward = envi_get_reward (agent->envi, agent);

  if (agent->eligibility_reset)
  {
    agent_modify_eligibility(agent, RIL_E_ZERO, NULL, -1);
    agent->eligibility_reset = GNUNET_NO;
  }
  else
  {
    agent_modify_eligibility (agent, RIL_E_DECAY, NULL, -1);
  }
  if (RIL_ACTION_INVALID != agent->a_old)
  {
    agent_modify_eligibility (agent, agent->envi->parameters.eligibility_trace_mode, agent->s_old, agent->a_old);
  }

  switch (agent->envi->parameters.algorithm)
  {
  case RIL_ALGO_SARSA:
    a_next = agent_select_action (agent, s_next);
    if (RIL_ACTION_INVALID != agent->a_old)
    {
      //updates weights with selected action (on-policy), if not first step
      agent_update (agent, reward, s_next, a_next);
    }
    break;

  case RIL_ALGO_Q:
    a_max = agent_get_action_max (agent, s_next);
    if (RIL_ACTION_INVALID != agent->a_old)
    {
      //updates weights with best action, disregarding actually selected action (off-policy), if not first step
      agent_update (agent, reward, s_next, a_max);
    }
    a_next = agent_select_action (agent, s_next);
    break;
  }

  GNUNET_assert(RIL_ACTION_INVALID != a_next);

  LOG (GNUNET_ERROR_TYPE_DEBUG, "step()  Step# %llu  R: %f  IN %llu  OUT %llu  A: %d\n",
        agent->step_count,
        reward,
        agent->bw_in/1024,
        agent->bw_out/1024,
        a_next);

  envi_do_action (agent->envi, agent, a_next);

  GNUNET_free(agent->s_old);
  agent->s_old = s_next;
  agent->a_old = a_next;

  agent->step_count += 1;
}

/**
 * Prototype of the ril_step() procedure
 *
 * @param solver the solver handle
 */
static void
ril_step (struct GAS_RIL_Handle *solver);


/**
 * Task for the scheduler, which performs one step and lets the solver know that
 * no further step is scheduled.
 *
 * @param cls the solver handle
 */
static void
ril_step_scheduler_task (void *cls)
{
  struct GAS_RIL_Handle *solver = cls;

  solver->step_next_task_id = NULL;
  ril_step (solver);
}

/**
 * Determines how much of the available bandwidth is assigned. If more is
 * assigned than available it returns 1. The function is used to determine the
 * step size of the adaptive stepping.
 *
 * @param solver the solver handle
 * @return the ratio
 */
static double
ril_get_used_resource_ratio (struct GAS_RIL_Handle *solver)
{
  int i;
  struct RIL_Scope net;
  unsigned long long sum_assigned = 0;
  unsigned long long sum_available = 0;
  double ratio;

  for (i = 0; i < solver->networks_count; i++)
  {
    net = solver->network_entries[i];
    if (net.bw_in_assigned > 0) //only consider scopes where an address is actually active
    {
      sum_assigned += net.bw_in_utilized;
      sum_assigned += net.bw_out_utilized;
      sum_available += net.bw_in_available;
      sum_available += net.bw_out_available;
    }
  }
  if (sum_available > 0)
  {
    ratio = ((double) sum_assigned) / ((double) sum_available);
  }
  else
  {
    ratio = 0;
  }

  return ratio > 1 ? 1 : ratio; //overutilization is possible, cap at 1
}

/**
 * Lookup network struct by type
 *
 * @param s the solver handle
 * @param type the network type
 * @return the network struct
 */
static struct RIL_Scope *
ril_get_network (struct GAS_RIL_Handle *s, uint32_t type)
{
  int i;

  for (i = 0; i < s->networks_count; i++)
  {
    if (s->network_entries[i].type == type)
    {
      return &s->network_entries[i];
    }
  }
  return NULL ;
}

/**
 * Determines whether more connections are allocated in a network scope, than
 * they would theoretically fit. This is used as a heuristic to determine,
 * whether a new connection can be allocated or not.
 *
 * @param solver the solver handle
 * @param network the network scope in question
 * @return GNUNET_YES if there are theoretically enough resources left
 */
static int
ril_network_is_not_full (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
{
  struct RIL_Scope *net;
  struct RIL_Peer_Agent *agent;
  unsigned long long address_count = 0;

  for (agent = solver->agents_head; NULL != agent; agent = agent->next)
  {
    if (agent->address_inuse && agent->is_active)
    {
      net = agent->address_inuse->solver_information;
      if (net->type == network)
      {
        address_count++;
      }
    }
  }

  net = ril_get_network (solver, network);
  return (net->bw_in_available > RIL_MIN_BW * address_count) && (net->bw_out_available > RIL_MIN_BW * address_count);
}

/**
 * Unblocks an agent for which a connection request is there, that could not
 * be satisfied. Iterates over the addresses of the agent, if one of its
 * addresses can now be allocated in its scope the agent is unblocked,
 * otherwise it remains unchanged.
 *
 * @param solver the solver handle
 * @param agent the agent in question
 * @param silent
 */
static void
ril_try_unblock_agent (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent, int silent)
{
  struct RIL_Address_Wrapped *addr_wrap;
  struct RIL_Scope *net;
  unsigned long long start_in;
  unsigned long long start_out;

  for (addr_wrap = agent->addresses_head; NULL != addr_wrap; addr_wrap = addr_wrap->next)
  {
    net = addr_wrap->address_naked->solver_information;
    if (ril_network_is_not_full(solver, net->type))
    {
      if (NULL == agent->address_inuse)
      {
        start_in = net->bw_in_available < net->bw_in_utilized ? (net->bw_in_available - net->bw_in_utilized) / 2 : RIL_MIN_BW;
        start_out = net->bw_out_available < net->bw_out_utilized ? (net->bw_out_available - net->bw_out_utilized) / 2 : RIL_MIN_BW;
        envi_set_active_suggestion (solver, agent, addr_wrap->address_naked, start_in, start_out, silent);
      }
      return;
    }
  }
  agent->address_inuse = NULL;
}

/**
 * Determines how much the reward needs to be discounted depending on the amount
 * of time, which has passed since the last time-step.
 *
 * @param solver the solver handle
 */
static void
ril_calculate_discount (struct GAS_RIL_Handle *solver)
{
  struct GNUNET_TIME_Absolute time_now;
  struct GNUNET_TIME_Relative time_delta;
  double tau;

  // MDP case only for debugging purposes
  if (solver->simulate)
  {
    solver->global_discount_variable = solver->parameters.gamma;
    solver->global_discount_integrated = 1;
    return;
  }

  // semi-MDP case

  //calculate tau, i.e. how many real valued time units have passed, one time unit is one minimum time step
  time_now = GNUNET_TIME_absolute_get ();
  time_delta = GNUNET_TIME_absolute_get_difference (solver->step_time_last, time_now);
  solver->step_time_last = time_now;
  tau = (double) time_delta.rel_value_us
      / (double) solver->parameters.step_time_min.rel_value_us;

  //calculate reward discounts (once per step for all agents)
  solver->global_discount_variable = pow (M_E, ((-1.0) * ((double) solver->parameters.beta) * tau));
  solver->global_discount_integrated = (1.0 - solver->global_discount_variable)
      / (double) solver->parameters.beta;
}

/**
 * Count the number of active agents/connections in a network scope
 *
 * @param solver the solver handle
 * @param scope the network scope in question
 * @return the number of allocated connections
 */
static int
ril_network_count_active_agents (struct GAS_RIL_Handle *solver, struct RIL_Scope *scope)
{
  int c = 0;
  struct RIL_Peer_Agent *cur_agent;

  for (cur_agent = solver->agents_head; NULL != cur_agent; cur_agent = cur_agent->next)
  {
    if (cur_agent->is_active && cur_agent->address_inuse && (cur_agent->address_inuse->solver_information == scope))
    {
      c++;
    }
  }
  return c;
}

/**
 * Calculates how much bandwidth is assigned in sum in a network scope, either
 * in the inbound or in the outbound direction.
 *
 * @param solver the solver handle
 * @param type the type of the network scope in question
 * @param direction_in GNUNET_YES if the inbound direction should be summed up,
 *   otherwise the outbound direction will be summed up
 * @return the sum of the assigned bandwidths
 */
static unsigned long long
ril_network_get_assigned (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
{
  struct RIL_Peer_Agent *cur;
  struct RIL_Scope *net;
  unsigned long long sum = 0;

  for (cur = solver->agents_head; NULL != cur; cur = cur->next)
  {
    if (cur->is_active && cur->address_inuse)
    {
      net = cur->address_inuse->solver_information;
      if (net->type == type)
      {
        if (direction_in)
          sum += cur->bw_in;
        else
          sum += cur->bw_out;
      }
    }
  }

  return sum;
}

/**
 * Calculates how much bandwidth is actually utilized in sum in a network scope,
 * either in the inbound or in the outbound direction.
 *
 * @param solver the solver handle
 * @param type the type of the network scope in question
 * @param direction_in GNUNET_YES if the inbound direction should be summed up,
 *   otherwise the outbound direction will be summed up
 * @return the sum of the utilized bandwidths (in bytes/second)
 */
static unsigned long long
ril_network_get_utilized (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type type, int direction_in)
{
  struct RIL_Peer_Agent *cur;
  struct RIL_Scope *net;
  unsigned long long sum = 0;

  for (cur = solver->agents_head; NULL != cur; cur = cur->next)
  {
    if (cur->is_active && cur->address_inuse)
    {
      net = cur->address_inuse->solver_information;
      if (net->type == type)
      {
        if (direction_in)
          sum += cur->address_inuse->norm_utilization_in.norm;
        else
          sum += cur->address_inuse->norm_utilization_out.norm;
      }
    }
  }

  return sum;
}

/**
 * Retrieves the state of the network scope, so that its attributes are up-to-
 * date.
 *
 * @param solver the solver handle
 */
static void
ril_networks_update_state (struct GAS_RIL_Handle *solver)
{
  int c;
  struct RIL_Scope *net;

  for (c = 0; c < solver->networks_count; c++)
  {
    net = &solver->network_entries[c];
    net->bw_in_assigned = ril_network_get_assigned(solver, net->type, GNUNET_YES);
    net->bw_in_utilized = ril_network_get_utilized(solver, net->type, GNUNET_YES);
    net->bw_out_assigned = ril_network_get_assigned(solver, net->type, GNUNET_NO);
    net->bw_out_utilized = ril_network_get_utilized(solver, net->type, GNUNET_NO);
    net->active_agent_count = ril_network_count_active_agents(solver, net);
    net->social_welfare = ril_network_get_social_welfare(solver, net);
  }
}

/**
 * Schedules the next global step in an adaptive way. The more resources are
 * left, the earlier the next step is scheduled. This serves the reactivity of
 * the solver to changed inputs.
 *
 * @param solver the solver handle
 */
static void
ril_step_schedule_next (struct GAS_RIL_Handle *solver)
{
  double used_ratio;
  double factor;
  double y;
  double offset;
  struct GNUNET_TIME_Relative time_next;

  used_ratio = ril_get_used_resource_ratio (solver);

  GNUNET_assert(
      solver->parameters.step_time_min.rel_value_us
          <= solver->parameters.step_time_max.rel_value_us);

  factor = (double) GNUNET_TIME_relative_subtract (solver->parameters.step_time_max,
      solver->parameters.step_time_min).rel_value_us;
  offset = (double) solver->parameters.step_time_min.rel_value_us;
  y = factor * pow (used_ratio, RIL_INTERVAL_EXPONENT) + offset;

  GNUNET_assert(y <= (double) solver->parameters.step_time_max.rel_value_us);
  GNUNET_assert(y >= (double) solver->parameters.step_time_min.rel_value_us);

  time_next = GNUNET_TIME_relative_multiply (GNUNET_TIME_UNIT_MICROSECONDS, (unsigned long long) y);

//  LOG (GNUNET_ERROR_TYPE_INFO, "ratio: %f, factor: %f, offset: %f, y: %f\n",
//      used_ratio,
//      factor,
//      offset,
//      y);

  if (solver->simulate)
  {
    time_next = GNUNET_TIME_UNIT_ZERO;
  }

  if ((NULL == solver->step_next_task_id) && (GNUNET_NO == solver->done))
  {
    solver->step_next_task_id = GNUNET_SCHEDULER_add_delayed (time_next, &ril_step_scheduler_task,
          solver);
  }
}

/**
 * Triggers one step per agent
 *
 * @param solver
 */
static void
ril_step (struct GAS_RIL_Handle *solver)
{
  struct RIL_Peer_Agent *cur;

  if (GNUNET_YES == solver->bulk_lock)
  {
    solver->bulk_changes++;
    return;
  }

  ril_inform (solver, GAS_OP_SOLVE_START, GAS_STAT_SUCCESS);

  LOG(GNUNET_ERROR_TYPE_DEBUG, "    RIL step number %d\n", solver->step_count);

  if (0 == solver->step_count)
  {
    solver->step_time_last = GNUNET_TIME_absolute_get ();
  }

  ril_calculate_discount (solver);
  ril_networks_update_state (solver);

  //trigger one step per active, unblocked agent
  for (cur = solver->agents_head; NULL != cur; cur = cur->next)
  {
    if (cur->is_active)
    {
      if (NULL == cur->address_inuse)
      {
        ril_try_unblock_agent(solver, cur, GNUNET_NO);
      }
      if (cur->address_inuse)
      {
        agent_step (cur);
      }
    }
  }

  ril_networks_update_state (solver);

  solver->step_count++;
  ril_step_schedule_next (solver);

  ril_inform (solver, GAS_OP_SOLVE_STOP, GAS_STAT_SUCCESS);

  ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_START, GAS_STAT_SUCCESS);
  for (cur = solver->agents_head; NULL != cur; cur = cur->next)
  {
    if (cur->suggestion_issue) {
      solver->env->bandwidth_changed_cb (solver->env->cls,
                                         cur->suggestion_address);
      cur->suggestion_issue = GNUNET_NO;
    }
  }
  ril_inform (solver, GAS_OP_SOLVE_UPDATE_NOTIFICATION_STOP, GAS_STAT_SUCCESS);
}

/**
 * Initializes the matrix W of parameter vectors theta with small random numbers.
 *
 * @param agent The respective agent
 */
static void
agent_w_init (struct RIL_Peer_Agent *agent)
{
  int i;
  int k;

  for (i = 0; i < agent->n; i++)
  {
    for (k = 0; k < agent->m; k++)
    {
      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));
    }
  }
}

/**
 * Initialize an agent without addresses and its knowledge base
 *
 * @param s ril solver
 * @param peer the one in question
 * @return handle to the new agent
 */
static struct RIL_Peer_Agent *
agent_init (void *s, const struct GNUNET_PeerIdentity *peer)
{
  int i;
  struct GAS_RIL_Handle * solver = s;
  struct RIL_Peer_Agent * agent = GNUNET_new (struct RIL_Peer_Agent);

  agent->envi = solver;
  agent->peer = *peer;
  agent->step_count = 0;
  agent->is_active = GNUNET_NO;
  agent->bw_in = RIL_MIN_BW;
  agent->bw_out = RIL_MIN_BW;
  agent->suggestion_issue = GNUNET_NO;
  agent->n = RIL_ACTION_TYPE_NUM;
  agent->m = 0;
  agent->W = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
  agent->E = (double **) GNUNET_malloc (sizeof (double *) * agent->n);
  for (i = 0; i < agent->n; i++)
  {
    agent->W[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
    agent->E[i] = (double *) GNUNET_malloc (sizeof (double) * agent->m);
  }
  agent_w_init(agent);
  agent->eligibility_reset = GNUNET_NO;
  agent->a_old = RIL_ACTION_INVALID;
  agent->s_old = GNUNET_malloc (sizeof (double) * agent->m);
  agent->address_inuse = NULL;
  agent->objective_old = 0;
  agent->nop_bonus = 0;

  return agent;
}

/**
 * Deallocate agent
 *
 * @param solver the solver handle
 * @param agent the agent to retire
 */
static void
agent_die (struct GAS_RIL_Handle *solver, struct RIL_Peer_Agent *agent)
{
  int i;

  for (i = 0; i < agent->n; i++)
  {
    GNUNET_free_non_null(agent->W[i]);
    GNUNET_free_non_null(agent->E[i]);
  }
  GNUNET_free_non_null(agent->W);
  GNUNET_free_non_null(agent->E);
  GNUNET_free_non_null(agent->s_old);
  GNUNET_free(agent);
}

/**
 * Returns the agent for a peer
 *
 * @param solver the solver handle
 * @param peer the identity of the peer
 * @param create whether or not to create an agent, if none is allocated yet
 * @return the agent
 */
static struct RIL_Peer_Agent *
ril_get_agent (struct GAS_RIL_Handle *solver, const struct GNUNET_PeerIdentity *peer, int create)
{
  struct RIL_Peer_Agent *cur;

  for (cur = solver->agents_head; NULL != cur; cur = cur->next)
  {
    if (0 == memcmp (peer, &cur->peer, sizeof(struct GNUNET_PeerIdentity)))
    {
      return cur;
    }
  }

  if (create)
  {
    cur = agent_init (solver, peer);
    GNUNET_CONTAINER_DLL_insert_tail(solver->agents_head, solver->agents_tail, cur);
    return cur;
  }
  return NULL ;
}

/**
 * Determine whether at least the minimum bandwidth is set for the network. Otherwise the network is
 * considered inactive and not used. Addresses in an inactive network are ignored.
 *
 * @param solver solver handle
 * @param network the network type
 * @return whether or not the network is considered active
 */
static int
ril_network_is_active (struct GAS_RIL_Handle *solver, enum GNUNET_ATS_Network_Type network)
{
  struct RIL_Scope *net;

  net = ril_get_network (solver, network);
  return net->bw_out_available >= RIL_MIN_BW;
}

/**
 * Cuts a slice out of a vector of elements. This is used to decrease the size of the matrix storing
 * the reward function approximation. It copies the memory, which is not cut, to the new vector,
 * frees the memory of the old vector, and redirects the pointer to the new one.
 *
 * @param old pointer to the pointer to the first element of the vector
 * @param element_size byte size of the vector elements
 * @param hole_start the first element to cut out
 * @param hole_length the number of elements to cut out
 * @param old_length the length of the old vector
 */
static void
ril_cut_from_vector (void **old,
    size_t element_size,
    unsigned int hole_start,
    unsigned int hole_length,
    unsigned int old_length)
{
  char *tmpptr;
  char *oldptr = (char *) *old;
  size_t size;
  unsigned int bytes_before;
  unsigned int bytes_hole;
  unsigned int bytes_after;

  GNUNET_assert(old_length >= hole_length);
  GNUNET_assert(old_length >= (hole_start + hole_length));

  size = element_size * (old_length - hole_length);

  bytes_before = element_size * hole_start;
  bytes_hole = element_size * hole_length;
  bytes_after = element_size * (old_length - hole_start - hole_length);

  if (0 == size)
  {
    tmpptr = NULL;
  }
  else
  {
    tmpptr = GNUNET_malloc (size);
    GNUNET_memcpy (tmpptr, oldptr, bytes_before);
    GNUNET_memcpy (tmpptr + bytes_before, oldptr + (bytes_before + bytes_hole), bytes_after);
  }
  if (NULL != *old)
  {
    GNUNET_free(*old);
  }
  *old = (void *) tmpptr;
}

/*
 *  Solver API functions
 *  ---------------------------
 */

/**
 * Change relative preference for quality in solver
 *
 * @param solver the solver handle
 * @param peer the peer to change the preference for
 * @param kind the kind to change the preference
 * @param pref_rel the normalized preference value for this kind over all clients
 */
static void
GAS_ril_address_change_preference (void *solver,
				   const struct GNUNET_PeerIdentity *peer,
				   enum GNUNET_ATS_PreferenceKind kind,
				   double pref_rel)
{
  LOG(GNUNET_ERROR_TYPE_DEBUG,
      "API_address_change_preference() Preference '%s' for peer '%s' changed to %.2f \n",
      GNUNET_ATS_print_preference_type (kind), GNUNET_i2s (peer), pref_rel);

  struct GAS_RIL_Handle *s = solver;

  s->parameters.temperature = s->parameters.temperature_init;
  s->parameters.epsilon = s->parameters.epsilon_init;
  ril_step (s);
}


/**
 * Add a new address for a peer to the solver
 *
 * The address is already contained in the addresses hashmap!
 *
 * @param solver the solver Handle
 * @param address the address to add
 * @param network network type of this address
 */
static void
GAS_ril_address_add (void *solver,
		     struct ATS_Address *address,
		     uint32_t network)
{
  struct GAS_RIL_Handle *s = solver;
  struct RIL_Peer_Agent *agent;
  struct RIL_Address_Wrapped *address_wrapped;
  struct RIL_Scope *net;
  unsigned int m_new;
  unsigned int m_old;
  unsigned int n_new;
  unsigned int n_old;
  int i;
  unsigned int zero;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_address_add()\n");

  net = ril_get_network (s, network);
  address->solver_information = net;

  if (!ril_network_is_active (s, network))
  {
    LOG(GNUNET_ERROR_TYPE_DEBUG,
        "API_address_add() Did not add %s address %s for peer '%s', network does not have enough bandwidth\n",
        address->plugin, address->addr, GNUNET_i2s (&address->peer));
    return;
  }

  s->parameters.temperature = s->parameters.temperature_init;
  s->parameters.epsilon = s->parameters.epsilon_init;

  agent = ril_get_agent (s, &address->peer, GNUNET_YES);

  //add address
  address_wrapped = GNUNET_new (struct RIL_Address_Wrapped);
  address_wrapped->address_naked = address;
  GNUNET_CONTAINER_DLL_insert_tail(agent->addresses_head, agent->addresses_tail, address_wrapped);

  //increase size of W
  m_new = agent->m + ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1));
  m_old = agent->m;
  n_new = agent->n + 1;
  n_old = agent->n;

  GNUNET_array_grow(agent->W, agent->n, n_new);
  agent->n = n_old;
  GNUNET_array_grow(agent->E, agent->n, n_new);
  for (i = 0; i < n_new; i++)
  {
    if (i < n_old)
    {
      agent->m = m_old;
      GNUNET_array_grow(agent->W[i], agent->m, m_new);
      agent->m = m_old;
      GNUNET_array_grow(agent->E[i], agent->m, m_new);
    }
    else
    {
      zero = 0;
      GNUNET_array_grow(agent->W[i], zero, m_new);
      zero = 0;
      GNUNET_array_grow(agent->E[i], zero, m_new);
    }
  }

  //increase size of old state vector
  agent->m = m_old;
  GNUNET_array_grow(agent->s_old, agent->m, m_new);

  ril_try_unblock_agent(s, agent, GNUNET_NO);

  ril_step (s);

  LOG(GNUNET_ERROR_TYPE_DEBUG, "API_address_add() Added %s %s address %s for peer '%s'\n",
      address->active ? "active" : "inactive", address->plugin, address->addr,
      GNUNET_i2s (&address->peer));
}

/**
 * Delete an address in the solver
 *
 * The address is not contained in the address hashmap anymore!
 *
 * @param solver the solver handle
 * @param address the address to remove
 */
static void
GAS_ril_address_delete (void *solver,
			struct ATS_Address *address)
{
  struct GAS_RIL_Handle *s = solver;
  struct RIL_Peer_Agent *agent;
  struct RIL_Address_Wrapped *address_wrapped;
  int address_index;
  unsigned int m_new;
  unsigned int n_new;
  int i;
  struct RIL_Scope *net;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_address_delete() Delete %s %s address %s for peer '%s'\n",
       address->active ? "active" : "inactive",
       address->plugin,
       address->addr,
       GNUNET_i2s (&address->peer));

  agent = ril_get_agent (s, &address->peer, GNUNET_NO);
  if (NULL == agent)
  {
    net = address->solver_information;
    GNUNET_assert(! ril_network_is_active (s, net->type));
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "No agent allocated for peer yet, since address was in inactive network\n");
    return;
  }

  s->parameters.temperature = s->parameters.temperature_init;
  s->parameters.epsilon = s->parameters.epsilon_init;

  address_index = agent_address_get_index (agent, address);
  address_wrapped = agent_address_get_wrapped (agent, address);

  if (NULL == address_wrapped)
  {
    net = address->solver_information;
    LOG (GNUNET_ERROR_TYPE_DEBUG,
         "Address not considered by agent, address was in inactive network\n");
    return;
  }
  GNUNET_CONTAINER_DLL_remove (agent->addresses_head,
                               agent->addresses_tail,
                               address_wrapped);
  GNUNET_free (address_wrapped);

  //decrease W
  m_new = agent->m - ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1));
  n_new = agent->n - 1;

  for (i = 0; i < agent->n; i++)
  {
    ril_cut_from_vector ((void **) &agent->W[i], sizeof(double),
        address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
        ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
    ril_cut_from_vector ((void **) &agent->E[i], sizeof(double),
        address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
        ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
  }
  GNUNET_free_non_null(agent->W[RIL_ACTION_TYPE_NUM + address_index]);
  GNUNET_free_non_null(agent->E[RIL_ACTION_TYPE_NUM + address_index]);
  ril_cut_from_vector ((void **) &agent->W, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
      1, agent->n);
  ril_cut_from_vector ((void **) &agent->E, sizeof(double *), RIL_ACTION_TYPE_NUM + address_index,
      1, agent->n);
  //correct last action
  if (agent->a_old > (RIL_ACTION_TYPE_NUM + address_index))
  {
    agent->a_old -= 1;
  }
  else if (agent->a_old == (RIL_ACTION_TYPE_NUM + address_index))
  {
    agent->a_old = RIL_ACTION_INVALID;
  }
  //decrease old state vector
  ril_cut_from_vector ((void **) &agent->s_old, sizeof(double),
                       address_index * ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)),
                       ((s->parameters.rbf_divisor+1) * (s->parameters.rbf_divisor+1)), agent->m);
  agent->m = m_new;
  agent->n = n_new;

  if (agent->address_inuse == address)
  {
    if (NULL != agent->addresses_head) //if peer has an address left, use it
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Active address died, suggesting alternative!\n");
      envi_set_active_suggestion (s,
                                  agent,
                                  agent->addresses_head->address_naked,
                                  agent->bw_in,
                                  agent->bw_out,
                                  GNUNET_YES);
    }
    else
    {
      GNUNET_log (GNUNET_ERROR_TYPE_DEBUG,
                  "Active address died, suggesting disconnect!\n");
      envi_set_active_suggestion (s, agent, NULL, 0, 0, GNUNET_NO);
    }
  }
  ril_step (solver);
  if (agent->suggestion_address == address)
  {
    agent->suggestion_issue = GNUNET_NO;
    agent->suggestion_address = NULL;
  }
  GNUNET_assert (agent->address_inuse != address);
}


/**
 * Update the properties of an address in the solver
 *
 * @param solver solver handle
 * @param address the address
 */
static void
GAS_ril_address_property_changed (void *solver,
				  struct ATS_Address *address)
{
  struct GAS_RIL_Handle *s = solver;

  LOG(GNUNET_ERROR_TYPE_DEBUG,
      "Properties for peer '%s' address changed\n",
      GNUNET_i2s (&address->peer));
  s->parameters.temperature = s->parameters.temperature_init;
  s->parameters.epsilon = s->parameters.epsilon_init;
  ril_step (s);
}


/**
 * Give feedback about the current assignment
 *
 * @param solver the solver handle
 * @param application the application
 * @param peer the peer to change the preference for
 * @param scope the time interval for this feedback: [now - scope .. now]
 * @param kind the kind to change the preference
 * @param score the score
 */
static void
GAS_ril_address_preference_feedback (void *solver,
                                     struct GNUNET_SERVER_Client *application,
                                     const struct GNUNET_PeerIdentity *peer,
                                     const struct GNUNET_TIME_Relative scope,
                                     enum GNUNET_ATS_PreferenceKind kind,
                                     double score)
{
  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_address_preference_feedback() Peer '%s' got a feedback of %+.3f from application %s for "
       "preference %s for %d seconds\n",
       GNUNET_i2s (peer),
       "UNKNOWN",
       GNUNET_ATS_print_preference_type (kind),
       scope.rel_value_us / 1000000);
}


/**
 * Start a bulk operation
 *
 * @param solver the solver
 */
static void
GAS_ril_bulk_start (void *solver)
{
  struct GAS_RIL_Handle *s = solver;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_bulk_start() lock: %d\n", s->bulk_lock+1);

  s->bulk_lock++;
}


/**
 * Bulk operation done
 *
 * @param solver the solver handle
 */
static void
GAS_ril_bulk_stop (void *solver)
{
  struct GAS_RIL_Handle *s = solver;

  LOG(GNUNET_ERROR_TYPE_DEBUG,
      "API_bulk_stop() lock: %d\n",
      s->bulk_lock - 1);

  if (s->bulk_lock < 1)
  {
    GNUNET_break(0);
    return;
  }
  s->bulk_lock--;

  if (0 < s->bulk_changes)
  {
    ril_step (solver);
    s->bulk_changes = 0;
  }
}


/**
 * Tell solver to notify ATS if the address to use changes for a specific
 * peer using the bandwidth changed callback
 *
 * The solver must only notify about changes for peers with pending address
 * requests!
 *
 * @param solver the solver handle
 * @param peer the identity of the peer
 */
static void
GAS_ril_get_preferred_address (void *solver,
			       const struct GNUNET_PeerIdentity *peer)
{
  struct GAS_RIL_Handle *s = solver;
  struct RIL_Peer_Agent *agent;

  LOG(GNUNET_ERROR_TYPE_DEBUG, "API_get_preferred_address()\n");

  agent = ril_get_agent (s, peer, GNUNET_YES);

  agent->is_active = GNUNET_YES;
  envi_set_active_suggestion (solver, agent, agent->address_inuse, agent->bw_in, agent->bw_out, GNUNET_YES);

  ril_try_unblock_agent(solver, agent, GNUNET_YES);

  if (agent->address_inuse)
  {
    LOG(GNUNET_ERROR_TYPE_DEBUG,
        "API_get_preferred_address() Activated agent for peer '%s' with %s address %s\n",
        GNUNET_i2s (peer), agent->address_inuse->plugin, agent->address_inuse->addr);
  }
  else
  {
    LOG(GNUNET_ERROR_TYPE_DEBUG,
        "API_get_preferred_address() Activated agent for peer '%s', but no address available\n",
        GNUNET_i2s (peer));
    s->parameters.temperature = s->parameters.temperature_init;
    s->parameters.epsilon = s->parameters.epsilon_init;
  }
  if (NULL != agent->address_inuse)
    s->env->bandwidth_changed_cb (s->env->cls,
                                  agent->address_inuse);
}


/**
 * Tell solver stop notifying ATS about changes for this peers
 *
 * The solver must only notify about changes for peers with pending address
 * requests!
 *
 * @param solver the solver handle
 * @param peer the peer
 */
static void
GAS_ril_stop_get_preferred_address (void *solver,
				    const struct GNUNET_PeerIdentity *peer)
{
  struct GAS_RIL_Handle *s = solver;
  struct RIL_Peer_Agent *agent;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_stop_get_preferred_address()");

  agent = ril_get_agent (s, peer, GNUNET_NO);

  if (NULL == agent)
  {
    GNUNET_break(0);
    return;
  }
  if (GNUNET_NO == agent->is_active)
  {
    GNUNET_break(0);
    return;
  }

  s->parameters.temperature = s->parameters.temperature_init;
  s->parameters.epsilon = s->parameters.epsilon_init;

  agent->is_active = GNUNET_NO;

  envi_set_active_suggestion (s, agent, agent->address_inuse, agent->bw_in, agent->bw_out,
      GNUNET_YES);

  ril_step (s);

  LOG(GNUNET_ERROR_TYPE_DEBUG,
      "API_stop_get_preferred_address() Paused agent for peer '%s'\n",
      GNUNET_i2s (peer));
}


/**
 * Entry point for the plugin
 *
 * @param cls pointer to the 'struct GNUNET_ATS_PluginEnvironment'
 */
void *
libgnunet_plugin_ats_ril_init (void *cls)
{
  static struct GNUNET_ATS_SolverFunctions sf;
  struct GNUNET_ATS_PluginEnvironment *env = cls;
  struct GAS_RIL_Handle *solver = GNUNET_new (struct GAS_RIL_Handle);
  struct RIL_Scope * cur;
  int c;
  char *string;
  float f_tmp;

  LOG (GNUNET_ERROR_TYPE_DEBUG,
       "API_init() Initializing RIL solver\n");

  GNUNET_assert (NULL != env);
  GNUNET_assert (NULL != env->cfg);
  GNUNET_assert (NULL != env->stats);
  GNUNET_assert (NULL != env->bandwidth_changed_cb);
  GNUNET_assert (NULL != env->get_preferences);

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number(env->cfg, "ats", "RIL_RBF_DIVISOR", &solver->parameters.rbf_divisor))
  {
    solver->parameters.rbf_divisor = RIL_DEFAULT_RBF_DIVISOR;
  }

  if (GNUNET_OK
      != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MIN",
          &solver->parameters.step_time_min))
  {
    solver->parameters.step_time_min = RIL_DEFAULT_STEP_TIME_MIN;
  }

  if (GNUNET_OK
      != GNUNET_CONFIGURATION_get_value_time (env->cfg, "ats", "RIL_STEP_TIME_MAX",
          &solver->parameters.step_time_max))
  {
    solver->parameters.step_time_max = RIL_DEFAULT_STEP_TIME_MAX;
  }

  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_ALGORITHM", &string))
  {
    GNUNET_STRINGS_utf8_toupper (string, string);
    if (0 == strcmp (string, "SARSA"))
    {
        solver->parameters.algorithm = RIL_ALGO_SARSA;
    }
    if (0 == strcmp (string, "Q-LEARNING"))
    {
        solver->parameters.algorithm = RIL_ALGO_Q;
    }

    GNUNET_free (string);
  }
  else
  {
    solver->parameters.algorithm = RIL_DEFAULT_ALGORITHM;
  }

  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SELECT", &string))
  {
    solver->parameters.select = !strcmp (string, "EGREEDY") ? RIL_SELECT_EGREEDY : RIL_SELECT_SOFTMAX;
    GNUNET_free (string);
  }
  else
  {
    solver->parameters.select = RIL_DEFAULT_SELECT;
  }


  solver->parameters.beta = RIL_DEFAULT_DISCOUNT_BETA;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_DISCOUNT_BETA", &f_tmp))
  {
    if (f_tmp < 0.0)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_DISCOUNT_BETA", f_tmp);
    }
    else
    {
      solver->parameters.beta = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_DISCOUNT_BETA", f_tmp);
    }
  }

  solver->parameters.gamma = RIL_DEFAULT_DISCOUNT_GAMMA;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_DISCOUNT_GAMMA", &f_tmp))
  {
    if ((f_tmp < 0.0) || (f_tmp > 1.0))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_DISCOUNT_GAMMA", f_tmp);
    }
    else
    {
      solver->parameters.gamma = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_DISCOUNT_GAMMA", f_tmp);
    }
  }

  solver->parameters.alpha = RIL_DEFAULT_GRADIENT_STEP_SIZE;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_GRADIENT_STEP_SIZE", &f_tmp))
  {
    if ((f_tmp < 0.0) || (f_tmp > 1.0))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_GRADIENT_STEP_SIZE", f_tmp);
    }
    else
    {
      solver->parameters.alpha = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_GRADIENT_STEP_SIZE", f_tmp);
    }
  }

  solver->parameters.lambda = RIL_DEFAULT_TRACE_DECAY;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_TRACE_DECAY", &f_tmp))
  {
    if ((f_tmp < 0.0) || (f_tmp > 1.0))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_TRACE_DECAY", f_tmp);
    }
    else
    {
      solver->parameters.lambda = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_TRACE_DECAY", f_tmp);
    }
  }

  solver->parameters.epsilon_init = RIL_DEFAULT_EXPLORE_RATIO;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_EXPLORE_RATIO", &f_tmp))
  {
    if ((f_tmp < 0.0) || (f_tmp > 1.0))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_EXPLORE_RATIO", f_tmp);
    }
    else
    {
      solver->parameters.epsilon_init = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_EXPLORE_RATIO", f_tmp);
    }
  }

  solver->parameters.epsilon_decay = RIL_DEFAULT_EXPLORE_DECAY;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_EXPLORE_DECAY", &f_tmp))
  {
    if ((f_tmp < 0.0) || (f_tmp > 1.0))
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_EXPLORE_DECAY", f_tmp);
    }
    else
    {
      solver->parameters.epsilon_decay = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_EXPLORE_DECAY", f_tmp);
    }
  }

  solver->parameters.temperature_init = RIL_DEFAULT_TEMPERATURE;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_TEMPERATURE", &f_tmp))
  {
    if (f_tmp <= 0.0)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_TEMPERATURE", f_tmp);
    }
    else
    {
      solver->parameters.temperature_init = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_TEMPERATURE", f_tmp);
    }
  }

  solver->parameters.temperature_decay = RIL_DEFAULT_TEMPERATURE_DECAY;
  if (GNUNET_SYSERR != GNUNET_CONFIGURATION_get_value_float (env->cfg, "ats",
      "RIL_TEMPERATURE_DECAY", &f_tmp))
  {
    if ((f_tmp <= 0.0) || solver->parameters.temperature_decay > 1)
    {
      LOG (GNUNET_ERROR_TYPE_ERROR, _("Invalid %s configuration %f \n"),
          "RIL_TEMPERATURE_DECAY", f_tmp);
    }
    else
    {
      solver->parameters.temperature_decay = f_tmp;
      LOG (GNUNET_ERROR_TYPE_INFO, "Using %s of %.3f\n",
          "RIL_TEMPERATURE_DECAY", f_tmp);
    }
  }

  if (GNUNET_OK != GNUNET_CONFIGURATION_get_value_number (env->cfg, "ats", "RIL_SIMULATE", &solver->simulate))
  {
    solver->simulate = GNUNET_NO;
  }

  if (GNUNET_YES == GNUNET_CONFIGURATION_get_value_yesno(env->cfg, "ats", "RIL_REPLACE_TRACES"))
  {
    solver->parameters.eligibility_trace_mode = RIL_E_REPLACE;
  }
  else
  {
    solver->parameters.eligibility_trace_mode = RIL_E_ACCUMULATE;
  }

  if (GNUNET_OK == GNUNET_CONFIGURATION_get_value_string (env->cfg, "ats", "RIL_SOCIAL_WELFARE", &string))
  {
    solver->parameters.social_welfare = !strcmp (string, "NASH") ? RIL_WELFARE_NASH : RIL_WELFARE_EGALITARIAN;
    GNUNET_free (string);
  }
  else
  {
    solver->parameters.social_welfare = RIL_DEFAULT_WELFARE;
  }

  solver->env = env;
  sf.cls = solver;
  sf.s_add = &GAS_ril_address_add;
  sf.s_address_update_property = &GAS_ril_address_property_changed;
  sf.s_get = &GAS_ril_get_preferred_address;
  sf.s_get_stop = &GAS_ril_stop_get_preferred_address;
  sf.s_pref = &GAS_ril_address_change_preference;
  sf.s_feedback = &GAS_ril_address_preference_feedback;
  sf.s_del = &GAS_ril_address_delete;
  sf.s_bulk_start = &GAS_ril_bulk_start;
  sf.s_bulk_stop = &GAS_ril_bulk_stop;

  solver->networks_count = env->network_count;
  solver->network_entries = GNUNET_malloc (env->network_count * sizeof (struct RIL_Scope));
  solver->step_count = 0;
  solver->done = GNUNET_NO;

  for (c = 0; c < env->network_count; c++)
  {
    cur = &solver->network_entries[c];
    cur->type = c;
    cur->bw_in_available = env->in_quota[c];
    cur->bw_out_available = env->out_quota[c];
    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);
  }

  LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  Parameters:\n");
  LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  Algorithm = %s, alpha = %f, beta = %f, lambda = %f\n",
      solver->parameters.algorithm ? "Q" : "SARSA",
      solver->parameters.alpha,
      solver->parameters.beta,
      solver->parameters.lambda);
  LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  exploration_ratio = %f, temperature = %f, ActionSelection = %s\n",
      solver->parameters.epsilon,
      solver->parameters.temperature,
      solver->parameters.select ? "EGREEDY" : "SOFTMAX");
  LOG(GNUNET_ERROR_TYPE_DEBUG, "init()  RBF_DIVISOR = %llu\n",
      solver->parameters.rbf_divisor);

  return &sf;
}


/**
 * Exit point for the plugin
 *
 * @param cls the solver handle
 */
void *
libgnunet_plugin_ats_ril_done (void *cls)
{
  struct GNUNET_ATS_SolverFunctions *sf = cls;
  struct GAS_RIL_Handle *s = sf->cls;
  struct RIL_Peer_Agent *cur_agent;
  struct RIL_Peer_Agent *next_agent;

  LOG(GNUNET_ERROR_TYPE_DEBUG, "API_done() Shutting down RIL solver\n");

  s->done = GNUNET_YES;

  cur_agent = s->agents_head;
  while (NULL != cur_agent)
  {
    next_agent = cur_agent->next;
    GNUNET_CONTAINER_DLL_remove(s->agents_head, s->agents_tail, cur_agent);
    agent_die (s, cur_agent);
    cur_agent = next_agent;
  }

  if (NULL != s->step_next_task_id)
  {
    GNUNET_SCHEDULER_cancel (s->step_next_task_id);
  }
  GNUNET_free(s->network_entries);
  GNUNET_free(s);

  return NULL;
}


/* end of plugin_ats_ril.c */