genalg 0.1.0

A flexible, high-performance genetic algorithm library written in Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
//! # Combinatorial Constraints
//!
//! This module provides common constraints for combinatorial optimization problems.
//! These constraints are particularly useful for problems involving selection, assignment,
//! or sequencing of discrete elements.

use std::collections::{HashMap, HashSet};
use std::fmt::Debug;
use std::hash::Hash;
use std::marker::PhantomData;

use crate::constraints::{Constraint, ConstraintError, ConstraintViolation};
use crate::phenotype::Phenotype;
use crate::rng::RandomNumberGenerator;

/// Result type for constraint operations.
pub type Result<T> = std::result::Result<T, ConstraintError>;

/// Ensures that all elements in a collection are unique.
///
/// This constraint is useful for problems where each element can only be used once,
/// such as assignment problems or permutation problems.
#[derive(Debug, Clone)]
pub struct UniqueElementsConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    /// Name of the constraint for error messages
    name: String,
    /// Function to extract the elements to check for uniqueness
    extractor: F,
    _marker: PhantomData<(P, T)>,
}

impl<P, T, F> UniqueElementsConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    /// Creates a new unique elements constraint with the given name and extractor function.
    ///
    /// The extractor function is used to extract the elements to check for uniqueness
    /// from the phenotype.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the constraint for error messages.
    /// * `extractor` - A function that extracts the elements to check for uniqueness from the phenotype.
    ///
    /// # Returns
    ///
    /// A new unique elements constraint, or an error if the name is empty.
    pub fn new<S: Into<String>>(name: S, extractor: F) -> Result<Self> {
        let name = name.into();
        if name.is_empty() {
            return Err(ConstraintError::EmptyName);
        }
        Ok(Self {
            name,
            extractor,
            _marker: PhantomData,
        })
    }

    /// Returns the name of the constraint.
    pub fn name(&self) -> &str {
        &self.name
    }
}

impl<P, T, F> Constraint<P> for UniqueElementsConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    fn check(&self, phenotype: &P) -> Vec<ConstraintViolation> {
        let elements = (self.extractor)(phenotype);
        let mut seen = HashSet::new();
        let mut violations = Vec::new();

        for (idx, element) in elements.iter().enumerate() {
            if !seen.insert(element) {
                violations.push(ConstraintViolation::new(
                    &self.name,
                    format!("Duplicate element {:?} at position {}", element, idx),
                ));
            }
        }

        violations
    }

    fn repair_with_rng(&self, phenotype: &mut P, rng: &mut RandomNumberGenerator) -> bool {
        // This is a generic implementation that might not work for all phenotypes
        // It relies on the phenotype's mutate method to potentially fix the uniqueness issue

        // Check if there are any violations
        let violations = self.check(phenotype);
        if violations.is_empty() {
            return false; // No violations to repair
        }

        // Try to repair by mutating the phenotype
        phenotype.mutate(rng);

        // Check if repair was successful
        let new_violations = self.check(phenotype);
        new_violations.is_empty()
    }
}

/// Ensures that all required keys are assigned a value.
///
/// This constraint is useful for assignment problems where each key must be assigned
/// a value from a set of possible values.
#[derive(Debug, Clone)]
pub struct CompleteAssignmentConstraint<P, K, V, F>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<K, V> + Send + Sync + Debug,
{
    /// Name of the constraint for error messages
    name: String,
    /// Function to extract the assignments from the phenotype
    extractor: F,
    /// The set of keys that must be assigned
    required_keys: HashSet<K>,
    /// Phantom data for the value type
    _marker: PhantomData<P>,
}

impl<P, K, V, F> CompleteAssignmentConstraint<P, K, V, F>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<K, V> + Send + Sync + Debug,
{
    /// Creates a new complete assignment constraint with the given name, extractor function,
    /// and set of required keys.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the constraint for error messages.
    /// * `extractor` - A function that extracts the assignments from the phenotype.
    /// * `required_keys` - The set of keys that must be assigned.
    ///
    /// # Returns
    ///
    /// A new complete assignment constraint, or an error if the name is empty or if the required keys set is empty.
    pub fn new<S: Into<String>>(name: S, extractor: F, required_keys: HashSet<K>) -> Result<Self> {
        let name = name.into();
        if name.is_empty() {
            return Err(ConstraintError::EmptyName);
        }
        if required_keys.is_empty() {
            return Err(ConstraintError::EmptyCollection(
                "Required keys set".to_string(),
            ));
        }
        Ok(Self {
            name,
            extractor,
            required_keys,
            _marker: PhantomData,
        })
    }
}

