optirustic 1.2.3

This crate moved to https://github.com/s-simoncelli/nsga-rs
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
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)
    }
}

/// 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 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 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)
    }
}

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))]
#[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(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()
    }
}

#[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);
    }
}