Fun

475 days ago by akosednar

from scipy.optimize import leastsq import urllib2 as U import scipy.stats as Stat import time current_year = time.localtime().tm_year co2data = U.urlopen('ftp://ftp.cmdl.noaa.gov/ccg/co2/trends/co2_mm_mlo.txt').readlines() datalines = [] for a_line in co2data: if a_line.find('Creation:') != -1: cdate = a_line if a_line[0] != '#': temp = a_line.replace('\n','').split(' ') temp = [float(q) for q in temp if q != ''] datalines.append(temp) npi = RDF(pi) @interact(layout=[['start_date'],['end_date'],['show_linear_fit','show_nonlinear_fit']]) def mauna_loa_co2(start_date = slider(1958,current_year,1,1958), end_date = slider(1958, current_year,1,current_year-1), show_linear_fit = checkbox(default=True), show_nonlinear_fit = checkbox(default=False)): htmls1 = '<h3>CO2 monthly averages at Mauna Loa (interpolated), from NOAA/ESRL data</h3>' htmls2 = '<h4>'+cdate+'</h4>' html(htmls1+htmls2) sel_data = [[q[2],q[4]] for q in datalines if start_date < q[2] < end_date] outplot = list_plot(sel_data, plotjoined=True, rgbcolor=(1,0,0)) if show_nonlinear_fit: def powerlaw(t,a): return sel_data[0][1] + a[0]*(t-sel_data[0][0])^(a[1]) def res_fun(a): return [q[1]-powerlaw(q[0],a) for q in sel_data] def fitcos(t,a): return a[0]*cos(t*2*npi+a[1])+a[2]*cos(t*4*npi+a[3]) def res_fun2(a): return [q[1]-fitcos(q[0],a) for q in resids] a1 = leastsq(res_fun,[1/2.4,1.3])[0] resids = [[q[0],q[1] - powerlaw(q[0],a1)] for q in sel_data] a2 = leastsq(res_fun2, [3,0,1,0])[0] r2_plot = list_plot([[q[0],powerlaw(q[0],a1)+fitcos(q[0],a2)] for q in resids], rgbcolor='green',plotjoined=True) outplot = outplot + r2_plot var('t') formula1 = '%.2f+%.2f(t - %d)^%.2f'%(sel_data[0][1],a1[0],sel_data[0][0],a1[1]) formula2 = '%.2fcos(2 pi t + %.2f)+%.2f cos(4 pi t + %.2f)'%(a2[0],a2[1],a2[2],a2[3]) html('Nonlinear fit: <br>%s<br>'%(formula1+'+'+formula2)) if show_linear_fit: slope, intercept, r, ttprob, stderr = Stat.linregress(sel_data) outplot = outplot + plot(slope*x+intercept,start_date,end_date) html('Linear regression slope: %.2f ppm/year; correlation coefficient: %.2f'%(slope,r)) var('x,y') c_max = max([q[1] for q in sel_data]) c_min = min([q[1] for q in sel_data]) show(outplot, xmin = start_date, ymin = c_min-2, axes = True, xmax = end_date, ymax = c_max+3, frame = False) 
       

Click to the left again to hide and once more to show the dynamic interactive window

import urllib2, csv months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'] longmonths = ['January','February','March','April','May','June','July','August','September','October','November','December'] @interact def iceplotter(month = selector(zip(range(1,13),longmonths),default = (4, 'April'),label="Month")): month_str = months[month-1] + '/N_%02d_area.txt'%(month) dialect=csv.excel dialect.skipinitialspace = True icedata_f = urllib2.urlopen('ftp://sidads.colorado.edu/DATASETS/NOAA/G02135/%s'%month_str) cr = csv.reader(icedata_f,delimiter=' ', dialect=dialect) icedata = list(cr) icedata = [x for x in icedata[1:] if len(x)==6 and N(x[5])>0] lp = list_plot([[N(x[0]),N(x[4])] for x in icedata]) def lin_regress(xdata, ydata): xmean = N(mean(xdata)) ymean = N(mean(ydata)) xm = vector(RDF,[q-xmean for q in xdata]) ym = vector(RDF,[q-ymean for q in ydata]) xy = xm.inner_product(ym) xx = xm.inner_product(xm) slope = xy/xx intercept = ymean - slope*xmean return slope, intercept years = [N(x[0]) for x in icedata] ice = [N(x[4]) for x in icedata] slope, inter = lin_regress(years,ice) reg = plot(lambda x:slope*x+inter,(min(years),max(years))) html('<h3>Extent of Arctic sea ice coverage in %s, %d - %d</h3>'%(longmonths[month-1],min(years),max(years))) html('Data from the <a href="http://nsidc.org/">National Snow and Ice Data Center</a>') show(lp+reg, figsize = [7,4]) 
       

