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
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
use crate::core::utils::dummy_evaluator;
use crate::core::{Constraint, Individual, OError, Objective, ObjectiveDirection, VariableType};
use crate::utils::has_unique_elements_by_key;

use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};

#[cfg(feature = "python")]
use crate::core::PyVariable;

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

#[cfg(feature = "python")]
use pyo3::types::PyDict;

/// The struct containing the results of the evaluation function. This is the output of
/// [`Evaluator::evaluate`], the user-defined function should produce. When the algorithm generates
/// a new population with new variables, its constraints and objectives must be evaluated to proceed
/// with the next evolution.
#[derive(Debug)]
pub struct EvaluationResult {
    /// The list of evaluated constraints. This is optional for unconstrained problems.
    pub constraints: Option<HashMap<String, f64>>,
    /// The list of evaluated objectives.
    pub objectives: HashMap<String, f64>,
}

/// The trait to use to evaluate the objective and constraint values when a new offspring is
/// created.
pub trait Evaluator: Sync + Send + Debug {
    /// A custom-defined function to use to assess the constraint and objective. When a new
    /// offspring is generated via crossover and mutation, new variables (or solutions) are
    /// assigned to it and the problem constraints and objective need to be evaluated. This
    /// function must return all the values for all the objectives and constraints set on
    /// the problem. An algorithm will return an error if the function fails to do so.
    ///
    /// # Arguments
    ///
    /// * `individual`: The individual.
    ///
    /// returns: `Result<EvaluationResult, Box<dyn Error>>`
    ///
    /// ## Example
    /// ```
    /// use std::collections::HashMap;
    /// use std::error::Error;
    /// use optirustic::core::{EvaluationResult, Individual, Evaluator};
    ///
    /// // solve a SCH problem with two objectives to minimise: x^2 and (x-2)^2. The problem has
    /// // one variable named "x" and two objectives named "x^2" and "(x-2)^2".
    /// #[derive(Debug)]
    ///     struct UserEvaluator;
    ///     impl Evaluator for UserEvaluator {
    ///         fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
    ///             // access new variable to evaluate the objectives
    ///             let x = i.get_variable_value("x")?.as_real()?;
    ///             // assess the objectives
    ///             let mut objectives = HashMap::new();
    ///             objectives.insert("x^2".to_string(), x.powi(2));
    ///             objectives.insert("(x-2)^2".to_string(), (x - 2.0).powi(2));
    ///
    ///             Ok(EvaluationResult {
    ///                 constraints: None,
    ///                 objectives,
    ///             })
    ///         }
    ///     }
    /// ```
    fn evaluate(&self, individual: &Individual) -> Result<EvaluationResult, Box<dyn Error>>;
}

#[derive(Serialize, Deserialize, Debug, Clone)]
/// Serialised data of a problem.
pub struct ProblemExport {
    /// The problem objectives.
    pub objectives: HashMap<String, Objective>,
    /// The problem constraints.
    pub constraints: HashMap<String, Constraint>,
    /// The problem variables.
    pub variables: HashMap<String, VariableType>,
    /// The constraint names.
    pub constraint_names: Vec<String>,
    /// The variable names.
    pub variable_names: Vec<String>,
    /// The objective names.
    pub objective_names: Vec<String>,
    /// The number of objectives
    pub number_of_objectives: usize,
    /// The number of constraints
    pub number_of_constraints: usize,
    /// The number of variables
    pub number_of_variables: usize,
}

/// Convert `ProblemExport` to `Problem`. The problem will have a dummy evaluator.
impl TryInto<Problem> for ProblemExport {
    type Error = OError;

    fn try_into(self) -> Result<Problem, Self::Error> {
        let objectives = self.objectives.values().cloned().collect();
        let variables = self.variables.values().cloned().collect();
        let constraints = self.constraints.values().cloned().collect();

        Problem::new(objectives, variables, Some(constraints), dummy_evaluator())
    }
}

