Skip to content

Commit

Permalink
Improve according to review comments
Browse files Browse the repository at this point in the history
  • Loading branch information
HeleNoir committed Dec 4, 2023
1 parent ca81a37 commit d4a1467
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 24 deletions.
32 changes: 15 additions & 17 deletions src/components/replacement/bh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use rand::Rng;
use serde::{Deserialize, Serialize};

use crate::{
population::BestIndividual, problems::LimitedVectorProblem, utils::squared_euclidean,
Component, ExecResult, Individual, SingleObjectiveProblem, State,
problems::LimitedVectorProblem, utils::squared_euclidean,
Component, ExecResult, SingleObjectiveProblem, State,
};

#[derive(Clone, Serialize, Deserialize)]
Expand All @@ -28,35 +28,33 @@ where
{
fn execute(&self, problem: &P, state: &mut State<P>) -> ExecResult<()> {
let mut populations = state.populations_mut();
let offspring = populations.pop();
let mut offspring = populations.pop();

let f_bh = state.best_objective_value().unwrap().value();

let fitness_sum = offspring.iter().map(|x| x.objective().value()).sum::<f64>();
let radius = f_bh / fitness_sum;

let best_ind = offspring.best_individual().cloned();
let best = best_ind.unwrap().solution().clone();
let (index, best) = offspring
.iter()
.enumerate()
.min_by_key(|(_u, i)| i.objective())
.unwrap();
let distances = offspring
.iter()
.map(|o| squared_euclidean(o.solution(), &best).sqrt())
.map(|o| squared_euclidean(o.solution(), best.solution()).sqrt())
.collect::<Vec<f64>>();

let mut new_offspring: Vec<Individual<P>> = vec![];
for (u, i) in offspring.iter().enumerate() {
for (u, i) in offspring.iter_mut().enumerate() {
// do not replace best individual
if distances[u] < radius && distances[u] != 0.0 {
let rand: Vec<f64> = (0..problem.dimension())
.map(|_| state.random_mut().gen_range(problem.domain()[0].clone()))
if distances[u] < radius && u != index {
let rand: Vec<f64> = problem.domain().iter()
.map(|d| state.random_mut().gen_range(d.clone()))
.collect();
let j = Individual::new_unevaluated(rand);
//println!("{:?}, {:?}", u, &j);
new_offspring.push(j);
} else {
new_offspring.push(i.clone());
*i.solution_mut() = rand;
}
}
populations.push(new_offspring);
populations.push(offspring);
Ok(())
}
}
12 changes: 6 additions & 6 deletions src/components/swarm/bh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,20 @@ where
}

fn execute(&self, _problem: &P, state: &mut State<P>) -> ExecResult<()> {
let distr = Uniform::new(0.0, 1.0);
let distribution = Uniform::new(0.0, 1.0);

// Get necessary state like global best `xg`
let best = state.populations().current().best_individual().cloned();
let binding = best.unwrap();
let xg = binding.solution();
let mut binding2 = state.populations_mut();
let xs = binding2.current_mut().as_solutions_mut();
let best_ind = best.unwrap();
let xg = best_ind.solution();
let mut population = state.populations_mut();
let xs = population.current_mut().as_solutions_mut();

// Perform the update step.
for x in xs {
for i in 0..x.len() {
// Calculate change in position
let pos = distr.sample(&mut *state.random_mut()) * (xg[i] - x[i]);
let pos = distribution.sample(&mut *state.random_mut()) * (xg[i] - x[i]);
// Add value to particle position
x[i] += pos;
}
Expand Down
2 changes: 1 addition & 1 deletion src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -47,5 +47,5 @@ impl<T> serde::Serialize for SerializablePhantom<T> {

/// Calculates squared Euclidean distance between two vectors.
pub fn squared_euclidean(a: &[f64], b: &Vec<f64>) -> f64 {
a.iter().zip(b).map(|(p, q)| (p - q).powf(2.0)).sum::<f64>()
a.iter().zip(b).map(|(p, q)| (p - q).powi(2)).sum::<f64>()
}

0 comments on commit d4a1467

Please sign in to comment.