Example #1
0
    def optimizeLambda(self, marginal, deltaRHS):
        """
        Compute the lambda values

        Parameters
        ----------
        marginal : int
            The indice of the perturbed marginal.
        deltaRHS : sequence of float of dim 2
            The values of the mean and variance + mean^2
        """

        # define the optimization function which the Lagrange function
        # and using the gradient and the hessian
        optimFunc = ot.PythonFunction(
            2,
            1,
            lambda lamb: [self.H(marginal, lamb, deltaRHS)],
            gradient=lambda lamb: self.gradH(marginal, lamb, deltaRHS),
            hessian=lambda lamb: self.hessianH(marginal, lamb))

        # define the optimization problem
        optimPb = ot.OptimizationProblem(
            optimFunc, ot.Function(), ot.Function(),
            ot.Interval([-1000.0] * 2, [1000.0] * 2))

        # solve the problem using SLSQP from NLopt
        optim = ot.NLopt(optimPb, 'LD_SLSQP')
        optim.setStartingPoint([0, 0])
        optim.run()
        # return the lambda values, solution of the problem
        return optim.getResult().getOptimalPoint()
Example #2
0
    def run(self):
        """
        Compute the Sobol indices with the chosen algorithm. 
        """

        # create the Function which computes the POD for a given
        # realization and for all defect sizes.
        if self._podType == "kriging":
            self._PODaggr = ot.Function(
                PODaggrKriging(self._POD, self._dim, self._defectSizes,
                               self._detectionBoxCox))
        elif self._podType == "chaos":
            self._PODaggr = ot.Function(
                PODaggrChaos(self._POD, self._dim, self._defectSizes,
                             self._detectionBoxCox, self._simulationSize))

        input_design = ot.SobolIndicesExperiment(self._distribution, self._N,
                                                 False).generate()
        output_design = self._PODaggr(input_design)

        # remove the output marginal when the variance is null because it causes
        # a failure. Must remove also the associated defect sizes.
        selected_marginal_index = []
        for index_output in range(output_design.getDimension()):
            if output_design.getMarginal(
                    index_output)[:self._N].computeCovariance()[0, 0] != 0:
                selected_marginal_index.append(index_output)

        if len(selected_marginal_index) != output_design.getDimension():
            self.setDefectSizes(self._defectSizes[selected_marginal_index])
            selected_output_design = np.array(
                output_design)[:, selected_marginal_index]

            logging.warning("Warning : some output variances are null. " + \
                         "Only the following defect sizes are taken into " + \
                         "account : {}".format(self._defectSizes))
        else:
            selected_output_design = output_design

        if self._method == "Saltelli":
            self._sa = ot.SaltelliSensitivityAlgorithm(input_design,
                                                       selected_output_design,
                                                       self._N)
        elif self._method == "Martinez":
            self._sa = ot.MartinezSensitivityAlgorithm(input_design,
                                                       selected_output_design,
                                                       self._N)
        elif self._method == "Jansen":
            self._sa = ot.JansenSensitivityAlgorithm(input_design,
                                                     selected_output_design,
                                                     self._N)
        elif self._method == "MauntzKucherenko":
            self._sa = ot.MauntzKucherenkoSensitivityAlgorithm(
                input_design, selected_output_design, self._N)

        self._sa.setUseAsymptoticDistribution(True)
Example #3
0
    def _exec(self, X):
        f = ot.Function(
            ot.PiecewiseLinearEvaluation(
                [x[0] for x in self.getInputMesh().getVertices()], X))
        outputValues = ot.Sample(0, 1)
        for t in self.getOutputMesh().getVertices():
            kernel = ot.Normal(t[0], 0.05)

            def pdf(X):
                return [kernel.computePDF(X)]

            weight = ot.Function(ot.PythonFunction(1, 1, pdf))
            outputValues.add(
                self.algo_.integrate(weight * f, kernel.getRange()))
        return outputValues
    def _exec(self, X):
        inputTG = X.getTimeGrid()
        inputValues = X.getValues()
        f = ot.Function(
            ot.PiecewiseLinearEvaluation([x[0] for x in inputTG.getVertices()],
                                         inputValues))
        outputValues = ot.Sample(0, 1)
        for t in self.outputGrid_.getVertices():
            kernel = ot.Normal(t[0], 0.05)

            def pdf(X):
                return [kernel.computePDF(X)]

            weight = ot.Function(ot.PythonFunction(1, 1, pdf))
            outputValues.add(
                self.algo_.integrate(weight * f, kernel.getRange()))
        return ot.Field(self.outputGrid_, outputValues)
