Example #1
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))
Example #2
0
    def _runMonteCarlo(self, defect):
        # set a parametric function where the first parameter = given defect
        g = ot.ParametricFunction(self._metamodel, [0], [defect])
        g = ot.MemoizeFunction(g)
        g.enableHistory()
        g.clearHistory()
        g.clearCache()
        output = ot.CompositeRandomVector(g,
                                          ot.RandomVector(self._distribution))
        event = ot.ThresholdEvent(output, ot.Greater(), self._detectionBoxCox)

        ##### Monte Carlo ########
        algo_MC = ot.ProbabilitySimulationAlgorithm(event)
        algo_MC.setMaximumOuterSampling(self._samplingSize)
        # set negative coef of variation to be sure the stopping criterion is the sampling size
        algo_MC.setMaximumCoefficientOfVariation(-1)
        algo_MC.run()
        return algo_MC.getResult()
Example #3
0
        def numericalmathfunction(*args, **kwargs):
            wrapper_instance = wrapper(*args, **kwargs)
            func = ot.Function(wrapper_instance)
            # Enable cache
            if self.enableCache:
                func = ot.MemoizeFunction(func)
                func.disableHistory()

            # Update __doc__ of the function
            if self.doc is None:
                # Inherit __doc__ from ParallelWrapper.
                func.__doc__ = wrapper.__doc__
            else:
                func.__doc__ = self.doc

            # Add the kwargs as attributes of the function for reference
            # purposes.
            func.__dict__.update(kwargs)
            func.__dict__.update(wrapper_instance.__dict__)
            return func
Example #4
0
# %%
def functionFlooding(X) :
    L = 5.0e3
    B = 300.0
    Q, K_s, Z_v, Z_m = X
    alpha = (Z_m - Z_v)/L
    if alpha < 0.0 or K_s <= 0.0:
        H = np.inf
    else:
        H = (Q/(K_s*B*np.sqrt(alpha)))**(3.0/5.0)
    return [H]


# %%
g = ot.PythonFunction(4, 1, functionFlooding) 
g = ot.MemoizeFunction(g)
g.setOutputDescription(["H (m)"])

# %%
# We load the input distribution for :math:`Q` :

# %%
Q = fm.Q
print(Q)

# %%
# Set the parameters to be calibrated.

# %%
K_s = ot.Dirac(30.0)
Z_v = ot.Dirac(50.0)
print(modelFunc.gradient([s[0], r, c]).transpose())
print(mycf.parameterGradient(s).transpose())

# Check if parametric functions and memoize functions work well together

n_calls = 0


def py_f(X):
    global n_calls
    n_calls += 1
    return X


ot_f = ot.MemoizeFunction(ot.PythonFunction(3, 3, py_f))
param_f = ot.ParametricFunction(ot_f, [0, 1], [1.0, 2.0])

x = [3.0]
y = [1.5]
n_calls_0 = ot_f.getCallsNumber()
par_grad = param_f.parameterGradient(x)
n_calls_1 = ot_f.getCallsNumber()
assert n_calls_1 - n_calls_0 == 4, "Expected n_calls_1 - n_calls_0 == 4, here n_calls_1 - n_calls_0 == " + \
    str(n_calls_1 - n_calls_0)
assert n_calls == 4, "Expected n_calls == 4, here n_calls == " + str(n_calls)

n_calls = 0
n_calls_0 = ot_f.getCallsNumber()
f_grad = param_f.gradient(y)
n_calls_1 = ot_f.getCallsNumber()
Example #6
0
def python_eval(X):
    a, b = X
    y = a + b
    return [y]


func4 = ot.PythonFunction(2, 1, python_eval)

# %%
# Ask for the dimension of the input and output vectors
print(f.getInputDimension())
print(f.getOutputDimension())

# %%
# Enable the history mechanism
f = ot.MemoizeFunction(f)

# %%
# Evaluate the function at a particular point
x = [1.0] * f.getInputDimension()
y = f(x)
print('x=', x, 'y=', y)

# %%
# Get the history
samplex = f.getInputHistory()
sampley = f.getOutputHistory()
print('evaluation history = ', samplex, sampley)

# %%
# Clear the history mechanism
def rastriginPy(X):
    A = 10.0
    delta = [x**2 - A * np.cos(2 * np.pi * x) for x in X]
    y = A + sum(delta)
    return [y]


dim = 2
rastrigin = ot.PythonFunction(dim, 1, rastriginPy)
print(rastrigin([1.0, 1.0]))

# %%
# Making `rastrigin` into a :class:`~openturns.MemoizeFunction` will make it recall all evaluated points.

# %%
rastrigin = ot.MemoizeFunction(rastrigin)

# %%
# This example is academic and the point achieving the global minimum of the function is known.

# %%
xexact = [0.0] * dim
print(xexact)

# %%
# The optimization bounds must be specified.

# %%
lowerbound = [-4.4] * dim
upperbound = [5.12] * dim
bounds = ot.Interval(lowerbound, upperbound)
# %%
x0 = ot.Point([-1.0, 1.0])

# %%
xexact = ot.Point([1.0, 1.0])

# %%
lowerbound = [-2.0, -2.0]
upperbound = [2.0, 2.0]

# %%
# Plot the iso-values of the objective function
# ---------------------------------------------

