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