esopt 0.2.0

General Evolution-Strategy-Optimizer implementation according to https://arxiv.org/abs/1703.03864 in Rust.
Documentation
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
//! General implementation of the ES strategy described in https://arxiv.org/pdf/1703.03864.pdf.
#![allow(clippy::assign_op_pattern)]
#![allow(clippy::expect_used)] // TODO: get rid of.

use std::{cmp::Ordering, fs, fs::File, io::prelude::*};

use rand::prelude::*;
use rand_distr::Normal;
use rayon::prelude::*;
use serde::{de::DeserializeOwned, Deserialize, Serialize};

/// This crate's float type to use.
pub type Float = f32;
#[cfg(feature = "floats-f64")]
/// This crate's float type to use.
pub type Float = f64;

// TODO:
// AdamaxBound ?
// DEBUG: show delta and grad?

/// Definition of standard evaluator trait.
pub trait Evaluator {
	/// Function to evaluate a set of parameters given as parameter.
	/// Return the score towards the target (optimizer maximizes).
	/// Only used once per optimization call (only for the returned score).
	fn eval_test(&self, parameters: &[Float]) -> Float;
	/// Function to evaluate a set of parameters also given the loop index as
	/// parameter. In addition to the parameters, the loop index is provided to
	/// allow selection of the same batch. Return the score towards the target
	/// (optimizer maximizes). Only used during training (very often).
	fn eval_train(&self, parameters: &[Float], loop_index: usize) -> Float;
}

/// Definition of the optimizer traits, to dynamically allow different
/// optimizers
pub trait Optimizer {
	/// Function to compute the delta step/update later applied to the
	/// parameters Takes parameters and gradient as input
	/// Returns delta vector
	fn get_delta(&mut self, parameters: &[Float], gradient: &[Float]) -> Vec<Float>;
	/// Get number of iterations already processed.
	fn get_t(&self) -> usize;
}

/// SGD Optimizer, which actually is SGA here (stochastic gradient ascent)
/// Momentum and weight decay is available
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SGD {
	/// Learning rate.
	lr: Float,
	/// Weight decay coefficient.
	lambda: Float,
	/// Momentum coefficient.
	beta: Float,
	/// Last momentum gradient.
	lastv: Vec<Float>,
	/// Number of iterations/timesteps.
	t: usize,
}

impl Default for SGD {
	fn default() -> Self {
		Self { lr: 0.01, lambda: 0.0, beta: 0.0, lastv: vec![0.0], t: 0 }
	}
}

impl SGD {
	/// Set learning rate
	pub fn set_lr(&mut self, learning_rate: Float) -> &mut Self {
		if learning_rate <= 0.0 {
			panic!("Learning rate must be greater than zero!");
		}
		self.lr = learning_rate;

		self
	}

	/// Set lambda factor for weight decay
	pub fn set_lambda(&mut self, coeff: Float) -> &mut Self {
		if coeff < 0.0 {
			panic!("Lambda coefficient may not be smaller than zero!");
		}
		self.lambda = coeff;

		self
	}

	/// Set beta factor for momentum
	pub fn set_beta(&mut self, factor: Float) -> &mut Self {
		if !(0.0..1.0).contains(&factor) {
			panic!("Prohibited momentum paramter: {}. Must be in [0.0, 1.0)!", factor);
		}
		self.beta = factor;

		self
	}

	/// Encodes the optimizer as a JSON string.
	#[must_use]
	pub fn to_json(&self) -> String {
		serde_json::to_string(self).expect("Encoding JSON failed!")
	}

	/// Builds a new optimizer from a JSON string.
	#[must_use]
	pub fn from_json(encoded: &str) -> SGD {
		serde_json::from_str(encoded).expect("Decoding JSON failed!")
	}

	/// Saves the model to a file
	pub fn save(&self, file: &str) -> Result<(), std::io::Error> {
		let mut file = File::create(file)?;
		let json = self.to_json();
		file.write_all(json.as_bytes())?;
		Ok(())
	}

	/// Creates a model from a previously saved file
	pub fn load(file: &str) -> Result<SGD, std::io::Error> {
		let json = fs::read_to_string(file)?;
		Ok(SGD::from_json(&json))
	}
}

impl Optimizer for SGD {
	/// Compute delta update from params and gradient
	fn get_delta(&mut self, params: &[Float], grad: &[Float]) -> Vec<Float> {
		if self.lastv.len() != params.len() {
			//initialize with zero gradient
			self.lastv = vec![0.0; params.len()];
		}

		//calculate momentum update and compute delta (parameter update)
		let mut delta = grad.to_vec();
		for ((m, d), p) in self.lastv.iter_mut().zip(delta.iter_mut()).zip(params.iter()) {
			//momentum update
			*m = self.beta.mul_add(*m, (1.0 - self.beta) * *d);
			//compute delta based on momentum
			*d = self.lr * *m; //here no minus, because ascend instead of descent
				   //add weight decay
			*d -= self.lr * self.lambda * *p;
		}
		self.t += 1;

		//return
		delta
	}

	/// Retrieve the timestep (to allow computing manual learning rate decay)
	fn get_t(&self) -> usize {
		self.t
	}
}

/// Adam Optimizer, with possibility of using AdaBound
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Adam {
	/// learning rate.
	lr: Float,
	/// weight decay coefficient.
	lambda: Float,
	/// exponential moving average factor.
	beta1: Float,
	/// exponential second moment average factor (squared gradient).
	beta2: Float,
	/// small epsilon to avoid divide by zero (fuzz factor).
	eps: Float,
	/// number of taken timesteps.
	t: usize,
	/// first order moment (avg).
	avggrad1: Vec<Float>,
	/// second oder moment (squared).
	avggrad2: Vec<Float>,
	/// switch whether to use the AdaBound variant.
	adabound: bool,
	/// final LR to use using AdaBound (SGD).
	final_lr: Float,
	/// convergence speed of bounding functions for AdaBound.
	gamma: Float,
}

