nsga_rs 1.3.0

A Rust implementation of the NSGA family of multi-objective evolutionary algorithms
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
use std::collections::HashMap;
use std::fmt::{Debug, Display, Formatter};
use std::fs::read_dir;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Instant;
use std::{fmt, fs};

use chrono::{DateTime, Utc};
use log::{debug, info};
use rayon::prelude::*;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};

#[cfg(feature = "python")]
use pyo3::exceptions::PyValueError;
#[cfg(feature = "python")]
use pyo3::prelude::*;

#[cfg(feature = "python")]
use crate::algorithms::{NSGA2Arg, NSGA3Arg};

use crate::algorithms::StoppingCondition;
use crate::core::{
    DataValue, Individual, IndividualExport, OError, ObjectiveDirection, Population, Problem,
    ProblemExport,
};

/// The data with the elapsed time.
#[derive(Serialize, Deserialize, Debug)]
pub struct Elapsed {
    /// Elapsed hours.
    pub hours: u64,
    /// Elapsed minutes.
    pub minutes: u64,
    /// Elapsed seconds.
    pub seconds: u64,
}

/// The struct used to export an algorithm serialised data.
#[derive(Serialize, Deserialize, Debug)]
pub struct AlgorithmSerialisedExport<T: Serialize> {
    /// Specific options for an algorithm.
    pub options: T,
    /// The problem configuration.
    pub problem: ProblemExport,
    /// The individuals in the population.
    pub individuals: Vec<IndividualExport>,
    /// The generation the export was collected at.
    pub generation: u32,
    /// The number of function evaluations
    #[serde(default)]
    pub number_of_function_evaluations: u32,
    /// The algorithm name.
    pub algorithm: String,
    /// Any additional data exported by the algorithm.
    pub additional_data: Option<HashMap<String, DataValue>>,
    /// The time took to reach the `generation`.
    pub took: Elapsed,
    /// The date and time when the data was exported
    pub exported_on: DateTime<Utc>,
}

/// Implement a list of helper functions to get the problem and individuals.
impl<T: Serialize> AlgorithmSerialisedExport<T> {
    /// Build the [`Problem`] struct from serialised data. The problem will have a dummy
    /// [`Algorithm::evolve`] method.
    ///
    /// returns: `Result<Problem, OError>`
    pub fn problem(&self) -> Result<Problem, OError> {
        self.problem.clone().try_into()
    }

    /// Build the vector of [`Individual`] from serialised data. Each individual will have the
    /// objective, constraint, variable and data values from the serialised data.
    ///
    /// returns: `Result<Vec<Individual>, OError>`
    pub fn individuals(&self) -> Result<Vec<Individual>, OError> {
        let problem = Arc::new(self.problem()?);
        let mut individuals: Vec<Individual> = vec![];
        for individual_data in &self.individuals {
            let mut ind = Individual::new(problem.clone());
            for (name, value) in &individual_data.objective_values {
                ind.update_objective(name, *value)?;
            }
            for (name, value) in &individual_data.constraint_values {
                ind.update_constraint(name, *value)?;
            }
            for (name, value) in &individual_data.variable_values {
                ind.update_variable(name, value.clone())?;
            }
            for (name, value) in &individual_data.data {
                ind.set_data(name, value.clone());
            }
            ind.set_evaluated();
            individuals.push(ind);
        }

        Ok(individuals)
    }

    #[cfg(feature = "plotting")]
    /// Plot the Pareto front from the results.
    ///
    /// # Arguments
    ///
    /// * `destination`: The path and file name where to save the PNG file.
    /// * `fig_size`: An optional argument to change the figure size. When `None` this
    /// defaults to [800, 500] px.
    ///
    /// returns: `Result<f64, OError>`
    pub fn plot_front(
        &self,
        destination: &PathBuf,
        fig_size: Option<[u32; 2]>,
    ) -> Result<(), OError> {
        use gnuplot::AxesCommon;
        use gnuplot::{
            Figure,
            PlotOption::{Color, PointSymbol},
        };

        let fig_size = fig_size.unwrap_or([800, 500]);
        let title = format!(
            "Results for {} @ generation={} \nPopulation size={}",
            self.algorithm,
            self.generation,
            self.individuals.len()
        );
        let obj_count = self.problem.number_of_objectives;
        let obj_names = self.problem.objective_names.clone();
        let mut fg = Figure::new();
        let point_style = [PointSymbol('O'), Color("black".into())];

        if obj_count >= 2 && obj_count <= 3 {
            let obj1_name = obj_names.get(0).unwrap();
            let obj2_name = obj_names.get(1).unwrap();

            let obj1: Vec<f64> = self
                .individuals()?
                .iter()
                .map(|i| i.get_objective_value(obj1_name).unwrap())
                .collect();
            let obj2: Vec<f64> = self
                .individuals()?
                .iter()
                .map(|i| i.get_objective_value(obj2_name).unwrap())
                .collect();

            if obj_count == 2 {
                fg.axes2d()
                    .points(obj1, obj2, &point_style)
                    .set_x_label(obj1_name, &[])
                    .set_y_label(obj2_name, &[])
                    .set_x_grid(true)
                    .set_y_grid(true)
                    .set_title(&title, &[]);
            } else {
                let obj3_name = obj_names.get(2).unwrap();
                let obj3: Vec<f64> = self
                    .individuals()?
                    .iter()
                    .map(|i| i.get_objective_value(obj3_name).unwrap())
                    .collect();
                fg.axes3d()
                    .points(obj1, obj2, obj3, &point_style)
                    .set_x_label(obj1_name, &[])
                    .set_y_label(obj2_name, &[])
                    .set_z_label(obj3_name, &[])
                    .set_x_grid(true)
                    .set_y_grid(true)
                    .set_z_grid(true)
                    .set_view(40.0, 110.0)
                    .set_title(&title, &[]);
            }

            return fg
                .save_to_png(destination, fig_size[0], fig_size[1])
                .map_err(|e| {
                    OError::Generic(format!("Cannot save the chart because {}", e.to_string()))
                });
        } else {
            return Err(OError::Generic(
                "Plotting of Pareto front is only supported for a 2 or 3-objective problem"
                    .to_string(),
            ));
        }
    }
}

