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
use std::cmp::Ordering;

use crate::core::{Individual, OError};

/// The preferred solution with the `BinaryComparisonOperator`.
#[derive(Debug, PartialOrd, PartialEq)]
pub enum PreferredSolution {
    /// The first solution is preferred.
    First,
    /// The second solution is preferred.
    Second,
    /// The two solutions are mutually preferred.
    MutuallyPreferred,
}

/// A trait to implement a comparison operator between two solutions.
pub trait BinaryComparisonOperator {
    /// Compare two solution and select the best one.
    ///
    /// # Arguments
    ///
    /// * `first_solution`: The first solution to compare.
    /// * `second_solution`: The second solution to compare.
    ///
    /// returns: `Result<PreferredSolution, OError>` The preferred solution.
    fn compare(
        first_solution: &Individual,
        second_solution: &Individual,
    ) -> Result<PreferredSolution, OError>
    where
        Self: Sized;
}

/// This assesses the Pareto dominance between two solutions $S_1$ and $S_2$ and their constraint
/// violations in constrained multi-objective optimization problems. A solution $S_1$ is
/// constraint-dominated if:
/// 1) $S_1$ is feasible but $S_2$ is not.
/// 2) Both $S_1$ and $S_2$ are infeasible and $CV(S_1) < CV(S_2)$ (where $CV$ is the constraint
///    violation function); or
/// 3) both are feasible and $S_1$ Pareto-dominate $S_2$ ($ S_1 \prec S_2 $).
///
///
/// See:
///  - Kalyanmoy Deb & Samir Agrawal. (2002). <https://doi.org/10.1007/978-3-7091-6384-9_40>.
///  - Shuang Li, Ke Li, Wei Li. (2022). <https://doi.org/10.48550/arXiv.2205.14349>.
///
pub struct ParetoConstrainedDominance;

impl BinaryComparisonOperator for ParetoConstrainedDominance {
    /// Get the dominance relation between two solutions with constraints.
    ///
    /// # Arguments
    ///
    /// * `first_solution`: The first solution to compare.
    /// * `second_solution`: The second solution to compare.
    ///
    /// returns: `Result<PreferredSolution, OError>` The dominance relation between solution 1
    /// and 2.
    fn compare(
        first_solution: &Individual,
        second_solution: &Individual,
    ) -> Result<PreferredSolution, OError> {
        let problem = first_solution.problem();
        let cv1 = first_solution.constraint_violation();
        let cv2 = second_solution.constraint_violation();

        // at least one solution is not feasible (step 1-2)
        if problem.number_of_constraints() > 0 && cv1 != cv2 {
            if first_solution.is_feasible() {
                // solution 1 dominates
                return Ok(PreferredSolution::First);
            } else if second_solution.is_feasible() {
                // solution 2 dominates
                return Ok(PreferredSolution::Second);
            } else if cv1 < cv2 {
                // solution 1 dominates
                return Ok(PreferredSolution::First);
            } else if cv1 > cv2 {
                // solution 2 dominates
                return Ok(PreferredSolution::Second);
            }
        }

        // check pareto dominance using all the objectives (step 2)
        let mut relation = PreferredSolution::MutuallyPreferred;
        for objective_name in problem.objective_names() {
            let obj_sol1 = first_solution.get_objective_value(objective_name.as_str())?;
            let obj_sol2 = second_solution.get_objective_value(objective_name.as_str())?;

            if obj_sol1 < obj_sol2 {
                // previous objective favours 2nd solution
                if relation == PreferredSolution::Second {
                    // mutually dominated
                    return Ok(PreferredSolution::MutuallyPreferred);
                }
                relation = PreferredSolution::First;
            } else if obj_sol1 > obj_sol2 {
                // previous objective favours 1st solution
                if relation == PreferredSolution::First {
                    // mutually dominated
                    return Ok(PreferredSolution::MutuallyPreferred);
                }
                relation = PreferredSolution::Second;
            }
        }

        Ok(relation)
    }
}

/// This implements the crowded-comparison operator from Deb et al. (2002) for the NSGAII algorithm.
/// A solution $S_i$ dominates a solution $S_j$ if:
///
///    - $rank_i < rank_j$
///
/// or when $rank_i =rank_j$
///
///    - ${distance}_i > {distance}_j$
///
/// where $rank_x$ is the rank from the fast non-dominated sort algorithm (see
/// [`crate::utils::fast_non_dominated_sort()`]) and $distance_x$ is the crowding distance using
/// neighboring solutions.
///
/// Implemented based on:
/// > K. Deb, A. Pratap, S. Agarwal and T. Meyarivan, "A fast and elitist multi-objective genetic
/// > algorithm: NSGA-II," in IEEE Transactions on Evolutionary Computation, vol. 6, no. 2, pp.
/// > 182-197, April 2002, doi: 10.1109/4235.996017.
///
pub struct CrowdedComparison;

