Beispiel #1
0
 def getRange(self):
     return ot.Interval(-1.0, 1.0)
def test_one_input_one_output():
    sampleSize = 6
    dimension = 1

    f = ot.SymbolicFunction(['x0'], ['x0 * sin(x0)'])

    X = ot.Sample(sampleSize, dimension)
    X2 = ot.Sample(sampleSize, dimension)
    for i in range(sampleSize):
        X[i, 0] = 3.0 + i
        X2[i, 0] = 2.5 + i
    X[0, 0] = 1.0
    X[1, 0] = 3.0
    X2[0, 0] = 2.0
    X2[1, 0] = 4.0
    Y = f(X)
    Y2 = f(X2)

    # create covariance model
    basis = ot.ConstantBasisFactory(dimension).build()
    covarianceModel = ot.SquaredExponential()

    # create algorithm
    algo = ot.KrigingAlgorithm(X, Y, covarianceModel, basis)

    # set sensible optimization bounds and estimate hyperparameters
    algo.setOptimizationBounds(ot.Interval(X.getMin(), X.getMax()))
    algo.run()

    # perform an evaluation
    result = algo.getResult()

    ott.assert_almost_equal(result.getMetaModel()(X), Y)
    ott.assert_almost_equal(result.getResiduals(), [1.32804e-07], 1e-3, 1e-3)
    ott.assert_almost_equal(result.getRelativeErrors(), [5.20873e-21])

    # Kriging variance is 0 on learning points
    covariance = result.getConditionalCovariance(X)
    nullMatrix = ot.Matrix(sampleSize, sampleSize)
    ott.assert_almost_equal(covariance, nullMatrix, 0.0, 1e-14)

    # Kriging variance is non-null on validation points
    validCovariance = result.getConditionalCovariance(X2)
    values = ot.Matrix([[0.81942182, -0.35599947,-0.17488593, 0.04622401, -0.03143555, 0.04054783],
                        [-0.35599947, 0.20874735, 0.10943841, -0.03236419, 0.02397483, -0.03269184],
                        [-0.17488593, 0.10943841, 0.05832917, -0.01779918, 0.01355719, -0.01891618],
                        [0.04622401, -0.03236419, -0.01779918, 0.00578327, -0.00467674, 0.00688697],
                        [-0.03143555, 0.02397483, 0.01355719, -0.00467674, 0.0040267, -0.00631173],
                        [0.04054783, -0.03269184, -0.01891618, 0.00688697, -0.00631173, 0.01059488]])
    ott.assert_almost_equal(validCovariance - values, nullMatrix, 0.0, 1e-7)


    # Covariance per marginal & extract variance component
    coll = result.getConditionalMarginalCovariance(X)
    var = [mat[0, 0] for mat in coll]
    ott.assert_almost_equal(var, [0]*sampleSize, 1e-14, 1e-14)

    # Variance per marginal
    var = result.getConditionalMarginalVariance(X)
    ott.assert_almost_equal(var, ot.Point(sampleSize), 1e-14, 1e-14)

    # Prediction accuracy
    ott.assert_almost_equal(Y2, result.getMetaModel()(X2), 0.3, 0.0)
Beispiel #3
0
#! /usr/bin/env python

import openturns as ot

ot.TESTPREAMBLE()

dim = 2
interval = ot.Interval([0.0] * dim, [10.0] * dim)
mesh = ot.IntervalMesher([30] * dim).build(interval)
f = ot.SymbolicFunction(["x", "y"], ["x + 0.5*sin(y)", "y-0.1*x*sin(x)"])
mesh.setVertices(f(mesh.getVertices()))

simplices = mesh.getSimplices()
nrSimplices = len(simplices)
naive = ot.NaiveEnclosingSimplex(mesh.getVertices(), simplices)
print("naive=", naive)

ot.RandomGenerator.SetSeed(0)
test = ot.ComposedDistribution([ot.Uniform(-1.0, 11.0)] * dim).getSample(100)

for i, vertex in enumerate(test):
    index = naive.query(vertex)
    if index >= nrSimplices:
        print(i, "is outside")
    else:
        found, coordinates = mesh.checkPointInSimplexWithCoordinates(
            vertex, index)
        if not found:
            print("Wrong simplex found for", vertex, "(index=", index,
                  simplices[index], "barycentric coordinates=", coordinates)
# %%
# Evaluate the survival function at the mean point
dist_2.computeSurvivalFunction(dist_2.getMean())

# %%
# Evaluate the PDF on a sample
dist_2.computePDF(dist_2.getSample(5))

# %%
# Evaluate the CDF on a sample
dist_2.computeCDF(dist_2.getSample(5))

# %%
# Evaluate the probability content of an 1-d interval
interval = ot.Interval(-2.0, 3.0)
dist_1.computeProbability(interval)

# %%
# Evaluate the probability content of a 2-d interval
interval = ot.Interval([0.4, -1], [3.4, 2])
dist_2.computeProbability(interval)

# %%
# Evaluate the quantile of order p=90%
dist_2.computeQuantile(0.90)

