RustedSciThe 0.4.8

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
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
use log::info;
use nalgebra::{DMatrix, DVector};

use strum_macros::Display;

///////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////SCALING METHODS///////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////
/// Levenberg: D = I (identity)

/// Marquardt: D[j,j] = ||J[:,j]||₂ (column norms)

/// More: D[j,j] = max(||J[:,j]||₂, D[j,j]) (cumulative max)
///
///  Scaling methods for trust region algorithms (GSL scaling.c)
#[derive(Debug, Clone, PartialEq, Display, Copy)]
pub enum ScalingMethod {
    /// Levenberg scaling: D = I (identity matrix)
    Levenberg,
    /// Marquardt scaling: D[j,j] = ||J[:,j]||_2 (column norms)
    Marquardt,

    More,
}

/// Scaling operations for trust region methods
pub struct TrustRegionScaling;

impl TrustRegionScaling {
    /// Initialize diagonal scaling matrix based on Jacobian and method
    pub fn init_scaling(jacobian: &DMatrix<f64>, method: &ScalingMethod) -> DVector<f64> {
        match method {
            ScalingMethod::Levenberg => Self::init_levenberg_scaling(jacobian),
            ScalingMethod::Marquardt => Self::init_marquardt_scaling(jacobian),
            ScalingMethod::More => Self::init_more_scaling(jacobian),
        }
    }

    /// Update diagonal scaling matrix based on current Jacobian (source: GSL file scaling.c)
    pub fn update_scaling(
        jacobian: &DMatrix<f64>,
        method: &ScalingMethod,
        current_diag: &mut DVector<f64>,
    ) {
        match method {
            ScalingMethod::Levenberg => {
                // Levenberg scaling never changes - always identity
                // No update needed
            }
            ScalingMethod::Marquardt => {
                Self::update_marquardt_scaling(jacobian, current_diag);
            }
            ScalingMethod::More => {
                Self::update_more_scaling(jacobian, current_diag);
            }
        }
    }

    ////////////////////////LEVENBERG//////////////////////////////////////////////////////////////////
    /// Levenberg scaling: D = I (all diagonal elements = 1.0)  (source: GSL file scaling.c)
    fn init_levenberg_scaling(jacobian: &DMatrix<f64>) -> DVector<f64> {
        let n_params = jacobian.ncols();
        DVector::from_element(n_params, 1.0)
    }
    ///////////////////MARQUARDT//////////////////////////////////////////////////////////////////
    /// Marquardt scaling: D[j,j] = ||J[:,j]||_2  (source: GSL file scaling.c)
    fn init_marquardt_scaling(jacobian: &DMatrix<f64>) -> DVector<f64> {
        let n_params = jacobian.ncols();
        let mut diag = DVector::zeros(n_params);
        Self::update_marquardt_scaling(jacobian, &mut diag);
        info!("\n Diagonal scaling vector created!: {}", diag);
        diag
    }
    /// Update Marquardt scaling with current Jacobian (source: GSL file scaling.c)
    fn update_marquardt_scaling(jacobian: &DMatrix<f64>, diag: &mut DVector<f64>) {
        let n_params = jacobian.ncols();

        for j in 0..n_params {
            // Get j-th column of Jacobian
            let column = jacobian.column(j);

            // Compute Euclidean norm of column
            let norm = column.norm();
            //info!("norm: {}, of column: {}", norm, j);
            // Handle degenerate case
            let scaling_value = if norm < 1e-12 { 1.0 } else { norm };

            diag[j] = scaling_value;
        }
    }
    /////////////////////////////////////////////////////MORE//////////////////////////////////////////////////////////////////
    /// More scaling: D[j,j] = max(||J[:,j]||_2, D[j,j])  (source: GSL file scaling.c)
    fn init_more_scaling(jacobian: &DMatrix<f64>) -> DVector<f64> {
        Self::init_marquardt_scaling(jacobian)
    }
    /// Update More scaling with current Jacobian (source: GSL file scaling.c)
    ///   this method described in More Eq. 6.3 p. 111-112
    fn update_more_scaling(jacobian: &DMatrix<f64>, diag: &mut DVector<f64>) {
        let n_params = jacobian.ncols();

        for j in 0..n_params {
            // Get j-th column of Jacobian
            let column = jacobian.column(j);

            // Compute Euclidean norm of column
            let norm = column.norm();
            //info!("norm: {}, of column: {}", norm, j);
            // Handle degenerate case
            let scaling_value = if norm < 1e-12 { 1.0 } else { norm };

            diag[j] = scaling_value.max(diag[j]);
        }
    }

