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  import urllib 
12  from Bio import BiopythonDeprecationWarning 
13  import warnings 
14  warnings.warn("The HotRand module is deprecated and likely to be removed in a future release of Biopython. Please use an alternative RNG.", BiopythonDeprecationWarning) 
15   
16   
17 -def byte_concat( text ):
18 val = 0 19 numbytes = len( text ) 20 for i in range( 0, numbytes ): 21 val = val * 256 22 val = val + ord( text[ i ] ) 23 24 return val
25 26
27 -class HotCache(object):
28
29 - def __init__( self ):
30 # self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1' 31 self.url = 'http://www.random.org/cgi-bin/randbyte?' 32 self.query = { 'nbytes': 128, 'fmt': 'h' } 33 self.fill_hot_cache()
34
35 - def fill_hot_cache( self ):
36 url = self.url + urllib.urlencode( self.query ) 37 fh = urllib.urlopen( url ) 38 self.hot_cache = fh.read() 39 fh.close()
40
41 - def next_num( self, num_digits = 4 ):
42 cache = self.hot_cache 43 numbytes = num_digits / 2 44 if( len( cache ) % numbytes != 0 ): 45 print 'len_cache is %d' % len( cache ) 46 raise ValueError 47 if( cache == '' ): 48 self.fill_hot_cache() 49 cache = self.hot_cache 50 hexdigits = cache[ :numbytes ] 51 self.hot_cache = cache[ numbytes: ] 52 return byte_concat( hexdigits )
53 54
55 -class HotRandom(object):
56
57 - def __init__( self ):
58 self.hot_cache = HotCache( )
59
60 - def hot_rand( self, high, low = 0 ):
61 span = high - low 62 val = self.hot_cache.next_num() 63 val = ( span * val ) >> 16 64 val = val + low 65 return val
66 67 68 if( __name__ == '__main__' ): 69 hot_random = HotRandom() 70 for j in range( 0, 130 ): 71 print hot_random.hot_rand( 25 ) 72 nums = [ '0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff' ] 73 for num in nums: 74 print hex_convert( num ) 75