# %%
# and the quantile of order 1-p
dist_2.computeQuantile(0.90, True)
Beispiel #5
0
# Instantiate one distribution object
referenceDistribution = [
    ot.TruncatedNormal(2.0, 1.5, 1.0, 4.0),
    ot.TruncatedNormal(2.0, 1.5, 1.0, 200.0),
    ot.TruncatedNormal(2.0, 1.5, -200.0, 4.0),
    ot.TruncatedNormal(2.0, 1.5, 1.0, 4.0)
]
distribution = [
    ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 1.0, 4.0),
    ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 1.0,
                             ot.TruncatedDistribution.LOWER),
    ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 4.0,
                             ot.TruncatedDistribution.UPPER),
    ot.TruncatedDistribution(ot.Normal(2.0, 1.5),
                             ot.Interval([1.0], [4.0], [True], [True]))
]

# add a 2-d test
dimension = 2
# This distribution takes too much time for the test
#size = 70
#ref = ot.Normal(dimension)
#sample = ref.getSample(size)
#ks = ot.KernelSmoothing().build(sample)
# Use a multivariate Normal distribution instead
ks = ot.Normal(2)
truncatedKS = ot.TruncatedDistribution(
    ks, ot.Interval([-0.5] * dimension, [2.0] * dimension))
distribution.append(truncatedKS)
referenceDistribution.append(ks)  # N/A
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

try:
    mesh = ot.IntervalMesher([9]).build(ot.Interval(-1.0, 1.0))
    cov1D = ot.AbsoluteExponential([1.0])
    algo = ot.KarhunenLoeveP1Algorithm(mesh, cov1D, 0.0)
    algo.run()
    result = algo.getResult()
    lambd = result.getEigenValues()
    KLModes = result.getModesAsProcessSample()
    print("KL modes=", KLModes)
    print("KL eigenvalues=", lambd)
    process = ot.TemporalNormalProcess(cov1D, KLModes.getMesh())
    coefficients = result.project(process.getSample(10))
    print("KL coefficients=", coefficients)
    KLFunctions = result.getModes()
    print("KL functions=", KLFunctions)
    print("KL lift=", result.lift(coefficients[0]))
    print("KL lift as field=", result.liftAsField(coefficients[0]))
    R = ot.CorrelationMatrix(2)
    R[0, 1] = 0.5
    scale = [1.0]
    amplitude = [1.0, 2.0]
    cov2D = ot.ExponentialModel(scale, amplitude, R)
    algo = ot.KarhunenLoeveP1Algorithm(mesh, cov2D, 0.0)
    algo.run()
    result = algo.getResult()
    lambd = result.getEigenValues()
Beispiel #7
0
algo.setMaximumConstraintError(1.0e-10)
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))
Beispiel #8
0
model = ot.SymbolicFunction(['a', 'b', 'c', 'x'],
                            ['a + b * exp(min(500, c * x))'])
p_ref = [2.8, 1.2, 0.5]  # a, b, c
modelx = ot.ParametricFunction(model, [0, 1, 2], p_ref)
y = modelx(x)


def residualFunction_py(p):
    modelx = ot.ParametricFunction(model, [0, 1, 2], p)
    return [modelx(x[i])[0] - y[i, 0] for i in range(m)]


residualFunction = ot.PythonFunction(n, m, residualFunction_py)

bounds = ot.Interval([0, 0, 0], [2.5, 8.0, 19])

for algoName in algoNames:
    line_search = not (algoName in ['LEVENBERG_MARQUARDT', 'DOGLEG'])
    for bound in [True, False]:
        if bound and line_search:
            # line search do not support bound constraints
            continue
        print('algoName=', algoName, 'bound=', bound)
        problem = ot.LeastSquaresProblem(residualFunction)
        if bound:
            problem.setBounds(bounds)
        startingPoint = [1.0] * n
        algo = ot.Ceres(problem, algoName)
        algo.setStartingPoint(startingPoint)
        # algo.setProgressCallback(progress)
Beispiel #9
0
# variables
dist_z0 = ot.Uniform(100, 150)
z0 = persalys.Input('z0', 100, dist_z0, '')
dist_v0 = ot.Normal(55, 10)
v0 = persalys.Input('v0', 55, dist_v0, '')
dist_m = ot.Normal(80, 8)
m = persalys.Input('m', 80, dist_m, '')
dist_c = ot.Uniform(0, 30)
c = persalys.Input('c', 16, dist_c, '')
z1 = persalys.Output('z1', '')
z2 = persalys.Output('z2', 'fake output')
inputs = [z0, v0, m, c]
outputs = [z1, z2]

# mesh model
meshModel = persalys.GridMeshModel(ot.Interval(0., 12.), [20])

# Python model
code = 'from math import exp\n\ndef _exec(z0,v0,m,c):\n    g = 9.81\n    zmin = 0.\n    tau = m / c\n    vinf = -m * g / c\n\n    # mesh nodes\n    t = getMesh().getVertices()\n\n    z = [max(z0 + vinf * t_i[0] + tau * (v0 - vinf) * (1 - exp(-t_i[0] / tau)), zmin) for t_i in t]\n    z2 = [2*max(z0 + vinf * t_i[0] + tau * (v0 - vinf) * (1 - exp(-t_i[0] / tau)), zmin) for t_i in t]\n\n    return z, z2'
PhysicalModel_1 = persalys.PythonFieldModel('PhysicalModel_1', meshModel, inputs, outputs, code)
Study_0.add(PhysicalModel_1)