/// Convert the [`AlgorithmSerialisedExport`] to [`AlgorithmExport`]
impl<T: Serialize> TryInto<AlgorithmExport> for AlgorithmSerialisedExport<T> {
    type Error = OError;

    fn try_into(self) -> Result<AlgorithmExport, Self::Error> {
        let data = AlgorithmExport {
            problem: Arc::new(self.problem()?),
            individuals: self.individuals()?,
            generation: self.generation,
            algorithm: self.algorithm,
            number_of_function_evaluations: self.number_of_function_evaluations,
            took: self.took,
            additional_data: self.additional_data.unwrap_or_default(),
        };
        Ok(data)
    }
}

/// The enum to determine how to group vectorial results.
pub enum ExportVecGroupBy {
    /// Return a vector reporting the results for each individual. The length of each
    /// nested vector equals the number of objectives.
    Individual,
    /// Return a vector reporting the results for each objective. The length of each
    /// nested vector equals the number of individuals in the population.
    Objective,
}

/// The type of reference points used in the [`AdaptiveNSGA3`]
pub struct ReferencePointType {
    /// The location of the original reference points (i.e. the points that were used
    /// to initialise the algorithm). These are the points that are always preserved
    /// during the optimisation.
    pub original: Vec<Vec<f64>>,
    /// The new points that were added along with the original point to reduce crowding
    /// and to allocate one point for each Pareto-optimal solution.
    pub new: Vec<Vec<f64>>,
}

/// The struct used to export an algorithm data.
#[derive(Debug)]
pub struct AlgorithmExport {
    /// The problem.
    pub problem: Arc<Problem>,
    /// The individuals with the solutions, constraint and objective values at the current generation.
    pub individuals: Vec<Individual>,
    /// The generation number.
    pub generation: u32,
    /// The number of function evaluations
    pub number_of_function_evaluations: u32,
    /// The algorithm name used to evolve the individuals.
    pub algorithm: String,
    /// The time the algorithm took to reach the current generation.
    pub took: Elapsed,
    /// Additional data stored in the algorithm (such as reference points for [`crate::algorithms::NSGA3`]).
    pub additional_data: HashMap<String, DataValue>,
}

impl AlgorithmExport {
    /// Get the numbers stored in a real variable in all individuals. This returns an error if the
    /// variable does not exist or is not a real type.
    ///
    /// # Arguments
    ///
    /// * `name`: The variable name.
    ///
    /// returns: `Result<f64, OError>`
    pub fn get_real_variables(&self, name: &str) -> Result<Vec<f64>, OError> {
        self.individuals
            .iter()
            .map(|i| i.get_real_value(name))
            .collect()
    }

    /// Get the numbers stored in an objective for all individuals. This returns an error if the
    /// objective does not exist.
    ///
    /// # Arguments
    ///
    /// * `name`: The objective name.
    ///
    /// returns: `Result<f64, OError>`
    pub fn get_objective(&self, name: &str) -> Result<Vec<f64>, OError> {
        self.individuals
            .iter()
            .map(|i| i.get_objective_value(name))
            .collect()
    }

    /// Get the objective values grouped by objective name.
    ///
    /// returns: `Result<HashMap<String, Vec<f64>>, OError>`
    pub fn get_objectives(&self) -> Result<HashMap<String, Vec<f64>>, OError> {
        let mut map = HashMap::new();
        for name in self.problem.objective_names() {
            let data_vec = self
                .individuals
                .iter()
                .map(|i| i.get_objective_value(&name))
                .collect::<Result<Vec<f64>, OError>>()?;
            map.insert(name, data_vec);
        }
        Ok(map)
    }

    /// Reshape a vector containing data for each individuals [NxM] into a vector containing data
    /// for each objective [MxN].
    fn group_by_objective(&self, vector: Vec<Vec<f64>>) -> Result<Vec<Vec<f64>>, OError> {
        let mut vector_by_objectives = vec![vec![]; self.problem.number_of_objectives()];
        for ind_objectives in vector.into_iter() {
            for obj_num in 0..self.problem.number_of_objectives() {
                let value = ind_objectives.get(obj_num);
                match value {
                    Some(v) => vector_by_objectives[obj_num].push(v.clone()),
                    None => {
                        return Err(OError::Generic(format!("Cannot group objective {obj_num}")));
                    }
                }
            }
        }
        Ok(vector_by_objectives)
    }

    /// Get the values of the normalised objective derived using the NSGA3 algorithm. This
    /// will return an error if the results were derived using another algorithm.
    ///
    /// # Arguments
    ///
    /// * `group_by`: Determine how the results are returned. When [`ExportVecGroupBy::Individual`],
    /// this returns a vector of vectors. The main vector have size equal to the number of
    /// individuals and the nested vectors have length equal to the objective number. When
    /// [`ExportVecGroupBy::Objective`], the vector is reshaped so that the main vector
    /// have size equal to the number of objectives and the nested vector length equal to
    /// the number of individuals.
    ///
    /// returns `Result<Vec<Vec<f64>>, OError>`: The vector with the value of the normalised
    /// objectives. The data is grouped based on the `group_by` value.
    pub fn get_nsga3_normalised_objectives(
        &self,
        group_by: ExportVecGroupBy,
    ) -> Result<Vec<Vec<f64>>, OError> {
        if self.algorithm != "NSGA3" {
            return Err(OError::Generic(
                "The exported data were not derived using NSGA3".to_string(),
            ));
        }

        let mut all_normalised_objectives_per_ind = Vec::new();
        for ind in self.individuals.iter() {
            all_normalised_objectives_per_ind
                .push(ind.get_data("normalised_objectives")?.as_f64_vec()?.clone());
        }

        let results = match group_by {
            ExportVecGroupBy::Individual => all_normalised_objectives_per_ind,
            //  self.group_by_objective(all_normalised_objectives_per_ind)?
            ExportVecGroupBy::Objective => {
                let mut all_normalised_objectives =
                    vec![vec![]; self.problem.number_of_objectives()];
                for ind_objectives in all_normalised_objectives_per_ind.into_iter() {
                    for obj_num in 0..self.problem.number_of_objectives() {
                        let value = ind_objectives.get(obj_num);
                        match value {
                            Some(v) => all_normalised_objectives[obj_num].push(v.clone()),
                            None => {
                                return Err(OError::Generic(format!(
                                    "Cannot group objective {obj_num}"
                                )));
                            }
                        }
                    }
                }
                all_normalised_objectives
            }
        };
        Ok(results)
    }

