### Run COBYLA Example Source: https://github.com/relf/cobyla/blob/main/README.md Execute the paraboloid example to see COBYLA in action. Ensure you have Cargo installed. ```bash cargo run --example paraboloid ``` -------------------------------- ### Minimize Function Example Source: https://context7.com/relf/cobyla/llms.txt Demonstrates using the `minimize` function with the Rosenbrock objective function, variable bounds, and no constraints. Requires `cobyla`, `Func`, `RhoBeg`, and `StopTols` imports. ```rust use cobyla::{minimize, Func, RhoBeg, StopTols}; // Define the objective function to minimize fn rosenbrock(x: &[f64], _data: &mut ()) -> f64 { let a = 1.0; let b = 100.0; (a - x[0]).powi(2) + b * (x[1] - x[0].powi(2)).powi(2) } fn main() { // Initial guess let xinit = vec![0.0, 0.0]; // Variable bounds: -5 <= x[i] <= 5 let bounds = vec![(-5.0, 5.0), (-5.0, 5.0)]; // No constraints for this example let cons: Vec<&dyn Func<()>> = vec![]; // Stopping tolerances let stop_tol = StopTols { ftol_rel: 1e-6, xtol_rel: 1e-6, ..StopTols::default() }; match minimize( rosenbrock, &xinit, &bounds, &cons, (), // user data (unused here) 1000, // max evaluations RhoBeg::All(0.5), // initial step size Some(stop_tol), ) { Ok((status, x_opt, f_opt)) => { println!("Optimization succeeded: {:?}", status); println!("Optimal x: [{:.6}, {:.6}]", x_opt[0], x_opt[1]); println!("Optimal f(x): {:.6}", f_opt); // Expected output: // Optimal x: [1.000000, 1.000000] // Optimal f(x): 0.000000 } Err((status, x, f)) => { println!("Optimization failed: {:?}", status); println!("Last x: {:?}, f(x): {}", x, f); } } } ``` -------------------------------- ### Func Trait with User Data Example Source: https://context7.com/relf/cobyla/llms.txt Illustrates using the `Func` trait with custom user data for objective and constraint functions. The `ProblemData` struct is passed to the objective function. Requires `cobyla`, `minimize`, `Func`, and `RhoBeg` imports. ```rust use cobyla::{minimize, Func, RhoBeg}; // User data structure for passing parameters to functions struct ProblemData { target: f64, weight: f64, } // Objective function using user data fn weighted_distance(x: &[f64], data: &mut ProblemData) -> f64 { data.weight * (x[0] - data.target).powi(2) + (x[1] - data.target).powi(2) } fn main() { let xinit = vec![5.0, 5.0]; let bounds = vec![(-10.0, 10.0), (-10.0, 10.0)]; // User data passed to objective function let user_data = ProblemData { target: 2.0, weight: 3.0, }; // Constraint: x[0] + x[1] >= 3 (rewritten as x[0] + x[1] - 3 >= 0) let constraint = |x: &[f64], _data: &mut ProblemData| x[0] + x[1] - 3.0; let cons: Vec<&dyn Func> = vec![&constraint]; match minimize( weighted_distance, &xinit, &bounds, &cons, user_data, 500, RhoBeg::All(1.0), None, ) { Ok((status, x_opt, f_opt)) => { println!("Status: {:?}", status); println!("x_opt = [{:.4}, {:.4}]", x_opt[0], x_opt[1]); println!("f_opt = {:.4}", f_opt); } Err((e, _, _)) => println!("Error: {:?}", e), } } ``` -------------------------------- ### Configure Initial Step Size with RhoBeg Source: https://context7.com/relf/cobyla/llms.txt Illustrates configuring the initial step size for the simplex using the `RhoBeg` enum. Use `RhoBeg::All` for uniform step sizes across all variables or `RhoBeg::Set` for per-variable step sizes, which is useful for variables with different scales. ```rust use cobyla::{minimize, Func, RhoBeg}; fn scaled_quadratic(x: &[f64], _: &mut ()) -> f64 { // Variables have very different scales 1000.0 * x[0].powi(2) + x[1].powi(2) } fn main() { let xinit = vec![1.0, 100.0]; let bounds = vec![(-10.0, 10.0), (-1000.0, 1000.0)]; let cons: Vec<&dyn Func<()>> = vec![]; // Use different initial step sizes for differently-scaled variables let rhobeg = RhoBeg::Set(vec![0.1, 10.0]); // Alternative: uniform step size // let rhobeg = RhoBeg::All(1.0); match minimize( scaled_quadratic, &xinit, &bounds, &cons, (), 500, rhobeg, None, ) { Ok((_, x_opt, f_opt)) => { println!("x_opt = {:?}", x_opt); println!("f_opt = {:.6}", f_opt); } Err((e, _, _)) => println!("Error: {:?}", e), } } ``` -------------------------------- ### minimize - Main Optimization Function Source: https://context7.com/relf/cobyla/llms.txt The minimize function is the primary entry point for performing constrained optimization. It executes the COBYLA algorithm based on the provided objective function, initial guess, bounds, constraints, and termination criteria. ```APIDOC ## minimize(func, xinit, bounds, cons, data, max_eval, rho_beg, stop_tols) ### Description Performs constrained optimization using the COBYLA algorithm. It returns the optimal parameters and the function value at the optimum, or an error status if the optimization fails. ### Parameters - **func** (Func trait) - Required - The objective function to minimize. - **xinit** (&[f64]) - Required - The initial guess for the variables. - **bounds** (&[(f64, f64)]) - Required - Variable bounds for each dimension. - **cons** (&[dyn Func]) - Required - A list of inequality constraints (must be >= 0). - **data** (U) - Required - User-defined data passed to the objective and constraint functions. - **max_eval** (usize) - Required - Maximum number of function evaluations. - **rho_beg** (RhoBeg) - Required - Initial step size for the algorithm. - **stop_tols** (Option) - Optional - Termination criteria including relative tolerances. ### Response - **Success (Ok)** - Returns a tuple containing (status, x_opt, f_opt). - **Failure (Err)** - Returns a tuple containing (status, x, f) representing the last state. ``` -------------------------------- ### Transpile C to Rust Source: https://github.com/relf/cobyla/blob/main/cobyla/nlopt/README.md Executes the c2rust transpile command using the generated compile_commands.json file. ```bash cd ../cobyla/nlopt c2rust transpile compile_commands.json ``` -------------------------------- ### Generate compile_commands.json with CMake Source: https://github.com/relf/cobyla/blob/main/cobyla/nlopt/README.md Creates a build directory and generates the compile_commands.json file required for c2rust. ```bash mkdir build cd build cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=1 ../cobyla/nlopt cp compile_commands.json ../cobyla/nlopt/compile_commands.json ``` -------------------------------- ### Minimize Function with Status Handling Source: https://context7.com/relf/cobyla/llms.txt Illustrates calling the `minimize` function and matching on the `Result` to handle both success and failure outcomes, printing the status and final parameters. ```Rust use cobyla::{minimize, Func, RhoBeg, StopTols, SuccessStatus, FailStatus}; fn quadratic(x: &[f64], _: &mut ()) -> f64 { x[0].powi(2) + x[1].powi(2) } fn main() { let xinit = vec![5.0, 5.0]; let bounds = vec![(-10.0, 10.0), (-10.0, 10.0)]; let cons: Vec<&dyn Func<()>> = vec![]; let stop_tol = StopTols { ftol_rel: 1e-8, ..StopTols::default() }; let result = minimize( quadratic, &xinit, &bounds, &cons, (), 100, // Limited evaluations to demonstrate MaxEvalReached RhoBeg::All(0.5), Some(stop_tol), ); match result { Ok((status, x, f)) => { match status { SuccessStatus::Success => println!("Converged successfully"), SuccessStatus::FtolReached => println!("Function tolerance reached"), SuccessStatus::XtolReached => println!("Parameter tolerance reached"), SuccessStatus::MaxEvalReached => println!("Max evaluations reached"), SuccessStatus::MaxTimeReached => println!("Max time reached"), SuccessStatus::StopValReached => println!("Stop value reached"), } println!("Final x: {:?}, f(x): {:.6}", x, f); } Err((status, x, f)) => { match status { FailStatus::Failure => println!("Generic failure"), FailStatus::InvalidArgs => println!("Invalid arguments"), FailStatus::OutOfMemory => println!("Out of memory"), FailStatus::RoundoffLimited => println!("Roundoff errors limiting progress"), FailStatus::ForcedStop => println!("Optimization was forcibly stopped"), FailStatus::UnexpectedError => println!("Unexpected error"), } println!("Last x: {:?}, f(x): {}", x, f); } } } ``` -------------------------------- ### Configure Multiple Stopping Criteria with StopTols Source: https://context7.com/relf/cobyla/llms.txt Demonstrates how to configure multiple termination criteria for the COBYLA optimizer using the `StopTols` struct. Conditions are disabled if values are not strictly positive. The algorithm stops when any specified condition is met. ```rust use cobyla::{minimize, Func, RhoBeg, StopTols}; fn sphere(x: &[f64], _: &mut ()) -> f64 { x.iter().map(|xi| xi.powi(2)).sum() } fn main() { let xinit = vec![1.0, 1.0, 1.0]; let bounds = vec![(-10.0, 10.0); 3]; let cons: Vec<&dyn Func<()>> = vec![]; // Configure multiple stopping criteria let stop_tol = StopTols { ftol_rel: 1e-8, // Stop when f changes by < 1e-8 * f ftol_abs: 1e-12, // Stop when f changes by < 1e-12 xtol_rel: 1e-6, // Stop when all x[i] change by < 1e-6 * x[i] xtol_abs: vec![1e-8; 3], // Stop when x[i] changes by < 1e-8 }; match minimize( sphere, &xinit, &bounds, &cons, (), 2000, RhoBeg::All(0.5), Some(stop_tol), ) { Ok((status, x_opt, f_opt)) => { println!("Termination: {:?}", status); println!("x_opt = {:?}", x_opt); println!("f_opt = {:.2e}", f_opt); // Expected: x_opt ≈ [0, 0, 0], f_opt ≈ 0 } Err((e, _, _)) => println!("Error: {:?}", e), } } ``` -------------------------------- ### Handle Inequality Constraints in COBYLA Source: https://context7.com/relf/cobyla/llms.txt Shows how to define and use inequality constraints for the COBYLA optimizer. Constraints are specified as functions that must be non-negative at the solution (c(x) >= 0). Multiple constraints can be combined. ```rust use cobyla::{minimize, Func, RhoBeg, StopTols}; // Minimize f(x) = -x[0] - x[1] (maximize x[0] + x[1]) fn objective(x: &[f64], _: &mut ()) -> f64 { -x[0] - x[1] } fn main() { let xinit = vec![0.5, 0.5]; let bounds = vec![(-2.0, 2.0), (-2.0, 2.0)]; // Constraint 1: x[1] >= x[0]^2 (parabolic boundary) let c1 = |x: &[f64], _: &mut ()| x[1] - x[0].powi(2); // Constraint 2: x[0]^2 + x[1]^2 <= 1 (inside unit circle) // Rewritten as: 1 - x[0]^2 - x[1]^2 >= 0 let c2 = |x: &[f64], _: &mut ()| 1.0 - x[0].powi(2) - x[1].powi(2); let cons: Vec<&dyn Func<()>> = vec![&c1, &c2]; let stop_tol = StopTols { ftol_rel: 1e-6, xtol_rel: 1e-6, ..StopTols::default() }; match minimize( objective, &xinit, &bounds, &cons, (), 500, RhoBeg::All(0.5), Some(stop_tol), ) { Ok((status, x_opt, f_opt)) => { println!("Status: {:?}", status); println!("x_opt = [{:.6}, {:.6}]", x_opt[0], x_opt[1]); println!("f(x) = {:.6}", f_opt); println!("Maximum x[0]+x[1] = {:.6}", -f_opt); // Expected: x ≈ [0.7071, 0.7071], max ≈ 1.4142 } Err((e, _, _)) => println!("Error: {:?}", e), } } ``` -------------------------------- ### Func Trait - Objective and Constraint Functions Source: https://context7.com/relf/cobyla/llms.txt The Func trait defines the interface for objective and constraint functions. Any closure or function with the signature Fn(&[f64], &mut U) -> f64 automatically implements this trait. ```APIDOC ## Func Trait ### Description Interface for defining objective functions and inequality constraints. Constraints are expected to be satisfied when the function returns a value >= 0. ### Signature - **Fn(&[f64], &mut U) -> f64** ### Usage - **x** (&[f64]) - The current variable vector. - **data** (&mut U) - Mutable reference to user-defined data structure. ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.