scirs2-optimize 0.4.2

Optimization module for SciRS2 (scirs2-optimize)
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
//! Advanced line search algorithms for optimization
//!
//! This module provides state-of-the-art line search methods including:
//! - Hager-Zhang (CG_DESCENT) line search
//! - Non-monotone line searches for difficult problems  
//! - Enhanced Strong Wolfe with cubic/quadratic interpolation
//! - Adaptive line search with automatic parameter tuning
//! - More-Thuente line search with safeguarding

use crate::error::OptimizeError;
use crate::unconstrained::utils::clip_step;
use crate::unconstrained::Bounds;
use scirs2_core::ndarray::{Array1, ArrayView1};
use std::collections::VecDeque;

/// Advanced line search method selection
#[derive(Debug, Clone, Copy)]
pub enum LineSearchMethod {
    /// Hager-Zhang line search (from CG_DESCENT)
    HagerZhang,
    /// Non-monotone line search with reference values
    NonMonotone,
    /// Enhanced Strong Wolfe with better interpolation
    EnhancedStrongWolfe,
    /// More-Thuente line search with safeguarding
    MoreThuente,
    /// Adaptive line search that adjusts parameters
    Adaptive,
}

/// Options for advanced line search methods
#[derive(Debug, Clone)]
pub struct AdvancedLineSearchOptions {
    /// Line search method to use
    pub method: LineSearchMethod,
    /// Armijo parameter (sufficient decrease)
    pub c1: f64,
    /// Wolfe parameter (curvature condition)
    pub c2: f64,
    /// Maximum number of line search iterations
    pub max_ls_iter: usize,
    /// Minimum step length
    pub alpha_min: f64,
    /// Maximum step length  
    pub alpha_max: f64,
    /// Initial step length
    pub alpha_init: f64,
    /// Tolerance for step length
    pub step_tol: f64,
    /// For non-monotone: memory length
    pub nm_memory: usize,
    /// For adaptive: enable parameter adaptation
    pub enable_adaptation: bool,
    /// Interpolation strategy
    pub interpolation: InterpolationStrategy,
}

/// Interpolation strategies for line search
#[derive(Debug, Clone, Copy)]
pub enum InterpolationStrategy {
    /// Linear interpolation
    Linear,
    /// Quadratic interpolation
    Quadratic,
    /// Cubic interpolation (most accurate)
    Cubic,
    /// Adaptive interpolation based on available information
    Adaptive,
}

impl Default for AdvancedLineSearchOptions {
    fn default() -> Self {
        Self {
            method: LineSearchMethod::HagerZhang,
            c1: 1e-4,
            c2: 0.9,
            max_ls_iter: 20,
            alpha_min: 1e-16,
            alpha_max: 1e6,
            alpha_init: 1.0,
            step_tol: 1e-12,
            nm_memory: 10,
            enable_adaptation: true,
            interpolation: InterpolationStrategy::Cubic,
        }
    }
}

/// Line search result with detailed information
#[derive(Debug, Clone)]
pub struct LineSearchResult {
    /// Step length found
    pub alpha: f64,
    /// Function value at new point
    pub f_new: f64,
    /// Gradient at new point (if computed)
    pub grad_new: Option<Array1<f64>>,
    /// Number of function evaluations
    pub n_fev: usize,
    /// Number of gradient evaluations  
    pub n_gev: usize,
    /// Success flag
    pub success: bool,
    /// Status message
    pub message: String,
    /// Internal algorithm statistics
    pub stats: LineSearchStats,
}

/// Statistics from line search algorithms
#[derive(Debug, Clone)]
pub struct LineSearchStats {
    /// Number of bracketing phases
    pub n_bracket: usize,
    /// Number of zoom phases
    pub n_zoom: usize,
    /// Final interval width
    pub final_width: f64,
    /// Maximum function value encountered
    pub max_f_eval: f64,
    /// Interpolation method used
    pub interpolation_used: InterpolationStrategy,
}

/// State for non-monotone line search
pub struct NonMonotoneState {
    /// Recent function values
    f_history: VecDeque<f64>,
    /// Maximum memory length
    max_memory: usize,
}

impl NonMonotoneState {
    fn new(max_memory: usize) -> Self {
        Self {
            f_history: VecDeque::new(),
            max_memory,
        }
    }

