def testTensorProductExperiment1(): # Generate a tensorized Gauss-Legendre rule in 2 dimensions. # The first marginal has 3 nodes. # The first marginal has 5 nodes. experiment1 = ot.GaussProductExperiment(ot.Uniform(0.0, 1.0), [3]) experiment2 = ot.GaussProductExperiment(ot.Uniform(0.0, 1.0), [5]) collection = [experiment1, experiment2] multivariateExperiment = ot.TensorProductExperiment(collection) nodes, weights = multivariateExperiment.generateWithWeights() # Sort nodes, weights = sortNodesAndWeights(nodes, weights) nodesExact = [ [0.11270, 0.04691], [0.11270, 0.23076], [0.11270, 0.5], [0.11270, 0.76923], [0.11270, 0.95309], [0.5, 0.04691], [0.5, 0.23076], [0.5, 0.5], [0.5, 0.76923], [0.5, 0.95309], [0.88729, 0.04691], [0.88729, 0.23076], [0.88729, 0.5], [0.88729, 0.76923], [0.88729, 0.95309], ] weightsExact = [ 0.0329065, 0.0664762, 0.0790123, 0.0664762, 0.0329065, 0.0526504, 0.106362, 0.12642, 0.106362, 0.0526504, 0.0329065, 0.0664762, 0.0790123, 0.0664762, 0.0329065, ] rtol = 0.0 atol = 1.e-5 ott.assert_almost_equal(nodes, nodesExact, rtol, atol) ott.assert_almost_equal(weights, weightsExact, rtol, atol) # size = multivariateExperiment.getSize() assert size == 15 # distribution = multivariateExperiment.getDistribution() collection = [ot.Uniform(0.0, 1.0), ot.Uniform(0.0, 1.0)] expected_distribution = ot.BlockIndependentDistribution(collection) assert distribution == expected_distribution
def testTensorProductExperiment2(): # Generate a tensorized Gauss-Legendre rule in 3 dimensions. # Each marginal elementary experiment has 6 nodes. dimension = 3 maximumMarginalLevel = 6 marginalLevels = [maximumMarginalLevel] * dimension collection = [] for i in range(dimension): marginalExperiment = ot.GaussProductExperiment( ot.Uniform(0.0, 1.0), [marginalLevels[i]] ) collection.append(marginalExperiment) multivariateExperiment = ot.TensorProductExperiment(collection) nodes, weights = multivariateExperiment.generateWithWeights() assert nodes.getDimension() == 3 size = nodes.getSize() assert size == weights.getDimension() assert size == maximumMarginalLevel ** dimension
# %% # We see that the number of polynomials is equal to 126. This will lead to the computation of 126 coefficients. # %% # We now set the method used to compute the coefficients; we select the integration method. # # We begin by getting the standard measure associated with the multivariate polynomial basis. We see that the range of the `Beta` distribution has been standardized into the [-1,1] interval. This is the same for the `Uniform` distribution and the second `Beta` distribution. # %% distributionMu = multivariateBasis.getMeasure() distributionMu # %% marginalDegrees = [4] * dim_input experiment = ot.GaussProductExperiment(distributionMu, marginalDegrees) # %% # We can see the size of the associated design of experiments. # %% experiment.generate().getSize() # %% # The choice of the `GaussProductExperiment` rule leads to 256 evaluations of the model. # %% projectionStrategy = ot.IntegrationStrategy(experiment) # %% # We can now create the functional chaos.
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View from math import sqrt domain = ot.Interval(-1.0, 1.0) basis = ot.OrthogonalProductFunctionFactory([ot.FourierSeriesFactory()]) basisSize = 10 experiment = ot.GaussProductExperiment(basis.getMeasure(), [20]) mustScale = False threshold = 0.001 model = ot.AbsoluteExponential([1.0]) algo = ot.KarhunenLoeveQuadratureAlgorithm(domain, domain, model, experiment, basis, basisSize, mustScale, threshold) algo.run() ev = algo.getResult().getEigenValues() functions = algo.getResult().getScaledModes() g = ot.Graph() g.setXTitle("$t$") g.setYTitle("$\sqrt{\lambda_n}\phi_n$") for i in range(functions.getSize()): g.add(functions.build(i).draw(-1.0, 1.0, 256)) g.setColors(ot.Drawable.BuildDefaultPalette(functions.getSize())) fig = plt.figure(figsize=(6, 4)) plt.suptitle("Quadrature approx. of KL expansion for $C(s,t)=e^{-|s-t|}$") axis = fig.add_subplot(111) axis.set_xlim(auto=True) View(g, figure=fig, axes=[axis], add_legend=False)
def __init__(self, strategy, degree, distributions, N_quad=None, sample=None, stieltjes=True, sparse_param={}): """Generate truncature and projection strategies. Allong with the strategies the sample is storred as an attribute. :attr:`sample` as well as corresponding weights: :attr:`weights`. :param str strategy: Least square or Quadrature ['LS', 'Quad', 'SparseLS']. :param int degree: Polynomial degree. :param distributions: Distributions of each input parameter. :type distributions: lst(:class:`openturns.Distribution`) :param array_like sample: Samples for least square (n_samples, n_features). :param bool stieltjes: Wether to use Stieltjes algorithm for the basis. :param dict sparse_param: Parameters for the Sparse Cleaning Truncation Strategy and/or hyperbolic truncation of the initial basis. - **max_considered_terms** (int) -- Maximum Considered Terms, - **most_significant** (int), Most Siginificant number to retain, - **significance_factor** (float), Significance Factor, - **hyper_factor** (float), factor for hyperbolic truncation strategy. """ # distributions self.in_dim = len(distributions) self.dist = ot.ComposedDistribution(distributions) self.sparse_param = sparse_param if 'hyper_factor' in self.sparse_param: enumerateFunction = ot.EnumerateFunction(self.in_dim, self.sparse_param['hyper_factor']) else: enumerateFunction = ot.EnumerateFunction(self.in_dim) if stieltjes: # Tend to result in performance issue self.basis = ot.OrthogonalProductPolynomialFactory( [ot.StandardDistributionPolynomialFactory( ot.AdaptiveStieltjesAlgorithm(marginal)) for marginal in distributions], enumerateFunction) else: self.basis = ot.OrthogonalProductPolynomialFactory( [ot.StandardDistributionPolynomialFactory(margin) for margin in distributions], enumerateFunction) self.n_basis = enumerateFunction.getStrataCumulatedCardinal(degree) # Strategy choice for expansion coefficient determination self.strategy = strategy if self.strategy == 'LS' or self.strategy == 'SparseLS': # least-squares method self.sample = sample else: # integration method # redefinition of sample size # n_samples = (degree + 1) ** self.in_dim # marginal degree definition # by default: the marginal degree for each input random # variable is set to the total polynomial degree 'degree'+1 measure = self.basis.getMeasure() if N_quad is not None: degrees = [int(N_quad ** 0.25)] * self.in_dim else: degrees = [degree + 1] * self.in_dim self.proj_strategy = ot.IntegrationStrategy( ot.GaussProductExperiment(measure, degrees)) self.sample, self.weights = self.proj_strategy.getExperiment().generateWithWeights() if not stieltjes: transformation = ot.Function(ot.MarginalTransformationEvaluation( [measure.getMarginal(i) for i in range(self.in_dim)], distributions, False)) self.sample = transformation(self.sample) self.pc = None self.pc_result = None
============================= """ # %% # In this example we are going to create a deterministic weighted design experiment using Gauss product. # %% import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) # %% # Define the underlying distribution, degrees distribution = ot.ComposedDistribution( [ot.Exponential(), ot.Triangular(-1.0, -0.5, 1.0)]) marginalSizes = [15, 8] # %% # Create the design experiment = ot.GaussProductExperiment(distribution, marginalSizes) sample = experiment.generate() # %% # Plot the design graph = ot.Graph("GP design", "x1", "x2", True, "") cloud = ot.Cloud(sample, "blue", "fsquare", "") graph.add(cloud) view = viewer.View(graph) plt.show()
f, ot.Normal(1.0, 1.0), ot.GreaterOrEqual(), [0.95]), otrobopt.MeanStandardDeviationTradeoffMeasure(f, thetaDist, [0.8]), otrobopt.QuantileMeasure(f, thetaDist, 0.99) ] aggregated = otrobopt.AggregatedMeasure(measures) measures.append(aggregated) for measure in measures: print(measure, '(continuous)', measure(x)) N = 10000 experiment = ot.LHSExperiment(N) factory = otrobopt.MeasureFactory(experiment) discretizedMeasure = factory.build(measure) print(discretizedMeasure, '(discretized LHS)', discretizedMeasure(x)) N = 4 experiment = ot.GaussProductExperiment([N]) factory = otrobopt.MeasureFactory(experiment) discretizedMeasure = factory.build(measure) print(discretizedMeasure, '(discretized Gauss)', discretizedMeasure(x)) # Second test: theta of dimension 2 thetaDist = ot.Normal([2.0] * 2, [0.1] * 2, ot.IdentityMatrix(2)) f_base = ot.SymbolicFunction(['x', 'theta0', 'theta1'], ['x*theta0+theta1']) f = ot.ParametricFunction(f_base, [1, 2], thetaDist.getMean()) x = [1.0] measures = [otrobopt.MeanMeasure(f, thetaDist), otrobopt.VarianceMeasure(f, thetaDist), otrobopt.WorstCaseMeasure( f, ot.ComposedDistribution([ot.Uniform(-1.0, 4.0)] * 2)),
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View ot.RandomGenerator.SetSeed(0) # Generate sample with the given plane distribution = ot.ComposedDistribution( ot.DistributionCollection( [ot.Exponential(), ot.Triangular(-1.0, -0.5, 1.0)])) marginalDegrees = ot.Indices([3, 6]) myPlane = ot.GaussProductExperiment(ot.Distribution(distribution), marginalDegrees) sample = myPlane.generate() # Create an empty graph graph = ot.Graph("", "x1", "x2", True, "") # Create the cloud cloud = ot.Cloud(sample, "blue", "fsquare", "") # Then, draw it graph.add(cloud) fig = plt.figure(figsize=(4, 4)) plt.suptitle("Gauss product experiment") axis = fig.add_subplot(111) axis.set_xlim(auto=True) View(graph, figure=fig, axes=[axis], add_legend=False)
# We compute the coefficients using a multivariate tensor product Gaussian # quadrature rule. Since the coefficients are computed in the standardized # space, we first use the `getMeasure` method of the multivariate basis in # order to get that standardized distribution. Then we use the # :class:`~openturns.GaussProductExperiment` class to create the quadrature, # using 6 nodes on each # of the dimensions. # %% standard_distribution = multivariateBasis.getMeasure() print(standard_distribution) marginal_number_of_nodes = 6 dim_input = im.model.getInputDimension() marginalDegrees = [marginal_number_of_nodes] * dim_input experiment = ot.GaussProductExperiment(standard_distribution, marginalDegrees) print("Sample size = ", experiment.generate().getSize()) # %% # # We see that 216 nodes are involved in this quadrature rule, which is the result # of :math:`6^3 = 216`. # # In the next cell, we compute the coefficients of the polynomial chaos expansion # using integration. # %% projectionStrategy = ot.IntegrationStrategy(experiment) chaosalgo = ot.FunctionalChaosAlgorithm(im.model, im.distributionX, adaptiveStrategy, projectionStrategy) chaosalgo.run()
def testTensorProductExperiment3(): # Experiment 1 : Uniform * 2 with 3 and 2 nodes. marginalSizes1 = [3, 2] dimension1 = len(marginalSizes1) distribution1 = ot.ComposedDistribution([ot.Uniform()] * dimension1) experiment1 = ot.GaussProductExperiment(distribution1, marginalSizes1) # Experiment 2 : Normal * 3 with 2, 2 and 1 nodes. marginalSizes2 = [2, 2, 1] dimension2 = len(marginalSizes2) distribution2 = ot.ComposedDistribution([ot.Normal()] * dimension2) experiment2 = ot.GaussProductExperiment(distribution2, marginalSizes2) # Tensor product collection = [experiment1, experiment2] multivariateExperiment = ot.TensorProductExperiment(collection) nodes, weights = multivariateExperiment.generateWithWeights() # Sort nodes, weights = sortNodesAndWeights(nodes, weights) assert nodes.getDimension() == 5 assert nodes.getSize() == 24 assert weights.getSize() == 24 nodesExact = [ [-0.77459, -0.57735, -1.0, -1.0, 0.0, ], [-0.77459, -0.57735, -1.0, 1.0, 0.0, ], [-0.77459, -0.57735, 1.0, -1.0, 0.0, ], [-0.77459, -0.57735, 1.0, 1.0, 0.0, ], [-0.77459, 0.57735, -1.0, -1.0, 0.0, ], [-0.77459, 0.57735, -1.0, 1.0, 0.0, ], [-0.77459, 0.57735, 1.0, -1.0, 0.0, ], [-0.77459, 0.57735, 1.0, 1.0, 0.0, ], [0.0, -0.57735, -1.0, -1.0, 0.0, ], [0.0, -0.57735, -1.0, 1.0, 0.0, ], [0.0, -0.57735, 1.0, -1.0, 0.0, ], [0.0, -0.57735, 1.0, 1.0, 0.0, ], [0.0, 0.57735, -1.0, -1.0, 0.0, ], [0.0, 0.57735, -1.0, 1.0, 0.0, ], [0.0, 0.57735, 1.0, -1.0, 0.0, ], [0.0, 0.57735, 1.0, 1.0, 0.0, ], [0.77459, -0.57735, -1.0, -1.0, 0.0, ], [0.77459, -0.57735, -1.0, 1.0, 0.0, ], [0.77459, -0.57735, 1.0, -1.0, 0.0, ], [0.77459, -0.57735, 1.0, 1.0, 0.0, ], [0.77459, 0.57735, -1.0, -1.0, 0.0, ], [0.77459, 0.57735, -1.0, 1.0, 0.0, ], [0.77459, 0.57735, 1.0, -1.0, 0.0, ], [0.77459, 0.57735, 1.0, 1.0, 0.0, ], ] weightsExact = [ 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0555556, 0.0555556, 0.0555556, 0.0555556, 0.0555556, 0.0555556, 0.0555556, 0.0555556, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, 0.0347222, ] rtol = 0.0 atol = 1.e-5 ott.assert_almost_equal(nodes, nodesExact, rtol, atol) ott.assert_almost_equal(weights, weightsExact, rtol, atol)
import openturns as ot from openturns.viewer import View # GaussProduct d = ot.GaussProductExperiment(ot.ComposedDistribution([ot.Uniform()] * 3), [4, 6, 8]) s = d.generate() s.setDescription(["X1", "X2", "X3"]) g = ot.Graph() g.setTitle("Gauss product experiment") g.setGridColor("black") p = ot.Pairs(s) g.add(p) View(g)
# %% fittingAlgorithm = ot.CorrectedLeaveOneOut() # Finally the metamodel selection algorithm embbeded in LeastSquaresStrategy approximationAlgorithm = ot.LeastSquaresMetaModelSelectionFactory( basisSequenceFactory, fittingAlgorithm) evaluationCoeffStrategy_2 = ot.LeastSquaresStrategy( ot.MonteCarloExperiment(sampleSize), approximationAlgorithm) # %% # Try integration. # %% marginalSizes = [2] * inputDimension evaluationCoeffStrategy_3 = ot.IntegrationStrategy( ot.GaussProductExperiment(distributionStandard, marginalSizes)) # %% # STEP 4: Creation of the Functional Chaos Algorithm # -------------------------------------------------- # # The `FunctionalChaosAlgorithm` class combines # # * the model : `model` # * the distribution of the input random vector : `distribution` # * the truncature strategy of the multivariate basis # * and the evaluation strategy of the coefficients # %% polynomialChaosAlgorithm = ot.FunctionalChaosAlgorithm( model, distribution, truncatureBasisStrategy, evaluationCoeffStrategy)
#! /usr/bin/env python import openturns as ot ot.TESTPREAMBLE() # Test default constructor print("experiment0=", repr(ot.GaussProductExperiment().generate())) distribution = ot.ComposedDistribution( [ot.Exponential(), ot.Triangular(-1.0, -0.5, 1.0)]) marginalSizes = [3, 6] # Test the constructor based on marginal degrees print("experiment1=", ot.GaussProductExperiment(marginalSizes)) # Test the constructor based on distribution print("experiment2=", ot.GaussProductExperiment(distribution)) # Test the constructor based on marginal degrees and distribution experiment = ot.GaussProductExperiment(distribution, marginalSizes) print("experiment = ", experiment) sample, weights = experiment.generateWithWeights() print("sample = ", repr(sample)) print("weights = ", repr(weights))
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View ot.RandomGenerator.SetSeed(0) experiment1 = ot.GaussProductExperiment(ot.Uniform(0.0, 1.0), [3]) experiment2 = ot.GaussProductExperiment(ot.Uniform(0.0, 1.0), [5]) collection = [experiment1, experiment2] experiment = ot.TensorProductExperiment(collection) sample = experiment.generate() # Create an empty graph graph = ot.Graph("Tensor product Gauss experiment", "x1", "x2", True, "") # Create the cloud cloud = ot.Cloud(sample, "blue", "fsquare", "") # Then, draw it graph.add(cloud) fig = plt.figure(figsize=(4, 4)) axis = fig.add_subplot(111) axis.set_xlim(auto=True) View(graph, figure=fig, axes=[axis], add_legend=False)