lbfgsbrs 0.1.2

Rust port of L-BFGS-B-C
Documentation
use lbfgsbrs::lbfgsb::{LbfgsbMinimizer, LbfgsbParameters};
use env_logger;
use log::info;

fn main() {
    env_logger::init();

    info!("Solving sample problem (Rosenbrock test fcn).");
    info!("      (f = 0.0 at the optimal solution.)\n\0");

    // Problem dimensions
    let n = 25;
    
    // Initialize the solution vector
    let mut x: Vec<f64> = vec![3.0; n];
    
    // Define the objective function (Rosenbrock function)
    let f = |x: &Vec<f64>| -> f64 {
        let mut f = 0.25 * (x[0] - 1.0).powi(2);
        
        for i in 1..n {
            let t = x[i] - x[i-1].powi(2);
            f += t.powi(2);
        }
        
        f * 4.0
    };
    
    // Define the gradient function
    let g = |x: &Vec<f64>| -> Vec<f64> {
        let mut grad = vec![0.0; n];
        
        let mut t1 = x[1] - x[0].powi(2);
        grad[0] = 2.0 * (x[0] - 1.0) - 16.0 * x[0] * t1;
        
        for i in 1..n-1 {
            let t2 = t1;
            t1 = x[i+1] - x[i].powi(2);
            grad[i] = 8.0 * t2 - 16.0 * x[i] * t1;
        }
        
        grad[n-1] = 8.0 * t1;
        
        grad
    };
    
    // Create parameters for the optimizer
    let params = LbfgsbParameters {
        m: 5,
        factr: 1e7,
        pgtol: 1e-5,
        time_limit: 0.2,
        max_iter: 1000,
    };
    
    // Create the optimizer
    let mut optimizer = LbfgsbMinimizer::new(&mut x, &f, &g, Some(params));
    
    // Set bounds for even indices
    for i in (0..n).step_by(2) {
        optimizer.set_lower_bound(i, 1.0);
        optimizer.set_upper_bound(i, 100.0);
    }
    
    // Set bounds for odd indices
    for i in (1..n).step_by(2) {
        optimizer.set_lower_bound(i, -100.0);
        optimizer.set_upper_bound(i, 100.0);
    }
    
    // Run the optimization
    match optimizer.minimize() {
        Ok(_) => {
            log::trace!("Optimization successful");
        },
        Err(e) => {
            log::warn!("Error during optimization: {:?}", e);
        },
    }
    
    // Get the optimized solution
    let solution = optimizer.get_x();
    
    // Print the solution
    info!("Optimization complete.");
    info!("Solution: {:?}", solution);
    info!("Objective value: {}", f(&solution));
}