def drawLevelSetContour2D(distribution, numberOfPointsInXAxis, alpha, threshold, sampleSize=500): ''' Compute the minimum volume LevelSet of measure equal to alpha and get the corresponding density value (named threshold). Generate a sample of the distribution and draw it. Draw a contour plot for the distribution, where the PDF is equal to threshold. ''' sample = distribution.getSample(sampleSize) X1min = sample[:, 0].getMin()[0] X1max = sample[:, 0].getMax()[0] X2min = sample[:, 1].getMin()[0] X2max = sample[:, 1].getMax()[0] xx = ot.Box([numberOfPointsInXAxis], ot.Interval([X1min], [X1max])).generate() yy = ot.Box([numberOfPointsInXAxis], ot.Interval([X2min], [X2max])).generate() xy = ot.Box([numberOfPointsInXAxis, numberOfPointsInXAxis], ot.Interval([X1min, X2min], [X1max, X2max])).generate() data = distribution.computePDF(xy) graph = ot.Graph('', 'X1', 'X2', True, 'topright') labels = ["%.2f%%" % (100 * alpha)] contour = ot.Contour(xx, yy, data, [threshold], labels) contour.setColor('black') graph.setTitle("%.2f%% of the distribution, sample size = %d" % (100 * alpha, sampleSize)) graph.add(contour) cloud = ot.Cloud(sample) graph.add(cloud) return graph
def test_two_inputs_one_output(): # Kriging use case inputDimension = 2 # Learning data levels = [8, 5] box = ot.Box(levels) inputSample = box.generate() # Scale each direction inputSample *= 10.0 model = ot.SymbolicFunction(['x', 'y'], ['cos(0.5*x) + sin(y)']) outputSample = model(inputSample) # Validation sampleSize = 10 inputValidSample = ot.ComposedDistribution( 2 * [ot.Uniform(0, 10.0)]).getSample(sampleSize) outputValidSample = model(inputValidSample) # 2) Definition of exponential model # The parameters have been calibrated using TNC optimization # and AbsoluteExponential models scales = [5.33532, 2.61534] amplitude = [1.61536] covarianceModel = ot.SquaredExponential(scales, amplitude) # 3) Basis definition basis = ot.ConstantBasisFactory(inputDimension).build() # 4) Kriging algorithm algo = ot.KrigingAlgorithm(inputSample, outputSample, covarianceModel, basis) algo.run() result = algo.getResult() # Get meta model metaModel = result.getMetaModel() outData = metaModel(inputValidSample) # 5) Errors # Interpolation ott.assert_almost_equal(outputSample, metaModel(inputSample), 3.0e-5, 3.0e-5) # 6) Kriging variance is 0 on learning points covariance = result.getConditionalCovariance(inputSample) ott.assert_almost_equal(covariance, ot.SquareMatrix(len(inputSample)), 7e-7, 7e-7) # Covariance per marginal & extract variance component coll = result.getConditionalMarginalCovariance(inputSample) var = [mat[0, 0] for mat in coll] ott.assert_almost_equal(var, [0] * len(var), 0.0, 1e-13) # Variance per marginal var = result.getConditionalMarginalVariance(inputSample) ott.assert_almost_equal(var, ot.Point(len(inputSample)), 0.0, 1e-13) # Estimation ott.assert_almost_equal(outputValidSample, outData, 1.e-1, 1e-1)
def drawLimitState(self, bounds, nX=50, nY=50): """ Draw the limit state of an event. Parameters ---------- event : an ot.Event The event we want to draw. bounds: an ot.Interval The lower and upper bounds of the interval. nX : an int The number of points in the X axis. nY : an int The number of points in the Y axis. Returns ------- None. """ if bounds.getDimension() != 2: raise ValueError("The input dimension of the bounds " "is equal to %d but should be 2." % (bounds.getDimension())) # threshold = self.event.getThreshold() g = self.event.getFunction() # boxExperiment = ot.Box([nX, nY], bounds) inputSample = boxExperiment.generate() outputSample = g(inputSample) # description = g.getInputDescription() graph = ot.Graph("Limit state surface", description[0], description[1], True, "") # Create the contour levels = ot.Point([threshold]) labels = [str(threshold)] drawLabels = True lowerBound = bounds.getLowerBound() upperBound = bounds.getUpperBound() x = LinearSample(lowerBound[0], upperBound[0], nX + 2) y = LinearSample(lowerBound[1], upperBound[1], nY + 2) contour = ot.Contour(x, y, outputSample, levels, labels, drawLabels) graph.add(contour) return graph
def drawLimitStateCrossCut(self, bounds, i=0, j=1, nX=50, nY=50): """ Draw the cross-cut of the limit state of an event on a cross-cut. Parameters ---------- bounds: an ot.Interval The lower and upper bounds of the cross-cut interval. i : int The index of the first marginal of the cross-cut. j : int The index of the second marginal of the cross-cut. nX : an int The number of points in the X axis. nY : an int The number of points in the Y axis. Returns ------- graph : ot.Graph The plot of the (i, j) cross cut. """ if bounds.getDimension() != 2: raise ValueError("The input dimension of the bounds " "is equal to %d but should be 2." % (bounds.getDimension())) # threshold = self.event.getThreshold() description = self.g.getInputDescription() boxExperiment = ot.Box([nX, nY], bounds) reducedInputSample = boxExperiment.generate() crosscutFunction = self.buildCrossCutFunction(i, j) outputSample = crosscutFunction(reducedInputSample) # graph = ot.Graph("Limit state surface", description[i], description[j], True, "") # Create the contour levels = ot.Point([threshold]) labels = [str(threshold)] drawLabels = True lowerBound = bounds.getLowerBound() upperBound = bounds.getUpperBound() x = LinearSample(lowerBound[0], upperBound[0], nX + 2) y = LinearSample(lowerBound[1], upperBound[1], nY + 2) contour = ot.Contour(x, y, outputSample, levels, labels, drawLabels) graph.add(contour) return graph
import openturns as ot from openturns.viewer import View # Box d = ot.Box([3, 4, 5]) s = d.generate() s.setDescription(["X1", "X2", "X3"]) g = ot.Graph() g.setTitle("Box experiment") g.setGridColor("black") p = ot.Pairs(s) g.add(p) View(g)
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View # Generate sample with the given plane levels = [4, 4] myPlane = ot.Box(levels) sample = myPlane.generate() # Create an empty graph graph = ot.Graph("Box plane", "x1", "x2", True, "") # Create the cloud cloud = ot.Cloud(sample, "blue", "fsquare", "") # Then, draw it graph.add(cloud) fig = plt.figure(figsize=(4, 4)) axis = fig.add_subplot(111) axis.set_xlim(auto=True) View(graph, figure=fig, axes=[axis], add_legend=False)
#! /usr/bin/env python import openturns as ot levels = [4] * 2 experiment = ot.Box(levels) print('experiment = ', experiment) sample = experiment.generate() print('sample = ', repr(sample)) experiment = ot.Box(levels, ot.Interval([7.0, 8.0], [9.0, 16.0])) print('experiment = ', experiment) sample = experiment.generate() print('sample = ', repr(sample))
s = 10.0 event = ot.ThresholdEvent(vectorY, ot.Greater(), s) # %% # This event can easily be represented with a 1D curve as it is a branch of an hyperbole. # If :math:`y = x_1 x_2 = 10.0`, then the boundary of the domain of failure is the curve : # # .. math:: # # h : x_1 \mapsto \frac{10.0}{x_1} # # %% # We shall represent this curve using a :class:`~openturns.Contour` object. nx, ny = 15, 15 xx = ot.Box([nx], ot.Interval([0.0], [10.0])).generate() yy = ot.Box([ny], ot.Interval([-10.0], [10.0])).generate() inputData = ot.Box([nx, ny], ot.Interval([0.0, -10.0], [10.0, 10.0])).generate() outputData = f(inputData) mycontour = ot.Contour(xx, yy, outputData, [10.0], ["10.0"]) myGraph = ot.Graph("Representation of the failure domain", r"$X_1$", r"$X_2$", True, "") myGraph.add(mycontour) # %% texts = [r" Event : $\mathcal{D} = \{Y \geq 10.0\}$"] myText = ot.Text([[4.0, 4.0]], texts) myText.setTextSize(1) myGraph.add(myText) view = otv.View(myGraph)
def draw(self, drawInliers=False, drawOutliers=True): """ Draw the high density regions. Parameters ---------- drawInliers : bool If True, draw inliers points. drawOutliers : bool If True, draw outliers points. """ plabels = self.sample.getDescription() # Bivariate space grid = ot.GridLayout(self.dim, self.dim) # Axis are created and stored top to bottom, left to right for i in range(self.dim): for j in range(self.dim): if i >= j: # lower triangle graph = ot.Graph("", "", "", True, "topright") if i == j: # diag marginal_distribution = self.distribution.getMarginal(i) curve = marginal_distribution.drawPDF() graph.add(curve) if drawInliers: marginal_sample = self.sample[self.inlier_indices, i] data = ot.Sample(marginal_sample.getSize(), 2) data[:, 0] = marginal_sample cloud = ot.Cloud(data) cloud.setColor(self.inlier_color) graph.add(cloud) if drawOutliers: marginal_sample = self.sample[self.outlier_indices, i] data = ot.Sample(marginal_sample.getSize(), 2) data[:, 0] = marginal_sample cloud = ot.Cloud(data) cloud.setColor(self.outlier_color) graph.add(cloud) elif i > j: # lower corners # Use a regular grid to compute probability response surface X1min = self.sample[:, j].getMin()[0] X1max = self.sample[:, j].getMax()[0] X2min = self.sample[:, i].getMin()[0] X2max = self.sample[:, i].getMax()[0] xx = ot.Box([self.numberOfPointsInXAxis], ot.Interval([X1min], [X1max])).generate() yy = ot.Box([self.numberOfPointsInXAxis], ot.Interval([X2min], [X2max])).generate() xy = ot.Box( [ self.numberOfPointsInXAxis, self.numberOfPointsInXAxis ], ot.Interval([X1min, X2min], [X1max, X2max]), ).generate() data = self.distribution.getMarginal([j, i]).computePDF(xy) # Label using percentage instead of probability n_contours = len(self.alphaLevels) labels = [ "%.0f %%" % (self.alphaLevels[i] * 100) for i in range(n_contours) ] contour = ot.Contour(xx, yy, data, self.pvalues, ot.Description(labels)) contour.setColor(self.contour_color) graph.add(contour) sample_ij = self.sample[:, [j, i]] if drawInliers: cloud = self._drawInliers(sample_ij) if cloud is not None: graph.add(cloud) if drawOutliers: cloud = self._drawOutliers(sample_ij) if cloud is not None: graph.add(cloud) if j == 0 and i > 0: graph.setYTitle(plabels[i]) if i == self.dim - 1: graph.setXTitle(plabels[j]) if i >= j: # lower triangle graph.setLegends([""]) grid.setGraph(i, j, graph) return grid
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)
twoSample = ot.Sample(size, 1) for i in range(size): oneSample[i, 0] = 7.0 * sin(-3.5 + (6.5 * i) / (size - 1.0)) + 2.0 twoSample[i, 0] = -2.0 * oneSample[i, 0] + 3.0 + 0.05 * sin(oneSample[i, 0]) test = ot.LinearModelAlgorithm(oneSample, twoSample) result = ot.LinearModelResult(test.getResult()) print("trend coefficients = ", result.getCoefficients()) print("Fit y ~ 1 + 0.1 x + 10 x^2 model using 100 points") ot.RandomGenerator.SetSeed(0) size = 100 # Define a linespace from 0 to 10 with size points # We use a Box expermient ==> remove 0 & 1 points experiment = ot.Box([size - 2]) X = experiment.generate() # X is defined in [0,1] X *= [10] # Stack X2 X2 = ot.Sample(X) for i in range(size): X2[i, 0] = X[i, 0] * X2[i, 0] X.stack(X2) # Define y Y = ot.Sample(size, 1) for i in range(size): Y[i, 0] = 1.0 + 0.1 * X[i, 0] + 10.0 * \ X[i, 0] * X[i, 0] + 0.1 * ot.DistFunc.rNormal() test = ot.LinearModelAlgorithm(X, Y) result = test.getResult()
# 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) kriging.run() # algo algo = ot.EfficientGlobalOptimization(problem, kriging.getResult())
def drawContour(self, drawData=False, drawOutliers=True): """Draw contour. If :attr:`drawData`, the whole sample is drawn. Otherwise, depending on :attr:`drawOutliers` it will either show the outliers or the inliers only. :param bool drawData: Plot inliers and outliers. :param bool drawOutliers: Whether to draw inliers or outliers. :returns: figure, axes and OpenTURNS Graph object. :rtypes: Matplotlib figure instances, Matplotlib AxesSubplot instances, :class:`openturns.Graph` """ plabels = self.sample.getDescription() # Bivariate space fig = plt.figure(figsize=(10, 10)) sub_ax = [] # Axis stored as a list sub_graph = [] # Axis are created and stored top to bottom, left to right for i in range(self.dim): for j in range(self.dim): k = i + j * self.dim + 1 if i <= j: # lower triangle ax = fig.add_subplot(self.dim, self.dim, k) graph = ot.Graph('', '', '', True, 'topright') if i == j: # diag pdf_graph = self.distribution.getMarginal(i).drawPDF() graph.add(pdf_graph) elif i < j: # lower corners # Use a regular grid to compute probability response surface X1min = self.sample[:, i].getMin()[0] X1max = self.sample[:, i].getMax()[0] X2min = self.sample[:, j].getMin()[0] X2max = self.sample[:, j].getMax()[0] xx = ot.Box([self.numberOfPointsInXAxis], ot.Interval([X1min], [X1max])).generate() yy = ot.Box([self.numberOfPointsInXAxis], ot.Interval([X2min], [X2max])).generate() xy = ot.Box([self.numberOfPointsInXAxis, self.numberOfPointsInXAxis], ot.Interval([X1min, X2min], [X1max, X2max])).generate() data = self.distribution.getMarginal([i, j]).computePDF(xy) # Label using percentage instead of probability n_contours = len(self.contoursAlpha) labels = ["%.0f %%" % (self.contoursAlpha[i] * 100) for i in range(n_contours)] contour = ot.Contour(xx, yy, data, self.pvalues, ot.Description(labels)) contour.setColor('black') graph.add(contour) sample_ = np.array(self.sample)[:, [i, j]] if drawData: inliers_ = self.drawInliers(sample=sample_) outliers_ = self.drawOutliers(sample=sample_) if inliers_ is not None: graph.add(inliers_) if outliers_ is not None: graph.add(outliers_) elif drawOutliers: outliers_ = self.drawOutliers(sample=sample_) if outliers_ is not None: graph.add(outliers_) else: inliers_ = self.drawInliers(sample=sample_) if inliers_ is not None: graph.add(inliers_) if i == 0: graph.setYTitle(plabels[j]) if j == (self.dim - 1): graph.setXTitle(plabels[i]) graph.setLegends(['']) sub_graph.append(ot.viewer.View(graph, figure=fig, axes=[ax])) sub_ax.append(ax) return fig, sub_ax, sub_graph
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View nrows = 3 ncols = 4 # coordinates of grid grid = ot.Box([5, 5], ot.Interval([0.0] * 2, [6.0] * 2)) sample = grid.generate() grid_x = sample.getMarginal(0) grid_y = sample.getMarginal(1) #plt.rc('text', usetex=True) q_values = [1.0, 0.75, 0.5] fig = plt.figure() index = 1 for i in range(nrows): q = q_values[i] enumerate = ot.HyperbolicAnisotropicEnumerateFunction(2, q) for j in range(ncols): ax = fig.add_subplot(nrows, ncols, index, aspect=1.0) ax.plot(grid_x, grid_y, 'xr') strataIndex = j + 3 strata_x, strata_y = [], [] strataCardinal = enumerate.getStrataCumulatedCardinal(strataIndex) for ii in range(strataCardinal): x = enumerate(ii) strata_x.append(x[0]) strata_y.append(x[1])
print("mean = ", distribution2D.getMean()) print("cov = ", distribution2D.getCovariance()) print("sigma = ", distribution2D.getStandardDeviation()) distribution2D.setBlockMin(3) distribution2D.setBlockMax(10) # Build a grid for validation xMin = distribution2D.getRange().getLowerBound()[0] xMax = distribution2D.getRange().getUpperBound()[0] yMin = distribution2D.getRange().getLowerBound()[1] yMax = distribution2D.getRange().getUpperBound()[1] # Number of points of discretization nx = 4 ny = 4 boxParameters = [nx, ny] boxGrid = ot.Box(boxParameters) grid = boxGrid.generate() # scaling box grid scaleFactor = [0.25 * (xMax - xMin), 0.25 * (yMax - yMin)] grid *= scaleFactor # translating translateFactor = distribution2D.getMean()[0:2] grid += translateFactor # Compute PDF # parameters for theoritical PDF, obtained thanks to Maple factor = sqrt(2) / (20 * pi) for index in range(grid.getSize()): point = grid[index] PDF = distribution2D.computePDF(point) # Very small values are not very accurate on x86, skip them if (PDF < 1.e-12):
sample += [5.0, 8.0] graph = drawBidimensionalSample(sample, "Factorial") view = viewer.View(graph) # %% # Composite design # ---------------- # %% experiment = ot.Composite(2, levels) sample = experiment.generate() sample *= 2.0 sample += [5.0, 8.0] graph = drawBidimensionalSample(sample, "Composite") view = viewer.View(graph) # %% # Grid design # ----------- # # %% levels = [3, 4] experiment = ot.Box(levels) sample = experiment.generate() sample *= 2.0 sample += [5.0, 8.0] graph = drawBidimensionalSample(sample, "Box") view = viewer.View(graph) plt.show()
graphModel0.setXTitle(r'$x_1$') graphModel0.setYTitle(r'$x_2$') graphModel0.setTitle(r'Isolines of the model : $Y = f(X)$, first marginal') # %% # We represent the second marginal of `vecY`. graphModel1 = f.draw(0, 1, 1, [0.0, 0.0], [-5.0, -5.0], [5.0, 5.0]) graphModel1.setXTitle(r'$x_1$') graphModel1.setYTitle(r'$x_2$') graphModel1.setTitle(r'Isolines of the model : $Y = f(X)$, second marginal') # %% # We shall now represent the curves delimiting the domain of interest : # nx, ny = 15, 15 xx = ot.Box([nx], ot.Interval([-5.0], [5.0])).generate() yy = ot.Box([ny], ot.Interval([-5.0], [5.0])).generate() inputData = ot.Box([nx, ny], ot.Interval([-5.0, -5.0], [5.0, 5.0])).generate() outputData = f(inputData) # %% # The contour line associated with the 0.0 value for the first marginal. mycontour0 = ot.Contour(xx, yy, outputData.getMarginal(0), [0.0], ["0.0"]) mycontour0.setColor("black") mycontour0.setLineStyle("dashed") graphModel0.add(mycontour0) # %% # The contour line associated with the 1.0 value for the first marginal. mycontour1 = ot.Contour(xx, yy, outputData.getMarginal(0), [1.0], ["1.0"]) mycontour1.setColor("black")
# %% # Graphically, both the metamodel and the exact function look the same. The metamodel also has three # basins around the minima and the value of the metamodel at each minimum location is comparable to # the exact value of -0.979476. We have roughly two correct digits for each isoline. # %% # Standard deviation # ------------------ # # We finally take a look at the standard deviation in the :math:`[0,1] \times [0,1]` domain. It may be # seen as a measure of the error of the metamodel. # %% # We discretize the domain with 22 points (N inside points and 2 endpoints) : N = 20 inputData = ot.Box([N, N]).generate() # %% # We compute the conditional variance of the model and take the square root to get the deviation : condCov = result.getConditionalMarginalVariance(inputData, 0) condCovSd = sqrt(condCov) # %% # As we have previously done we build contours with the following levels ans labels : levels = [0.01, 0.025, 0.050, 0.075, 0.1, 0.125, 0.150, 0.175] labels = ['0.01', '0.025', '0.050', '0.075', '0.1', '0.125', '0.150', '0.175'] contour = ot.Contour(N + 2, N + 2, condCovSd) graph = ot.Graph('', 'x', 'y', True, '') graph.add(contour) # %%
import openturns as ot from math import cos, sin ot.TESTPREAMBLE() try: # 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())
#! /usr/bin/env python from __future__ import print_function import openturns as ot levels = [4] * 2 myPlane = ot.Box(levels) print('myPlane = ', myPlane) sample = myPlane.generate() print('sample = ', repr(sample)) myPlane = ot.Box(levels, ot.Interval([7.0, 8.0], [9.0, 16.0])) print('myPlane = ', myPlane) sample = myPlane.generate() print('sample = ', repr(sample))