    /////////////////////////////////////REGULARIZATION////////////////////////////////////////////////////////
    /// Create scaled regularization matrix based on method
    pub fn create_scaled_regularization(
        mu: f64,
        diag: &DVector<f64>,
        method: &ScalingMethod,
    ) -> DMatrix<f64> {
        let n = diag.len();
        let mut regularization = DMatrix::zeros(n, n);

        match method {
            ScalingMethod::Levenberg => {
                // Levenberg: μ * I (identity matrix)
                for i in 0..n {
                    regularization[(i, i)] = mu;
                }
            }
            ScalingMethod::Marquardt | ScalingMethod::More => {
                // Marquardt: μ * D^T * D = μ * diag(d_i^2)
                for i in 0..n {
                    regularization[(i, i)] = mu * diag[i] * diag[i];
                }
            }
        }
        regularization
    }
}
/////////////////////END OF SCALING////////////////////////////////////////////////////////////////////////

////////////////////////////////REDUCTION RAIO//////////////////////////////////////////////////////////////
///  Two approaches for reduction ratio:
///Nielsen: Simple formula ||f||² - ||f + J*p||²
///More: GSL formula with ||Jp||²/||f||² + 2μ*||D*p||²/||f||²
#[derive(Debug, Clone, PartialEq, Display, Copy)]
pub enum ReductionRatio {
    Nielsen, // Nielsen, p. 120
    More,    // More, p. 108
}