Example #5
0
    def __new__(self, path_fmu=None, inputs_fmu=None, outputs_fmu=None,
                inputs=None, outputs=None, n_cpus=None, kind=None,
                initialization_script=None, final_time=None):
        lowlevel = OpenTURNSFMUFunction(
            path_fmu=path_fmu, inputs_fmu=inputs_fmu, outputs_fmu=outputs_fmu,
            inputs=inputs, n_cpus=n_cpus, outputs=outputs, kind=kind,
            initialization_script=initialization_script, final_time=final_time)

        highlevel = ot.Function(lowlevel)
        # highlevel._model = lowlevel.model
        return highlevel
Example #6
0
    def __init__(self, simulateur, annee, S, D):
        """
        Crée un modèle de pension probabiliste.
        
        Paramètres :
            simulateur : un SimulateurRetraite
            annee : un flottant, l'année de calcul de P
            S : un flottant, le solde financier en part de PIB
            D : un flottant positif, le montant des dépenses de retraites 
            en part de PIB
        
        Description :
            Crée un modèle de pension probabiliste pour le 
            ratio (pension moyenne) / (salaire moyen).
            
            Les entrées du modèle sont "As", "F", "TauC" 
            et la sortie est "P". 
            
            Les paramètres S et D sont fixés par le constructeur 
            de la classe au moment de la création de l'objet. 
            
            * S : le solde financier du système de retraites (% PIB)
            * D : le montant des dépenses (% PIB)
            * As : l'âge moyen de départ à la retraite défini par l'utilisateur
            * F  : facteur d'élasticité de report de l'âge de départ 
                (par exemple F=0.5)
            * TauC : le taux de chômage (par exemple TauC = 4.5)

            Les distributions des variables sont ot.Uniform 
            et indépendantes.

        Exemple :
            S = 0.0
            D = 0.14
            annee = 2050
            modele = ModelePensionProbabiliste(simulateur, annee, S, D)
            fonction = modele.getFonction()
            inputDistribution = modele.getInputDistribution()
        """
        # Crée le modèle de pension complet : entrées = (S, D, As, F, TauC)
        modelePension = ot.Function(FonctionPension(simulateur, annee))
        # Crée le modèle réduit à partir du modèle complet : entrées = (As, F, TauC)
        indices = ot.Indices([0, 1])
        referencePoint = ot.Point([S, D])
        self.fonction = ot.ParametricFunction(modelePension, indices, referencePoint)
        # Distribution
        As = ot.Uniform(62.0, 66.0)
        F = ot.Uniform(0.25, 0.75)
        TauC = ot.Uniform(4.5, 10.0)
        self.inputDistribution = ot.ComposedDistribution([As, F, TauC])
        self.inputDistribution.setDescription(["As", "F", "TauC"])
        return
