1
2
3
4
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
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
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
39
41
42 self.url = 'http://www.random.org/cgi-bin/randbyte?'
43 self.query = { 'nbytes' : 128, 'fmt' : 'h' }
44 self.fill_hot_cache()
45
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
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
74
77
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