-
Notifications
You must be signed in to change notification settings - Fork 1
/
mutation.py
75 lines (64 loc) · 1.63 KB
/
mutation.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
from random import randint
from random import sample
from copy import deepcopy
import random
def template_mutation(individual):
"""[summary]
Args:
individual ([type]): [description]
Returns:
[type]: [description]
"""
return individual
def swap_mutation(individual):
"""
Parameters
----------
individual : TYPE
DESCRIPTION.
Returns
-------
tmp : TYPE
DESCRIPTION.
"""
# Position of the start and end substring
mut_points = sample(range(len(individual)),2)
i = deepcopy(individual)
i[mut_points[0]], i[mut_points[1]] = i[mut_points[1]], i[mut_points[0]]
return i
def inversion_mutation(individual):
"""
Parameters
----------
individual : TYPE
DESCRIPTION.
Returns
-------
i : TYPE
DESCRIPTION.
"""
# Position of the start and end substring
mut_points = sample(range(len(individual)), 2)
i = deepcopy(individual)
# This method assumes that the second point is after the first one.
mut_points.sort()
# Invert for the mutation
i[mut_points[0]:mut_points[1]]= i[mut_points[0]:mut_points[1]][::-1]
return i
def shuffle_mutation(individual):
"""
Parameters
----------
individual : TYPE
DESCRIPTION.
Returns
-------
i : TYPE
DESCRIPTION.
"""
# Position of the start and end substring
mut_points = sample(range(len(individual)),2)
mut_points.sort()
i = deepcopy(individual)
i[mut_points[0]:mut_points[1]] = sorted(i[mut_points[0]:mut_points[1]], key=lambda x: random.random())
return i