impl BinaryComparisonOperator for CrowdedComparison {
    /// Get the crowded comparison relation between two solutions with rank and crowding distance
    /// data. This returns an error if the data does not exist on either solutions.
    ///
    /// # Arguments
    ///
    /// * `first_solution`: The first solution to compare.
    /// * `second_solution`: The second solution to compare.
    ///
    /// returns: `Result<PreferredSolution, OError>` The dominance relation between solution 1
    /// and 2.
    fn compare(
        first_solution: &Individual,
        second_solution: &Individual,
    ) -> Result<PreferredSolution, OError> {
        let name = "CrowdedComparison".to_string();
        let rank1 = match first_solution.get_data("rank") {
            Err(_) => {
                return Err(OError::ComparisonOperator(
                    name,
                    "The rank on the first individual does not exist".to_string(),
                ))
            }
            Ok(r) => r.as_integer()?,
        };
        let rank2 = match second_solution.get_data("rank") {
            Err(_) => {
                return Err(OError::ComparisonOperator(
                    name,
                    "The rank on the second individual does not exist".to_string(),
                ))
            }
            Ok(r) => r.as_integer()?,
        };

        match rank1.cmp(&rank2) {
            Ordering::Less => Ok(PreferredSolution::First),
            Ordering::Equal => {
                let d1 = match first_solution.get_data("crowding_distance") {
                    Err(_) => {
                        return Err(OError::ComparisonOperator(
                            name,
                            format!(
                                "The crowding distance on the first individual {:?} does not exist",
                                first_solution.variables()
                            ),
                        ))
                    }
                    Ok(r) => r.as_real()?,
                };
                let d2 = match second_solution.get_data("crowding_distance") {
                    Err(_) => {
                        return Err(OError::ComparisonOperator(
                            name,
                            format!(
                            "The crowding distance on the second individual {:?} does not exist",
                            second_solution.variables()
                        ),
                        ))
                    }
                    Ok(r) => r.as_real()?,
                };

                if d1 > d2 {
                    Ok(PreferredSolution::First)
                } else {
                    Ok(PreferredSolution::Second)
                }
            }
            Ordering::Greater => Ok(PreferredSolution::Second),
        }
    }
}

#[cfg(test)]
mod test_pareto_constrained_dominance {
    use std::sync::Arc;

    use crate::core::utils::dummy_evaluator;
    use crate::core::{
        BoundedNumber, Constraint, Individual, Objective, ObjectiveDirection, Problem,
        RelationalOperator, VariableType,
    };
    use crate::operators::{
        BinaryComparisonOperator, ParetoConstrainedDominance, PreferredSolution,
    };

    #[test]
    /// Test unconstrained problem with one objective
    fn test_unconstrained_solutions_1_objective() {
        let objectives = vec![Objective::new("obj1", ObjectiveDirection::Minimise)];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());

        // Sol 1 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Sol 2 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 1.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );

        // Both are non dominated
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 5.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::MutuallyPreferred
        );

        // Maximisation problem
        let objectives = vec![Objective::new("obj1", ObjectiveDirection::Maximise)];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());

        // Sol 2 dominates with larger objective
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );
    }

    #[test]
    /// Test unconstrained problem with two objectives
    fn test_unconstrained_solutions_2_objectives() {
        let objectives = vec![
            Objective::new("obj1", ObjectiveDirection::Minimise),
            Objective::new("obj2", ObjectiveDirection::Minimise),
        ];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());

        // Sol 1 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution1.update_objective("obj2", 1.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();
        solution2.update_objective("obj2", 25.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Sol 2 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution1.update_objective("obj2", 1.0).unwrap();
        solution2.update_objective("obj1", -15.0).unwrap();
        solution2.update_objective("obj2", -25.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );

        // Obj1 of Sol 1 dominates and Obj2 of Sol 2 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution1.update_objective("obj2", 100.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();
        solution2.update_objective("obj2", 25.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::MutuallyPreferred
        );

        // compare three solutions
        let mut solution3 = Individual::new(problem.clone());
        solution1.update_objective("obj1", 0.0).unwrap();
        solution1.update_objective("obj2", 0.0).unwrap();
        solution2.update_objective("obj1", 1.0).unwrap();
        solution2.update_objective("obj2", 1.0).unwrap();
        solution3.update_objective("obj1", 0.0).unwrap();
        solution3.update_objective("obj2", 1.0).unwrap();

        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution2, &solution1).unwrap(),
            PreferredSolution::Second
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution3).unwrap(),
            PreferredSolution::First
        );
        // mutually dominated for obj1, but obj2 of sol1 dominates
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution3, &solution1).unwrap(),
            PreferredSolution::Second
        );

        // non-dominance
        solution1.update_objective("obj1", 0.0).unwrap();
        solution1.update_objective("obj2", 1.0).unwrap();
        solution2.update_objective("obj1", 0.5).unwrap();
        solution2.update_objective("obj2", 0.5).unwrap();
        solution3.update_objective("obj1", 1.0).unwrap();
        solution3.update_objective("obj2", 0.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::MutuallyPreferred
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution2, &solution1).unwrap(),
            PreferredSolution::MutuallyPreferred
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution2, &solution3).unwrap(),
            PreferredSolution::MutuallyPreferred
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution3, &solution2).unwrap(),
            PreferredSolution::MutuallyPreferred
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution3).unwrap(),
            PreferredSolution::MutuallyPreferred
        );
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution3, &solution1).unwrap(),
            PreferredSolution::MutuallyPreferred
        );

        // Maximisation problem
        let objectives = vec![
            Objective::new("obj1", ObjectiveDirection::Minimise),
            Objective::new("obj2", ObjectiveDirection::Maximise),
        ];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());

        // Neither dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();
        solution1.update_objective("obj2", 5.0).unwrap();
        solution2.update_objective("obj2", 15.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::MutuallyPreferred
        );

        // Sol 2 dominates
        solution1.update_objective("obj1", 5.0).unwrap();
        solution1.update_objective("obj2", -5.0).unwrap();
        solution2.update_objective("obj1", 1.0).unwrap();
        solution2.update_objective("obj2", 15.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );
    }

    #[test]
    /// Test constrained problem with. The constraint violation determines the dominance relation.
    fn test_constrained_solutions() {
        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)];

        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, Some(constraints), e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());
        solution1.update_objective("obj1", 5.0).unwrap();
        solution2.update_objective("obj1", 15.0).unwrap();

        // Sol 2 dominates because is feasible
        solution1.update_constraint("c1", 0.0).unwrap();
        solution2.update_constraint("c1", 1.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );

        // Solution 1 dominates due to the smaller violation
        solution1.update_constraint("c1", 0.5).unwrap();
        solution2.update_constraint("c1", 3.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Solution 1 is returned when violation magnitude is the same
        solution1.update_constraint("c1", 0.5).unwrap();
        solution2.update_constraint("c1", 0.5).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Two objectives
        let objectives = vec![
            Objective::new("obj1", ObjectiveDirection::Minimise),
            Objective::new("obj2", ObjectiveDirection::Minimise),
        ];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let constraints = vec![Constraint::new("c1", RelationalOperator::EqualTo, 5.0)];

        let e = dummy_evaluator();
        let problem2 = Arc::new(Problem::new(objectives, variables, Some(constraints), e).unwrap());

        let mut solution1 = Individual::new(problem2.clone());
        let mut solution2 = Individual::new(problem2);
        solution1.update_objective("obj2", 100.0).unwrap();
        solution2.update_objective("obj2", 15.0).unwrap();
        solution1.update_constraint("c1", 0.5).unwrap();
        solution2.update_constraint("c1", 3.0).unwrap();
        assert_eq!(
            ParetoConstrainedDominance::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );
    }
}

#[cfg(test)]
mod test_crowded_comparison {
    use std::sync::Arc;

    use crate::core::utils::dummy_evaluator;
    use crate::core::{
        BoundedNumber, DataValue, Individual, Objective, ObjectiveDirection, Problem, VariableType,
    };
    use crate::operators::comparison::CrowdedComparison;
    use crate::operators::{BinaryComparisonOperator, PreferredSolution};

    #[test]
    fn test_different_rank() {
        let objectives = vec![Objective::new("obj1", ObjectiveDirection::Minimise)];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());
        solution1.set_data("rank", DataValue::Integer(1));
        solution2.set_data("rank", DataValue::Integer(4));

        // Sol 1 dominates
        assert_eq!(
            CrowdedComparison::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Sol 2 dominates
        solution1.set_data("rank", DataValue::Integer(5));
        assert_eq!(
            CrowdedComparison::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );
    }

    #[test]
    fn test_same_rank() {
        let objectives = vec![Objective::new("obj1", ObjectiveDirection::Minimise)];
        let variables = vec![VariableType::Real(
            BoundedNumber::new("X1", 0.0, 2.0).unwrap(),
        )];
        let e = dummy_evaluator();
        let problem = Arc::new(Problem::new(objectives, variables, None, e).unwrap());

        let mut solution1 = Individual::new(problem.clone());
        let mut solution2 = Individual::new(problem.clone());
        solution1.set_data("rank", DataValue::Integer(1));
        solution2.set_data("rank", DataValue::Integer(1));

        solution1.set_data("crowding_distance", DataValue::Real(10.5));
        solution2.set_data("crowding_distance", DataValue::Real(0.32));
        // Sol 1 dominates
        assert_eq!(
            CrowdedComparison::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::First
        );

        // Sol 2 dominates
        solution2.set_data("crowding_distance", DataValue::Real(100.32));
        assert_eq!(
            CrowdedComparison::compare(&solution1, &solution2).unwrap(),
            PreferredSolution::Second
        );
    }
}