impl<P, K, V, F> Constraint<P> for CompleteAssignmentConstraint<P, K, V, F>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<K, V> + Send + Sync + Debug,
{
    fn check(&self, phenotype: &P) -> Vec<ConstraintViolation> {
        let assignments = (self.extractor)(phenotype);
        let mut violations = Vec::new();

        for key in &self.required_keys {
            if !assignments.contains_key(key) {
                violations.push(ConstraintViolation::new(
                    &self.name,
                    format!("Missing assignment for key {:?}", key),
                ));
            }
        }

        violations
    }

    fn repair_with_rng(&self, phenotype: &mut P, rng: &mut RandomNumberGenerator) -> bool {
        // This is a generic implementation that might not work for all phenotypes
        // It relies on the phenotype's mutate method to potentially fix the assignment issue

        // Check if there are any violations
        let violations = self.check(phenotype);
        if violations.is_empty() {
            return false; // No violations to repair
        }

        // Try to repair by mutating the phenotype
        phenotype.mutate(rng);

        // Check if repair was successful
        let new_violations = self.check(phenotype);
        new_violations.is_empty()
    }
}

/// Ensures that assignments satisfy capacity constraints.
///
/// This constraint is useful for bin packing or resource allocation problems
/// where each bin or resource has a limited capacity.
#[derive(Debug, Clone)]
pub struct CapacityConstraint<P, K, V, F, G>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<V, Vec<K>> + Send + Sync + Debug,
    G: Fn(&V) -> usize + Send + Sync + Debug,
{
    /// Name of the constraint for error messages
    name: String,
    /// Function to extract the assignments from the phenotype
    extractor: F,
    /// Function to get the capacity of each bin
    capacity_fn: G,
    /// Phantom data for the key and value types
    _marker: PhantomData<P>,
}

impl<P, K, V, F, G> CapacityConstraint<P, K, V, F, G>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<V, Vec<K>> + Send + Sync + Debug,
    G: Fn(&V) -> usize + Send + Sync + Debug,
{
    /// Creates a new capacity constraint with the given name, extractor function,
    /// and capacity function.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the constraint for error messages.
    /// * `extractor` - A function that extracts the assignments from the phenotype.
    /// * `capacity_fn` - A function that returns the capacity of each bin.
    ///
    /// # Returns
    ///
    /// A new capacity constraint, or an error if the name is empty.
    pub fn new<S: Into<String>>(name: S, extractor: F, capacity_fn: G) -> Result<Self> {
        let name = name.into();
        if name.is_empty() {
            return Err(ConstraintError::EmptyName);
        }
        Ok(Self {
            name,
            extractor,
            capacity_fn,
            _marker: PhantomData,
        })
    }
}

impl<P, K, V, F, G> Constraint<P> for CapacityConstraint<P, K, V, F, G>
where
    P: Phenotype,
    K: Eq + Hash + Debug + Clone + Send + Sync,
    V: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> HashMap<V, Vec<K>> + Send + Sync + Debug,
    G: Fn(&V) -> usize + Send + Sync + Debug,
{
    fn check(&self, phenotype: &P) -> Vec<ConstraintViolation> {
        let assignments = (self.extractor)(phenotype);
        let mut violations = Vec::new();

        for (bin, items) in assignments.iter() {
            let capacity = (self.capacity_fn)(bin);
            if items.len() > capacity {
                violations.push(ConstraintViolation::new(
                    &self.name,
                    format!(
                        "Bin {:?} has {} items but capacity is {}",
                        bin,
                        items.len(),
                        capacity
                    ),
                ));
            }
        }

        violations
    }

    fn repair_with_rng(&self, phenotype: &mut P, rng: &mut RandomNumberGenerator) -> bool {
        // This is a generic implementation that might not work for all phenotypes
        // It relies on the phenotype's mutate method to potentially fix the capacity issue

        // Check if there are any violations
        let violations = self.check(phenotype);
        if violations.is_empty() {
            return false; // No violations to repair
        }

        // Try to repair by mutating the phenotype
        phenotype.mutate(rng);

        // Check if repair was successful
        let new_violations = self.check(phenotype);
        new_violations.is_empty()
    }
}

/// Ensures that dependencies between elements are satisfied.
///
/// This constraint is useful for problems where some elements must come before
/// others, such as scheduling or sequencing problems.
#[derive(Debug, Clone)]
pub struct DependencyConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    /// Name of the constraint for error messages
    name: String,
    /// Function to extract the sequence from the phenotype
    extractor: F,
    /// The set of dependencies (before, after) pairs
    dependencies: Vec<(T, T)>,
    /// Phantom data for the phenotype type
    _marker: PhantomData<P>,
}