/// Define a new problem to optimise as:
///
///  $$$ Min/Max(f_1(x), f_2(x), ..., f_M(x)) $
///
/// where
///   - where the integer $M \geq 1$ is the number of objectives;
///   - $x$ the $N$-variable solution vector bounded to $$$ x_i^{(L)} \leq x_i \leq x_i^{(U)}$ with
///     $i=1,2,...,N$.
///
/// The problem is also subjected to the following constraints:
/// - $$$ g_j(x) \geq 0 $ with $j=1,2,...,J$ and $J$ the number of inequality constraints.
/// - $$$ h_k(x) = 0 $ with $k=1,2,...,H$ and $H$ the number of equality constraints.
///
/// # Example
/// ```
///  use std::error::Error;
///  use optirustic::core::{BoundedNumber, Constraint, EvaluationResult, Evaluator, Individual, Objective, ObjectiveDirection, Problem, RelationalOperator, VariableType};
///
///  // Define a one-objective one-variable problem with two constraints
///  let objectives = vec![Objective::new("obj1", ObjectiveDirection::Minimise)];
///  let variables = vec![VariableType::Real(
///     BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
///  )];
///  let constraints = vec![
///     Constraint::new("c1", RelationalOperator::EqualTo, 1.0),
///     Constraint::new("c2", RelationalOperator::EqualTo, 599.0),
///  ];
///
///  #[derive(Debug)]
///  struct UserEvaluator;
///  impl Evaluator for UserEvaluator {
///     fn evaluate(&self, individual: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
///         Ok(EvaluationResult {
///             constraints: Default::default(),
///             objectives: Default::default(),
///         })
///     }
///  }
///
///  let problem = Problem::new(objectives, variables, Some(constraints), Box::new(UserEvaluator{})).unwrap();
///  println!("{}", problem);
/// ```
#[derive(Debug)]
pub struct Problem {
    /// The problem objectives.
    objectives: Vec<Objective>,
    /// The problem constraints.
    constraints: Vec<Constraint>,
    /// The problem variable types.
    variables: Vec<VariableType>,
    /// The trait with the function to use to evaluate the objective and constraint values of
    /// new offsprings.
    evaluator: Box<dyn Evaluator>,
}

impl Display for Problem {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Problem with {} variables, {} objectives and {} constraints",
            self.number_of_variables(),
            self.number_of_objectives(),
            self.number_of_constraints(),
        )
    }
}

impl Problem {
    /// Initialise the problem.
    ///
    /// # Arguments
    ///
    /// * `objectives`: The vector of objective to set on the problem.
    /// * `variable_types`: The vector of variable types to set on the problem.
    /// * `constraints`: The optional vector of constraints.
    /// * `evaluator`: The trait with the function to use to evaluate the objective and constraint
    ///    values when new offsprings are generated by an algorithm. The [`Evaluator::evaluate`]
    ///    receives the [`Individual`] with the new variables/solutions and should return the
    ///    [`EvaluationResult`].
    ///
    /// returns: `Result<Problem, OError>`
    pub fn new(
        objectives: Vec<Objective>,
        variable_types: Vec<VariableType>,
        constraints: Option<Vec<Constraint>>,
        evaluator: Box<dyn Evaluator>,
    ) -> Result<Self, OError> {
        // Check vector lengths
        if objectives.is_empty() {
            return Err(OError::NoObjective);
        }
        if variable_types.is_empty() {
            return Err(OError::NoVariables);
        }

        // check unique names
        if !has_unique_elements_by_key(&objectives, |o| o.name()) {
            return Err(OError::DuplicatedName("objective".to_string()));
        }
        if !has_unique_elements_by_key(&variable_types, |v| v.name()) {
            return Err(OError::DuplicatedName("variable".to_string()));
        }
        let constraints = constraints.unwrap_or_default();
        if !has_unique_elements_by_key(&constraints, |c| c.name()) {
            return Err(OError::DuplicatedName("constraint".to_string()));
        }

        Ok(Self {
            variables: variable_types,
            objectives,
            constraints,
            evaluator,
        })
    }

    /// Whether a problem objective is being minimised. This returns an error if the objective does
    /// not exist.
    ///
    /// # Arguments
    ///
    /// * `name`: The objective name.
    ///
    ///
    /// returns: `Result<bool, OError>`
    pub fn is_objective_minimised(&self, name: &str) -> Result<bool, OError> {
        match self.objectives.iter().position(|o| o.name() == name) {
            None => Err(OError::NonExistingName(
                "objective".to_string(),
                name.to_string(),
            )),
            Some(p) => Ok(self.objectives[p].direction() == ObjectiveDirection::Minimise),
        }
    }

    /// Get the total number of objectives of the problem.
    ///
    /// returns: `usize`
    pub fn number_of_objectives(&self) -> usize {
        self.objectives.len()
    }

    /// Get the total number of constraints of the problem.
    ///
    /// returns: `usize`
    pub fn number_of_constraints(&self) -> usize {
        self.constraints.len()
    }

    /// Get the total number of variables of the problem.
    ///
    /// returns: `usize`
    pub fn number_of_variables(&self) -> usize {
        self.variables.len()
    }

    /// Get the name of the variables set on the problem.
    ///
    /// return `Vec<String>`
    pub fn variable_names(&self) -> Vec<String> {
        self.variables.iter().map(|o| o.name()).collect()
    }

    /// Get the name of the objectives set on the problem.
    ///
    /// return `Vec<String>`
    pub fn objective_names(&self) -> Vec<String> {
        self.objectives.iter().map(|o| o.name()).collect()
    }

    /// Get the name of the constraints set on the problem.
    ///
    /// return `Vec<String>`
    pub fn constraint_names(&self) -> Vec<String> {
        self.constraints.iter().map(|o| o.name()).collect()
    }

