% 免疫优化优化算法
% 本代码实现单次优化
% x=[mn1,mn3,beta1,beta3,u1,z1,z3,phi1,phi3],phi1,phi3为齿宽系数
tic;
clear all;
close all;
G=100;NP=300;D=9;
pm=0.7; % 变异概率
alfa=1;belta=0.5; % 激励度计算系数
detas=0.2; % 相似度阈值
Nc=10; % 克隆扩增倍数
deta0=5; % 领域范围初值
f = zeros(D,NP); % 初始种群
af = zeros(D,NP/2); % 免疫操作后的种群
bf = zeros(D,NP/2); % 刷新后的种群
f1 = zeros(D,NP); % 合并种群
MSLL = zeros(1,NP); % 种群激励度
aMSLL = zeros(1,NP/2); % 对应种群的激励度
bMSLL = zeros(1,NP/2); % 对应种群的激励度
ND = zeros(1,NP); % 抗体浓度
aND = zeros(1,NP/2); % 对应种群的抗体浓度
bND = zeros(1,NP/2); % 对应种群的抗体浓度
nd = zeros(1,NP); % 抗体间的亲和度
nda = zeros(1,NP/2); % 对应种群的抗体亲和度
ndb = zeros(1,NP/2); % 对应种群的抗体亲和度
yy1 = zeros(1,G); % 每次迭代的最优结果
NaMSLL = zeros(1,D); % 克隆种群的激励度
%% 创建初始种群 %%
% 随机生成
i=0;
while i<NP
x(1)=2+10*rand;
x(2)=2+10*rand;
x(5)=5+5*rands(1);
x(3)=7+8*rand;
x(6)=17*cos(x(3)/180*pi)^3+5*rand;
x(4)=7+8*rand;
x(7)=17*cos(x(4)/180*pi)^3+5*rand;
x(8)=0.3+0.3*rand;
x(9)=0.3+0.3*rand;
[g,y]=mycon(x);
if g==1
i=i+1;
f(:,i)=y;
end
end
for np=1:NP
MSLL(np)=funmin(f(:,np));
end
%计算个体浓度和激励度
for np=1:NP
for j=1:NP
nd(j)=sqrt(sum((f(:,np)-f(:,j)).^2)); %第np个抗体与第j个抗体的亲和度
if nd(j)<detas
nd(j)=1;
else
nd(j)=0;
end
end
ND(np)=sum(nd)/NP; %抗体浓度
end
MSLL=alfa*MSLL-belta*ND;
[SortMSLL,Index]=sort(MSLL);
Sortf=f(:,Index);
%% 免疫循环
gen=0;
while gen<G
for i=1:NP/2
% 选择激励度前一半的个体进行免疫操作
a=Sortf(:,i);
Na=repmat(a,1,Nc); % 克隆操作
deta=deta0/gen; % 克隆即在某个体的邻域内进行搜索,随着迭代次数增加,邻域范围减小
for j=2:Nc
for ii=1:D
if rand<pm
Na(ii,j)=Na(ii,j)+(rand-0.5)*deta; % 变异
end
end
[g,y] = mycon(Na(:,j));
if g == 1
Na(:,j) = y;
NaMSLL(j) = funmin(Na(:,j));
else
Na(:,j) = Inf;
NaMSLL(j) = Inf;
end
end
Na(:,1) = Sortf(:,i);
NaMSLL(1) = funmin(Na(:,1));
[NaSortMSLL,Index]=min(NaMSLL);
aMSLL(i) = NaSortMSLL;
af(:,i) = Na(:,Index);
end
% 免疫操作后的种群激励度
for np=1:NP/2
for j=1:NP/2
nda(j)=sqrt(sum((af(:,np)-af(:,j)).^2)); % 第np个抗体与第j个抗体的亲和度
if nda(j)<detas
nda(j)=1;
else
nda(j)=0;
end
end
aND(np)=sum(nda)/(NP/2); % 第np个抗体的抗体浓度
end
aMSLL=alfa*aMSLL-belta*aND;
% 种群刷新
np=0;
while np<NP/2
% 种群随机
x(1)=2+10*rand;
x(2)=2+10*rand;
x(5)=5+5*rands(1);
x(3)=7+8*rand;
x(6)=17*cos(x(3)/180*pi)^3+5*rand;
x(4)=7+8*rand;
x(7)=17*cos(x(4)/180*pi)^3+5*rand;
x(8)=0.3+0.3*rand;
x(9)=0.3+0.3*rand;
[g,y]=mycon(x);
if g==1
np=np+1;
bf(:,np)=y;
end
end
for np=1:NP/2
bMSLL(np)=funmin(bf(:,np));
end
% 新生成种群激励度
for np=1:NP/2
for j=1:NP/2
ndb(j)=sqrt(sum((bf(:,np)-bf(:,j)).^2));
if ndb(j)<detas
ndb(j)=1;
else
ndb(j)=0;
end
end
bND(np)=sum(ndb)/NP/2;
end
bMSLL=alfa*bMSLL-belta*bND;
% 免疫种群与新种群合并
f1=[af,bf];
MSLL=[aMSLL,bMSLL];
[SortMSLL,Index]=sort(MSLL);
Sortf=f1(:,Index);
gen=gen+1;
yy1(gen)=funmin(Sortf(:,1));
end
%% 输出结果
% V_best是优化后的体积值(目标函数值),x_best是优化后的参数,G是约束函数值
[V_best,x_best,G]=funmin(Sortf(:,1))
toc;
figure;
plot(yy1);
xlabel('迭代次数')
ylabel('目标函数值')
title(['亲和度进化曲线 终止代数=' num2str(gen) ' 时间已过' num2str(toc) '秒'])