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 string 
10  import urllib 
11   
12   
13 -def hex_convert( text ):
14 num_val = 0L 15 text = text.lower() 16 for letter in text: 17 hex_digit = string.hexdigits.find( letter ) 18 if( hex_digit < 0 ): 19 raise ValueError 20 num_val = ( num_val * 16 ) + hex_digit 21 return num_val
22
23 -def byte_concat( text ):
24 val = 0 25 numbytes = len( text ) 26 for i in range( 0, numbytes ): 27 val = val * 256 28 val = val + ord( text[ i ] ) 29 30 return val
31
32 -class HotCache:
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 + urllib.urlencode( self.query ) 42 fh = urllib.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 numbytes = num_digits / 2 49 if( len( cache ) % numbytes != 0 ): 50 print 'len_cache is %d' % len( cache ) 51 raise ValueError 52 if( cache == '' ): 53 self.fill_hot_cache() 54 cache = self.hot_cache 55 hexdigits = cache[ :numbytes ] 56 self.hot_cache = cache[ numbytes: ] 57 return byte_concat( hexdigits )
58 59 60
61 -class HotRandom:
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 = 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 hex_convert( num ) 81