def test(self): refrng = rngmodule.rng() mylist = rngmodule.list_available_rngs() for i in mylist: if i == "knuthran2002": continue r = getattr(rngmodule, i)() test = 0 try: assert type(r) == type(refrng) test = 1 finally: if test == 0: print "r = %s %s" % (type(r), repr(r)) print "refrng = %s %s" % (type(refrng), repr(refrng))
def siman_exp(): prepare_distance_matrix() # set up a trivial initial route */ print("# initial order of cities:\n") for city in cities: print city #print " # distance matrix is:" #print_distance_matrix(); mytsp = Tsp() mytsp.SetRoute(numx.arange(n_cities)) mytsp.SetNCities(n_cities) result = siman.solve(rng.rng(), mytsp) route = result.GetRoute() print("# final order of cities:\n") for i in route: print cities[i]
def run(): r = rng.rng() bw = bspline(4, nbreak) # Data to be fitted x = 15. / (N-1) * numx.arange(N) y = numx.cos(x) * numx.exp(0.1 * x) sigma = .1 w = 1.0 / sigma**2 * numx.ones(N) dy = r.gaussian(sigma, N) y = y + dy # use uniform breakpoints on [0, 15] bw.knots_uniform(0.0, 15.0) X = numx.zeros((N, ncoeffs)) for i in range(N): B = bw.eval(x[i]) X[i,:] = B # do the fit c, cov, chisq = multifit.wlinear(X, w, y, multifit.linear_workspace(N, ncoeffs)) # output the smoothed curve res_y = [] res_y_err = [] for i in range(N): B = bw.eval(x[i]) yi, yi_err = multifit.linear_est(B, c, cov) res_y.append(yi) res_y_err.append(yi_err) #print yi, yerr res_y = numx.array(res_y) res_y_err = numx.array(res_y_err) return (x, y,), (x, res_y), res_y_err
for k in trx: sumtr+=k if sumtr>=lk: i=cnt break cnt+=1 return i #################### #Model A import pickle from pygsl import rng as rn SEED=987654321 rk=rn.rng() rk.set(SEED) N=1e3 ao=10 I=[] #Players S=[] #Available tn=0.0 #monte-carlo time Tau=500 #Final time tp=1.0 #print time step na=ao #players 0 I nb=N-ao #non players S nt=[na, nb] #na I, nb nonplayer S
def job(PT, SEED, nte, neff, tn, RXCLRPTS, CRKPTS, TES, nj, gold, Qi): from math import floor from pygsl import rng as rn import sys import gc sys.path.append('../LNKMODEL/') import Lffit import LffitB Np = PT[0] m1 = PT[1] #hgt effs m2 = PT[2] #hgt te m3 = PT[3] #eff recomb m4 = PT[4] #te dup m5 = PT[5] #eff dup+te m6 = PT[6] #eff->null m7 = PT[7] #null ->0 m8 = PT[8] ##eff->0 beta1 = PT[9] beta2 = PT[10] wo = PT[11] #print("parameter vector:"% PT) av1 = 0.5 * (RXCLRPTS[2] - RXCLRPTS[1]) av2 = 0.5 * (CRKPTS[2] - CRKPTS[1]) av3 = 0.5 * (TES[2] - TES[1]) Lth = floor( (RXCLRPTS[0] + CRKPTS[0] + TES[0]) * (1.0 / 3.0) * (av1 + av2 + av3)) #print Lth MU = [Np, m1, m2, m3, m4, m5, m6, m7, m8, Lth, beta1, beta2, wo] Qj = Qi #SEED=987654320 rk = rn.rng() rk.set(SEED) ################ if nj == 0: gen = {} trs = {} gen = Lffit.inigenome(nte, neff, rk, [TES[1], TES[2]], [CRKPTS[1], RXCLRPTS[2]]) #print gen #raw_input() ################ if nj > 0: gen = {} trs = {} k = 0 for i in gold.keys(): gl = [] if gold[i][0] == 'te': gl = [gold[i][0], gold[i][1]] gen[k] = gl k += 1 if gold[i][0] == 'eff': qj = rk.uniform_pos() snew = gold[i][2] + (0.01 * (1.0 - 2.0 * rk.uniform_pos())) if ((qj > Qj) and (snew > 0.0)): gl = [gold[i][0], gold[i][1], snew] else: gl = [gold[i][0], gold[i][1], 0.0] gen[k] = gl k += 1 # print gen # raw_input() ################ Ntot = RXCLRPTS[0] + CRKPTS[0] + TES[0] pqr = {} ltn = [] lth = [] ngt = [] fitn = [] trns = [] flg = 'all-good' for nk in range(tn): trs = Lffit.trates(gen, MU) rij, sr = Lffit.montec(trs, rk) trns.append(rij) if sr != 'TRUE': pqr[nk] = [rij[0], rij[1], gen] ltn.append(Lffit.lent(gen)) lth.append(Lth) #fitn.append(Lffit.ft(gen)) wq = Lffit.ft(gen) fitn.append(1.0 - (wq / (wq + wo))) ngt.append(len(gen.keys())) #del gu gu = {} gu = LffitB.transform(rij, gen, rk, [TES[1], TES[2]], [CRKPTS[1], RXCLRPTS[2]]) del gen gen = {} for i in gu.keys(): gen[i] = gu[i] #gc.collect() else: flg = 'sumzero' break if len(gen.keys()) > 2000: flg = 'limit-reached' break #print("JOB COMPLETED") #print flg gc.collect() return [lth, ltn, ngt, pqr, gen, flg, fitn, trns]
def run(): x_init = np.array([1.0, 1.0, 0.0]) xtol = 1e-8 gtol = 1e-8 ftol = 0 p = 3 n = 40 rng.env_setup() r = rng.rng() t = np.arange(n) x_final = 5., .1 , 1 y = func(x_final, t) s = 0.1 * y dy = np.array(list(map(r.gaussian, s))) y = y + dy weights = 1./((0.1 * y)**2) T = multifit_nlinear.cvar.trust pygsl.add_c_traceback_frames(True) pygsl.set_debug_level(0) params = multifit_nlinear.default_parameters() w = multifit_nlinear.workspace(T, params, n, p) # What a hack w.set_pyobject(w) w.winit(x_init, weights, df= expb_df, f=expb_f, fvv = None, args=y) f = w.residual() chisq0 = np.dot(f, f) #plt.ion() fig = plt.figure() ax = fig.add_subplot(111) ax.clear() ax.errorbar(t, y, yerr=dy) Y = func(x_init, t) line, = ax.plot(t, Y, '-') plt.show(False) plt.draw() max_iter = 200 #status, info = w.driver(200, xtol, gtol, ftol, callback) for step in range(max_iter): x = w.position() print("x = %s" %(x,)) #x = w.x() Y = func(x, t) line.set_data(t, Y) w.iterate() status, info = w.test(xtol, gtol, ftol) fig.canvas.draw() plt.pause(0.5) #ax.figure.clf() if status == errno.GSL_SUCCESS: break elif status == errno.GSL_CONTINUE: continue else: raise ValueError("Unexpected status %d" %(status,)) else: raise ValueError("Did not finish within %d steps" %(max_iter,)) covar = w.covar(0.0) f = w.residual() chisq = np.dot(f, f) dof = n - p c = max(1, np.sqrt(chisq / dof)) reasons = ("small gradient", "small step size") status, info = w.test(xtol, gtol, ftol) print("Summary from method %s/%s" %(w.name(), w.trs_name()) ) print(" number of iterations %d" %(w.niter(),) ) print(" function evaluations %d" %(w.params.fdf.nevalf,)) print(" jacobian evaluations %d" %(w.params.fdf.nevaldf,)) print(" reason for stopping %s" %(reasons[info],)) print(" initial |f(x)| = %f" %(np.sqrt(chisq0),) ) print(" final |f(x)| = %f" %(np.sqrt(chisq),) ) print(" chisq / dof %g" %(chisq / dof) ) x = w.position() x = w.x() print(" A = %.5f +/- %.5f" % ( x[0], c * covar[0,0]) ) print(" lamba = %.5f +/- %.5f" % ( x[1], c * covar[1,1]) ) print(" b = %.5f +/- %.5f" % ( x[2], c * covar[2,2]) ) plt.show()
efflens, telens = Lffit.splitgen(gen) print len(efflens), len(telens) pthl = po + nx if telens or efflens: pdt.savedata(lth, ltn, ngt, efflens, telens, P, SEED, pthl, fitn, trns, nefft, ntest, lnefft, lntest, tn, JMPS) qij.put(gen) ############################################################################### RO = 0 for rnz in range(RO, RUNS): PAR = 9 NUM_PROCESSES = 3 * 3 rk = rn.rng() rk.set(SEED - rnz) Qi = 0.1 gno = Lffit.inigenome(nte, neff, rk, PL1, PL2) for i in range(PAR): P1 = [Np, m1, m2, m3, m4, m5, m6, m7, m8, Lth, beta1, beta2, wo, Ntot] for j in range(JMPS): qij = Queue() if j == 0: gn = {} pj = Process(target=evolx, args=( P1,
def graph(N,gtype): A={} ########################### if gtype[0]=='grid': k=0 for j in range(N): for i in range(N): nnh=[] if i<(N-1): nnh.append(k+1) if i>0: nnh.append(k-1) if j>0: nnh.append(k-N) if j<(N-1): nnh.append(k+N) A[k]=nnh k+=1 #print A ########################## if gtype[0]=='torus': k=0 for j in range(N): for i in range(N): nnh=[] ########################## if i<(N-1): nnh.append(k+1) if i==(N-1): nnh.append(k-(N-1)) if i>0: nnh.append(k-1) if i==0: nnh.append(k+(N-1)) ########################### if j>0: nnh.append(k-N) if j==0: nnh.append(k+(N-1)*N) if j<(N-1): nnh.append(k+N) if j==(N-1): nnh.append(k-(N-1)*N) ########################### A[k]=nnh k+=1 ########################## if gtype[0]=='ring': k=0 for i in range(N): nnh=[] if i==0: nnh.append(i+1) nnh.append(N-1) if (i>0) and (i<N-1): nnh.append(i-1) nnh.append(i+1) if i==(N-1): nnh.append(0) nnh.append(i-1) A[k]=nnh k+=1 ############################# if gtype[0]=='line': k=0 for i in range(N): nnh=[] if i==0: nnh.append(i+1) #nnh.append(N-1) if (i>0) and (i<N-1): nnh.append(i-1) nnh.append(i+1) if i==(N-1): #nnh.append(0) nnh.append(i-1) A[k]=nnh k+=1 ############################ if gtype[0]=='BarAlb': import math from pygsl import rng as rn print("BaALB!") print gtype print N No=int(math.floor(N/10)) #N>10! Nr=No SEED=gtype[1]#123456789 rk=rn.rng() rk.set(SEED) adjx={} for i in range(No): nnh=[] qs=0 while qs==0: pr=rk.uniform_int(No) if pr!=i: nnh.append(int(pr)) qs=1 adjx[i]=nnh for i in adjx.keys(): nnh=[] nnh.append(adjx[i][0]) for j in adjx.keys(): if i!=j: if adjx[j][0]==i: nnh.append(j) A[i]=nnh m=int(math.floor(No/2)) #N>10! Nr=len(A.keys()) #print Nr, m while Nr<=N: cnt=0 zn=0.0 for i in A.keys(): zn+=len(A[i]) nnh=[] while cnt<=m: qi=zn*rk.uniform_pos() sx=0.0 for ik in A.keys(): sx+=len(A[ik]) if (sx>=qi) and ik not in nnh: nnh.append(ik) cnt+=1 break A[Nr]=nnh for i in nnh: A[i].append(Nr) Nr+=1 #print Nr, N ############################ if gtype[0]=='hubs': M=gtype[1] Adj={} k=0 for i in range(N): nnh=[] if i==0: for j in range(1,N): nnh.append(j) if i>0: nnh.append(0) Adj[k]=nnh k+=1 Bj={} kx=0 for j in range(M): if j==0: for n in range(N): Bj[kx]=Adj[n] kx+=1 if j>0: for n in range(N): kz=kx-(j*(len(Adj.keys()))) #print kx,kz,j*N nnh=[] if kz==0: for jx in range(1,N): nnh.append(jx+j*(N)) if kz>0: nnh.append(j*N) Bj[kx]=nnh kx+=1 z=[] for j in range(M): z.append(j*N) #print z for rj in z: for rk in z: if (rk not in Bj[rj]) and rk!=rj: Bj[rj].append(rk) ##print Bj for nk in Bj.keys(): A[nk]=Bj[nk] ############################ if gtype[0]=="fully": for i in range(N): nnh=[] for j in range(N): if j != i: nnh.append(j) A[i]=nnh ############################ return A
from pygsl import histogram, rng import pygsl import sys from time import clock from matplotlib import pylab pygsl.set_debug_level(0) n = 2000 m = 5000 h =histogram.histogram(n) h.set_ranges_uniform(-8,8.) r = rng.rng() t0 = clock() h.increment(r.gaussian(1,n*m)) t1 = clock() print "Needed %d seconds" % (t1 - t0) x, d = h.plot_data() x = (x[:,0]+x[:,1])/2 pylab.plot(x,d) pylab.show()
def job(PT,SEED,nte,neff,tn,RXCLRPTS,CRKPTS,TES): from math import floor from pygsl import rng as rn import sys sys.path.append('../LNKMODEL/') import Lf Np=PT[0] m1=PT[1] #hgt effs m2=PT[2] #hgt te m3=PT[3] #eff recomb m4=PT[4] #te dup m5=PT[5] #eff dup+te m6=PT[6] #eff->null m7=PT[7] #null ->0 m8=PT[8] ##eff->0 beta1=PT[9] beta2=PT[10] #print("parameter vector:"% PT) av1=0.5*(RXCLRPTS[2]-RXCLRPTS[1]) av2=0.5*(CRKPTS[2]-CRKPTS[1]) av3=0.5*(TES[2]-TES[1]) Lth=floor((RXCLRPTS[0]+CRKPTS[0]+TES[0])*(1.0/3.0)*(av1+av2+av3)) #print Lth MU=[Np,m1,m2,m3,m4,m5,m6,m7,m8,Lth,beta1,beta2] #SEED=987654320 rk=rn.rng() rk.set(SEED) ################ gen={} trs={} # nte=10 # neff=10 gen=Lf.inigenome(nte,neff,rk,[TES[1],TES[2]],[CRKPTS[1], RXCLRPTS[2]]) ################ Ntot=RXCLRPTS[0]+CRKPTS[0]+TES[0] pqr={} ltn=[] lth=[] ngt=[] flg='all-good' for nk in range(tn):#Ntot): trs=Lf.trates(gen,MU) rij,sr =Lf.montec(trs,rk) if sr!='TRUE': pqr[nk]=[rij[0],rij[1],gen] ltn.append(Lf.lent(gen)) lth.append(Lth) ngt.append(len(gen.keys())) gu={} gu=Lf.transform(rij,gen,rk,[TES[1],TES[2]],[CRKPTS[1], RXCLRPTS[2]]) gen={} for i in gu.keys(): gen[i]=gu[i] else: flg='sumzero' break if len(gen.keys())>2000: flg='limit-reached' break #print("JOB COMPLETED") #print flg return [lth,ltn,ngt,pqr,gen,flg]
def run(gsl_example = True): n = 1000 p = 2 # Input data #rng.env_setup() r = rng.rng() # Initalising the data ... the call sequence to the random generator # influences the result. # Well a really ill conditioned example if gsl_example: # Initalise it GSL' style. The random generator is called # sequentially for each vector. X = np.zeros((n,p), np.float_) y = np.zeros((n,), np.float_) for i in range(n): ui = 5 * r.gaussian(1.0) vi = ui + r.gaussian(0.001) yi = ui + vi + r.gaussian(1.0) X[i,0] = ui X[i,1] = vi y[i] = yi else: # That's a more pythonic style. Call it sequentially for one vector # and then for the next. The results are then slightly different from # the example. But regularisation gives suprisiningly good results u = 5 * r.gaussian(1.0, n) v = u + r.gaussian(0.001, n) y = u + v + r.gaussian(1.0, n) X = np.array((u,v), order="F").transpose() # Fit w = multifit.multifit(n, p) w.svd(X) rcond = w.rcond() print("marix condition number %e" %(1.0/rcond,) ) c, rnorm, snorm = w.solve(0.0, X, y) chisq = rnorm**2 print("=== Unregularized fit ===") print("best fit: y = %g u + %g v" % tuple(c)) print("residual norm = %g" %(rnorm,)); print("solution norm = %g" %(snorm,)); print("chisq/dof = %g" %( chisq / (n - p),)); # Reqularisation lcurve n_points = 200 reg_param, rho, eta = w.lcurve(y, n_points) reg_idx = multifit.lcorner(rho, eta) lambda_l = reg_param[reg_idx] c_lcurve, rnorm, snorm = w.solve(lambda_l, X, y) chisq = rnorm**2 + (lambda_l * snorm)**2 print("\n=== Regularized fit (L-curve) ===") print("optimal lambda: %g" %(lambda_l,)) print("best fit: y = %g u + %g v" % tuple(c_lcurve)) print("residual norm = %g" %(rnorm,)); print("solution norm = %g" %(snorm,)); print("chisq/dof = %g" %( chisq / (n - p),)); # GCV G, lambda_gcv, G_gcv = w.gcv(y, reg_param) c_gcv, rnorm, snorm = w.solve(lambda_gcv, X, y) chisq = rnorm**2 + (lambda_gcv * snorm)**2 print("\n=== Regularized fit (GCV) ===") print("optimal lambda: %g" %(lambda_gcv,)) print("best fit: y = %g u + %g v" % tuple(c_gcv)) print("residual norm = %g" %(rnorm,)); print("solution norm = %g" %(snorm,)); print("chisq/dof = %g" %( chisq / (n - p),)); return reg_param, rho, eta, G, reg_idx, lambda_gcv, G_gcv pass
from pygsl import histogram, rng import pygsl import sys from time import clock from matplotlib import pylab pygsl.set_debug_level(0) n = 2000 m = 5000 h = histogram.histogram(n) h.set_ranges_uniform(-8, 8.) r = rng.rng() t0 = clock() h.increment(r.gaussian(1, n * m)) t1 = clock() print "Needed %d seconds" % (t1 - t0) x, d = h.plot_data() x = (x[:, 0] + x[:, 1]) / 2 pylab.plot(x, d) pylab.show()