def test_ret_arr_args(self): """ Test an integrand that returns an array with an argument. """ func = lambda x, a, b: np.array((a * x**2, b * x**3)) npoints = 2000 aval, bval = 4., 5. (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func, npoints, [0.], [1.], nprocs=1, seed=123456, args=(aval, bval)) res_sq2, sd_sq2 = mcquad(lambda x, a: a * x**2, npoints, [0.], [1.], nprocs=1, seed=123456, args=(aval, )) res_cb2, sd_cb2 = mcquad(lambda x, b: b * x**3, npoints, [0.], [1.], nprocs=1, seed=123456, args=(bval, )) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def computeMstep(self, etalist, features=None, lambdas=None, states=None): if features is None: features = self.features if lambdas is None: lambdas = self.lambdalist if states is None: states = self.states denom = self.computenormalizerdp(lambdas, states) gammastep = np.zeros(len(features)) for iteration in range(0, 2): for i in range(0, len(features)): a = features[i][0] b = features[i][1] gammastep[i] += -1 * ( (skmonaco.mcquad(self.fep, xl=np.zeros(self.numvar), xu=np.ones(self.numvar), args=([a, b, gammastep[i]]), npoints=100000)[0] - denom * etalist[i]) / (skmonaco.mcquad(self.ffep, xl=np.zeros(self.numvar), xu=np.ones(self.numvar), args=([a, b, gammastep[i]]), npoints=100000)[0])) print(gammastep) return gammastep
def test_seed_different(self): """ Test different seed -> different result. """ npoints = 50000 res,error = mcquad(lambda x: x**2,npoints,xl=[0.],xu=[1.],seed=[1235,5678]) res2, error2 = mcquad(lambda x: x**2,npoints,xl=[0.],xu=[1.],seed=[1234,5678]) assert res != res2 assert error != error2
def test_seed(self): """ Test same seed -> same result. """ npoints = 50000 res,error = mcquad(lambda x:x**2,npoints,xl=[0.],xu=[1.],seed=[1234,5678]) res2, error2 = mcquad(lambda x:x**2,npoints,xl=[0.],xu=[1.],seed=[1234,5678]) assert res == res2 assert error == error2
def test_ret_arr(self): """ Test an integrand that returns an array. """ func = lambda x: np.array((x**2,x**3)) npoints = 2000 (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func,npoints,[0.],[1.],nprocs=1, seed=123456) res_sq2, sd_sq2 = mcquad(lambda x: x**2,npoints,[0.],[1.],nprocs=1,seed=123456) res_cb2, sd_cb2 = mcquad(lambda x: x**3,npoints,[0.],[1.],nprocs=1,seed=123456) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def mass_moment(self, xmin, xmax, ymin, ymax): massMoment, mMerror = mcquad(self.g23, npoints=1000, xl=[xmin, ymin], xu=[xmax, ymax], nprocs=1) return massMoment
def run_serial(self,f,npoints,expected_value,expected_variance,**kwargs): res, sd = mcquad(f,npoints,nprocs=1,**kwargs) volume = self.calc_volume(kwargs["xl"],kwargs["xu"]) error = volume*np.sqrt(expected_variance/float(npoints)) assert_within_tol(res,expected_value,3.*max(error,1e-10), "Error in <f> in serial run.") assert_within_tol(sd,error,0.1*max(error,1e-10), "Error in expected error in serial run.")
def test_seed(self): """ Test same seed -> same result. """ npoints = 50000 res, error = mcquad(lambda x: x**2, npoints, xl=[0.], xu=[1.], seed=[1234, 5678]) res2, error2 = mcquad(lambda x: x**2, npoints, xl=[0.], xu=[1.], seed=[1234, 5678]) assert res == res2 assert error == error2
def test_seed_different(self): """ Test different seed -> different result. """ npoints = 50000 res, error = mcquad(lambda x: x**2, npoints, xl=[0.], xu=[1.], seed=[1235, 5678]) res2, error2 = mcquad(lambda x: x**2, npoints, xl=[0.], xu=[1.], seed=[1234, 5678]) assert res != res2 assert error != error2
def test_ret_arr_args(self): """ Test an integrand that returns an array with an argument. """ func = lambda x, a,b : np.array((a*x**2,b*x**3)) npoints = 2000 aval, bval = 4.,5. (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func,npoints,[0.],[1.],nprocs=1, seed=123456,args=(aval,bval)) res_sq2, sd_sq2 = mcquad(lambda x,a: a*x**2,npoints,[0.],[1.],nprocs=1, seed=123456,args=(aval,)) res_cb2, sd_cb2 = mcquad(lambda x,b: b*x**3,npoints,[0.],[1.],nprocs=1, seed=123456,args=(bval,)) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def test_ret_arr_parallel(self): """ Test an integrand that returns an array: parallel implementation. """ func = lambda x: np.array((x**2,x**3)) npoints = 5000 nprocs = 2 (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func,npoints,[0.],[1.],nprocs=nprocs, seed=123456) res_sq2, sd_sq2 = mcquad(lambda x: x**2,npoints,[0.],[1.], nprocs=nprocs,seed=123456) res_cb2, sd_cb2 = mcquad(lambda x: x**3,npoints,[0.],[1.], nprocs=nprocs,seed=123456) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def run_serial(self, f, npoints, expected_value, expected_variance, **kwargs): res, sd = mcquad(f, npoints, nprocs=1, **kwargs) volume = self.calc_volume(kwargs["xl"], kwargs["xu"]) error = volume * np.sqrt(expected_variance / float(npoints)) assert_within_tol(res, expected_value, 3. * max(error, 1e-10), "Error in <f> in serial run.") assert_within_tol(sd, error, 0.1 * max(error, 1e-10), "Error in expected error in serial run.")
def density(x0=np.linspace(0, 8), q=3, ne=2, npoints=1e5, err=0.05, **kwds): #XXX choose ONLY symmetric positive part leads to large error l, u = [-10., 10.] M, Merr = mcquad(Laughlin_1d(x0=x0, q=q), npoints=npoints, xl=[l]*(ne-1), xu=[u]*(ne-1), **kwds) # Caclculate N, which will not affect relative density profile # N, Nerr = mcquad(Laughlin_1d(q=q), npoints=npoints, xl=[l]*ne, xu=[u]*ne) # This N works only if x0 is large enough N = M.sum()*(x0[1]-x0[0])*2 # 2 for positive part only reM = Merr/M if max(reM) > err: print 'Large err for ne={}, q={}: M ~{:.2f}%'.format(ne, q, max(reM)*100) return M * ne / N
def overlap_int(wf1,wf2): def integrand(x, p1, p2): wf1 = p1.get_value([x[0], x[1], x[2]]) wf2 = p2.get_value([x[0], x[1], x[2]]) return wf1*wf2 xl = [-6.5, 0.0, -6.5] xu = [6.5, 8.9, 6.5] v, a = mcquad(integrand, xl=xl, xu=xu, npoints=1000000, args=[wf1, wf2]) return v, a
def test_ret_arr(self): """ Test an integrand that returns an array. """ func = lambda x: np.array((x**2, x**3)) npoints = 2000 (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func, npoints, [0.], [1.], nprocs=1, seed=123456) res_sq2, sd_sq2 = mcquad(lambda x: x**2, npoints, [0.], [1.], nprocs=1, seed=123456) res_cb2, sd_cb2 = mcquad(lambda x: x**3, npoints, [0.], [1.], nprocs=1, seed=123456) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def test_ret_arr_parallel(self): """ Test an integrand that returns an array: parallel implementation. """ func = lambda x: np.array((x**2, x**3)) npoints = 5000 nprocs = 2 (res_sq, res_cb), (sd_sq, sd_cb) = mcquad(func, npoints, [0.], [1.], nprocs=nprocs, seed=123456) res_sq2, sd_sq2 = mcquad(lambda x: x**2, npoints, [0.], [1.], nprocs=nprocs, seed=123456) res_cb2, sd_cb2 = mcquad(lambda x: x**3, npoints, [0.], [1.], nprocs=nprocs, seed=123456) assert_almost_equal(res_sq, res_sq2) assert_almost_equal(res_cb, res_cb2) assert_almost_equal(sd_sq, sd_sq2) assert_almost_equal(sd_cb, sd_cb2)
def run_check_seeded_distribution(self, f, ntrials, *args, **kwargs): """ Check that the results returned by integrating f are normally distributed. Seeds each trial with the trial number. """ import scipy.stats results, errors = [], [] for itrial in range(ntrials): res, err = mcquad(f, *args, seed=itrial, **kwargs) results.append(res) errors.append(err) results = np.array(results).flatten() w, p = scipy.stats.shapiro(results) self.assertGreater(p, 0.1)
def run_check_seeded_distribution(self,f,ntrials,*args,**kwargs): """ Check that the results returned by integrating f are normally distributed. Seeds each trial with the trial number. """ import scipy.stats results, errors = [], [] for itrial in range(ntrials): res, err = mcquad(f,*args,seed=itrial,**kwargs) results.append(res) errors.append(err) results = np.array(results).flatten() w,p = scipy.stats.shapiro(results) self.assertGreater(p,0.1)
def computenormalizerdp(self, lambdas=None, states=None): if lambdas is None: lambdas = self.lambdalist if states is None: states = self.states normalizer = 0 integrand = 0 for state in states: integrand += skmonaco.mcquad(self.p, xl=np.zeros(self.numvar), xu=np.ones(self.numvar), args=([state]), npoints=100000)[0] return integrand
def two_el_int(wf1, wf2, wf3, wf4): def integrand(x, p1, p2, p3, p4): x1=np.array([x[0], x[1], x[2]]) x2=np.array([x[3], x[4], x[5]]) wf1 = p1.get_value(x1) wf2 = p2.get_value(x1) wf3 = p3.get_value(x2) wf4 = p4.get_value(x2) D=np.sqrt(np.sum((x1-x2)**2)) return wf1*wf2*(1/D)*wf3*wf4 xl = [-6.5, 0.0, -6.5, -6.5, 0.0, -6.5] xu = [6.5, 8.9, 6.5, 6.5, 8.9, 6.5] v, a = mcquad(integrand, xl=xl, xu=xu, npoints=1000000, args=[wf1, wf2, wf3, wf4]) return v, a
def test_wrong_nprocs(self): """ Raise a ValueError if nprocs < 1 """ with self.assertRaises(ValueError): mcquad(self.const,2000,xl=[0.],xu=[1.],nprocs=-1)
def test_wrong_npoints(self): """ Raise a ValueError if npoints < 2. """ with self.assertRaises(ValueError): mcquad(self.const, 0, xl=[0.], xu=[1.])
def test_wrong_nprocs(self): """ Raise a ValueError if nprocs < 1 """ with self.assertRaises(ValueError): mcquad(self.const, 2000, xl=[0.], xu=[1.], nprocs=-1)
def test_wrong_xl(self): """ Raise a ValueError if len(xl) != len(xu). """ with self.assertRaises(ValueError): mcquad(self.const, 2000, xl=[0., 0.], xu=[1.])
def test_wrong_npoints(self): """ Raise a ValueError if npoints < 2. """ with self.assertRaises(ValueError): mcquad(self.const,0,xl=[0.],xu=[1.])
import numpy as np from skmonaco import mcquad # f = lambda x_y,alpha,beta: np.exp(-alpha*x_y[0]**2)*np.exp(-beta*x_y[1]**2) def f(x_y, alpha, beta): return np.exp(-alpha*x_y[0]**2)*np.exp(-beta*x_y[1]**2) alpha = 1.0 beta = 2.0 ans, err = mcquad(f,xl=[0.,0.],xu=[1.,1.],npoints=100000,args=(alpha,beta)) print ans print err
import sympy as sp from skmonaco import mcquad import time x0, y1, x1, y2,x2 = sp.symbols('x0 y1 x1 y2 x2') Fx0 = x0 Fy1 = y1 Fx1 = sp.Piecewise((2*(x1-y1), sp.And(0<x1-y1, x1-y1<1)), ( 0, True )) Fy2 = y2 Fx2 = sp.Piecewise((2*(x2-y1-y2), sp.And(0<x2-y1-y2, x2-y1-y2<1)), ( 0, True )) integrand = Fx0*Fy1*Fx1*Fy2*Fx2 func = lambda s1, s2, s3, s4, s5: integrand.subs([(x0,s1),(y1,s2),(x1,s3),(y2,s4),(x2,s5)]) lb = [0.0,0.0,0.0,0.0,1.0] ub = [1.0,1.0,1.0,1.0,2.0] t = time.time() print mcquad(lambda x: float(apply(func,x)),100,lb,ub) print (time.time()-t)
def g(x, y): return f(numpy.sqrt(x**2 + y**2)) print("1d integration") x = numpy.linspace(0, 10, num=10000, endpoint=True) y = numpy.vectorize(f)(x) plt.plot(x, y) plt.draw() for order in range(1, 6): with benchmark("Monte-Carlo {} points".format(10**order)): integral, error = mcquad(f, xl=[0.], xu=[10.], npoints=10**order) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 10, epsabs=0, epsrel=1e-8) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 9, epsabs=0, epsrel=1e-8) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 8, epsabs=0, epsrel=1e-8) print(integral, error, end='') with benchmark("QUADPACK full"):
def test_wrong_xl(self): """ Raise a ValueError if len(xl) != len(xu). """ with self.assertRaises(ValueError): mcquad(self.const,2000,xl=[0.,0.],xu=[1.])
def test_zero_volume(self): """ Passing an empty integration volume raises ValueError. """ with self.assertRaises(ValueError): mcquad(lambda x: x**2, 20000, [0.], [0.])
def test_zero_volume(self): """ Passing an empty integration volume raises ValueError. """ with self.assertRaises(ValueError): mcquad(lambda x:x**2, 20000, [0.],[0.])
XXX = np.vstack((x, x*0.0+6.45, 0.0*x)) xi, yi = np.meshgrid(x, y) x, y = xi.flatten(), yi.flatten() z = x*0.0 XX = np.vstack((x, y, z)) wf = WF(sn=10, qn=0, flag='int') AA = wf.get_value(XX.T) fig = plt.figure() plt.contour(xi, yi, -AA.reshape(xi.shape), colors='red') plt.hold(True) plt.show() def square_mod(x, par): wf1 = wf.get_value([x[0], x[1], x[2]]) wf2 = wf.get_value([x[0], x[1], x[2]]) return wf1*wf2 xl = [-6.5, 0.0, -6.5] xu = [6.5, 8.9, 6.5] v, a = mcquad(square_mod, xl=xl, xu=xu, npoints=100000, args=[wf]) print v print a # def overlap(x1): # def two_elec_integrand(x1,x2):
XXX = np.vstack((x, x*0.0+6.45, 0.0*x)) xi, yi = np.meshgrid(x, y) x, y = xi.flatten(), yi.flatten() z = x*0.0 XX = np.vstack((x, y, z)) wf = WF(sn=10, qn=0, flag='int') AA = wf.get_value(XX.T) fig = plt.figure() plt.contour(xi, yi, -AA.reshape(xi.shape), colors='red') plt.hold(True) plt.show() def square_mod(x, par): wf1 = par.get_value([x[0], x[1], x[2]]) wf2 = par.get_value([x[0], x[1], x[2]]) return wf1*wf2 xl = [-6.5, 0.0, -6.5] xu = [6.5, 8.9, 6.5] v, a = mcquad(square_mod, xl=xl, xu=xu, npoints=100000, args=[wf]) print v print a # def overlap(x1): # def two_elec_integrand(x1,x2):
def g(x, y): return f(numpy.sqrt(x**2 + y**2)) print("1d integration") x = numpy.linspace(0, 10, num=10000, endpoint=True) y = numpy.vectorize(f)(x) plt.plot(x, y) plt.draw() for order in range(1, 6): with benchmark("Monte-Carlo {} points".format(10**order)): integral, error = mcquad(f, xl=[0.], xu=[10.], npoints=10**order) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 10, epsabs=0, epsrel=1e-8) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 9, epsabs=0, epsrel=1e-8) print(integral, error, end='') with benchmark("QUADPACK full"): integral, error = quad(f, 0, 8, epsabs=0, epsrel=1e-8) print(integral, error, end='')
# TODO: FILTER ongeldige berekeningen. Fout in encodering, of problog? symbols = set(map(lambda x: str(x), f.formula.free_symbols)) if not symbols == set(keys): bounds = list( compress(bounds, [key in symbols for key in keys])) org_keys = keys keys = [key for key in keys if key in symbols] # print(f.formula) # print(symbols) # print(set(keys)) # print(bounds) func = sympy.lambdify(keys, f.formula) xl = map(lambda x: x[0], bounds) xu = map(lambda x: x[1], bounds) try: (integral, err) = mcquad(lambda x: apply(func, x), 100, xl, xu) except: print(f.formula) print(org_keys) print(set(keys)) print(bounds) integral = 0 integral = sympy.S(integral) # print(integral) # print("integration time: {}".format(time.time()-t)) # else: # integral = sympy.S(0) result = operator.perform(result, integral) return result def __str__(self):