Example #7
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 #8
0
    def build(self, dataX, dataY):
        logLikelihood = ot.Function(ReducedLogLikelihood(dataX, dataY))
        xlb = np.linspace(self.lambdaMin_, self.lambdaMax_, num=500)
        lambdax = [logLikelihood([x])[0] for x in xlb]
        algo = ot.TNC(logLikelihood)
        algo.setStartingPoint([xlb[np.array(lambdax).argmax()]])
        algo.setBoundConstraints(ot.Interval(self.lambdaMin_, self.lambdaMax_))
        algo.setOptimizationProblem(
            ot.BoundConstrainedAlgorithmImplementationResult.MAXIMIZATION)
        algo.run()
        optimalLambda = algo.getResult().getOptimizer()[0]

        # graph
        optimalLogLikelihood = algo.getResult().getOptimalValue()
        graph = logLikelihood.draw(0.01 * optimalLambda, 10.0 * optimalLambda)
        c = ot.Cloud([[optimalLambda, optimalLogLikelihood]])
        c.setColor("red")
        c.setPointStyle("circle")
        graph.add(c)
        return ot.BoxCoxTransform([optimalLambda]), graph
    def _exec(self, X):

        Y = [X[0] + X[1]]
        return Y


F = FUNC()
print(('in_dim=' + str(F.getInputDimension()) + ' out_dim=' +
       str(F.getOutputDimension())))

print((F((10, 5))))

print((F(((10, 5), (6, 7)))))

# Instance creation
myFunc = ot.Function(F)

# Copy constructor
newFunc = ot.Function(myFunc)

print(('myFunc input dimension= ' + str(myFunc.getInputDimension())))
print(('myFunc output dimension= ' + str(myFunc.getOutputDimension())))

inPt = ot.Point(2, 2.)
print((repr(inPt)))

outPt = myFunc(inPt)
print((repr(outPt)))

outPt = myFunc((10., 11.))
print((repr(outPt)))
Example #10
0
 def __new__(self, algo, in_dim, out_dim):
     python_function = SklearnPyFunction(algo, in_dim, out_dim)
     return ot.Function(python_function)
Example #11
0
ot.TESTPREAMBLE()
ot.RandomGenerator.SetSeed(0)


def progress(percent):
    sys.stderr.write('-- progress=' + str(percent) + '%\n')


def stop():
    sys.stderr.write('-- stop?\n')
    return False


# We create a numerical math function
myFunction = ot.Function(
    ["E", "F", "L", "I"], ["d"], ["-F*L^3/(3*E*I)"])

dim = myFunction.getInputDimension()

# We create a normal distribution point of dimension 1
mean = [0.0] * dim
# E
mean[0] = 50.0
# F
mean[1] = 1.0
# L
mean[2] = 10.0
# I
mean[3] = 5.0
sigma = [1.0] * dim
R = ot.IdentityMatrix(dim)
Example #12
0
print('f(x^)=', printPoint(result.getOptimalValue(), 4))
print('lambda^=', printPoint(result.computeLagrangeMultipliers(), 4))

# bounds
linear = ot.SymbolicFunction(
    ['x1', 'x2', 'x3', 'x4'], ['x1+2*x2-3*x3+4*x4'])

dim = 4
startingPoint = [0.] * dim

bounds = ot.Interval([-3.] * dim, [5.] * dim)

for minimization in [True, False]:

    problem = ot.OptimizationProblem(
        linear, ot.Function(), ot.Function(), bounds)
    problem.setMinimization(minimization)
    algo = ot.Cobyla(problem)
    algo.setMaximumEvaluationNumber(150)
    algo.setStartingPoint(startingPoint)
    print('algo=', algo)
    algo.run()
    result = algo.getResult()
    print('x^=', printPoint(result.getOptimalPoint(), 4))
    print('f(x^)=', printPoint(result.getOptimalValue(), 4))
    print('lambda^=', printPoint(result.computeLagrangeMultipliers(), 4))

# empty problem
algo = ot.Cobyla()
try:
    algo.run()
Example #13
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

ot.TESTPREAMBLE()

# Instance creation
myFunc = ot.SymbolicFunction(
    ['x1', 'x2'], ['x1*sin(x2)', 'cos(x1+x2)', '(x2+1)*exp(x1-2*x2)'])

# Copy constructor
newFunc = ot.Function(myFunc)

print("myFunc=" + repr(myFunc))
print("myFunc input parameter(s)=")
for i in range(myFunc.getInputDimension()):
    print(myFunc.getInputDescription()[i])