impl Default for Adam {
	/// Create new Adam optimizer instance using default hyperparameters (lr =
	/// 0.001, lambda = 0, beta1 = 0.9, beta2 = 0.999, eps = 1e-8, adabound =
	/// false, final_lr = 0.1, gamma: 0.001) Also try higher LR; beta2 = 0.99;
	/// try adabound!
	fn default() -> Self {
		Self {
			lr: 0.001,
			lambda: 0.0,
			beta1: 0.9,
			beta2: 0.999,
			eps: 1e-8,
			t: 0,
			avggrad1: vec![0.0],
			avggrad2: vec![0.0],
			adabound: false,
			final_lr: 0.1,
			gamma: 0.001,
		}
	}
}

impl Adam {
	/// Set learning rate
	pub fn set_lr(&mut self, learning_rate: Float) -> &mut Self {
		if learning_rate <= 0.0 {
			panic!("Learning rate must be greater than zero!");
		}
		self.lr = learning_rate;

		self
	}

	/// Set final learning rate for AdaBound (SGD)
	pub fn set_final_lr(&mut self, learning_rate: Float) -> &mut Self {
		if learning_rate <= 0.0 {
			panic!("Learning rate must be greater than zero!");
		}
		self.final_lr = learning_rate;

		self
	}

	/// Set lambda factor for weight decay
	pub fn set_lambda(&mut self, coeff: Float) -> &mut Self {
		if coeff < 0.0 {
			panic!("Lambda coefficient may not be smaller than zero!");
		}
		self.lambda = coeff;

		self
	}

	/// Set gamma factor for AdaBound bounding convergence
	pub fn set_gamma(&mut self, coeff: Float) -> &mut Self {
		if !(0.0..1.0).contains(&coeff) {
			panic!("Gamma coefficient is in appropriate!");
		}
		self.gamma = coeff;

		self
	}

	/// Set beta1 coefficient (for exponential moving average of first moment)
	pub fn set_beta1(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta1 = beta;

		self
	}

	/// Set beta2 coefficient (for exponential moving average of second moment)
	pub fn set_beta2(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta2 = beta;

		self
	}

	/// Set epsilon to avoid divide by zero (fuzz factor)
	pub fn set_eps(&mut self, epsilon: Float) -> &mut Self {
		if epsilon < 0.0 {
			panic!("Epsilon must be >= 0!");
		}
		self.eps = epsilon;

		self
	}

	/// Set usage of AdaBound
	pub fn set_adabound(&mut self, use_bound: bool) -> &mut Self {
		self.adabound = use_bound;
		self
	}

	/// Encodes the optimizer as a JSON string.
	#[must_use]
	pub fn to_json(&self) -> String {
		serde_json::to_string(self).expect("Encoding JSON failed!")
	}

	/// Builds a new optimizer from a JSON string.
	#[must_use]
	pub fn from_json(encoded: &str) -> Adam {
		serde_json::from_str(encoded).expect("Decoding JSON failed!")
	}

	/// Saves the model to a file
	pub fn save(&self, file: &str) -> Result<(), std::io::Error> {
		let mut file = File::create(file)?;
		let json = self.to_json();
		file.write_all(json.as_bytes())?;
		Ok(())
	}

	/// Creates a model from a previously saved file
	pub fn load(file: &str) -> Result<Adam, std::io::Error> {
		let json = fs::read_to_string(file)?;
		Ok(Adam::from_json(&json))
	}
}

impl Optimizer for Adam {
	/// Compute delta update from params and gradient
	fn get_delta(&mut self, params: &[Float], grad: &[Float]) -> Vec<Float> {
		if self.avggrad1.len() != params.len() || self.avggrad2.len() != params.len() {
			//initialize with zero moments
			self.avggrad1 = vec![0.0; params.len()];
			self.avggrad2 = vec![0.0; params.len()];
		}

		//timestep + unbias factor
		self.t += 1;
		let lr_unbias = self.lr * (1.0 - self.beta2.powf(self.t as Float)).sqrt()
			/ (1.0 - self.beta1.powf(self.t as Float));
		//dynamic bound
		let lower_bound = (1.0 - 1.0 / (self.gamma.mul_add(self.t as Float, 1.0))) * self.final_lr;
		let upper_bound = (1.0 + 1.0 / (self.gamma * self.t as Float)) * self.final_lr;

		//update exponential moving averages and compute delta (parameter update)
		let mut delta = grad.to_vec();
		for (((g1, g2), d), p) in self
			.avggrad1
			.iter_mut()
			.zip(self.avggrad2.iter_mut())
			.zip(delta.iter_mut())
			.zip(params.iter())
		{
			//moment 1 and 2 update
			*g1 = self.beta1.mul_add(*g1, (1.0 - self.beta1) * *d);
			*g2 = self.beta2.mul_add(*g2, (1.0 - self.beta2) * *d * *d);
			//delta update
			if self.adabound {
				//dynamic bound
				let bound_lr =
					(lr_unbias / (g2.sqrt() + self.eps)).max(lower_bound).min(upper_bound);
				*d = bound_lr * *g1;
			} else {
				*d = lr_unbias * *g1 / (g2.sqrt() + self.eps); //normally it would be
				                               // -lr_unbias, but we want to
				                               // maximize
			}
			//weight decay
			*d -= self.lr * self.lambda * *p;
		}

		//return
		delta
	}

	/// Retrieve the timestep (to allow computing manual learning rate decay)
	fn get_t(&self) -> usize {
		self.t
	}
}

/// RAdam Optimizer (Rectified Adam)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RAdam {
	/// learning rate.
	lr: Float,
	/// weight decay coefficient.
	lambda: Float,
	/// exponential moving average factor.
	beta1: Float,
	/// exponential second moment average factor (squared gradient).
	beta2: Float,
	/// small epsilon to avoid divide by zero (fuzz factor).
	eps: Float,
	/// number of taken timesteps.
	t: usize,
	/// first order moment (avg).
	avggrad1: Vec<Float>,
	/// second oder moment (squared).
	avggrad2: Vec<Float>,
}

impl Default for RAdam {
	/// Create new RAdam optimizer instance using default hyperparameters (lr =
	/// 0.001, lambda = 0, beta1 = 0.9, beta2 = 0.999, eps = 1e-8)
	/// Also try higher LR; beta2 = 0.99; try adabound!
	fn default() -> Self {
		RAdam {
			lr: 0.001,
			lambda: 0.0,
			beta1: 0.9,
			beta2: 0.999,
			eps: 1e-8,
			t: 0,
			avggrad1: vec![0.0],
			avggrad2: vec![0.0],
		}
	}
}

