radiate-engines 1.2.22

Engines for the Radiate genetic algorithm library.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
//! # Engine Iterator System
//!
//! This module provides a comprehensive iterator system for genetic algorithm engines,
//! enabling fine-grained control over evolutionary execution with various termination
//! conditions and monitoring capabilities.
//!
//! The iterator system extends the basic `Engine` trait with powerful methods for:
//! - **Termination Control**: Generation limits, time limits, score thresholds, and convergence detection
//! - **Monitoring**: Logging, progress tracking, and performance metrics
//! - **Adaptive Execution**: Stagnation detection and early stopping
//! - **Composable Limits**: Combining multiple termination conditions
//!
//! # Key Components
//!
//! - **EngineIterator**: Basic iterator wrapper around any engine
//! - **EngineIteratorExt**: Extension trait providing termination and monitoring methods
//! - **Specialized Iterators**: Various iterator types for different termination strategies
//! - **Limit System**: Flexible limit specification and combination
#[cfg(feature = "serde")]
use crate::{CheckpointWriter, JsonCheckpointWriter};
use crate::{Generation, Limit, control::EngineControl, init_logging};
use radiate_core::{Chromosome, Engine, Metric, Objective, Optimize, Score};
use radiate_expr::{AnyValue, ApplyExpr, Expr};
#[cfg(feature = "serde")]
use serde::Serialize;
#[cfg(feature = "serde")]
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::{collections::VecDeque, time::Duration};
use tracing::info;

/// A basic iterator wrapper around any engine that implements the [Engine] trait.
///
/// [EngineIterator] provides a simple way to iterate over the generations produced
/// by an engine, yielding one generation per iteration. This is the foundation
/// for more sophisticated iteration patterns through the extension trait.
///
/// The [EngineIterator] is an 'infinite' iterator, meaning it will continue to
/// produce generations until explicitly terminated so always provide termination conditions,
/// whether through traditional means (like `.last()`, `.take()`, or custom predicates).
///
/// # Generic Parameters
///
/// - `E`: The engine type that this iterator wraps
///
/// # Examples
///
/// ```rust,ignore
/// use radiate_engines::*;
///
/// let engine = GeneticEngine::builder()
///     .codec(FloatCodec::vector(5, 0.0..1.0))
///     .fitness_fn(|x: Vec<f32>| x.iter().sum::<f32>())
///     .build();
///
/// // Basic iteration
/// for generation in engine.iter() {
///     println!("Generation {}: Score = {}",
///              generation.index(), generation.score().as_f32());
///
///     if generation.index() > 10 {
///         break;
///     }
/// }
///
/// // Basic iterator through functional methods - notice the call to last().
/// // This will retrieve the last generation after 10 iterations.
/// let last_generation = engine.iter().take(10).last();
/// ```
///
/// # Design
///
/// This iterator is intentionally simple, providing the basic iteration capability
/// while delegating advanced functionality to the extension trait. This separation
/// allows for clean composition of different iteration strategies.
pub struct EngineIterator<E>
where
    E: Engine,
{
    engine: E,
    control: Option<EngineControl>,
}

impl<E> EngineIterator<E>
where
    E: Engine,
{
    /// Creates a new [EngineIterator] wrapping the specified engine.
    ///
    /// # Arguments
    ///
    /// * `engine` - The engine to wrap with the iterator
    /// * `control` - Optional engine control for pausing/stopping/resuming
    ///
    /// # Returns
    ///
    /// A new instance of [EngineIterator]
    pub fn new(engine: E, control: Option<EngineControl>) -> Self {
        EngineIterator { engine, control }
    }
}

/// Implementation of `Iterator` for [EngineIterator].
///
/// Each call to `next()` advances the engine by one generation and returns
/// the resulting generation data. The iterator continues indefinitely until
/// external termination conditions are applied - so always provide termination conditions.
impl<E> Iterator for EngineIterator<E>
where
    E: Engine,
{
    type Item = E::Epoch;

    fn next(&mut self) -> Option<Self::Item> {
        if let Some(control) = &self.control {
            if control.is_stopped() {
                return None;
            }
        }

        match self.engine.next() {
            Ok(epoch) => Some(epoch),
            Err(e) => panic!("{e}"),
        }
    }
}

