function [opt_rte,promin_gzz] = ga(Params,pop_size,num_iter)
disp(strcat('--采用遗传粒子群算法GAPSO进行优化分析时:'));
% Input:
% Paras为相关参数
% POP_SIZE (scalar integer) is the size of the population (should be divisible by 4)
% NUM_ITER (scalar integer) is the number of desired iterations for the algorithm to run
% SHOW_PROG (scalar logical) shows the GA progress if true
% SHOW_RES (scalar logical) shows the GA results if true
%
% Output:
% OPT_RTE (integer array) is the best route found by the algorithm
% MIN_DIST (scalar float) is the cost of the best route
%
n = Params.N;
promin_gzz = zeros(1,num_iter);
% Sanity Checks
pop_size = 5*ceil(pop_size/5);
num_iter = max(1,round(real(num_iter(1))));
% Initialize the Population
pop = zeros(pop_size,n);
YXSX = sum(Params.QX');
[~,pop(1,:)] = sort(YXSX,'descend');
for k = 2:pop_size
pop(k,:) = pop(1,:);
end
% Run the GA
global_min = Inf;
total_gzz = zeros(1,pop_size);
dist_history = zeros(1,num_iter);
tmp_pop = zeros(5,n);
new_pop = zeros(pop_size,n);
show_res = 0;
for iter = 1:num_iter
% Evaluate Each Population Member (Calculate Total Distance)
for p = 1:pop_size
total_gzz(p) = f_single(Params,pop(p,:),show_res);
end
% Find the Best Route in the Population
[min_gzz,index] = min(total_gzz);
dist_history(iter) = min_gzz;
if min_gzz < global_min
global_min = min_gzz;
opt_rte = pop(index,:);
end
promin_gzz(iter) = min_gzz;
% Genetic Algorithm Operators
rand_pair = randperm(pop_size);
for p = 5:5:pop_size
rtes = pop(rand_pair(p-4:p),:);
dists = total_gzz(rand_pair(p-4:p));
[ignore,idx] = min(dists);
best_of_5_rte = rtes(idx,:);
ins_pts = sort(ceil(n*rand(1,2)));
I = ins_pts(1);
J = ins_pts(2);
for k = 1:5 % Mutate the Best to get Three New Routes
tmp_pop(k,:) = best_of_5_rte;
switch k
case 2 % Flip翻转
tmp_pop(k,I:J) = fliplr(tmp_pop(k,I:J));
case 3 % Swap变异
tmp_pop(k,[I J]) = tmp_pop(k,[J I]);
case 4 % Slide平移
tmp_pop(k,I:J) = tmp_pop(k,[I+1:J I]);
case 5 %cross 交叉
jy1 = tmp_pop(k,I:J); %待交叉基因段
jy2 = opt_rte(I:J); %最优染色体的待交叉基因段
jybtc = intersect(jy1,jy2); %两个基因段中均有的基因无需填充
for l = 1:length(jybtc)
jy1(find(jy1==jybtc(l))) = [];
jy2(find(jy2==jybtc(l))) = [];
end
for l = 1:length(jy1)
tmp_pop(k,find(tmp_pop(k,:)==jy2(l))) = jy1(l);
end
tmp_pop(k,I:J) = opt_rte(I:J); %交叉
otherwise % Do Nothing
end
end
new_pop(p-4:p,:) = tmp_pop;
end
pop = new_pop;
end
min_gzz = f_single(Params,opt_rte,1);
%opt_rte;
%min_dist;
end