print("myFunc output parameter(s) and marginal(s)=")
for i in range(myFunc.getOutputDimension()):
    print(myFunc.getOutputDescription()[i])
    print("Marginal function", i, "=", repr(myFunc.getMarginal(i)))

try:
    print(ot.Function() == None)
except TypeError:
    # swig<4
    print(False)
    # Fix numerical precision
    ot.PlatformInfo.SetNumericalPrecision(2)

    # Kriging use case
    spatialDimension = 2

    # Learning data
    levels = [8, 5]
    box = ot.Box(levels)
    inputSample = box.generate()
    # Scale each direction
    inputSample *= 10

    # Define model
    model = ot.Function(['x', 'y'], ['z'], ['cos(0.5*x) + sin(y)'])
    outputSample = model(inputSample)

    # 2) Definition of exponential model
    covarianceModel = ot.SquaredExponential([1.988, 0.924], [3.153])

    # 3) Basis definition
    basisCollection = ot.BasisCollection(
        1,
        ot.ConstantBasisFactory(spatialDimension).build())

    # Kriring algorithm
    algo = ot.KrigingAlgorithm(inputSample, outputSample, covarianceModel,
                               basisCollection)
    algo.run()
    result = algo.getResult()
Example #15
0
    myStudy.add('beta', beta)

    # Create an analytical Function
    input = ot.Description(3)
    input[0] = 'a'
    input[1] = 'b'
    input[2] = 'c'
    output = ot.Description(3)
    output[0] = 'squaresum'
    output[1] = 'prod'
    output[2] = 'complex'
    formulas = ot.Description(output.getSize())
    formulas[0] = 'a+b+c'
    formulas[1] = 'a-b*c'
    formulas[2] = '(a+2*b^2+3*c^3)/6'
    analytical = ot.Function(input, output, formulas)
    analytical.setName('analytical')
    myStudy.add('analytical', analytical)

    # Create a TaylorExpansionMoments algorithm
    antecedent = ot.RandomVector(
        ot.IndependentCopula(analytical.getInputDimension()))
    antecedent.setName('antecedent')
    composite = ot.RandomVector(analytical, antecedent)
    composite.setName('composite')
    taylorExpansionsMoments = ot.TaylorExpansionMoments(composite)
    taylorExpansionsMoments.setName('taylorExpansionsMoments')
    taylorExpansionsMoments.getMeanFirstOrder()
    taylorExpansionsMoments.getMeanSecondOrder()
    taylorExpansionsMoments.getCovariance()
print("Relative error: ", result.getRelativeError())
print("Residual error: ", result.getResidualError())
print("Constraint error: ", result.getConstraintError())

# %%
# Solving problem with bounds, using LBFGS strategy
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# In the following example, the input variables will be bounded so the function global optimal point is not included in the search interval.
#
# The problem will be solved using LBFGS strategy, which allows the user to limit the amount of memory used by the optimization process.

# %%
# Define the bounds and the problem
bounds = ot.Interval([0.0, 0.0], [0.8, 2.0])
boundedProblem = ot.OptimizationProblem(rosenbrock, ot.Function(),
                                        ot.Function(), bounds)

# %%
# Define the Dlib algorithm
boundedAlgo = ot.Dlib(boundedProblem, "lbfgs")
boundedAlgo.setMaxSize(15)  # Default value for LBFGS' maxSize parameter is 10

startingPoint = [0.5, 1.5]
boundedAlgo.setStartingPoint(startingPoint)

boundedAlgo.run()

# %%
# Retrieve results
result = boundedAlgo.getResult()
Example #17
0
#!/usr/bin/env python

from __future__ import print_function, division
import openturns as ot

#
# Physical model
#

limitState = ot.Function(['u1', 'u2'], ['g'], ['u1-u2'])
dim = limitState.getInputDimension()

#
# Probabilistic model
#

mean = ot.Point(dim, 0.0)
mean[0] = 7.
mean[1] = 2.
sigma = ot.Point(dim, 1.0)

R = ot.IdentityMatrix(dim)
myDistribution = ot.Normal(mean, sigma, R)

