refactoring genes
[experiments.git] / evolution / utils.py
1
2
3 import logging
4 import math
5 import time
6
7 class Clock:
8 def __init__(self, delay):
9 self.delay = delay
10 self._tick = 0
11
12 def tick(self):
13 time.sleep(self.delay)
14 self._tick += 1
15
16 def getTick(self):
17 return self._tick
18
19
20 class SceneLogger(logging.LoggerAdapter):
21 def __init__(self, scene):
22 super(SceneLogger, self).__init__(logging.getLogger(scene.name), {})
23 self.scene = scene
24
25 def process(self, msg, kwargs):
26 return '[%8d] %s' % (self.scene.clock.getTick(), msg), kwargs
27
28
29 class Vector:
30 def __init__(self, *data):
31 self.data = list(data)
32
33 def __repr__(self):
34 return repr(self.data)
35
36 def __add__(self, other):
37 return Vector(*map(lambda x, y: x+y, self, other))
38
39 def __sub__(self, other):
40 return Vector(*map(lambda x, y: x-y, self, other))
41
42 def __mul__(self, other):
43 return Vector(*map(lambda x: x*other, self))
44
45 def __getitem__(self, index):
46 return self.data[index]
47
48 def __len__(self):
49 return len(self.data)
50
51 def magnitude(self):
52 return math.sqrt(sum(map(lambda x:x**2, self.data)))
53
54 def normalize(self):
55 magnitude = self.magnitude()
56 if magnitude:
57 return Vector(*map(lambda x: x/magnitude, self))
58 return Vector(*map(lambda x: 0, self))
59
60