Please check the build logs for more information.

See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.

If you believe this is docs.rs' fault, open an issue.

# argmin

A pure Rust optimization framework

This crate offers a (work in progress) numerical optimization toolbox/framework written entirely in Rust. It is at the moment potentially very buggy. Please use with care and report any bugs you encounter. This crate is looking for contributors!

Documentation of most recent release

## Design goals

This crate's intention is to be useful to users as well as developers of optimization algorithms, meaning that it should be both easy to apply and easy to implement algorithms. In particular, as a developer of optimization algorithms you should not need to worry about usability features (such as logging, dealing with different types, setters and getters for certain common parameters, counting cost function and gradient evaluations, termination, and so on). Instead you can focus on implementing your algorithm.

- Easy framework for the implementation of optimization algorithms: Implement a single iteration of your method and let the framework do the rest. This leads to similar interfaces for different solvers, making it easy for users.
- Pure Rust implementations of a wide range of optimization methods: This avoids the need to compile and interface C/C++/Fortran code.
- Type-agnostic: Many problems require data structures that go beyond simple vectors to represent the parameters. In argmin, everything is generic: All that needs to be done is implementing certain traits on your data type. For common types, these traits are already implemented.
- Convenient: Easy and consistent logging of anything that may be important. Log to the terminal, to a file or implement your own observers. Future plans include sending metrics to databases and connecting to big data piplines.
- Algorithm evaluation: Methods to assess the performance of an algorithm for different parameter settings, problem classes, ...

Since this crate is in a very early stage, so far most points are only partially implemented or remain future plans.

## Algorithms

- Line searches
- Trust region method
- Steepest descent
- Conjugate gradient method
- Nonlinear conjugate gradient method
- Newton methods
- Quasi-Newton methods
- Gauss-Newton method
- Gauss-Newton method with linesearch
- Landweber iteration
- Brent's method
- Nelder-Mead method
- Simulated Annealing
- Particle Swarm Optimization

## Usage

Add this to your `Cargo.toml`

:

```
[]
= "0.2.6"
```

### Optional features (recommended)

There are additional features which can be activated in `Cargo.toml`

:

```
[]
= { = "0.2.6", = ["ctrlc", "ndarrayl"] }
```

These may become default features in the future. Without these features compilation to
`wasm32-unknown-unkown`

seems to be possible.

`ctrlc`

: Uses the`ctrlc`

crate to properly stop the optimization (and return the current best result) after pressing Ctrl+C.`ndarrayl`

: Support for`ndarray`

,`ndarray-linalg`

and`ndarray-rand`

.

### Running the tests

Running the tests requires the `ndarrayl`

feature to be enabled

```
```

## 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 and `Hessian`

is the type of the Hessian.
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`

.

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

in argmin:

```
use ;
use *;
use ;
/// First, create a struct for your problem
/// Implement `ArgminOp` for `Rosenbrock`
```

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 *;
use SteepestDescent;
use MoreThuenteLineSearch;
// Define cost function (must implement `ArgminOperator`)
let cost = Rosenbrock ;
// Define initial parameter vector
let init_param: = vec!;
// Set up line search
let linesearch = new;
// Set up solver
let solver = new;
// Run solver
let res = new
// Add an observer which will log all iterations to the terminal
.add_observer
// Set maximum iterations to 10
.max_iters
// run the solver on the defined problem
.run?;
// print result
println!;
```

## Observing iterations

Argmin offers an interface to observe the state of the iteration 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 implment 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 if the buffer is full.
Parameter vectors can be written to disc 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 `i`

th iteration.

```
let res = new
// Add an observer which will log all iterations to the terminal (without blocking)
.add_observer
// Log to file whenever a new best solution is found
.add_observer
// Write parameter vector to `params/param.arg` every 20th iteration
.add_observer
// run the solver on the defined problem
.run?;
```

## Checkpoints

The probability of crashes increases with runtime, therefore one may want to save checkpoints
in order to be able to resume the optimization after a crash.
The `CheckpointMode`

defines how often checkpoints are saved and is either `Never`

(default),
`Always`

(every iteration) or `Every(u64)`

(every Nth iteration). It is set via the setter
method `checkpoint_mode`

of `Executor`

.
In addition, the directory where the checkpoints and a prefix for every file can be set via
`checkpoint_dir`

and `checkpoint_name`

, respectively.

The following example shows how the `from_checkpoint`

method can be used to resume from a
checkpoint. In case this fails (for instance because the file does not exist, which could mean
that this is the first run and there is nothing to resume from), it will resort to creating a
new `Executor`

, thus starting from scratch.

```
let res = from_checkpoint
.unwrap_or
.max_iters
.checkpoint_dir
.checkpoint_name
.checkpoint_mode
.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 *;
use ;
// 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`.
```

## TODOs

- More optimization methods
- Automatic differentiation
- Parallelization
- Tests
- Evaluation on real problems
- Evaluation framework
- Documentation & Tutorials
- C interface
- Python wrapper
- Solver and problem definition via a config file

Please open an issue if you want to contribute! Any help is appreciated!

## License

Licensed under either of

- Apache License, Version 2.0, (LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0)
- MIT License (LICENSE-MIT or http://opensource.org/licenses/MIT)

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.

License: MIT OR Apache-2.0