    /// Get the values of the reference points used by the NSGA3 algorithm. This
    /// will return an error if the results were derived using another algorithm.
    ///
    /// # Arguments
    ///
    /// * `group_by`: Determine how the results are returned. When [`ExportVecGroupBy::Individual`],
    /// this returns a vector of vectors. The main vector have size equal to the number of
    /// individuals and the nested vectors have length equal to the objective number. When
    /// [`ExportVecGroupBy::Objective`], the vector is reshaped so that the main vector
    /// have size equal to the number of objectives and the nested vector length equal to
    /// the number of individuals.
    ///
    /// returns `Result<Vec<Vec<f64>>, OError>`: The vector with the value of the reference
    /// points. The data is grouped based on the `group_by` value.
    pub fn get_nsga3_reference_points(
        &self,
        group_by: ExportVecGroupBy,
    ) -> Result<Vec<Vec<f64>>, OError> {
        if self.algorithm != "NSGA3" {
            return Err(OError::Generic(
                "The exported data were not derived using NSGA3".to_string(),
            ));
        }

        let ref_points_per_ind = match self.additional_data.get("reference_points") {
            Some(values) => {
                let mut ref_points = vec![];
                for point_vec in values.as_data_vec()?.into_iter() {
                    ref_points.push(point_vec.as_f64_vec()?.clone());
                }
                ref_points
            }
            None => {
                return Err(OError::Generic(format!("Cannot group reference_points")));
            }
        };

        let results: Vec<Vec<f64>> = match group_by {
            ExportVecGroupBy::Individual => ref_points_per_ind,
            ExportVecGroupBy::Objective => self.group_by_objective(ref_points_per_ind)?,
        };
        Ok(results)
    }

    /// Get the values of the reference points used by the adaptive NSGA3 algorithm. This
    /// function returns to group of points:
    /// - original point: these are the points that were used to initialise the algorithm
    /// and that are always preserved during the optimisation.
    /// - adaptive points: the new points that were added along with the original point
    /// to reduce crowding and to allocate one point for each Pareto-optimal solution.
    ///
    /// This will return an error if the results were derived using another algorithm.
    ///
    /// # Arguments
    ///
    /// * `group_by`: Determine how the results are returned. When [`ExportVecGroupBy::Individual`],
    /// this returns a vector of vectors. The main vector have size equal to the number of
    /// individuals and the nested vectors have length equal to the objective number. When
    /// [`ExportVecGroupBy::Objective`], the vector is reshaped so that the main vector
    /// have size equal to the number of objectives and the nested vector length equal to
    /// the number of individuals.
    ///
    /// returns `Result<Vec<Vec<f64>>, OError>`: The vector with the value of the reference
    /// points. The data is grouped based on the `group_by` value.
    pub fn get_adaptive_nsga3_reference_points(
        &self,
        group_by: ExportVecGroupBy,
    ) -> Result<ReferencePointType, OError> {
        let mut ref_points = self.get_nsga3_reference_points(ExportVecGroupBy::Individual)?;
        // split using the original number of points
        let original_point_count = match self.additional_data.get("number_of_reference_points") {
            Some(count) => count.as_real()?, // NOTE: this is deserialised as real
            None => {
                return Err(OError::Generic(
                    "Cannot find additional_data.number_of_reference_points".to_string(),
                ))
            }
        };
        let adaptive_points = ref_points.split_off(original_point_count as usize);

        let result = match group_by {
            ExportVecGroupBy::Individual => ReferencePointType {
                original: ref_points,
                new: adaptive_points,
            },
            ExportVecGroupBy::Objective => ReferencePointType {
                original: self.group_by_objective(ref_points)?,
                new: self.group_by_objective(adaptive_points)?,
            },
        };

        Ok(result)
    }
}

impl Display for AlgorithmExport {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "{} at {} generations, took {} hours, {} minutes and {} seconds",
            self.algorithm, self.generation, self.took.hours, self.took.minutes, self.took.seconds
        )
    }
}

/// A struct with the options to configure the individual's history export. Export may be enabled in
/// an algorithm to save objectives, constraints and solutions to a file each time the generation
/// counter in [`Algorithm::generation`] increases by a certain step provided in `generation_step`.
/// Exporting history may be useful to track convergence and inspect an algorithm evolution.
#[cfg_attr(feature = "python", pyclass(get_all, from_py_object))]
#[derive(Serialize, Deserialize, Clone, Debug)]
pub struct ExportHistory {
    /// Export the algorithm data each time the generation counter in [`Algorithm::generation`]
    /// increases by the provided step.
    generation_step: usize,
    /// Serialise the algorithm history and export the results to a JSON file in the given folder.
    destination: PathBuf,
}

impl ExportHistory {
    /// Initialise the export history configuration. This returns an error if the destination folder
    /// does not exist.
    ///
    /// # Arguments
    ///
    /// * `generation_step`: export the algorithm data each time the generation counter in a genetic
    //  algorithm increases by the provided step.
    /// * `destination`: serialise the algorithm history and export the results to a JSON file in
    ///    the given folder.
    ///
    /// returns: `Result<ExportHistory, OError>`
    pub fn new(generation_step: usize, destination: &PathBuf) -> Result<Self, OError> {
        if !destination.exists() {
            return Err(OError::Generic(format!(
                "The destination folder '{:?}' does not exist",
                destination
            )));
        }
        Ok(Self {
            generation_step,
            destination: destination.to_owned(),
        })
    }

    /// Get the destination where to save the files.
    ///
    /// returns: `&PathBuf`
    pub fn destination(&self) -> &PathBuf {
        &self.destination
    }