# central tendency
mcAnalysis1 = persalys.FieldMonteCarloAnalysis("mcAnalysis", PhysicalModel_1)
mcAnalysis1.setMaximumCalls(10)
mcAnalysis1.setMaximumElapsedTime(1000)
mcAnalysis1.setBlockSize(5)
mcAnalysis1.setSeed(2)
mcAnalysis1.setInterestVariables(['z'])
mcAnalysis1.setKarhunenLoeveThreshold(2e-5)
Study_0.add(mcAnalysis1)
#! /usr/bin/env python

import openturns as ot

ot.PlatformInfo.SetNumericalPrecision(6)

dim = 2

# First domain: [0,2]x[0,2]
cube = ot.Interval([0.0] * dim, [2.0] * dim)

# Second domain: sphere center=(0,0) r=1
function = ot.SymbolicFunction(["x", "y"], ["x^2 + y^2"])
sphere = ot.LevelSet(function, ot.LessOrEqual(), 1.0)

# Inside sphere but not cube
p0 = [-0.25, 0.25]
# Inside cube and sphere
p1 = [0.25, 0.25]
# Inside cube but not sphere
p2 = [1.8, 1.8]
# Outside
p3 = [4.0, 4.0]

domain = ot.DomainDisjunctiveUnion(cube, sphere)
print("cube=", cube)
print("sphere=", sphere)
print("disjunctive union=", domain)
# Accessors
print("Dimension=", domain.getDimension())
# Contains
Beispiel #11
0
def PlotDesign(design,
               bounds=None,
               subdivisions=None,
               figure=None,
               axes=[],
               plot_kwargs=None,
               axes_kwargs=None,
               text_kwargs=None,
               enableTicks=True):
    """
    Plot a design using a scatter plot. 
    If the dimension is equal to 2, then plots the 2D projection. 
    If the dimension is greater or equal to 3, then plots all 2D projections.

    In addition, the function plots a grid, i.e. horizontal and vertical lines
    to see the dispersion of the points. 
    This allows to see how the sample fills the space. 

    Parameters
    ----------
    design : 2-d sequence of float
        The sample. 
    figure : a Matplotlib figure. 
        If this is not None, then create a new figure. 
        Otherwise, use the existing figure. 
    axes : a Matplotlib axis. 
        If empty, then create new axes. 
    bounds: :class:`~openturns.Interval`
        Bounds of the plot. By default, compute the bounds from the sample. 
    subdivisions : a list of integers
        Number of subdivisions in the each direction. 
        By default, set the number of subdivisions in each direction 
        as equal to the sample size. 
    enableTicks :
        A boolean. If True, then the ticks are plotted. 

    Returns
    -------
    fig : matplotlib figure
          Figure representing the sample.

    Examples
    --------
    
    Plot a sample in 2 dimensions.
    
    >>> import openturns as ot
    >>> from openturns.viewer import PlotDesign
    >>> dim = 20
    >>> X = [ot.Uniform()] * dim
    >>> distribution = ot.ComposedDistribution(X)
    >>> sampleSize = 10
    >>> sample = distribution.getSample(sampleSize)
    >>> fig = PlotDesign(sample)

    Plot a sample in 5 dimensions.

    >>> import openturns as ot
    >>> from openturns.viewer import PlotDesign
    >>> dim = 5
    >>> size = 10
    >>> distribution = ot.ComposedDistribution([ot.Uniform(0.0, 1.0)]*dim)
    >>> bounds = distribution.getRange()
    >>> lhs = ot.LHSExperiment(distribution, size)
    >>> sample = lhs.generate()
    >>> subdivisions = [size]*dim
    >>> fig = PlotDesign(sample, bounds, subdivisions)
    """
    # check that arguments are dictionnaries
    axes_kwargs = View._CheckDict(axes_kwargs)
    plot_kwargs = View._CheckDict(plot_kwargs)
    text_kwargs = View._CheckDict(text_kwargs)

    # retrieve data
    data = ot.Sample(design)
    dim = data.getDimension()
    if dim < 2:
        raise TypeError('Expected designs of dimension >=2')

    # Get the bounds
    if bounds is None:
        lowerBound = data.getMin()
        upperBound = data.getMax()
        bounds = ot.Interval(lowerBound, upperBound)
    if bounds.getDimension() != dim:
        raise ValueError(
            'Dimension of bounds %d do not match the dimension of the sample %d'
            % (bounds.getDimension(), dim))

    # Check the subdivisions
    if subdivisions is None:
        size = data.getSize()
        subdivisions = [size] * dim
    if len(subdivisions) != dim:
        raise ValueError(
            'Number of subdivisions %d does not match the dimension of the sample %d'
            % (len(subdivisions), dim))

    # Get description
    labels = data.getDescription()

    # adjust font
    if (not 'fontsize' in text_kwargs) and (not 'size' in text_kwargs):
        text_kwargs['fontsize'] = max(16 - dim, 4)
    text_kwargs.setdefault('horizontalalignment', 'center')
    text_kwargs.setdefault('verticalalignment', 'center')

    # set marker
    pointStyleDict = {
        'square': 's',
        'circle': 'o',
        'triangleup': '2',
        'plus': '+',
        'times': '+',
        'diamond': '+',
        'triangledown': 'v',
        'star': '*',
        'fsquare': 's',
        'fcircle': 'o',
        'ftriangleup': '2',
        'fdiamond': 'D',
        'bullet': '.',
        'dot': ',',
        'none': 'None'
    }
    if not 'marker' in plot_kwargs:
        plot_kwargs['marker'] = pointStyleDict["square"]

    if not enableTicks:
        axes_kwargs['xticks'] = []
        axes_kwargs['yticks'] = []

    # set figure
    if figure is None:
        figure = plt.figure()
        axes = figure.axes
    else:
        # Figure exists: get the axes
        axes = figure.axes

    # Special case of dim=2
    if dim == 2:
        Nx = subdivisions[0]
        Ny = subdivisions[1]
        axes = [figure.add_subplot(111, **axes_kwargs)]
        if not enableTicks:
            axes[0].axison = False

        x = data.getMarginal(0)
        y = data.getMarginal(1)
        # x axis
        x_min = bounds.getLowerBound()[0]
        x_max = bounds.getUpperBound()[0]
        dx = x_max - x_min
        # y axis
        y_min = bounds.getLowerBound()[1]
        y_max = bounds.getUpperBound()[1]
        dy = y_max - y_min
        # Draw horizontal lines
        dydiv = float(Ny)
        xk = [x_min, x_max]
        for k in range(Ny):
            yk = [y_min + k * dy / dydiv, y_min + k * dy / dydiv]
            axes[0].plot(xk, yk, 'k')
        yk = [y_max, y_max]
        axes[0].plot(xk, yk, 'k')
        # Draw vertical lines
        dxdiv = float(Nx)
        yk = [y_min, y_max]
        for k in range(Nx):
            xk = [x_min + k * dx / dxdiv, x_min + k * dx / dxdiv]
            axes[0].plot(xk, yk, 'k-')
        xk = [x_max, x_max]
        axes[0].plot(xk, yk, 'k-')
        plot_kwargs['linestyle'] = 'None'
        axes[0].plot(x, y, **plot_kwargs)
        axes[0].set_xlabel(labels[0])
        axes[0].set_ylabel(labels[1])
        axes[0].set_xlim(x_min, x_max)
        axes[0].set_ylim(y_min, y_max)
        return figure

    # General case

    # For the diagonal of a multidimensional plot,
    # disable the ticks, always
    diagonal_axes_kwargs = axes_kwargs.copy()  # An independent copy
    diagonal_axes_kwargs['xticks'] = []
    diagonal_axes_kwargs['yticks'] = []

    # Graph of type Pairs + horizontal/vertical lines
    # to illustrate the cells
    index_axis = -1
    for i in range(dim):
        Ny = subdivisions[i]
        # y axis
        y = data.getMarginal(i)
        y_min = bounds.getLowerBound()[i]
        y_max = bounds.getUpperBound()[i]
        dy = y_max - y_min
        for j in range(dim):
            Nx = subdivisions[j]
            index_axis += 1

            if i == j:
                axes.append(
                    figure.add_subplot(dim, dim, index_axis + 1,
                                       **diagonal_axes_kwargs))
                text_kwargs['transform'] = axes[index_axis].transAxes
                axes[index_axis].text(0.5, 0.5, labels[i], **text_kwargs)
            else:
                axes.append(
                    figure.add_subplot(dim, dim, index_axis + 1,
                                       **axes_kwargs))
                # disable axis : grid, ticks, axis?
                if not enableTicks:
                    axes[index_axis].axison = False

                # x axis
                x = data.getMarginal(j)
                x_min = bounds.getLowerBound()[j]
                x_max = bounds.getUpperBound()[j]
                dx = x_max - x_min
                # Draw horizontal lines
                dydiv = float(Ny)
                for k in range(Ny):
                    xk = [x_min, x_max]
                    yk = [y_min + k * dy / dydiv, y_min + k * dy / dydiv]
                    axes[index_axis].plot(xk, yk, 'k-')
                # Draw vertical lines
                dxdiv = float(Nx)
                for k in range(Nx):
                    xk = [x_min + k * dx / dxdiv, x_min + k * dx / dxdiv]
                    yk = [y_min, y_max]
                    axes[index_axis].plot(xk, yk, 'k-')
                plot_kwargs['linestyle'] = 'None'
                axes[index_axis].plot(x, y, **plot_kwargs)
                axes[index_axis].set_xlim(x_min, x_max)
                axes[index_axis].set_ylim(y_min, y_max)

    # Finally get the figure
    return figure