pub struct ReductionRatioSolver {}
impl ReductionRatioSolver {
    pub fn solve_reduction_ratio(
        Jy: &DMatrix<f64>,
        Fy: &DVector<f64>,
        Fy_new: &DVector<f64>,

        scaling: &DVector<f64>,
        p: &DVector<f64>,
        mu: f64,
        reduction_ratio_method: ReductionRatio,
    ) -> f64 {
        match reduction_ratio_method {
            ReductionRatio::Nielsen => {
                // Compute the reduction ratio using Nielsen's method
                let rr = Self::nielsen_reduction_ratio(Jy, Fy, Fy_new, p);
                rr
            }
            ReductionRatio::More => {
                // Compute the reduction ratio using More's method
                let rr = Self::gsl_reduction_ratio(Jy, Fy, Fy_new, p, scaling, mu);
                rr
            }
        }
    }
    /// Compute the reduction ratio using Nielsen's method (Nielsen, p. 120)
    fn nielsen_reduction_ratio(
        Jy: &DMatrix<f64>,
        Fy: &DVector<f64>,
        Fy_new: &DVector<f64>,
        p: &DVector<f64>,
    ) -> f64 {
        let actual_reduction = Fy.norm_squared() - Fy_new.norm_squared();
        let predicted_residual = Fy + Jy * p;
        // Method-specific predicted reduction calculation
        // Using Nielsen's formula: pred = ||f||² - ||f + J*p||²
        let predicted_reduction = Fy.norm_squared() - predicted_residual.norm_squared(); // ||F||² - ||F + J*p||²;

        let rho = if predicted_reduction.abs() > 1e-12 {
            actual_reduction / predicted_reduction
        } else {
            0.0
        };

        info!(
            "rho = {}, actual_reduction = {}, predicted_reduction = {}",
            rho, actual_reduction, predicted_reduction
        );

        rho
    }
    /// Compute the reduction ratio using More's method (More, p. 108)
    /// This method is implemented in the GSL library
    fn gsl_reduction_ratio(
        Jy: &DMatrix<f64>,
        Fy: &DVector<f64>,
        Fy_new: &DVector<f64>,
        p: &DVector<f64>,

        scaling: &DVector<f64>,
        mu: f64,
    ) -> f64 {
        // Actual reduction
        let norm_f = Fy.norm_squared();
        let norm_f_trial = Fy_new.norm_squared();

        if norm_f_trial >= norm_f {
            info!("Cost increased, rejecting step");
            return -1.0; // reject immediately if cost increased
        }

        // Actual reduction
        let actual_reduction = 1.0 - (norm_f_trial / norm_f).powf(2.0);

        // Predicted reduction (from quadratic model)
        // Uses method-specific calculation from trust region subproblem
        let predicted_reduction = Self::predicted_reduction(Fy, Jy, p, scaling, mu);

        if predicted_reduction > 0.0 {
            let rho = actual_reduction / predicted_reduction;
            info!(
                "rho = {}, actual_reduction = {}, predicted_reduction = {}",
                rho, actual_reduction, predicted_reduction
            );
            return rho;
        } else {
            info!(
                "rho = {}, actual_reduction = {}, predicted_reduction = {}",
                -1.0, actual_reduction, predicted_reduction
            );
            return -1.0; // reject immediately if predicted reduction is negative
        }
    }
    fn predicted_reduction(
        Fy: &DVector<f64>,
        Jy: &DMatrix<f64>,
        p: &DVector<f64>,

        scaling: &DVector<f64>,
        mu: f64,
    ) -> f64 {
        // source More p. 108-109: Moré's formula (Eq 4.4):
        // pred = ||J*p||²/||f||² + 2*mu*||D*p||²/||f||²
        // where p is the velocity component of the step
        let norm_f = Fy.norm();
        let norm_Jp = (Jy * p).norm();
        // Compute scaled norm ||D * velocity||
        let norm_Dp = (scaling.component_mul(p)).norm();

        // Normalize by residual norm
        let u = norm_Jp / norm_f;
        let v = norm_Dp / norm_f;
        // Moré's formula (Eq 4.4)
        let predicted_reduction = u.powf(2.0) + 2.0 * mu * v.powf(2.0);
        predicted_reduction
    }
}

//////////////////////////////CONVERGENCE CRITERIA///////////////////////////////////////////////////////////
/// Convergence test for Levenberg-Marquardt algorithm
/// Based on GSL implementation in convergence.c
///
/// Returns: (converged: bool, info: i32)
/// - converged: true if algorithm has converged
/// - info: convergence type (1=parameter change, 2=gradient, 0=no convergence)
#[derive(Debug, Clone, PartialEq, Display)]
pub enum ConvergenceCriteria {
    GSL,
    SimpleScaled,
}
pub struct ConvergenceCriteriaSolver {}
impl ConvergenceCriteriaSolver {
    pub fn test_convergence(
        x: &DVector<f64>,    // Current parameter vector
        dx: &DVector<f64>,   // Parameter step vector
        g: &DVector<f64>,    // Gradient vector J^T * f
        f: &DVector<f64>,    // Residual vector
        diag: &DVector<f64>, // Diagonal matrix of parameter scaling factors
        xtol: f64,           // Parameter change tolerance
        gtol: Option<f64>,   // Gradient tolerance
        ftol: Option<f64>,   // Function change tolerance (currently unused)
        convergence_criteria: ConvergenceCriteria,
    ) -> (bool, i32) {
        match convergence_criteria {
            ConvergenceCriteria::GSL => test_convergence_gsl(x, dx, g, f, xtol, gtol, ftol),
            ConvergenceCriteria::SimpleScaled => test_convergence_simple_scaled(dx, diag, xtol),
        }
    }
}