    /// Get the number of generation step the history file is saved.
    ///
    /// returns: `usize`
    pub fn generation_step(&self) -> usize {
        self.generation_step
    }
}

#[cfg(feature = "python")]
#[pymethods]
impl ExportHistory {
    #[new]
    fn py_new(generation_step: usize, destination: PathBuf) -> PyResult<Self> {
        ExportHistory::new(generation_step, &destination)
            .map_err(|e| PyValueError::new_err(e.to_string()))
    }
}

/// The trait to use to implement an algorithm.
pub trait Algorithm<AlgorithmOptions: Serialize + DeserializeOwned>: Display {
    /// Initialise the algorithm.
    ///
    /// return: `Result<(), OError>`
    fn initialise(&mut self) -> Result<(), OError>;

    /// Evolve the population.
    ///
    /// return: `Result<(), OError>`
    fn evolve(&mut self) -> Result<(), OError>;

    /// Return the current step of the algorithm evolution.
    ///
    /// return: `u32`.
    fn generation(&self) -> u32;

    /// Return the number of function evaluations. This is the number of times the algorithm evaluates
    /// an individual's objectives and constraints using [`Algorithm::evaluate_individual`]. If no
    /// new solutions/individuals are chosen by an algorithm, this counter will not increase, as past
    /// solutions are already evaluated.
    ///
    /// return: `u32`.
    fn number_of_function_evaluations(&self) -> u32;

    /// Return the algorithm name.
    ///
    /// return: `String`.
    fn name(&self) -> String;

    /// Get the time when the algorithm started.
    ///
    /// return: `&Instant`.
    fn start_time(&self) -> &Instant;

    /// Return the stopping condition.
    ///
    /// return: `&StoppingConditionType`.
    fn stopping_condition(&self) -> &StoppingCondition;

    /// Return the evolved population.
    ///
    /// return: `&Population`.
    fn population(&self) -> &Population;

    /// Return the problem.
    ///
    /// return: `Arc<Problem>`.
    fn problem(&self) -> Arc<Problem>;

    /// Return the history export configuration, if provided by the algorithm.
    ///
    /// return: `Option<&ExportHistory>`.
    fn export_history(&self) -> Option<&ExportHistory>;

    /// Export additional data stored by the algorithm.
    ///
    /// return: `Option<HashMap<String, DataValue>>`
    fn additional_export_data(&self) -> Option<HashMap<String, DataValue>> {
        None
    }

    /// Get the elapsed hours, minutes and seconds since the start of the algorithm.
    ///
    /// return: `[u64; 3]`. An array with the number of elapsed hours, minutes and seconds.
    fn elapsed(&self) -> [u64; 3] {
        let duration = self.start_time().elapsed();
        let seconds = duration.as_secs() % 60;
        let minutes = (duration.as_secs() / 60) % 60;
        let hours = (duration.as_secs() / 60) / 60;
        [hours, minutes, seconds]
    }

    /// Format the elapsed time as string.
    ///
    /// return: `String`.
    fn elapsed_as_string(&self) -> String {
        let [hours, minutes, seconds] = self.elapsed();
        format!(
            "{:0>2} hours, {:0>2} minutes and {:0>2} seconds",
            hours, minutes, seconds
        )
    }

    /// Evaluate the objectives and constraints for unevaluated individuals in the population. This
    /// updates the individual data only, runs the evaluation function in threads and increase the
    /// `nfe` counter by the number of evaluated individuals.
    /// This returns an error if the evaluation function fails or the evaluation function does not
    /// provide a value for a problem constraints or objectives for one individual.
    ///
    /// # Arguments
    ///
    /// * `individuals`: The individuals to evaluate.
    /// * `nfe`: The reference to the number of function evaluation counter.
    ///
    /// return `Result<(), OError>`
    fn do_parallel_evaluation(individuals: &mut [Individual], nfe: &mut u32) -> Result<(), OError> {
        let delta_nfe = Self::count_unevaluated(individuals);
        individuals
            .into_par_iter()
            .enumerate()
            .try_for_each(|(idx, i)| Self::evaluate_individual(idx, i))?;
        *nfe += delta_nfe;
        Ok(())
    }

    /// Evaluate the objectives and constraints for unevaluated individuals in the population. This
    /// updates the individual data only, runs the evaluation function in a plain loop and increase
    /// the `nfe` counter by the number of evaluated individuals.
    /// This returns an error if the evaluation function fails or the evaluation function does not
    /// provide a value for a problem constraints or objectives for one individual.
    /// Evaluation may be performed in threads using [`Self::do_parallel_evaluation`].
    ///
    /// # Arguments
    ///
    /// * `individuals`: The individuals to evaluate.
    /// * `nfe`: The reference to the number of function evaluation counter.
    ///
    /// return `Result<usize, OError>`.
    fn do_evaluation(individuals: &mut [Individual], nfe: &mut u32) -> Result<(), OError> {
        let delta_nfe = Self::count_unevaluated(individuals);
        individuals
            .iter_mut()
            .enumerate()
            .try_for_each(|(idx, i)| Self::evaluate_individual(idx, i))?;
        *nfe += delta_nfe;
        Ok(())
    }

    /// Evaluate the objectives and constraints for one unevaluated individual. This returns an
    /// error if the evaluation function fails or the evaluation function does not provide a
    /// value for a problem constraints or objectives.
    ///
    /// # Arguments
    ///
    /// * `idx`: The individual index.
    /// * `individual`: The individual to evaluate.
    ///
    /// return `Result<(), OError>`
    fn evaluate_individual(idx: usize, i: &mut Individual) -> Result<(), OError> {
        debug!("Evaluating individual #{} - {:?}", idx + 1, i.variables());

        // skip evaluated solutions
        if i.is_evaluated() {
            debug!("Skipping evaluation for individual #{idx}. Already evaluated.");
            return Ok(());
        }
        let problem = i.problem();
        let results = problem
            .evaluator()
            .evaluate(i)
            .map_err(|e| OError::Evaluation(e.to_string()))?;

        // update the objectives and constraints for the individual
        debug!("Updating individual #{idx} objectives and constraints");
        for name in problem.objective_names() {
            if !results.objectives.contains_key(&name) {
                return Err(OError::Evaluation(format!(
                    "The evaluation function did non return the value for the objective named '{}'",
                    name
                )));
            };
            i.update_objective(&name, results.objectives[&name])?;
        }
        if let Some(constraints) = results.constraints {
            for name in problem.constraint_names() {
                if !constraints.contains_key(&name) {
                    return Err(OError::Evaluation(format!(
                        "The evaluation function did non return the value for the constraints named '{}'",
                        name
                    )));
                };

                i.update_constraint(&name, constraints[&name])?;
            }
        }
        i.set_evaluated();
        Ok(())
    }

