Package Bio :: Module HotRand
[hide private]
[frames] | no frames]

Source Code for Module Bio.HotRand

 1  # Copyright 2002 by Katharine Lindner.  All rights reserved. 
 2  # This code is part of the Biopython distribution and governed by its 
 3  # license.  Please see the LICENSE file that should have been included 
 4  # as part of this package. 
 5   
 6  """handles true random numbers supplied from the web server of 
 7     fourmilab. Based on atmospheric noise.  The motivation is to 
 8     support biosimulations that rely on random numbers. 
 9  """ 
10   
11  from __future__ import print_function 
12   
13  #Importing these functions with leading underscore as not intended for reuse 
14  from Bio._py3k import urlopen as _urlopen 
15  from Bio._py3k import urlencode as _urlencode 
16   
17  from Bio import BiopythonDeprecationWarning 
18  import warnings 
19  warnings.warn("The HotRand module is deprecated and likely to be removed in a future release of Biopython. Please use an alternative RNG.", BiopythonDeprecationWarning) 
20   
21   
22 -def byte_concat(text):
23 val = 0 24 numbytes = len(text) 25 for i in range(0, numbytes): 26 val = val * 256 27 # Slice trick for Python 2 and 3 to get single char (byte) string: 28 val += ord(text[i:i+1]) 29 return val
30 31
32 -class HotCache(object):
33
34 - def __init__( self ):
35 # self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1' 36 self.url = 'http://www.random.org/cgi-bin/randbyte?' 37 self.query = {'nbytes': 128, 'fmt': 'h'} 38 self.fill_hot_cache()
39
40 - def fill_hot_cache(self):
41 url = self.url + _urlencode(self.query) 42 fh = _urlopen(url) 43 self.hot_cache = fh.read() 44 fh.close()
45
46 - def next_num(self, num_digits=4):
47 cache = self.hot_cache 48 # Must explicitly use integer division on python 3 49 numbytes = num_digits // 2 50 if len(cache) % numbytes != 0: 51 print('len_cache is %d' % len(cache)) 52 raise ValueError 53 if cache == '': 54 self.fill_hot_cache() 55 cache = self.hot_cache 56 hexdigits = cache[:numbytes] 57 self.hot_cache = cache[numbytes:] 58 return byte_concat(hexdigits)
59 60
61 -class HotRandom(object):
62
63 - def __init__(self):
64 self.hot_cache = HotCache( )
65
66 - def hot_rand(self, high, low=0):
67 span = high - low 68 val = self.hot_cache.next_num() 69 val = (span * val) >> 16 70 val += low 71 return val
72 73 74 if __name__ == '__main__': 75 hot_random = HotRandom() 76 for j in range(0, 130): 77 print(hot_random.hot_rand(25)) 78 nums = ['0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff'] 79 for num in nums: 80 print(int(num, 16)) 81