-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain.m
More file actions
294 lines (232 loc) · 13 KB
/
Main.m
File metadata and controls
294 lines (232 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%% Created by: PREMKUMAR VINCENT %%%%%%
%%%%%% Contact: vinpremkumar@gmail.com %%%%%%
%%%%%% This is an evolutionary algorithm method used to design %%%%%%
%%%%%% grating patterns on the top and bottom electrodes of solar cell %%%%%%
%%%%%% The interspacing between the grating patterns is also evolved to %%%%%%
%%%%%% find the best result. Both the shape and spacing between the gratings %%%%%%
%%%%%% will evolve together to find the most optimized grating pattern. %%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
clearvars;
close all;
clc;
% When polygons are merged, the 2 polygons are first slipt into
% numOfMeshes x numOfMeshes and when mixed to make a new polygon.
numOfMeshes = 4;
%% Generic Algorithm's paramteres
maxPopulation = 50;
maxGeneration = 100;
mutationProbability = 0.1;
numOfChildren = 2;
currentGeneration = 0;
rng('shuffle');
%% Input the radius in which polygon is created (Unit: nm)
%%%%%%%%%%%%%%%%%%%%%%%
% Enter circle radius %
inputDiameter = 350; % within which the %
% random polygon is %
sizingFactor = 10; % created %
Radius = ((inputDiameter/2) * sizingFactor); %%%%%%%%%%%%%%%%%%%%%%%
%% Pre-allocation of memory
x = cell(1, maxPopulation);
y = cell(1, maxPopulation);
population.binaryImage = cell(1, maxPopulation);
fitnessValue = zeros(1,maxPopulation);
popBreed.binaryImage = cell(1,maxPopulation-1);
%% If maxGeneration hasn't reached yet, run the simulation
while currentGeneration <= maxGeneration
tStart = tic;
if currentGeneration == 0
%% Polygon parameter initilization
numVerts = randi([3 14], 1, maxPopulation);
vertIndex = find(numVerts > 12); % Limiting too many rounded structures
numVerts(vertIndex) = 35;
AspectRatio = randi([1 12], 1, maxPopulation)*25/100;
population.dBetweenGratings = randi([1 40], 1, maxPopulation) * 50;
%% Creating initial population
for i = 1:maxPopulation
% Generate random convex polygons
[x{i},y{i}] = GenerateRegularPolygon (Radius, numVerts(i), AspectRatio(i));
% Obtain binary image of the polygons
population.binaryImage{i} = MaskPolygon(x{i},y{i},Radius);
% figure(i)
% imshow(binaryImage{i});
end
%% Calculate the Fitness
for i = 1:maxPopulation
fitnessValue(i) = FitnessFunction (population.dBetweenGratings(i), population.binaryImage{i}, sizingFactor);
% For testing purpose only
% fitnessValue(i) = rand(1);
end
else
for i = 2:maxPopulation
fitnessValue(i) = FitnessFunction (population.dBetweenGratings(i), population.binaryImage{i}, sizingFactor);
% For testing purpose only
% fitnessValue(i) = rand(1);
end
end
% Display currentGeneration and fitnessValue in command window
fprintf('Current Generation = %d\n', currentGeneration);
% Rank the population by their fitnessValue (minimization problem)
[fitnessSorted, fitIndex] = sort(fitnessValue, 'ascend');
fmt=['Fitness values:\n' repmat(' %.2f',1,numel(fitnessSorted))];
fprintf(fmt,fitnessSorted);
%% Sorting population (binary image and distance between gratings) according to rank
% popSorted.binaryImage is the sorted binaryImage population
popSorted.binaryImage = population.binaryImage;
for i = 1:size(popSorted.binaryImage,2)
popSorted.binaryImage{2,i} = fitIndex(i);
end
popSorted.binaryImage = popSorted.binaryImage';
popSorted.binaryImage = sortrows(popSorted.binaryImage,2);
popSorted.binaryImage = popSorted.binaryImage';
popSorted.binaryImage(2,:) = [];
% popSorted.dBetweenGratings
popSorted.dBetweenGratings = population.dBetweenGratings(fitIndex);
%% Cloninng the best specimen as a backup of best specimen
popBest.binaryImage = popSorted.binaryImage{1};
popBest.dBetweenGratings = popSorted.dBetweenGratings(1);
%% Replacing the worst specimen by the cloned best specimen
popSorted.binaryImage{end} = [];
popSorted.binaryImage{end} = popBest.binaryImage;
popSorted.dBetweenGratings(end) = popBest.dBetweenGratings;
% Shifting the last element to the first since it was replaced by the best specimen
popSorted.binaryImage = circshift(popSorted.binaryImage,[2,1]);
popSorted.dBetweenGratings = circshift(popSorted.dBetweenGratings,[2,1]);
%% Save the best specimen
path = pwd;
filenamePoly = strcat(path,'\Results\Polygons\Gen',int2str(currentGeneration),'.txt');
polyBest = ReconstructPolygon(popBest.binaryImage, sizingFactor);
save(filenamePoly, 'polyBest', '-ascii');
filenamedBetweenGratings = strcat(path,'\Results\dBetweenGratings\Gen',int2str(currentGeneration),'.txt');
dBetweenGratingsBest = popBest.dBetweenGratings;
save(filenamedBetweenGratings, 'dBetweenGratingsBest' , '-ascii');
%% Selection
% Make population to be used for selection
for i = 2 : size(popSorted.binaryImage,2)
popBreed.binaryImage{i-1} = popSorted.binaryImage{i};
end
popBreed.dBetweenGratings = popSorted.dBetweenGratings(2:end);
fitnessBreed = fitnessSorted(2:end);
% Even number of population is required to be input for selection
if(mod(maxPopulation,2))
nPop_withoutmax = maxPopulation - (numOfChildren - 1);
else
nPop_withoutmax = maxPopulation - numOfChildren;
end
if currentGeneration < maxGeneration
nextParents = Selection(fitnessBreed, popBreed, nPop_withoutmax, numOfChildren);
%% Cross-Breeding (Reproduction)
% Pre-allocate memory
newPopulation.binaryImage = cell(1, maxPopulation);
newPopulation.dBetweenGratings = zeros(1, maxPopulation);
% Function handle CreateChild for MergePolygon
CreateChild = @(parent1, parent2)MergePolygon(parent1, parent2, mutationProbability, numOfMeshes, Radius);
tempCount = 0;
% Choose parents for breeding
for i = 1:size(nextParents.binaryImage,2)
parent1.binaryImage = nextParents.binaryImage{i};
parent1.dBetweenGratings = nextParents.dBetweenGratings(i);
parent2.binaryImage = nextParents.binaryImage{end - i + 1};
parent2.dBetweenGratings = nextParents.dBetweenGratings(end - i + 1);
for j=1:1:numOfChildren
numOfAttempts = 0;
tempCount = tempCount + 1;
while true
child = CreateChild(parent1, parent2);
% Check for center of gravity
% Reconstruct vertices from binary image
polygonVertices = ReconstructPolygon(child.binaryImage, sizingFactor);
% Split vertices of the reconstructed polygon
x_vertices = polygonVertices(:,1);
y_vertices = polygonVertices(:,2);
% Offset the polygon to have a vertex at (0,0)
if min(y_vertices) < 0
y_vertices = y_vertices + abs(min(y_vertices));
else
y_vertices = y_vertices - abs(min(y_vertices));
end
if min(x_vertices) < 0
x_vertices = x_vertices + abs(min(x_vertices));
else
x_vertices = x_vertices - abs(min(x_vertices));
end
% Find the centroid
[x_centroid, ~] = polygoncentroid(x_vertices,y_vertices);
% If the centroid falls within the base of the polygon, then it is a balanced polygon
CenterOfMass_balanced = nnz(x_centroid >= min(x_vertices(y_vertices == min(y_vertices))) & x_centroid <= max(x_vertices(y_vertices == min(y_vertices))));
% Auto-escape condition
numOfAttempts = numOfAttempts + 1;
if CenterOfMass_balanced == 1 || numOfAttempts == 4
break;
end
end
newPopulation.binaryImage{tempCount+1} = child.binaryImage;
newPopulation.dBetweenGratings(tempCount+1) = child.dBetweenGratings;
end
end
% Input the clone into the newPopulation
newPopulation.binaryImage{1} = popBest.binaryImage;
newPopulation.dBetweenGratings(1) = popBest.dBetweenGratings;
% Fill the rest of newPopulaion with child of self cross-breeding of pop_best
tempIndex = find(~cellfun(@isempty,newPopulation.binaryImage));
for i = size(tempIndex,2)+1 : maxPopulation
parent1.binaryImage = popBest.binaryImage;
parent1.dBetweenGratings = popBest.dBetweenGratings;
parent2 = parent1;
numOfAttempts = 0;
while true
child = CreateChild(parent1, parent2);
% Check for center of gravity
% Reconstruct vertices from binary image
polygonVertices = ReconstructPolygon(child.binaryImage, sizingFactor);
% Split vertices of the reconstructed polygon
x_vertices = polygonVertices(:,1);
y_vertices = polygonVertices(:,2);
% Offset the polygon to have a vertex at (0,0)
if min(y_vertices) < 0
y_vertices = y_vertices + abs(min(y_vertices));
else
y_vertices = y_vertices - abs(min(y_vertices));
end
if min(x_vertices) < 0
x_vertices = x_vertices + abs(min(x_vertices));
else
x_vertices = x_vertices - abs(min(x_vertices));
end
% Find the centroid
[x_centroid, ~] = polygoncentroid(x_vertices,y_vertices);
% If the centroid falls within the base of the polygon, then it is a balanced polygon
CenterOfMass_balanced = nnz(x_centroid >= min(x_vertices(y_vertices == min(y_vertices))) & x_centroid <= max(x_vertices(y_vertices == min(y_vertices))));
% Auto-escape condition
numOfAttempts = numOfAttempts + 1;
if CenterOfMass_balanced == 1 || numOfAttempts == 4
break;
end
end
popIndex = find(cellfun('isempty', newPopulation.binaryImage),1);
if ~isempty(popIndex)
newPopulation.binaryImage{popIndex} = child.binaryImage;
newPopulation.dBetweenGratings(popIndex) = child.dBetweenGratings;
end
end
% Update population for Genetic Algorithm
population.binaryImage = newPopulation.binaryImage;
population.dBetweenGratings = newPopulation.dBetweenGratings;
% Update best population's fitnessValue
fitnessValue(1) = fitnessSorted(1);
end
% Elapsed time
tEnd = toc(tStart);
fprintf('\nElapsed time is %d minutes and %f seconds', floor(tEnd/60), rem(tEnd,60));
% Display status in command window
cprintf('*red',['\n----------Completion (%%) = ', num2str(round((currentGeneration/maxGeneration)*100)),' %%----------\n']);
cprintf('*blue', 'Simulation running; Please do not shutdown\n');
fprintf("-----------------------------------------------------------------------------------------\n\n");
% Update Generation
currentGeneration = currentGeneration + 1;
end
cprintf('*[0.4,0.8,0.5]', '----------Completion (%%) = 100 %%----------\n');
cprintf('*blue', 'Simulation completed\n');
fprintf("-----------------------------------------------------------------------------------------\n\n");
diary outputfile