forked from ArztSamuel/Applying_EANNs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
EvolutionManager.cs
345 lines (291 loc) · 12.3 KB
/
EvolutionManager.cs
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
/// Author: Samuel Arzt
/// Date: March 2017
#region Includes
using UnityEngine;
using System.Collections.Generic;
using System;
using System.IO;
#endregion
/// <summary>
/// Singleton class for managing the evolutionary processes.
/// </summary>
public class EvolutionManager : MonoBehaviour
{
#region Members
private static System.Random randomizer = new System.Random();
public static EvolutionManager Instance
{
get;
private set;
}
// Whether or not the results of each generation shall be written to file, to be set in Unity Editor
[SerializeField]
private bool SaveStatistics = false;
private string statisticsFileName;
// How many of the first to finish the course should be saved to file, to be set in Unity Editor
[SerializeField]
private uint SaveFirstNGenotype = 1;
private uint genotypesSaved = 0;
// Population size, to be set in Unity Editor
[SerializeField]
private int PopulationSize = 3;
// After how many generations should the genetic algorithm be restart (0 for never), to be set in Unity Editor
[SerializeField]
private int RestartAfter = 0;
// Whether to use elitist selection or remainder stochastic sampling, to be set in Unity Editor
[SerializeField]
private bool ElitistSelection = false;
// Topology of the agent's FNN, to be set in Unity Editor
[SerializeField]
private uint[] FNNTopology;
// The current population of agents.
private List<Agent> agents = new List<Agent>();
/// <summary>
/// The amount of agents that are currently alive.
/// </summary>
public int AgentsAliveCount
{
get;
private set;
}
/// <summary>
/// Event for when all agents have died.
/// </summary>
public event System.Action AllAgentsDied;
private GeneticAlgorithm geneticAlgorithm;
/// <summary>
/// The age of the current generation.
/// </summary>
public uint GenerationCount
{
get { return geneticAlgorithm.GenerationCount; }
}
#endregion
/// <summary>
/// Returns the time in seconds since the start of the current generation.
/// </summary>
public float CurrentGenerationTime
{
get { return geneticAlgorithm.timeInterval; }
}
#region Constructors
void Awake()
{
if (Instance != null)
{
Debug.LogError("More than one EvolutionManager in the Scene.");
return;
}
Instance = this;
}
#endregion
#region Methods
/// <summary>
/// Starts the evolutionary process.
/// </summary>
public void StartEvolution()
{
Debug.Log("Starting Evolution");
//Create neural network to determine parameter count
NeuralNetwork nn = new NeuralNetwork(FNNTopology);
//Setup genetic algorithm
geneticAlgorithm = new GeneticAlgorithm((uint) nn.WeightCount, (uint) PopulationSize);
genotypesSaved = 0;
geneticAlgorithm.Evaluation = StartEvaluation;
if (ElitistSelection)
{
//Second configuration
geneticAlgorithm.Selection = GeneticAlgorithm.DefaultSelectionOperator;
geneticAlgorithm.Recombination = RandomRecombination;
geneticAlgorithm.Mutation = MutateAllButBestTwo;
Debug.Log("Using elitist selection");
}
else
{
//First configuration
geneticAlgorithm.Selection = RemainderStochasticSampling;
geneticAlgorithm.Recombination = RandomRecombination;
geneticAlgorithm.Mutation = MutateAllButBestTwo;
Debug.Log("Using remainder stochastic sampling");
}
AllAgentsDied += geneticAlgorithm.EvaluationFinished;
//Statistics
if (SaveStatistics)
{
statisticsFileName = "Evaluation - " + GameStateManager.Instance.TrackName + " " + DateTime.Now.ToString("yyyy_MM_dd_HH-mm-ss");
WriteStatisticsFileStart();
geneticAlgorithm.FitnessCalculationFinished += WriteStatisticsToFile;
Debug.Log("Saving statistics to file");
}
geneticAlgorithm.FitnessCalculationFinished += CheckForTrackFinished;
//Restart logic
if (RestartAfter > 0)
{
geneticAlgorithm.TerminationCriterion += CheckGenerationTermination;
geneticAlgorithm.AlgorithmTerminated += OnGATermination;
Debug.Log("Restarting genetic logic after " + RestartAfter + " generations");
}
geneticAlgorithm.Start();
}
// Writes the starting line to the statistics file, stating all genetic algorithm parameters.
private void WriteStatisticsFileStart()
{
File.WriteAllText(statisticsFileName + ".txt", "Evaluation of a Population with size " + PopulationSize +
", on Track \"" + GameStateManager.Instance.TrackName + "\", using the following GA operators: " + Environment.NewLine +
"MaxCheckpointDelay: " + Environment.NewLine +
"Selection: " + geneticAlgorithm.Selection.Method.Name + Environment.NewLine +
"Recombination: " + geneticAlgorithm.Recombination.Method.Name + Environment.NewLine +
"Mutation: " + geneticAlgorithm.Mutation.Method.Name + Environment.NewLine +
"FitnessCalculation: " + geneticAlgorithm.FitnessCalculationMethod.Method.Name + Environment.NewLine + Environment.NewLine);
}
// Appends the current generation count and the evaluation of the best genotype to the statistics file.
private void WriteStatisticsToFile(IEnumerable<Genotype> currentPopulation)
{
foreach (Genotype genotype in currentPopulation)
{
File.AppendAllText(statisticsFileName + ".txt", geneticAlgorithm.GenerationCount + "\t" + genotype.Evaluation + Environment.NewLine);
break; //Only write first
}
}
// Checks the current population and saves genotypes to a file if their evaluation is greater than or equal to 1
private void CheckForTrackFinished(IEnumerable<Genotype> currentPopulation)
{
if (genotypesSaved >= SaveFirstNGenotype) return;
string saveFolder = statisticsFileName + "/";
foreach (Genotype genotype in currentPopulation)
{
if (genotype.Evaluation >= 1)
{
Directory.CreateDirectory(saveFolder);
File.WriteAllText(saveFolder + "Genotype " + genotypesSaved + ".txt", genotype.ToString());
genotypesSaved++;
}
}
}
// Checks whether the termination criterion of generation count was met.
private bool CheckGenerationTermination(IEnumerable<Genotype> currentPopulation)
{
Debug.Log("Generation count: " + geneticAlgorithm.GenerationCount);
return geneticAlgorithm.GenerationCount >= RestartAfter;
}
// To be called when the genetic algorithm was terminated
private void OnGATermination(GeneticAlgorithm ga)
{
AllAgentsDied -= ga.EvaluationFinished;
Debug.Log("Evolution algorithm terminated after " + ga.GenerationCount + " generations.");
RestartAlgorithm(5.0f);
}
// Restarts the algorithm after a specific wait time second wait
private void RestartAlgorithm(float wait)
{
Invoke("StartEvolution", wait);
Debug.Log("Restarting evolution algorithm in " + wait + " seconds.");
}
// Starts the evaluation by first creating new agents from the current population and then restarting the track manager.
private void StartEvaluation(IEnumerable<Genotype> currentPopulation)
{
//Create new agents from currentPopulation
agents.Clear();
AgentsAliveCount = 0;
foreach (Genotype genotype in currentPopulation)
agents.Add(new Agent(genotype, MathHelper.SoftSignFunction, FNNTopology));
TrackManager.Instance.SetCarAmount(agents.Count);
IEnumerator<CarController> carsEnum = TrackManager.Instance.GetCarEnumerator();
for (int i = 0; i < agents.Count; i++)
{
if (!carsEnum.MoveNext())
{
Debug.LogError("Cars enum ended before agents.");
break;
}
carsEnum.Current.Agent = agents[i];
AgentsAliveCount++;
agents[i].AgentDied += OnAgentDied;
}
Debug.Log("Restarting track with: " + AgentsAliveCount + " agents alive.");
TrackManager.Instance.Restart();
}
// Callback for when an agent died.
private void OnAgentDied(Agent agent)
{
// Debug.Log("Agent died");
AgentsAliveCount--;
if (AgentsAliveCount == 0 && AllAgentsDied != null)
AllAgentsDied();
}
#region GA Operators
// Selection operator for the genetic algorithm, using a method called remainder stochastic sampling.
private List<Genotype> RemainderStochasticSampling(List<Genotype> currentPopulation)
{
List<Genotype> intermediatePopulation = new List<Genotype>();
//Put integer portion of genotypes into intermediatePopulation
//Assumes that currentPopulation is already sorted
foreach (Genotype genotype in currentPopulation)
{
if (genotype.Fitness < 1)
break;
else
{
for (int i = 0; i < (int)genotype.Fitness; i++)
intermediatePopulation.Add(new Genotype(genotype.GetParameterCopy()));
}
}
//Put remainder portion of genotypes into intermediatePopulation
foreach (Genotype genotype in currentPopulation)
{
float remainder = genotype.Fitness - (int)genotype.Fitness;
if (randomizer.NextDouble() < remainder)
intermediatePopulation.Add(new Genotype(genotype.GetParameterCopy()));
}
return intermediatePopulation;
}
// Recombination operator for the genetic algorithm, recombining random genotypes of the intermediate population
private List<Genotype> RandomRecombination(List<Genotype> intermediatePopulation, uint newPopulationSize)
{
//Check arguments
if (intermediatePopulation.Count < 2)
throw new System.ArgumentException("The intermediate population has to be at least of size 2 for this operator.");
List<Genotype> newPopulation = new List<Genotype>();
//Always add best two (unmodified)
newPopulation.Add(intermediatePopulation[0]);
newPopulation.Add(intermediatePopulation[1]);
while (newPopulation.Count < newPopulationSize)
{
//Get two random indices that are not the same
int randomIndex1 = randomizer.Next(0, intermediatePopulation.Count), randomIndex2;
do
{
randomIndex2 = randomizer.Next(0, intermediatePopulation.Count);
} while (randomIndex2 == randomIndex1);
Genotype offspring1, offspring2;
GeneticAlgorithm.CompleteCrossover(intermediatePopulation[randomIndex1], intermediatePopulation[randomIndex2],
GeneticAlgorithm.DefCrossSwapProb, out offspring1, out offspring2);
newPopulation.Add(offspring1);
if (newPopulation.Count < newPopulationSize)
newPopulation.Add(offspring2);
}
Debug.Log("New population size: " + newPopulation.Count);
return newPopulation;
}
// Mutates all members of the new population with the default probability, while leaving the first 2 genotypes in the list untouched.
private void MutateAllButBestTwo(List<Genotype> newPopulation)
{
for (int i = 2; i < newPopulation.Count; i++)
{
if (randomizer.NextDouble() < GeneticAlgorithm.DefMutationPerc)
GeneticAlgorithm.MutateGenotype(newPopulation[i], GeneticAlgorithm.DefMutationProb, GeneticAlgorithm.DefMutationAmount);
}
}
// Mutates all members of the new population with the default parameters
private void MutateAll(List<Genotype> newPopulation)
{
foreach (Genotype genotype in newPopulation)
{
if (randomizer.NextDouble() < GeneticAlgorithm.DefMutationPerc)
GeneticAlgorithm.MutateGenotype(genotype, GeneticAlgorithm.DefMutationProb, GeneticAlgorithm.DefMutationAmount);
Debug.Log("Mutated genotype to default" + genotype);
}
}
#endregion
#endregion
}