1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
pub mod job_config;
mod swarm;

pub use swarm::swarm_config;

use job_config::{Bounds, JobConfig, StopCondition};
use std::thread;
use swarm::{GlobalRecord, Swarm};
use swarm_config::SwarmConfig;

/// Particle Swarm Optimizer
#[derive(Clone, Debug)]
pub struct PSO {
    num_swarms: usize,
    swarm_configs: Vec<SwarmConfig>,
    verbose: bool,
    console_update: Option<usize>,
}

impl PSO {
    /// Generate a PSO from a list of Swarm Configuartions
    pub fn from_swarm_configs(verbose: bool, swarm_configs: Vec<SwarmConfig>) -> Self {
        let num_swarms = swarm_configs.len();

        assert_ne!(num_swarms, 0, "At least One SwarmConfig must be provided!");

        if verbose {
            initialization_message(num_swarms);

            println!("\nSwarm Configurations: ");
            for (swarm_index, sc) in swarm_configs.iter().enumerate() {
                println!("Swarm");
                cyan_ln!("{}:", swarm_index);
                green_ln!("{}", sc);
            }
        }

        Self {
            num_swarms,
            swarm_configs,
            verbose,
            console_update: None,
        }
    }

    /// Generate a PSO with `num_swarms` swarms with a the given Swarm Configuration
    pub fn from_swarm_config(num_swarms: usize, verbose: bool, swarm_config: &SwarmConfig) -> Self {
        assert_ne!(0, num_swarms, "The PSO must have at least one Swarm!");

        let swarm_configs = (0..num_swarms).map(|_| swarm_config.clone()).collect();
        if verbose {
            initialization_message(num_swarms);

            println!("\nSwarm Configuration: ");
            green_ln!("{}", swarm_config);
        }

        Self {
            num_swarms,
            swarm_configs,
            verbose,
            console_update: None,
        }
    }

    /// Generate a PSO with `num_swarms` swarms with the default Swarm Configuration
    pub fn default(num_swarms: usize, verbose: bool) -> Self {
        let swarm_config = SwarmConfig::new();

        Self::from_swarm_config(num_swarms, verbose, &swarm_config)
    }

    /// Set the PSO to update the console with progress every `console_update_rate` iterations
    pub fn show_progress(&mut self, console_update_rate: usize) {
        self.console_update = Some(console_update_rate)
    }

    /// Run an optimization with the given Job Configuration and Objective Funciton
    ///
    /// Returns a tuple with the minimum cost and corresponding location in the search space
    /// The Objective Function is cloned for each swarm
    pub fn run_job<F>(&self, job_config: JobConfig, objective_function: F) -> (f64, Vec<f64>)
    where
        F: Fn(&[f64]) -> f64 + Clone + Sync + Send + 'static,
    {
        println!("\n Starting Optimization Job with: ");
        dark_cyan_ln!("{}", job_config);

        let global_record = GlobalRecord::new(job_config.num_variables);

        let swarm_threads: Vec<std::thread::JoinHandle<()>> = self
            .swarm_configs
            .iter()
            .enumerate()
            .map(|(i, swarm_config)| {
                let ob = objective_function.clone();
                let jc = job_config.clone();
                let sc = swarm_config.clone();
                let mut gr = global_record.clone();

                thread::Builder::new()
                    .name(format!("swarm_thread_{}", i))
                    .spawn(move || {
                        let mut swarm = Swarm::new(format!("swarm_{}", i), sc);
                        swarm.minimize(ob, jc, &mut gr)
                    })
                    .unwrap()
            })
            .collect();

        for st in swarm_threads {
            st.join().expect("Thread panicked during operation!");
        }

        global_record
            .to_tuple()
            .expect("Should not block, Main thread is the only owner here.")
    }
}

fn initialization_message(num_swarms: usize) {
    if num_swarms == 1 {
        print!("PSO Initialized with ");
        yellow!("1");
        println!(" Swarm!");
    } else {
        print!("PSO Initialized with ");
        yellow!("{}", num_swarms);
        println!(" Swarms!");
    }
}