Skip to content

BasinNumerical optimization in Rust

Solve optimization problems with your choice of solver and linear-algebra backend. Run natively or in the browser.

Optimization trajectories on the Rosenbrock functionOptimization trajectories on the Rosenbrock function

A small example ​

Implement CostFunction and Gradient, then hand your problem, a solver, and a starting point to the Executor.

Here's a live example of gradient descent on the Rosenbrock valley. Drag the sliders or click the plot to move the start, and watch the run and the code update together.

To try more problems and solvers, open the visualizer.

Live solver: animates as it scrolls into view.
rosenbrock.rs
use std::convert::Infallible;use basin::{CostFunction, Executor, FirstOrderState, Gradient, GradientDescent}; struct Rosenbrock; impl CostFunction for Rosenbrock {    type Param = Vec<f64>;    type Output = f64;    type Error = Infallible;    fn cost(&self, x: &Vec<f64>) -> Result<f64, Infallible> {        let residual = x[1] - x[0].powi(2);        Ok((1.0 - x[0]).powi(2) + 100.0 * residual.powi(2))    }} impl Gradient for Rosenbrock {    type Gradient = Vec<f64>;    fn gradient(&self, x: &Vec<f64>) -> Result<Vec<f64>, Infallible> {        let residual = x[1] - x[0].powi(2);        Ok(vec![-2.0 * (1.0 - x[0]) - 400.0 * x[0] * residual, 200.0 * residual])    }} fn main() {    let solver = GradientDescent::new(0.001);    let state = FirstOrderState::new(vec![-1.2, 1.0]);    let result = Executor::new(Rosenbrock, solver, state)        .max_iter(500).run().unwrap();     println!("x = {:?} (f = {})", result.param(), result.cost());}
Output
Run output appears here once the solver runs.

Basin v3.6.0