-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGeneticAlgorithm.cpp
More file actions
102 lines (73 loc) · 2.4 KB
/
GeneticAlgorithm.cpp
File metadata and controls
102 lines (73 loc) · 2.4 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
//
// Created by alican on 09.05.2016.
//
#include <iostream>
#include <fstream>
#include "GeneticAlgorithm.h"
void GeneticAlgorithm::run() {
Population p = createBasePopulation();
p.process();
generations.push_back(p);
double fitness = 0.001;
int generation = 0;
while(generation < params.generations){
//p.printChromos();
generation++;
p = p.tournament_selection(generation);
p.crossover_selection(params.crossoverPercent);
p.mutation(params.mutationPercent);
p.process();
p.calcDiversity();
//p.printBestCandidate();
// std::cout << "Min Fitness: " << p.minFitness << std::endl;
// std::cout << "Max Fitness: " << p.maxFitness << std::endl;
generations.push_back(p);
}
generations.back().printBestCandidate();
//resultToFile();
resultAsJson();
}
Population GeneticAlgorithm::createBasePopulation() {
Population base(params.populationSize);
return base;
}
bool GeneticAlgorithm::keepGoing() {
return false;
}
void GeneticAlgorithm::resultAsJson() {
json results;
json min;
json max;
json average;
json diversity;
int generation = 0;
for (auto p : generations){
min.push_back(json::object({{"x", generation},{"y", p.minFitness}}));
max.push_back(json::object({{"x", generation},{"y", p.maxFitness}}));
average.push_back(json::object({{"x", generation},{"y", p.averageFitness}}));
diversity.push_back(json::object({{"x", generation},{"y", p.diversity*100}}));
generation++;
//results.push_back(p.toJson());
}
results["min"] = min;
results["max"] = max;
results["average"] = average;
results["diversity"] = diversity;
std::ofstream myfile ("C:\\Users\\alican\\ClionProjects\\GeneticAlgorithm\\viewer\\results.json");
if (myfile.is_open())
{
myfile << "data = " << results;
myfile.close();
}
}
void GeneticAlgorithm::resultToFile() {
std::ofstream myfile ("C:\\Users\\alican\\ClionProjects\\GeneticAlgorithm\\viewer\\results.tsv");
if (myfile.is_open())
{
myfile << "Generation" << "\t" << "max fitness" << "\t" << "min fitness" << "\t" << "average fitness" << "\n";
for (auto p : generations){
myfile << p.minFitness << "\t" << p.maxFitness << "\t" << p.averageFitness << "\n";
};
myfile.close();
}
}