/// Blanket implementation of the extension trait for any iterator over generations.
///
/// This implementation provides the extension methods to any iterator that yields
/// [`Generation<C, T>`] items, making the termination and monitoring functionality
/// available to a wide range of iteration patterns.
impl<I, C, T> EngineIteratorExt<C, T> for I
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
    T: Clone,
{
}

/// Extension trait providing advanced iteration capabilities for [Engine]s.
///
/// [`EngineIteratorExt`] adds powerful methods for controlling and monitoring the
/// evolutionary process, including various termination conditions, convergence
/// detection, stagnation monitoring, and logging capabilities.
///
/// # Generic Parameters
///
/// - `C`: The [Chromosome] type used by the engine
/// - `T`: The phenotype type produced by the engine
///
/// # Examples
///
/// ## Basic Termination
///
/// ```rust,ignore
/// use radiate_engines::*;
///
/// let engine = GeneticEngine::builder()
///     .codec(FloatCodec::vector(5, 0.0..1.0))
///     .fitness_fn(|x: Vec<f32>| x.iter().sum())
///     .build();
///
/// // Run for exactly 100 generations - this is essentially
/// // the same as using a '.Take(100)' on a traditional iterator & is
/// // also completely viable as a solution.
/// for generation in engine.iter().limit(Limit::Generation(100)) {
///     // Process each generation
/// }
///
/// // Run until fitness reaches 0.95
/// for generation in engine.iter().until_score(0.95) {
///     // Process until target fitness
/// }
///
/// // Run for 5 minutes
/// for generation in engine.iter().until_seconds(300) {
///     // Process for time limit
/// }
///
/// let last_generation = engine
///     .iter()
///     .logging() // Enable logging
///     .until_seconds(5)
///     .last(); // Get the last generation after 5 seconds
/// ```
///
/// ## Advanced Termination
///
/// ```rust,ignore
/// // Run until convergence (no improvement for 50 generations)
/// for generation in engine.iter().until_converged(50, 0.001) {
///     // Process until convergence
/// }
///
/// // Run until stagnation (no significant improvement for 100 generations)
/// for generation in engine.iter().until_stagnant(100, 0.01) {
///     // Process until stagnation
/// }
///
/// // Combine multiple limits
/// let combined_limit = Limit::Combined(vec![
///     Limit::Generation(1000),
///     Limit::Score(0.99),
///     Limit::Seconds(600.0),
/// ]);
///
/// for generation in engine.iter().limit(combined_limit) {
///     // Process with combined limits
/// }
/// ```
///
/// ## Monitoring and Logging
///
/// ```rust,ignore
/// // Add logging to see progress
/// for generation in engine.iter()
///     .take(100)
///     .logging() {
///     // Each generation will be logged automatically
/// }
/// ```
///
/// # Termination Strategies
///
/// The extension provides several termination strategies:
///
/// - **Generation Limits**: Stop after a fixed number of generations
/// - **Time Limits**: Stop after a specified duration
/// - **Score Thresholds**: Stop when fitness reaches a target value
/// - **Convergence Detection**: Stop when improvement rate falls below threshold
/// - **Stagnation Detection**: Stop when no significant improvement occurs
/// - **Combined Limits**: Apply multiple termination conditions
///
/// # Performance Considerations
///
/// - **Early Termination**: Conditions are checked efficiently without blocking
/// - **Memory Management**: History-based iterators use bounded memory
/// - **Composable Design**: Multiple limits can be combined efficiently
pub trait EngineIteratorExt<C, T>: Iterator<Item = Generation<C, T>>
where
    C: Chromosome,
    T: Clone,
{
    fn run(self) -> Option<Generation<C, T>>
    where
        Self: Sized,
    {
        self.last()
    }

    /// Limits iteration to a specified number of seconds.
    ///
    /// This method creates an iterator that stops when the cumulative execution
    /// time reaches the specified limit. The time is measured by the internal metric system,
    /// so it may not correspond exactly to wall-clock time. Instead, it is equal
    /// to the amount of actual compute time the engine takes.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum execution time in seconds as a floating-point value
    ///
    /// # Returns
    ///
    /// An iterator that respects the time limit
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Run for exactly 2.5 minutes
    /// for generation in engine.iter().until_seconds(150.0) {
    ///     // Process for 2.5 minutes
    /// }
    ///
    /// // Run for 30 seconds
    /// for generation in engine.iter().until_seconds(30.0) {
    ///     // Process for 30 seconds
    /// }
    /// ```
    fn until_seconds(self, limit: f64) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        DurationIterator {
            iter: self,
            limit: Duration::from_secs_f64(limit),
            done: false,
        }
    }

    /// Limits iteration to a specified duration.
    ///
    /// This method provides a more flexible way to specify time limits using
    /// Rust's `Duration` type, which can be constructed from various time units.
    ///
    /// # Arguments
    ///
    /// * `limit` - Maximum execution time as a `Duration`
    ///
    /// # Returns
    ///
    /// An iterator that respects the duration limit
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use std::time::Duration;
    ///
    /// // Run for 5 minutes
    /// for generation in engine.iter().until_duration(Duration::from_secs(300)) {
    ///     // Process for 5 minutes
    /// }
    ///
    /// // Run for 1 hour and 30 minutes
    /// let duration = Duration::from_secs(3600) + Duration::from_secs(1800);
    /// for generation in engine.iter().until_duration(duration) {
    ///     // Process for 1.5 hours
    /// }
    ///
    /// // Run for 500 milliseconds
    /// for generation in engine.iter().until_duration(Duration::from_millis(500)) {
    ///     // Process for 500ms
    /// }
    /// ```
    fn until_duration(self, limit: impl Into<Duration>) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        DurationIterator {
            iter: self,
            limit: limit.into(),
            done: false,
        }
    }

    /// Limits iteration until a target fitness score is reached.
    ///
    /// This method creates an iterator that stops when the best individual's
    /// fitness reaches or exceeds the specified threshold. The comparison
    /// respects the optimization objective (minimize/maximize) and works
    /// with both single and multi-objective problems.
    ///
    /// # Arguments
    ///
    /// * `limit` - The target fitness score to reach
    ///
    /// # Returns
    ///
    /// An iterator that stops when the target score is reached
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // For minimization problems, stop when score <= 0.01
    /// for generation in engine.iter().until_score(0.01) {
    ///     // Process until score drops below 0.01
    /// }
    ///
    /// // For maximization problems, stop when score >= 0.95
    /// for generation in engine.iter().until_score(0.95) {
    ///     // Process until score exceeds 0.95
    /// }
    ///
    /// // Multi-objective problems work automatically
    /// let target_scores = vec![0.01, 0.02, 0.03];
    /// for generation in engine.iter().until_score(target_scores) {
    ///     // Process until all objectives meet their targets
    /// }
    /// ```
    ///
    /// # Objective Handling
    ///
    /// The method automatically handles different optimization objectives:
    /// - **Minimize**: Stops when score <= target
    /// - **Maximize**: Stops when score >= target
    /// - **Multi-objective**: Stops when all objectives meet their targets
    fn until_score(self, limit: impl Into<Score>) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        ScoreIterator {
            iter: self,
            limit: limit.into(),
            done: false,
        }
    }

    /// Limits iteration until convergence is detected.
    ///
    /// This method creates an iterator that stops when the improvement rate
    /// over a specified window of generations falls below a threshold. This
    /// is great for detecting when the algorithm has converged to a local
    /// or global optimum.
    ///
    /// # Arguments
    ///
    /// * `window` - Number of generations to consider for convergence detection
    /// * `epsilon` - Minimum improvement threshold (non-negative)
    ///
    /// # Returns
    ///
    /// An iterator that stops when convergence is detected
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Stop when no improvement > 0.001 over 50 generations
    /// for generation in engine.iter().until_converged(50, 0.001) {
    ///     // Process until convergence
    /// }
    ///
    /// // More sensitive convergence detection
    /// for generation in engine.iter().until_converged(20, 0.0001) {
    ///     // Process until convergence with smaller window and threshold
    /// }
    /// ```
    ///
    /// # Algorithm
    ///
    /// Convergence detection works by:
    /// 1. Maintaining a sliding window of fitness scores
    /// 2. Comparing the first and last scores in the window
    /// 3. Stopping when the difference is less than epsilon
    /// 4. The window size determines sensitivity to local fluctuations
    ///
    /// # Use Cases
    ///
    /// - **Local Optima**: Detect when stuck in local optima
    /// - **Global Convergence**: Identify when approaching global solution
    /// - **Resource Management**: Stop when further improvement is unlikely
    fn until_converged(self, window: usize, epsilon: f32) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        assert!(window > 0, "Window size must be greater than 0");
        assert!(epsilon >= 0.0, "Epsilon must be non-negative");

        ConvergenceIterator {
            iter: self,
            history: VecDeque::new(),
            window,
            epsilon,
            done: false,
        }
    }

    /// Limits iteration until stagnation is detected.
    ///
    /// This method creates an iterator that stops when no significant
    /// improvement occurs for a specified number of generations. This is
    /// great for detecting when the algorithm has plateaued and further
    /// progress is unlikely without parameter adjustments.
    ///
    /// # Arguments
    ///
    /// * `patience` - Number of generations to wait for improvement
    /// * `min_improvement` - Minimum improvement threshold (non-negative)
    ///
    /// # Returns
    ///
    /// An iterator that stops when stagnation is detected
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Stop when no improvement > 0.01 for 100 generations
    /// for generation in engine.iter().until_stagnant(100, 0.01) {
    ///     // Process until stagnation
    /// }
    ///
    /// // More sensitive stagnation detection
    /// for generation in engine.iter().until_stagnant(50, 0.001) {
    ///     // Process until stagnation with higher sensitivity
    /// }
    /// ```
    ///
    /// # Algorithm
    ///
    /// Stagnation detection works by:
    /// 1. Tracking the best fitness score seen so far
    /// 2. Counting generations since the last significant improvement
    /// 3. Stopping when the patience threshold is exceeded
    /// 4. Resetting the counter when improvement occurs
    ///
    /// # Use Cases
    ///
    /// - **Plateau Detection**: Identify when algorithm stops improving
    /// - **Parameter Tuning**: Signal when to adjust mutation rates
    /// - **Resource Management**: Stop when further computation is unlikely to help
    fn until_stagnant(
        self,
        patience: usize,
        min_improvement: f32,
    ) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        assert!(patience > 0, "Patience must be greater than 0");
        assert!(
            min_improvement >= 0.0,
            "Min improvement must be non-negative"
        );

        StagnationIterator {
            iter: self,
            best_score: None,
            patience,
            min_improvement,
            stagnant_count: 0,
            done: false,
        }
    }

    /// Limits iteration based on a custom metric predicate.
    ///     
    /// This method creates an iterator that stops when a specified metric
    /// satisfies a user-defined predicate function. This allows for flexible
    /// termination conditions based on any tracked metric.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the metric to monitor
    /// * `predicate` - A function that takes a [Metric] and returns true to
    ///                 stop iteration
    /// # Returns
    ///
    ///  An iterator that stops when the metric predicate is satisfied
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Stop when evaluation count exceeds 1000
    /// let result = engine
    ///     .iter()
    ///     .until_metric(metric_names::EVALUATION_COUNT, |metric| {
    ///         metric.value_sum().map(|v| v >= 1000.0).unwrap_or(false)
    ///     })
    ///     .last();
    /// ```
    fn until_metric(
        self,
        name: &str,
        predicate: impl Fn(&Metric) -> bool + 'static,
    ) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        MetricLimitIterator {
            iter: self,
            metric_name: name.to_string(),
            limit: Arc::new(predicate),
            done: false,
        }
    }

    /// Applies a [Limit] specification to the iterator.
    ///
    /// This method provides a unified interface for applying various types
    /// of limits to the iteration process. It supports all [Limit] types and
    /// can combine multiple limits for complex termination conditions. This will
    /// stop evolution when any [Limit] is reached.
    ///
    /// # Arguments
    ///
    /// * `limit` - The limit specification to apply
    ///
    /// # Returns
    ///
    /// A boxed iterator that respects the specified limits
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// use radiate_engines::Limit;
    ///
    /// // Single limit
    /// let limit = Limit::Generation(100);
    /// for generation in engine.iter().limit(limit) {
    ///     // Process for 100 generations
    /// }
    ///
    /// // Combined limits
    /// let combined = Limit::Combined(vec![
    ///     Limit::Generation(1000),
    ///     Limit::Score(0.99),
    ///     Limit::Seconds(300.0),
    /// ]);
    ///
    /// for generation in engine.iter().limit(combined) {
    ///     // Process until any limit is reached
    /// }
    /// ```
    ///
    /// # Limit Types
    ///
    /// The method supports all [Limit] types:
    /// - **Generation**: Stop after N generations
    /// - **Seconds**: Stop after N seconds
    /// - **Score**: Stop when target fitness is reached
    /// - **Convergence**: Stop when convergence is detected
    /// - **Combined**: Apply multiple limits simultaneously
    ///
    /// # Performance
    ///
    /// The method returns a boxed iterator to support dynamic dispatch of
    /// different limit types. This provides flexibility at a small runtime cost.
    fn limit(self, limit: impl Into<Limit>) -> Box<dyn Iterator<Item = Generation<C, T>>>
    where
        Self: Sized + 'static,
        C: 'static,
        T: 'static,
    {
        let limit = limit.into();

        match limit {
            Limit::Generation(lim) => Box::new(GenerationIterator {
                iter: self,
                max_index: lim,
                done: false,
            }),
            Limit::Seconds(sec) => Box::new(DurationIterator {
                iter: self,
                limit: sec,
                done: false,
            }),
            Limit::Score(score) => Box::new(ScoreIterator {
                iter: self,
                limit: score,
                done: false,
            }),
            Limit::Convergence(window, epsilon) => Box::new(ConvergenceIterator {
                iter: self,
                window,
                epsilon,
                done: false,
                history: VecDeque::new(),
            }),
            Limit::Metric(name, predicate) => Box::new(MetricLimitIterator {
                iter: self,
                metric_name: name,
                limit: predicate,
                done: false,
            }),
            Limit::Expr(expr) => Box::new(ExprLimitIterator {
                iter: self,
                expr,
                done: false,
            }),
            Limit::Combined(limits) => {
                let mut iter: Box<dyn Iterator<Item = Generation<C, T>>> = Box::new(self);
                for limit in limits {
                    iter = match limit {
                        Limit::Generation(lim) => Box::new(GenerationIterator {
                            iter,
                            max_index: lim,
                            done: false,
                        }),
                        Limit::Seconds(sec) => Box::new(DurationIterator {
                            iter,
                            limit: sec,
                            done: false,
                        }),
                        Limit::Score(score) => Box::new(ScoreIterator {
                            iter,
                            limit: score,
                            done: false,
                        }),
                        Limit::Convergence(window, epsilon) => {
                            Box::new(iter.until_converged(window, epsilon))
                        }
                        Limit::Metric(name, predicate) => Box::new(MetricLimitIterator {
                            iter,
                            metric_name: name,
                            limit: predicate,
                            done: false,
                        }),
                        Limit::Expr(expr) => Box::new(ExprLimitIterator {
                            iter,
                            expr,
                            done: false,
                        }),
                        _ => iter,
                    };
                }

                iter
            }
        }
    }

    /// Adds logging to the iteration process.
    ///
    /// This method wraps the iterator with logging capabilities, automatically
    /// logging information about each generation including index, scores, and
    /// execution time.
    ///
    /// # Examples
    ///
    /// ```rust,ignore
    /// // Add logging to see progress
    /// for generation in engine.iter()
    ///     .limit(Limit::Generation(100))
    ///     .logging() {
    ///     // Each generation will be logged automatically
    ///     // Output format: "Epoch 1    | Score: 0.8500 | Time: 0.15s"
    /// }
    /// ```
    ///
    /// # Logging Format
    ///
    /// The logging provides structured information:
    /// - **Single Objective**: "Epoch N | Score: X.XXXX | Time: Y.YYs"
    /// - **Multi Objective**: "Epoch N | Scores: [X, Y, Z] | Time: Y.YYs"
    ///
    /// # Integration
    ///
    /// Logging integrates with the `tracing` crate, allowing you to:
    fn logging(self) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
    {
        init_logging();
        LoggingIterator { iter: self }
    }

    /// Adds checkpointing to the iteration process.
    ///
    /// This method wraps the iterator with checkpointing capabilities, automatically
    /// saving the state of each generation to disk at specified intervals. This is great if
    /// you want to be able to resume evolution from a specific generation in case of
    /// interruptions or crashes.
    ///
    /// **Note**: This method requires the `serde` feature to be enabled.
    ///
    /// The saved JSON object is simply the serialized [Generation] object. Thus, it can be
    /// loaded back into memory using `serde_json::from_str` or similar methods then added back
    /// to the engine using the `.generation(...)` method on the engine builder to resume evolution.
    ///
    /// # Arguments
    /// * `interval` - The interval (in generations) at which to save checkpoints
    /// * `path` - The directory path where checkpoints will be saved
    ///
    /// # Examples
    /// ```rust,ignore
    /// // Add checkpointing to save every 10 generations
    /// let generation = engine.iter()
    ///     .checkpoint(10, "checkpoints")
    ///     .take(100)
    ///     .last()
    ///     .unwrap();
    /// ```
    #[cfg(feature = "serde")]
    fn checkpoint(
        self,
        interval: usize,
        folder_path: impl AsRef<Path>,
    ) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
        C: Serialize,
        T: Serialize,
    {
        let path_without_extension = folder_path
            .as_ref()
            .to_str()
            .and_then(|s| s.rsplit('.').nth(1))
            .unwrap_or(folder_path.as_ref().to_str().unwrap_or("checkpoints"));

        CheckpointIterator {
            iter: self,
            interval,
            path: PathBuf::from(path_without_extension),
            writer: Box::new(JsonCheckpointWriter),
        }
    }

    #[cfg(feature = "serde")]
    fn checkpoint_with(
        self,
        interval: usize,
        folder_path: impl AsRef<Path>,
        writer: Box<dyn CheckpointWriter<C, T>>,
    ) -> impl Iterator<Item = Generation<C, T>>
    where
        Self: Sized,
        C: Serialize,
        T: Serialize,
    {
        let path_without_extension = folder_path
            .as_ref()
            .to_str()
            .and_then(|s| s.rsplit('.').nth(1))
            .unwrap_or(folder_path.as_ref().to_str().unwrap_or("checkpoints"));

        CheckpointIterator {
            iter: self,
            interval,
            path: PathBuf::from(path_without_extension),
            writer,
        }
    }

    /// Conditionally chains another iterator based on a predicate.
    ///
    /// This method allows for dynamic composition of iterators, where
    /// an additional iterator can be chained based on a boolean condition.
    /// This is useful for applying optional behaviors like logging or
    /// checkpointing without duplicating code.
    ///
    /// # Arguments
    /// * `pred` - The predicate condition to evaluate
    /// * `chain_fn` - A function that takes the current iterator and returns another iterator to chain
    ///
    /// # Returns
    /// An iterator that conditionally chains another iterator
    ///
    /// # Examples
    /// ```rust,ignore  
    /// // Conditionally add logging based on a flag
    /// let enable_logging = true;
    /// let generation = engine.iter()
    ///     .chain_if(enable_logging, |iter| iter.logging())
    ///     .take(50)
    ///     .last()
    ///     .unwrap();
    /// ```
    fn chain_if<F, I>(self, pred: bool, chain_fn: F) -> EitherIter<Self, I>
    where
        Self: Sized,
        F: FnOnce(Self) -> I,
        I: Iterator<Item = Generation<C, T>>,
    {
        if pred {
            EitherIter::B(chain_fn(self))
        } else {
            EitherIter::A(self)
        }
    }
}