#
# Limit state
#

vect = ot.RandomVector(myDistribution)

output = ot.RandomVector(limitState, vect)
study.save()

# %%
# Create a new study associated to the same file
study = ot.Study()
study.setStorageManager(ot.XMLStorageManager(fileName))

# %%
# Load the file and all its objects
study.load()

# %%
# Check the content of the myStudy
print("Study = ", study)

# %%
# List names of stored objects
study.printLabels()

# %%
# Check our 'distribution' labelled object was loaded
study.hasObject('distribution')

# %%
# Load the objects; we must create a void object of the desired type (or parent type)
distribution2 = ot.Normal()
function2 = ot.Function()
study.fillObject('distribution', distribution2)
study.fillObject('function', function2)
str(distribution2), str(function2)
Example #19
0
    print("      -- Evaluation number = ", result.getEvaluationNumber())
    print("      -- Absolute error = {:.6e}".format(result.getAbsoluteError()))
    print("      -- Relative error = {:.6e}".format(result.getRelativeError()))
    print("      -- Residual error = {:.6e}".format(result.getResidualError()))
    print("      -- Constraint error = {:.6e}".format(
        result.getConstraintError()))


# Define the problems based on Rastrigin function
rastrigin = ot.SymbolicFunction(
    ['x1', 'x2'], ['20 + x1^2 - 10*cos(2*pi_*x1) + x2^2 - 10*cos(2*pi_*x2)'])

unboundedProblem = ot.OptimizationProblem(rastrigin)

notConstrainingBounds = ot.Interval([-5.0, -5.0], [3.0, 2.0])
notConstrainingBoundsProblem = ot.OptimizationProblem(rastrigin, ot.Function(),
                                                      ot.Function(),
                                                      notConstrainingBounds)

constrainingBounds = ot.Interval([-1.0, -2.0], [5.0, -0.5])
constrainingBoundsProblem = ot.OptimizationProblem(rastrigin, ot.Function(),
                                                   ot.Function(),
                                                   constrainingBounds)

boundedPref = [0.0, -1.0]
unboundedPref = [0.0, 0.0]

## GLOBAL ALGORITHM ##

# Non-contraining bounds Global
notConstrainingBoundsGlobal = ot.Dlib(notConstrainingBoundsProblem, "Global")
tensorEval = ot.CanonicalTensorEvaluation(factoryCollection, nk, rank)

for r in range(rank):
    for j in range(dim):
        coefs = ot.Normal(nk[j]).getRealization()
        tensorEval.setCoefficients(r, j, coefs)

tensorGrad = ot.CanonicalTensorGradient(tensorEval)

x = [1.0] * dim
print(x)

df = tensorGrad.gradient(x) * ot.Point([1.0])
print('df=', df)

f = ot.Function(tensorEval)
fx = f(x)[0]

eps = 1e-5

dffd = [0.0] * dim
for i in range(dim):
    xp = ot.Point(x)
    xp[i] += eps
    fp = f(xp)
    dffd[i] = (f(xp)[0] - fx) / eps
print('dffd', dffd)

# print(tensor)

ottest.assert_almost_equal(df, dffd, 1e-4)
Example #21
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

eps = 0.4
# Instance creation
myFunc = ot.Function(['x1', 'x2'], ['f1', 'f2', 'f3'],
                     ['x1*sin(x2)', 'cos(x1+x2)', '(x2+1)*exp(x1-2*x2)'])
center = ot.Point(myFunc.getInputDimension())
for i in range(center.getDimension()):
    center[i] = 1.0 + i
myTaylor = ot.QuadraticTaylor(center, myFunc)
myTaylor.run()
responseSurface = ot.Function(myTaylor.getResponseSurface())
print("myTaylor=", repr(myTaylor))
print("responseSurface=", repr(responseSurface))
print("myFunc(", repr(center), ")=", repr(myFunc(center)))
print("responseSurface(", repr(center), ")=", repr(responseSurface(center)))
inPoint = ot.Point(center)
inPoint[0] += eps
inPoint[1] -= eps / 2
print("myFunc(", repr(inPoint), ")=", repr(myFunc(inPoint)))
print("responseSurface(", repr(inPoint), ")=", repr(responseSurface(inPoint)))
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot
import os