    fn update(&mut self, f_new: f64) {
        self.f_history.push_back(f_new);
        while self.f_history.len() > self.max_memory {
            self.f_history.pop_front();
        }
    }

    fn get_reference_value(&self) -> f64 {
        self.f_history
            .iter()
            .fold(f64::NEG_INFINITY, |a, &b| a.max(b))
    }
}

/// Main advanced line search function
#[allow(dead_code)]
pub fn advanced_line_search<F, G>(
    fun: &mut F,
    grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
    nm_state: Option<&mut NonMonotoneState>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    match options.method {
        LineSearchMethod::HagerZhang => {
            hager_zhang_line_search(fun, grad_fun, x, f0, direction, grad0, options, bounds)
        }
        LineSearchMethod::NonMonotone => non_monotone_line_search(
            fun, grad_fun, x, f0, direction, grad0, options, bounds, nm_state,
        ),
        LineSearchMethod::EnhancedStrongWolfe => {
            enhanced_strong_wolfe(fun, grad_fun, x, f0, direction, grad0, options, bounds)
        }
        LineSearchMethod::MoreThuente => {
            more_thuente_line_search(fun, grad_fun, x, f0, direction, grad0, options, bounds)
        }
        LineSearchMethod::Adaptive => {
            adaptive_line_search(fun, grad_fun, x, f0, direction, grad0, options, bounds)
        }
    }
}