impl<P, T, F> DependencyConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    /// Creates a new dependency constraint with the given name, extractor function,
    /// and dependencies.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the constraint for error messages.
    /// * `extractor` - A function that extracts the sequence from the phenotype.
    /// * `dependencies` - A vector of (before, after) pairs representing dependencies.
    ///
    /// # Returns
    ///
    /// A new dependency constraint, or an error if the name is empty or if the dependencies vector is empty.
    pub fn new<S: Into<String>>(name: S, extractor: F, dependencies: Vec<(T, T)>) -> Result<Self> {
        let name = name.into();
        if name.is_empty() {
            return Err(ConstraintError::EmptyName);
        }
        if dependencies.is_empty() {
            return Err(ConstraintError::EmptyCollection(
                "Dependencies vector".to_string(),
            ));
        }
        Ok(Self {
            name,
            extractor,
            dependencies,
            _marker: PhantomData,
        })
    }
}

impl<P, T, F> Constraint<P> for DependencyConstraint<P, T, F>
where
    P: Phenotype,
    T: Eq + Hash + Debug + Clone + Send + Sync,
    F: Fn(&P) -> Vec<T> + Send + Sync + Debug,
{
    fn check(&self, phenotype: &P) -> Vec<ConstraintViolation> {
        let sequence = (self.extractor)(phenotype);
        let mut violations = Vec::new();

        // Build a map of element to position
        let mut positions = HashMap::new();
        for (pos, element) in sequence.iter().enumerate() {
            positions.insert(element, pos);
        }

        // Check each dependency
        for (before, after) in &self.dependencies {
            if let (Some(&before_pos), Some(&after_pos)) =
                (positions.get(before), positions.get(after))
            {
                if before_pos >= after_pos {
                    violations.push(ConstraintViolation::new(
                        &self.name,
                        format!(
                            "Dependency violation: {:?} must come before {:?}",
                            before, after
                        ),
                    ));
                }
            }
        }

        violations
    }

    fn repair_with_rng(&self, phenotype: &mut P, rng: &mut RandomNumberGenerator) -> bool {
        // This is a generic implementation that might not work for all phenotypes
        // It relies on the phenotype's mutate method to potentially fix the dependency issue

        // Check if there are any violations
        let violations = self.check(phenotype);
        if violations.is_empty() {
            return false; // No violations to repair
        }

        // Try to repair by mutating the phenotype
        phenotype.mutate(rng);

        // Check if repair was successful
        let new_violations = self.check(phenotype);
        new_violations.is_empty()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // Test the constraint violation struct
    #[test]
    fn test_constraint_violation() {
        let violation = ConstraintViolation::new("TestConstraint", "Test violation");
        assert_eq!(violation.constraint_name(), "TestConstraint");
        assert_eq!(violation.description(), "Test violation");
        assert!(violation.severity().is_none());

        let violation_with_severity =
            ConstraintViolation::with_severity("TestConstraint", "Test violation", 2.5);
        assert_eq!(violation_with_severity.constraint_name(), "TestConstraint");
        assert_eq!(violation_with_severity.description(), "Test violation");
        assert_eq!(violation_with_severity.severity(), Some(2.5));
    }

    // Test the constraint module documentation examples
    #[test]
    fn test_constraint_documentation_examples() {
        // This test verifies that the examples in the module documentation compile
        // and work as expected. It doesn't directly test the constraints themselves,
        // but ensures that the API is usable as documented.

        // Example of creating a constraint violation
        let violation = ConstraintViolation::new("UniqueValues", "Duplicate value 2 at position 3");
        assert_eq!(violation.constraint_name(), "UniqueValues");
        assert_eq!(violation.description(), "Duplicate value 2 at position 3");

        // Example of creating a constraint violation with severity
        let violation = ConstraintViolation::with_severity(
            "CapacityConstraint",
            "Bin 1 exceeds capacity by 3 items",
            3.0,
        );
        assert_eq!(violation.severity(), Some(3.0));

        // Example of formatting a constraint violation
        let violation = ConstraintViolation::new("TestConstraint", "Test violation");
        let formatted = format!("{}", violation);
        assert!(formatted.contains("TestConstraint"));
        assert!(formatted.contains("Test violation"));
    }

    #[test]
    fn test_empty_name_validation() {
        // Test that empty names are rejected
        let empty_name = "".to_string();
        let valid_name = "Test".to_string();

        // Check that empty names are rejected
        assert!(empty_name.is_empty());
        assert!(!valid_name.is_empty());
    }

    #[test]
    fn test_empty_collection_validation() {
        // Test that empty collections are rejected
        let empty_keys: HashSet<i32> = HashSet::new();
        let valid_keys: HashSet<i32> = [1, 2, 3].iter().cloned().collect();

        let empty_deps: Vec<(i32, i32)> = Vec::new();
        let valid_deps: Vec<(i32, i32)> = vec![(1, 2), (2, 3)];

        // Check that empty collections are rejected
        assert!(empty_keys.is_empty());
        assert!(!valid_keys.is_empty());

        assert!(empty_deps.is_empty());
        assert!(!valid_deps.is_empty());
    }
}