Exemple #1
0
 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))
Exemple #2
0
    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))
Exemple #3
0
    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()

# Evaluate the integral with the default IteratedQuadrature algorithm:
Exemple #5
0
#! /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)
Exemple #6
0
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)
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

f = ot.SymbolicFunction(['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.Point()
bi = ot.Point()
fi = ot.Sample()
ei = ot.Point()
error = ot.Point()
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.Point(ai.getDimension()))
lower.setColor("magenta")
lower.setPointStyle('circle')
g.add(lower)

fig = plt.figure(figsize=(8, 4))
plt.suptitle(r"GaussKronrod example: $\int_{-5/2}^{9/2}|\sin(t)|\,dt=$" +
             str(value))
axis = fig.add_subplot(111)
axis.set_xlim(auto=True)