Beispiel #12
0
#! /usr/bin/env python

import openturns as ot
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
from openturns.viewer import View
import time

ot.RandomGenerator.SetSeed(0)
ot.Log.Show(ot.Log.INFO)

# Bounds are [0,1]^dimension
dimension = 2
bounds = ot.Interval(dimension)

# Size of sample
size = 10

# Factory: lhs generates
lhsDesign = ot.LHSExperiment(
    ot.ComposedDistribution([ot.Uniform(0.0, 1.0)] * dimension), size)
lhsDesign.setAlwaysShuffle(True)  # randomized

geomProfile = ot.GeometricProfile(10.0, 0.999, 50000)
c2 = ot.SpaceFillingC2()
sa = ot.SimulatedAnnealingLHS(lhsDesign, geomProfile, c2)
tic = time.time()
result = sa.generate()
toc = time.time()
dt1 = toc - tic
Beispiel #13
0
    def _estimKrigingTheta(self, algoKriging, lowerBound, upperBound, size):
        """
        Estimate the kriging theta values with an initial random search using
        a Sobol sequence of size samples.
        """
        # get input parameters of the kriging algorithm
        X = algoKriging.getInputSample()
        Y = algoKriging.getOutputSample()

        algoKriging.run()
        krigingResult = algoKriging.getResult()
        covarianceModel = krigingResult.getCovarianceModel()
        basis = krigingResult.getBasisCollection()
        if LooseVersion(ot.__version__) == '1.9':
            llf = algoKriging.getReducedLogLikelihoodFunction()
        else:
            llf = algoKriging.getLogLikelihoodFunction()

        # create uniform distribution of the parameters bounds
        dim = len(lowerBound)
        distBoundCol = []
        for i in range(dim):
            distBoundCol += [ot.Uniform(lowerBound[i], upperBound[i])]
        distBound = ot.ComposedDistribution(distBoundCol)

        if size > 0:
            # Generate starting points with a low discrepancy sequence
            thetaStart = ot.LowDiscrepancyExperiment(ot.SobolSequence(),
                                                     distBound,
                                                     size).generate()
            # Get the best theta from the maximum llf value
            llfValue = llf(thetaStart)
            indexMax = int(np.argmax(llfValue))
            bestTheta = thetaStart[indexMax]

            # update theta after random search
            if LooseVersion(ot.__version__) == '1.6':
                covarianceModel.setScale(bestTheta)
            elif LooseVersion(ot.__version__) > '1.6':
                # optimize theta and sigma in ot 1.8
                covarianceModel.setScale(bestTheta[:-1])
                covarianceModel.setAmplitude([bestTheta[-1]])

        # Now the KrigingAlgorithm is used to optimize the likelihood using a
        # good starting point
        if LooseVersion(ot.__version__) == "1.9":
            algoKriging = ot.KrigingAlgorithm(X, Y, covarianceModel, basis)
        else:
            algoKriging = ot.KrigingAlgorithm(X, Y, basis, covarianceModel,
                                              True)

        # set TNC optim
        searchInterval = ot.Interval(lowerBound, upperBound)
        if LooseVersion(ot.__version__) == '1.6':
            optimizer = ot.TNC()
            optimizer.setBoundConstraints(searchInterval)
            algoKriging.setOptimizer(optimizer)
        elif LooseVersion(ot.__version__) in ['1.7', '1.8']:
            optimizer = algoKriging.getOptimizationSolver()
            problem = optimizer.getProblem()
            problem.setBounds(searchInterval)
            optimizer.setProblem(problem)
            algoKriging.setOptimizationSolver(optimizer)
        elif LooseVersion(ot.__version__) == '1.9':
            algoKriging.setOptimizationBounds(searchInterval)

        return algoKriging