    /// Get the map of variables.
    ///
    /// return `Vec<(String, VariableType)>`
    pub fn variables(&self) -> Vec<(String, VariableType)> {
        self.variables
            .iter()
            .map(|o| (o.name().clone(), o.clone()))
            .collect()
    }

    /// Get a variable type by name. This returns an error if the variable does not exist.
    ///
    /// # Arguments
    ///
    /// * `name`: The name of the variable to fetch.
    ///
    /// return `Result<VariableType, OError>`
    pub fn get_variable(&self, name: &str) -> Result<VariableType, OError> {
        match self.variables.iter().position(|o| o.name() == name) {
            None => Err(OError::NonExistingName(
                "variable".to_string(),
                name.to_string(),
            )),
            Some(p) => Ok(self.variables[p].clone()),
        }
    }

    /// Check if a variable name exists.
    ///
    /// # Arguments
    ///
    /// * `name`: The name of the variable to check.
    ///
    /// return `bool`
    pub fn does_variable_exist(&self, name: &str) -> bool {
        self.variables.iter().any(|o| o.name() == name)
    }

    /// Get a constraint by name. This returns an error if the constraint does not exist.
    ///
    /// # Arguments
    ///
    /// * `name`: The name of the constraint to fetch.
    ///
    /// return `Result<Constraint, OError>`
    pub fn get_constraint(&self, name: &str) -> Result<Constraint, OError> {
        match self.constraints.iter().position(|o| o.name() == name) {
            None => Err(OError::NonExistingName(
                "variable".to_string(),
                name.to_string(),
            )),
            Some(p) => Ok(self.constraints[p].clone()),
        }
    }

    /// Get the list of objectives.
    ///
    /// return `Vec<(String, Objective)>`
    pub fn objectives(&self) -> Vec<(String, Objective)> {
        self.objectives
            .iter()
            .map(|o| (o.name().clone(), o.clone()))
            .collect()
    }

    /// Get the list of constraints.
    ///
    /// return `Vec<(String, Constraint)>`
    pub fn constraints(&self) -> Vec<(String, Constraint)> {
        self.constraints
            .iter()
            .map(|o| (o.name().clone(), o.clone()))
            .collect()
    }

    /// The function used to evaluate the constraint and objective values for a new offsprings.
    ///
    /// return `&Evaluator`
    pub fn evaluator(&self) -> &dyn Evaluator {
        self.evaluator.as_ref()
    }

    /// Serialise the problem data.
    ///
    /// return: `ProblemExport`
    pub fn serialise(&self) -> ProblemExport {
        let objectives: HashMap<String, Objective> = self
            .objectives()
            .iter()
            .map(|(name, obj)| (name.clone(), obj.clone()))
            .collect();
        let constraints: HashMap<String, Constraint> = self
            .constraints()
            .iter()
            .map(|(name, c)| (name.clone(), c.clone()))
            .collect();
        let variables: HashMap<String, VariableType> = self
            .variables()
            .iter()
            .map(|(name, var)| (name.clone(), var.clone()))
            .collect();

        ProblemExport {
            objectives,
            constraints,
            variables,
            constraint_names: self.constraint_names().clone(),
            variable_names: self.variable_names(),
            objective_names: self.objective_names().clone(),
            number_of_objectives: self.number_of_objectives(),
            number_of_constraints: self.number_of_constraints(),
            number_of_variables: self.number_of_variables(),
        }
    }
}

/// Python interface for data held by [`Problem`]. This uses a separate class as some Rust struct
/// cannot be directly converted into Python objects.
#[cfg(feature = "python")]
#[pyclass(name = "Problem", get_all)]
#[derive(Clone)]
pub struct PyProblem {
    /// The vector og objectives.
    pub objectives_list: Vec<(String, Objective)>,
    /// The vector of constraints.
    pub constraints_list: Vec<(String, Constraint)>,
    /// The vector of Variables.
    pub variables_list: Vec<(String, VariableType)>,
    /// The list of problem constraint names.
    pub constraint_names: Vec<String>,
    /// The list of problem variable names.
    pub variable_names: Vec<String>,
    /// The list of problem objective names.
    pub objective_names: Vec<String>,
    /// The number of problem objectives.
    pub number_of_objectives: usize,
    /// The number of problem constraints.
    pub number_of_constraints: usize,
    /// The number of problem variables.
    pub number_of_variables: usize,
}

#[cfg(feature = "python")]
#[pymethods]
impl PyProblem {
    #[getter]
    /// Get the variables as Python dictionary. The keys contain the variable name and the values
    /// the corresponding variable value.
    pub fn variables(&self) -> PyResult<Py<PyDict>> {
        Python::with_gil(|py| {
            let dict = PyDict::new(py);
            for (name, var) in &self.variables_list {
                let var: PyVariable = var.into();
                dict.set_item(name.clone(), var)?;
            }
            Ok(dict.unbind())
        })
    }

