def get_segment(iphi): '''Input function for `omp_functions.run`. Computes one angular segment. **Parameters:** iphi : int Index of lower integration bound in phi. **Returns:** intVal : 1-D numpy.ndarray, shape[0]=ndim Contains the ndim integral values error : 1-D numpy.ndarray, shape[0]=ndim Contains the ndim values of the integration error. ''' # Specify the integration limits for each variable xmin = numpy.array([ 0.,phi[iphi] +phi0, -8],dtype=float) xmax = numpy.array([15.,phi[iphi+1]+phi0, 8],dtype=float) # use cubature and function <okCylinder> to integrate try: # old cubature syntax intVal,error = cubature(3,func,xmin,xmax,args=[True,calc_mo],norm=0,\ adaptive='h',abserr=abserr,relerr=relerr,maxEval=0,\ vectorized=True) except: # new cubature syntax # number of return values of func if calc_mo: fdim = len(qc.mo_spec) else: fdim = 1 intVal,error = cubature(func,3,fdim,xmin,xmax,args=[False,calc_mo],norm=0,\ adaptive='h',abserr=abserr,relerr=relerr,maxEval=0,\ vectorized=True) return intVal,error
def interp_cuba(datamesh, xaxis, yaxis): ''' Cubature integration of a 2D data mesh using a cubic interpolator funtion. Can be used by the map function to do parallel integration of hyper-images. Parameters ---------- datamesh : np.ndarray Numpy array containig a 2D data mesh. Dimensions correspond to input arrays datamesh.shape = [len(yaxis), len(xaxis)] xaxis : np.ndarray Numpy vector with correct dimensions. yaxis : np.ndarray Numpy vector with correct dimensions. Returns ------- cuba_integral: np.ndarray Numpy vector, same length as yaxis. ''' foomesh = interp2d(xaxis, yaxis, datamesh.T, kind='cubic') cuba_integral, err = cubature(foomesh, ndim=1, fdim=len(yaxis), xmin=[xaxis.min()], xmax=[xaxis.max()], args=(yaxis, )) return cuba_integral
def test_hcubature_cubature_one(): d = 3 xmax = np.ones((d,), dtype=float) xmin = np.zeros_like(xmax) ti.cubature_one(xmin) exact = ti.cubature_one_exact(xmax) val, err = cubature(ti.cubature_one, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_one(): d = 3 xmax = np.ones((d, ), dtype=float) xmin = np.zeros_like(xmax) ti.cubature_one(xmin) exact = ti.cubature_one_exact(xmax) val, err = cubature(ti.cubature_one, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_three(): d = 8 xmin = np.zeros((d,)) xmax = np.ones((d,)) exact = ti.cubature_three_exact(xmin, xmax) val, err = cubature(ti.cubature_three, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_five(): d = 3 xmin = -np.ones((d, )) xmax = np.ones((d, )) exact = 1. val, err = cubature(ti.cubature_five, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_seven(): d = 4 xmin = np.zeros((d,)) xmax = np.ones((d,)) exact = 1. val, err = cubature(ti.cubature_seven, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_five(): d = 3 xmin = -np.ones((d,)) xmax = np.ones((d,)) exact = 1. val, err = cubature(ti.cubature_five, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_seven(): d = 4 xmin = np.zeros((d, )) xmax = np.ones((d, )) exact = 1. val, err = cubature(ti.cubature_seven, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_three(): d = 8 xmin = np.zeros((d, )) xmax = np.ones((d, )) exact = ti.cubature_three_exact(xmin, xmax) val, err = cubature(ti.cubature_three, d, 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_zero(): xmin = np.zeros((4, )) xmax = np.array([12, 4, 0.25, 1], dtype=float) # check that it is possible to run ti.cubature_zero(xmax) exact = ti.cubature_zero_exact(xmax) val, err = cubature(ti.cubature_zero, xmax.shape[0], 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_zero(): xmin = np.zeros((4,)) xmax = np.array([12, 4, 0.25, 1], dtype=float) # check that it is possible to run ti.cubature_zero(xmax) exact = ti.cubature_zero_exact(xmax) val, err = cubature(ti.cubature_zero, xmax.shape[0], 1, xmin, xmax) assert np.allclose([exact], [val])
def test_hcubature_cubature_two(): radius = 0.68244456511919859846 d = 2 xmin = -np.ones((d,)) xmax = np.ones((d,)) exact = ti.cubature_two_exact(d, radius) val, err = cubature(ti.cubature_two, d, 1, xmin, xmax, args=(radius,), abserr=1e-4, relerr=1e-4, maxEval=1000000) true_error = np.abs(val - exact) assert true_error < 1e-4
def Sr(Eps, Lz, K, M, a): rMin, rMax = GR.rMinMax(Eps, Lz, K, M, a) xmin = np.array([rMin[0]], np.float64) xmax = np.array([rMax[0]], np.float64) return cubature(integrand_v, 1, 1, xmin, xmax, vectorized=True, args=(Eps, Lz, K, M, a), relerr=1.e-3)[0]
def test_hcubature_genz_gaussian(): u = np.array([1, 21, 2], dtype=float) a = np.array([1/10, 1/100, 1/500], dtype=float) xmin = np.zeros_like(u) xmax = np.ones_like(u) exact = ti.genz_gaussian_exact(u, a) val, err = cubature(ti.genz_gaussian, u.shape[0], 1, xmin, xmax, args=(u, a), adaptive='h') assert np.allclose([exact], [val])
def test_hcubature_genz_oscillatory_d2(): u = 2*np.pi*15/609 a = np.array([15.51, 2], dtype=float) n = 3 xmin = np.zeros((2,)) xmax = np.ones((2,)) * n exact = ti.genz_oscillatory_exact(n, a, u) # check that integrand is callable ti.genz_oscillatory(np.ones((2,), dtype=float), a, u) val, err = cubature(ti.genz_oscillatory, 2, 1, xmin, xmax, args=(a, u), adaptive='h') assert np.allclose(exact, val)
def dnase_asinh_normalLogLik_quadmean_expab_marginal_overab(dnase_asinh, c = 0, k = 1, mu_a = 0, sd_a = 1, mu_b = 0, sd_b = 1 ): import cubature as cuba # integration rectangle for a and b xmin = np.array([mu_a - 5*sd_a, mu_b - 5 * sd_b], float); xmax = np.array([mu_a + 5*sd_a, mu_b + 5*sd_b], float) int_res = cuba.cubature(2, dnase_asinh_normalLogLik_quadmean_expab_marginalab_integrand, xmin = xmin, xmax = xmax, adaptive = 'h', abserr = 0.0, relerr = 1e-5, args = tuple([dnase_asinh, 0, c, k, mu_a, sd_a, mu_b, sd_b])) if int_res[0][0] / int_res[1][0] < 1e4: warnings.warn('integration relative error larger than 1e-4') return np.log(int_res[0][0])
def f_mu(self, d): """ #vector of domain extend mean function :param d: domain :type d: Domain """ if type(d) is Domain: self.d = d self.extend_v = numpy.array([d.extend.x, d.extend.y, d.extend.time], dtype=numpy.float64) # vector of positions self.pos_v = numpy.array([d.position.x, d.position.y, d.position.time], dtype=numpy.float64) lower = [] for p, v in zip(self.pos_v, self.extend_v): if v != 0: lower.append(p) #lower=min(lower) upper = [] for p, v in zip(self.pos_v, self.extend_v): if v != 0: if v + p != 0: x = p + v upper.append(x) upper = numpy.array(upper, dtype=numpy.float64) lower = numpy.array(lower, dtype=numpy.float64) #I = integrate.fixed_quad(self.f_int,a=lower[0],b=upper[0]) I = cubature(self.f_int, ndim=lower.shape[0], fdim=upper.shape[0], maxEval=10000, xmin=lower, xmax=upper, adaptive='p', ) return I[0][0] else: return self.mean
def integrationRoutine(function, param_set, nComponents, rngx, rngy, integration = "trapezium"): ''' integrationRoutine - Chose the method by which the integrate the distribution over the specified region of space then perform the integral. Parameters ---------- function - function or interpolant - The function to be integrated over the specified region of space param_set - list of floats - Set of parameters which define the GMM. nComponents - int - Number of components of the GMM. rngx, rngy - tuple of floats - Boundary of region of colour-magnitude space being calculated. **kwargs -------- integration='trapezium' - str - The type of integration routine to be tested - 'analytic', 'trapezium', 'simpson', 'cubature' Returns ------- contInteg - float - Value of the integral after calculation ''' # analytic if we have analytic solution to the distribution - this is the fastest if integration == "analytic": contInteg = multiIntegral(param_set, nComponents) # trapezium is a simple approximation for the integral - fast - ~1% accurate elif integration == "trapezium": contInteg = numericalIntegrate(function, *(rngx, rngy)) # simpson is a quadratic approximation to the integral - reasonably fast - ~1% accurate elif integration == "simpson": contInteg = simpsonIntegrate(function, *(rngx, rngy)) # cubature is another possibility but this is far slower! elif integration == "cubature": contInteg, err = cubature(func2d, 2, 1, (rngx[0], rngy[0]), (rngx[1], rngy[1])) contInteg = float(contInteg) return contInteg
def testIntegral(self, integration='trapezium'): ''' testIntegral - Test the approximate integral calculated using the given integration rule against the accurate integral calculated using cubature for which we know the uncertainty **kwargs -------- integration='trapezium' - str - The type of integration routine to be tested - 'analytic', 'trapezium', 'simpson', 'cubature' Returns ------- calc_val - float - integral calculated using trapezium rule approximation real_val - float - integral calculated using cubature routine err - float - The error of the calculated value with respect to the real value Also prints out the values and errors of each calculation automatically ''' function = lambda a, b: self.distribution(self.params_f, a, b) cub_func = lambda X: self.distribution(self.params_f, X[0], X[1]) real_val, err = cubature(function, 2, 1, (self.rngx_s[0], self.rngy_s[0]), (self.rngx_s[1], self.rngy_s[1])) calc_val = integrationRoutine(function, self.params_f, self.nComponents, *(self.rngx_s, self.rngy_s), integration=integration) percent = ((calc_val - float(real_val))/calc_val)*100 cubature_percent = 100*float(err)/float(real_val) print("\nThe error in the linear numerical integral was %.3E%%" % float(percent)) print("\nThe cubature calculation error is quoted as %.3E or %.3E%%" % (float(err), cubature_percent) ) return calc_val, real_val, err
def _relative_entropy_from_densities_with_support_for_shannon_divergence( p: tp.Callable, q: tp.Callable, a: float, b: float, log_fun: tp.Callable = np.log, eps_abs: float = 1.49e-08, eps_rel: float = 1.49e-08) -> float: """ Compute the relative entropy of the distribution q relative to the distribution p D_KL(p||q) = E_p [log(p/q)] via numerical integration from a to b. The argument base can be used to specify the units in which the entropy is measured. The default choice is the natural logarithm. Parameters ---------- p: probability density function of the distribution p q: probability density function of the distribution q a: lower bound of the integration region b: upper bound of the integration region eps_abs: absolute error tolerance for numerical integration eps_rel: relative error tolerance for numerical integration Returns ------- The relative entropy of the distribution q relative to the distribution p. """ def integrand(x): return p(x) * log_fun(p(x) / q(x)) if p(x) > 0.0 else 0.0 return cubature(func=integrand, ndim=1, fdim=1, xmin=np.array([a]), xmax=np.array([b]), vectorized=False, adaptive='p', abserr=eps_abs, relerr=eps_rel)[0].item()
def dnase_asinh_normalLogLik_quadmean_expab_marginal_overab( dnase_asinh, c=0, k=1, mu_a=0, sd_a=1, mu_b=0, sd_b=1): import cubature as cuba # integration rectangle for a and b xmin = np.array([mu_a - 5 * sd_a, mu_b - 5 * sd_b], float) xmax = np.array([mu_a + 5 * sd_a, mu_b + 5 * sd_b], float) int_res = cuba.cubature( 2, dnase_asinh_normalLogLik_quadmean_expab_marginalab_integrand, xmin=xmin, xmax=xmax, adaptive='h', abserr=0.0, relerr=1e-5, args=tuple([dnase_asinh, 0, c, k, mu_a, sd_a, mu_b, sd_b])) if int_res[0][0] / int_res[1][0] < 1e4: warnings.warn('integration relative error larger than 1e-4') return np.log(int_res[0][0])
def gridIntegrate(function, rngx, rngy): ''' gridIntegrate - Integrate over the grid when using PenalisedGridModel Parameters ---------- function - function or interpolant - The function to be integrated over the specified region of space nComponents - int - Number of components of the GMM. Returns ------- compInteg: float - Integral over the region ''' #compInteg = integ.dblquad(function, rngx[0], rngx[1], rngy[0], rngy[1]) compInteg, err = cubature(function, 2, 1, (rngx[0], rngy[0]), (rngx[1], rngy[1])) return compInteg
def calculate(self, filein, v, x): try: printed = [ "Note: If the mean error of any of the computed integrals is large, consider increasing max. evaluations value\n" ] printed.append( "=============================================================\n" ) printed.append( "Filename Overlap Integral Mean Absolute Error \n" ) numproc = 1 #: Specifies number of subprocesses. slice_length = 1e4 infile = filein.split(",") filenames_RPA_singlet = sorted(infile) for filename in filenames_RPA_singlet: fullpath, just_filename = os.path.split(filename) orbkit.options.quiet = True orbkit.options.no_log = True pattern = "[GTO]" lines = [] num = 0 with open(filename, "r") as f: lines1 = f.readlines() for line in lines1: if num == 0: lines.append(line.lstrip()) elif num == 1: lines.append(line) if pattern in line: num = 1 f.close() filename2 = "RPA_S" + ".molden" with open(filename2, "w") as f: f.writelines(lines) f.close() qc = read.main_read(filename2, all_mo=True) orbkit.init() orbkit.options.quiet = True orbkit.options.no_log = True orbkit.options.calc_mo = [1] orbkit.options.filename = filename2 orbkit.options.adjust_grid = [5, 0.5] data = orbkit.run_orbkit() xl = numpy.amin(orbkit.grid.x) yl = numpy.amin(orbkit.grid.y) zl = numpy.amin(orbkit.grid.z) xh = numpy.amax(orbkit.grid.x) yh = numpy.amax(orbkit.grid.y) zh = numpy.amax(orbkit.grid.z) eig = [sub['energy'] for sub in qc.mo_spec] fdim = len(qc.mo_spec) / 2 fdim = int(fdim) i = numpy.argsort(eig) j = i[::-1] orbkit.init() orbkit.options.quiet = True orbkit.options.no_log = True orbkit.grid.is_initialized = True def func(x_array, *args): x_array = x_array.reshape((-1, 3)) orbkit.grid.x = numpy.array(x_array[:, 0], copy=True) orbkit.grid.y = numpy.array(x_array[:, 1], copy=True) orbkit.grid.z = numpy.array(x_array[:, 2], copy=True) out = orbkit.rho_compute(qc, calc_mo=True, slice_length=slice_length, drv=None, laplacian=False, numproc=numproc) out1 = out[i] out2 = out[j] out1 = numpy.abs(out1) out2 = numpy.abs(out2) out = out1[:fdim] * out2[:fdim] return out.transpose() ndim = 3 xmin = numpy.array([xl, yl, zl], dtype=float) xmax = numpy.array([xh, yh, zh], dtype=float) abserr = 1e-15 relerr = 1e-5 integral_mo, error_mo = cubature(func, ndim, fdim, xmin, xmax, args=[], adaptive='h', abserr=abserr, relerr=relerr, norm=0, maxEval=v, vectorized=True) coeff = numpy.sort(eig)[:fdim] sum = numpy.sum(numpy.abs(coeff)) norm_integral_mo = (numpy.abs(coeff) * integral_mo) / sum delta = numpy.sum(norm_integral_mo) mae = numpy.mean(numpy.abs(error_mo)) printed.append( str(just_filename) + " " + str("%.5f" % delta) + " " + str("%.5f" % mae) + "\n") printed.append("Job completed! \n") printed.append( "====================================================================\n" ) print(printed) with open(os.path.join(fullpath, 'Overlap.txt'), 'w') as fw: fw.writelines(("%s\n" % k for k in printed)) fw.close() return printed except: printed = ["\n Oops! Something went wrong! \n"] printed.append( "====================================================================\n" ) return printed
result = np.zeros(len(Eps))*1. rMin, rMax = GR.rMinMax(Eps, Lz, K, M, a) thMin, thMax= GR.thMinMax(Eps,Lz, K, M, a) # Filter: cond=(np.isnan(rMin)==False)&(np.imag(rMin)==0)&(np.isnan(thMin)==False)&(r>rMin)&(r<rMax)&(th<thMax)&(th>thMin) #print cond Eps = Eps[cond] Lz = Lz[cond] K = K[cond] ut = GR.u(Eps,Lz,K,M,a,r,th)[0] # Get determinant detg= GR.detg(M,a,r,th) # Jacobian J = np.abs(GR.jacobian(Eps,Lz,K,M,a,r,th)) # Calculate density result[cond] = np.sqrt(-1.*detg) * f0 * (4. / J) if np.sum(np.isnan(result)) != 0: print Eps, Lz, K, M, a, J, result raise ValueError("Bad result") return result M = 1. a = 0. r = 10. th = np.pi/2. xmin = [0.99,-7, 0] xmax = [0.999, 7, 7*7] val,er = cubature(integrand_v, 3, 1, xmin, xmax, vectorized=True,args=(M,a,r,th),relerr=1.e-1, maxEval=100000000) print val
def main(lndim, tol, functions, maxEval, lfdim): global count, ndim, fdim, function ndim = lndim fdim = lfdim logger = Logger() # instanciate Logger to redirect print to test_cubature.txt xmin = zeros(ndim) xmax = ones(ndim) abserr = tol relerr = tol for vectorized in [False, True]: print('======================================') print(' VECTORIZED={0}'.format(vectorized)) print('======================================') print('') for function in functions: count = 0 print('______________________________________') print(' ') print(' CASE {0}'.format(function)) print('______________________________________') for adaptive in ['h', 'p']: if adaptive == 'h': print('__________________') print(' ') print('Testing h_adaptive') print('__________________') else: print('__________________') print(' ') print('Testing p_adaptive') print('__________________') print('') print('Python Cubature:') print('----------------') print('{0}-dim integral, tolerance = {1}'.format(ndim, relerr)) print('') if vectorized: val, err = cubature(ndim, f_test_vec, xmin, xmax, (), adaptive, abserr, relerr, norm=0, maxEval=maxEval, vectorized=vectorized) else: val, err = cubature(ndim, f_test, xmin, xmax, (), adaptive, abserr, relerr, norm=0, maxEval=maxEval, vectorized=vectorized) true_err = abs(val[0] - exact_integral(function, ndim, xmax)) print('integrand {0}: integral = {1}, est err = {2}, true err = {3:e}' .format(function, val[0], err[0], true_err)) print('') print('#evals = {0}'.format(count)) print('') htest_path = os.path.join('.', 'cpackage', 'htest.exe') ptest_path = os.path.join('.', 'cpackage', 'ptest.exe') if os.path.isfile(htest_path) or os.path.isfile(ptest_path): print('C Cubature:') print('-----------') else: print('C Cubature program not compiled!') print('compile using (more details in ".\cpackage\README:"') print('\tcc -DHCUBATURE -o htest hcubature.c test.c -lm') print('\tcc -DPCUBATURE -o ptest pcubature.c test.c -lm') fdim_str = '/'.join(['x' for j in range(fdim)]) if adaptive=='h' and os.path.isfile(htest_path): p = Popen([htest_path] + list(map(str, [ndim,tol,function, maxEval,fdim_str])), stdout = PIPE) p.wait() for l in p.stdout: print(l) if adaptive=='p' and os.path.isfile(ptest_path): p = Popen([ptest_path] + list(map(str, [ndim,tol,function, maxEval,fdim_str])), stdout = PIPE) p.wait() for l in p.stdout: print(l)
return 4. / 3 * pi * r**3 def exact_ellipsoid(a, b, c): return 4. / 3 * pi * a * b * c if __name__ == '__main__': # brick print('_________________') print('') print('Brick') a, b, c = 1., 2., 3. xmin = np.zeros((3, ), dtype=float) xmax = np.array([a, b, c], dtype=float) val, err = cubature(integrand_brick, 3, 1, xmin, xmax) print('Approximated: {0}'.format(val)) print('Exact: {0}'.format(exact_brick(a, b, c))) # sphere print('_________________') print('') print('Sphere') radius = 1. xmin = np.array([0, 0, 0], np.float64) xmax = np.array([radius, 2 * pi, pi], np.float64) val, err = cubature(integrand_sphere, 3, 1, xmin, xmax) print('Approximated: {0}'.format(val)) print('Exact: {0}'.format(exact_sphere(radius))) # ellipsoid print('_________________') print('')
def f_cov(self, d1, d2): """ :param d1: :type d1: :param d2: :type d2: :return: :rtype: """ #logger.debug("d1 = %s"%d1) #logger.debug("d2 = %s"%d2) mark = False if type(d1) is Coor and type(d2) is Coor: #logger.debug("self.c1 %s" % d1) #logger.debug("self.c2 %s" % d2) var = self.sigma ** 2 dist_spatial = sqrt((d1.x - d2.x) ** 2 + (d1.y - d2.y) ** 2) dist_temporal = abs(d1.time - d2.time) timeDiv = dist_temporal / self.l_temporal expFeed = (-1) * ((dist_spatial / self.l_spatial) ** self.gamma) - (timeDiv ** self.gamma) cov = var * exp(expFeed) #logger.debug('134') #logger.debug("f_cov %s" % cov) return cov else: # ----------- ## covariance (kernel) function for ( Domain, Domain ) if type(d1) is Coor and type(d2) is Domain: ## --- for ( Coor, Domain ) d1 = Domain(d1, Coor(0, 0), 0) mark = True if type(d2) is Coor and type(d1) is Domain and not mark: d2 = Domain(d2, Coor(0, 0), 0) self.extend_v = numpy.array([d1.extend.x, d1.extend.y, d1.extend.time, d2.extend.x, d2.extend.y, d2.extend.time], dtype=numpy.float64) # # vector of positions self.pos_v = numpy.array([d1.position.x, d1.position.y, d1.position.time, d2.position.x, d2.position.y, d2.position.time], dtype=numpy.float64) self.d1 = d1 self.d2 = d2 # # construct function to integrate over lower = list() for p, v in zip(self.pos_v, self.extend_v): if v != 0: lower.append(p) upper = list() for p, v in zip(self.pos_v, self.extend_v): if v != 0 and v + p != 0: x = p + v upper.append(x) ## integrate #sumExtend_v=sum(self.extend_v) #TODOif sumExtend_v != 0 and sumExtend_v >2: # for >2-dimensional integration dim = 0 for ex in self.extend_v: if ex != 0: dim += 1 upper = numpy.array(upper, dtype=numpy.float64) lower = numpy.array(lower, dtype=numpy.float64) if dim > 2: #logger.debug("dim >2") # "I = cubature(self.f_int, xmin=lower,xmax=upper,ndim=lower.shape[0],fdim=upper.shape[0], maxEval=10000)") #I = integrate.nquad(self.f_int,[lower,upper]) I = cubature(self.f_int, xmin=lower, xmax=upper, ndim=lower.shape[0], fdim=upper.shape[0], maxEval=10000) #I = integrate.fixed_quad(self.f_int,a=lower[0],b=upper[0]) else: #logger.debug("dim <= 2") #logger.debug("self.d1 %s" % self.d1) #logger.debug("self.d2 %s" % self.d2) #logger.debug("upper = %s" % upper) #logger.debug("lower = %s" % lower) #logger.debug('199') #if len(upper)>2: #I = integrate.quad(self.f_int,a=lower[0],b=upper[0]) #logger.debug('upper.shape %s' % upper.shape) #.debug('upper.shape[0] %s' % upper.shape[0]) I = cubature(self.f_int, ndim=lower.shape[0], fdim=upper.shape[0], maxEval=10000, xmin=lower, xmax=upper, adaptive='p') #logger.error(logger.findCaller()) #logger.debug('212 cubature --------') #logger.debug("I[0] = %s" % I[0]) try: return I[0][0] except: return I[0] logger.error('f_cov nothing happened')
''' Example One =========== Run the cubature routine together with orbkit and integrate the density. ''' count_calls = 0 calc_mo = False # Call the cubature routine together with orbkit. try: integral, error = cubature(func, ndim, fdim, xmin, xmax, args=[vectorized, calc_mo], adaptive='h', abserr=abserr, relerr=relerr, norm=0, maxEval=0, vectorized=vectorized) except TypeError: raise RuntimeError( 'Calculation failed. Should work with cubature 0.13.1 which has a different syntax than earlier versions.' ) print('After %d function calls the integral is %.14f. (Error: %.4e)' % (count_calls, integral, error)) ''' Example Two ===========
def exact_sphere(r): return 4./3*pi*r**3 def exact_ellipsoid(a,b,c): return 4./3*pi*a*b*c if __name__ == '__main__': # brick print('_________________') print('') print('Brick') a, b, c = 1., 2., 3. xmin = np.zeros((3,), dtype=float) xmax = np.array([a, b, c], dtype=float) val, err = cubature(integrand_brick, 3, 1, xmin, xmax) print('Approximated: {0}'.format(val)) print('Exact: {0}'.format(exact_brick(a,b,c))) # sphere print('_________________') print('') print('Sphere') radius = 1. xmin = np.array([0, 0, 0], np.float64) xmax = np.array([radius, 2*pi, pi], np.float64) val, err = cubature(integrand_sphere, 3, 1, xmin, xmax) print('Approximated: {0}'.format(val)) print('Exact: {0}'.format(exact_sphere(radius))) # ellipsoid print('_________________') print('')
return a * b def exact_circle(r): return pi * r**2 if __name__ == '__main__': # rectangle print('_________________') print('') print('Rectangle') a, b = 3, 5 xmin = [0, 0] xmax = [a, b] val, err = cubature(integrand_rectangle, 2, 1, xmin, xmax) print('Approximated: {0}'.format(val)) print('Exact: {0}'.format(exact_rectangle(a, b))) # rectangle (vectorized) print('_________________') print('') print('Rectangle (vectorized)') a, b = 3, 5 xmin = [0, 0] xmax = [a, b] val, err = cubature(integrand_rectangle_v, 2, 1, xmin, xmax, vectorized=True)
def main(lndim, tol, functions, maxEval, lfdim): global count, ndim, fdim, function ndim = lndim fdim = lfdim logger = Logger( ) # instanciate Logger to redirect print to test_cubature.txt xmin = zeros(ndim) xmax = ones(ndim) abserr = tol relerr = tol for vectorized in [False, True]: print('======================================') print(' VECTORIZED={0}'.format(vectorized)) print('======================================') print('') for function in functions: count = 0 print('______________________________________') print(' ') print(' CASE {0}'.format(function)) print('______________________________________') for adaptive in ['h', 'p']: if adaptive == 'h': print('__________________') print(' ') print('Testing h_adaptive') print('__________________') else: print('__________________') print(' ') print('Testing p_adaptive') print('__________________') print('') print('Python Cubature:') print('----------------') print('{0}-dim integral, tolerance = {1}'.format(ndim, relerr)) print('') if vectorized: val, err = cubature(ndim, f_test_vec, xmin, xmax, (), adaptive, abserr, relerr, norm=0, maxEval=maxEval, vectorized=vectorized) else: val, err = cubature(ndim, f_test, xmin, xmax, (), adaptive, abserr, relerr, norm=0, maxEval=maxEval, vectorized=vectorized) true_err = abs(val[0] - exact_integral(function, ndim, xmax)) print( 'integrand {0}: integral = {1}, est err = {2}, true err = {3:e}' .format(function, val[0], err[0], true_err)) print('') print('#evals = {0}'.format(count)) print('') htest_path = os.path.join('.', 'cpackage', 'htest.exe') ptest_path = os.path.join('.', 'cpackage', 'ptest.exe') if os.path.isfile(htest_path) or os.path.isfile(ptest_path): print('C Cubature:') print('-----------') else: print('C Cubature program not compiled!') print( 'compile using (more details in ".\cpackage\README:"') print('\tcc -DHCUBATURE -o htest hcubature.c test.c -lm') print('\tcc -DPCUBATURE -o ptest pcubature.c test.c -lm') fdim_str = '/'.join(['x' for j in range(fdim)]) if adaptive == 'h' and os.path.isfile(htest_path): p = Popen([htest_path] + list( map(str, [ndim, tol, function, maxEval, fdim_str])), stdout=PIPE) p.wait() for l in p.stdout: print(l) if adaptive == 'p' and os.path.isfile(ptest_path): p = Popen([ptest_path] + list( map(str, [ndim, tol, function, maxEval, fdim_str])), stdout=PIPE) p.wait() for l in p.stdout: print(l)
out2 = numpy.abs(out2) out = out1[:fdim] * out2[:fdim] return out.transpose() ndim = 3 xmin = numpy.array([xl, yl, zl], dtype=float) xmax = numpy.array([xh, yh, zh], dtype=float) abserr = 1e-15 relerr = 1e-5 integral_mo, error_mo = cubature(func, ndim, fdim, xmin, xmax, args=[], adaptive='h', abserr=abserr, relerr=relerr, norm=0, maxEval=v, vectorized=True) coeff = numpy.sort(eig)[:fdim] sum = numpy.sum(numpy.abs(coeff)) norm_integral_mo = (numpy.abs(coeff) * integral_mo) / sum delta = numpy.sum(norm_integral_mo) mae = numpy.mean(numpy.abs(error_mo)) print( str(just_filename) + "\n" + "Overlap: " + str("%.5f" % delta) + " MAE: " + str("%.5f" % mae) + "\n") printed.append( str(just_filename) + " " + str("%.5f" % delta) +
return a * b def exact_circle(r): return pi * r ** 2 if __name__ == "__main__": # rectangle print("_________________") print("") print("Rectangle") a, b = 3, 5 xmin = [0, 0] xmax = [a, b] val, err = cubature(integrand_rectangle, 2, 1, xmin, xmax) print("Approximated: {0}".format(val)) print("Exact: {0}".format(exact_rectangle(a, b))) # rectangle (vectorized) print("_________________") print("") print("Rectangle (vectorized)") a, b = 3, 5 xmin = [0, 0] xmax = [a, b] val, err = cubature(integrand_rectangle_v, 2, 1, xmin, xmax, vectorized=True) print("Approximated: {0}".format(val)) print("Exact: {0}".format(exact_rectangle(a, b))) # circle print("_________________") print("")