/// Hager-Zhang line search (from CG_DESCENT algorithm)
/// This is one of the most robust line search methods available
#[allow(dead_code)]
fn hager_zhang_line_search<F, G>(
    fun: &mut F,
    mut grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    let mut stats = LineSearchStats {
        n_bracket: 0,
        n_zoom: 0,
        final_width: 0.0,
        max_f_eval: f0,
        interpolation_used: options.interpolation,
    };

    let mut n_fev = 0;
    let mut n_gev = 0;

    let dphi0 = grad0.dot(direction);
    if dphi0 >= 0.0 {
        return Err(OptimizeError::ValueError(
            "Search direction is not a descent direction".to_string(),
        ));
    }

    // Hager-Zhang specific parameters
    let _epsilon = 1e-6;
    let _theta = 0.5;
    let _gamma = 0.66;
    let sigma = 0.1;

    let mut alpha = options.alpha_init;
    if let Some(bounds) = bounds {
        alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
    }

    // Initial bracketing phase
    let mut alpha_lo = 0.0;
    let mut alpha_hi = alpha;
    let mut phi_lo = f0;
    let mut dphi_lo = dphi0;

    // Try initial step
    let x_new = x + alpha * direction;
    let phi = fun(&x_new.view());
    n_fev += 1;
    stats.max_f_eval = stats.max_f_eval.max(phi);

    // Hager-Zhang bracketing
    #[allow(clippy::explicit_counter_loop)]
    for i in 0..options.max_ls_iter {
        // Check Armijo condition with Hager-Zhang modification
        if phi <= f0 + options.c1 * alpha * dphi0 {
            // Compute gradient if needed
            if let Some(ref mut grad_fun) = grad_fun {
                let grad_new = grad_fun(&x_new.view());
                n_gev += 1;
                let dphi = grad_new.dot(direction);

                // Check Wolfe condition
                if dphi >= options.c2 * dphi0 {
                    return Ok(LineSearchResult {
                        alpha,
                        f_new: phi,
                        grad_new: Some(grad_new),
                        n_fev,
                        n_gev,
                        success: true,
                        message: format!("Hager-Zhang converged in {} iterations", i + 1),
                        stats,
                    });
                }

                // Update for next iteration
                alpha_lo = alpha;
                phi_lo = phi;
                dphi_lo = dphi;

                // Hager-Zhang expansion rule
                if dphi >= 0.0 {
                    alpha_hi = alpha;
                    break;
                }

                // Expand step using Hager-Zhang rules
                let alpha_new = if i == 0 {
                    // Initial expansion
                    alpha * (1.0 + 4.0 * (phi - f0 - alpha * dphi0) / (alpha * dphi0))
                } else {
                    // Subsequent expansions
                    alpha + (alpha - alpha_lo) * dphi / (dphi_lo - dphi)
                };

                alpha = alpha_new
                    .max(alpha + sigma * (alpha_hi - alpha))
                    .min(alpha_hi);

                if let Some(bounds) = bounds {
                    alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
                }
            } else {
                // No gradient function provided, use simple expansion
                alpha_lo = alpha;
                phi_lo = phi;
                alpha *= 2.0;
                if let Some(bounds) = bounds {
                    alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
                }
            }
        } else {
            // Armijo condition failed, need to reduce step
            alpha_hi = alpha;
            break;
        }

        if alpha >= options.alpha_max {
            let _alpha_max = options.alpha_max; // Cap alpha but break immediately
            break;
        }

        // Evaluate at new point
        let x_new = x + alpha * direction;
        let phi = fun(&x_new.view());
        n_fev += 1;
        stats.max_f_eval = stats.max_f_eval.max(phi);
    }

    stats.n_bracket = 1;

    // Zoom phase using Hager-Zhang interpolation
    for zoom_iter in 0..options.max_ls_iter {
        stats.n_zoom += 1;

        if (alpha_hi - alpha_lo).abs() < options.step_tol {
            break;
        }

        // Hager-Zhang interpolation
        alpha = interpolate_hager_zhang(alpha_lo, alpha_hi, phi_lo, f0, dphi0, dphi_lo, options);

        if let Some(bounds) = bounds {
            alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
        }

        let x_new = x + alpha * direction;
        let phi = fun(&x_new.view());
        n_fev += 1;
        stats.max_f_eval = stats.max_f_eval.max(phi);

        // Check Armijo condition
        if phi <= f0 + options.c1 * alpha * dphi0 {
            if let Some(ref mut grad_fun) = grad_fun {
                let grad_new = grad_fun(&x_new.view());
                n_gev += 1;
                let dphi = grad_new.dot(direction);

                // Check Wolfe condition
                if dphi >= options.c2 * dphi0 {
                    stats.final_width = (alpha_hi - alpha_lo).abs();
                    return Ok(LineSearchResult {
                        alpha,
                        f_new: phi,
                        grad_new: Some(grad_new),
                        n_fev,
                        n_gev,
                        success: true,
                        message: format!(
                            "Hager-Zhang zoom converged in {} iterations",
                            zoom_iter + 1
                        ),
                        stats,
                    });
                }

                // Update interval
                if dphi >= 0.0 {
                    alpha_hi = alpha;
                } else {
                    alpha_lo = alpha;
                    phi_lo = phi;
                    dphi_lo = dphi;
                }
            } else {
                // No gradient, accept point
                return Ok(LineSearchResult {
                    alpha,
                    f_new: phi,
                    grad_new: None,
                    n_fev,
                    n_gev,
                    success: true,
                    message: "Hager-Zhang converged (no gradient)".to_string(),
                    stats,
                });
            }
        } else {
            alpha_hi = alpha;
        }
    }

    // Return best point found
    stats.final_width = (alpha_hi - alpha_lo).abs();
    let x_final = x + alpha_lo * direction;
    let f_final = fun(&x_final.view());
    n_fev += 1;

    Ok(LineSearchResult {
        alpha: alpha_lo,
        f_new: f_final,
        grad_new: None,
        n_fev,
        n_gev,
        success: false,
        message: "Hager-Zhang reached maximum iterations".to_string(),
        stats,
    })
}

/// Interpolation function for Hager-Zhang method
#[allow(dead_code)]
fn interpolate_hager_zhang(
    alpha_lo: f64,
    alpha_hi: f64,
    phi_lo: f64,
    phi0: f64,
    dphi0: f64,
    dphi_lo: f64,
    options: &AdvancedLineSearchOptions,
) -> f64 {
    match options.interpolation {
        InterpolationStrategy::Cubic => {
            // Cubic interpolation using function and derivative values
            let d1 = dphi_lo + dphi0 - 3.0 * (phi0 - phi_lo) / (alpha_lo - 0.0);
            let d2_sign = if d1 * d1 - dphi_lo * dphi0 >= 0.0 {
                1.0
            } else {
                -1.0
            };
            let d2 = d2_sign * (d1 * d1 - dphi_lo * dphi0).abs().sqrt();

            let alpha_c =
                alpha_lo - (alpha_lo - 0.0) * (dphi_lo + d2 - d1) / (dphi_lo - dphi0 + 2.0 * d2);

            // Ensure within bounds
            alpha_c
                .max(alpha_lo + 0.01 * (alpha_hi - alpha_lo))
                .min(alpha_hi - 0.01 * (alpha_hi - alpha_lo))
        }
        InterpolationStrategy::Quadratic => {
            // Quadratic interpolation
            let alpha_q = alpha_lo
                - 0.5 * dphi_lo * (alpha_lo * alpha_lo) / (phi_lo - phi0 - dphi0 * alpha_lo);
            alpha_q
                .max(alpha_lo + 0.01 * (alpha_hi - alpha_lo))
                .min(alpha_hi - 0.01 * (alpha_hi - alpha_lo))
        }
        _ => {
            // Bisection fallback
            0.5 * (alpha_lo + alpha_hi)
        }
    }
}