    /// Count the number on unevaluated individuals.
    ///
    /// # Arguments
    ///
    /// * `individuals`: The individuals to check.
    ///
    /// returns: `u32`
    fn count_unevaluated(individuals: &[Individual]) -> u32 {
        individuals
            .iter()
            .filter_map(|i| if !i.is_evaluated() { Some(1) } else { None })
            .sum()
    }
    /// Run the algorithm.
    ///
    /// return: `Result<(), OError>`
    fn run(&mut self) -> Result<(), OError> {
        info!("Starting {}", self.name());
        self.initialise()?;
        // Export at init
        if let Some(export) = self.export_history() {
            self.save_to_json(&export.destination, Some("Init"))?;
        }

        let mut history_gen_step: usize = 0;
        loop {
            // Export history
            if let Some(export) = self.export_history() {
                if history_gen_step == export.generation_step - 1 {
                    self.save_to_json(&export.destination, None)?;
                    history_gen_step = 0;
                } else {
                    history_gen_step += 1;
                }
            }

            // Evolve population
            info!("Generation #{}", self.generation());
            self.evolve()?;
            info!(
                "Evolved generation #{} - Elapsed Time: {}",
                self.generation(),
                self.elapsed_as_string()
            );
            debug!("========================");
            debug!("");
            debug!("");

            // Termination
            let cond = self.stopping_condition();
            let terminate = self.is_stopping_condition_met(cond)?;
            if terminate {
                // save last file
                if let Some(export) = self.export_history() {
                    self.save_to_json(&export.destination, Some("Final"))?;
                }

                info!("Stopping evolution because the {} was reached", cond.name());
                info!("Took {}", self.elapsed_as_string());
                break;
            }
        }

        Ok(())
    }

    /// Check if the given stopping condition is met.
    ///
    /// # Arguments
    ///
    /// * `condition`: The stopping condition type.
    ///
    /// returns: `Result<bool, OError>`
    fn is_stopping_condition_met(&self, condition: &StoppingCondition) -> Result<bool, OError> {
        let is_met = match condition {
            StoppingCondition::MaxDurationAsMinutes(duration) => {
                *duration <= ((Instant::now().elapsed().as_secs() / 60) as u32)
            }
            StoppingCondition::MaxDurationAsHours(duration) => {
                *duration <= ((Instant::now().elapsed().as_secs() / 60 / 60) as u32)
            }
            StoppingCondition::MaxGeneration(generation) => *generation <= self.generation(),
            StoppingCondition::MaxFunctionEvaluations(nfe) => {
                *nfe <= self.number_of_function_evaluations()
            }
            StoppingCondition::Any(conditions) => {
                if StoppingCondition::has_nested_vector(conditions) {
                    return Err(OError::AlgorithmRun(
                        self.name(),
                        "A vector of stopping condition vector is not allowed".to_string(),
                    ));
                }
                conditions
                    .iter()
                    .any(|c| self.is_stopping_condition_met(c).unwrap())
            }
            StoppingCondition::All(conditions) => {
                if StoppingCondition::has_nested_vector(conditions) {
                    return Err(OError::AlgorithmRun(
                        self.name(),
                        "A vector of stopping condition vector is not allowed".to_string(),
                    ));
                }
                conditions
                    .iter()
                    .all(|c| self.is_stopping_condition_met(c).unwrap())
            }
        };
        Ok(is_met)
    }

    /// Get the results of the run.
    ///
    /// return: `AlgorithmExport`.
    fn get_results(&self) -> AlgorithmExport {
        let [hours, minutes, seconds] = self.elapsed();
        AlgorithmExport {
            problem: self.problem(),
            individuals: self.population().individuals().to_vec(),
            generation: self.generation(),
            number_of_function_evaluations: self.number_of_function_evaluations(),
            algorithm: self.name(),
            took: Elapsed {
                hours,
                minutes,
                seconds,
            },
            additional_data: self.additional_export_data().unwrap_or_default(),
        }
    }

    fn algorithm_options(&self) -> AlgorithmOptions;

    /// Save the algorithm data (individuals' objective, variables and constraints, the problem,
    /// ...) to a JSON file. This returns an error if the file cannot be saved.
    ///
    /// # Arguments
    ///
    /// * `destination`: The path to the JSON file.
    /// * `file_prefix`: A prefix to prepend at the beginning of the file name. Empty when `None`.
    ///
    /// return `Result<(), OError>`
    fn save_to_json(&self, destination: &PathBuf, file_prefix: Option<&str>) -> Result<(), OError> {
        let file_prefix = file_prefix.unwrap_or("History");

        let [hours, minutes, seconds] = self.elapsed();
        let export = AlgorithmSerialisedExport {
            options: self.algorithm_options(),
            problem: self.problem().serialise(),
            individuals: self.population().serialise(),
            generation: self.generation(),
            number_of_function_evaluations: self.number_of_function_evaluations(),
            algorithm: self.name(),
            additional_data: self.additional_export_data(),
            took: Elapsed {
                hours,
                minutes,
                seconds,
            },
            exported_on: Utc::now(),
        };
        let data = serde_json::to_string_pretty(&export).map_err(|e| {
            OError::AlgorithmExport(format!(
                "The following error occurred while converting the history struct: {e}"
            ))
        })?;

        let mut file = destination.to_owned();

        file.push(format!(
            "{}_{}_gen{}.json",
            file_prefix,
            self.name(),
            self.generation()
        ));

        info!("Saving JSON file {:?}", file);
        fs::write(file, data).map_err(|e| {
            OError::AlgorithmExport(format!(
                "The following error occurred while exporting the history JSON file: {e}",
            ))
        })?;
        Ok(())
    }