ot.TESTPREAMBLE()

f = ot.Function()

# load
study = ot.Study()
study.setStorageManager(ot.XMLStorageManager('pyf.xml'))
study.load()
study.fillObject('f', f)

x = [4, 5]
print(f(x))

os.remove('pyf.xml')
import openturns as ot
import otrobopt
from matplotlib import pyplot as plt
from openturns.viewer import View

thetaDist = ot.Normal(2.0, 0.1)
if 'VarianceMeasure' == 'WorstCaseMeasure':
    thetaDist = ot.Uniform(-1.0, 4.0)
elif 'ChanceMeasure' in 'VarianceMeasure':
    thetaDist = ot.Normal(1.0, 1.0)

f_base = ot.Function(['x', 'theta'], ['y'], ['x*theta'])
f = ot.Function(f_base, [1], thetaDist.getMean())

if 'VarianceMeasure' == 'JointChanceMeasure':
    measure = otrobopt.JointChanceMeasure(f, thetaDist, ot.GreaterOrEqual(),
                                          0.95)
elif 'VarianceMeasure' == 'IndividualChanceMeasure':
    measure = otrobopt.IndividualChanceMeasure(f, thetaDist,
                                               ot.GreaterOrEqual(), [0.95])
elif 'VarianceMeasure' == 'MeanStandardDeviationTradeoffMeasure':
    measure = otrobopt.MeanStandardDeviationTradeoffMeasure(
        f, thetaDist, [0.8])
elif 'VarianceMeasure' == 'QuantileMeasure':
    measure = otrobopt.QuantileMeasure(f, thetaDist, 0.99)
else:
    measure = otrobopt.VarianceMeasure(f, thetaDist)

N = 10
experiment = ot.LHSExperiment(N)
factory = otrobopt.MeasureFactory(experiment)
Example #24
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

# Create a function
f = ot.Function(["x", "y"], ["z"], ["exp(-sin(cos(y)^2*x^2+sin(x)^2*y^2))"])

# Generate the data for the curves to be drawn
nX = 75
nY = 75
inputData = ot.Box([nX, nY]).generate()
inputData *= [10.0] * 2
inputData += [-5.0] * 2
data = f(inputData)
levels = [(0.5 + i) / 5 for i in range(5)]
# Create an empty graph
graph = ot.Graph("Complex iso lines", "u1", "u2", True, "")

# Create the contour
contour = ot.Contour(nX + 2, nY + 2, data)
contour.setLevels(levels)

# Then, draw it
graph.add(contour)

fig = plt.figure(figsize=(4, 4))
plt.suptitle("Complex iso lines example")
axis = fig.add_subplot(111)
axis.set_xlim(auto=True)
View(graph, figure=fig, axes=[axis], add_legend=False)
Example #25
0
data[4] = point
point[0] = -0.25
point[1] = -0.25
data[5] = point
point[0] = -0.25
point[1] = 0.25
data[6] = point
point[0] = 0.25
point[1] = -0.25
data[7] = point
point[0] = 0.25
point[1] = 0.25
data[8] = point
myLeastSquares = ot.LinearLeastSquares(data, myFunc)
myLeastSquares.run()
responseSurface = ot.Function(myLeastSquares.getMetaModel())
print("myLeastSquares=", repr(myLeastSquares))
print("responseSurface=", repr(responseSurface))
inPoint = ot.Point(myFunc.getInputDimension(), 0.1)
print("myFunc(", repr(inPoint), ")=", repr(myFunc(inPoint)))
print("responseSurface(", repr(inPoint), ")=", repr(responseSurface(inPoint)))
dataOut = myFunc(data)
myLeastSquares = ot.LinearLeastSquares(data, dataOut)
myLeastSquares.run()
responseSurface = ot.Function(myLeastSquares.getMetaModel())
print("myLeastSquares=", repr(myLeastSquares))
print("responseSurface=", repr(responseSurface))
inPoint = ot.Point(myFunc.getInputDimension(), 0.1)
print("myFunc(", repr(inPoint), ")=", repr(myFunc(inPoint)))
print("responseSurface(", repr(inPoint), ")=", repr(responseSurface(inPoint)))
Example #26
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

