# NOT RUN {
#---Find the four smallest numbers in a random vector of 100 uniforms---
# Generate the numbers and sort them so the best solution is (1,2,3,4).
Numbers <- sort(runif(100))
Numbers[1:6] #-View the smallest numbers.
ObjFun <- function(v, some_numbers) sum(some_numbers[v]) #-The objective function.
ObjFun(1:4, Numbers) #-The global minimum.
out <- kofnGA(n = 100, k = 4, OF = ObjFun, ngen = 50, some_numbers = Numbers) #-Run the GA.
summary(out)
plot(out)
# }
# NOT RUN {
# Note: the following two examples take tens of seconds to run (on a 2018 laptop).
#---Harder: find the 50x50 principal submatrix of a 500x500 matrix s.t. determinant is max---
# Use eigenvalue decomposition and QR decomposition to make a matrix with known eigenvalues.
n <- 500 #-Dimension of the matrix.
k <- 50 #-Size of subset to sample.
eigenvalues <- seq(10, 1, length.out=n) #-Choose the eigenvalues (all positive).
L <- diag(eigenvalues)
RandMat <- matrix(rnorm(n^2), nrow=n)
Q <- qr.Q(qr(RandMat))
M <- Q %*% L %*% t(Q)
M <- (M+t(M))/2 #-Enusre symmetry (fix round-off errors).
ObjFun <- function(v,Mat) -(determinant(Mat[v,v],log=TRUE)$modulus)
out <- kofnGA(n=n, k=k, OF=ObjFun, Mat=M)
print(out)
summary(out)
plot(out)
#---For interest: run GA searches iteratively (use initpop argument to pass results)---
# Alternate running with mutation probability 0.05 and 0.005, 50 generations each time.
# Use the same problem as just above (need to run that first).
mutprob <- 0.05
result <- kofnGA(n=n, k=k, OF=ObjFun, ngen=50, mutprob=mutprob, Mat=M) #-First run (random start)
allavg <- result$old$avg #-For holding population average OF values
allbest <- result$old$obj #-For holding population best OF values
for(i in 2:10) {
if(mutprob==0.05) mutprob <- 0.005 else mutprob <- 0.05
result <- kofnGA(n=n, k=k, OF=ObjFun, ngen=50, mutprob=mutprob, initpop=result$pop, Mat=M)
allavg <- c(allavg, result$old$avg[2:51])
allbest <- c(allbest, result$old$obj[2:51])
}
plot(0:500, allavg, type="l", col="blue", ylim=c(min(allbest), max(allavg)))
lines(0:500, allbest, col="red")
legend("topright", legend=c("Pop average", "Pop best"), col=c("blue", "red"), bty="n",
lty=1, cex=0.8)
summary(result)
# }
# NOT RUN {
# }
Run the code above in your browser using DataLab