/// Non-monotone line search for difficult optimization problems
#[allow(dead_code)]
fn non_monotone_line_search<F, G>(
    fun: &mut F,
    mut grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
    nm_state: Option<&mut NonMonotoneState>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    let mut stats = LineSearchStats {
        n_bracket: 0,
        n_zoom: 0,
        final_width: 0.0,
        max_f_eval: f0,
        interpolation_used: options.interpolation,
    };

    let mut n_fev = 0;
    let mut n_gev = 0;

    let dphi0 = grad0.dot(direction);
    if dphi0 >= 0.0 {
        return Err(OptimizeError::ValueError(
            "Search direction is not a descent direction".to_string(),
        ));
    }

    // Get reference value for non-monotone condition
    let f_ref = if let Some(ref nm_state_ref) = nm_state {
        nm_state_ref.get_reference_value()
    } else {
        f0
    };

    let mut alpha = options.alpha_init;
    if let Some(bounds) = bounds {
        alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
    }

    // Non-monotone Armijo search
    #[allow(clippy::explicit_counter_loop)]
    for i in 0..options.max_ls_iter {
        let x_new = x + alpha * direction;
        let phi = fun(&x_new.view());
        n_fev += 1;
        stats.max_f_eval = stats.max_f_eval.max(phi);

        // Non-monotone Armijo condition: f(x + alpha*d) <= max{f_ref} + c1*alpha*g'*d
        if phi <= f_ref + options.c1 * alpha * dphi0 {
            // Check Wolfe condition if gradient function is provided
            if let Some(ref mut grad_fun) = grad_fun {
                let grad_new = grad_fun(&x_new.view());
                n_gev += 1;
                let dphi = grad_new.dot(direction);

                if dphi >= options.c2 * dphi0 {
                    // Update non-monotone _state
                    if let Some(nm_state) = nm_state {
                        nm_state.update(phi);
                    }

                    return Ok(LineSearchResult {
                        alpha,
                        f_new: phi,
                        grad_new: Some(grad_new),
                        n_fev,
                        n_gev,
                        success: true,
                        message: format!("Non-monotone converged in {} iterations", i + 1),
                        stats,
                    });
                }
            } else {
                // No gradient function, accept point
                if let Some(nm_state) = nm_state {
                    nm_state.update(phi);
                }

                return Ok(LineSearchResult {
                    alpha,
                    f_new: phi,
                    grad_new: None,
                    n_fev,
                    n_gev,
                    success: true,
                    message: format!(
                        "Non-monotone converged in {} iterations (no gradient)",
                        i + 1
                    ),
                    stats,
                });
            }
        }

        // Reduce step size
        alpha *= 0.5;

        if alpha < options.alpha_min {
            break;
        }
    }

    Err(OptimizeError::ComputationError(
        "Non-monotone line search failed to find acceptable step".to_string(),
    ))
}