    #[getter]
    /// Get the objectives as Python dictionary. The keys contain the objective name and the values
    /// the corresponding objective value.
    pub fn objectives(&self) -> PyResult<Py<PyDict>> {
        Python::with_gil(|py| {
            let dict = PyDict::new(py);
            for (name, objective) in &self.objectives_list {
                dict.set_item(name, objective.clone())?;
            }
            Ok(dict.unbind())
        })
    }

    #[getter]
    /// Get the constraints as Python dictionary. The keys contain the constraint name and the
    /// values the corresponding constraint value.
    pub fn constraints(&self) -> PyResult<Py<PyDict>> {
        Python::with_gil(|py| {
            let dict = PyDict::new(py);
            for (name, constraint) in &self.constraints_list {
                dict.set_item(name, constraint.clone())?;
            }
            Ok(dict.unbind())
        })
    }

    pub fn __repr__(&self) -> PyResult<String> {
        Ok(format!(
            "Problem(variables={}, objectives={}, constraints={})",
            self.number_of_variables, self.number_of_objectives, self.number_of_constraints
        ))
    }

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

/// Convert [`Problem`] to [`PyProblem`]
#[cfg(feature = "python")]
impl From<&Problem> for PyProblem {
    fn from(p: &Problem) -> Self {
        PyProblem {
            variables_list: p.variables(),
            objectives_list: p.objectives(),
            constraints_list: p.constraints(),
            constraint_names: p.constraint_names(),
            variable_names: p.variable_names(),
            objective_names: p.objective_names(),
            number_of_objectives: p.number_of_objectives(),
            number_of_constraints: p.number_of_constraints(),
            number_of_variables: p.number_of_variables(),
        }
    }
}

/// Built-in problem used to test the algorithms. See table I in Deb et al. (2002)'s NSGA2 paper.
pub mod builtin_problems {
    use std::collections::HashMap;
    use std::error::Error;
    use std::f64::consts::PI;

    use nalgebra::RealField;

    use crate::core::{
        BoundedNumber, Constraint, EvaluationResult, Evaluator, Individual, OError, Objective,
        ObjectiveDirection, Problem, RelationalOperator, VariableType,
    };

    /// The Schaffer’s study (SCH) problem.
    #[derive(Debug)]
    pub struct SCHProblem;

    impl SCHProblem {
        /// Create the problem for the optimisation.
        pub fn create() -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("x^2", ObjectiveDirection::Minimise),
                Objective::new("(x-2)^2", ObjectiveDirection::Minimise),
            ];
            let variables = vec![VariableType::Real(BoundedNumber::new(
                "x", -1000.0, 1000.0,
            )?)];

            let e = Box::new(SCHProblem);
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function
        pub fn f1(x: f64) -> f64 {
            x.powi(2)
        }

        /// The second objective function
        pub fn f2(x: f64) -> f64 {
            (x - 2.0).powi(2)
        }
    }

    impl Evaluator for SCHProblem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x = i.get_variable_value("x")?.as_real()?;
            let mut objectives = HashMap::new();
            objectives.insert("x^2".to_string(), SCHProblem::f1(x));
            objectives.insert("(x-2)^2".to_string(), SCHProblem::f2(x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// The Fonseca and Fleming’s study (FON) problem.
    #[derive(Debug)]
    pub struct FonProblem;

    impl FonProblem {
        /// Create the problem for the optimisation.
        pub fn create() -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let variables = vec![
                VariableType::Real(BoundedNumber::new("x1", -4.0, 4.0)?),
                VariableType::Real(BoundedNumber::new("x2", -4.0, 4.0)?),
                VariableType::Real(BoundedNumber::new("x3", -4.0, 4.0)?),
            ];

            let e = Box::new(FonProblem);
            Problem::new(objectives, variables, None, e)
        }
    }

    impl Evaluator for FonProblem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let mut x: Vec<f64> = Vec::new();
            for var_name in ["x1", "x2", "x3"] {
                x.push(i.get_variable_value(var_name)?.as_real()?);
            }
            let mut objectives = HashMap::new();

            let mut exp_arg1 = 0.0;
            let mut exp_arg2 = 0.0;
            for x_val in x {
                exp_arg1 += (x_val - 1.0 / 3.0_f64.sqrt()).powi(2);
                exp_arg2 += (x_val + 1.0 / 3.0_f64.sqrt()).powi(2);
            }
            objectives.insert("f1".to_string(), 1.0 - f64::exp(-exp_arg1));
            objectives.insert("f2".to_string(), 1.0 - f64::exp(-exp_arg2));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Problem #1 from Zitzler et al. (2000).
    #[derive(Debug)]
    pub struct ZTD1Problem {
        /// The number of variables.
        n: usize,
    }

    impl ZTD1Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n`: The number of variables.
        pub fn create(n: usize) -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(ZTD1Problem { n });
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function.
        pub fn f1(x: &[f64]) -> f64 {
            x[0]
        }

        /// The second objective function.
        pub fn f2(&self, x: &[f64]) -> f64 {
            let a: f64 = (1..self.n).map(|xi| x[xi]).sum();
            let g = 1.0 + 9.0 * a / (self.n as f64 - 1.0);
            g * (1.0 - f64::sqrt(x[0] / g))
        }
    }
    impl Evaluator for ZTD1Problem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x: Vec<f64> = i
                .get_variable_values()?
                .iter()
                .map(|v| v.as_real())
                .collect::<Result<Vec<f64>, _>>()?;

            let mut objectives = HashMap::new();
            objectives.insert("f1".to_string(), ZTD1Problem::f1(&x));
            objectives.insert("f2".to_string(), self.f2(&x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Problem #2 from Zitzler et al. (2000)
    #[derive(Debug)]
    pub struct ZTD2Problem {
        /// The number of variables.
        n: usize,
    }

    impl ZTD2Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n`: The number of variables.
        pub fn create(n: usize) -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(ZTD2Problem { n });
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function.
        pub fn f1(x: &[f64]) -> f64 {
            x[0]
        }

        /// The second objective function.
        pub fn f2(&self, x: &[f64]) -> f64 {
            let a: f64 = (1..self.n).map(|xi| x[xi]).sum();
            let g = 1.0 + 9.0 * a / (self.n as f64 - 1.0);
            g * (1.0 - (x[0] / g).powi(2))
        }
    }

