-
Notifications
You must be signed in to change notification settings - Fork 1
/
randspool.py
57 lines (42 loc) · 1.48 KB
/
randspool.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
from builtins import object
import numpy as np
from functools import reduce
def order2prime(order):
if order == 6:
return 100003
elif order == 5:
return 10007
else:
return int(10**order) + 1
class randspool(object):
def __init__(self, cache_len=64433, genfun=np.random.standard_normal,
order=None):
"""Init new spooler.
cache_len: size to cache. should be prime?
http://www.primos.mat.br/primeiros_10000_primos.txt
"""
if order is not None:
cache_len = order2prime(order)
self.genfun = genfun
self.cache = self._generate(cache_len)
self._index = 0
def _generate(self, cache_len):
return self.genfun(size=(cache_len,))
def get(self, shape=None, copy=False):
N = reduce(np.multiply, shape)
stop_index = self._index + N
if shape is None:
shape = (1,)
if stop_index <= len(self.cache):
res = self.cache[self._index:stop_index]
else:
# only works for a single overrun..
res = np.concatenate([
self.cache[self._index:],
self.cache[:N-(len(self.cache)-self._index)]
])
res = res.reshape(shape)
self._index = np.mod(stop_index, len(self.cache)) # in case of ==
if copy is True:
res = res.copy()
return res