/// Simple scaled convergence test
fn test_convergence_simple_scaled(
    dx: &DVector<f64>,
    diag: &DVector<f64>,
    xtol: f64,
) -> (bool, i32) {
    let scaled_norm = scaled_norm_common(diag, dx);
    let converged = scaled_norm < xtol;
    let info = if converged { 1 } else { 0 };
    (converged, info)
}

/// Compute scaled norm: ||D * v||_2
pub fn scaled_norm_common(diag: &DVector<f64>, vector: &DVector<f64>) -> f64 {
    let mut sum_squares = 0.0;

    for i in 0..vector.len() {
        let scaled_component = vector[i] * diag[i];
        sum_squares += scaled_component * scaled_component;
    }

    let scaled_norm = sum_squares.sqrt();
    info!("scaled norm ||step*D|| {}", scaled_norm);
    scaled_norm
}
/////////////////////////////GSL CONVERGENCE CRITERIA///////////////////////////////////////////////////////////
pub fn test_convergence_gsl(
    x: &DVector<f64>,  // Current parameter vector
    dx: &DVector<f64>, // Parameter step vector
    g: &DVector<f64>,  // Gradient vector J^T * f
    f: &DVector<f64>,  // Residual vector
    xtol: f64,         // Parameter change tolerance
    gtol: Option<f64>, // Gradient tolerance
    ftol: Option<f64>, // Function change tolerance (currently unused)
) -> (bool, i32) {
    let gtol = gtol.unwrap_or(1e-6);
    let ftol = ftol.unwrap_or(1e-6);
    info!("Checking convergence conditions:");
    info!("  xtol = {}, gtol = {}, ftol = {}", xtol, gtol, ftol);
    info!(
        "  ||dx|| = {}, ||g|| = {}, ||f|| = {}",
        dx.norm(),
        g.norm(),
        f.norm()
    );

    // ═══════════════════════════════════════════════════════════════════════
    // TEST 1: PARAMETER CHANGE TEST (xtol)
    // Check if parameter changes are negligibly small
    // ═══════════════════════════════════════════════════════════════════════

    if test_parameter_change(dx, x, xtol) {
        info!("CONVERGED: Parameter change test passed");
        info!("  ||dx|| components are all < xtol = {}", xtol);
        return (true, 1);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // TEST 2: GRADIENT TEST (gtol)
    // Check if scaled gradient norm is small (near optimal point)
    // ═══════════════════════════════════════════════════════════════════════

    // Compute scaled infinity norm of gradient
    let gnorm = scaled_infnorm(x, g);

    // Compute current objective function value
    let fnorm = f.norm();
    let phi = 0.5 * fnorm * fnorm; // Current objective: Φ = ½||f||²

    // Gradient convergence threshold
    let gradient_threshold = gtol * phi.max(1.0);

    info!("Gradient test:");
    info!("  gnorm = {}", gnorm);
    info!("  phi = 0.5 * ||f||² = {}", phi);
    info!("  threshold = gtol * max(phi, 1) = {}", gradient_threshold);

    if gnorm <= gradient_threshold {
        info!("CONVERGED: Gradient test passed");
        info!(
            "  Scaled gradient norm {} <= threshold {}",
            gnorm, gradient_threshold
        );
        return (true, 2);
    }

    // ═══════════════════════════════════════════════════════════════════════
    // TEST 3: FUNCTION CHANGE TEST (ftol) - CURRENTLY DISABLED
    // This test is disabled in GSL, but we include the structure for completeness
    // ═══════════════════════════════════════════════════════════════════════

    // Note: In GSL this test is commented out (#if 0)
    // If you want to enable it in the future, you would need to track
    // the previous function norm and compare changes
    let _ftol_unused = ftol; // Suppress unused parameter warning

    // ═══════════════════════════════════════════════════════════════════════
    // NO CONVERGENCE
    // ═══════════════════════════════════════════════════════════════════════

    info!("No convergence detected:");
    info!("  Parameter change test: FAILED");
    info!(
        "  Gradient test: gnorm = {} > threshold = {}",
        gnorm, gradient_threshold
    );
    info!("  Function change test: DISABLED (following GSL)");

    (false, 0)
}
/// Test if parameter changes are small enough for convergence
/// Based on GSL's test_delta function
fn test_parameter_change(dx: &DVector<f64>, x: &DVector<f64>, xtol: f64) -> bool {
    let n = dx.len();
    let xtol_squared = xtol * xtol;

    info!("\n Parameter change test (component-wise):");

    for i in 0..n {
        let dx_i = dx[i];
        let x_i = x[i];

        // Absolute tolerance test
        if dx_i.abs() > xtol {
            info!(
                "  Component {}: |dx| = {} > xtol = {} (FAIL absolute)",
                i,
                dx_i.abs(),
                xtol
            );
            return false;
        }

        // Relative tolerance test
        if dx_i.abs() > xtol_squared * x_i.abs() {
            info!(
                "  Component {}: |dx| = {} > xtol² * |x| = {} (FAIL relative)",
                i,
                dx_i.abs(),
                xtol_squared * x_i.abs()
            );
            return false;
        }

        info!("  Component {}: |dx| = {} (PASS both tests)", i, dx_i.abs());
    }

    info!("All components passed parameter change test");
    true
}

/// Compute scaled infinity norm of gradient
/// Based on GSL's scaled_infnorm function
///
/// Formula: max_i(|g_i| * max(|x_i|, 1))
/// This scaling accounts for the magnitude of parameters
fn scaled_infnorm(x: &DVector<f64>, g: &DVector<f64>) -> f64 {
    let n = x.len();
    let mut max_scaled_grad: f64 = 0.0;

    info!("\n Computing scaled gradient norm:");

    for i in 0..n {
        let x_i = x[i];
        let g_i = g[i];

        // Scale factor: max(|x_i|, 1.0)
        let scale_factor = x_i.abs().max(1.0);

        // Scaled gradient component: |g_i| * scale_factor
        let scaled_grad_i: f64 = g_i.abs() * scale_factor;

        // Track maximum
        max_scaled_grad = max_scaled_grad.max(scaled_grad_i);

        info!(
            "  Component {}: |g| = {}, scale = {}, scaled = {}",
            i,
            g_i.abs(),
            scale_factor,
            scaled_grad_i
        );
    }

    info!("Maximum scaled gradient component: {}", max_scaled_grad);
    max_scaled_grad
}

/// Convergence information codes (matching GSL)
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ConvergenceInfo {
    NoConvergence = 0,
    ParameterChange = 1,
    GradientSmall = 2,
    FunctionChange = 3, // Reserved for future use
}

impl From<i32> for ConvergenceInfo {
    fn from(code: i32) -> Self {
        match code {
            1 => ConvergenceInfo::ParameterChange,
            2 => ConvergenceInfo::GradientSmall,
            3 => ConvergenceInfo::FunctionChange,
            _ => ConvergenceInfo::NoConvergence,
        }
    }
}

impl std::fmt::Display for ConvergenceInfo {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            ConvergenceInfo::NoConvergence => write!(f, "No convergence"),
            ConvergenceInfo::ParameterChange => write!(f, "Converged: parameter change small"),
            ConvergenceInfo::GradientSmall => write!(f, "Converged: gradient small"),
            ConvergenceInfo::FunctionChange => write!(f, "Converged: function change small"),
        }
    }
}

