Ejemplo n.º 1
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

grid = ot.GridLayout(2, 3)
palette = ot.Drawable.BuildDefaultPalette(10)
for j in range(grid.getNbColumns()):
    alpha = 1.0 + j
    pdf_curve = ot.WeibullMin(1.0, alpha, 0.0).drawPDF()
    cdf_curve = ot.WeibullMin(1.0, alpha, 0.0).drawCDF()
    pdf_curve.setColors([palette[j]])
    cdf_curve.setColors([palette[j]])
    pdf_curve.setLegends(['alpha={}'.format(alpha)])
    cdf_curve.setLegends(['alpha={}'.format(alpha)])
    grid.setGraph(0, j, pdf_curve)
    grid.setGraph(1, j, cdf_curve)
graph = grid

fig = plt.figure(figsize=(12, 8))
View(graph, figure=fig, add_legend=True)
Ejemplo n.º 2
0
Y_test = model(X_test)


# %%
def drawMetaModelValidation(X_test, Y_test, krigingMetamodel, title):
    val = ot.MetaModelValidation(X_test, Y_test, krigingMetamodel)
    Q2 = val.computePredictivityFactor()[0]
    graph = val.drawValidation().getGraph(0, 0)
    graph.setLegends([""])
    graph.setLegends(["%s, Q2 = %.2f%%" % (title, 100*Q2), ""])
    graph.setLegendPosition("topleft")
    return graph


# %%
grid = ot.GridLayout(1, 3)
grid.setTitle("Different trends")
graphConstant = drawMetaModelValidation(
    X_test, Y_test, krigingWithConstantTrend, "Constant")
graphLinear = drawMetaModelValidation(
    X_test, Y_test, krigingWithLinearTrend, "Linear")
graphQuadratic = drawMetaModelValidation(
    X_test, Y_test, krigingWithQuadraticTrend, "Quadratic")
grid.setGraph(0, 0, graphConstant)
grid.setGraph(0, 1, graphLinear)
grid.setGraph(0, 2, graphQuadratic)
_ = View(grid, figure_kw={'figsize': (13, 4)})

# %%
# We observe that the three trends perform very well in this case. With more coefficients, the Kriging metamodel is more flexibile and can adjust better to the training sample. This does not mean, however, that the trend coefficients will provide a good fit for the validation sample.
#
    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
Ejemplo n.º 4
0
#
# Validate the metamodel
# ++++++++++++++++++++++

# %%
# We create a new Monte-Carlo design of experiment. On this design of
# experiment, the FMU is simulated as well as the metamodel.

inputTestSample = inputLaw.getSample(10)
outputFMUTestSample = function(inputTestSample)
outputMetamodelTestSample = globalMetamodel(inputTestSample)

# %%
# First, we have a visual check:

gridLayout = ot.GridLayout(1, 2)

graph1 = outputFMUTestSample.draw().getGraph(0, 0)
graph1.setTitle("FMU simulations")
graph2 = outputMetamodelTestSample.draw().getGraph(0, 0)
graph2.setTitle("Metamodel")

for graph in [graph1, graph2]:
    graph.setXTitle("Time")
    graph.setYTitle("Number of infected")
    graph.setLegends(["{:.3f}".format(line[0]) for line in inputSample])

gridLayout.setGraph(0, 0, graph1)
gridLayout.setGraph(0, 1, graph2)
view = viewer.View(gridLayout,
                   legend_kw={
Ejemplo n.º 5
0
sampler = ot.RandomWalkMetropolisHastings(prior, initialState, proposal)
sampler.setLikelihood(conditional, x)
sampleSize = 10000
sample = sampler.getSample(sampleSize)
# compute acceptance rate
print("Acceptance rate: %s" % (sampler.getAcceptanceRate()))

# %%
# Plot prior to posterior marginal plots.
#

# %%
kernel = ot.KernelSmoothing()
posterior = kernel.build(sample)
grid = ot.GridLayout(1, 2)
grid.setTitle('Bayesian inference')
for parameter_index in range(2):
    graph = posterior.getMarginal(parameter_index).drawPDF()
    priorGraph = prior.getMarginal(parameter_index).drawPDF()
    graph.add(priorGraph)
    graph.setColors(ot.Drawable.BuildDefaultPalette(2))
    graph.setLegends(['Posterior', 'Prior'])
    grid.setGraph(0, parameter_index, graph)
_ = View(grid)

# %%
# Define an improper prior
# --------------------------

# %%