-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathConnectionGene.py
72 lines (58 loc) · 2.45 KB
/
ConnectionGene.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
#!/usr/bin/env python3
import random
from NEATConfiguration import NEATConfiguration as config
from NodeGene import Node, NodeGene
class ConnectionGene:
""" NEAT's abstract neural network connection gene """
precision = config.precision
min_weight = config.minimum_weight
max_weight = config.maximum_weight
def __init__(self,
in_node: int,
out_node: int,
weight: float=None,
innv: int=None,
disabled: bool=False):
self.incoming = in_node
self.outgoing = out_node
self.weight = weight
self.disabled = disabled
self.innv = innv # inovation number(historical mark)
if (weight == None):
self.perturb_weight(randomize=True)
@staticmethod
def Copy(conn):
return ConnectionGene(conn.incoming,
conn.outgoing,
conn.weight,
conn.innv,
conn.disabled,)
def normalize_weight(self, min: int=-1.0, max: int=1.0):
""" normalizes the weight of the connection between min and max"""
self.weight = max if (self.weight > max) else \
min if (self.weight < min) else \
self.weight
def perturb_weight(self, randomize:bool=False):
""" Perturb the weight of the connection.
if randomize is set to True, the weight is completely randomized.
"""
if (randomize):
self.weight = random.uniform(ConnectionGene.min_weight,
ConnectionGene.max_weight)
else:
self.weight += random.uniform(ConnectionGene.min_weight/2,
ConnectionGene.max_weight/2)
# normalize the weight
self.normalize_weight(ConnectionGene.min_weight,
ConnectionGene.max_weight)
self.weight = round(self.weight, ConnectionGene.precision)
def __repr__(self):
""" For debugging purposes.. use pprint.pprint to print the connection"""
return f"ConnectionGene({self.incoming}, " + \
f"{self.outgoing}, " + \
f"{self.weight}, " + \
f"{self.innv}, " + \
f"{self.disabled})"
def __str__(self):
""" For hashing purposes.. """
return f"{self.incoming:07.0f}:{self.outgoing:07.0f}"