/// An enum representing either of two iterator types.
/// Radiate uses this to conditionally chain iterators.
pub enum EitherIter<A, B> {
    A(A),
    B(B),
}

impl<A, B, T> Iterator for EitherIter<A, B>
where
    A: Iterator<Item = T>,
    B: Iterator<Item = T>,
{
    type Item = T;

    fn next(&mut self) -> Option<Self::Item> {
        match self {
            EitherIter::A(a) => a.next(),
            EitherIter::B(b) => b.next(),
        }
    }
}

/// Iterator that adds checkpointing to each generation.
///
/// **Note**: This iterator requires the `serde` feature to be enabled.
///
/// This iterator automatically saves the state of each generation to disk
/// at specified intervals, allowing for recovery and analysis of the
/// evolutionary process. Checkpoints are saved as serialized JSON files.
#[cfg(feature = "serde")]
struct CheckpointIterator<I, C, T>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    interval: usize,
    path: PathBuf,
    writer: Box<dyn CheckpointWriter<C, T>>,
}

/// Implementation of `Iterator` for [CheckpointIterator].
///
/// Each call to `next()` retrieves the next generation, and if the generation
/// index matches the checkpoint interval, it serializes and saves the generation
/// to a JSON file in the specified directory. The filename format is
/// `generation_{index}.json`.
#[cfg(feature = "serde")]
impl<I, C, T> Iterator for CheckpointIterator<I, C, T>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome + Serialize,
    T: Serialize,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.iter.next()?;

        if next.index() % self.interval == 0 {
            let file_path = self.path.join(format!(
                "chckpnt_{}.{}",
                next.index(),
                self.writer.extension()
            ));

            if !self.path.exists() {
                std::fs::create_dir_all(&self.path).expect("Failed to create checkpoint directory");
            }

            let write_result = self.writer.write_checkpoint(file_path, &next);

            if let Err(e) = write_result {
                eprintln!("Failed to write checkpoint: {e}");
                return None;
            }
        }

        Some(next)
    }
}

