Skip to content

Commit

Permalink
Merge pull request #112 from mahf-opt/rework_pso
Browse files Browse the repository at this point in the history
Rework pso
  • Loading branch information
luleyleo authored Oct 20, 2022
2 parents 849dcbd + 985dd04 commit 6ef3bc6
Show file tree
Hide file tree
Showing 37 changed files with 582 additions and 574 deletions.
6 changes: 3 additions & 3 deletions examples/bmf.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ fn main() -> anyhow::Result<()> {
let config = pso::real_pso(
pso::RealProblemParameters {
num_particles: 100,
a: 1.0,
b: 1.0,
c: 1.0,
weight: 1.0,
c_one: 1.0,
c_two: 1.0,
v_max: 1.0,
},
termination::FixedIterations::new(500),
Expand Down
6 changes: 2 additions & 4 deletions src/framework/components.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
//! The Component trait and structural components.
use crate::{
framework::{
conditions::Condition,
state::{common, State},
},
framework::conditions::Condition,
problems::Problem,
state::{common, State},
};
use serde::Serialize;
use std::any::Any;
Expand Down
5 changes: 1 addition & 4 deletions src/framework/conditions.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,5 @@
/// The Condition trait and combinators.
use crate::{
framework::{components::AnyComponent, state::State},
problems::Problem,
};
use crate::{framework::components::AnyComponent, problems::Problem, state::State};
use serde::Serialize;

/// A condition for loops or branches.
Expand Down
2 changes: 1 addition & 1 deletion src/framework/configuration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,10 @@ use crate::{
framework::{
components::{Block, Branch, Component, Loop, Scope},
conditions::Condition,
state,
},
operators,
problems::{MultiObjectiveProblem, Problem, SingleObjectiveProblem},
state,
};

/// A heuristic, constructed from a set of components.
Expand Down
2 changes: 1 addition & 1 deletion src/framework/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@

pub mod components;
pub mod conditions;
pub mod state;

mod configuration;
pub use configuration::{Configuration, ConfigurationBuilder};
Expand All @@ -17,6 +16,7 @@ mod random;
pub use random::{Random, RandomConfig};

use crate::problems::Problem;
use crate::state;
use crate::tracking::Log;

/// Runs the heuristic on the given problem.
Expand Down
2 changes: 1 addition & 1 deletion src/framework/random.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ use rand::{RngCore, SeedableRng};
use serde::Serialize;
use std::any::type_name;

use crate::framework::state::CustomState;
use crate::state::CustomState;

/// A random number generator.
///
Expand Down
8 changes: 4 additions & 4 deletions src/heuristics/aco.rs
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,13 @@ pub fn aco<P: SingleObjectiveProblem>(
}

mod ant_ops {
use rand::distributions::{Distribution, WeightedIndex};

use crate::state::PheromoneMatrix;
use crate::{
framework::{components::*, state::State, Individual, Random, SingleObjective},
operators::custom_state::PheromoneMatrix,
framework::{components::*, Individual, Random, SingleObjective},
problems::tsp::SymmetricTsp,
state::State,
};
use rand::distributions::{Distribution, WeightedIndex};

#[derive(serde::Serialize)]
pub struct AcoGeneration {
Expand Down
126 changes: 10 additions & 116 deletions src/heuristics/pso.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,14 +4,15 @@ use crate::{
framework::{components::Component, conditions::Condition, Configuration},
operators::*,
problems::{LimitedVectorProblem, SingleObjectiveProblem},
state,
};

/// Parameters for [real_pso].
pub struct RealProblemParameters {
pub num_particles: u32,
pub a: f64,
pub b: f64,
pub c: f64,
pub weight: f64,
pub c_one: f64,
pub c_two: f64,
pub v_max: f64,
}

Expand All @@ -27,9 +28,9 @@ where
{
let RealProblemParameters {
num_particles,
a,
b,
c,
weight,
c_one,
c_two,
v_max,
} = params;

Expand All @@ -39,9 +40,9 @@ where
.update_best_individual()
.do_(pso(
Parameters {
particle_init: pso_ops::PsoStateInitialization::new(v_max),
particle_update: generation::swarm::PsoGeneration::new(a, b, c, v_max),
state_update: pso_ops::PsoStateUpdate::new(),
particle_init: state::PsoState::intializer(v_max),
particle_update: generation::swarm::PsoGeneration::new(weight, c_one, c_two, v_max),
state_update: state::PsoState::updater(),
},
termination,
logger,
Expand Down Expand Up @@ -83,110 +84,3 @@ where
})
.build_component()
}

#[allow(clippy::new_ret_no_self)]
pub mod pso_ops {
use crate::problems::SingleObjectiveProblem;
use crate::{
framework::{components::*, state::State, Individual},
operators::custom_state::PsoState,
problems::{LimitedVectorProblem, Problem},
};
use rand::Rng;

#[derive(Debug, serde::Serialize)]
pub struct PsoStateInitialization {
v_max: f64,
}
impl PsoStateInitialization {
pub fn new<P: Problem>(v_max: f64) -> Box<dyn Component<P>>
where
P: SingleObjectiveProblem<Encoding = Vec<f64>> + LimitedVectorProblem<T = f64>,
{
Box::new(Self { v_max })
}
}
impl<P> Component<P> for PsoStateInitialization
where
P: SingleObjectiveProblem<Encoding = Vec<f64>> + LimitedVectorProblem<T = f64>,
{
fn initialize(&self, _problem: &P, state: &mut State) {
// Initialize with empty state to satisfy `state.require()` statements
state.insert(PsoState {
velocities: vec![],
bests: vec![],
global_best: Individual::<P>::new_unevaluated(Vec::new()),
})
}

fn execute(&self, problem: &P, state: &mut State) {
let population = state.population_stack_mut::<P>().pop();
let rng = state.random_mut();

let velocities = population
.iter()
.map(|_| {
(0..problem.dimension())
.into_iter()
.map(|_| rng.gen_range(-self.v_max..=self.v_max))
.collect::<Vec<f64>>()
})
.collect::<Vec<Vec<f64>>>();

let bests = population.to_vec();

let global_best = bests
.iter()
.min_by_key(|i| Individual::objective(i))
.cloned()
.unwrap();

state.population_stack_mut().push(population);

state.insert(PsoState {
velocities,
bests,
global_best,
});
}
}

/// State update for PSO.
///
/// Updates best found solutions of particles and global best in [PsoState].
#[derive(Debug, serde::Serialize)]
pub struct PsoStateUpdate;
impl PsoStateUpdate {
pub fn new<P: Problem>() -> Box<dyn Component<P>>
where
P: Problem<Encoding = Vec<f64>> + LimitedVectorProblem<T = f64>,
{
Box::new(Self)
}
}
impl<P> Component<P> for PsoStateUpdate
where
P: Problem<Encoding = Vec<f64>> + LimitedVectorProblem<T = f64>,
{
fn initialize(&self, _problem: &P, state: &mut State) {
state.require::<PsoState<P>>();
}

fn execute(&self, _problem: &P, state: &mut State) {
let population = state.population_stack_mut().pop();
let mut pso_state = state.get_mut::<PsoState<P>>();

for (i, individual) in population.iter().enumerate() {
if pso_state.bests[i].objective() > individual.objective() {
pso_state.bests[i] = individual.clone();

if pso_state.global_best.objective() > individual.objective() {
pso_state.global_best = individual.clone();
}
}
}

state.population_stack_mut().push(population);
}
}
}
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ pub mod heuristics;
pub mod operators;
pub mod prelude;
pub mod problems;
pub mod state;
pub mod tracking;
pub mod utils;

Expand Down
65 changes: 0 additions & 65 deletions src/operators/archive.rs

This file was deleted.

Loading

0 comments on commit 6ef3bc6

Please sign in to comment.