eps = 0.4
# Instance creation
myFunc = ot.SymbolicFunction(
    ['x1', 'x2'], ['x1*sin(x2)', 'cos(x1+x2)', '(x2+1)*exp(x1-2*x2)'])
center = ot.Point(myFunc.getInputDimension())
for i in range(center.getDimension()):
    center[i] = 1.0 + i
myTaylor = ot.QuadraticTaylor(center, myFunc)
myTaylor.run()
responseSurface = ot.Function(myTaylor.getMetaModel())
print("myTaylor=", repr(myTaylor))
print("responseSurface=", repr(responseSurface))
print("myFunc(", repr(center), ")=", repr(myFunc(center)))
print("responseSurface(", repr(center), ")=", repr(responseSurface(center)))
inPoint = ot.Point(center)
inPoint[0] += eps
inPoint[1] -= eps / 2
print("myFunc(", repr(inPoint), ")=", repr(myFunc(inPoint)))
print("responseSurface(", repr(inPoint), ")=", repr(responseSurface(inPoint)))
Example #27
0
    # Create a Beta distribution from the one stored in the Study
    beta = ot.Beta()
    myStudy.fillObject('beta', beta)

    print('beta = ', beta)

    randomGeneratorState = ot.RandomGeneratorState()

    myStudy.fillObject('randomGeneratorState', randomGeneratorState)

    print('randomGeneratorState = ', randomGeneratorState)

    # Create an analytical Function from the one stored in the
    # Study
    analytical = ot.Function()
    myStudy.fillObject('analytical', analytical)

    print('analytical = ', analytical)
    print('analytical.outputDescription=', analytical.getOutputDescription())

    # Create a GeneralLinearModelResult from the one stored in the Study
    generalizedLinearModelResult = ot.GeneralLinearModelResult()
    myStudy.fillObject('generalizedLinearModelResult',
                       generalizedLinearModelResult)

    print('generalizedLinearModelResult = ', generalizedLinearModelResult)

    # KDTree
    kDTree = ot.KDTree()
    myStudy.fillObject('kDTree', kDTree)
