%% Geneticki algoritam - Vezbe - IEM (SmartGrid) PopulationSize=50; GenerationNumber=500; CrossoverProbability=0.8; % 80% MutationProbability=0.02; % 2% Elitism=2; % broj resenja koja se direktno prepisuju %% promenljive velicine xmin=[8 8]; xmax=[15 15]; dx=[0.1 0.1]; % proracun duzine hromozoma for i=1:length(xmin) VariableLength(i)=ceil(log2((xmax(i)-xmin(i))/dx(i))); end ChromosomeLength=sum(VariableLength); %% Inicijalizacija Population=round(rand(PopulationSize,ChromosomeLength)); %% Proracun fintes vrednosti % proracun promenljivih X b=1; for j=1:PopulationSize for i=1:length(xmin) e=b+VariableLength(i)-1; DV(j,i)=bin2dec(num2str(Population(j,b:e))); b=e+1; X(j,i)=xmin(i)+(xmax(i)-xmin(i))/((2^VariableLength(i))-1)*DV(j,i); end b=1; end % proracun fitnesa for j=1:PopulationSize Fitnes(j,:)=ObjectiveFunction_SmartGrid2(X(j,:)); end %rangiranje [Fitnes,index]=sort(Fitnes,'ascend'); %sortira od najveceg do najmanjeg Population=Population(index,:); %sortira od najboljeg do najlosijeg X=X(index,:); %sortira od najboljeg do najlosijeg Rang(:,1)=1:length(Fitnes); %formira se rang za odre]ivanje verovatnoce P=(max(Rang)-Rang+1)/sum(Rang); %verovatnoca izbora % u ovom trenutku imamo inicijalnu populaciju sa proracunatom verovatnocom % izbora resenja, sortirano sve od najboljeg do najlosijeg %% ovde pocinje petlja GA koja se ponavlja for gen=1:GenerationNumber %% elitizam Selection(1:Elitism,:)=Population(1:Elitism,:); %% selekcija (selection) Wheel=cumsum(P); for i=(Elitism+1):length(Wheel) Point=rand; for j=1:length(Population) if Point<=Wheel(j) Selection(i,:)=Population(j,:); break end end end %% ukrstanje (crossover) for i=1:2:length(Selection) if rand>CrossoverProbability %ne vrsi se ukrstanje NewPopulation(i,:)=Selection(i,:); NewPopulation(i+1,:)=Selection(i+1,:); else %vrsi se ukrstanje Point=ceil(rand*(ChromosomeLength-1)); Child1(1:Point)=Selection(i,1:Point); Child1(Point+1:ChromosomeLength)=Selection(i+1,Point+1:ChromosomeLength); Child2(1:Point)=Selection(i+1,1:Point); Child2(Point+1:ChromosomeLength)=Selection(i,Point+1:ChromosomeLength); NewPopulation(i,:)=Child1; NewPopulation(i+1,:)=Child2; end end %% mutacija (mutation) for i=1:length(Selection) if rand