Beispiel #14
0
import openturns.testing as ott

# Define the objective function
objectiveFun = ot.SymbolicFunction(
    ["x", "y", "z", "t"], ["-(15*x + 12*y + 4*z + 2*t)"])
constraintFun = ot.SymbolicFunction(
    ["x", "y", "z", "t"], ["-(8*x + 5*y + 3*z + 2*t -10)"])
x = [0, 1, 1, 1]
print("Evaluate f at x=", x)
print("f(x)=", objectiveFun(x))
print("g(x)=", constraintFun(x))

# Define problem
problem = ot.OptimizationProblem(objectiveFun)
problem.setInequalityConstraint(constraintFun)
bounds = ot.Interval([0., 0., 0., 0.], [1., 1., 1., 1.])
problem.setBounds(bounds)
problem.setMinimization(True)
problem.setVariablesType([ot.OptimizationProblemImplementation.BINARY, ot.OptimizationProblemImplementation.BINARY,
                          ot.OptimizationProblemImplementation.BINARY, ot.OptimizationProblemImplementation.BINARY])

# Define OptimizationAlgorithm
x0 = [0., 0., 0., 0.]
algo = ot.Bonmin(problem, "B-BB")
algo.setStartingPoint(x0)
algo.setMaximumEvaluationNumber(10000)
algo.setMaximumIterationNumber(1000)
ot.ResourceMap.AddAsScalar('Bonmin-bonmin.time_limit', 60)
algo.run()

# Retrieve result
# 2. covariance model
cov = ot.MaternModel([1.], [2.5], 1.5)
print(cov)

# 3. kriging algorithm
algokriging = ot.KrigingAlgorithm(x, y, cov, basis)

## error measure
#algokriging.setNoise([5*1e-1]*n_pt)

# 4. Optimization
# algokriging.setOptimizationAlgorithm(ot.NLopt('GN_DIRECT'))
lhsExperiment = ot.LHSExperiment(ot.Uniform(1e-1, 1e2), 50)
algokriging.setOptimizationAlgorithm(
    ot.MultiStart(ot.TNC(), lhsExperiment.generate()))
algokriging.setOptimizationBounds(ot.Interval([0.1], [1e2]))

# if we choose not to optimize parameters
#algokriging.setOptimizeParameters(False)

# 5. run the algorithm
algokriging.run()

# %%
# Results
# -------

# %%
# get some results
krigingResult = algokriging.getResult()
print('residual = ', krigingResult.getResiduals())
        pt1 = self.vertices[i]
        pt2 = self.vertices[j]
        difference = pt1 - pt2
        val = m.exp(-difference.norm() / self.scaling)
        return val


ot.ResourceMap.SetAsBool('HMatrix-ForceSequential', True)
ot.ResourceMap.SetAsUnsignedInteger('HMatrix-MaxLeafSize', 10)

ot.PlatformInfo.SetNumericalPrecision(3)