    /// Read the results previously exported with [`Self::save_to_json`].
    ///
    /// # Arguments
    ///
    /// * `file`: The path to the JSON file exported from this library.
    ///
    /// returns: `Result<AlgorithmSerialisedExport<T>, OError>`
    fn read_json_file(
        file: &PathBuf,
    ) -> Result<AlgorithmSerialisedExport<AlgorithmOptions>, OError> {
        if !file.exists() {
            return Err(OError::File(
                file.to_path_buf(),
                "the file does not exist".to_string(),
            ));
        }
        let data = fs::File::open(file).map_err(|e| {
            OError::File(
                file.to_path_buf(),
                format!("cannot read the JSON file because: {e}"),
            )
        })?;

        let mut history: AlgorithmSerialisedExport<AlgorithmOptions> =
            serde_json::from_reader(data).map_err(|e| {
                OError::File(
                    file.to_path_buf(),
                    format!("cannot parse the JSON file because: {e}"),
                )
            })?;

        // invert sign of maximised objective values
        for ind in &mut history.individuals {
            for (name, value) in ind.objective_values.iter_mut() {
                if history.problem.objectives[name].direction() == ObjectiveDirection::Maximise {
                    *value *= -1.0;
                }
            }
        }

        Ok(history)
    }

    /// Read the results from files exported during an algorithm evolution. This returns an error if
    /// the path does not exist or does not contain valid JSON files.
    ///
    /// # Arguments
    ///
    /// * `folder`: The folder path to the JSON files.
    ///
    /// returns: `Result<Vec<AlgorithmSerialisedExport<T>>, OError>`
    fn read_json_files(
        folder: &PathBuf,
    ) -> Result<Vec<AlgorithmSerialisedExport<AlgorithmOptions>>, OError> {
        let json_files: Vec<_> = read_dir(folder)
            .map_err(|e| OError::Generic(format!("Cannot read folder because {e}")))?
            .filter_map(|res| res.ok())
            .map(|dir_entry| dir_entry.path())
            .filter_map(|path| {
                if path.extension().map_or(false, |ext| ext == "json") {
                    Some(path)
                } else {
                    None
                }
            })
            .collect();

        let results = json_files
            .iter()
            .map(|file| Self::read_json_file(file))
            .collect::<Result<Vec<_>, OError>>()?;
        Ok(results)
    }

    /// Seed the population using the values of variables, objectives and constraints exported
    /// to a JSON file.
    ///
    /// # Arguments
    ///
    /// * `problem`: The problem.
    /// * `name`: The algorithm name.
    /// * `expected_individuals`: The number of individuals to expect in the file. If this does not
    ///     match the population size, being used in the algorithm, an error is thrown.
    /// * `file`: The path to the JSON file exported from this library.
    ///
    /// returns: `Result<Population, OError>`
    fn seed_population_from_file(
        problem: Arc<Problem>,
        name: &str,
        expected_individuals: usize,
        file: &PathBuf,
    ) -> Result<Population, OError> {
        let data = Self::read_json_file(file)?;

        // check number of variables
        if problem.number_of_variables() != data.problem.variables.len() {
            return Err(OError::AlgorithmInit(
                name.to_string(),
                format!(
                    "The number of variables from the history file ({}) does not \
                    match the number of variables ({}) defined in the problem",
                    data.problem.variables.len(),
                    problem.number_of_variables()
                ),
            ));
        }

        // check individuals
        if expected_individuals != data.individuals.len() {
            return Err(OError::AlgorithmInit(
                name.to_string(),
                format!(
                    "The number of individuals from the history file ({}) does not \
                    match the population size ({}) used in the algorithm",
                    data.problem.variables.len(),
                    problem.number_of_variables()
                ),
            ));
        }

        Population::deserialise(&data.individuals, problem.clone())
    }
}

/// Enum used to identify the chosen algorithm and its options in a python wrapper. Pass this
/// to another python class to then match and run an algorithm from Rust.
///
/// # Python example
/// ```python
/// # define the NSGA2 options
/// args = NSGA2Arg(
///     number_of_individuals=10,
///     stopping_condition=StoppingCondition(
///         condition=StoppingConditionValue.max_duration(3)
///     )
/// )
///
/// # initialise the enum
/// algo = Algorithm.nsga2(args)
/// ```
#[cfg(feature = "python")]
#[pyclass(from_py_object, name = "Algorithm")]
#[derive(Clone)]
#[allow(non_camel_case_types)]
pub enum PyAlgorithm {
    nsga2 { options: NSGA2Arg },
    nsga3 { options: NSGA3Arg },
    adaptive_nsga3 { options: NSGA3Arg },
}

#[cfg(feature = "python")]
#[pymethods]
impl PyAlgorithm {
    fn __repr__(&self) -> PyResult<String> {
        let value = match self {
            PyAlgorithm::nsga2 { options } => {
                format!("NSGA2(options={:?})", options.__repr__()?)
            }
            PyAlgorithm::nsga3 { options } => {
                format!("NSGA3(options={:?})", options.__repr__()?)
            }
            PyAlgorithm::adaptive_nsga3 { options } => {
                format!("AdaptiveNSGA3(options={:?})", options.__repr__()?)
            }
        };
        Ok(value)
    }

    fn __str__(&self) -> String {
        self.__repr__().unwrap()
    }
}

