-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgene.py
More file actions
107 lines (83 loc) · 2.71 KB
/
gene.py
File metadata and controls
107 lines (83 loc) · 2.71 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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import random
import datetime
import math
maxnumber=500
class DNA(object):
def __init__(self):
random.seed(datetime.datetime.now())
self.gene=random.randint(0,maxnumber)
def setGene(self, number):
self.gene=number
#By How much percentage is the timeAPP greater than timeOr
def fitness(self, timeApp, timeOr):
diff=timeApp-timeOr
rateofdiff=diff/timeApp
return rateofdiff
# Val value of
def RetVal(self, a1, b, val):
# y=0
# y=a*x+b
y = a1 * val + b
return y
def crossover(self, partnergene,a,b):
child=[]
owngene=self.gene
partg=partnergene
#diff=math.fabs(owngene-partg)
newchild1=a*owngene+b
newchild12=a*partg+b
#print(str(newchild1)+" "+str(newchild12))
diff=math.fabs(newchild1-newchild12)
owngeneStr = str(newchild1)
partgStr = str(newchild12)
#pad with zeros in case one is less than the other
if(len(owngeneStr)>len(partgStr)):
diff=len(owngeneStr)-len(partgStr)
tempdiff=diff+len(partgStr)
for i in range(len(partgStr), len(owngeneStr)):
partgStr+="0"
else:
if (len(partgStr) > len(owngeneStr)):
for i in range(len(owngeneStr), len(partgStr)):
owngeneStr+="0"
midpoint=random.randint(0,len(owngeneStr))
for i in range(0, len(owngeneStr)):
if(i > midpoint):
child.append(owngeneStr[i])
else:
if(i >= len(partgStr)):
child.append(0)
else:
child.append(partgStr[i])
stemo=map(str,child)
stemo=''.join(stemo)
if stemo.count('.') > 1:
tmps=stemo.split(".")
stemo=tmps[0]
kid=DNA()
somenum=random.random()
if(somenum<0.3):
stemo = math.fabs(float(stemo) + diff)
else:
stemo = math.fabs(float(stemo) - diff)
stemo=math.ceil(float(stemo))
print(stemo)
kid.setGene(int(stemo))
return kid
def mutate(self, mutationRate ):
kidgene=self.gene
kidgeneStr=str(kidgene)
newgene=[]
for i in range(0, len(kidgeneStr)):
somenum=random.random()
if(somenum < mutationRate):
#mutate current num
temnum=str(random.randint(0,9))
newgene.append(temnum)
else:
newgene.append(kidgeneStr[i])
mapNum=map(str, newgene)
mapNum=''.join(mapNum)
newKid=DNA()
newKid.setGene(int(mapNum))
return newKid