/// Enhanced Strong Wolfe line search with improved interpolation
#[allow(dead_code)]
fn enhanced_strong_wolfe<F, G>(
    fun: &mut F,
    grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    let mut stats = LineSearchStats {
        n_bracket: 0,
        n_zoom: 0,
        final_width: 0.0,
        max_f_eval: f0,
        interpolation_used: options.interpolation,
    };

    let mut n_fev = 0;
    let mut n_gev = 0;

    let dphi0 = grad0.dot(direction);
    if dphi0 >= 0.0 {
        return Err(OptimizeError::ValueError(
            "Search direction is not a descent direction".to_string(),
        ));
    }

    if grad_fun.is_none() {
        return Err(OptimizeError::ValueError(
            "Enhanced Strong Wolfe requires gradient function".to_string(),
        ));
    }

    let grad_fun = grad_fun.expect("Operation failed");

    let mut alpha = options.alpha_init;
    if let Some(bounds) = bounds {
        alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
    }

    let mut alpha_prev = 0.0;
    let mut phi_prev = f0;
    let alpha_max = options.alpha_max;

    // Main search loop
    #[allow(clippy::explicit_counter_loop)]
    for i in 0..options.max_ls_iter {
        let x_new = x + alpha * direction;
        let phi = fun(&x_new.view());
        n_fev += 1;
        stats.max_f_eval = stats.max_f_eval.max(phi);

        // Check Armijo condition
        if phi > f0 + options.c1 * alpha * dphi0 || (phi >= phi_prev && i > 0) {
            // Enter zoom phase
            stats.n_bracket = 1;
            return enhanced_zoom(
                fun, grad_fun, x, direction, alpha_prev, alpha, phi_prev, phi, f0, dphi0, options,
                &mut stats, &mut n_fev, &mut n_gev,
            );
        }

        let grad_new = grad_fun(&x_new.view());
        n_gev += 1;
        let dphi = grad_new.dot(direction);

        // Check Wolfe condition
        if dphi.abs() <= -options.c2 * dphi0 {
            stats.final_width = 0.0;
            return Ok(LineSearchResult {
                alpha,
                f_new: phi,
                grad_new: Some(grad_new),
                n_fev,
                n_gev,
                success: true,
                message: format!("Enhanced Strong Wolfe converged in {} iterations", i + 1),
                stats,
            });
        }

        if dphi >= 0.0 {
            // Enter zoom phase
            stats.n_bracket = 1;
            return enhanced_zoom(
                fun, grad_fun, x, direction, alpha, alpha_prev, phi, phi_prev, f0, dphi0, options,
                &mut stats, &mut n_fev, &mut n_gev,
            );
        }

        // Choose next alpha using sophisticated interpolation
        alpha_prev = alpha;
        phi_prev = phi;

        alpha = match options.interpolation {
            InterpolationStrategy::Cubic => {
                interpolate_cubic(alpha, alpha_max, phi, f0, dphi, dphi0)
            }
            InterpolationStrategy::Quadratic => interpolate_quadratic(alpha, phi, f0, dphi, dphi0),
            _ => 2.0 * alpha,
        };

        alpha = alpha.min(alpha_max);

        if let Some(bounds) = bounds {
            alpha = clip_step(x, direction, alpha, &bounds.lower, &bounds.upper);
        }
    }

    Err(OptimizeError::ComputationError(
        "Enhanced Strong Wolfe failed to converge".to_string(),
    ))
}

/// Enhanced zoom phase with better interpolation
#[allow(dead_code)]
fn enhanced_zoom<F, G>(
    fun: &mut F,
    grad_fun: &mut G,
    x: &ArrayView1<f64>,
    direction: &ArrayView1<f64>,
    mut alpha_lo: f64,
    mut alpha_hi: f64,
    mut phi_lo: f64,
    mut phi_hi: f64,
    phi0: f64,
    dphi0: f64,
    options: &AdvancedLineSearchOptions,
    stats: &mut LineSearchStats,
    n_fev: &mut usize,
    n_gev: &mut usize,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    for zoom_iter in 0..options.max_ls_iter {
        stats.n_zoom += 1;

        if (alpha_hi - alpha_lo).abs() < options.step_tol {
            break;
        }

        // Use sophisticated interpolation
        let alpha = match options.interpolation {
            InterpolationStrategy::Cubic => {
                interpolate_cubic_zoom(alpha_lo, alpha_hi, phi_lo, phi_hi, phi0, dphi0)
            }
            InterpolationStrategy::Quadratic => {
                interpolate_quadratic_zoom(alpha_lo, alpha_hi, phi_lo, phi_hi)
            }
            _ => 0.5 * (alpha_lo + alpha_hi),
        };

        let x_new = x + alpha * direction;
        let phi = fun(&x_new.view());
        *n_fev += 1;
        stats.max_f_eval = stats.max_f_eval.max(phi);

        if phi > phi0 + options.c1 * alpha * dphi0 || phi >= phi_lo {
            alpha_hi = alpha;
            phi_hi = phi;
        } else {
            let grad_new = grad_fun(&x_new.view());
            *n_gev += 1;
            let dphi = grad_new.dot(direction);

            if dphi.abs() <= -options.c2 * dphi0 {
                stats.final_width = (alpha_hi - alpha_lo).abs();
                return Ok(LineSearchResult {
                    alpha,
                    f_new: phi,
                    grad_new: Some(grad_new),
                    n_fev: *n_fev,
                    n_gev: *n_gev,
                    success: true,
                    message: format!("Enhanced zoom converged in {} iterations", zoom_iter + 1),
                    stats: stats.clone(),
                });
            }

            if dphi * (alpha_hi - alpha_lo) >= 0.0 {
                alpha_hi = alpha_lo;
                phi_hi = phi_lo;
            }

            alpha_lo = alpha;
            phi_lo = phi;
        }
    }

    Err(OptimizeError::ComputationError(
        "Enhanced zoom failed to converge".to_string(),
    ))
}

