def MonteCarloEval(g1, g2, es1, es2, ids, nsamples): #result, error=mcint.integrate(TestIntegrand,sampler(),measure=pi,n=1000000) global sm, es1_, es2_, g1_, g2_ g1_ = g1 g2_ = g2 es1_ = es1 es2_ = es2 if ids == '11': result, error = mcint.integrate(mfisherIntegrand11, sampler(), measure=pi, n=nsamples) elif ids == '22': result, error = mcint.integrate(mfisherIntegrand22, sampler(), measure=pi, n=nsamples) elif ids == '12': result, error = mcint.integrate(mfisherIntegrand12, sampler(), measure=pi, n=nsamples) else: print "Invalid integrand ID. Exiting." sys.exit() #result, error=mcint.integrate(TestIntegrand,sampler(),measure=1.0,n=1000) #print result, error return result, error
def te_calc(x_pred, x_hist, y_hist, mcsamples): """Calculates the transfer entropy between two variables from a set of vectors already calculated. ampbins is the number of amplitude bins to use over each variable """ # First do an example for the case of k = l = 1 # TODO: Sum loops to allow for a general case # Divide the range of each variable into amplitude bins to sum over # TODO: Will make this general x_pred_min = x_pred.min() x_pred_max = x_pred.max() x_hist_min = x_hist.min() x_hist_max = x_hist.max() y_hist_min = y_hist.min() y_hist_max = y_hist.max() x_pred_range = x_pred_max - x_pred_min x_hist_range = x_hist_max - x_hist_min y_hist_range = y_hist_max - y_hist_min # Calculate PDFs for all combinations required [pdf_1, pdf_2, pdf_3, pdf_4] = pdfcalcs(x_pred, x_hist, y_hist) def integrand(x): s1 = x[0] s2 = x[1] s3 = x[2] return te_elementcalc(pdf_1, pdf_2, pdf_3, pdf_4, s1, s2, s3) def sampler(): while True: s1 = random.uniform(x_pred_min, x_pred_max) s2 = random.uniform(x_hist_min, x_hist_max) s3 = random.uniform(y_hist_min, y_hist_max) yield (s1, s2, s3) domainsize = x_pred_range * x_hist_range * y_hist_range # Do triple integration using scipy.integrate.tplquad # Also do a version using mcint # See this for higher orders: # http://stackoverflow.com/questions/14071704/integrating-a-multidimensional-integral-in-scipy for nmc in [mcsamples]: random.seed(1) result, error = mcint.integrate(integrand, sampler(), measure=domainsize, n=nmc) print "Using n = ", nmc print "Result = ", result return result
def simul_dist(n, y): surv = 0 num = 1 t = symbols('t') tup = [t] for i in range(0,n): new_l = symbols('l_'+str(i)) new = density(Lam_old)(new_l) num = num * (1 - exp(-new * t)) surv = surv + ((new * exp(-new*t)/(1 - exp(-new * t)))) tup.append(new_l) surv = surv*num for i in range(0,n): new_l = symbols('l_'+str(i)) new = density(Lam_old)(new_l) surv = surv*new # pprint((surv)) tup = tuple(tup) simul = lambdify(tup, surv, "math") # simulstr = lambdastr(tup, surv, "math") # print(simulstr) def sampler(n, y): while True: tup = [y] for i in range(0,n): tup.append(random.uniform(-100,100)) tup = tuple(tup) yield tup def unpacker(tup): # print(*tup) return simul(*tup) # return integrate.quad(lambda x: simul(y,x), -100, 100)[0] return mcint.integrate(unpacker, sampler(n, y), n=100000)[0]
def te_calc(x_pred, x_hist, y_hist, mcsamples): """Calculates the transfer entropy between two variables from a set of vectors already calculated. ampbins is the number of amplitude bins to use over each variable """ # First do an example for the case of k = l = 1 # TODO: Sum loops to allow for a general case # Divide the range of each variable into amplitude bins to sum over # TODO: Will make this general x_pred_min = x_pred.min() x_pred_max = x_pred.max() x_hist_min = x_hist.min() x_hist_max = x_hist.max() y_hist_min = y_hist.min() y_hist_max = y_hist.max() x_pred_range = x_pred_max - x_pred_min x_hist_range = x_hist_max - x_hist_min y_hist_range = y_hist_max - y_hist_min # Calculate PDFs for all combinations required [pdf_1, pdf_2, pdf_3, pdf_4] = pdfcalcs(x_pred, x_hist, y_hist) def integrand(x): s1 = x[0] s2 = x[1] s3 = x[2] return te_elementcalc(pdf_1, pdf_2, pdf_3, pdf_4, s1, s2, s3) def sampler(): while True: s1 = random.uniform(x_pred_min, x_pred_max) s2 = random.uniform(x_hist_min, x_hist_max) s3 = random.uniform(y_hist_min, y_hist_max) yield(s1, s2, s3) domainsize = x_pred_range * x_hist_range * y_hist_range # Do triple integration using scipy.integrate.tplquad # Also do a version using mcint # See this for higher orders: # http://stackoverflow.com/questions/14071704/integrating-a-multidimensional-integral-in-scipy for nmc in [mcsamples]: random.seed(1) result, error = mcint.integrate(integrand, sampler(), measure=domainsize, n=nmc) print "Using n = ", nmc print "Result = ", result return result
def integrator_uniform(self, integrand, bounds, sample_iter): ''' using mcint package to determine the integral via uniform distribution sampling over an interval ''' # measure is the 'volume' over the region you are integrating over result,error = mcint.integrate(integrand, self.sampler(bounds), self.get_measure(bounds), sample_iter) return result, error
def MonteCarloEval(g1,g2,es1,es2,ids,nsamples): #result, error=mcint.integrate(TestIntegrand,sampler(),measure=pi,n=1000000) global sm, es1_,es2_,g1_,g2_ g1_=g1 g2_=g2 es1_=es1 es2_=es2 if ids=='11': result, error=mcint.integrate(mfisherIntegrand11,sampler(),measure=pi,n=nsamples) elif ids=='22': result, error=mcint.integrate(mfisherIntegrand22,sampler(),measure=pi,n=nsamples) else: print "Invalid integrand ID. Exiting." sys.exit() #result, error=mcint.integrate(TestIntegrand,sampler(),measure=1.0,n=1000) #print result, error return result,error
return (alpha*G*(rhoa-rhosi)/dist**2)*math.exp(-dist/lam)*(1.0 + dist/lam)*rhob*dV(phi,theta,r)*rhat_dot_xhat def sampler(): while True: r = random.uniform(0.,D/2.) theta = random.uniform(0.,2.*math.pi) phi = random.uniform(0.,math.pi) x = random.uniform(-a_depth/2.0+au_thick,a_depth/2.0+au_thick) y = random.uniform(-a/2., a/2.) z = random.uniform(-a/2., a/2.) yield (r, theta, phi, x, y, z) nmc = 100000000 domainsize = D * math.pi**2 * a_depth * a**2 random.seed(1) result, error = mcint.integrate(integrand, sampler(), measure=domainsize, n=nmc) print("integral is: ", result, error) #fname = 'data/lam_arr_%.3f_%.3f.npy' % (gap*1e6,lam*1e6) #np.save(fname,intval)
return 1 # using fubini, para separar def sampler(): while True: yield random.random() ############## primeira aplicacao result_r, error = mcint.integrate(integrand_r, sampler(), measure=1.0, n=100) print( "A integral de (r -r**3) no intervalo de 0 and 1 com Monte Carlo é, aproximadamente, ", result_r) #print ("error",error) #print ("\n") ############## outra aplicacao result_theta, error = mcint.integrate(integrand_theta, sampler(), measure=2 * np.pi, n=100) print( "A integral de 1 no intervalo de 0 a 2*pi com Monte Carlo é, aproximadamente, ", result_theta) #print ("error",error)
ab = [2, 0, 1 / 2, 2, 0, 1 / 2] cd = [0, 1, 1 / 2, 0, 1, 1 / 2] JM = [0, 0] zeta = 1 start = time.time() #result, error = mcint.integrate(normal_ms_alt, sampler_three(), measure=domainsize3, n=nmc) #result, error = mcint.integrate(anti_symmetrize, sampler_six(), measure=domainsize6, n=nmc) #print("Scale =", scale) #print("Result = ", result.real) #print("Error estimate =", error) #print("Time =", time.time()-start) scales = np.array([1, 1.5, 2, 2.5, 3]) gams = np.array([1, 1.5, 2, 2.5, 3]) results = np.zeros(shape=(len(scales), len(gams))) errors = np.zeros(shape=(len(scales), len(gams))) for i, scale in enumerate(scales): for j, a_gam in enumerate(gams): result, error = mcint.integrate(anti_symmetrize, sampler_six(), measure=domainsize6, n=nmc) results[i, j] = result errors[i, j] = error np.save("Results5533.npy", results) np.save("Errors5533.npy", errors)
integrand0 = lambda x: phi(x[0],x[1])*phi_c(x[2],x[3])*phi(x[2],x[3])*phi_c(x[0],x[1]) integrand0_check = lambda x:phi_check(x[0],x[1])*phi_check(x[2],x[3])\ *phi_check(x[2],x[3])*phi_check(x[0],x[1]) integrand1 = lambda x: phi(x[0],x[1])*phi_c(x[0],x[1])*phi(x[2],x[3])*phi_c(x[2],x[3]) integrand1_check = lambda x: phi_check(x[0],x[1])*phi_check(x[0],x[1])*phi_check(x[2],x[3])*phi_check(x[2],x[3]) integrand2 = lambda x: phi(x[0],x[1]) * phi_c(x[2],x[1]) * phi(x[2],x[3]) * phi_c(x[0],x[3]) integrand2_check = lambda x: phi_check(x[0],x[1]) * phi_check(x[2],x[1]) * phi_check(x[2],x[3]) * phi_check(x[0],x[3]) final = [] A = linspace(0.01,.5,51) B = L-A for j in A: print j k = L-j #result0_check,error0_check = integrate(integrand0_check, sampler([j,j,j,j]),measure = j**4, n=100) result0, error0 = integrate(integrand0, sampler([j,j,j,j]),measure = j**4, n=1000) #result1_check,error0_check = integrate(integrand1_check, sampler([k,k,k,k]),measure = k**4, n=100) result1, error1 = integrate(integrand1, sampler([k,k,k,k]),measure = k**4, n=1000) #result2_check,error0_check = integrate(integrand2_check, sampler([j,k,j,k]), measure = j**2*k**2, n=100) result2, error2 = integrate(integrand2, sampler([j,k,j,k]), measure = j**2*k**2, n=1000) final.append(result0+result1+2*result2) #print final, result0, result1, result2 #print result0_check, result1_check, result2_check ax1.plot(A,-1*log(final), label = '%.2g' %(g_i)) ax1.legend() ax1.set_xlabel('Region A (length)') ax1.set_ylabel('Renyi Entropy ' + r'$\alpha = 2$') f1.savefig('Renyi Entanglement Entropy %i' %(nc)) ax1.clear() print 'done %i' %(nc)
u = random.uniform(0, 1) theta = random.uniform(0, 2 * math.pi) phi = random.uniform(0, math.pi) yield (u, theta, phi) def sampler_six(): while True: u1 = random.uniform(0, 1) theta1 = random.uniform(0, 2 * math.pi) phi1 = random.uniform(0, math.pi) u2 = random.uniform(0, 1) theta2 = random.uniform(0, 2 * math.pi) phi2 = random.uniform(0, math.pi) yield (u1, theta1, phi1, u2, theta2, phi2) domainsize = 4 * math.pi**4 nmc = 100000 start = time.time() #result, error = mcint.integrate(f, sampler_three(), measure=domainsize, n=nmc) result, error = mcint.integrate(norm_test, sampler_six(), measure=domainsize, n=nmc) print("Result = ", result.real) print("Error estimate =", error) print("Time =", time.time() - start)
x1 = 0 b1 = bounds[2][0] b2 = bounds[2][1] m = {sympy.Symbol("x0"): x0, sympy.Symbol("y0"): y0} # while not(2<x1<3): x1 = random.uniform(b1.subs(m), b2.subs(m)) yield (x0, y0, x1) print(inspect.getsource(f.formula)) f = sympy.lambdify(keys, f.formula) def integrand(x): return apply(f, x) t = time.time() mcint.integrate(integrand, sampler(), n=100) integral = sympy.S(integral) print("integration time: {}".format(time.time() - t)) result = operator.perform(result, integral) print(self.key) return result def __str__(self): return " + ".join( map(lambda (i, f): "(" + str(i) + " | " + str(f) + ")", self.list)) # return ",".join(map(lambda (i, f): str(f), self.list)) intTime = 0 integralTime = 0
T = 1. ww = w(r, theta, phi, alpha, beta, gamma) return (math.exp(-ww/(k*T)) - 1.)*r*r*math.sin(beta)*math.sin(theta) def sampler(): while True: r = random.uniform(0.,1.) theta = random.uniform(0.,2.*math.pi) alpha = random.uniform(0.,2.*math.pi) beta = random.uniform(0.,2.*math.pi) gamma = random.uniform(0.,2.*math.pi) phi = random.uniform(0.,math.pi) yield (r, theta, alpha, beta, gamma, phi) domainsize = math.pow(2*math.pi,4)*math.pi*1 expected = 16.0*math.pow(math.pi,5)/3. for nmc in [1000, 10000, 100000, 1000000, 10000000, 100000000]: t0 = time.time() random.seed(1) #random.seed() result, error = mcint.integrate(integrand, sampler(), measure=domainsize, n=nmc) diff = abs(result - expected) t1 = time.time() print "Using n = ", nmc print "Result = ", result, "estimated error = ", error print "Known result = ", expected, " error = ", diff, " = ", 100.*diff/expected, "%" print " " print "completed in time ",t1-t0,"sec"
import numpy as np from scipy.special import gamma, assoc_laguerre, sph_harm from sympy.physics.wigner import wigner_3j, wigner_6j from sympy import N import matplotlib.pyplot as plt import mcint import random import math def f(x): return x[0] * x[1] * x[2] def sampler(): while True: x = random.uniform(0, 1) y = random.uniform(0, 1) z = random.uniform(0, 1) yield (x, y, z) result, error = mcint.integrate(f, sampler(), measure=1, n=100000000) print("Result =", result) print("Error =", error)
from scipy import integrate import time def f(r_pol): u, theta = r_pol return -np.log(u) * np.exp(-(np.log(u)**2)) / u def sampler(): while True: u = random.uniform(0, 1) theta = random.uniform(0, 2 * math.pi) yield (u, theta) domainsize = 2 * math.pi nmcs = [] elapsed = [] errors = [] for nmc in [5**10]: start = time.time() result, trash = mcint.integrate(f, sampler(), measure=domainsize, n=nmc) nmcs.append(nmc) elapsed.append(time.time() - start) errors.append(result - np.pi) print(errors)
def coefs_MC_wrapper(nb_samples, a_nu, with_cheb_weights = False, rhs = 1., variability = 1./6., abar = 5.): domainsize = 1. # math.pow(2,6) np.random.seed(1) result, error = mcint.integrate(lambda (x0, x1, x2, x3, x4, x5): integrand(x0,x1,x2,x3,x4,x5, a_nu[0],a_nu[1],a_nu[2],a_nu[3],a_nu[4],a_nu[5], with_cheb_weights, rhs, variability, abar), sampler(), measure=domainsize, n=nb_samples) return result