n = 2
indices = [n, n]
intervalMesher = ot.IntervalMesher(indices)
interval = ot.Interval([0.0] * 2, [1.0] * 2)
mesh2D = intervalMesher.build(interval)
vertices = mesh2D.getVertices()

factory = ot.HMatrixFactory()
parameters = ot.HMatrixParameters()
parameters.setAssemblyEpsilon(1.e-6)
parameters.setRecompressionEpsilon(1.e-6)
# HMatrix must be symmetric in order to perform Cholesky decomposition
hmat = factory.build(vertices, 1, True, parameters)
simpleAssembly = TestHMatrixRealAssemblyFunction(vertices, 0.1)

hmat.assembleReal(simpleAssembly, 'L')

hmatRef = ot.HMatrix(hmat)
Beispiel #17
0
ot.ResourceMap.SetAsScalar(
    'SimulationAlgorithm-DefaultMaximumCoefficientOfVariation', 0.0)
ot.ResourceMap.SetAsScalar(
    'SimulationAlgorithm-DefaultMaximumStandardDeviation', 0.0)
ot.ResourceMap.SetAsScalar('RootStrategy-DefaultStepSize', 0.1)

algorithms = ['MonteCarlo', 'LHS', 'QuasiMonteCarlo', 'DirectionalSampling']

inDim = 4
X = ot.RandomVector(ot.Normal(inDim))
inVars = ot.Description.BuildDefault(inDim, 'x')

low = 1.0
up = 2.0
intervals = [
    ot.Interval([low], [up], [True], [False]),
    ot.Interval([low], [up], [False], [True]),
    ot.Interval([low], [up], [True], [True]),
    ot.Interval([low], [up], [False], [False]),
    ot.Interval([low] * 2, [up] * 2, [True, True], [True, True]),
    ot.Interval([low] * 2, [up] * 2, [True, True], [True, False]),
    ot.Interval([low] * 2, [up] * 2, [True, True], [False, True]),
    ot.Interval([low] * 2, [up] * 2, [True, True], [False, False]),
    ot.Interval([low] * 2, [up] * 2, [True, False], [True, True]),
    ot.Interval([low] * 2, [up] * 2, [True, False], [True, False]),
    ot.Interval([low] * 2, [up] * 2, [True, False], [False, True]),
    ot.Interval([low] * 2, [up] * 2, [True, False], [False, False]),
    ot.Interval([low] * 2, [up] * 2, [False, True], [True, True]),
    ot.Interval([low] * 2, [up] * 2, [False, True], [True, False]),
    ot.Interval([low] * 2, [up] * 2, [False, True], [False, True]),
    ot.Interval([low] * 2, [up] * 2, [False, True], [False, False]),
Beispiel #18
0
#    *InverseBoxCoxTransform* that can be evaluated on a field.
#    The new field based shares the same mesh than the initial field.
#

# %%
from __future__ import print_function
import openturns as ot
import openturns.viewer as viewer
from matplotlib import pylab as plt
ot.Log.Show(ot.Log.NONE)

# %%
# Define a process
myIndices = ot.Indices([10, 5])
myMesher = ot.IntervalMesher(myIndices)
myInterval = ot.Interval([0.0, 0.0], [2.0, 1.0])
myMesh = myMesher.build(myInterval)
amplitude = [1.0]
scale = [0.2, 0.2]
myCovModel = ot.ExponentialModel(scale, amplitude)
myXproc = ot.GaussianProcess(myCovModel, myMesh)
g = ot.SymbolicFunction(['x1'], ['exp(x1)'])
myDynTransform = ot.ValueFunction(g, myMesh)
myXtProcess = ot.CompositeProcess(myDynTransform, myXproc)

# %%
# Draw a field
field = myXtProcess.getRealization()
graph = field.drawMarginal(0)
view = viewer.View(graph)
timeStep = 0.1
n = 100
tgrid = ot.RegularGrid(tMin, timeStep, n)

# %%
# Create a normal process
amplitude = [5.0]
scale = [3.0]
model = ot.ExponentialModel(scale, amplitude)
process = ot.GaussianProcess(model, tgrid)

# %%
# Create the 1-d domain A: [2.,5.]
lowerBound = [2.0]
upperBound = [5.0]
domain = ot.Interval(lowerBound, upperBound)

# %%
# Create an event from a Process and a Domain
event = ot.ProcessEvent(process, domain)

# %%
# Create the Monte-Carlo algorithm
montecarlo = ot.ProbabilitySimulationAlgorithm(event)

# Define the maximum number of simulations
montecarlo.setMaximumOuterSampling(1000)

# Define the block size
montecarlo.setBlockSize(100)
# branin

dim = 2

# model
branin = ot.SymbolicFunction(['x1', 'x2'], [
    '((x2-(5.1/(4*_pi^2))*x1^2+5*x1/_pi-6)^2+10*(1-1/8*_pi)*cos(x1)+10-54.8104)/51.9496',
    '0.96'
])
transfo = ot.SymbolicFunction(['u1', 'u2'], ['15*u1-5', '15*u2'])
model = ot.ComposedFunction(branin, transfo)

# problem
problem = ot.OptimizationProblem()
problem.setObjective(model)
bounds = ot.Interval([0.0] * dim, [1.0] * dim)
problem.setBounds(bounds)

# design
experiment = ot.Box([1, 1])
inputSample = experiment.generate()
modelEval = model(inputSample)
outputSample = modelEval.getMarginal(0)

# first kriging model
covarianceModel = ot.SquaredExponential([0.3007, 0.2483], [0.981959])
basis = ot.ConstantBasisFactory(dim).build()
kriging = ot.KrigingAlgorithm(inputSample, outputSample, covarianceModel,
                              basis)
noise = list(map(lambda x: x[1], modelEval))
kriging.setNoise(noise)
Beispiel #21
0
covarianceModel = ot.SquaredExponential(dimension)

# %%
# Typically, the optimization algorithm is quite good at setting sensible optimization bounds.
# In this case, however, the range of the input domain is extreme.

# %%
print("Lower and upper bounds of X_train:")
print(X_train.getMin(), X_train.getMax())

# %%
# We need to manually define sensible optimization bounds.
# Note that since the amplitude parameter is computed analytically (this is possible when the output dimension is 1), we only need to set bounds on the scale parameter.

# %%
scaleOptimizationBounds = ot.Interval(
    [1.0, 1.0, 1.0, 1.0e-10], [1.0e11, 1.0e3, 1.0e1, 1.0e-5])

# %%
# Finally, we use the `KrigingAlgorithm` class to create the Kriging metamodel.
# It requires a training sample, a covariance kernel and a trend basis as input arguments.
# We need to set the initial scale parameter for the optimization. The upper bound of the input domain is a sensible choice here.
# We must not forget to actually set the optimization bounds defined above.

# %%
covarianceModel.setScale(X_train.getMax())
algo = ot.KrigingAlgorithm(X_train, Y_train, covarianceModel, basis)
algo.setOptimizationBounds(scaleOptimizationBounds)

# %%
# Run the algorithm and get the result.
Beispiel #22
0
# %%
#
# In this example we are going to assess a Karhunen-Loeve decomposition
#

# %%
from __future__ import print_function
import openturns as ot
import openturns.viewer as viewer
from matplotlib import pylab as plt
ot.Log.Show(ot.Log.NONE)

# %%
# Create a Gaussian process
numberOfVertices = 20
interval = ot.Interval(-1.0, 1.0)
mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval)
covariance = ot.SquaredExponential()
process = ot.GaussianProcess(covariance, mesh)