/// Iterator that adds logging to each generation.
///
/// This iterator automatically logs information about each generation as it
/// is produced, providing real-time monitoring of the evolutionary process.
/// The logging format adapts to single and multi-objective problems.
struct LoggingIterator<I, C, T>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
}

/// Implementation of `Iterator` for [LoggingIterator].
///
/// Each call to `next()` retrieves the next generation, logs relevant
/// information, and returns the generation unchanged. The logging provides
/// structured output for monitoring and debugging.
impl<I, C, T> Iterator for LoggingIterator<I, C, T>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        let next = self.iter.next()?;

        match next.objective() {
            Objective::Single(_) => {
                info!(
                    "Epoch {:<4} | Score: {:>8.4} | Time: {:>5.2?}",
                    next.index(),
                    next.score().as_f32(),
                    next.time()
                );
            }
            Objective::Multi(_) => {
                let front_size = next.metrics().front_size();
                let front_size_value = front_size.map(|ent| ent.last_value()).unwrap_or(0.0);
                info!(
                    "Epoch {:<4} | Front Size: {:.3} | Time: {:>5.2?}",
                    next.index(),
                    front_size_value,
                    next.time()
                );
            }
        }

        Some(next)
    }
}

/// Iterator that limits iteration based on a custom metric predicate.
/// This iterator stops producing items when a specified metric satisfies
/// a user-defined predicate function. This allows for flexible termination
/// conditions based on any tracked metric.
struct MetricLimitIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    metric_name: String,
    limit: Arc<dyn Fn(&Metric) -> bool>,
    done: bool,
}