impl RAdam {
	/// Set learning rate
	pub fn set_lr(&mut self, learning_rate: Float) -> &mut Self {
		if learning_rate <= 0.0 {
			panic!("Learning rate must be greater than zero!");
		}
		self.lr = learning_rate;

		self
	}

	/// Set lambda factor for weight decay
	pub fn set_lambda(&mut self, coeff: Float) -> &mut Self {
		if coeff < 0.0 {
			panic!("Lambda coefficient may not be smaller than zero!");
		}
		self.lambda = coeff;

		self
	}

	/// Set beta1 coefficient (for exponential moving average of first moment)
	pub fn set_beta1(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta1 = beta;

		self
	}

	/// Set beta2 coefficient (for exponential moving average of second moment)
	pub fn set_beta2(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta2 = beta;

		self
	}

	/// Set epsilon to avoid divide by zero (fuzz factor)
	pub fn set_eps(&mut self, epsilon: Float) -> &mut Self {
		if epsilon < 0.0 {
			panic!("Epsilon must be >= 0!");
		}
		self.eps = epsilon;

		self
	}

	/// Encodes the optimizer as a JSON string.
	#[must_use]
	pub fn to_json(&self) -> String {
		serde_json::to_string(self).expect("Encoding JSON failed!")
	}

	/// Builds a new optimizer from a JSON string.
	#[must_use]
	pub fn from_json(encoded: &str) -> RAdam {
		serde_json::from_str(encoded).expect("Decoding JSON failed!")
	}

	/// Saves the model to a file
	pub fn save(&self, file: &str) -> Result<(), std::io::Error> {
		let mut file = File::create(file)?;
		let json = self.to_json();
		file.write_all(json.as_bytes())?;
		Ok(())
	}

	/// Creates a model from a previously saved file
	pub fn load(file: &str) -> Result<RAdam, std::io::Error> {
		let json = fs::read_to_string(file)?;
		Ok(RAdam::from_json(&json))
	}
}

impl Optimizer for RAdam {
	/// Compute delta update from params and gradient
	fn get_delta(&mut self, params: &[Float], grad: &[Float]) -> Vec<Float> {
		if self.avggrad1.len() != params.len() || self.avggrad2.len() != params.len() {
			//initialize with zero moments
			self.avggrad1 = vec![0.0; params.len()];
			self.avggrad2 = vec![0.0; params.len()];
		}

		//timestep, bias-correct LR, SMAs for rectification
		self.t += 1;
		let t_float = self.t as Float;
		let beta1_pt = self.beta1.powf(t_float);
		let beta2_pt = self.beta2.powf(t_float);
		let sma_inf = 2.0 / (1.0 - self.beta2) - 1.0;
		let sma_t = sma_inf - 2.0 * t_float * beta2_pt / (1.0 - beta2_pt);
		let r_t = (((sma_t - 4.0) * (sma_t - 2.0) * sma_inf)
			/ ((sma_inf - 4.0) * (sma_inf - 2.0) * sma_t))
			.sqrt(); //variance rectification term
		let lr_unbias1 = self.lr / (1.0 - beta1_pt);
		let lr_unbias12 = self.lr * (1.0 - beta2_pt).sqrt() / (1.0 - beta1_pt);

		//update exponential moving averages and compute delta (parameter update)
		let mut delta = grad.to_vec();
		for (((g1, g2), d), p) in self
			.avggrad1
			.iter_mut()
			.zip(self.avggrad2.iter_mut())
			.zip(delta.iter_mut())
			.zip(params.iter())
		{
			//moment 1 and 2 update
			*g1 = self.beta1.mul_add(*g1, (1.0 - self.beta1) * *d);
			*g2 = self.beta2.mul_add(*g2, (1.0 - self.beta2) * *d * *d);
			//delta update depending on variance
			if sma_t > 4.0 {
				*d = lr_unbias12 * r_t * *g1 / (g2.sqrt() + self.eps); //normally it would be
				                                       // -lr_unbias, but we
				                                       // want to maximize
			} else {
				*d = lr_unbias1 * *g1; //normally it would be -lr_unbias, but we want to
				       // maximize
			}
			//weight decay
			*d -= self.lr * self.lambda * *p;
		}

		//return
		delta
	}

	/// Retrieve the timestep (to allow computing manual learning rate decay)
	fn get_t(&self) -> usize {
		self.t
	}
}

/// Adamax Optimizer
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Adamax {
	/// learning rate.
	lr: Float,
	/// weight decay coefficient.
	lambda: Float,
	/// exponential moving average factor.
	beta1: Float,
	/// exponential second moment average factor (squared gradient).
	beta2: Float,
	/// small epsilon to avoid divide by zero (fuzz factor).
	eps: Float,
	/// number of taken timesteps.
	t: usize,
	/// first order moment (avg).
	avggrad1: Vec<Float>,
	/// second oder moment (squared).
	avggrad2: Vec<Float>,
}

impl Default for Adamax {
	/// Create new Adamax optimizer instance using default hyperparameters (lr =
	/// 0.002, lambda = 0, beta1 = 0.9, beta2 = 0.999, eps = 0) Also try higher
	/// LR; beta2 = 0.99
	fn default() -> Self {
		Self {
			lr: 0.002,
			lambda: 0.0,
			beta1: 0.9,
			beta2: 0.999,
			eps: 0.0,
			t: 0,
			avggrad1: vec![0.0],
			avggrad2: vec![0.0],
		}
	}
}

impl Adamax {
	/// Set learning rate
	pub fn set_lr(&mut self, learning_rate: Float) -> &mut Self {
		if learning_rate <= 0.0 {
			panic!("Learning rate must be greater than zero!");
		}
		self.lr = learning_rate;

		self
	}

	/// Set lambda factor for weight decay
	pub fn set_lambda(&mut self, coeff: Float) -> &mut Self {
		if coeff < 0.0 {
			panic!("Lambda coefficient may not be smaller than zero!");
		}
		self.lambda = coeff;

		self
	}