// Macro to generate python class for an algorithm data reader
#[cfg(feature = "python")]
macro_rules! create_py_reader_interface {
    ($name: ident, $type: ident, $ArgType: ident) => {
        #[pyclass]
        pub struct $name {
            export_data: crate::algorithms::AlgorithmExport,
            #[pyo3(get)]
            problem: crate::core::PyProblem,
            #[pyo3(get)]
            individuals: Vec<Individual>,
            #[pyo3(get)]
            took: Py<PyAny>,
            #[pyo3(get)]
            objectives: std::collections::HashMap<String, Vec<f64>>,
            #[pyo3(get)]
            additional_data: Option<std::collections::HashMap<String, DataValue>>,
            #[pyo3(get)]
            exported_on: chrono::DateTime<chrono::Utc>,
        }

        #[pymethods]
        impl $name {
            #[new]
            /// Initialise the class
            pub fn new(file: PathBuf) -> PyResult<Self> {
                let path = PathBuf::from(file);
                let file_data: crate::algorithms::AlgorithmSerialisedExport<$ArgType> =
                    $type::read_json_file(&path)
                        .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;

                // Algorthm data
                let additional_data = file_data.additional_data.clone();
                let exported_on = file_data.exported_on.clone();

                // Convert export
                let export_data: crate::algorithms::AlgorithmExport = file_data
                    .try_into()
                    .map_err(|e: OError| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;

                // Problem
                let problem: crate::core::PyProblem = export_data.problem.as_ref().into();

                // Time taken
                let took = Python::attach(|py| -> PyResult<Py<PyAny>> {
                    let module = PyModule::import(py, "datetime")?;

                    let timedelta = module.getattr("timedelta")?;
                    let kwargs = pyo3::types::IntoPyDict::into_py_dict(
                        &[
                            ("hours", export_data.took.hours),
                            ("minutes", export_data.took.minutes),
                            ("seconds", export_data.took.seconds),
                        ],
                        py,
                    )?;
                    let result = timedelta.call((), Some(&kwargs))?;
                    Ok(result.extract::<Py<PyAny>>()?)
                })?;

                // Individuals
                let individuals = export_data.individuals.clone();

                // All objective values by name
                let objectives = export_data
                    .get_objectives()
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;

                Ok(Self {
                    export_data,
                    problem,
                    took,
                    individuals,
                    objectives,
                    additional_data,
                    exported_on,
                })
            }

            #[getter]
            /// Get the generation number.
            pub fn generation(&self) -> u32 {
                self.export_data.generation
            }

            #[getter]
            /// Get the algorithm name.
            pub fn algorithm(&self) -> String {
                self.export_data.algorithm.clone()
            }

            /// Calculate the hyper-volume metric.
            pub fn hyper_volume(&mut self, reference_point: Vec<f64>) -> PyResult<f64> {
                let hv = crate::metrics::HyperVolume::from_individual(
                    &mut self.export_data.individuals,
                    &reference_point,
                )
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
                Ok(hv)
            }

            /// Estimate the reference point from serialised data.
            #[pyo3(signature = (offset=None))]
            pub fn estimate_reference_point(&self, offset: Option<Vec<f64>>) -> PyResult<Vec<f64>> {
                let individuals = &self.export_data.individuals;
                let ref_point =
                    crate::metrics::HyperVolume::estimate_reference_point(individuals, offset)
                        .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
                Ok(ref_point)
            }

            /// Estimate the reference point from files.
            #[staticmethod]
            #[pyo3(signature = (folder, offset=None))]
            pub fn estimate_reference_point_from_files(
                folder: PathBuf,
                offset: Option<Vec<f64>>,
            ) -> PyResult<Vec<f64>> {
                let all_serialise_data_vec = $type::read_json_files(&folder)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
                let ref_point = crate::metrics::HyperVolume::estimate_reference_point_from_files(
                    &all_serialise_data_vec,
                    offset,
                )
                .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
                Ok(ref_point)
            }

            #[staticmethod]
            pub fn convergence_data(
                folder: String,
                reference_point: Vec<f64>,
            ) -> PyResult<(Vec<u32>, Vec<chrono::DateTime<chrono::Utc>>, Vec<f64>)> {
                let folder = PathBuf::from(folder);
                let all_serialise_data = $type::read_json_files(&folder)
                    .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;
                let data =
                    crate::metrics::HyperVolume::from_files(&all_serialise_data, &reference_point)
                        .map_err(|e| pyo3::exceptions::PyValueError::new_err(e.to_string()))?;

                Ok((data.generations(), data.times(), data.values()))
            }
        }
    };
}
// // Export macro to parent module
#[cfg(feature = "python")]
pub(crate) use create_py_reader_interface;

#[cfg(test)]
mod test {
    use std::env;
    use std::path::Path;
    use std::sync::Arc;

    use crate::algorithms::{Algorithm, NSGA2Arg, StoppingCondition, NSGA2};
    use crate::core::builtin_problems::{SCHProblem, ZTD1Problem};

    #[test]
    /// Test seed_population_from_file
    fn test_load_from_file() {
        let file = Path::new(&env::current_dir().unwrap())
            .join("examples")
            .join("results")
            .join("SCH_2obj_NSGA2_gen250.json");

        let problem = SCHProblem::create().unwrap();
        let pop = NSGA2::seed_population_from_file(Arc::new(problem), "NSGA2", 100, &file);
        assert!(pop.is_ok());
    }

    #[test]
    /// Test seed_population_from_file when the number of individuals is wrong.
    fn test_load_from_file_error() {
        let file = Path::new(&env::current_dir().unwrap())
            .join("examples")
            .join("results")
            .join("SCH_2obj_NSGA2_gen250.json");

        let problem = SCHProblem::create().unwrap();
        let pop = NSGA2::seed_population_from_file(Arc::new(problem), "NSGA2", 10, &file);
        assert!(pop
            .err()
            .unwrap()
            .to_string()
            .contains("number of individuals from the history file"));
    }

    #[test]
    /// Test seed_population_from_file when the wrong problem is used.
    fn test_load_from_file_wrong_problem() {
        let file = Path::new(&env::current_dir().unwrap())
            .join("examples")
            .join("results")
            .join("SCH_2obj_NSGA2_gen250.json");

        let problem = ZTD1Problem::create(30).unwrap();
        let pop = NSGA2::seed_population_from_file(Arc::new(problem), "NSGA2", 10, &file);

        assert!(pop
            .err()
            .unwrap()
            .to_string()
            .contains("number of variables from the history file"));
    }

    #[test]
    /// Test StoppingConditionType::MaxGeneration
    fn test_stopping_condition_max_generation() {
        let problem = SCHProblem::create().unwrap();
        let args = NSGA2Arg {
            number_of_individuals: 10,
            stopping_condition: StoppingCondition::MaxGeneration(20),
            crossover_operator_options: None,
            mutation_operator_options: None,
            parallel: Some(false),
            export_history: None,
            resume_from_file: None,
            seed: Some(10),
        };
        let mut algo = NSGA2::new(problem, args).unwrap();
        algo.run().unwrap();
        let results = algo.get_results();

        assert_eq!(results.generation, 20);
    }

    #[test]
    /// Test StoppingConditionType::MaxFunctionEvaluations
    fn test_stopping_condition_max_nfe() {
        let problem = SCHProblem::create().unwrap();
        let args = NSGA2Arg {
            number_of_individuals: 10,
            stopping_condition: StoppingCondition::MaxFunctionEvaluations(20),
            crossover_operator_options: None,
            mutation_operator_options: None,
            parallel: Some(false),
            export_history: None,
            resume_from_file: None,
            seed: Some(10),
        };
        let mut algo = NSGA2::new(problem, args).unwrap();
        algo.run().unwrap();
        let results = algo.get_results();

        assert_eq!(results.number_of_function_evaluations, 20);
        assert_eq!(results.generation, 2);
    }

    #[test]
    /// Test StoppingConditionType::Any
    fn test_stopping_condition_any() {
        let problem = SCHProblem::create().unwrap();
        let args = NSGA2Arg {
            number_of_individuals: 10,
            stopping_condition: StoppingCondition::Any(vec![
                StoppingCondition::MaxFunctionEvaluations(20),
                StoppingCondition::MaxGeneration(10),
            ]),
            crossover_operator_options: None,
            mutation_operator_options: None,
            parallel: Some(false),
            export_history: None,
            resume_from_file: None,
            seed: Some(10),
        };
        let mut algo = NSGA2::new(problem, args).unwrap();
        algo.run().unwrap();
        let results = algo.get_results();

        assert_eq!(results.number_of_function_evaluations, 20);
        assert_eq!(results.generation, 2);
    }
}

#[cfg(feature = "python")]
#[cfg(test)]
mod test_python_api {
    use std::env;
    use std::error::Error;
    use std::path::Path;

    use crate::algorithms::NSGA3Data;
    use crate::utils::{DasDarren1998, NumberOfPartitions, TwoLayerPartitions};
    use float_cmp::assert_approx_eq;
    use pyo3::prelude::*;
    use pyo3::types::PyList;

    #[test]
    /// test the NSGA*Data class.
    fn test_reader() -> Result<(), Box<dyn Error>> {
        Python::attach(|py| -> Result<(), Box<dyn Error>> {
            let file = Path::new(&env::current_dir()?)
                .join("examples")
                .join("results")
                .join("DTLZ1_3obj_NSGA3_gen400.json");
            let reader = Py::new(py, NSGA3Data::new(file)?)?;

            // check problem
            let problem = reader.getattr(py, "problem")?;
            assert_eq!(
                problem
                    .getattr(py, "number_of_variables")?
                    .extract::<i32>(py)?,
                7
            );
            assert_eq!(
                problem
                    .getattr(py, "variables")?
                    .call_method1(py, "get", ("x1".to_string(),))?
                    .getattr(py, "min_value")?
                    .extract::<f64>(py)?,
                0.0
            );
            assert_eq!(
                problem
                    .getattr(py, "objectives")?
                    .call_method0(py, "__len__")?
                    .extract::<i32>(py)?,
                3
            );

            // check reader props
            assert_eq!(
                reader.getattr(py, "algorithm")?.extract::<String>(py)?,
                "NSGA3".to_string()
            );
            assert_eq!(reader.getattr(py, "generation")?.extract::<i32>(py)?, 400);
            assert_eq!(
                reader
                    .getattr(py, "exported_on")?
                    .getattr(py, "day")?
                    .extract::<u32>(py)?,
                10
            );

            // test individuals
            let ind = reader
                .getattr(py, "individuals")?
                .call_method1(py, "pop", (0,))?;
            assert_eq!(
                ind.call_method0(py, "constraint_violation")?
                    .extract::<f32>(py)?,
                0.0
            );
            assert_approx_eq!(
                f32,
                ind.call_method1(py, "get_objective_value", ("f2",))?
                    .extract::<f32>(py)?,
                0.167,
                epsilon = 0.001
            );
            assert!(ind
                .call_method0(py, "variables")?
                .call_method0(py, "keys")?
                .call_method1(py, "__contains__", ("x5".to_string(),))?
                .extract::<bool>(py)?);
            assert!(ind
                .call_method0(py, "data")?
                .call_method0(py, "keys")?
                .call_method1(py, "__contains__", ("reference_point_index".to_string(),))?
                .extract::<bool>(py)?);
            assert_approx_eq!(
                f32,
                reader
                    .call_method1(py, "hyper_volume", (PyList::new(py, [100, 100, 100])?,),)?
                    .extract::<f32>(py)?,
                999999.97,
                epsilon = 0.001
            );
            Ok(())
        })
    }

    #[test]
    /// Test the DasDarren1998 class
    fn test_hypervolume() -> Result<(), Box<dyn Error>> {
        Python::attach(|py| -> Result<(), Box<dyn Error>> {
            let hv = Py::new(py, DasDarren1998::new(3, &NumberOfPartitions::OneLayer(5))?)?;
            assert_eq!(
                hv.call_method0(py, "calculate")?
                    .call_method0(py, "__len__")?
                    .extract::<u32>(py)?,
                21
            );

            // assert len(ds.calculate()) == 25
            let hv = Py::new(
                py,
                DasDarren1998::new(
                    3,
                    &&NumberOfPartitions::TwoLayers(TwoLayerPartitions {
                        boundary_layer: 3,
                        inner_layer: 4,
                        scaling: None,
                    }),
                )?,
            )?;
            assert_eq!(
                hv.call_method0(py, "calculate")?
                    .call_method0(py, "__len__")?
                    .extract::<u32>(py)?,
                25
            );

            Ok(())
        })
    }
}