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 
 7  atmospheric noise.  The motivation is to support biosimulations that rely on random numbers. 
 8  """ 
 9   
10  import os 
11  import sys 
12  import string 
13  from urllib import FancyURLopener 
14  from urllib import urlencode 
15   
16  from Bio.SGMLExtractor import SGMLExtractorHandle 
17   
18   
19 -def hex_convert( text ):
20 num_val = 0L 21 text = text.lower() 22 for letter in text: 23 hex_digit = string.hexdigits.find( letter ) 24 if( hex_digit < 0 ): 25 raise ValueError 26 num_val = ( num_val * 16 ) + hex_digit 27 return num_val
28
29 -def byte_concat( text ):
30 val = 0 31 numbytes = len( text ) 32 for i in range( 0, numbytes ): 33 val = val * 256 34 val = val + ord( text[ i ] ) 35 36 return val
37
38 -class HotCache:
39
40 - def __init__( self ):
41 # self.url = 'http://www.fourmilab.ch/cgi-bin/uncgi/Hotbits?num=5000&min=1&max=6&col=1' 42 self.url = 'http://www.random.org/cgi-bin/randbyte?' 43 self.query = { 'nbytes' : 128, 'fmt' : 'h' } 44 self.fill_hot_cache()
45
46 - def fill_hot_cache( self ):
47 bases = [ 'a', 'g', 'c', 't' ] 48 url = self.url + urlencode( self.query ) 49 url_opener = FancyURLopener( ) 50 fh = url_opener.open( url ) 51 hot_rand_handle = SGMLExtractorHandle( fh, [ 'pre', ] ) 52 53 hot_cache = fh.read() 54 self.hot_cache = hot_cache 55 fh.close() 56 return self.hot_cache
57
58 - def next_num( self, num_digits = 4 ):
59 cache = self.hot_cache 60 numbytes = num_digits / 2 61 if( len( cache ) % numbytes != 0 ): 62 print 'len_cache is %d' % len( cache ) 63 raise ValueError 64 if( cache == '' ): 65 self.fill_hot_cache() 66 cache = self.hot_cache 67 hexdigits = cache[ :numbytes ] 68 self.hot_cache = cache[ numbytes: ] 69 return byte_concat( hexdigits )
70 71 72
73 -class HotRandom:
74
75 - def __init__( self ):
76 self.hot_cache = HotCache( )
77
78 - def hot_rand( self, high, low = 0 ):
79 span = high - low 80 val = self.hot_cache.next_num() 81 val = ( span * val ) >> 16 82 val = val + low 83 return val
84 85 86 if( __name__ == '__main__' ): 87 hot_random = HotRandom() 88 for j in range ( 0, 130 ): 89 print hot_random.hot_rand( 25 ) 90 nums = [ '0000', 'abcd', '1234', '5555', '4321', 'aaaa', 'ffff' ] 91 for num in nums: 92 print hex_convert( num ) 93