	/// Set beta1 coefficient (for exponential moving average of first moment)
	pub fn set_beta1(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta1 = beta;

		self
	}

	/// Set beta2 coefficient (for exponential moving average of second moment)
	pub fn set_beta2(&mut self, beta: Float) -> &mut Self {
		if !(0.0..1.0).contains(&beta) {
			panic!("Prohibited beta coefficient: {}. Must be in [0.0, 1.0)!", beta);
		}
		self.beta2 = beta;

		self
	}

	/// Set epsilon to avoid divide by zero (fuzz factor)
	pub fn set_eps(&mut self, epsilon: Float) -> &mut Self {
		if epsilon < 0.0 {
			panic!("Epsilon must be >= 0!");
		}
		self.eps = epsilon;

		self
	}

	/// Encodes the optimizer as a JSON string.
	#[must_use]
	pub fn to_json(&self) -> String {
		serde_json::to_string(self).expect("Encoding JSON failed!")
	}

	/// Builds a new optimizer from a JSON string.
	#[must_use]
	pub fn from_json(encoded: &str) -> Adamax {
		serde_json::from_str(encoded).expect("Decoding JSON failed!")
	}

	/// Saves the model to a file
	pub fn save(&self, file: &str) -> Result<(), std::io::Error> {
		let mut file = File::create(file)?;
		let json = self.to_json();
		file.write_all(json.as_bytes())?;
		Ok(())
	}

	/// Creates a model from a previously saved file
	pub fn load(file: &str) -> Result<Adamax, std::io::Error> {
		let json = fs::read_to_string(file)?;
		Ok(Adamax::from_json(&json))
	}
}

impl Optimizer for Adamax {
	/// Compute delta update from params and gradient
	fn get_delta(&mut self, params: &[Float], grad: &[Float]) -> Vec<Float> {
		if self.avggrad1.len() != params.len() || self.avggrad2.len() != params.len() {
			//initialize with zero moments
			self.avggrad1 = vec![0.0; params.len()];
			self.avggrad2 = vec![0.0; params.len()];
		}

		//timestep + unbias factor
		self.t += 1;
		let lr_unbias = self.lr / (1.0 - self.beta1.powf(self.t as Float));

		//update exponential moving averages and compute delta (parameter update)
		let mut delta = grad.to_vec();
		for (((g1, g2), d), p) in self
			.avggrad1
			.iter_mut()
			.zip(self.avggrad2.iter_mut())
			.zip(delta.iter_mut())
			.zip(params.iter())
		{
			//moment 1 and 2 update
			*g1 = self.beta1.mul_add(*g1, (1.0 - self.beta1) * *d);
			*g2 = (self.beta2 * *g2).max(d.abs());
			//delta update
			*d = lr_unbias * *g1 / (*g2 + self.eps); //normally it would be -lr_unbias, but we want to maximize
										 //weight decay
			*d -= self.lr * self.lambda * *p;
		}

		//return
		delta
	}

	/// Retrieve the timestep (to allow computing manual learning rate decay)
	fn get_t(&self) -> usize {
		self.t
	}
}

/// Lookahead optimizer on top of other optimizers
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Lookahead<Opt: Optimizer> {
	/// Sub-optimizer.
	subopt: Opt,
	/// Outer step size.
	alpha: Float,
	/// Number of taken timesteps.
	t: usize,
	/// Number of steps between paramter synchronizations.
	k: usize,
	/// Temporary storage of parameters for the k steps.
	paramssave: Vec<Float>,
}

impl<Opt: Optimizer> Lookahead<Opt> {
	/// Create new Lookahead optimizer instance using default hyperparameters
	/// (alpha = 0.5, k = 5)
	#[must_use]
	pub fn new(opt: Opt) -> Lookahead<Opt> {
		Lookahead { subopt: opt, alpha: 0.5, t: 0, k: 5, paramssave: Vec::new() }
	}

	/// Set outer step size
	pub fn set_alpha(&mut self, step: Float) -> &mut Self {
		if step <= 0.0 {
			panic!("Step size must be greater than zero!");
		}
		self.alpha = step;

		self
	}

	/// Set synchronization frequency.
	pub fn set_k(&mut self, syncfreq: usize) -> &mut Self {
		if syncfreq < 1 {
			panic!("Synchronization frequency in Lookahead must be at least k=1");
		}
		self.k = syncfreq;

		self
	}

	/// Get inner optimizer.
	pub fn get_opt(&self) -> &Opt {
		&self.subopt
	}

	/// Get inner optimizer mutably.
	pub fn get_opt_mut(&mut self) -> &mut Opt {
		&mut self.subopt
	}
}

impl<Opt: Optimizer + Serialize + DeserializeOwned> Lookahead<Opt> {
	/// Encodes the optimizer as a JSON string.
	#[must_use]
	pub fn to_json(&self) -> String {
		serde_json::to_string(self).expect("Encoding JSON failed!")
	}

	/// Builds a new optimizer from a JSON string.
	#[must_use]
	pub fn from_json(encoded: &str) -> Lookahead<Opt> {
		serde_json::from_str(encoded).expect("Decoding JSON failed!")
	}

	/// Saves the model to a file
	pub fn save(&self, file: &str) -> Result<(), std::io::Error> {
		let mut file = File::create(file)?;
		let json = self.to_json();
		file.write_all(json.as_bytes())?;
		Ok(())
	}

	/// Creates a model from a previously saved file
	pub fn load(file: &str) -> Result<Lookahead<Opt>, std::io::Error> {
		let json = fs::read_to_string(file)?;
		Ok(Lookahead::<Opt>::from_json(&json))
	}
}

impl<Opt: Optimizer> Optimizer for Lookahead<Opt> {
	/// Compute delta update from params and gradient
	fn get_delta(&mut self, params: &[Float], grad: &[Float]) -> Vec<Float> {
		//save initial parameters on start
		if self.t == 0 {
			self.paramssave = params.to_vec();
		}

		//inner update
		let mut delta = self.subopt.get_delta(params, grad);

		//timestep
		self.t += 1;

		//outer update
		if self.t % self.k == 0 {
			for ((ps, p), d) in self.paramssave.iter_mut().zip(params.iter()).zip(delta.iter_mut())
			{
				let diff = (*p + *d) - *ps; //difference between initial params and explored params
				let new = self.alpha.mul_add(diff, *ps); //outer update target params
				*d = new - *p; //calculate delta to get from current params to new params
				*ps = new; //update paramssave
			}
		}

		//return
		delta
	}