# %%
# decompose it using KL-SVD
sampleSize = 100
processSample = process.getSample(sampleSize)
threshold = 1.0e-7
algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold)
algo.run()
klresult = algo.getResult()

# %%
# Instanciate the validation service
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)

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

# %%
graph = rastrigin.draw(lowerbound, upperbound, [100]*dim)
graph.setTitle("Rastrigin function")
view = viewer.View(graph, legend_kw={
                   'bbox_to_anchor': (1, 1), 'loc': "upper left"})
view.getFigure().tight_layout()

# %%
# We see that the Rastrigin function has several local minima. However, there is only one single global minimum at :math:`\vect{x}^\star=(0, 0)`.

f = ot.PythonFunction(3, 2, flow)
phi = ot.ParametricFunction(f, [2], [0.0])
solver = ot.RungeKutta(phi)

initialState = [2.0, 2.0]
nt = 47
dt = 0.1
timeGrid = ot.RegularGrid(0.0, dt, nt)
result = solver.solve(initialState, timeGrid)
xMin = result.getMin()
xMax = result.getMax()
delta = 0.2 * (xMax - xMin)
mesh = ot.IntervalMesher([12] * 2).build(
    ot.Interval(xMin - delta, xMax + delta))
field = ot.Field(mesh, phi(mesh.getVertices()))
ot.ResourceMap.SetAsScalar("Field-ArrowScaling", 0.1)
graph = field.draw()
cloud = ot.Cloud(mesh.getVertices())
cloud.setColor("black")
graph.add(cloud)
curve = ot.Curve(result)
curve.setColor("red")
curve.setLineWidth(2)
graph.add(curve)

fig = plt.figure()
ax = fig.add_subplot(111)
View(graph, figure=fig)
plt.suptitle("Lotka-Volterra ODE system")
Beispiel #25
0
# It can be built from a mesh and values or as a realization of a stochastic process.

# %%
import openturns as ot
import openturns.viewer as viewer
from matplotlib import pylab as plt
import math as m
ot.Log.Show(ot.Log.NONE)

# %%
# First, we define a regular 2-d mesh
discretization = [10, 5]
mesher = ot.IntervalMesher(discretization)
lowerBound = [0.0, 0.0]
upperBound = [2.0, 1.0]
interval = ot.Interval(lowerBound, upperBound)
mesh = mesher.build(interval)
graph = mesh.draw()
graph.setTitle('Regular 2-d mesh')
view = viewer.View(graph)

# %%
# We now create a field from a mesh and some values
values = ot.Normal([0.0] * 2, [1.0] * 2,
                   ot.CorrelationMatrix(2)).getSample(len(mesh.getVertices()))
for i in range(len(values)):
    x = values[i]
    values[i] = 0.05 * x / x.norm()
field = ot.Field(mesh, values)

# %%
Beispiel #26
0
# -------------------------
#
# We now perform the target analysis which consists in using a filter function over the
# output.

# %%
# Defining a filter function
# ^^^^^^^^^^^^^^^^^^^^^^^^^^
#
# We define a filter function on the output variable for the target
# analysis. In this example we use the function :math:`\exp{(-d/s)}` where :math:`d` is the distance
# to a well-chosen interval.

