-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.hpp
93 lines (82 loc) · 1.85 KB
/
utils.hpp
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
#pragma once
#include "Solution.hpp"
#include <cassert>
#include <limits>
#include <random>
using namespace std;
ostream& operator<<(ostream& os, const vector<double>& obj)
{
for (double d : obj) {
os << d << " ";
}
return os;
}
class Mutate {
public:
double v1, mutationChance;
random_device dev;
uniform_real_distribution<double> chooser;
normal_distribution<double> dis1, dis2;
Mutate(double s1, double s2, double v1, double mutate)
: v1{ v1 }
, mutationChance{ mutate }
{
chooser = uniform_real_distribution<double>(0, 1);
dis1 = normal_distribution<double>(0, s1);
dis2 = normal_distribution<double>(0, s2);
};
void operator()(vector<double>& c)
{
if (chooser(dev) < v1) {
for (unsigned int i = 0; i < c.size(); ++i) {
if (chooser(dev) < mutationChance) {
c[i] += dis1(dev);
}
}
} else {
for (unsigned int i = 0; i < c.size(); ++i) {
if (chooser(dev) < mutationChance) {
c[i] = dis2(dev);
}
}
}
};
};
void scaleFitness(vector<Solution>& pop, Solution& best)
{
double sum = 0,
min = std::numeric_limits<double>::max();
if (best.sol.size() == 0) {
best = pop.front();
}
for (auto& s : pop) {
// cout << "s.err: " << s.err << endl;
// cout << "best.err: " << (*best)->err << endl;
if (s.err < best.err) {
best = s;
}
sum += s.fit;
if (s.fit < min) {
min = s.fit;
}
}
sum -= min * pop.size();
for (auto& s : pop) {
s.fit -= min;
s.fit /= sum;
// cout << "s.fit: " << s.fit << endl;
}
}
const Solution& select(const vector<Solution>& pop)
{
static random_device dev;
static auto dis = uniform_real_distribution<double>(0, 1);
double ch = dis(dev);
for (auto& p : pop) {
ch -= p.fit;
if (ch < 0) {
return p;
}
}
return pop.back();
}