    impl Evaluator for ZTD2Problem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x: Vec<f64> = i
                .get_variable_values()?
                .iter()
                .map(|v| v.as_real())
                .collect::<Result<Vec<f64>, _>>()?;

            let mut objectives = HashMap::new();
            objectives.insert("f1".to_string(), ZTD2Problem::f1(&x));
            objectives.insert("f2".to_string(), self.f2(&x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Problem #3 from Zitzler et al. (2000)
    #[derive(Debug)]
    pub struct ZTD3Problem {
        /// The number of variables.
        n: usize,
    }

    impl ZTD3Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n`: The number of variables.
        pub fn create(n: usize) -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(ZTD3Problem { n });
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function.
        pub fn f1(x: &[f64]) -> f64 {
            x[0]
        }

        /// The second objective function.
        pub fn f2(&self, x: &[f64]) -> f64 {
            let a: f64 = (1..self.n).map(|xi| x[xi]).sum();
            let g = 1.0 + 9.0 * a / (self.n as f64 - 1.0);
            g * (1.0 - (x[0] / g).powi(2) - x[0] / g * f64::sin(10.0 * PI * x[0]))
        }
    }

    impl Evaluator for ZTD3Problem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x: Vec<f64> = i
                .get_variable_values()?
                .iter()
                .map(|v| v.as_real())
                .collect::<Result<Vec<f64>, _>>()?;

            let mut objectives = HashMap::new();
            objectives.insert("f1".to_string(), ZTD3Problem::f1(&x));
            objectives.insert("f2".to_string(), self.f2(&x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Problem #4 from Zitzler et al. (2000)
    #[derive(Debug)]
    pub struct ZTD4Problem {
        /// The number of variables.
        n: usize,
    }

    impl ZTD4Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n`: The number of variables.
        pub fn create(n: usize) -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let mut variables: Vec<VariableType> = Vec::new();
            variables.push(VariableType::Real(BoundedNumber::new("x1", 0.0, 1.0)?));
            for i in 2..=n {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    -5.0,
                    5.0,
                )?));
            }
            let e = Box::new(ZTD4Problem { n });
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function.
        pub fn f1(x: &[f64]) -> f64 {
            x[0]
        }

        /// The second objective function.
        pub fn f2(&self, x: &[f64]) -> f64 {
            let a: f64 = (1..self.n)
                .map(|xi| {
                    let xi = x[xi];
                    xi.powi(2) - 10.0 * f64::cos(4.0 * PI * xi)
                })
                .sum();
            let g: f64 = 1.0 + 10.0 * (self.n as f64 - 1.0) + a;

            g * (1.0 - (x[0] / g).sqrt())
        }
    }

    impl Evaluator for ZTD4Problem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x: Vec<f64> = i
                .get_variable_values()?
                .iter()
                .map(|v| v.as_real())
                .collect::<Result<Vec<f64>, _>>()?;

            let mut objectives = HashMap::new();
            objectives.insert("f1".to_string(), ZTD4Problem::f1(&x));
            objectives.insert("f2".to_string(), self.f2(&x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Problem #6 from Zitzler et al. (2000)
    #[derive(Debug)]
    pub struct ZTD6Problem {
        /// The number of variables.
        n: usize,
    }

    impl ZTD6Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n`: The number of variables.
        pub fn create(n: usize) -> Result<Problem, OError> {
            let objectives = vec![
                Objective::new("f1", ObjectiveDirection::Minimise),
                Objective::new("f2", ObjectiveDirection::Minimise),
            ];
            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(ZTD6Problem { n });
            Problem::new(objectives, variables, None, e)
        }

        /// The first objective function.
        pub fn f1(x: &[f64]) -> f64 {
            1.0 - f64::exp(-4.0 * x[0]) * f64::powi(f64::sin(6.0 * PI * x[0]), 6)
        }

        /// The second objective function.
        pub fn f2(&self, x: &[f64]) -> f64 {
            let a = (1..self.n).map(|xi| x[xi]).sum::<f64>() / (self.n as f64 - 1.0);
            let g = 1.0 + 9.0 * f64::powf(a, 0.25);
            g * (1.0 - (ZTD6Problem::f1(x) / g).powi(2))
        }
    }

    impl Evaluator for ZTD6Problem {
        fn evaluate(&self, i: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            let x: Vec<f64> = i
                .get_variable_values()?
                .iter()
                .map(|v| v.as_real())
                .collect::<Result<Vec<f64>, _>>()?;

            let mut objectives = HashMap::new();
            objectives.insert("f1".to_string(), ZTD6Problem::f1(&x));
            objectives.insert("f2".to_string(), self.f2(&x));
            Ok(EvaluationResult {
                constraints: None,
                objectives,
            })
        }
    }

    /// Test problem DTLZ1 from K.Deb,L. Thiele,M. Laumanns,and E. Zitzler, “Scalable test problems
    /// for evolutionary multi-objective optimization”
    #[derive(Debug)]
    pub struct DTLZ1Problem {
        /// The number of variables.
        n_vars: usize,
        /// The number of objectives.
        n_objectives: usize,
        /// Whether to invert the problem
        invert: bool,
    }

    impl DTLZ1Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n_vars`: The number of variables.
        /// * `n_objectives`: The number of objectives.
        /// * `invert`: Whether to invert the problem based on Section VIIIA of Jain and Deb (2014)'s
        ///    paper.
        ///
        /// returns: `Result<Problem, OError>`
        pub fn create(n_vars: usize, n_objectives: usize, invert: bool) -> Result<Problem, OError> {
            // if k must be > 0, then n + 1 >= M
            if n_vars + 1 < n_objectives {
                return Err(OError::Generic(
                    "n_vars + 1 >= n_objectives not met. Increase n_vars.".to_string(),
                ));
            }

            let objectives = (1..=n_objectives)
                .map(|i| Objective::new(format!("f{i}").as_str(), ObjectiveDirection::Minimise))
                .collect();
            let constraints: Vec<Constraint> = vec![Constraint::new(
                "g",
                RelationalOperator::GreaterOrEqualTo,
                0.0,
            )];

            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n_vars {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(DTLZ1Problem {
                n_vars,
                n_objectives,
                invert,
            });
            Problem::new(objectives, variables, Some(constraints), e)
        }
    }

    impl Evaluator for DTLZ1Problem {
        fn evaluate(&self, ind: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            // Calculate g(x_M)
            let k = self.n_vars - self.n_objectives + 1;
            let mut sum_g = Vec::new();
            // get last k variables
            for i in (self.n_vars - k + 1)..=self.n_vars {
                let xi = ind
                    .get_variable_value(format!("x{i}").as_str())?
                    .as_real()?;
                sum_g.push((xi - 0.5).powi(2) - f64::cos(20.0 * f64::pi() * (xi - 0.5)));
            }

            let g = 100.0 * (k as f64 + sum_g.iter().sum::<f64>());

            // Add constraints values
            let mut constraints = HashMap::new();
            constraints.insert("g".to_string(), g);

            // Add objective values
            // M = 5 (self.n_objectives)
            // F1 (o=1) = 0.5 * x1 * x2 * x3 * x4 * (1 + g) = 0.5 * Prod_{j=1:M-o} * 1 * (1 + g)
            // F2 (o=2) = 0.5 * x1 * x2 * x3 * (1 - x4) * (1 + g) = 0.5 * Prod_{j=1:M-o} * (1 - x_{M-o+1}) * (1 + g)
            // ...
            // F4 = 0.5 * x1 * (1 - x2) * (1 + g)
            // F5 (o=5) = 0.5 * (1 - x1) * (1 + g) = 0.5 * 1 * (1 - x_{M-o+1})
            let mut objectives = HashMap::new();
            for o in 1..=self.n_objectives {
                // first factor (product of x's)
                let prod = if self.n_objectives == o {
                    1.0
                } else {
                    let mut tmp = Vec::new();
                    for j in 1..=self.n_objectives - o {
                        tmp.push(
                            ind.get_variable_value(format!("x{j}").as_str())?
                                .as_real()?,
                        );
                    }
                    tmp.iter().product()
                };
                // second factor (1 - x_{M-o+1})
                let delta = if o == 1 {
                    1.0
                } else {
                    let x = ind
                        .get_variable_value(format!("x{}", self.n_objectives - o + 1).as_str())?
                        .as_real()?;
                    1.0 - x
                };
                let mut obj_value = 0.5 * prod * delta * (1.0 + g);
                if self.invert {
                    obj_value = 0.5 * (1.0 + g) - obj_value;
                }
                objectives.insert(format!("f{o}"), obj_value);
            }
            Ok(EvaluationResult {
                constraints: Some(constraints),
                objectives,
            })
        }
    }

    /// Test problem DTLZ2 from K.Deb,L. Thiele,M. Laumanns,and E. Zitzler, “Scalable test problems
    /// for evolutionary multi-objective optimization”
    #[derive(Debug)]
    pub struct DTLZ2Problem {
        /// The number of variables.
        n_vars: usize,
        /// The number of objectives.
        n_objectives: usize,
    }

    impl DTLZ2Problem {
        /// Create the problem for the optimisation.
        ///
        /// # Arguments:
        ///
        /// * `n_vars`: The number of variables.
        /// * `n_objectives`: The number of objectives.
        pub fn create(n_vars: usize, n_objectives: usize) -> Result<Problem, OError> {
            // sphere function defined when n >= M
            if n_vars + 1 < n_objectives {
                return Err(OError::Generic(
                    "n_vars >= n_objectives not met. Increase n_vars.".to_string(),
                ));
            }

            let objectives = (1..=n_objectives)
                .map(|i| Objective::new(format!("f{i}").as_str(), ObjectiveDirection::Minimise))
                .collect();
            let constraints: Vec<Constraint> = vec![Constraint::new(
                "g",
                RelationalOperator::GreaterOrEqualTo,
                0.0,
            )];

            let mut variables: Vec<VariableType> = Vec::new();
            for i in 1..=n_vars {
                variables.push(VariableType::Real(BoundedNumber::new(
                    format!("x{i}").as_str(),
                    0.0,
                    1.0,
                )?));
            }

            let e = Box::new(DTLZ2Problem {
                n_vars,
                n_objectives,
            });
            Problem::new(objectives, variables, Some(constraints), e)
        }
    }

    impl Evaluator for DTLZ2Problem {
        fn evaluate(&self, ind: &Individual) -> Result<EvaluationResult, Box<dyn Error>> {
            // Calculate g(x_M)
            let k = self.n_vars - self.n_objectives + 1;
            let mut sum_g = Vec::new();
            // get first M variables
            for i in (self.n_vars - k + 1)..=self.n_vars {
                let xi = ind
                    .get_variable_value(format!("x{i}").as_str())?
                    .as_real()?;
                sum_g.push((xi - 0.5).powi(2));
            }
            let g = sum_g.iter().sum::<f64>();

            // Add constraints values
            let mut constraints = HashMap::new();
            constraints.insert("g".to_string(), g);

            // Add objective values
            // M = 5 (self.n_objectives)
            // F1 (o=1) = (1 + g) * cos(x1 pi/2) * cos(x2 pi/2) * cos(x3 pi/2) * cos(x4 pi/2)
            // F2 (o=2) = (1 + g) * cos(x1 pi/2) * cos(x2 pi/2) * cos(x3 pi/2) * sin(x4 pi/2) = (1 + g) * sum_{1:M-o}^j( cos(x_j pi/2) ) * sin(x_{M-o+1} pi/2)
            // F3 (o=3) = (1 + g) * cos(x1 pi/2) * cos(x2 pi/2) * sin(x3 pi/2)
            // ...
            // F4 (o=4) = (1 + g) * cos(x1 pi/2) * sin(x2 pi/2)
            // F5 (o=5) = (1 + g) * sin(x1 pi/2)
            let mut objectives = HashMap::new();
            let c = f64::pi() / 2.0;
            for o in 1..=self.n_objectives {
                // product of cos functions
                let mut tmp = vec![];
                for j in 1..=self.n_objectives - o {
                    tmp.push(f64::cos(
                        ind.get_variable_value(format!("x{j}").as_str())?
                            .as_real()?
                            * c,
                    ));
                }
                // last sin function
                if o > 1 {
                    let x = ind
                        .get_variable_value(format!("x{}", self.n_objectives - o + 1).as_str())?
                        .as_real()?;
                    tmp.push(f64::sin(x * c));
                }
                objectives.insert(format!("f{o}"), (1.0 + g) * tmp.iter().product::<f64>());
            }

            Ok(EvaluationResult {
                constraints: Some(constraints),
                objectives,
            })
        }
    }
}

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

    use float_cmp::assert_approx_eq;

    use crate::core::builtin_problems::{DTLZ1Problem, DTLZ2Problem};
    use crate::core::test_utils::read_csv_test_file;
    use crate::core::utils::dummy_evaluator;
    use crate::core::{
        BoundedNumber, Constraint, Individual, Objective, ObjectiveDirection, Problem,
        RelationalOperator, VariableType, VariableValue,
    };

    #[test]
    /// Test when objectives and constraints already exist when a new problem is created.
    fn test_already_existing_data() {
        let objectives = vec![
            Objective::new("obj1", ObjectiveDirection::Minimise),
            Objective::new("obj1", ObjectiveDirection::Maximise),
        ];
        let var_types = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let var_types2 = var_types.clone();
        let e = dummy_evaluator();

        assert!(Problem::new(objectives, var_types, None, e).is_err());

        let e = dummy_evaluator();
        let objectives = vec![Objective::new("obj1", ObjectiveDirection::Minimise)];
        let constraints = vec![
            Constraint::new("c1", RelationalOperator::EqualTo, 1.0),
            Constraint::new("c1", RelationalOperator::GreaterThan, -1.0),
        ];
        assert!(Problem::new(objectives, var_types2, Some(constraints), e).is_err());
    }

    #[test]
    /// Test the DTLZ1 problem implementation with the optimal solution
    fn test_dtlz1_optimal_solutions() {
        let problem = Arc::new(DTLZ1Problem::create(4, 3, false).unwrap());
        let mut individual = Individual::new(problem.clone());
        individual
            .update_variable("x1", VariableValue::Real(0.2))
            .unwrap();
        for i in 2..=problem.number_of_variables() {
            individual
                .update_variable(format!("x{i}").as_str(), VariableValue::Real(0.5))
                .unwrap();
        }
        let data = problem.evaluator.evaluate(&individual).unwrap();
        let constraints = data.constraints.clone().unwrap();
        individual.update_constraint("g", constraints["g"]).unwrap();

        // g must yield 0
        assert!(
            individual.is_feasible(),
            "g must be larger or equal to 0 but was {:?}",
            individual.get_constraint_value("g").unwrap()
        );

        // ideal Pareto front leads to sum of objective = 0.5
        assert_eq!(
            problem
                .objective_names()
                .iter()
                .map(|name| data.objectives[name])
                .sum::<f64>(),
            0.5
        );
    }

    #[test]
    /// Test the DTLZ1 problem with random individuals
    fn test_dtlz1_random_solutions() {
        let test_path = Path::new(&env::current_dir().unwrap())
            .join("src")
            .join("core")
            .join("test_data");
        let var_file = test_path.join("DTLZ1_variables.csv");
        let obj_file = test_path.join("DTLZ1_objectives.csv");

        // randomly generated variables
        let all_vars = read_csv_test_file(&var_file, None);
        let all_expected_objectives = read_csv_test_file(&obj_file, None);

        for (expected_objectives, vars) in all_expected_objectives.iter().zip(all_vars) {
            let problem = Arc::new(DTLZ1Problem::create(vars.len(), 3, false).unwrap());
            let mut individual = Individual::new(problem.clone());
            for (i, var) in vars.iter().enumerate() {
                individual
                    .update_variable(format!("x{}", i + 1).as_str(), VariableValue::Real(*var))
                    .unwrap();
            }
            let data = problem.evaluator.evaluate(&individual).unwrap();

            for (i, obj) in expected_objectives.iter().enumerate() {
                let name = format!("f{}", i + 1);
                assert_approx_eq!(f64, *obj, data.objectives[&name], epsilon = 0.00001);
            }
        }
    }

    #[test]
    /// Test the DTLZ2 problem implementation with the optimal solution
    fn test_dtlz2_optimal_solutions() {
        let problem = Arc::new(DTLZ2Problem::create(4, 3).unwrap());
        let mut individual = Individual::new(problem.clone());
        individual
            .update_variable("x1", VariableValue::Real(0.2))
            .unwrap();
        individual
            .update_variable("x2", VariableValue::Real(0.2))
            .unwrap();
        for i in 3..=problem.number_of_variables() {
            individual
                .update_variable(format!("x{i}").as_str(), VariableValue::Real(0.5))
                .unwrap();
        }
        let data = problem.evaluator.evaluate(&individual).unwrap();
        let constraints = data.constraints.clone().unwrap();
        individual.update_constraint("g", constraints["g"]).unwrap();

        // g must yield 0
        assert!(
            individual.is_feasible(),
            "g must be larger or equal to 0 but was {:?}",
            individual.get_constraint_value("g").unwrap()
        );

        // Eq 6.9
        assert_approx_eq!(
            f64,
            problem
                .objective_names()
                .iter()
                .map(|name| data.objectives[name].powi(2))
                .sum::<f64>(),
            1.0,
            epsilon = 0.00001
        );
    }
}