def __init__(self): outputGrid = ot.RegularGrid(-1.0, 0.02, 101) super(GaussianConvolution, self).__init__(mesh, 1, outputGrid, 1) self.setInputDescription(["x"]) self.setOutputDescription(["y"]) self.algo_ = ot.GaussKronrod( 20, 1.0e-4, ot.GaussKronrodRule(ot.GaussKronrodRule.G7K15))
def setGaussKronrod(self, algo): """ Accessor to the Gauss Kronrod algorithm used to compute integrals Parameters ---------- algo : :py:class:`openturns.GaussKronrod` The algorithm """ try: self._gaussKronrod = ot.GaussKronrod(algo) except NotImplementedError: raise AttributeError("The parameter must be a GaussKronrod algorithm.")
def __init__(self, monteCarloResult, distribution, deltas): # the monte carlo result must have its underlying function with # the history enabled because the failure sample is obtained using it self._monteCarloResult = monteCarloResult self.function = ot.MemoizeFunction( self._monteCarloResult.getEvent().getFunction()) if self.function.getOutputHistory().getSize() == 0: raise AttributeError("The performance function of the Monte Carlo "+\ "simulation result should be a MemoizeFunction.") # the original distribution if distribution.hasIndependentCopula(): self._distribution = distribution else: raise Exception( "The distribution must have an independent copula.") self._dim = self._distribution.getDimension() # the 1d or 2d sequence of deltas self._originalDelta = np.vstack(np.array(deltas)) self._deltaValues = self._originalDelta.copy() self._deltaSize = self._deltaValues.shape[0] if self._deltaValues.shape[1] != 1 and self._deltaValues.shape[ 1] != self._dim: raise AttributeError('The deltas parameter must be 1d sequence of ' + \ 'float or 2d sequence of float of dimension ' +\ 'equal to {}.'.format(self._dim)) # check if the delta values have only one dimension -> copy the columns if self._deltaValues.shape[1] == 1: self._deltaValues = np.ones((self._deltaValues.shape[0], self._dim)) * \ self._deltaValues # initialize array result # rows : delta # columns : maginal self._pfdelta = np.zeros((self._deltaSize, self._dim)) self._varPfdelta = np.zeros((self._deltaSize, self._dim)) self._indices = np.zeros((self._deltaSize, self._dim)) # for loop to avoid copy id of the distribution collection self._estimatorDist = [ ot.DistributionCollection(self._dim) for i in range(self._deltaSize) ] # set the gaus Kronrod algorithm self._gaussKronrod = ot.GaussKronrod( 50, 1e-5, ot.GaussKronrodRule(ot.GaussKronrodRule.G7K15))
def __init__(self, POD, delta): className = type(POD).__name__ if className == "PolynomialChaosPOD": self._podResult = POD.getPolynomialChaosResult() self._metamodel = self._podResult.getMetaModel() self._podType = "chaos" elif className in ["KrigingPOD", "AdaptiveSignalPOD"]: self._podResult = POD.getKrigingResult() self._metamodel = ot.ComposedFunction( self._podResult.getMetaModel(), POD._transformation) self._podType = "kriging" else: raise Exception("Sobol indices can only be computed based on a " + \ "POD built with Kriging or polynomial chaos.") # dimension is minus 1 to remove the defect parameter self._dim = self._podResult.getMetaModel().getInputDimension() - 1 assert (self._dim >=2), "The number of parameters must be greater or " + \ "equal than 2 to be able to perform the sensitivity analysis." self._POD = POD self._defectSizes = POD.getDefectSizes() self._defectNumber = self._defectSizes.shape[0] self._detectionBoxCox = POD._detectionBoxCox self._samplingSize = 10000 # the distribution of the parameters without the one of the defects. tmpDistribution = POD.getDistribution() self._distribution = ot.ComposedDistribution( [tmpDistribution.getMarginal(i) for i in range(1, self._dim + 1)]) self._delta = np.vstack(np.array(delta)) self._gaussKronrod = ot.GaussKronrod( 50, 1e-5, ot.GaussKronrodRule(ot.GaussKronrodRule.G7K15)) # initialize result matrix self._initializeResultMatrix()
g = ot.Graph('IteratedQuadrature example', 'x', 'y', True, 'topright') g.add(f.draw([a, a], [b, b])) curve = l[0].draw(a, b).getDrawable(0) curve.setLineWidth(2) curve.setColor('red') g.add(curve) curve = u[0].draw(a, b).getDrawable(0) curve.setLineWidth(2) curve.setColor('red') g.add(curve) # Evaluate the integral with high precision: Iref = ot.IteratedQuadrature( ot.GaussKronrod(100000, 1e-13, ot.GaussKronrodRule( ot.GaussKronrodRule.G11K23))).integrate(f, a, b, l, u) # Evaluate the integral with the default GaussKronrod algorithm: f = ot.MemoizeFunction(f) I1 = ot.IteratedQuadrature(ot.GaussKronrod()).integrate(f, a, b, l, u) sample1 = f.getInputHistory() print('I1=', I1, '#evals=', sample1.getSize(), 'err=', abs(100.0 * (1.0 - I1[0] / Iref[0])), '%') cloud = ot.Cloud(sample1) cloud.setPointStyle('fcircle') cloud.setColor('green') g.add(cloud) f.clearHistory()
#! /usr/bin/env python from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() ot.RandomGenerator.SetSeed(0) # First, compute the volume of the unit ball in R^n a = -1.0 b = 1.0 formula = "1.0" lower = list() upper = list() algo = ot.IteratedQuadrature( ot.GaussKronrod(20, 1.0e-6, ot.GaussKronrodRule(ot.GaussKronrodRule.G3K7))) for n in range(3): inVars = ot.Description.BuildDefault(n + 1, "x") inVarsBounds = inVars[0:n] if (n > 0): formula += "-" + inVars[n - 1] + "^2" lower.append( ot.SymbolicFunction(inVarsBounds, ["-sqrt(" + formula + ")"])) upper.append( ot.SymbolicFunction(inVarsBounds, ["sqrt(" + formula + ")"])) integrand = ot.SymbolicFunction(inVars, ["1.0"]) value = algo.integrate(integrand, a, b, lower, upper)[0] print("dim=", n + 1, ", volume= %.12g" % value, ", calls=", integrand.getCallsNumber()) # Second, integrate a multi-valued function bounds = ot.Interval([-1.0] * 3, [1.0] * 3)
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View f = ot.NumericalMathFunction('x', 'abs(sin(x))') a = -2.5 b = 4.5 algo = ot.GaussKronrod( 100000, 1e-13, ot.GaussKronrodRule(ot.GaussKronrodRule.G11K23)) value = algo.integrate(f, ot.Interval(a, b))[0] ai = ot.NumericalPoint() bi = ot.NumericalPoint() fi = ot.NumericalSample() ei = ot.NumericalPoint() error = ot.NumericalPoint() value2 = algo.integrate(f, a, b, error, ai, bi, fi, ei)[0] ai.add(b) g = f.draw(a, b, 512) lower = ot.Cloud(ai, ot.NumericalPoint(ai.getDimension())) lower.setColor("magenta") lower.setPointStyle('circle') g.add(lower) fig = plt.figure(figsize=(4, 4)) plt.suptitle("GaussKronrod example") axis = fig.add_subplot(111) axis.set_xlim(auto=True)
ot.Beta(0.5, 1.0, -2.0, 3.0), ot.Gamma(1.0, 3.0), ot.Arcsine() ] for n in range(len(distributionCollection)): distribution = distributionCollection[n] name = distribution.getClassName() polynomialFactory = ot.StandardDistributionPolynomialFactory( ot.AdaptiveStieltjesAlgorithm(distribution)) print("polynomialFactory(", name, "=", polynomialFactory, ")") for i in range(iMax): print(name, " polynomial(", i, ")=", clean(polynomialFactory.build(i))) roots = polynomialFactory.getRoots(iMax - 1) print(name, " polynomial(", iMax - 1, ") roots=", roots) nodes, weights = polynomialFactory.getNodesAndWeights(iMax - 1) print(name, " polynomial(", iMax - 1, ") nodes=", nodes, " and weights=", weights) M = ot.SymmetricMatrix(iMax) for i in range(iMax): pI = polynomialFactory.build(i) for j in range(i + 1): pJ = polynomialFactory.build(j) def kernel(x): return [pI(x[0]) * pJ(x[0]) * distribution.computePDF(x)] M[i, j] = ot.GaussKronrod().integrate(ot.PythonFunction(1, 1, kernel), distribution.getRange())[0] print("M=\n", M.clean(1.0e-6))