/// More-Thuente line search with safeguarding
#[allow(dead_code)]
fn more_thuente_line_search<F, G>(
    fun: &mut F,
    grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    // More-Thuente is complex to implement fully here
    // For now, use enhanced Strong Wolfe as a sophisticated alternative
    enhanced_strong_wolfe(fun, grad_fun, x, f0, direction, grad0, options, bounds)
}

/// Adaptive line search that adjusts parameters based on problem characteristics
#[allow(dead_code)]
fn adaptive_line_search<F, G>(
    fun: &mut F,
    grad_fun: Option<&mut G>,
    x: &ArrayView1<f64>,
    f0: f64,
    direction: &ArrayView1<f64>,
    grad0: &ArrayView1<f64>,
    options: &AdvancedLineSearchOptions,
    bounds: Option<&Bounds>,
) -> Result<LineSearchResult, OptimizeError>
where
    F: FnMut(&ArrayView1<f64>) -> f64,
    G: FnMut(&ArrayView1<f64>) -> Array1<f64>,
{
    // Adaptive logic: try different methods based on problem characteristics
    let grad_norm = grad0.mapv(|x| x.abs()).sum();
    let _direction_norm = direction.mapv(|x| x.abs()).sum();

    // Choose method based on problem characteristics
    let mut adaptive_options = options.clone();

    if grad_norm > 1e2 {
        // Large gradient: use more conservative approach
        adaptive_options.c1 = 1e-3;
        adaptive_options.c2 = 0.1;
        adaptive_options.method = LineSearchMethod::HagerZhang;
    } else if grad_norm < 1e-3 {
        // Small gradient: use more aggressive approach
        adaptive_options.c1 = 1e-5;
        adaptive_options.c2 = 0.9;
        adaptive_options.method = LineSearchMethod::EnhancedStrongWolfe;
    } else {
        // Medium gradient: use Hager-Zhang
        adaptive_options.method = LineSearchMethod::HagerZhang;
    }

    // Try primary method
    match adaptive_options.method {
        LineSearchMethod::HagerZhang => hager_zhang_line_search(
            fun,
            grad_fun,
            x,
            f0,
            direction,
            grad0,
            &adaptive_options,
            bounds,
        ),
        LineSearchMethod::EnhancedStrongWolfe => enhanced_strong_wolfe(
            fun,
            grad_fun,
            x,
            f0,
            direction,
            grad0,
            &adaptive_options,
            bounds,
        ),
        _ => {
            // Fallback to Hager-Zhang
            hager_zhang_line_search(
                fun,
                grad_fun,
                x,
                f0,
                direction,
                grad0,
                &adaptive_options,
                bounds,
            )
        }
    }
}

// Helper interpolation functions

#[allow(dead_code)]
fn interpolate_cubic(
    alpha: f64,
    alpha_max: f64,
    phi: f64,
    phi0: f64,
    dphi: f64,
    dphi0: f64,
) -> f64 {
    let d1 = dphi + dphi0 - 3.0 * (phi0 - phi) / alpha;
    let d2_term = d1 * d1 - dphi * dphi0;
    if d2_term >= 0.0 {
        let d2 = d2_term.sqrt();
        let alpha_c = alpha * (1.0 - (dphi + d2 - d1) / (dphi - dphi0 + 2.0 * d2));
        alpha_c.max(1.1 * alpha).min(0.9 * alpha_max)
    } else {
        2.0 * alpha
    }
}