impl<I, C, T> Iterator for MetricLimitIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let next = self.iter.next()?;
        if let Some(metric) = next.metrics().get(&self.metric_name) {
            if (self.limit)(metric) {
                self.done = true;
            }
        } else {
            panic!(
                "Metric '{}' not found in generation metrics",
                self.metric_name,
            );
        }

        Some(next)
    }
}

struct ExprLimitIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    expr: Expr,
    done: bool,
}

impl<I, C, T> Iterator for ExprLimitIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let next = self.iter.next()?;
        let expr_output = next.metrics().apply(&mut self.expr);
        if let AnyValue::Bool(val) = expr_output {
            self.done = val;
        } else {
            panic!(
                "Expression should evaluate to a boolean value, got: {:?}",
                expr_output
            );
        }

        Some(next)
    }
}

/// Iterator that limits iteration to a maximum number of generations.
///
/// This iterator stops producing items after the specified number of generations
/// has been reached. It's useful for controlling the computational budget
/// and ensuring the algorithm doesn't run indefinitely.
struct GenerationIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    max_index: usize,
    done: bool,
}

/// Implementation of `Iterator` for [GenerationIterator].
///
/// The iterator produces generations until the maximum index is reached,
/// then stops producing items. Its really just a simple way to limit
/// computational effort.
impl<I, C, T> Iterator for GenerationIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.max_index == 0 || self.done {
            return None;
        }

        let next_ctx = self.iter.next()?;
        if next_ctx.index() >= self.max_index {
            self.done = true;
        }

        Some(next_ctx)
    }
}

