def __setDefaultState__(self): """Gets the data from the inputs and intializes the attributes of the object, either with data passed in __init__, or with an empty default state. """ if (self.func is not None or self.func_sample is not None) and self.__AKLR__ is not None: try: self.__inputDim__ = self.__AKLR__.getSizeModes() self.setInputDescription( ot.Description(self.__AKLR__.__mode_description__)) self.setOutputDescription( ot.Description.BuildDefault(self.__nOutputs__, 'Y_')) except Exception as e: print( 'Check if your aggregated karhunen loeve result object is correct' ) raise e else: self.func = None self.func_sample = None self.__AKLR__ = None self.__nOutputs__ = 0 self.__inputDim__ = 0 self._inputDescription = ot.Description() self._outputDescription = ot.Description()
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, ot.Point([threshold]), ot.Description(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 setInputDescription(self, description): """Sets the input description Arguments --------- description : list of str """ self._inputDescription.clear() self._inputDescription = ot.Description(list(description))
def setOutputDescription(self, description): """Sets the description of each separate outputs Arguments --------- description : list of str """ assert len(description) == self.__nOutputs__ "You must specify the name for each separate output, not for each element of each output" self._outputDescription.clear() self._outputDescription = ot.Description(description)
from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() dim = 2 distribution = ot.Normal(dim) # # Case 1: composite random vector based event # # The input vector X = ot.RandomVector(distribution) # The model: the identity function inVars = ot.Description(dim) for i in range(dim): inVars[i] = "x" + str(i) model = ot.SymbolicFunction(inVars, inVars) # The output vector Y = ot.CompositeRandomVector(model, X) # The domain: [0, 1]^dim domain = ot.Interval(dim) # The event event = ot.DomainEvent(Y, domain) print("sample=", event.getSample(10)) # # Case 2: process based event #
import openturns as ot from openturns.viewer import View ot.RandomGenerator.SetSeed(0) size = 100 inputDimension = 6 inputSample = ot.Normal(inputDimension).getSample(size) inputVar = ot.Description(inputDimension) for i in range(inputDimension): inputVar[i] = 'X' + str(i) inputSample.setDescription(inputVar) formula = ot.Description(1) expression = '' for i in range(inputDimension): if i > 0: expression += '+' expression += 'cos(' + str(i + 1) + '*' + inputVar[i] + ')' formula[0] = expression outputVar = ot.Description(1) outputVar[0] = 'y' model = ot.NumericalMathFunction(inputVar, outputVar, formula) outputSample = model(inputSample) cobweb = ot.VisualTest_DrawCobWeb(inputSample, outputSample, 2.5, 3.0, 'red', False) bb = cobweb.getBoundingBox() # define the increasing factor of the bounding box factor = 1.1 bb[1] = factor * bb[1]
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
distribution = ot.Normal(2) size = 30 sample2D = distribution.getSample(size) cloud = ot.Cloud(sample2D, "red", "fsquare", "Sample2D Cloud") graph.add(cloud) # Display extrema indices x1 = [x[0] for x in sample2D[:, 0]] x2 = [x[0] for x in sample2D[:, 1]] idx = [0] * 4 idx[0] = x1.index(min(x1)) idx[1] = x1.index(max(x1)) idx[2] = x2.index(min(x2)) idx[3] = x2.index(max(x2)) labels = ot.Description(sample2D.getSize()) for i in range(4): labels[idx[i]] = str(idx[i]) position = ot.Description(sample2D.getSize(), "top") position[idx[0]] = "right" position[idx[1]] = "left" position[idx[2]] = "top" position[idx[3]] = "bottom" text = ot.Text(sample2D, labels) text.setColor("red") text.setTextPositions(position) graph.add(text) view = View(graph)
firstSample[i] = ot.Point(1, sample2D[i, 0]) secondSample[i] = ot.Point(1, sample2D[i, 1]) lmtest = ot.LinearModelAlgorithm(firstSample, secondSample).getResult() drawLinearModelVTest = ot.VisualTest.DrawLinearModel(lmtest) print("LinearModelV = ", drawLinearModelVTest) drawLinearModelResidualTest = ot.VisualTest.DrawLinearModelResidual(lmtest) print("LinearModelR = ", drawLinearModelResidualTest) # CobWeb tests size = 100 inputDimension = 6 inputSample = ot.Normal(inputDimension).getSample(size) inputVar = ["X" + str(i) for i in range(inputDimension)] formula = ot.Description(1) expression = "" for i in range(inputDimension): if i > 0: expression += "+" expression += "cos(" + str(i + 1) + "*" + inputVar[i] + ")" formula[0] = expression model = ot.SymbolicFunction(inputVar, formula) outputSample = model(inputSample) cobwebValue = ot.VisualTest.DrawParallelCoordinates( inputSample, outputSample, 2.5, 3.0, "red", False) print("cobwebValue = ", cobwebValue) cobwebQuantile = ot.VisualTest.DrawParallelCoordinates( inputSample, outputSample, 0.7, 0.9, "red", False) print("cobwebQuantile = ", cobwebQuantile)
def buildEvent(vector, interval): dimension = vector.getDimension() if dimension != interval.getDimension(): raise Exception('Dimensions not compatible') finiteLowerBound = interval.getFiniteLowerBound() finiteUpperBound = interval.getFiniteUpperBound() lowerBound = interval.getLowerBound() upperBound = interval.getUpperBound() # Easy case: 1D interval if (dimension == 1): if finiteLowerBound[0] and not finiteUpperBound[0]: print('case 1') return ot.Event(vector, Greater(), lowerBound[0]) if not finiteLowerBound[0] and finiteUpperBound[0]: print('case 2') return ot.Event(vector, Less(), upperBound[0]) if finiteLowerBound[0] and finiteUpperBound[0]: print('case 3') testFunction = ot.SymbolicFunction( 'x', 'min(x-(' + str(lowerBound[0]) + '), (' + str(upperBound[0]) + ') - x)') newVector = ot.RandomVector( ot.Function(testFunction, vector.getFunction()), vector.getAntecedent()) return ot.Event(newVector, Greater(), 0.0) # Here we build an event that is always true and much cheaper to # compute print('case 4') inputDimension = vector.getFunction().getInputDimension() return ot.Event( ot.RandomVector( ot.SymbolicFunction( ot.Description.BuildDefault(inputDimension, 'x'), ['0.0']), vector.getAntecedent()), Less(), 1.0) # General case numConstraints = 0 inVars = ot.Description.BuildDefault(dimension, 'y') slacks = ot.Description(0) for i in range(dimension): if finiteLowerBound[i]: slacks.add(inVars[i] + '-(' + str(lowerBound[i]) + ')') if finiteUpperBound[i]: slacks.add('(' + str(upperBound[i]) + ')-' + inVars[i]) # No constraint if slacks.getSize() == 0: # Here we build an event that is always true and much cheaper to # compute inputDimension = vector.getFunction().getInputDimension() return ot.Event( ot.RandomVector( ot.SymbolicFunction( ot.Description.BuildDefault(inputDimension, 'x'), ['0.0']), vector.getAntecedent()), Less(), 1.0) # Only one constraint if slacks.getSize() == 1: print('case 6') testFunction = ot.SymbolicFunction(inVars, [slacks[0]]) # Several constraints else: print('case 7') formula = 'min(' + slacks[0] for i in range(1, slacks.getSize()): formula += ',' + slacks[i] formula += ')' testFunction = ot.SymbolicFunction(inVars, [formula]) newVector = ot.RandomVector( ot.Function(testFunction, vector.getFunction()), vector.getAntecedent()) return ot.Event(newVector, Greater(), 0.0)
X = ot.RandomVector(dist) Y = ot.CompositeRandomVector(f, X) # %% # The failure domain :math:`\mathcal{D}` is :math:`\mathcal{D} = \{ x=(x_1, x_2) \in \mathbb{R}^2 / f(x) \geq 0 \}` failureEvent = ot.ThresholdEvent(Y, ot.Less(), 0.0) # %% # We shall represent the failure domain event using a :class:`~openturns.Contour` object. nx, ny = 25, 25 xx = ot.Box([nx], ot.Interval([-8.0], [8.0])).generate() yy = ot.Box([ny], ot.Interval([-8.0], [8.0])).generate() inputData = ot.Box([nx, ny], ot.Interval([-8.0, -8.0], [8.0, 8.0])).generate() outputData = f(inputData) mycontour = ot.Contour(xx, yy, outputData, ot.Point([0.0]), ot.Description(["0.0"])) mycontour.setColor("black") mycontour.setLineStyle("dashed") graphModel.add(mycontour) view = otv.View(graphModel) # %% # In the physical space the failure domain boundary is the dashed black curve. We recall that one of # the steps of the FORM method is to find the closest point of the failure domain boundary to the origin. # Here we see that the symmetry of the domain implies that two points exist, one in the :math:`x_1 \geq 0` half-space and the other in the :math:`x_1 \leq 0` half-space. # %% # We build the :class:`~openturns.MultiFORM` algorithm in a similar fashion as the :class:`~openturns.FORM` algorithm. We choose an optimization solver, here the Cobyla solver, and a starting point, the mean # of the distribution `dist`. solver = ot.Cobyla() starting_pt = dist.getMean()
#! /usr/bin/env python import openturns as ot import pickle from io import BytesIO obj_list = [] obj_list.append(ot.Point([1.6, -8.7])) obj_list.append(ot.Sample([[4.6, -3.7], [8.4, 6.3]])) obj_list.append(ot.Description(['x', 'y', 'z'])) obj_list.append(ot.Indices([1, 2, 4])) obj_list.append(ot.Matrix([[1, 2], [3, 4]])) obj_list.append(ot.SymbolicFunction(['x1', 'x2'], ['y1=x1+x2'])) src = BytesIO() for obj in obj_list: pickle.dump(obj, src) src.seek(0) for obj in obj_list: obj2 = pickle.load(src) print(('object: ' + str(obj))) print(('same: ' + str(obj2 == obj) + '\n'))
cNameList = [ 'LHS', 'DirectionalSampling', 'SimulationSensitivityAnalysis', 'ProbabilitySimulationAlgorithm' ] for cName in cNameList: otClass = getattr(ot, cName) instance = otClass() myStudy.add(cName, instance) # Create a Beta distribution beta = ot.Beta(3.0, 5.0, -1.0, 4.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)
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), ot.Point([0.0]), ot.Description(["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), ot.Point([1.0]), ot.Description(["1.0"])) mycontour1.setColor("black") mycontour1.setLineStyle("dashed") graphModel0.add(mycontour1) view = otv.View(graphModel0) # %% # The contour line associated with the 0.0 value for the second marginal. mycontour2 = ot.Contour(xx, yy, outputData.getMarginal(1), ot.Point([0.0]), ot.Description(["0.0"]))
myAlgo.setProgressCallback(progress) myAlgo.setStopCallback(stop) print('algo=', myAlgo) # Perform the simulation myAlgo.run() # Stream out the result print('algo result=', myAlgo.getResult()) print('probability distribution=', myAlgo.getResult().getProbabilityDistribution()) print('-' * 32) ot.RandomGenerator.SetSeed(0) description = ot.Description() description.add('composite vector/comparison event') dim = 2 distribution = ot.Normal(dim) Xvector = ot.RandomVector(distribution) f = ot.SymbolicFunction(['x0', 'x1'], ['x0+x1']) Yvector = ot.CompositeRandomVector(f, Xvector) s = 1.0 event1 = ot.Event(Yvector, ot.Greater(), s) description.add('composite vector/domain event') domain1D = ot.LevelSet(ot.SymbolicFunction(['x0'], ['sin(x0)']), ot.LessOrEqual(), -0.5) event2 = ot.Event(Yvector, domain1D) description.add('composite vector/interval event') interval = ot.Interval(0.5, 1.5) event3 = ot.Event(Yvector, interval)
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
# check array / IndicesCollection conversion a0 = np.array(((1, 3, 5), (2, 4, 6))) i0 = ot.IndicesCollection(a0) print("array", a0, "=> IndicesCollection", i0) a1 = np.array(i0) print("IndicesCollection", i0, "=> array", a1) # Check sequence protocol for IndicesCollection for x in i0: print("value", x) # Check tuple / Description conversion t0 = ('blob', 'zou') i0 = ot.Description(t0) print("tuple", t0, "=> Description", i0) t1 = tuple(i0) print("Description", i0, "=> tuple", t1) # Check list / Description conversion l0 = ['blob', 'zou'] i0 = ot.Description(l0) print("list", l0, "=> Description", i0) l1 = list(i0) print("Description", i0, "=> list", l1) # array / Description conversion a0 = np.array(('x0', 'x1', 'x2'))
cNameList = [ 'LHS', 'DirectionalSampling', 'SimulationSensitivityAnalysis', 'ProbabilitySimulationAlgorithm' ] for cName in cNameList: otClass = getattr(ot, cName) instance = otClass() print('--', cName, instance) myStudy.add(cName, instance) # Create a Beta distribution beta = ot.Beta(3.0, 2.0, -1.0, 4.0) myStudy.add('beta', beta) # Create an analytical Function input = ot.Description(3) input[0] = 'a' input[1] = 'b' input[2] = 'c' formulas = ot.Description(3) formulas[0] = 'a+b+c' formulas[1] = 'a-b*c' formulas[2] = '(a+2*b^2+3*c^3)/6' analytical = ot.SymbolicFunction(input, formulas) analytical.setName('analytical') analytical.setOutputDescription(['z1', 'z2', 'z3']) myStudy.add('analytical', analytical) # Create a TaylorExpansionMoments algorithm antecedent = ot.RandomVector( ot.IndependentCopula(analytical.getInputDimension()))
import openturns as ot print(ot.__file__) desc = ot.Description(5, "zou") print(desc) print(desc[1])