/////
//////////////////////////////////END OF CONVERGENCE CHECKING////////////////////////////////////////////
/// Compute scaled gradient norm for optimality check
#[allow(dead_code)]
fn compute_scaled_gradient_norm(
    jacobian: &DMatrix<f64>,
    residuals: &DVector<f64>,
    residuals_norm: f64,
) -> f64 {
    let mut max_scaled_grad: f64 = 0.0;

    for j in 0..jacobian.ncols() {
        let col = jacobian.column(j);
        let col_norm = col.norm();
        if col_norm > 0.0 && residuals_norm > 0.0 {
            let grad_component = col.dot(residuals).abs();
            let scaled_grad: f64 = grad_component / (col_norm * residuals_norm);
            max_scaled_grad = max_scaled_grad.max(scaled_grad);
        }
    }

    max_scaled_grad
}
/// Compute scaled gradient norm for optimality check for More method
pub fn compute_scaled_gradient_norm2(
    jacobian: &DMatrix<f64>,  // Full Jacobian matrix J
    residuals: &DVector<f64>, // Residual vector r
) -> Option<f64> {
    let residual_norm = residuals.norm();
    if residual_norm == 0.0 {
        return Some(0.0);
    }

    let mut max_scaled_gradient: f64 = 0.0;
    let n = jacobian.ncols();

    // For each column of the Jacobian
    for j in 0..n {
        let jacobian_column = jacobian.column(j);
        let mut column_norm = jacobian_column.norm();

        // Skip zero columns
        if column_norm.abs() < 1e-40 {
            column_norm = 1.0;
        }

        // Compute (J^T * r)_j = dot product of j-th column with residuals
        let gradient_component = jacobian_column.dot(residuals);

        // Scale by column norm and residual norm
        let scaled_gradient = gradient_component.abs() / (column_norm * residual_norm);

        // Check for numerical issues
        if scaled_gradient.is_nan() {
            return None;
        }

        // Track maximum
        max_scaled_gradient = max_scaled_gradient.max(scaled_gradient);
    }

    Some(max_scaled_gradient)
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////TRUST REGION SUBPROBLEM/////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////
/*
#[derive(Debug, Clone, PartialEq)]
pub enum SubproblemMethod {
    Dogleg_simple,
    Dogleg_gsl,
    Direct,
}
impl Display for SubproblemMethod {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SubproblemMethod::Dogleg_simple => write!(f, "Dogleg_simple"),
            SubproblemMethod::Dogleg_gsl => write!(f, "Dogleg_gsl"),
            SubproblemMethod::Direct => write!(f, "Direct"),
        }
    }
}
pub struct TrustRegionSubproblem;
impl TrustRegionSubproblem {
    /// Solve trust region subproblem using specified method
    /// The Levenberg-Marquardt method does NOT use delta directly in solving the subproblem. Bit dogleg methods do.
    pub fn solve(
        jacobian: &DMatrix<f64>,
        residuals: &DVector<f64>,
        gradient: &DVector<f64>,
        scaling: &DVector<f64>,
        mu: f64,
        _delta: f64,
        linear_solver: &str,
        scaling_method: &ScalingMethod,
        method: SubproblemMethod,
    ) -> DVector<f64> {
        match method {
            SubproblemMethod::Direct => Self::direct_method(
                jacobian,
                residuals,
                gradient,
                scaling,
                mu,
                linear_solver,
                scaling_method,
            ),
            SubproblemMethod::Dogleg_simple => {
                unimplemented!()
                // Self::dogleg_simple_method(jacobian, residuals, gradient, scaling, delta, linear_solver, scaling_method)
            }
            SubproblemMethod::Dogleg_gsl => {
                unimplemented!()
                // Self::dogleg_gsl_method(jacobian, residuals, gradient, scaling, delta, linear_solver, scaling_method)
            }
        }
    }
    /// Direct method: Solve regularized normal equations
    /// This is the standard Levenberg-Marquardt approach (source: Nielsen, p. 122)
    ///
    fn direct_method(
        jacobian: &DMatrix<f64>,
        _residuals: &DVector<f64>,
        gradient: &DVector<f64>,
        scaling: &DVector<f64>,
        mu: f64,
        linear_solver: &str,
        scaling_method: &ScalingMethod,
    ) -> DVector<f64> {
        info!("Solving trust region subproblem using Direct method");

        // Compute J^T * J
        let JtJ = jacobian.transpose() * jacobian;

        // Create scaled regularization matrix (method-specific)
        let regularization =
            TrustRegionScaling::create_scaled_regularization(mu, scaling, scaling_method);

        // Form augmented system: A = J^T*J + regularization
        let A = &JtJ + &regularization;

        // Solve: A * p = -gradient
        let p = solve_linear_system(linear_solver.to_string(), &A, gradient)
            .expect("Failed to solve linear system in direct method");

        info!("Direct method step norm: {}", p.norm());
        p
    }
    /// Simple dogleg method: Combines Gauss-Newton and steepest descent directions
    #[allow(dead_code)]
    fn dogleg_simple_method(
        jacobian: &DMatrix<f64>,
        _residuals: &DVector<f64>,
        gradient: &DVector<f64>,
        scaling: &DVector<f64>,
        delta: f64,
        linear_solver: &str,
        scaling_method: &ScalingMethod,
    ) -> DVector<f64> {
        info!("Solving trust region subproblem using Simple Dogleg method");

        // 1. Compute Gauss-Newton step (unregularized)
        let JtJ = jacobian.transpose() * jacobian;
        let p_gn =
            solve_linear_system(linear_solver.to_string(), &JtJ, gradient).unwrap_or_else(|_| {
                // Fallback to regularized system if singular
                let regularization =
                    TrustRegionScaling::create_scaled_regularization(1e-6, scaling, scaling_method);
                let A_reg = &JtJ + &regularization;
                solve_linear_system(linear_solver.to_string(), &A_reg, gradient)
                    .expect("Failed to solve regularized system")
            });

        // 2. Check if Gauss-Newton step is within trust region
        let scaled_gn_norm = scaled_norm_common(scaling, &p_gn);

        if scaled_gn_norm <= delta {
            info!("Gauss-Newton step accepted, norm: {}", scaled_gn_norm);
            return p_gn;
        }

        // 3. Compute steepest descent step
        let grad_norm_sq = gradient.norm_squared();
        let Jg = jacobian * gradient;
        let alpha = grad_norm_sq / Jg.norm_squared();
        let p_sd = -alpha * gradient;

        // 4. Find dogleg path intersection with trust region boundary
        let scaled_sd_norm = scaled_norm_common(scaling, &p_sd);

        if scaled_sd_norm >= delta {
            // Use scaled steepest descent to boundary
            let tau = delta / scaled_sd_norm;
            info!("Using steepest descent step with tau: {}", tau);
            return tau * p_sd;
        }

        // 5. Find intersection of dogleg path with trust region
        // Solve: ||D * (p_sd + t * (p_gn - p_sd))||^2 = delta^2
        let diff = &p_gn - &p_sd;
        let scaled_diff = scaling.component_mul(&diff);
        let scaled_sd = scaling.component_mul(&p_sd);

        let a = scaled_diff.norm_squared();
        let b = 2.0 * scaled_sd.dot(&scaled_diff);
        let c = scaled_sd.norm_squared() - delta * delta;

        let discriminant = b * b - 4.0 * a * c;
        let t = if discriminant >= 0.0 {
            (-b + discriminant.sqrt()) / (2.0 * a)
        } else {
            1.0 // Fallback
        };

        let t = t.clamp(0.0, 1.0);
        let p_dogleg = &p_sd + t * diff;

        info!(
            "Dogleg step with t: {}, norm: {}",
            t,
            scaled_norm_common(scaling, &p_dogleg)
        );
        p_dogleg
    }
}
/////////////////////////END OF TRUST REGION SUBPROBLEM SOLVERS////////////////////////////////////////////////
*/