# %%
# We first define a critical domain: in our case that is the :math:`[5,+\infty[` interval.
criticalDomain = ot.Interval(5, float('inf'))

# %%
# We have access to the distance to this  domain thanks to the
# :class:`~openturns.DistanceToDomainFunction` class.
dist2criticalDomain = ot.DistanceToDomainFunction(criticalDomain)

# %%
# We define the parameters in our function from the output sample
s = 0.1 * Y.computeStandardDeviation()[0]

# %%
# We now define our filter function by composition of the parametrized function and
# the distance function.
f = ot.SymbolicFunction(["x", "s"], ["exp(-x/s)"])
phi = ot.ParametricFunction(f, [1], [s])
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

try:
    ot.ResourceMap.SetAsScalar(
        "LinearCombinationEvaluation-SmallCoefficient", 1.0e-10)
    domain = ot.Interval(-1.0, 1.0)
    basis = ot.OrthogonalProductPolynomialFactory([ot.LegendreFactory()])
    basisSize = 5
    experiment = ot.LHSExperiment(basis.getMeasure(), 100)
    mustScale = False
    threshold = 0.0001
    model = ot.AbsoluteExponential([1.0])
    algo = ot.KarhunenLoeveQuadratureAlgorithm(
        domain, model, experiment, basis, basisSize, mustScale, threshold)
    algo.run()
    result = algo.getResult()
    lambd = result.getEigenValues()
    KLModes = result.getModesAsProcessSample()
    print("KL modes=", KLModes)
    print("KL eigenvalues=", lambd)
    process = ot.GaussianProcess(model, KLModes.getMesh())
    sample = process.getSample(10)
    coefficients = result.project(sample)
    print("KL coefficients=", coefficients)
    KLFunctions = result.getModes()
    print("KL functions=", KLFunctions)
    print("KL lift=", result.lift(coefficients[0]))
    print("KL lift as field=", result.liftAsField(coefficients[0]))
Beispiel #28
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

f = ot.SymbolicFunction(['x'], ['sin(x)'])
a = -2.5
b = 4.5
algo = ot.Fejer1([20])
value, nodes = algo.integrateWithNodes(f, ot.Interval(a, b))

g = f.draw(a, b, 512)
lower = ot.Cloud(nodes, ot.Sample(nodes.getSize(), 1))
lower.setColor("magenta")
lower.setPointStyle('circle')
g.add(lower)
g.setTitle(r"GaussLegendre example: $\int_{-5/2}^{9/2}\sin(t)\,dt=$" +
           str(value[0]))

fig = plt.figure(figsize=(8, 4))
axis = fig.add_subplot(111)
axis.set_xlim(auto=True)
View(g, figure=fig, axes=[axis], add_legend=False)
graph2 = mesh2D.draw()
graph2.setTitle('Bidimensional mesh')
graph2.setLegendPosition('bottomright')
view = viewer.View(graph2)

# %%
# We can also define a mesh which is a regularly meshed box in dimension 1 or 2.
# We define the number of intervals in each direction of the box :
myIndices = [5, 10]
myMesher = ot.IntervalMesher(myIndices)

# %%
# We then create the mesh of the box :math:`[0, 2] \times [0, 4]` :
lowerBound = [0., 0.]
upperBound = [2., 4.]
myInterval = ot.Interval(lowerBound, upperBound)
myMeshBox = myMesher.build(myInterval)
mygraph3 = myMeshBox.draw()
mygraph3.setTitle('Bidimensional mesh on a box')
view = viewer.View(mygraph3)

# %%
# It is possible to perform a transformation on a regularly meshed box.
myIndices = [20, 20]
mesher = ot.IntervalMesher(myIndices)
# r in [1., 2.] and theta in (0., pi]
lowerBound2 = [1.0, 0.0]
upperBound2 = [2.0, m.pi]
myInterval = ot.Interval(lowerBound2, upperBound2)
meshBox2 = mesher.build(myInterval)
import openturns.testing as ott

ot.TESTPREAMBLE()

f = ot.SymbolicFunction(["x"], ["sin(x)"])
a = -2.5
b = 4.5
# Integrate sin(t) between a & b --> cos(b) - sin(b)
ref = math.cos(a) - math.cos(b)

all_methods = [ot.FejerAlgorithm.FEJERTYPE1,
               ot.FejerAlgorithm.FEJERTYPE2, ot.FejerAlgorithm.CLENSHAWCURTIS]
# 1D checking
for method in all_methods:
    algo = ot.FejerAlgorithm([100],  method)
    value, adaptedNodes = algo.integrateWithNodes(f, ot.Interval(a, b))
    ott.assert_almost_equal(value[0], ref, 1e-10, 1e-10)

g = ot.SymbolicFunction(["x", "y"], ["cos(pi_ * x / 2) * sin(pi_ * y)"])
ref = 8 / (math.pi * math.pi)
interval = ot.Interval([-1, 0], [1, 1])
for method in all_methods:
    algo = ot.FejerAlgorithm([64, 64], method)
    value, adaptedNodes = algo.integrateWithNodes(g, interval)
    ott.assert_almost_equal(value[0], ref, 1e-10, 1e-10)

# Now we use the same calculus using variables changes
h = ot.SymbolicFunction(
    ["x", "y"], ["cos(pi_ * x / 2) * sin(pi_ * y / 2 + pi_/2 ) / 2"])
interval = ot.Interval([-1, -1], [1, 1])
for method in all_methods: