# pso-rs

An easy-to-use, simple Particle Swarm Optimization (PSO) implementation in Rust.

Crates.io docs.rs GitHub

It uses the rand crate for random initialization, and the rayon crate for parallel objective function computation. It also has a nice progress bar curtesy of the indicatif crate.

The example below can get you started. In order to use it on your own optimization problem, you will need to define an objective function as it is defined in the run function, and a Config object. See the Notes section for more tips.

Examples

```rust use pso_rs::model::*;

// define objective function (Rosenbrock) fn objectivefunction(p: &Particle, _flatdim: usize, _dimensions: &Vec) -> f64 { // x = p[0], y = p[1] (1.0-p[0]).powf(2.0) + 100.0 * ((p[1]-p[0]).powf(2.0)).powf(2.0) }

// define a termination condition fn terminate(fbest: f64) -> bool { fbest - (0.0) < 1e-4 }

let config = Config { // dimension shape of each particle dimensions: vec![2], // problem bounds in each dimension bounds: (-5.0, 10.0), // maximum no. of objective function computations t_max: 10000, // leave the rest of the params as default ..Config::default() };

let pso = psors::run(config, objectivefunction, Some(terminate)).unwrap();

let model = pso.model; println!("Model: {:?} ", model.getfbest()); ```

Notes

Even though you can have particles of any shape and size, as long as each item is f64, pso_rs represents each particle as a flat vector: Vec<f64>.

This means that, for example, in order to find clusters of 20 molecules in 3D space that minimize the Lennard-Jones potential energy, you can define dimensions as (20, 3). If you want, you can also create a custom reshape function, like this one for molecule clusters below:

```rust use pso_rs::model::*;

fn reshape(particle: &Particle, particledims: &Vec) -> Vec> { let mut reshapedcluster = vec![]; let mut i = 0; for _ in 0..particledims[0] { let mut reshapedmolecule = vec![]; for _ in 0..particledims[1] { reshapedmolecule.push(particle[i]); i += 1; } reshapedcluster.push(reshapedmolecule); } reshaped_cluster }

// used in the objective function fn objectivefunction(p: &Particle, _flatdim: usize, dimensions: &Vec) -> f64 { let reshapedparticle = reshape(p, dimensions); /* Do stuff */ 0.0 }

let config = Config { dimensions: vec![20, 3], bounds: (-2.5, 2.5), tmax: 1, ..Config::default() }; let pso = psors::run(config, objective_function, None).unwrap();

// somewhere in main(), after running PSO as in the example: println!( "Best found minimizer: {:#?} ", reshape(&pso.model.getxbest(), &pso.model.config.dimensions) ); ```

License: MIT