# NOT RUN {
# In this example we use the PSO to solve the following equation:
# a * 5 + b * 25 + 10 = 15
fitness_function <- function(values){
a <- values[1]
b <- values[2]
particule_result <- a*5 + b*25 + 10
difference <- 15 - particule_result
fitness <- 1 - abs(difference)
return(fitness)
}
values_ranges <- list(c(-10^3,10^3),c(-10^3,10^3))
swarm <- ParticleSwarm$new(pop_size = 200,
values_names = list("a","b"),
fitness_function = fitness_function,
max_it = 75,
acceleration_coefficient_range = list(c(0,1),c(0,1)),
inertia = 0.5,
ranges_of_values = values_ranges)
swarm$run(plot = FALSE,verbose = FALSE,save_file = FALSE)
# the solution is :
swarm$swarm_best_values
swarm$swarm_best_values[[1]]*5 + swarm$swarm_best_values[[2]] *25 + 10
## ------------------------------------------------
## Method `ParticleSwarm$new`
## ------------------------------------------------
# Create a ParticleSwarm object
swarm <- ParticleSwarm$new(pop_size=20,
values_names=c('a','b'),
max_it=20,
fitness_function = function(values){return(values[1]+values[2])},
acceleration_coefficient=list(c(0.5,1),c(0.5,1)),
inertia=0.5,
ranges_of_values=list(c(-100,100),c(-100,100)))
## ------------------------------------------------
## Method `ParticleSwarm$run`
## ------------------------------------------------
# Create a ParticleSwarm object
swarm <- ParticleSwarm$new(pop_size=20,
values_names=c('a','b'),
max_it=20,
fitness_function = function(values){return(values[1]+values[2])},
acceleration_coefficient=list(c(0.5,1),c(0.5,1)),
inertia=0.5,
ranges_of_values=list(c(-100,100),c(-100,100)))
# run the PSO
swarm$run(verbose = FALSE,
plot = FALSE,
save_file = FALSE)
# return the best result:
print(swarm$swarm_best_values)
# }
Run the code above in your browser using DataLab