Example #28
0
    def __init__(self, strategy, degree, distributions, N_quad=None, sample=None,
                 stieltjes=True, sparse_param={}):
        """Generate truncature and projection strategies.

        Allong with the strategies the sample is storred as an attribute.
        :attr:`sample` as well as corresponding weights: :attr:`weights`.

        :param str strategy: Least square or Quadrature ['LS', 'Quad', 'SparseLS'].
        :param int degree: Polynomial degree.
        :param  distributions: Distributions of each input parameter.
        :type distributions: lst(:class:`openturns.Distribution`)
        :param array_like sample: Samples for least square
          (n_samples, n_features).
        :param bool stieltjes: Wether to use Stieltjes algorithm for the basis.
        :param dict sparse_param: Parameters for the Sparse Cleaning Truncation
          Strategy and/or hyperbolic truncation of the initial basis.

            - **max_considered_terms** (int) -- Maximum Considered Terms,
            - **most_significant** (int), Most Siginificant number to retain,
            - **significance_factor** (float), Significance Factor,
            - **hyper_factor** (float), factor for hyperbolic truncation
              strategy.
        """
        # distributions
        self.in_dim = len(distributions)
        self.dist = ot.ComposedDistribution(distributions)
        self.sparse_param = sparse_param

        if 'hyper_factor' in self.sparse_param:
            enumerateFunction = ot.EnumerateFunction(self.in_dim, self.sparse_param['hyper_factor'])
        else:
            enumerateFunction = ot.EnumerateFunction(self.in_dim)

        if stieltjes:
            # Tend to result in performance issue
            self.basis = ot.OrthogonalProductPolynomialFactory(
                [ot.StandardDistributionPolynomialFactory(
                    ot.AdaptiveStieltjesAlgorithm(marginal))
                 for marginal in distributions], enumerateFunction)
        else:
            self.basis = ot.OrthogonalProductPolynomialFactory(
                [ot.StandardDistributionPolynomialFactory(margin)
                 for margin in distributions], enumerateFunction)

        self.n_basis = enumerateFunction.getStrataCumulatedCardinal(degree)

        # Strategy choice for expansion coefficient determination
        self.strategy = strategy
        if self.strategy == 'LS' or self.strategy == 'SparseLS':  # least-squares method
            self.sample = sample
        else:  # integration method
            # redefinition of sample size
            # n_samples = (degree + 1) ** self.in_dim
            # marginal degree definition
            # by default: the marginal degree for each input random
            # variable is set to the total polynomial degree 'degree'+1
            measure = self.basis.getMeasure()

            if N_quad is not None:
                degrees = [int(N_quad ** 0.25)] * self.in_dim
            else:
                degrees = [degree + 1] * self.in_dim

            self.proj_strategy = ot.IntegrationStrategy(
                ot.GaussProductExperiment(measure, degrees))
            self.sample, self.weights = self.proj_strategy.getExperiment().generateWithWeights()

            if not stieltjes:
                transformation = ot.Function(ot.MarginalTransformationEvaluation(
                    [measure.getMarginal(i) for i in range(self.in_dim)],
                    distributions, False))
                self.sample = transformation(self.sample)

        self.pc = None
        self.pc_result = None
Example #29
0
algo.run()
print('algo=', algo)
algo.run()
result = algo.getResult()
print('x^=', printPoint(result.getOptimalPoint(), 4))
print('f(x^)=', printPoint(result.getOptimalValue(), 4))
print('lambda^=', printPoint(result.getLagrangeMultipliers(), 4))

# bounds
linear = ot.SymbolicFunction(['x1', 'x2', 'x3', 'x4'], ['x1+2*x2-3*x3+4*x4'])

dim = 4
startingPoint = [0.] * dim

bounds = ot.Interval([-3.] * dim, [5.] * dim)

for minimization in [True, False]:

    problem = ot.OptimizationProblem(linear, ot.Function(), ot.Function(),
                                     bounds)
    problem.setMinimization(minimization)
    algo = ot.Cobyla(problem)
    algo.setMaximumIterationNumber(150)
    algo.setStartingPoint(startingPoint)
    print('algo=', algo)
    algo.run()
    result = algo.getResult()
    print('x^=', printPoint(result.getOptimalPoint(), 4))
    print('f(x^)=', printPoint(result.getOptimalValue(), 4))
    print('lambda^=', printPoint(result.getLagrangeMultipliers(), 4))
Example #30
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

eps = 0.2
# Instance creation
myFunc = ot.SymbolicFunction(
    ['x1', 'x2'], ['x1*sin(x2)', 'cos(x1+x2)', '(x2+1)*exp(x1-2*x2)'])
center = ot.Point(myFunc.getInputDimension())
for i in range(center.getDimension()):
    center[i] = 1.0 + i
myTaylor = ot.LinearTaylor(center, myFunc)
myTaylor.run()
responseSurface = ot.Function(myTaylor.getResponseSurface())
print("myTaylor=", repr(myTaylor))
print("responseSurface=", repr(responseSurface))
print("myFunc(", repr(center), ")=", repr(myFunc(center)))
print("responseSurface(", repr(center), ")=", repr(responseSurface(center)))
inPoint = ot.Point(center)
inPoint[0] += eps
inPoint[1] -= eps / 2
print("myFunc(", repr(inPoint), ")=", repr(myFunc(inPoint)))
print("responseSurface(", repr(inPoint), ")=", repr(responseSurface(inPoint)))