/// Iterator that limits iteration to a maximum execution time.
///
/// This iterator stops producing items when the cumulative execution time
/// reaches the specified limit.
struct DurationIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    limit: Duration,
    done: bool,
}

/// Implementation of `Iterator` for [DurationIterator].
///
/// The iterator produces generations until the time limit is reached,
/// then stops producing items. Time is measured from the [Engine]'s internal
/// metric system, which provides a consistent and accurate way to track
/// elapsed time.
impl<I, C, T> Iterator for DurationIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.limit <= Duration::from_millis(0) || self.done {
            return None;
        }

        let next = self.iter.next()?;
        if next.time() >= self.limit {
            self.done = true;
        }

        Some(next)
    }
}

/// Iterator that limits iteration until a target fitness score is reached.
///
/// This iterator stops producing items when the best individual's fitness
/// reaches or exceeds the specified threshold. The comparison respects
/// the optimization objective and works with multi-objective problems.
struct ScoreIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    limit: Score,
    done: bool,
}

/// Implementation of `Iterator` for [ScoreIterator].
///
/// The iterator produces generations until the target fitness is reached,
/// respecting the optimization objective. For multi-objective problems,
/// all objectives must meet their targets.
impl<I, C, T> Iterator for ScoreIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let ctx = self.iter.next()?;

        let passed = match ctx.objective() {
            Objective::Single(obj) => match obj {
                Optimize::Minimize => ctx.score() > &self.limit,
                Optimize::Maximize => ctx.score() < &self.limit,
            },
            Objective::Multi(objs) => {
                let mut all_pass = true;
                for (i, score) in ctx.score().iter().enumerate() {
                    let passed = match objs[i] {
                        Optimize::Minimize => score > &self.limit[i],
                        Optimize::Maximize => score < &self.limit[i],
                    };

                    if !passed {
                        all_pass = false;
                        break;
                    }
                }

                all_pass
            }
        };

        if !passed {
            self.done = true;
        }

        Some(ctx)
    }
}