	/// Retrieve the timestep (to allow computing manual learning rate decay)
	fn get_t(&self) -> usize {
		self.t
	}
}

/// Evolution-Strategy optimizer class. Optimizes given parameters towards a
/// maximum evaluation-score.
#[derive(Debug)]
pub struct ES<Feval: Evaluator, Opt: Optimizer> {
	/// Problem dimensionality.
	dim: usize,
	/// Current parameters.
	params: Vec<Float>,
	/// Chosen optimizer.
	opt: Opt,
	/// Evaluator function.
	eval: Feval,
	/// Standard deviation to calculate the noise for parameters.
	std: Float,
	/// Number of mirror-samples per step to approximate the gradient.
	samples: usize,
}

impl<Feval: Evaluator> ES<Feval, SGD> {
	/// Shortcut for ES::new(...) using SGD:
	/// Create a new ES-Optimizer using SGA (create SGD object with the given
	/// parameters).
	pub fn new_with_sgd(
		evaluator: Feval,
		learning_rate: Float,
		beta: Float,
		lambda: Float,
	) -> ES<Feval, SGD> {
		let mut optimizer = SGD::default();
		optimizer.set_lr(learning_rate).set_beta(beta).set_lambda(lambda);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Lookahead<SGD>> {
	/// Shortcut for ES::new(...) using Lookahead with SGD:
	/// Create a new ES-Optimizer using Lookahead with SGA (create Lookahead and
	/// SGD object with the given parameters).
	pub fn new_with_lookahead_sgd(
		evaluator: Feval,
		k: usize,
		learning_rate: Float,
		beta: Float,
		lambda: Float,
	) -> ES<Feval, Lookahead<SGD>> {
		let mut optimizer = SGD::default();
		optimizer.set_lr(learning_rate).set_beta(beta).set_lambda(lambda);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Adam> {
	/// Shortcut for ES::new(...) using Adam (/AdaBound):
	/// Create a new ES-Optimizer using Adam (create Adam object with the given
	/// parameters, rest left to default). Change these paramters using method
	/// get_opt_mut().set_<...>(...).
	pub fn new_with_adam(evaluator: Feval, learning_rate: Float, lambda: Float) -> ES<Feval, Adam> {
		let mut optimizer = Adam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using Adam (/AdaBound):
	/// Create a new ES-Optimizer using Adam (create Adam object with the given
	/// parameters).
	pub fn new_with_adam_ex(
		evaluator: Feval,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
		adabound: bool,
		final_lr: Float,
	) -> ES<Feval, Adam> {
		let mut optimizer = Adam::default();
		optimizer
			.set_lr(learning_rate)
			.set_lambda(lambda)
			.set_beta1(beta1)
			.set_beta2(beta2)
			.set_adabound(adabound)
			.set_final_lr(final_lr);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Lookahead<Adam>> {
	/// Shortcut for ES::new(...) using Lookahead with Adam:
	/// Create a new ES-Optimizer using Lookahead with Adam (create Lookahead
	/// and Adam object with the given parameters, rest left to default). Change
	/// these paramters using method get_opt_mut().set_<...>(...) and
	/// get_opt_mut().get_opt_mut().set_<...>(...).
	pub fn new_with_lookahead_adam(
		evaluator: Feval,
		k: usize,
		learning_rate: Float,
		lambda: Float,
	) -> ES<Feval, Lookahead<Adam>> {
		let mut optimizer = Adam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using Adam:
	/// Create a new ES-Optimizer using Adam (create Lookahead and Adam object
	/// with the given parameters).
	pub fn new_with_lookahead_adam_ex(
		evaluator: Feval,
		alpha: Float,
		k: usize,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
	) -> ES<Feval, Lookahead<Adam>> {
		let mut optimizer = Adam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda).set_beta1(beta1).set_beta2(beta2);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_alpha(alpha).set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, RAdam> {
	/// Shortcut for ES::new(...) using RAdam:
	/// Create a new ES-Optimizer using RAdam (create RAdam object with the
	/// given parameters, rest left to default). Change these paramters using
	/// method get_opt_mut().set_<...>(...).
	pub fn new_with_radam(
		evaluator: Feval,
		learning_rate: Float,
		lambda: Float,
	) -> ES<Feval, RAdam> {
		let mut optimizer = RAdam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using RAdam:
	/// Create a new ES-Optimizer using RAdam (create RAdam object with the
	/// given parameters).
	pub fn new_with_radam_ex(
		evaluator: Feval,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
	) -> ES<Feval, RAdam> {
		let mut optimizer = RAdam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda).set_beta1(beta1).set_beta2(beta2);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Lookahead<RAdam>> {
	/// Shortcut for ES::new(...) using Lookahead with RAdam:
	/// Create a new ES-Optimizer using Lookahead with RAdam (create Lookahead
	/// and RAdam object with the given parameters, rest left to default).
	/// Change these paramters using method get_opt_mut().set_<...>(...) and
	/// get_opt_mut().get_opt_mut().set_<...>(...).
	pub fn new_with_lookahead_radam(
		evaluator: Feval,
		k: usize,
		learning_rate: Float,
		lambda: Float,
	) -> ES<Feval, Lookahead<RAdam>> {
		let mut optimizer = RAdam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using RAdam:
	/// Create a new ES-Optimizer using RAdam (create Lookahead and RAdam object
	/// with the given parameters).
	pub fn new_with_lookahead_radam_ex(
		evaluator: Feval,
		alpha: Float,
		k: usize,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
	) -> ES<Feval, Lookahead<RAdam>> {
		let mut optimizer = RAdam::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda).set_beta1(beta1).set_beta2(beta2);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_alpha(alpha).set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Adamax> {
	/// Shortcut for ES::new(...) using Adamax:
	/// Create a new ES-Optimizer using Adamax (create Adam object with the
	/// given parameters, rest left to default). Change these paramters using
	/// method get_opt_mut().set_<...>(...).
	pub fn new_with_adamax(
		evaluator: Feval,
		learning_rate: Float,
		lambda: Float,
	) -> ES<Feval, Adamax> {
		let mut optimizer = Adamax::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using Adam:
	/// Create a new ES-Optimizer using Adam (create Adam object with the given
	/// parameters).
	pub fn new_with_adamax_ex(
		evaluator: Feval,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
		eps: Float,
	) -> ES<Feval, Adamax> {
		let mut optimizer = Adamax::default();
		optimizer
			.set_lr(learning_rate)
			.set_lambda(lambda)
			.set_beta1(beta1)
			.set_beta2(beta2)
			.set_eps(eps);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator> ES<Feval, Lookahead<Adamax>> {
	/// Shortcut for ES::new(...) using Lookahead with Adamax:
	/// Create a new ES-Optimizer using Lookahead with Adamax (create Lookahead
	/// and Adamax object with the given parameters, rest left to default).
	/// Change these paramters using method get_opt_mut().set_<...>(...) and
	/// get_opt_mut().get_opt_mut().set_<...>(...).
	pub fn new_with_lookahead_adamax(
		evaluator: Feval,
		k: usize,
		learning_rate: Float,
		lambda: Float,
	) -> ES<Feval, Lookahead<Adamax>> {
		let mut optimizer = Adamax::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Shortcut for ES::new(...) using Adamax:
	/// Create a new ES-Optimizer using Adamax (create Lookahead and Adamax
	/// object with the given parameters).
	pub fn new_with_lookahead_adamax_ex(
		evaluator: Feval,
		alpha: Float,
		k: usize,
		learning_rate: Float,
		lambda: Float,
		beta1: Float,
		beta2: Float,
	) -> ES<Feval, Lookahead<Adamax>> {
		let mut optimizer = Adamax::default();
		optimizer.set_lr(learning_rate).set_lambda(lambda).set_beta1(beta1).set_beta2(beta2);
		let mut optimizer = Lookahead::new(optimizer);
		optimizer.set_alpha(alpha).set_k(k);
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}
}

impl<Feval: Evaluator, Opt: Optimizer> ES<Feval, Opt> {
	/// Create a new ES-Optimizer
	/// evaluator = object with Evaluator trait that computes the objetive-score
	/// based on the paramters optimizer = optimizer to calculate the parameter
	/// update using the gradient and the current parameters. (e.g. use
	/// SGD::new() aka SGA) Important: set the initial parameters afterswards by
	/// calling set_params to specify the problem dimension. (Default is [0.0],
	/// dim=1)
	pub fn new(optimizer: Opt, evaluator: Feval) -> ES<Feval, Opt> {
		ES { dim: 1, params: vec![0.0], opt: optimizer, eval: evaluator, std: 0.02, samples: 500 }
	}

	/// Set the parameters (potentially reinitializing the process)
	/// params = set of parameters to optimize
	pub fn set_params(&mut self, params: Vec<Float>) -> &mut Self {
		self.params = params;
		self.dim = self.params.len();

		self
	}

	/// Change the optimizer
	pub fn set_opt(&mut self, optimizer: Opt) -> &mut Self {
		self.opt = optimizer;

		self
	}

	/// Change the evaluator function
	pub fn set_eval(&mut self, evaluator: Feval) -> &mut Self {
		self.eval = evaluator;

		self
	}

	/// Set noise's standard deviation (applied to the parameters)
	/// Humanoid example in the paper used 0.02 as an example (default).
	/// Probably best to choose in dependence of evaluator output size.
	/// Tweak learning rate to fit to the std.
	pub fn set_std(&mut self, noise: Float) -> &mut Self {
		if noise <= 0.0 {
			panic!("Noise std may not be <= 0!");
		}
		self.std = noise;

		self
	}

	/// Set the number of mirror-samples per step to approximate the gradient
	/// Was probably around 700 in paper (1400 workers)
	pub fn set_samples(&mut self, num: usize) -> &mut Self {
		if num == 0 {
			panic!("Number of samples cannot be zero!");
		}
		self.samples = num;

		self
	}

	/// Get the current parameters (as ref)
	pub fn get_params(&self) -> &Vec<Float> {
		&self.params
	}

	/// Get the optimizer (as ref)
	pub fn get_opt(&self) -> &Opt {
		&self.opt
	}

	/// Get the evaluator (as ref)
	pub fn get_eval(&self) -> &Feval {
		&self.eval
	}

	/// Get the current parameters (as mut)
	pub fn get_params_mut(&mut self) -> &mut Vec<Float> {
		&mut self.params
	}

	/// Get the optimizer (as mut, to change parameters)
	pub fn get_opt_mut(&mut self) -> &mut Opt {
		&mut self.opt
	}

	/// Get the evaluator (as mut, to change parameters)
	pub fn get_eval_mut(&mut self) -> &mut Feval {
		&mut self.eval
	}

	/// Optimize for n steps.
	/// Uses the evaluator's score to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize(&mut self, n: usize) -> (Float, Float) {
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			grad = vec![0.0; self.dim];
			for i in 0..self.samples {
				//(repeatable) eps generation
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//generate random epsilon
				let eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
				//compute test parameters in both directions
				let mut testparampos = eps.clone();
				let mut testparamneg = eps.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate test parameters
				let scorepos = self.eval.eval_train(&testparampos, t + iterations);
				let scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
				//calculate grad sum update
				for (g, e) in grad.iter_mut().zip(eps.iter()) {
					*g += *e * (scorepos - scoreneg);
				}
			}
			//calculate gradient from the sum
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps.
	/// Uses the centered ranks to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_ranked(&mut self, n: usize) -> (Float, Float) {
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			grad = vec![0.0; self.dim];
			//first generate and fill whole vector of scores
			let mut scores = Vec::new();
			for i in 0..self.samples {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//gen and compute test parameters
				let mut testparampos = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				let mut testparamneg = testparampos.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate parameters and save scores
				let scorepos = self.eval.eval_train(&testparampos, t + iterations);
				let scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
				scores.push((i, false, scorepos));
				scores.push((i, true, scoreneg));
			}
			//sort, create ranks, sum up and calculate gradient from the sum
			sort_scores(&mut scores);
			scores.iter().enumerate().for_each(|(rank, (i, neg, _score))| {
				let mut rng = SmallRng::seed_from_u64(seed + *i as u64);
				let eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
				let negfactor = if *neg { -1.0 } else { 1.0 };
				let centered_rank = rank as Float / (self.samples as Float - 0.5) - 1.0;
				for (g, e) in grad.iter_mut().zip(eps.iter()) {
					*g += *e * negfactor * centered_rank;
				}
			});
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps.
	/// Uses the standardized scores to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_std(&mut self, n: usize) -> (Float, Float) {
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			grad = vec![0.0; self.dim];
			//first generate and fill whole vector of scores
			let mut scores = vec![(0.0, 0.0); self.samples];
			scores.iter_mut().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//gen and compute test parameters
				let mut testparampos = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				let mut testparamneg = testparampos.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate parameters and save scores
				*scorepos = self.eval.eval_train(&testparampos, t + iterations);
				*scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
			});
			//calculate std, mean
			let (_mean, std) = get_mean_std(&scores);
			//sum up and calculate gradient from the sum
			scores.iter().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				let eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
				for (g, e) in grad.iter_mut().zip(eps.iter()) {
					//subtraction by mean cancels out
					*g += *e * (*scorepos - *scoreneg) / std;
				}
			});
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps.
	/// Uses the normalized scores to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_norm(&mut self, n: usize) -> (Float, Float) {
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			grad = vec![0.0; self.dim];
			//first generate and fill whole vector of scores
			let mut scores = vec![(0.0, 0.0); self.samples];
			let mut maximum = -1.0;
			scores.iter_mut().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//gen and compute test parameters
				let mut testparampos = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				let mut testparamneg = testparampos.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate parameters and save scores
				*scorepos = self.eval.eval_train(&testparampos, t + iterations);
				*scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
				//calculate maxmimum absolute score
				if scorepos.abs() > maximum {
					maximum = scorepos.abs();
				}
				if scoreneg.abs() > maximum {
					maximum = scoreneg.abs();
				}
			});
			//sum up and calculate gradient from the sum
			scores.iter().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				let eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
				for (g, e) in grad.iter_mut().zip(eps.iter()) {
					//subtraction by mean cancels out
					*g += *e * (*scorepos - *scoreneg) / maximum;
				}
			});
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps (evaluation in parallel).
	/// Uses the evaluator's score to calculate the gradients.
	/// Optimizer and Evaluator must satisfy the Sync trait.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_par(&mut self, n: usize) -> (Float, Float)
	where
		Opt: Sync,
		Feval: Sync,
	{
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			grad = (0..self.samples)
				.into_par_iter()
				.map(|i| {
					//(repeatable) eps generation
					let mut rng = SmallRng::seed_from_u64(seed + i as u64);
					//gen and compute test parameters
					let mut eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
					let mut testparampos = eps.clone();
					let mut testparamneg = eps.clone();
					for ((pos, neg), p) in
						testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
					{
						*pos = *p + *pos;
						*neg = *p - *neg;
					}
					//evaluate parameters to compute scores
					let scorepos = self.eval.eval_train(&testparampos, t + iterations);
					let scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
					//compute gradient parts and the sum up in reduce to calculate the gradient
					mul_scalar(&mut eps, scorepos - scoreneg);
					eps
				})
				.reduce(
					|| vec![0.0; self.dim],
					|mut a, b| {
						add_inplace(&mut a, &b);
						a
					},
				);
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps (evaluation in parallel).
	/// Uses the centered ranks to calculate the gradients.
	/// Optimizer and Evaluator must satisfy the Sync trait.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_ranked_par(&mut self, n: usize) -> (Float, Float)
	where
		Opt: Sync,
		Feval: Sync,
	{
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			//first generate and fill whole vector of scores
			let mut scores = vec![(0, false, 0.0); 2 * self.samples];
			for i in 0..self.samples {
				scores[2 * i].0 = i;
				scores[2 * i + 1].0 = i;
				scores[2 * i + 1].1 = true;
			}
			scores.par_iter_mut().for_each(|(i, neg, score)| {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + *i as u64);
				//gen and compute test parameters
				let mut testparam = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				if *neg {
					mul_scalar(&mut testparam, -1.0);
				}
				add_inplace(&mut testparam, &self.params);
				//evaluate parameters and save scores
				*score = self.eval.eval_train(&testparam, t + iterations);
			});
			//compute the centered ranks and calculate the summed result to compute the
			// gradient
			sort_scores(&mut scores);
			grad = scores
				.par_iter()
				.enumerate()
				.map(|(rank, (i, neg, _score))| {
					let mut rng = SmallRng::seed_from_u64(seed + *i as u64);
					let mut eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
					let negfactor = if *neg { -1.0 } else { 1.0 };
					let centered_rank = rank as Float / (self.samples as Float - 0.5) - 1.0;
					mul_scalar(&mut eps, negfactor * centered_rank);
					eps
				})
				.reduce(
					|| vec![0.0; self.dim],
					|mut a, b| {
						add_inplace(&mut a, &b);
						a
					},
				);
			//if reduce saves too much and takes too much memory: do serial (normal iter)
			// and initialize grad before, sum components to grad in loop (for_each);
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps (in parallel).
	/// Optimizer and Evaluator must satisfy the Sync trait.
	/// Uses the standardized scores to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_std_par(&mut self, n: usize) -> (Float, Float)
	where
		Opt: Sync,
		Feval: Sync,
	{
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			//first generate and fill whole vector of scores
			let mut scores = vec![(0.0, 0.0); self.samples];
			scores.par_iter_mut().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//gen and compute test parameters
				let mut testparampos = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				let mut testparamneg = testparampos.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate parameters and save scores
				*scorepos = self.eval.eval_train(&testparampos, t + iterations);
				*scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
			});
			//calculate std, mean
			let (_mean, std) = get_mean_std(&scores);
			//sum up and calculate gradient from the sum
			grad = scores
				.par_iter()
				.enumerate()
				.map(|(i, (scorepos, scoreneg))| {
					let mut rng = SmallRng::seed_from_u64(seed + i as u64);
					let mut eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
					//subtraction by mean cancels out
					mul_scalar(&mut eps, (*scorepos - *scoreneg) / std);
					eps
				})
				.reduce(
					|| vec![0.0; self.dim],
					|mut a, b| {
						add_inplace(&mut a, &b);
						a
					},
				);
			//if reduce saves too much and takes too much memory: do serial (normal iter)
			// and initialize grad before, sum components to grad in loop (for_each);
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}

	/// Optimize for n steps (in parallel).
	/// Optimizer and Evaluator must satisfy the Sync trait.
	/// Uses the normalized scores to calculate the gradients.
	/// Returns a tuple (score, gradnorm), which is the latest parameters'
	/// evaluated score and the norm of the last gradient/delta change.
	pub fn optimize_norm_par(&mut self, n: usize) -> (Float, Float)
	where
		Opt: Sync,
		Feval: Sync,
	{
		let mut rng = thread_rng();
		let mut grad = vec![0.0; self.dim];
		//for n iterations:
		let t = self.opt.get_t();
		for iterations in 0..n {
			//generate seed for repeatable random vector generation
			let seed = rng.gen::<u64>() % (std::u64::MAX - self.samples as u64);
			//approximate gradient with self.samples double-sided samples
			//first generate and fill whole vector of scores
			let mut scores = vec![(0.0, 0.0); self.samples];
			scores.par_iter_mut().enumerate().for_each(|(i, (scorepos, scoreneg))| {
				//repeatable eps generation to save memory
				let mut rng = SmallRng::seed_from_u64(seed + i as u64);
				//gen and compute test parameters
				let mut testparampos = gen_rnd_vec_rng(&mut rng, self.dim, self.std); //eps
				let mut testparamneg = testparampos.clone();
				for ((pos, neg), p) in
					testparampos.iter_mut().zip(testparamneg.iter_mut()).zip(self.params.iter())
				{
					*pos = *p + *pos;
					*neg = *p - *neg;
				}
				//evaluate parameters and save scores
				*scorepos = self.eval.eval_train(&testparampos, t + iterations);
				*scoreneg = self.eval.eval_train(&testparamneg, t + iterations);
			});
			//calculate maxmimum absolute score
			let mut maximum = -1.0;
			scores.iter().for_each(|x| {
				if x.0.abs() > maximum {
					maximum = x.0.abs();
				}
				if x.1.abs() > maximum {
					maximum = x.1.abs();
				}
			});
			//sum up and calculate gradient from the sum
			grad = scores
				.par_iter()
				.enumerate()
				.map(|(i, (scorepos, scoreneg))| {
					let mut rng = SmallRng::seed_from_u64(seed + i as u64);
					let mut eps = gen_rnd_vec_rng(&mut rng, self.dim, self.std);
					//subtraction by mean cancels out
					mul_scalar(&mut eps, (*scorepos - *scoreneg) / maximum);
					eps
				})
				.reduce(
					|| vec![0.0; self.dim],
					|mut a, b| {
						add_inplace(&mut a, &b);
						a
					},
				);
			//if reduce saves too much and takes too much memory: do serial (normal iter)
			// and initialize grad before, sum components to grad in loop (for_each);
			mul_scalar(&mut grad, 1.0 / ((2 * self.samples) as Float * self.std));
			//calculate the delta update using the optimizer
			let delta = self.opt.get_delta(&self.params, &grad);
			//update the parameters
			add_inplace(&mut self.params, &delta);
		}

		(self.eval.eval_test(&self.params), norm(&grad))
	}
}

/// Generate a vector of random numbers with 0 mean and std std, normally
/// distributed. Using specified RNG.
fn gen_rnd_vec_rng<RNG: Rng>(rng: &mut RNG, n: usize, std: Float) -> Vec<Float> {
	let normal =
		Normal::new(0.0, f64::from(std)).expect("Invalid parameters for Normal distribution!");
	normal.sample_iter(rng).take(n).map(|x| x as Float).collect()
}

/// Generate a vector of random numbers with 0 mean and std std, normally
/// distributed. Using standard thread_rng.
#[must_use]
pub fn gen_rnd_vec(n: usize, std: Float) -> Vec<Float> {
	let mut rng = thread_rng();
	let normal =
		Normal::new(0.0, f64::from(std)).expect("Invalid parameters for Normal distribution!");
	normal.sample_iter(&mut rng).take(n).map(|x| x as Float).collect()
}

/// Add a second vector onto the first vector in place
fn add_inplace(v1: &mut [Float], v2: &[Float]) {
	for (val1, val2) in v1.iter_mut().zip(v2.iter()) {
		*val1 += *val2;
	}
}

/// Multiplies a scalar to a vector
fn mul_scalar(vec: &mut [Float], scalar: Float) {
	for val in vec.iter_mut() {
		*val *= scalar;
	}
}

/// Calculates the norm of a vector
#[must_use]
fn norm(vec: &[Float]) -> Float {
	let mut norm = 0.0;
	for val in vec.iter() {
		norm += *val * *val;
	}
	norm.sqrt()
}

/// calculate mean and standard deviation of the scores
#[must_use]
fn get_mean_std(vec: &[(Float, Float)]) -> (Float, Float) {
	let mut mean = 0.0;
	vec.iter().for_each(|(scorepos, scoreneg)| {
		mean += *scorepos + *scoreneg;
	});
	mean /= (2 * vec.len()) as Float;

	let mut std = 0.0;
	vec.iter().for_each(|(scorepos, scoreneg)| {
		let mut diff = *scorepos - mean;
		std += diff * diff;
		diff = *scoreneg - mean;
		std += diff * diff;
	});
	std /= (2 * vec.len()) as Float;
	std = std.sqrt();

	(mean, std)
}

/// Sorts the internal score-vector, so that ranks can be computed
fn sort_scores<T, U>(vec: &mut [(T, U, Float)]) {
	//worst score in front
	vec.sort_unstable_by(|r1, r2| {
		//partial cmp and check for NaN
		(r1.2).partial_cmp(&r2.2).unwrap_or_else(|| {
			if r1.2.is_nan() {
				if r2.2.is_nan() {
					Ordering::Equal
				} else {
					Ordering::Less
				}
			} else {
				Ordering::Greater
			}
		})
	});
}