Back to index

python-biopython  1.60
HotRand.py
Go to the documentation of this file.
00001 # Copyright 2002 by Katharine Lindner.  All rights reserved.
00002 # This code is part of the Biopython distribution and governed by its
00003 # license.  Please see the LICENSE file that should have been included
00004 # as part of this package.
00005 
00006 """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.
00007 """
00008 
00009 import urllib
00010 
00011 
00012 def byte_concat( text ):
00013     val = 0
00014     numbytes = len( text )
00015     for i in range( 0, numbytes ):
00016         val = val * 256
00017         val = val + ord( text[ i ] )
00018 
00019     return val
00020 
00021 class HotCache(object):
00022 
00023     def __init__( self  ):
00024 #        self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1'
00025         self.url = 'http://www.random.org/cgi-bin/randbyte?'
00026         self.query = { 'nbytes' : 128, 'fmt' : 'h' }
00027         self.fill_hot_cache()
00028 
00029     def fill_hot_cache( self ):
00030         url = self.url + urllib.urlencode( self.query )
00031         fh = urllib.urlopen( url )
00032         self.hot_cache = fh.read()
00033         fh.close()
00034 
00035     def next_num( self, num_digits = 4 ):
00036         cache = self.hot_cache
00037         numbytes = num_digits / 2
00038         if( len( cache ) % numbytes != 0 ):
00039             print 'len_cache is %d' % len( cache )
00040             raise ValueError
00041         if( cache == '' ):
00042             self.fill_hot_cache()
00043             cache = self.hot_cache
00044         hexdigits = cache[ :numbytes ]
00045         self.hot_cache = cache[ numbytes: ]
00046         return byte_concat( hexdigits )
00047 
00048 
00049 
00050 class HotRandom(object):
00051 
00052     def __init__( self ):
00053         self.hot_cache = HotCache( )
00054 
00055     def hot_rand( self, high, low = 0 ):
00056         span = high - low
00057         val = self.hot_cache.next_num()
00058         val = ( span * val ) >> 16
00059         val = val + low
00060         return val
00061 
00062 
00063 if( __name__ == '__main__' ):
00064     hot_random = HotRandom()
00065     for j in range ( 0, 130 ):
00066         print hot_random.hot_rand( 25 )
00067     nums = [ '0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff' ]
00068     for num in nums:
00069         print hex_convert( num )
00070 
00071 
00072