import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if (ot.ChiSquare().__class__.__name__ == 'ComposedDistribution'): correlation = ot.CorrelationMatrix(2) correlation[1, 0] = 0.25 aCopula = ot.NormalCopula(correlation) marginals = [ot.Normal(1.0, 2.0), ot.Normal(2.0, 3.0)] distribution = ot.ComposedDistribution(marginals, aCopula) elif (ot.ChiSquare().__class__.__name__ == 'CumulativeDistributionNetwork'): distribution = ot.CumulativeDistributionNetwork( [ot.Normal(2), ot.Dirichlet([0.5, 1.0, 1.5])], ot.BipartiteGraph([[0, 1], [0, 1]])) elif (ot.ChiSquare().__class__.__name__ == 'Histogram'): distribution = ot.Histogram([-1.0, 0.5, 1.0, 2.0], [0.45, 0.4, 0.15]) else: distribution = ot.ChiSquare() dimension = distribution.getDimension() if dimension <= 2: if distribution.getDimension() == 1: distribution.setDescription(['$x$']) pdf_graph = distribution.drawPDF() cdf_graph = distribution.drawCDF() fig = plt.figure(figsize=(10, 4)) plt.suptitle(str(distribution)) pdf_axis = fig.add_subplot(121) cdf_axis = fig.add_subplot(122) View(pdf_graph, figure=fig, axes=[pdf_axis], add_legend=False) View(cdf_graph, figure=fig, axes=[cdf_axis], add_legend=False) else: distribution.setDescription(['$x_1$', '$x_2$'])
from openturns.viewer import View threshold = 10.0 N = 10000 distribution = ot.Normal(2) X = ot.RandomVector(distribution) f = ot.SymbolicFunction(["x", "y"], ["x^2+y^2"]) Y = ot.RandomVector(f, X) event = ot.Event(Y, ot.Greater(), threshold) algo = ot.ProbabilitySimulationAlgorithm(event, ot.MonteCarloExperiment(1)) algo.setConvergenceStrategy(ot.Full()) algo.setMaximumOuterSampling(N) algo.setMaximumCoefficientOfVariation(0.0) algo.setMaximumStandardDeviation(0.0) algo.run() pRef = ot.ChiSquare(2).computeComplementaryCDF(threshold) # Draw convergence graph = algo.drawProbabilityConvergence() graph.setXMargin(0.0) graph.setLogScale(1) graph.setLegendPosition("topright") graph.setXTitle(r"n") graph.setYTitle(r"$\hat{p}_n$") graph.setTitle("Monte Carlo simulation - convergence history") ref = ot.Curve([[1, pRef], [N, pRef]]) ref.setColor("black") ref.setLineStyle("dashed") ref.setLegend(r"$p_{ref}$") graph.add(ref) view = View(graph, (800, 600))
b = ot.Box([N, N, N]) # Grid ==> (mu, mu+sigma) grid3D = b.generate() * dist_3D.getStandardDeviation() + dist_3D.getMean() for i in range(grid3D.getSize() // 4): point = grid3D[4 * i] PDF = dist_3D.computePDF(point) print("pdf = %.6g" % PDF) # For ticket 882 mixture = ot.RandomMixture([ot.Dirac()]) graph = mixture.drawPDF() graph = mixture.drawCDF() # Test computeQuantile for the specific case of an analytical 1D mixture case1 = 0.1 * ot.ChiSquare() q = case1.computeQuantile(0.95)[0] print("case 1, q=%.6f" % q) q = case1.computeQuantile(0.95, True)[0] print("case 1, q comp=%.6f" % q) case2 = -0.1 * ot.ChiSquare() q = case2.computeQuantile(0.95)[0] print("case 2, q=%.6f" % q) q = case2.computeQuantile(0.95, True)[0] print("case 2, q comp=%.6f" % q) # For ticket 953 atom1 = ot.TruncatedDistribution(ot.Uniform(0.0, 1.0), 0.0, 1.0) atom2 = ot.Uniform(0.0, 2.0) sum = atom1 + atom2 print("sum=", sum) print("CDF=%.6g" % sum.computeCDF(2.0))
def run(self): """ Build the POD models. Notes ----- This method build the polynomial chaos model. First the censored data are filtered if needed. The Box Cox transformation is performed if it is enabled. Then it builds the POD models, the Monte Carlo simulation is performed for each given defect sizes. The confidence interval is computed by simulating new coefficients of the polynomial chaos, then Monte Carlo simulations are performed. """ # run the chaos algorithm and get result if not given if not self._userChaos: if self._verbose: print('Start build polynomial chaos model...') self._algoChaos = self._buildChaosAlgo(self._input, self._signals) self._algoChaos.run() if self._verbose: print('Polynomial chaos model completed') self._chaosResult = self._algoChaos.getResult() # get the metamodel self._chaosPred = self._chaosResult.getMetaModel() # get the basis, coef and transformation, needed for the confidence interval self._chaosCoefs = self._chaosResult.getCoefficients() self._reducedBasis = self._chaosResult.getReducedBasis() self._transformation = self._chaosResult.getTransformation() self._basisFunction = ot.NumericalMathFunction( ot.NumericalMathFunction(self._reducedBasis), self._transformation) # compute the residuals and stderr inputSize = self._input.getSize() basisSize = self._reducedBasis.getSize() self._residuals = self._signals - self._chaosPred( self._input) # residuals self._stderr = np.sqrt( np.sum(np.array(self._residuals)**2) / (inputSize - basisSize - 1)) # Check the quality of the chaos model R2 = self.getR2() Q2 = self.getQ2() if self._verbose: print('Polynomial chaos validation R2 (>0.8) : {:0.4f}'.format(R2)) print('Polynomial chaos validation Q2 (>0.8) : {:0.4f}'.format(Q2)) # Compute the POD values for each defect sizes self.POD = self._computePOD(self._defectSizes, self._chaosCoefs) # create the interpolate function interpModel = interp1d(self._defectSizes, self.POD, kind='linear') self._PODmodel = ot.PythonFunction(1, 1, interpModel) ####################### confidence interval ############################ dof = inputSize - basisSize - 1 varEpsilon = (ot.ChiSquare(dof).inverse() * dof * self._stderr**2).getRealization()[0] gramBasis = ot.Matrix(self._basisFunction(self._input)).computeGram() covMatrix = gramBasis.solveLinearSystem( ot.IdentityMatrix(basisSize)) * varEpsilon self._coefsDist = ot.Normal( np.hstack(self._chaosCoefs), ot.CovarianceMatrix(covMatrix.getImplementation())) coefsRandom = self._coefsDist.getSample(self._simulationSize) self._PODPerDefect = ot.NumericalSample(self._simulationSize, self._defectNumber) for i, coefs in enumerate(coefsRandom): self._PODPerDefect[i, :] = self._computePOD( self._defectSizes, coefs) if self._verbose: updateProgress(i, self._simulationSize, 'Computing POD per defect')
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if ot.ChiSquare().__class__.__name__ == 'Bernoulli': distribution = ot.Bernoulli(0.7) elif ot.ChiSquare().__class__.__name__ == 'Binomial': distribution = ot.Binomial(5, 0.2) elif ot.ChiSquare().__class__.__name__ == 'ComposedDistribution': copula = ot.IndependentCopula(2) marginals = [ot.Uniform(1.0, 2.0), ot.Normal(2.0, 3.0)] distribution = ot.ComposedDistribution(marginals, copula) elif ot.ChiSquare().__class__.__name__ == 'CumulativeDistributionNetwork': coll = [ot.Normal(2), ot.Dirichlet([0.5, 1.0, 1.5])] distribution = ot.CumulativeDistributionNetwork( coll, ot.BipartiteGraph([[0, 1], [0, 1]])) elif ot.ChiSquare().__class__.__name__ == 'Histogram': distribution = ot.Histogram([-1.0, 0.5, 1.0, 2.0], [0.45, 0.4, 0.15]) elif ot.ChiSquare().__class__.__name__ == 'KernelMixture': kernel = ot.Uniform() sample = ot.Normal().getSample(5) bandwith = [1.0] distribution = ot.KernelMixture(kernel, bandwith, sample) elif ot.ChiSquare().__class__.__name__ == 'MaximumDistribution': coll = [ ot.Uniform(2.5, 3.5), ot.LogUniform(1.0, 1.2), ot.Triangular(2.0, 3.0, 4.0) ] distribution = ot.MaximumDistribution(coll) elif ot.ChiSquare().__class__.__name__ == 'Multinomial': distribution = ot.Multinomial(5, [0.2])
print("distribution=", repr(distribution)) print("Estimated distribution=", repr(estimatedDistribution)) estimatedDistribution = factory.build() print("Default distribution=", estimatedDistribution) estimatedHistogram = factory.buildAsHistogram(sample) print("Histogram =", distribution) print("Estimated histogram=", estimatedHistogram) estimatedHistogram = factory.buildAsHistogram(sample, 0.1) print("Histogram =", distribution) print("Estimated histogram=", estimatedHistogram) estimatedHistogram = factory.buildAsHistogram(sample, 15) print("Histogram =", distribution) print("Estimated histogram=", estimatedHistogram) first = -2. width = ot.Point(5, 1.) estimatedHistogram = factory.buildAsHistogram(sample, first, width) print("Estimated histogram=", estimatedHistogram) estimatedHistogram = factory.buildAsHistogram() print("Default histogram=", estimatedHistogram) sample = ot.ChiSquare(0.0120637).getSample(32) for useQuantile in [True, False]: print( 'useQuantile=', useQuantile, ot.Point( 1, ot.HistogramFactory().computeBandwidth(sample, useQuantile))) except: import sys print("t_HistogramFactory_std.py", sys.exc_info()[0], sys.exc_info()[1])