def drawObservationsVsPredictions(self): """ Plots the output of the model depending on the output observations before and after calibration. """ ySize = self.outputObservations.getSize() yDim = self.outputObservations.getDimension() graph = ot.Graph("", "Observations", "Predictions", True, "topleft") # Plot the diagonal if (yDim == 1): graph = self._drawObservationsVsPredictions1Dimension( self.outputObservations, self.outputAtPrior, self.outputAtPosterior) elif (ySize == 1): outputObservations = ot.Sample(self.outputObservations[0], 1) outputAtPrior = ot.Sample(self.outputAtPrior[0], 1) outputAtPosterior = ot.Sample(self.outputAtPosterior[0], 1) graph = self._drawObservationsVsPredictions1Dimension( outputObservations, outputAtPrior, outputAtPosterior) else: fig = pl.figure(figsize=(self.unitlength * yDim, self.unitlength)) for i in range(yDim): outputObservations = self.outputObservations[:, i] outputAtPrior = self.outputAtPrior[:, i] outputAtPosterior = self.outputAtPosterior[:, i] graph = self._drawObservationsVsPredictions1Dimension( outputObservations, outputAtPrior, outputAtPosterior) ax = fig.add_subplot(1, yDim, i + 1) _ = otv.View(graph, figure=fig, axes=[ax]) return graph
def drawBidimensionalSample(sample, title): n = sample.getSize() graph = ot.Graph("%s, size=%d" % (title, n), r"$X_1$", r"$X_2$", True, '') #cloud = ot.Cloud(sample) cloud = ot.Cloud(sample, "blue", "fsquare", "") graph.add(cloud) return graph
def drawKSDistance(sample, distribution, observation, D, distFactory): graph = ot.Graph("KS Distance = %.4f" % (D), "X", "CDF", True, "topleft") # Thick vertical line at point x ECDF_x_plus = sample.computeEmpiricalCDF(observation) ECDF_x_minus = ECDF_x_plus - 1.0 / sample.getSize() CDF_index = distribution.computeCDF(observation) curve = ot.Curve( [observation[0], observation[0], observation[0]], [ECDF_x_plus, ECDF_x_minus, CDF_index], ) curve.setLegend("KS Statistics") curve.setLineWidth(4.0 * curve.getLineWidth()) graph.add(curve) # Empirical CDF empiricalCDF = ot.UserDefined(sample).drawCDF() empiricalCDF.setLegends(["Empirical DF"]) graph.add(empiricalCDF) # distname = distFactory.getClassName() distribution = distFactory.build(sample) cdf = distribution.drawCDF() cdf.setLegends([distname]) graph.add(cdf) graph.setColors(ot.Drawable.BuildDefaultPalette(3)) return graph
def drawKSDistance(sample, distribution, observation, D, distFactory, delta_x=ot.Point([1.0e-6])): graph = ot.Graph("KS Distance = %.4f" % (D), "X", "CDF", True, "topleft") # Vertical line at point x ECDF_index = sample.computeEmpiricalCDF(observation) ECDF_index_shifted = sample.computeEmpiricalCDF(observation - delta_x) CDF_index = distribution.computeCDF(observation) curve = ot.Curve( [observation[0], observation[0], observation[0]], [ECDF_index, ECDF_index_shifted, CDF_index], ) curve.setColor("green") curve.setLegend("KS Statistics") curve.setLineWidth(4.0 * curve.getLineWidth()) graph.add(curve) # Empirical CDF empiricalCDF = ot.UserDefined(sample).drawCDF() empiricalCDF.setColors(["blue"]) empiricalCDF.setLegends(["Empirical DF"]) graph.add(empiricalCDF) # distname = distFactory.getClassName() distribution = distFactory.build(sample) cdf = distribution.drawCDF() cdf.setLegends([distname]) graph.add(cdf) return graph
def myPolynomialCurveFittingGraph(total_degree, x_train, y_train): """Returns the graphics for a polynomial curve fitting with given total degree""" responseSurface, basis = myPolynomialDataFitting(total_degree, x_train, y_train) # Graphics n_test = 100 x_test = linearSample(0, 1, n_test) ypredicted_test = responseSurface(basis(x_test)) # Graphics graph = ot.Graph("Polynomial curve fitting", "x", "y", True, "topright") # The "unknown" function curve = g.draw(0, 1) curve.setColors(["green"]) graph.add(curve) # Training set cloud = ot.Cloud(x_train, y_train) cloud.setPointStyle("circle") cloud.setLegend("N=%d" % (x_train.getSize())) graph.add(cloud) # Predictions curve = ot.Curve(x_test, ypredicted_test) curve.setLegend("Polynomial Degree = %d" % (total_degree)) curve.setColor("red") graph.add(curve) return graph
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 drawFamily(factory, degreeMax=5): # Load all the valid colors colorList = ot.Drawable.BuildDefaultPalette(degreeMax) # Create a fine title titleJacobi = factory.__class__.__name__.replace('Factory', '') + " polynomials" # Create an empty graph which will be fullfilled # with curves graphJacobi = ot.Graph(titleJacobi, "z", "polynomial values", True, "topright") # Fix the number of points for the graph pointNumber = 101 # Bounds of the graph xMinJacobi = -1.0 xMaxJacobi = 1.0 # Get the curves for i in range(degreeMax): graphJacobi_temp = factory.build(i).draw(xMinJacobi, xMaxJacobi, pointNumber) graphJacobi_temp_draw = graphJacobi_temp.getDrawable(0) graphJacobi_temp_draw.setLegend("degree " + str(i)) graphJacobi_temp_draw.setColor(colorList[i]) graphJacobi.add(graphJacobi_temp_draw) return graphJacobi
def plotMyBasicKriging(krigResult, xMin, xMax, X, Y, level = 0.95): ''' Given a kriging result, plot the data, the kriging metamodel and a confidence interval. ''' samplesize = X.getSize() meta = krigResult.getMetaModel() graphKriging = meta.draw(xMin, xMax) graphKriging.setLegends(["Kriging"]) # Create a grid of points and evaluate the function and the kriging nbpoints = 50 xGrid = linearSample(xMin,xMax,nbpoints) yFunction = g(xGrid) yKrig = meta(xGrid) # Compute the conditional covariance epsilon = ot.Point(nbpoints,1.e-8) conditionalVariance = krigResult.getConditionalMarginalVariance(xGrid)+epsilon conditionalVarianceSample = ot.Sample([[cv] for cv in conditionalVariance]) conditionalSigma = sqrt(conditionalVarianceSample) # Compute the quantile of the Normal distribution alpha = 1-(1-level)/2 quantileAlpha = ot.DistFunc.qNormal(alpha) # Graphics of the bounds epsilon = 1.e-8 dataLower = [yKrig[i,0] - quantileAlpha * conditionalSigma[i,0] for i in range(nbpoints)] dataUpper = [yKrig[i,0] + quantileAlpha * conditionalSigma[i,0] for i in range(nbpoints)] # Coordinates of the vertices of the Polygons vLow = [[xGrid[i,0],dataLower[i]] for i in range(nbpoints)] vUp = [[xGrid[i,0],dataUpper[i]] for i in range(nbpoints)] # Compute the Polygon graphics boundsPoly = plot_kriging_bounds(vLow,vUp,nbpoints) boundsPoly.setLegend("95% bounds") # Validate the kriging metamodel mmv = ot.MetaModelValidation(xGrid, yFunction, meta) Q2 = mmv.computePredictivityFactor()[0] # Plot the function graphFonction = ot.Curve(xGrid,yFunction) graphFonction.setLineStyle("dashed") graphFonction.setColor("magenta") graphFonction.setLineWidth(2) graphFonction.setLegend("Function") # Draw the X and Y observed cloudDOE = ot.Cloud(X, Y) cloudDOE.setPointStyle("circle") cloudDOE.setColor("red") cloudDOE.setLegend("Data") # Assemble the graphics graph = ot.Graph() graph.add(boundsPoly) graph.add(graphFonction) graph.add(cloudDOE) graph.add(graphKriging) graph.setLegendPosition("bottomright") graph.setAxes(True) graph.setGrid(True) graph.setTitle("Size = %d, Q2=%.2f%%" % (samplesize,100*Q2)) graph.setXTitle("X") graph.setYTitle("Y") return graph
def drawResidualsQQplot(self, model="uncensored", name=None): """ Draw the residuals QQ plot with the fitted distribution. Parameters ---------- model : string The residuals to be used, either *uncensored* or *censored* if censored threshold were given. Default is *uncensored*. name : string name of the figure to be saved with *transparent* option sets to True and *bbox_inches='tight'*. It can be only the file name or the full path name. Default is None. Returns ------- fig : `matplotlib.figure <http://matplotlib.org/api/figure_api.html>`_ Matplotlib figure object. ax : `matplotlib.axes <http://matplotlib.org/api/axes_api.html>`_ Matplotlib axes object. """ # Check is the censored model exists when asking for it if model == "censored" and not self._censored: raise NameError('Residuals for censored data is not available.') if model == "uncensored": residuals = self._resultsUnc.residuals distribution = self._resultsUnc.resDist elif model == "censored": residuals = self._resultsCens.residuals distribution = self._resultsCens.resDist else: raise NameError("model can be 'uncensored' or 'censored'.") fig, ax = plt.subplots(figsize=(8, 8)) graph = ot.VisualTest.DrawQQplot(residuals, distribution) drawables = graph.getDrawables() drawables[1].setPointStyle('dot') drawables[1].setLineWidth(3) drawables[1].setColor('blue') graph = ot.Graph() graph.add(drawables) graph.setXTitle('Residuals empirical quantiles') graph.setYTitle(distribution.__str__()) graph.setGrid(True) View(graph, axes=[ax]) if model == "uncensored": ax.set_title('QQ-plot of the residuals ') elif model == "censored": ax.set_title('QQ-plot of the residuals for censored data') if name is not None: fig.savefig(name, bbox_inches='tight', transparent=True) return fig, ax
def drawSample(self, inputSample, outputSample): """ Draw the sample of an event. The points inside and outside the event are colored. Parameters ---------- inputSample: an ot.Sample The input 2D sample. outputSample: an ot.Sample The output 1D sample. Returns ------- None. """ if inputSample.getDimension() != 2: raise ValueError("The input dimension of the input sample " "is equal to %d but should be 2." % (inputSample.getDimension())) # threshold = self.event.getThreshold() g = self.event.getFunction() operator = self.event.getOperator() # sampleSize = outputSample.getSize() insideIndices = [] outsideIndices = [] for i in range(sampleSize): y = outputSample[i, 0] isInside = operator(y, threshold) if isInside: insideIndices.append(i) else: outsideIndices.append(i) # insideSample = ot.Sample([inputSample[i] for i in insideIndices]) outsideSample = ot.Sample([inputSample[i] for i in outsideIndices]) # description = g.getInputDescription() title = "Points X s.t. g(X) %s %s" % (operator, threshold) graph = ot.Graph(title, description[0], description[1], True, "") if len(insideIndices) > 0: cloud = ot.Cloud(insideSample, self.insideEventPointColor, "fsquare", "In") graph.add(cloud) if len(outsideIndices) > 0: cloud = ot.Cloud(outsideSample, self.outsideEventPointColor, "fsquare", "Out") graph.add(cloud) graph.setLegendPosition("topright") return graph
def plot_marginals(name, marginals): g = ot.Graph('', '', '', True) for m in marginals[:3]: g.add(m.drawPDF()) g.setDefaultColors() # Saving figure view = otv.View(g) view.save(name) view.close()
def plotXvsY(sampleX, sampleY, figsize=(15, 3)): dimX = sampleX.getDimension() inputdescr = sampleX.getDescription() fig = pl.figure(figsize=figsize) for i in range(dimX): ax = fig.add_subplot(1, dimX, i + 1) graph = ot.Graph('', inputdescr[i], 'Y', True, '') cloud = ot.Cloud(sampleX[:, i], sampleY) graph.add(cloud) _ = ot.viewer.View(graph, figure=fig, axes=[ax]) return fig
def pairs(data, filename): print(" Draw pairs") print(" Distribution") g = ot.Graph() pairs_data = ot.Pairs(data) pairs_data.setPointStyle('dot') g.add(pairs_data) view = otv.View(g, (800, 800), square_axes=True) view.save(filename) print("Saving figure in {}".format(filename)) view.close() print(" Copula") g = ot.Graph() pairs_data = ot.Pairs((data.rank() + 0.5) / data.getSize()) pairs_data.setPointStyle('dot') g.add(pairs_data) view = otv.View(g, (800, 800), square_axes=True) view.save(filename) print("Saving figure in {}".format(filename)) view.close()
def plot_exact_model(): graph = ot.Graph('', 'x', '', True, '') y_test = model(x_test) curveModel = ot.Curve(x_test, y_test) curveModel.setLineStyle("solid") curveModel.setColor("black") graph.add(curveModel) cloud = ot.Cloud(Xtrain, Ytrain) cloud.setColor("black") cloud.setPointStyle("fsquare") graph.add(cloud) return graph
def drawDimensionReduction(self): """Pairdraw of the principal components. :return: OpenTURNS Graph object. :rtype: :class:`openturns.Graph` """ graph = ot.Graph('Reduced Space', '', '', True, 'topright') cloud = ot.Pairs(self.principalComponents) cloud.setLabels(self.principalComponents.getDescription()) graph.add(cloud) return graph
def computeBoxCox(factors, valuesInit, shift): # if no affine trend is considered graph = ot.Graph() myBoxCoxFactory = ot.BoxCoxFactory() myModelTransform = myBoxCoxFactory.build(valuesInit, [shift], graph) lambdaBoxCox = myModelTransform.getLambda()[0] # if an affine trend is considered (more computing time required) # works only in 1D # myBoxCoxFactory = LinearBoxCoxFactory() # myModelTransform, graph = myBoxCoxFactory.build(factors, valuesInit) # lambdaBoxCox = myModelTransform.getLambda()[0] return lambdaBoxCox, graph
def pairs(data, filename): ''' Allows to plot the data for each pair of component random variable''' print(" Draw pairs") print(" Distribution") g = ot.Graph() pairs_data = ot.Pairs(data) pairs_data.setPointStyle('dot') g.add(pairs_data) view = otv.View(g, (800, 800), square_axes=True) view.save(filename) print("Saving figure in {}".format(filename)) view.close() print(" Copula") g = ot.Graph() pairs_data = ot.Pairs((data.rank() + 0.5) / data.getSize()) pairs_data.setPointStyle('dot') g.add(pairs_data) view = otv.View(g, (800, 800), square_axes=True) view.save( filename.parent.joinpath(filename.stem + '_copula' + filename.suffix)) print("Saving figure in {}".format( filename.parent.joinpath(filename.stem + '_copula' + filename.suffix))) view.close()
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 test_HighDensityRegionAlgorithm(): ot.RandomGenerator.SetSeed(0) numberOfPointsForSampling = 500 ot.ResourceMap.Set('Distribution-MinimumVolumeLevelSetBySampling', 'true') ot.ResourceMap.Set('Distribution-MinimumVolumeLevelSetSamplingSize', str(numberOfPointsForSampling)) # Dataset fname = os.path.join(os.path.dirname(__file__), 'data', 'gauss-mixture.csv') sample = ot.Sample.ImportFromCSVFile(fname) # Creation du kernel smoothing ks = ot.KernelSmoothing() sample_distribution = ks.build(sample) dp = HighDensityRegionAlgorithm(sample, sample_distribution) dp.run() # Draw contour/inliers/outliers graph = ot.Graph('High Density Region draw', '', '', True, 'topright') fig, axs, graphs = dp.drawContour() plt.show() fig, axs, graphs = dp.drawContour(drawData=True) plt.show() fig, axs, graphs = dp.drawContour(drawOutliers=False) plt.show() graph.add(dp.drawInliers()) View(graph) plt.show() # Plot data graph.add(dp.drawOutliers()) View(graph) plt.show() outlierIndices = dp.computeOutlierIndices() expected_outlierIndices = [ 31, 60, 84, 105, 116, 121, 150, 151, 200, 207, 215, 218, 220, 248, 282, 284, 291, 359, 361, 378, 382, 404, 412, 418, 425, 426, 433, 449, 450, 457, 461, 466, 474, 490, 498, 567, 587, 616, 634, 638, 652, 665, 687, 714, 729, 730, 748, 751, 794, 876, 894, 896, 903, 925, 928, 963, 968, 987 ] assert_equal(outlierIndices, expected_outlierIndices)
def draw(dist, Y): g = ot.Graph() g.setAxes(True) g.setGrid(True) c = ot.Cloud(dist.getSample(10000)) c.setColor("red") c.setPointStyle("bullet") g.add(c) c = ot.Cloud(Y) c.setColor("black") c.setPointStyle("bullet") g.add(c) g.setBoundingBox(ot.Interval( Y.getMin()-0.5*Y.computeRange(), Y.getMax()+0.5*Y.computeRange())) return g
def drawIFS(f_i, skip=100, iterations=1000, batch_size=1, name="IFS", color="blue"): # Any set of initial points should work in theory initialPoints = ot.Normal(2).getSample(batch_size) # Compute the contraction factor of each function all_r = [m.sqrt(abs(f[1].computeDeterminant())) for f in f_i] # Find the box counting dimension, ie the value s such that r_1^s+...+r_n^s-1=0 equation = "-1.0" for r in all_r: equation += "+" + str(r) + "^s" dim = len(f_i) s = ot.Brent().solve(ot.SymbolicFunction("s", equation), 0.0, 0.0, -m.log(dim) / m.log(max(all_r))) # Add a small perturbation to sample even the degenerated transforms probabilities = [r**s + 1e-2 for r in all_r] # Build the sampling distribution support = [[i] for i in range(dim)] choice = ot.UserDefined(support, probabilities) currentPoints = initialPoints points = ot.Sample(0, 2) # Convert the f_i into LinearEvaluation to benefit from the evaluation over # a Sample phi_i = [ot.LinearEvaluation([0.0] * 2, f[0], f[1]) for f in f_i] # Burning phase for i in range(skip): index = int(round(choice.getRealization()[0])) currentPoints = phi_i[index](currentPoints) # Iteration phase for i in range(iterations): index = int(round(choice.getRealization()[0])) currentPoints = phi_i[index](currentPoints) points.add(currentPoints) # Draw the IFS graph = ot.Graph() graph.setTitle(name) graph.setXTitle("x") graph.setYTitle("y") graph.setGrid(True) cloud = ot.Cloud(points) cloud.setColor(color) cloud.setPointStyle("dot") graph.add(cloud) return graph, s
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
def drawParameterDistributions(self): """ Plots the prior and posterior distribution of the calibrated parameter theta. """ thetaPrior = self.calibrationResult.getParameterPrior() thetaDescription = thetaPrior.getDescription() thetaPosterior = self.calibrationResult.getParameterPosterior() thetaDim = thetaPosterior.getDimension() fig = pl.figure(figsize=(12, 4)) for i in range(thetaDim): graph = ot.Graph("", thetaDescription[i], "PDF", True, "topright") # Prior distribution thetaPrior_i = thetaPrior.getMarginal(i) priorPDF = thetaPrior_i.drawPDF() priorPDF.setColors([self.priorColor]) priorPDF.setLegends(["Prior"]) graph.add(priorPDF) # Posterior distribution thetaPosterior_i = thetaPosterior.getMarginal(i) postPDF = thetaPosterior_i.drawPDF() postPDF.setColors([self.posteriorColor]) postPDF.setLegends(["Posterior"]) graph.add(postPDF) ''' If the prior is a Dirac, set the vertical axis bounds to the posterior. Otherwise, the Dirac set to [0,1], where the 1 can be much larger than the maximum PDF of the posterior. ''' if (thetaPrior_i.getName() == "Dirac"): # The vertical (PDF) bounds of the posterior postbb = postPDF.getBoundingBox() pdf_upper = postbb.getUpperBound()[1] pdf_lower = postbb.getLowerBound()[1] # Set these bounds to the graph bb = graph.getBoundingBox() graph_upper = bb.getUpperBound() graph_upper[1] = pdf_upper bb.setUpperBound(graph_upper) graph_lower = bb.getLowerBound() graph_lower[1] = pdf_lower bb.setLowerBound(graph_lower) graph.setBoundingBox(bb) # Add it to the graphics ax = fig.add_subplot(1, thetaDim, i + 1) _ = otv.View(graph, figure=fig, axes=[ax]) return fig
def _drawObservationsVsInputs1Dimension(self, inputObservations, outputObservations, outputAtPrior, outputAtPosterior): """ Plots the observed output of the model depending on the observed input before and after calibration. Can manage only 1D samples. """ xDim = inputObservations.getDimension() if (xDim != 1): raise TypeError('Input observations are not 1D.') yDim = outputObservations.getDimension() xdescription = inputObservations.getDescription() ydescription = outputObservations.getDescription() graph = ot.Graph("", xdescription[0], ydescription[0], True, "topright") # Observations if (yDim == 1): cloud = ot.Cloud(inputObservations, outputObservations) cloud.setColor(self.observationColor) cloud.setLegend("Observations") graph.add(cloud) else: raise TypeError('Output observations are not 1D.') # Model outputs before calibration yPriorDim = outputAtPrior.getDimension() if (yPriorDim == 1): cloud = ot.Cloud(inputObservations, outputAtPrior) cloud.setColor(self.priorColor) cloud.setLegend("Prior") graph.add(cloud) else: raise TypeError('Output prior predictions are not 1D.') # Model outputs after calibration yPosteriorDim = outputAtPosterior.getDimension() if (yPosteriorDim == 1): cloud = ot.Cloud(inputObservations, outputAtPosterior) cloud.setColor(self.posteriorColor) cloud.setLegend("Posterior") graph.add(cloud) else: raise TypeError('Output posterior predictions are not 1D.') return graph
def _drawResiduals1Dimension(self, outputObservations, outputAtPrior, outputAtPosterior, observationsError): """ Plot the distribution of the residuals and the distribution of the observation errors. Can manage only 1D samples. """ ydescription = outputObservations.getDescription() xlabel = "%s Residuals" % (ydescription[0]) graph = ot.Graph("Residuals analysis", xlabel, "Probability distribution function", True, "topright") yDim = outputObservations.getDimension() yPriorDim = outputAtPrior.getDimension() yPosteriorDim = outputAtPrior.getDimension() if (yDim == 1) and (yPriorDim == 1): posteriorResiduals = outputObservations - outputAtPrior kernel = ot.KernelSmoothing() fittedDist = kernel.build(posteriorResiduals) residualPDF = fittedDist.drawPDF() residualPDF.setColors([self.priorColor]) residualPDF.setLegends(["Prior"]) graph.add(residualPDF) else: raise TypeError('Output prior observations are not 1D.') if (yDim == 1) and (yPosteriorDim == 1): posteriorResiduals = outputObservations - outputAtPosterior kernel = ot.KernelSmoothing() fittedDist = kernel.build(posteriorResiduals) residualPDF = fittedDist.drawPDF() residualPDF.setColors([self.posteriorColor]) residualPDF.setLegends(["Posterior"]) graph.add(residualPDF) else: raise TypeError('Output posterior observations are not 1D.') # Plot the distribution of the observation errors if (observationsError.getDimension() == 1): # In the other case, we just do not plot obserrgraph = observationsError.drawPDF() obserrgraph.setColors([self.observationColor]) obserrgraph.setLegends(["Observation errors"]) graph.add(obserrgraph) return graph
def drawKL(scaledKL, KLev, mesh, title="Scaled KL modes"): graph_modes = scaledKL.drawMarginal() graph_modes.setTitle(title + " scaled KL modes") graph_modes.setXTitle('$x$') graph_modes.setYTitle(r'$\sqrt{\lambda_i}\phi_i$') data_ev = [[i, KLev[i]] for i in range(scaledKL.getSize())] graph_ev = ot.Graph() graph_ev.add(ot.Curve(data_ev)) graph_ev.add(ot.Cloud(data_ev)) graph_ev.setTitle(title + " KL eigenvalues") graph_ev.setXTitle('$k$') graph_ev.setYTitle(r'$\lambda_i$') graph_ev.setAxes(True) graph_ev.setGrid(True) graph_ev.setLogScale(2) bb = graph_ev.getBoundingBox() lower = bb.getLowerBound() lower[1] = 1.0e-7 bb = ot.Interval(lower, bb.getUpperBound()) graph_ev.setBoundingBox(bb) return graph_modes, graph_ev
def _drawObservationsVsPredictions1Dimension(self, outputObservations, outputAtPrior, outputAtPosterior): """ Plots the output of the model depending on the output observations before and after calibration. Can manage only 1D samples. """ yDim = outputObservations.getDimension() ydescription = outputObservations.getDescription() xlabel = "%s Observations" % (ydescription[0]) ylabel = "%s Predictions" % (ydescription[0]) graph = ot.Graph("", xlabel, ylabel, True, "topleft") # Plot the diagonal if (yDim == 1): curve = ot.Curve(outputObservations, outputObservations) curve.setColor(self.observationColor) graph.add(curve) else: raise TypeError('Output observations are not 1D.') # Plot the predictions before yPriorDim = outputAtPrior.getDimension() if (yPriorDim == 1): cloud = ot.Cloud(outputObservations, outputAtPrior) cloud.setColor(self.priorColor) cloud.setLegend("Prior") graph.add(cloud) else: raise TypeError('Output prior predictions are not 1D.') # Plot the predictions after yPosteriorDim = outputAtPosterior.getDimension() if (yPosteriorDim == 1): cloud = ot.Cloud(outputObservations, outputAtPosterior) cloud.setColor(self.posteriorColor) cloud.setLegend("Posterior") graph.add(cloud) else: raise TypeError('Output posterior predictions are not 1D.') return graph
def ot_drawcontour(ot_draw): ot.ResourceMap_SetAsUnsignedInteger("Contour-DefaultLevelsNumber", 7) drawables = ot_draw.getDrawables() levels = [] for i in range(len(drawables)): contours = drawables[i] levels.append(contours.getLevels()[0]) ot.ResourceMap.SetAsUnsignedInteger('Drawable-DefaultPalettePhase', len(levels)) #Colors palette = ot.Drawable.BuildDefaultPalette(len(levels)) #Colors newcontour = ot_draw.getDrawable(0) drawables = list() for i in range(len(levels)): newcontour.setLevels([levels[i]]) # Inline the level values newcontour.setDrawLabels(True) newcontour.setLabels([str("{:.3e}".format(levels[i]))]) # We have to copy the drawable because a Python list stores only pointers drawables.append(ot.Drawable(newcontour)) graphFineTune = ot.Graph("", "", "", True, '') graphFineTune.setDrawables(drawables) graphFineTune.setColors(palette) # Add colors return graphFineTune
def drawKSDistance(sample, distribution, x, D, distFactory): graph = ot.Graph("KS Distance = %.4f" % (D), "X", "CDF", True, "topleft") # Vertical line at point x ECDF_index = sample.computeEmpiricalCDF([x]) CDF_index = distribution.computeCDF(x) curve = ot.Curve([x, x], [ECDF_index, CDF_index]) curve.setColor("green") curve.setLegend("KS Statistics") curve.setLineWidth(4. * curve.getLineWidth()) graph.add(curve) # Empirical CDF empiricalCDF = ot.UserDefined(sample).drawCDF() empiricalCDF.setColors(["blue"]) empiricalCDF.setLegends(["Empirical DF"]) graph.add(empiricalCDF) # distname = distFactory.getClassName() distribution = distFactory.build(sample) cdf = distribution.drawCDF() cdf.setLegends([distname]) graph.add(cdf) return graph
# thanks to the spatial function g # myXtProcess R --> R g = ot.SymbolicFunction(['x1'], ['exp(x1)']) myDynTransform = ot.ValueFunction(g, 2) myXtProcess = ot.CompositeProcess(myDynTransform, myXproc) myField = myXtProcess.getRealization() graphMarginal1 = ot.KernelSmoothing().build(myField.getValues()).drawPDF() graphMarginal1.setTitle("") graphMarginal1.setXTitle("X") graphMarginal1.setLegendPosition("") # Initiate a BoxCoxFactory myBoxCoxFactory = ot.BoxCoxFactory() graph = ot.Graph() shift = [0.0] # We estimate the lambda parameter from the field myField # All values of the field are positive myModelTransform = myBoxCoxFactory.build(myField, shift, graph) graphMarginal2 = ot.KernelSmoothing().build( myModelTransform(myField).getValues()).drawPDF() graphMarginal2.setTitle("") graphMarginal2.setXTitle("T_lambda(X)") graphMarginal2.setLegendPosition("") graph.setLegendPosition("bottomright") fig = plt.figure(figsize=(12, 4)) plt.suptitle("Box Cox log-likelihood example")