/// Iterator that limits iteration until convergence is detected.
///
/// This iterator stops producing items when the improvement rate over a
/// specified window of generations falls below a threshold.
struct ConvergenceIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    iter: I,
    history: VecDeque<f32>,
    window: usize,
    epsilon: f32,
    done: bool,
}

/// Implementation of `Iterator` for [ConvergenceIterator].
///
/// The iterator maintains a sliding window of fitness scores and stops
/// when the improvement rate falls below the epsilon threshold. This
/// provides adaptive termination based on algorithm behavior.
impl<I, C, T> Iterator for ConvergenceIterator<C, T, I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let next_ctx = self.iter.next()?;
        let score = next_ctx.score().as_f32();

        self.history.push_back(score);
        if self.history.len() > self.window {
            self.history.pop_front();
        }

        if self.history.len() == self.window {
            let first = self.history.front().unwrap();
            let last = self.history.back().unwrap();
            if (first - last).abs() < self.epsilon {
                self.done = true;
            }
        }

        Some(next_ctx)
    }
}

/// Iterator that limits iteration until stagnation is detected.
///
/// This iterator stops producing items when no significant improvement
/// occurs for a specified number of generations.
struct StagnationIterator<I> {
    iter: I,
    best_score: Option<f32>,
    patience: usize,
    min_improvement: f32,
    stagnant_count: usize,
    done: bool,
}

/// Implementation of `Iterator` for [StagnationIterator].
///
/// The iterator tracks the best fitness score and stops when no
/// significant improvement occurs for the specified patience period.
/// This provides early termination for stuck algorithms.
impl<I, C, T> Iterator for StagnationIterator<I>
where
    I: Iterator<Item = Generation<C, T>>,
    C: Chromosome,
{
    type Item = Generation<C, T>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.done {
            return None;
        }

        let generation = self.iter.next()?;
        let current_score = generation.score().as_f32();

        match self.best_score {
            Some(best) => {
                if current_score - best > self.min_improvement {
                    self.best_score = Some(current_score);
                    self.stagnant_count = 0;
                } else {
                    self.stagnant_count += 1;
                    if self.stagnant_count >= self.patience {
                        self.done = true;
                    }
                }
            }
            None => {
                self.best_score = Some(current_score);
            }
        }

        Some(generation)
    }
}