#[allow(dead_code)]
fn interpolate_quadratic(alpha: f64, phi: f64, phi0: f64, dphi: f64, dphi0: f64) -> f64 {
    let alpha_q = -dphi0 * alpha * alpha / (2.0 * (phi - phi0 - dphi0 * alpha));
    alpha_q.max(1.1 * alpha)
}

#[allow(dead_code)]
fn interpolate_cubic_zoom(
    alpha_lo: f64,
    alpha_hi: f64,
    phi_lo: f64,
    phi_hi: f64,
    _phi0: f64,
    dphi0: f64,
) -> f64 {
    let d = alpha_hi - alpha_lo;
    let a = (phi_hi - phi_lo - dphi0 * d) / (d * d);
    let b = dphi0;

    if a != 0.0 {
        let discriminant = b * b - 3.0 * a * phi_lo;
        if discriminant >= 0.0 && a > 0.0 {
            let alpha_c = alpha_lo + (-b + discriminant.sqrt()) / (3.0 * a);
            return alpha_c.max(alpha_lo + 0.01 * d).min(alpha_hi - 0.01 * d);
        }
    }

    // Fallback to bisection
    0.5 * (alpha_lo + alpha_hi)
}

#[allow(dead_code)]
fn interpolate_quadratic_zoom(alpha_lo: f64, alpha_hi: f64, phi_lo: f64, phi_hi: f64) -> f64 {
    let d = alpha_hi - alpha_lo;
    let a = (phi_hi - phi_lo) / (d * d);

    if a > 0.0 {
        let alpha_q = alpha_lo + 0.5 * d;
        alpha_q.max(alpha_lo + 0.01 * d).min(alpha_hi - 0.01 * d)
    } else {
        0.5 * (alpha_lo + alpha_hi)
    }
}

/// Create a non-monotone state for algorithms that need it
#[allow(dead_code)]
pub fn create_non_monotone_state(_memory_size: usize) -> NonMonotoneState {
    NonMonotoneState::new(_memory_size)
}

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

    #[test]
    fn test_hager_zhang_line_search() {
        let mut quadratic = |x: &ArrayView1<f64>| -> f64 { x[0] * x[0] + x[1] * x[1] };

        let mut grad =
            |x: &ArrayView1<f64>| -> Array1<f64> { Array1::from_vec(vec![2.0 * x[0], 2.0 * x[1]]) };

        let x = Array1::from_vec(vec![1.0, 1.0]);
        let f0 = quadratic(&x.view());
        let direction = Array1::from_vec(vec![-1.0, -1.0]);
        let grad0 = grad(&x.view());

        let options = AdvancedLineSearchOptions::default();

        let result = hager_zhang_line_search(
            &mut quadratic,
            Some(&mut grad),
            &x.view(),
            f0,
            &direction.view(),
            &grad0.view(),
            &options,
            None,
        )
        .expect("Operation failed");

        assert!(result.success);
        assert!(result.alpha > 0.0);
        assert!(result.f_new < f0);
    }

    #[test]
    fn test_non_monotone_state() {
        let mut nm_state = NonMonotoneState::new(3);

        nm_state.update(10.0);
        assert_abs_diff_eq!(nm_state.get_reference_value(), 10.0, epsilon = 1e-10);

        nm_state.update(5.0);
        assert_abs_diff_eq!(nm_state.get_reference_value(), 10.0, epsilon = 1e-10);

        nm_state.update(15.0);
        assert_abs_diff_eq!(nm_state.get_reference_value(), 15.0, epsilon = 1e-10);

        // Test memory limit
        nm_state.update(8.0);
        nm_state.update(12.0);
        assert_abs_diff_eq!(nm_state.get_reference_value(), 15.0, epsilon = 1e-10);
    }

    #[test]
    fn test_interpolation_methods() {
        let alpha = interpolate_cubic(1.0, 10.0, 5.0, 10.0, -2.0, -5.0);
        assert!(alpha > 1.0);

        let alpha_q = interpolate_quadratic(1.0, 5.0, 10.0, -2.0, -5.0);
        assert!(alpha_q > 1.0);
    }
}