Click to the left again to hide and once more to show the dynamic interactive window

@interact def _(N=(100,(2..2000))): html("<font color='red'>$\pi(x)$</font> and <font color='blue'>$x/(\log(x)-1)$</font> for $x < %s$"%N) show(plot(prime_pi, 0, N, rgbcolor='red') + plot(x/(log(x)-1), 5, N, rgbcolor='blue')) 
       

Click to the left again to hide and once more to show the dynamic interactive window

@interact def diffie_hellman(bits=slider(8, 513, 4, 8, 'Number of bits', False), button=selector(["Show new example"],label='',buttons=True)): maxp = 2 ^ bits p = random_prime(maxp) k = GF(p) if bits > 100: g = k(2) else: g = k.multiplicative_generator() a = ZZ.random_element(10, maxp) b = ZZ.random_element(10, maxp) print """ <html> <style> .gamodp, .gbmodp { color:#000; padding:5px } .gamodp { background:#846FD8 } .gbmodp { background:#FFFC73 } .dhsame { color:#000; font-weight:bold } </style> <h2 style="color:#000;font-family:Arial, Helvetica, sans-serif">%s-Bit Diffie-Hellman Key Exchange</h2> <ol style="color:#000;font-family:Arial, Helvetica, sans-serif"> <li>Alice and Bob agree to use the prime number p = %s and base g = %s.</li> <li>Alice chooses the secret integer a = %s, then sends Bob (<span class="gamodp">g<sup>a</sup> mod p</span>):<br/>%s<sup>%s</sup> mod %s = <span class="gamodp">%s</span>.</li> <li>Bob chooses the secret integer b=%s, then sends Alice (<span class="gbmodp">g<sup>b</sup> mod p</span>):<br/>%s<sup>%s</sup> mod %s = <span class="gbmodp">%s</span>.</li> <li>Alice computes (<span class="gbmodp">g<sup>b</sup> mod p</span>)<sup>a</sup> mod p:<br/>%s<sup>%s</sup> mod %s = <span class="dhsame">%s</span>.</li> <li>Bob computes (<span class="gamodp">g<sup>a</sup> mod p</span>)<sup>b</sup> mod p:<br/>%s<sup>%s</sup> mod %s = <span class="dhsame">%s</span>.</li> </ol></html> """ % (bits, p, g, a, g, a, p, (g^a), b, g, b, p, (g^b), (g^b), a, p, (g^ b)^a, g^a, b, p, (g^a)^b) 
       

Click to the left again to hide and once more to show the dynamic interactive window

html('<h1>A Random Walk</h1>') vv = []; nn = 0 @interact def foo(pts = checkbox(True, "Show points"), refresh = checkbox(False, "New random walk every time"), steps = (50,(10..500))): # We cache the walk in the global variable vv, so that # checking or unchecking the points checkbox doesn't change # the random walk. html("<h2>%s steps</h2>"%steps) global vv if refresh or len(vv) == 0: s = 0; v = [(0,0)] for i in range(steps): s += random() - 0.5 v.append((i, s)) vv = v elif len(vv) != steps: # Add or subtract some points s = vv[-1][1]; j = len(vv) for i in range(steps - len(vv)): s += random() - 0.5 vv.append((i+j,s)) v = vv[:steps] else: v = vv L = line(v, rgbcolor='#4a8de2') if pts: L += points(v, pointsize=10, rgbcolor='red') show(L, xmin=0, figsize=[8,3]) 
       

Click to the left again to hide and once more to show the dynamic interactive window

m = hmm.DiscreteHiddenMarkovModel([[0.8,0.2],[0.1,0.9]], [[1/10,1/10,1/10,1/10,1/10,1/2],[1/6,1/6,1/6,1/6,1/6,1/6]], [.2,.8],emission_symbols=[1,2,3,4,5,6]) @interact def dishonest_casino(auto_update=False): test = list(m.generate_sequence(80)) vit_test = list(m.viterbi(test[0])[0]) html('<h3>The Occasionally Dishonest Casino</h3>') html('Emissions:'+str(test[0]).replace(',','').replace(' ','')[1:-1]) vit_str = str(vit_test).replace(',','').replace(' ','') vit_str = vit_str.replace('1','F').replace('0','<font color="#FF0000">L</font>')[1:-1] html('Viterbi: '+vit_str) actual_str = str(list(test[1])).replace(',','').replace(' ','') actual_str = actual_str.replace('1','F').replace('0','<font color="#FF0000">L</font>')[1:-1] html('Actual: '+ actual_str) 
       

Click to the left again to hide and once more to show the dynamic interactive window