-
Notifications
You must be signed in to change notification settings - Fork 0
/
test_genetic_algorithm.py
83 lines (62 loc) · 2.56 KB
/
test_genetic_algorithm.py
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
"""
test_genetic_algorithm.py.py: to test Genetic Algorithem class.
"""
import unittest
import numpy as np
from genetic_algorithm import GeneticAlgorithm
__author__ = "Mostafa Rafaie"
__license__ = "APLv2"
class GeneticAlgorithmTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(GeneticAlgorithmTest, self).__init__(*args, **kwargs)
self.path = 'sample_genom_struct.csv'
self.ga = GeneticAlgorithm(self.path)
def test_init_ga(self):
init_population_size = 10
population = self.ga.init_ga(init_population_size)
self.assertEqual(len(population), init_population_size)
self.assertEqual(len(np.unique(population, axis=0)),
init_population_size)
self.assertEqual(population[1, 5], 0)
def test_crossovers(self):
g1 = np.array([1, 2, 3, 4, 5, 0.0])
g2 = np.array([15, 16, 17, 18, 19, 1.0])
g3 = self.ga.do_crossover(GeneticAlgorithm.SINGLE_POINT_CROSSOVER,
g1, g2)
# print(g3)
self.assertEqual(len(g3), 6)
g3 = self.ga.do_crossover(GeneticAlgorithm.TWO_POINT_CROSSOVER,
g1, g2)
# print(g3)
self.assertEqual(len(g3), 6)
g3 = self.ga.do_crossover(GeneticAlgorithm.CUT_SLICE_CROSSOVER,
g1, g2)
# print(g3)
self.assertEqual(len(g3), 6)
g3 = self.ga.do_crossover(GeneticAlgorithm.UNIFORM_CROSSOVER,
g1, g2)
# print(g3)
self.assertEqual(len(g3), 6)
def fitness(g):
return sum(g)
def test_scenario1(self):
population = np.array([[1, 2, 3, 0, 0, 0],
[4, 5, 6, 0, 0, 0],
[7, 8, 9, 0, 0, 0],
[10, 11, 12, 0, 0, 0]], dtype=np.float)
self.ga.evaluate_fitness(population, GeneticAlgorithmTest.fitness)
self.assertEqual(population[0][-1], 6)
self.assertEqual(population[2][-1], 24)
new_population = self.ga.choose_best_population(population, 3)
# print(new_population)
self.assertEqual(len(new_population), 3)
self.assertEqual(new_population[0][-1], 33)
self.assertEqual(new_population[1][-1], 24)
g = self.ga.tournament_selection(new_population)
self.assertTrue(g in new_population)
g1 = self.ga.do_mutate(g)
diff = 0
for i in range(len(g)):
if g[1] != g1[1]:
diff += 1
self.assertTrue(diff <= 1)