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 the web server of fourmilab. Based on atmospheric noise.  The motivation is to support biosimulations that rely on random numbers. 
 7  """ 
 8   
 9  import urllib 
10   
11   
12 -def hex_convert(text):
13 import warnings 14 warnings.warn("The function Bio.HotRand.hex_convert is deprecated. Instead of Bio.HotRand.hex_convert(text), please use int(text, 16) instead", DeprecationWarning) 15 return int(text, 16)
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 -class HotCache:
27
28 - def __init__( self ):
29 # self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1' 30 self.url = 'http://www.random.org/cgi-bin/randbyte?' 31 self.query = { 'nbytes' : 128, 'fmt' : 'h' } 32 self.fill_hot_cache()
33
34 - def fill_hot_cache( self ):
35 url = self.url + urllib.urlencode( self.query ) 36 fh = urllib.urlopen( url ) 37 self.hot_cache = fh.read() 38 fh.close()
39
40 - def next_num( self, num_digits = 4 ):
41 cache = self.hot_cache 42 numbytes = num_digits / 2 43 if( len( cache ) % numbytes != 0 ): 44 print 'len_cache is %d' % len( cache ) 45 raise ValueError 46 if( cache == '' ): 47 self.fill_hot_cache() 48 cache = self.hot_cache 49 hexdigits = cache[ :numbytes ] 50 self.hot_cache = cache[ numbytes: ] 51 return byte_concat( hexdigits )
52 53 54
55 -class HotRandom:
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