GithubHelp home page GithubHelp logo

schaudge / argmin Goto Github PK

View Code? Open in Web Editor NEW

This project forked from argmin-rs/argmin

0.0 1.0 0.0 26.48 MB

Mathematical optimization in pure Rust

Home Page: http://argmin-rs.org

License: Apache License 2.0

Rust 100.00%

argmin's Introduction

argmin

argmin CI argmin on deps.rs argmin on crates.io argmin on docs.rs Source Code Repository Maintenance License: MIT OR Apache-2.0 Gitter chat

argmin is a numerical optimization library written entirely in Rust.

Documentation of most recent release

Documentation of main branch

This is the README for the current development version. For the README of the most recent release please visit crates.io!

Design goals

argmin aims at offering a wide range of optimization algorithms with a consistent interface, written purely in Rust. It comes with additional features such as checkpointing and observers which for instance make it possible to log the progress of an optimization to screen or file.

It further provides a framework for implementing iterative optimization algorithms in a convenient manner. Essentially, a single iteration of the algorithm needs to be implemented and everything else, such as handling termination, parameter vectors, gradients and Hessians, is taken care of by the library.

This library uses generics to be as type-agnostic as possible. Abstractions over common math functions enable the use of common backends such as ndarray and nalgebra via the argmin-math crate. All operations can be performed with 32 and 64 bit floats. Custom types are of course also supported.

Contributing

This crate is looking for contributors! Potential projects can be found in the Github issues, but feel free to suggest your own ideas as well. Besides adding optimization methods and new features, other contributions are also highly welcome, for instance improving performance, documentation, writing examples (with real world problems), developing tests, adding observers, implementing a C interface or Python wrappers. Bug reports (and fixes) are of course also highly appreciated.

Algorithms

Examples

Examples for each solver can be found here (current released version) and here (main branch).

Usage

Add this to your Cargo.toml:

[dependencies]
argmin = "0.5.0"
argmin-math = { version = "0.1.0", features = ["ndarray_latest-serde,nalgebra_latest-serde"] }

or, for the current development version:

[dependencies]
argmin = { git = "https://github.com/argmin-rs/argmin" }
argmin-math = { git = "https://github.com/argmin-rs/argmin", features = ["ndarray_latest-serde,nalgebra_latest-serde"] }

(For which features to select for argmin-math please see the documentation.)

Features

Default features

  • slog-logger: Support for logging using slog
  • serde1: Support for serde. Needed for checkpointing and writing parameters to disk as well as logging to disk.

Optional features

The ctrlc feature uses the ctrlc crate to properly stop the optimization (and return the current best result) after pressing Ctrl+C during an optimization run.

[dependencies]
argmin = { version = "0.5.0", features = ["ctrlc"] }

Experimental support for compiling to WebAssembly

When compiling to WASM, the feature wasm-bindgen must be used.

WASM support is still experimental. Please report any issues you encounter when using argmin in a WASM context.

Compiling without serde dependency

The serde dependency can be removed by turning off the serde1 feature, for instance like so:

[dependencies]
argmin = { version = "0.5.0", default-features = false, features = ["slog-logger"] }

Note that this will remove the ability to write parameters and logs to disk as well as checkpointing.

Running the tests and building the examples

The tests and examples require a set of features to be enabled:

cargo test --features "argmin/ctrlc,argmin-math/ndarray_latest-serde,argmin-math/nalgebra_latest-serde,argmin/ndarrayl"

Defining a problem

A problem can be defined by implementing the ArgminOp trait which comes with the associated types Param, Output and Hessian. Param is the type of your parameter vector (i.e. the input to your cost function), Output is the type returned by the cost function, Hessian is the type of the Hessian and Jacobian is the type of the Jacobian. The trait provides the following methods:

  • apply(&self, p: &Self::Param) -> Result<Self::Output, Error>: Applys the cost function to parameters p of type Self::Param and returns the cost function value.
  • gradient(&self, p: &Self::Param) -> Result<Self::Param, Error>: Computes the gradient at p.
  • hessian(&self, p: &Self::Param) -> Result<Self::Hessian, Error>: Computes the Hessian at p.
  • jacobian(&self, p: &Self::Param) -> Result<Self::Jacobian, Error>: Computes the Jacobian at p.

The following code snippet shows an example of how to use the Rosenbrock test functions from argmin-testfunctions in argmin:

use argmin_testfunctions::{rosenbrock_2d, rosenbrock_2d_derivative, rosenbrock_2d_hessian};
use argmin::core::{ArgminOp, Error};

/// First, create a struct for your problem
struct Rosenbrock {
    a: f64,
    b: f64,
}

/// Implement `ArgminOp` for `Rosenbrock`
impl ArgminOp for Rosenbrock {
    /// Type of the parameter vector
    type Param = Vec<f64>;
    /// Type of the return value computed by the cost function
    type Output = f64;
    /// Type of the Hessian. Can be `()` if not needed.
    type Hessian = Vec<Vec<f64>>;
    /// Type of the Jacobian. Can be `()` if not needed.
    type Jacobian = ();
    /// Floating point precision
    type Float = f64;

    /// Apply the cost function to a parameter `p`
    fn apply(&self, p: &Self::Param) -> Result<Self::Output, Error> {
        Ok(rosenbrock_2d(p, self.a, self.b))
    }

    /// Compute the gradient at parameter `p`.
    fn gradient(&self, p: &Self::Param) -> Result<Self::Param, Error> {
        Ok(rosenbrock_2d_derivative(p, self.a, self.b))
    }

    /// Compute the Hessian at parameter `p`.
    fn hessian(&self, p: &Self::Param) -> Result<Self::Hessian, Error> {
        let t = rosenbrock_2d_hessian(p, self.a, self.b);
        Ok(vec![vec![t[0], t[1]], vec![t[2], t[3]]])
    }
}

It is optional to implement any of these methods, as there are default implementations which will return an Err when called. What needs to be implemented is defined by the requirements of the solver that is to be used.

Running a solver

The following example shows how to use the previously shown definition of a problem in a Steepest Descent (Gradient Descent) solver.

use argmin::core::{ArgminOp, Error, Executor};
use argmin::core::{ArgminSlogLogger, ObserverMode};
use argmin::solver::gradientdescent::SteepestDescent;
use argmin::solver::linesearch::MoreThuenteLineSearch;

// Define cost function (must implement `ArgminOperator`)
let cost = Rosenbrock { a: 1.0, b: 100.0 };
 
// Define initial parameter vector
let init_param: Vec<f64> = vec![-1.2, 1.0];
 
// Set up line search
let linesearch = MoreThuenteLineSearch::new();
 
// Set up solver
let solver = SteepestDescent::new(linesearch);
 
// Run solver
let res = Executor::new(cost, solver, init_param)
    // Add an observer which will log all iterations to the terminal
    .add_observer(ArgminSlogLogger::term(), ObserverMode::Always)
    // Set maximum iterations to 10
    .max_iters(10)
    // run the solver on the defined problem
    .run()?;
// print result
println!("{}", res);

Observing iterations

Argmin offers an interface to observe the state of the solver at initialization as well as after every iteration. This includes the parameter vector, gradient, Hessian, iteration number, cost values and many more as well as solver-specific metrics. This interface can be used to implement loggers, send the information to a storage or to plot metrics. Observers need to implement the Observe trait. Argmin ships with a logger based on the slog crate. ArgminSlogLogger::term logs to the terminal and ArgminSlogLogger::file logs to a file in JSON format. Both loggers also come with a *_noblock version which does not block the execution of logging, but may drop some messages in case of a full buffer. Parameter vectors can be written to disk using WriteToFile. For each observer it can be defined how often it will observe the progress of the solver. This is indicated via the enum ObserverMode which can be either Always, Never, NewBest (whenever a new best solution is found) or Every(i) which means every ith iteration.

let res = Executor::new(problem, solver, init_param)
let res = res
    // Add an observer which will log all iterations to the terminal (without blocking)
    .add_observer(ArgminSlogLogger::term_noblock(), ObserverMode::Always)
    // Log to file whenever a new best solution is found
    .add_observer(ArgminSlogLogger::file("solver.log", false)?, ObserverMode::NewBest)
    // Write parameter vector to `params/param.arg` every 20th iteration
    .add_observer(WriteToFile::new("params", "param"), ObserverMode::Every(20))
    // run the solver on the defined problem
    .run()?;

Checkpoints

Checkpointing is a useful mechanism for mitigating the effects of crashes when software is run in unstable environment, particularly for long run times. Checkpoints are saved regularly with a definable frequency. Optimizations can then be resumed from a given checkpoint after a crash.

A FileCheckpoint is provided, which saves checkpoints to disk. Via the Checkpoint trait other checkpointing mechanisms can be implemented.

The CheckpointingFrequency defines how often checkpoints are saved and is either Always (every iteration), Every(u64) (every Nth iteration) or Never.

The following example shows how the checkpointing method is used to activate checkpointing. If no checkpoint is available on disk, an optimization will be started from scratch. If the run crashes and a checkpoint is found on disk, then it will resume from the checkpoint.

let res = Executor::from_checkpoint(".checkpoints/optim.arg", Rosenbrock {})
    .unwrap_or(Executor::new(Rosenbrock {}, solver, init_param))
    .max_iters(iters)
    .checkpoint_dir(".checkpoints")
    .checkpoint_name("optim")
    .checkpoint_mode(CheckpointMode::Every(20))
    .run()?;

Implementing an optimization algorithm

In this section we are going to implement the Landweber solver, which essentially is a special form of gradient descent. In iteration k, the new parameter vector x_{k+1} is calculated from the previous parameter vector x_k and the gradient at x_k according to the following update rule:

x_{k+1} = x_k - omega * \nabla f(x_k)

In order to implement this using the argmin framework, one first needs to define a struct which holds data specific to the solver. Then, the Solver trait needs to be implemented for the struct. This requires setting the associated constant NAME which gives your solver a name. The next_iter method defines the computations performed in a single iteration of the solver. Via the parameters op and state one has access to the operator (cost function, gradient computation, Hessian, …) and to the current state of the optimization (parameter vectors, cost function values, iteration number, …), respectively.

use argmin::core::{ArgminFloat, ArgminIterData, ArgminOp, Error, IterState, OpWrapper, Solver};
#[cfg(feature = "serde1")]
use serde::{Deserialize, Serialize};
use argmin_math::ArgminScaledSub;

// Define a struct which holds any parameters/data which are needed during the execution of the
// solver. Note that this does not include parameter vectors, gradients, Hessians, cost
// function values and so on, as those will be handled by the `Executor`.
#[cfg_attr(feature = "serde1", derive(Serialize, Deserialize))]
pub struct Landweber<F> {
    /// omega
    omega: F,
}

impl<F> Landweber<F> {
    /// Constructor
    pub fn new(omega: F) -> Self {
        Landweber { omega }
    }
}

impl<O, F> Solver<O> for Landweber<F>
where
    // `O` always needs to implement `ArgminOp`
    O: ArgminOp<Float = F>,
    // `O::Param` needs to implement `ArgminScaledSub` because of the update formula
    O::Param: ArgminScaledSub<O::Param, O::Float, O::Param>,
    F: ArgminFloat,
{
    // This gives the solver a name which will be used for logging
    const NAME: &'static str = "Landweber";

    // Defines the computations performed in a single iteration.
    fn next_iter(
        &mut self,
        // This gives access to the operator supplied to the `Executor`. `O` implements
        // `ArgminOp` and `OpWrapper` takes care of counting the calls to the respective
        // functions.
        op: &mut OpWrapper<O>,
        // Current state of the optimization. This gives access to the parameter vector,
        // gradient, Hessian and cost function value of the current, previous and best
        // iteration as well as current iteration number, and many more.
        state: &IterState<O>,
    ) -> Result<ArgminIterData<O>, Error> {
        // First we obtain the current parameter vector from the `state` struct (`x_k`).
        let xk = state.get_param();
        // Then we compute the gradient at `x_k` (`\nabla f(x_k)`)
        let grad = op.gradient(&xk)?;
        // Now subtract `\nabla f(x_k)` scaled by `omega` from `x_k` to compute `x_{k+1}`
        let xkp1 = xk.scaled_sub(&self.omega, &grad);
        // Return new paramter vector which will then be used by the `Executor` to update
        // `state`.
        Ok(ArgminIterData::new().param(xkp1))
    }
}

License

Licensed under either of

at your option.

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

argmin's People

Contributors

armavica avatar cattleprodigy avatar cfunky avatar dariogoetz avatar dependabot-preview[bot] avatar dependabot[bot] avatar glitchy-tozier avatar mattburn avatar nilgoyette avatar optozorax avatar regexident avatar rth avatar sdd avatar stefan-k avatar thatgeoguy avatar theironborn avatar vadixidav avatar w1th0utnam3 avatar wilkensteiner avatar xemwebe avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.