标识符命名规则
一般变量
变量命名多采用小驼峰命名方式,如下
var serverForYou
循环变量多采用 i , j , k i,j,k i,j,k等前缀形式命名,应避少用非前缀的命名方式,避免与matlab虚数单位重复
for i_population=1:K
常量、全局变量
常量或者全局变量均采用字母大写形式,如
DECISION
矩阵、结构体、元胞变量
矩阵,结构体及元胞变量多采用各类型英文名+"_"+变量实际代表含义名称,如
cell_mother
struct_population
matrix_fish
结构体属性构建及引用方式
构建
% state: optimization state of one generation
state = struct(...
'currentGen', 1,... % current generation number
'evaluateCount', 0,... % number of objective function evaluation
'totalTime', 0,... % total time from the beginning
'firstFrontCount', 0,... % individual number of first front
'frontCount', 0,... % number of front
'avgEvalTime', 0 ... % average evaluation time of objective function (current generation)
);
引用
options.popSize = 100; % populaion size
options.maxGen = 150; % max generation 若此数值小于listbox值max,则不会显示
options.numObj = 2; % number of objectives
options.numVar = 2; % number of design variables
options.numCons = 2; % number of constraints
函数
- 函数命名多采用小写字母+下划线分割形式命名
non_dominant_sort()
- get/set前缀多用来访问对象或者属性用
- compute前缀多用来计算某些量的函数用,如
compute_objectives()
- is前缀多用来判断
isbool()
代码版式
文件表头
样例
%___________________________________________________________________%
% Multi-Objective Grey Wolf Optimizer (MOGWO) %
% Source codes demo version 1.0 %
% %
% Developed in MATLAB R2011b(7.13) %
% %
% Author and programmer: Seyedali Mirjalili %
% %
% e-Mail: ali.mirjalili@gmail.com %
% seyedali.mirjalili@griffithuni.edu.au %
% %
% Homepage: http://www.alimirjalili.com %
% %
% Main paper: %
% %
% S. Mirjalili, S. Saremi, S. M. Mirjalili, L. Coelho, %
% Multi-objective grey wolf optimizer: A novel algorithm for %
% multi-criterion optimization, Expert Systems with Applications,%
% in press, DOI: http://dx.doi.org/10.1016/j.eswa.2015.10.039 % %
% %
%___________________________________________________________________%
函数说明
样例1:
function [ 函数输出参数] = 函数名( 函数输入)
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%此处为函数名,如果不是函数文件就取消此行
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%创建人:
%日期:
%修改人:
%日期:
%函数变量及功能的简单描述
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
--函数主体
样例2:
function result = nsga2(opt, varargin)
% Function: result = nsga2(opt, varargin)
% Description: The main flowchart of of NSGA-II. Note:
% All objectives must be minimization. If a objective is maximization, the
% objective should be multipled by -1.
%
% Syntax:
% result = nsga2(opt): 'opt' is generated by function nsgaopt().
% result = nsga2(opt, param): 'param' can be any data type, it will be
% pass to the objective function objfun().
%
% Then ,the result structure can be pass to plotnsga to display the
% population: plotnsga(result);
%
% Parameters:
% opt : A structure generated by funciton nsgaopt().
% varargin : Additional parameter will be pass to the objective functions.
% It can be any data type. For example, if you call: nsga2(opt, param),
% then objfun would be called as objfun(x,param), in which, x is the
% design variables vector.
% Return:
% result : A structure contains optimization result.
%
% LSSSSWC, NWPU
% Revision: 1.2 Data: 2011-07-26
%*************************************************************************
样例3:
%NDSort - Do non-dominated sorting by efficient non-dominated sort.
%
% FrontNo = NDSort(F,s) does non-dominated sorting on F, where F is the
% matrix of objective values of a set of individuals, and s is the number
% of individuals to be sorted at least. FrontNo(i) denotes the front
% number of the i-th individual. The individuals have not been sorted are
% assigned a front number of inf.
%
% FrontNo = NDSort(F,C,s) does non-dominated sorting based on constrained
% domination, where C is the matrix of constraint values of the
% individuals. In this case, feasible solutions always dominate
% infeasible solutions, and one infeasible solution dominates another
% infeasible solution if the former has a smaller overall constraint
% violation than the latter.
%
% In particular, s = 1 indicates finding only the first non-dominated
% front, s = size(F,1)/2 indicates sorting only half the population
% (which is often used in the algorithm), and s = inf indicates sorting
% the whole population.
%
% [FrontNo,K] = NDSort(...) also returns the maximum front number besides
% inf.
%
% Example:
% [FrontNo,MaxFNo] = NDSort(PopObj,1)
% [FrontNo,MaxFNo] = NDSort(PopObj,PopCon,inf)
%------------------------------- Reference --------------------------------
% [1] X. Zhang, Y. Tian, R. Cheng, and Y. Jin, An efficient approach to
% nondominated sorting for evolutionary multiobjective optimization, IEEE
% Transactions on Evolutionary Computation, 2015, 19(2): 201-213.
% [2] X. Zhang, Y. Tian, R. Cheng, and Y. Jin, A decision variable
% clustering based evolutionary algorithm for large-scale many-objective
% optimization, IEEE Transactions on Evolutionary Computation, 2018, 22(1):
% 97-112.
%------------------------------- Copyright --------------------------------
% Copyright (c) 2018-2019 BIMK Group. You are free to use the PlatEMO for
% research purposes. All publications which use this platform or any code
% in the platform should acknowledge the use of "PlatEMO" and reference "Ye
% Tian, Ran Cheng, Xingyi Zhang, and Yaochu Jin, PlatEMO: A MATLAB platform
% for evolutionary multi-objective optimization [educational forum], IEEE
% Computational Intelligence Magazine, 2017, 12(4): 73-87".
%--------------------------------------------------------------------------
代码主体
空行
空行起着分割块或段落的作用,块(段落)之间一般留一个或两个空行。
空行使用规则:
逻辑块之间要留空行
%*************************************************************************
% 1. Initialization
%*************************************************************************
numObj = length( pop(1).obj ); % number of objectives
refPoints = opt.refPoints;
refWeight = opt.refWeight; % weight factor of objectives
if(isempty(refWeight))
refWeight = ones(1, numObj);
end
epsilon = opt.refEpsilon;
numRefPoint = size(refPoints, 1);
% Determine the normalized factors
bUseFrontMaxMin = false; % bUseFrontMaxMin : If use the maximum and minimum value in the front as normalized factor.
if( strcmpi(opt.refUseNormDistance, 'ever') )
% 1) Find possiable (not current population) maximum and minimum value
% of each objective.
obj = vertcat(pop.obj);
if( ~isfield(opt, 'refObjMax_tmp') )
opt.refObjMax_tmp = max(obj);
opt.refObjMin_tmp = min(obj);
else
objMax = max(obj);
objMin = min(obj);
for i = 1:numObj
if(opt.refObjMax_tmp(i) < objMax(i))
opt.refObjMax_tmp(i) = objMax(i);
end
if(opt.refObjMin_tmp(i) > objMin(i))
opt.refObjMin_tmp(i) = objMin(i);
end
end
clear objMax objMin
end
objMaxMin = opt.refObjMax_tmp - opt.refObjMin_tmp;
clear obj
elseif( strcmpi(opt.refUseNormDistance, 'front') )
% 2) Do not use normalized Euclidean distance.
bUseFrontMaxMin = true;
elseif( strcmpi(opt.refUseNormDistance, 'no') )
% 3) Do not use normalized Euclidean distance.
objMaxMin = ones(1,numObj);
else
% 3) Error
error('NSGA2:ParamError', ...
'No support parameter: options.refUseNormDistance="%s", only "yes" or "no" are supported',...
opt.refUseNormDistance);
end
%*************************************************************************
% 2. Calculate preference distance pop(:).prefDistance
%*************************************************************************
for fid = 1:length(front)
% Step1: Calculate the weighted Euclidean distance in each front
idxFront = front(fid).f; % idxFront : index of individuals in current front
numInd = length(idxFront); % numInd : number of individuals in current front
popFront = pop(idxFront); % popFront : individuals in front fid
objFront = vertcat(popFront.obj); % objFront : the whole objectives of all individuals
if(bUseFrontMaxMin)
objMaxMin = max(objFront) - min(objFront); % objMaxMin : the normalized factor in current front
end
% normDistance : weighted normalized Euclidean distance
normDistance = calcWeightNormDistance(objFront, refPoints, objMaxMin, refWeight);
% Step2: Assigned preference distance
prefDistanceMat = zeros(numInd, numRefPoint);
for ipt = 1:numRefPoint
[~,ix] = sort(normDistance(:, ipt));%升序排序,选择距离小的
prefDistanceMat(ix, ipt) = 1:numInd;%排序位置
end
prefDistance = min(prefDistanceMat, [], 2); % 2表示计算每行min 对于参考点距离的rank位置,rank的值当作参考距离
clear ix
% Step3: Epsilon clearing strategy
idxRemain = 1:numInd; % idxRemain : index of individuals which were not processed
while(~isempty(idxRemain))
% 1. Select one individual from remains
objRemain = objFront( idxRemain, :);
selIdx = randi( [1,length(idxRemain)] );
selObj = objRemain(selIdx, :);
% 2. Calc normalized Euclidean distance
% distanceToSel : normalized Euclidean distance to the selected points
distanceToSel = calcWeightNormDistance(objRemain, selObj, objMaxMin, refWeight);
% 3. Process the individuals within a epsilon-neighborhood
idx = find( distanceToSel <= epsilon ); % idx : index in idxRemain
if(length(idx) == 1) % the only individual is the selected one
idxRemain(selIdx)=[];
else
for i=1:length(idx)
if( idx(i)~=selIdx )
idInIdxRemain = idx(i); % idx is the index in idxRemain vector
id = idxRemain(idInIdxRemain);
% *Increase the preference distance to discourage the individuals
% to remain in the selection.
prefDistance(id) = prefDistance(id) + round(numInd/2);
end
end
idxRemain(idx) = [];
end
end
% Save the preference distance
for i=1:numInd
id = idxFront(i);
pop(id).prefDistance = prefDistance(i);
end
结构体定义之间要留空行
% pop : current population
% newpop : new population created by genetic algorithm operators
% combinepop = pop + newpop;
pop = repmat( struct(...
'var', zeros(1,nVar), ... % 变量值
'obj', zeros(1,nObj), ... %目标函数值
'cons', zeros(1,nCons),... %
'rank', 0,...
'distance', 0,...
'prefDistance', 0,... % preference distance used in R-NSGA-II
'nViol', 0,... % The number of constraints
'violSum', 0),... % The sum of abs(constraints)
[1,popsize]); %struct 默认是行形式存在的,如果[2, popsize]则与数组相同
% state: optimization state of one generation
state = struct(...
'currentGen', 1,... % current generation number
'evaluateCount', 0,... % number of objective function evaluation
'totalTime', 0,... % total time from the beginning
'firstFrontCount', 0,... % individual number of first front
'frontCount', 0,... % number of front
'avgEvalTime', 0 ... % average evaluation time of objective function (current generation)
);
函数定义体之间要留空行
函数体内,完整的控制结构和单独的语句块之间要留空行
GreyWolves=CreateEmptyParticle(GreyWolves_num);
for i=1:GreyWolves_num
GreyWolves(i).Velocity=0;
GreyWolves(i).Position=zeros(1,nVar);
for j=1:nVar
GreyWolves(i).Position(1,j)=unifrnd(lb(j),ub(j),1);
end
GreyWolves(i).Cost=fobj(GreyWolves(i).Position')';
GreyWolves(i).Best.Position=GreyWolves(i).Position;
GreyWolves(i).Best.Cost=GreyWolves(i).Cost;
end
GreyWolves=DetermineDomination(GreyWolves);
% Eq.(3.4) in the paper
c=2.*rand(1, nVar);
% Eq.(3.1) in the paper
D=abs(c.*Beta.Position-GreyWolves(i).Position);
% Eq.(3.3) in the paper
A=2.*a.*rand()-a;
% Eq.(3.9) in the paper
X2=Beta.Position-A.*abs(D);
% Eq.(3.4) in the paper
c=2.*rand(1, nVar);
% Eq.(3.1) in the paper
D=abs(c.*Alpha.Position-GreyWolves(i).Position);
% Eq.(3.3) in the paper
A=2.*a.*rand()-a;
% Eq.(3.10) in the paper
X3=Alpha.Position-A.*abs(D);
逻辑上密切相关的语句序列之间不要留空行
未完,待续!🌜🌛