# %%
rosenbrock = ot.MemoizeFunction(rosenbrock)

# %%
graph = rosenbrock.draw(lowerbound, upperbound, [100] * 2)
graph.setTitle("Rosenbrock function")
view = viewer.View(graph)

# %%
# We see that the minimum is on the top right of the picture and the starting point is on the top left of the picture. Since the function has a long valley following the curve :math:`x_2 - x^2=0`, the algorithm generally have to follow the bottom of the valley.

# %%
# Create and solve the optimization problem
# -----------------------------------------

# %%
problem = ot.OptimizationProblem(rosenbrock)
Example #9
0
    # GumbelMuSigma parameter save
    gms_parameters = ot.GumbelMuSigma(1.5, 1.3)
    myStudy.add('gms_parameters', gms_parameters)
    # LogNormalMuSigma parameter save
    lnms_parameters = ot.LogNormalMuSigma(30000.0, 9000.0, 15000)
    myStudy.add('lnms_parameters', lnms_parameters)
    # LogNormalMuSigmaOverMu parameter save
    lnmsm_parameters = ot.LogNormalMuSigmaOverMu(0.63, 5.24, -0.5)
    myStudy.add('lnmsm_parameters', lnmsm_parameters)
    # WeibullMinMuSigma parameter save
    wms_parameters = ot.WeibullMinMuSigma(1.3, 1.23, -0.5)
    myStudy.add('wms_parameters', wms_parameters)

    # MemoizeFunction
    f = ot.SymbolicFunction(['x1', 'x2'], ['x1*x2'])
    memoize = ot.MemoizeFunction(f)
    memoize([5, 6])
    myStudy.add('memoize', memoize)

    # print ('Study = ' , myStudy)
    myStudy.save()

    # Create a new Study Object
    myStudy = ot.Study()
    myStudy.setStorageManager(ot.XMLStorageManager(fileName))

    myStudy.load()
    # print 'loaded Study = ' , myStudy

    # MemoizeFunction
    memoize = ot.MemoizeFunction()
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:

I2 = ot.IteratedQuadrature().integrate(f, a, b, l, u)
sample2 = f.getInputHistory()
# print('I2=', I2, '#evals=', sample2.getSize(), \
#! /usr/bin/env python

import openturns as ot
from openturns.testing import assert_almost_equal


f = ot.SymbolicFunction("x", "x^2")
f = ot.MemoizeFunction(f)
f.disableHistory()
print(f)
size = 4
inputSample = ot.Sample(size, 1)
for i in range(size):
    inputSample[i, 0] = i
outputSample = f(inputSample)
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
f.enableHistory()
outputSample = f(inputSample)
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
f.clearHistory()
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
# Perform the computation twice
outputSample = f(inputSample)
outputSample = f(inputSample)
print("input history=", f.getInputHistory())
# %%
# Create the model.

# %%
model = ot.SymbolicFunction(['R', 'F'], ['R-F/(pi_*100.0)'])

# %%
modelCallNumberBefore = model.getEvaluationCallsNumber()
modelGradientCallNumberBefore = model.getGradientCallsNumber()
modelHessianCallNumberBefore = model.getHessianCallsNumber()

# %%
# To have access to the input and output samples after the simulation, activate the History mechanism.

# %%
model = ot.MemoizeFunction(model)

# %%
# Remove all the values stored in the history mechanism.
# Care : it is done regardless the status of the History mechanism.

# %%
model.clearHistory()

# %%
# Create the event whose probability we want to estimate.

# %%
vect = ot.RandomVector(distribution)
G = ot.CompositeRandomVector(model, vect)
event = ot.ThresholdEvent(G, ot.Less(), 0.0)
#
# The `MemoizeFunction` class defines a history system to store the calls to the function.
#
#  ====================   ===============================================
#  Methods                Description
#  ====================   ===============================================
#  `enableHistory()`      enables the history (it is enabled by default)
#  `disableHistory()`     disables the history
#  `clearHistory()`       deletes the content of the history
#  `getHistoryInput()`    a `Sample`, the history of inputs X
#  `getHistoryOutput()`   a `Sample`, the history of outputs Y
#  ====================   ===============================================

# %%
myfunction = ot.PythonFunction(3, 2, mySimulator)
myfunction = ot.MemoizeFunction(myfunction)

# %%
outputVariableOfInterest = ot.CompositeRandomVector(myfunction,
                                                    inputRandomVector)
montecarlosize = 10
outputSample = outputVariableOfInterest.getSample(montecarlosize)

# %%
# Get the history of input points.

# %%
inputs = myfunction.getInputHistory()
inputs

# %%
Example #14
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

f = ot.SymbolicFunction("x", "x^2")
f = ot.MemoizeFunction(f)
f.disableHistory()
print(f)
size = 4
inputSample = ot.Sample(size, 1)
for i in range(size):
    inputSample[i, 0] = i
outputSample = f(inputSample)
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
f.enableHistory()
outputSample = f(inputSample)
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
f.clearHistory()
print("Is history enabled for f? ", f.isHistoryEnabled())
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())
# Perform the computation twice
outputSample = f(inputSample)
outputSample = f(inputSample)
print("input history=", f.getInputHistory())
print("output history=", f.getOutputHistory())