def generateDataForSpecificInstance(size): R = ot.CorrelationMatrix(3) R[0, 1] = 0.5 R[0, 2] = 0.45 collection = [ot.FrankCopula(3.0), ot.NormalCopula(R), ot.ClaytonCopula(2.0)] copula = ot.ComposedCopula(collection) return copula.getSample(size)
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if (ot.ClaytonCopula().__class__.__name__ == 'SklarCopula'): myStudent = ot.Student(3.0, [1.0] * 2, [3.0] * 2, ot.CorrelationMatrix(2)) copula = ot.SklarCopula(myStudent) else: copula = ot.ClaytonCopula() if copula.getDimension() == 1: copula = ot.ClaytonCopula(2) copula.setDescription(['$u_1$', '$u_2$']) pdf_graph = copula.drawPDF() cdf_graph = copula.drawCDF() fig = plt.figure(figsize=(10, 4)) plt.suptitle(str(copula)) pdf_axis = fig.add_subplot(121) cdf_axis = fig.add_subplot(122) View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False, square_axes=True) View(cdf_graph, figure=fig, axes=[cdf_axis], add_legend=False, square_axes=True)
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) view = View(grid) # Square axes graph = ot.ClaytonCopula(5.0).drawPDF() view = View(graph, square_axes=True) # Show axes as prescribed by getAxes() graph = ot.Normal().drawPDF() graph.setAxes(False) view = View(graph) view.ShowAll(block=True) # test _repr_png_ png = graph._repr_png_() assert (b'PNG' in png[:10]) # BuildDefaultPalette, BuildTableauPalette ncurves = 5 graph = ot.Graph("BuildPalette", "X", "Y", True, "topright")
""" Assemble copulas ================ """ # %% # In this example we are going to merge a collection of independent copulas into one. # # %% 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 collection of copulas R = ot.CorrelationMatrix(3) R[0, 1] = 0.5 R[0, 2] = 0.25 collection = [ot.FrankCopula(3.0), ot.NormalCopula(R), ot.ClaytonCopula(2.0)] # %% # merge the copulas copula = ot.ComposedCopula(collection) print(copula)
from __future__ import print_function import openturns as ot from openturns.viewer import View from time import time size = 250 copula1 = ot.ClaytonCopula(3.0) tau = copula1.getKendallTau()[0, 1] print("tau=", tau) copula2 = ot.GumbelCopula(1.0 / (1.0 - tau)) sample = copula1.getSample(size) graph = ot.VisualTest.DrawKendallPlot(sample, copula1) graph.add(ot.VisualTest.DrawKendallPlot(sample, copula2).getDrawable(1)) graph.setColors(["red", "green", "blue"]) graph.setLegends( ["", "sample vs " + str(copula1), "sample vs " + str(copula2)]) graph.setLegendPosition("bottomright") graph.setTitle("Copula assessment using Kendall plot") graph.setXTitle(r"$x$") graph.setYTitle(r"$y$") view = View(graph, (800, 600)) view._ax[0].axis("equal") view.save("../plot_kendall_plot.png") view.close()
def check_bernstein_copula(est_copula): """ Check if an estimated distribution of kind EmpiricalBernstein is of type copula and all marginals are also. """ print("Is estimation a copula ? --> ", est_copula.isCopula()) print("Maginal checking") dimension = est_copula.getDimension() for d in range(dimension): print("Is marginal %d a copula ? --> %s" % (d, est_copula.isCopula())) try: coll = [ot.GumbelCopula(3.0), ot.ClaytonCopula(3.0), ot.FrankCopula(3.0)] size = 100 for i, ref_copula in enumerate(coll): ref_copula = coll[i] print("Reference copula", str(ref_copula)) sample = ref_copula.getSample(size) # Default method: log-likelihood m = ot.BernsteinCopulaFactory.ComputeLogLikelihoodBinNumber(sample) print("Log-likelihood m=", m) est_copula = ot.BernsteinCopulaFactory().build(sample, m) max_error = compute_max_error(ref_copula, est_copula) print("Max. error=%.5f" % max_error) check_bernstein_copula(est_copula) # AMISE method m = ot.BernsteinCopulaFactory.ComputeAMISEBinNumber(sample) print("AMISE m=", m)
=========================== """ # %% # In this example we are going to visualize an estimated copula versus the data in the rank space. # %% 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 data marginals = [ot.Normal()] * 2 dist = ot.ComposedDistribution(marginals, ot.ClaytonCopula(3)) N = 500 sample = dist.getSample(N) # %% # The estimated copula estimated = ot.ClaytonCopulaFactory().build(sample) # %% # Cloud in the rank space ranksTransf = ot.MarginalTransformationEvaluation(marginals, ot.MarginalTransformationEvaluation.FROM) rankSample = ranksTransf(sample) rankCloud = ot.Cloud(rankSample, 'blue', 'plus', 'sample') # %% # Graph with rank sample and estimated copula
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if ot.ClaytonCopula().__class__.__name__ == 'EmpiricalBernsteinCopula': sample = ot.Dirichlet([1.0, 2.0, 3.0]).getSample(100) copula = ot.EmpiricalBernsteinCopula(sample, 4) elif ot.ClaytonCopula().__class__.__name__ == 'ExtremeValueCopula': copula = ot.ExtremeValueCopula(ot.SymbolicFunction("t", "t^3/2-t/2+1")) elif ot.ClaytonCopula( ).__class__.__name__ == 'MaximumEntropyOrderStatisticsCopula': marginals = [ot.Beta(1.5, 3.2, 0.0, 1.0), ot.Beta(2.0, 4.3, 0.5, 1.2)] copula = ot.MaximumEntropyOrderStatisticsCopula(marginals) elif ot.ClaytonCopula().__class__.__name__ == 'NormalCopula': R = ot.CorrelationMatrix(2) R[1, 0] = 0.8 copula = ot.NormalCopula(R) elif ot.ClaytonCopula().__class__.__name__ == 'SklarCopula': student = ot.Student(3.0, [1.0] * 2, [3.0] * 2, ot.CorrelationMatrix(2)) copula = ot.SklarCopula(student) else: copula = ot.ClaytonCopula() if copula.getDimension() == 1: copula = ot.ClaytonCopula(2) copula.setDescription(['$u_1$', '$u_2$']) pdf_graph = copula.drawPDF() cdf_graph = copula.drawCDF() fig = plt.figure(figsize=(10, 4)) pdf_axis = fig.add_subplot(121) cdf_axis = fig.add_subplot(122) View(pdf_graph, figure=fig,
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View myColl = [ot.ClaytonCopula(0.3), ot.NormalCopula(3)] myMergedCop = ot.ComposedCopula(myColl) myMergedCop.setDescription(['$u_1$', '$u_2$', '$u_3$', '$u_4$', '$u_5$']) graphPDF = myMergedCop.drawMarginal2DPDF(0, 1, [0.0] * 2, [1.0] * 2, [100] * 2) graphPDF.setXTitle('$u_1$') graphPDF.setYTitle('$u_2$') graphCDF = myMergedCop.drawMarginal2DCDF(0, 1, [0.0] * 2, [1.0] * 2, [100] * 2) graphCDF.setXTitle('$u_1$') graphCDF.setYTitle('$u_2$') fig = plt.figure(figsize=(10, 4)) pdf_axis = fig.add_subplot(121) cdf_axis = fig.add_subplot(122) pdf_axis.set_xlim(auto=True) cdf_axis.set_xlim(auto=True) View(graphPDF, figure=fig, axes=[pdf_axis], add_legend=True) View(graphCDF, figure=fig, axes=[cdf_axis], add_legend=True) fig.suptitle("ComposedCopula(Clayton(0.3), NormalCopula(3)): pdf and cdf")
#! /usr/bin/env python from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() model = ot.SymbolicFunction(['x0', 'x1', 'x2', 'x3'], ['-(6+x0^2-x1+x2+3*x3)']) dim = model.getInputDimension() marginals = [ot.Normal(5.0, 3.0) for i in range(dim)] distribution = ot.ComposedDistribution( marginals, ot.ComposedCopula([ot.ClaytonCopula(), ot.NormalCopula()])) #distribution = ot.Normal([5]*dim, [3]*dim, ot.CorrelationMatrix(dim)) #distribution = ot.ComposedDistribution(marginals, ot.IndependentCopula(dim)) distribution.setDescription(['marginal' + str(i) for i in range(dim)]) vect = ot.RandomVector(distribution) output = ot.CompositeRandomVector(model, vect) event = ot.Event(output, ot.Greater(), 0.0) solver = ot.Cobyla() solver.setMaximumEvaluationNumber(200) solver.setMaximumAbsoluteError(1.0e-10) solver.setMaximumRelativeError(1.0e-10) solver.setMaximumResidualError(1.0e-10) solver.setMaximumConstraintError(1.0e-10) algo = ot.FORM(solver, event, distribution.getMean()) algo.run() result = algo.getResult() hasoferReliabilityIndexSensitivity = result.getHasoferReliabilityIndexSensitivity( ) print(hasoferReliabilityIndexSensitivity)
ot.Normal(-1.0, 1.0), ot.Uniform(5.0, 6.0) ] weights = [0.4, 1.0, 0.2] # %% # create the mixture distribution = ot.Mixture(distributions, weights) print(distribution) # %% # draw PDF graph = distribution.drawPDF() view = viewer.View(graph) # %% # define a list of copulas and the associated weights copulas = [ot.GumbelCopula(4.5), ot.ClaytonCopula(2.3)] weights = [0.2, 0.8] # %% # create a mixture of copulas distribution = ot.Mixture(copulas, weights) print(distribution) # %% # draw PDF graph = distribution.drawPDF() view = viewer.View(graph) plt.show()
# %% 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 two samples N = 500 dist1 = ot.ComposedDistribution([ot.Normal()] * 2, ot.GumbelCopula(3.0)) sample1 = dist1.getSample(N) sample1.setName('sample1') dist2 = ot.ComposedDistribution([ot.Normal()] * 2, ot.ClaytonCopula(0.2)) sample2 = dist2.getSample(N) sample2.setName('sample2') # %% # Change the parameter for the evaluation of E(Wi) ot.ResourceMap.SetAsUnsignedInteger('VisualTest-KendallPlot-MonteCarloSize', 25) # %% # Test a specific copula model for a given sample copula_test = ot.GumbelCopula(3) graph = ot.VisualTest.DrawKendallPlot(sample1, copula_test) view = viewer.View(graph) # %%
print("anotherSample covariance=", repr(anotherSample.computeCovariance())) # test transfo sample = distribution.getSample(10) print(sample) sample_iso = distribution.getIsoProbabilisticTransformation()(sample) print(sample_iso) sample_inv = distribution.getInverseIsoProbabilisticTransformation()( sample_iso) print(sample_inv) x = 0.6 y = [0.2] * (dim - 1) print("conditional PDF=%.6f" % distribution.computeConditionalPDF(x, y)) print("conditional CDF=%.6f" % distribution.computeConditionalCDF(x, y)) print("conditional quantile=%.6f" % distribution.computeConditionalQuantile(x, y)) pt = ot.Point([i + 1.5 for i in range(dim)]) print("sequential conditional PDF=", distribution.computeSequentialConditionalPDF(point)) resCDF = distribution.computeSequentialConditionalCDF(pt) print("sequential conditional CDF(", pt, ")=", resCDF) print("sequential conditional quantile(", resCDF, ")=", distribution.computeSequentialConditionalQuantile(resCDF)) # comparison d = ot.ComposedDistribution([ot.Uniform()] * 2, ot.ClaytonCopula(2.5)) d1 = ot.MaximumDistribution(d) d2 = ot.MaximumDistribution(d) assert d1.getDistribution() == d2.getDistribution(), "comp1" assert d1 == d2, "comp2"
# Copula fitting test using Kendall plot # -------------------------------------- # # We first perform a visual goodness-of-fit test for a copula with the Kendall plot test. # %% # We create two samples of size 500. N = 500 # %% dist1 = ot.ComposedDistribution([ot.Normal()] * 2, ot.GumbelCopula(3.0)) sample1 = dist1.getSample(N) sample1.setName('sample1') # %% dist2 = ot.ComposedDistribution([ot.Normal()] * 2, ot.ClaytonCopula(0.2)) sample2 = dist2.getSample(N) sample2.setName('sample2') # %% # We change the parameter for the evaluation of E(Wi) thanks to the `ResourceMap` : ot.ResourceMap.SetAsUnsignedInteger('VisualTest-KendallPlot-MonteCarloSize', 25) # %% # We can test a specific copula model for a given sample, copula_test = ot.GumbelCopula(3) graph = ot.VisualTest.DrawKendallPlot(sample1, copula_test) view = viewer.View(graph) # %%
# # - find the dependent components # - estimate a copula on each dependent bloc # - assemble the estimated copulas # # %% from __future__ import print_function import openturns as ot import math as m ot.Log.Show(ot.Log.NONE) # %% # generate some multivariate data to estimate, with correlation cop1 = ot.AliMikhailHaqCopula(0.6) cop2 = ot.ClaytonCopula(2.5) copula = ot.ComposedCopula([cop1, cop2]) marginals = [ ot.Uniform(5.0, 6.0), ot.Arcsine(), ot.Normal(-40.0, 3.0), ot.Triangular(100.0, 150.0, 300.0) ] distribution = ot.ComposedDistribution(marginals, copula) sample = distribution.getSample(10000).getMarginal([0, 2, 3, 1]) # %% # estimate marginals dimension = sample.getDimension() marginalFactories = [] for factory in ot.DistributionFactory.GetContinuousUniVariateFactories():
# - to draw some curves # %% 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 an 1-d distribution dist_1 = ot.Normal() # Create a 2-d distribution dist_2 = ot.ComposedDistribution( [ot.Normal(), ot.Triangular(0.0, 2.0, 3.0)], ot.ClaytonCopula(2.3)) # Create a 3-d distribution copula_dim3 = ot.Student(5.0, 3).getCopula() dist_3 = ot.ComposedDistribution( [ot.Normal(), ot.Triangular(0.0, 2.0, 3.0), ot.Exponential(0.2)], copula_dim3) # %% # Get the dimension fo the distribution dist_2.getDimension() # %% # Get the 2nd marginal dist_2.getMarginal(1)
#! /usr/bin/env python import openturns as ot ot.TESTPREAMBLE() model = ot.SymbolicFunction(['x0', 'x1', 'x2', 'x3'], ['-(6+x0^2-x1+x2+3*x3)']) dim = model.getInputDimension() marginals = [ot.Normal(5.0, 3.0) for i in range(dim)] distribution = ot.ComposedDistribution( marginals, ot.ComposedCopula([ot.ClaytonCopula(), ot.NormalCopula()])) #distribution = ot.Normal([5]*dim, [3]*dim, ot.CorrelationMatrix(dim)) #distribution = ot.ComposedDistribution(marginals, ot.IndependentCopula(dim)) distribution.setDescription(['marginal'+str(i) for i in range(dim)]) vect = ot.RandomVector(distribution) output = ot.CompositeRandomVector(model, vect) event = ot.ThresholdEvent(output, ot.Greater(), 0.0) solver = ot.Cobyla() solver.setMaximumEvaluationNumber(1000) solver.setMaximumAbsoluteError(1.0e-10) solver.setMaximumRelativeError(1.0e-10) solver.setMaximumResidualError(1.0e-10) solver.setMaximumConstraintError(1.0e-10) algo = ot.FORM(solver, event, distribution.getMean()) algo.run() result = algo.getResult() hasoferReliabilityIndexSensitivity = result.getHasoferReliabilityIndexSensitivity() print(hasoferReliabilityIndexSensitivity)