def test_SquaredExponential(self): # With 2 principal components setup_HDRenv() # Test with no outlier in the band xmin = 0.0 step = 0.1 n = 100 timeGrid = ot.RegularGrid(xmin, step, n + 1) amplitude = [7.0] scale = [1.5] covarianceModel = ot.SquaredExponential(scale, amplitude) process = ot.GaussianProcess(covarianceModel, timeGrid) nbTrajectories = 50 processSample = process.getSample(nbTrajectories) # KL decomposition reduction = othdr.KarhunenLoeveDimensionReductionAlgorithm( processSample, 2) reduction.run() reducedComponents = reduction.getReducedComponents() # Distribution fit in reduced space ks = ot.KernelSmoothing() reducedDistribution = ks.build(reducedComponents) hdr = othdr.ProcessHighDensityRegionAlgorithm(processSample, reducedComponents, reducedDistribution, [0.95, 0.5]) hdr.run() graph = hdr.draw() otv.View(graph)
def test_NonZeroMean(self): # Create the KL result numberOfVertices = 10 interval = ot.Interval(-1.0, 1.0) mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval) covariance = ot.SquaredExponential() zeroProcess = ot.GaussianProcess(covariance, mesh) # Define a trend function f = ot.SymbolicFunction(["t"], ["30 * t"]) fTrend = ot.TrendTransform(f, mesh) # Add it to the process process = ot.CompositeProcess(fTrend, zeroProcess) # Sample sampleSize = 100 processSample = process.getSample(sampleSize) threshold = 0.0 algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold) algo.run() klresult = algo.getResult() # Create the KL reduction meanField = processSample.computeMean() klreduce = ot.KarhunenLoeveReduction(klresult) # Generate a trajectory and reduce it field = process.getRealization() values = field.getValues() reducedValues = klreduce(values) ott.assert_almost_equal(values, reducedValues)
def test_KarhunenLoeveValidationMultidimensional(self): # Create the KL result numberOfVertices = 20 interval = ot.Interval(-1.0, 1.0) mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval) outputDimension = 2 univariateCovariance = ot.SquaredExponential() covarianceCollection = [univariateCovariance] * outputDimension multivariateCovariance = ot.TensorizedCovarianceModel( covarianceCollection) process = ot.GaussianProcess(multivariateCovariance, mesh) sampleSize = 100 sampleSize = 10 processSample = process.getSample(sampleSize) threshold = 1.0e-7 algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold) algo.run() klresult = algo.getResult() # Create the validation validation = ot.KarhunenLoeveValidation(processSample, klresult) # Check residuals residualProcessSample = validation.computeResidual() assert (type(residualProcessSample) is ot.ProcessSample) # Check standard deviation residualSigmaField = validation.computeResidualStandardDeviation() zeroSample = ot.Sample(numberOfVertices, outputDimension) ott.assert_almost_equal(residualSigmaField, zeroSample) # Check graph graph = validation.drawValidation() if False: from openturns.viewer import View View(graph).save('validation2.png')
def plotCovarianceModel(myCovarianceModel, myTimeGrid, nbTrajectories): '''Plots the given number of trajectories with given covariance model.''' process = ot.GaussianProcess(myCovarianceModel, myTimeGrid) sample = process.getSample(nbTrajectories) graph = sample.drawMarginal(0) graph.setTitle("") return graph
def test_KarhunenLoeveValidation(self): # Create the KL result numberOfVertices = 20 interval = ot.Interval(-1.0, 1.0) mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval) covariance = ot.SquaredExponential() process = ot.GaussianProcess(covariance, mesh) sampleSize = 100 processSample = process.getSample(sampleSize) threshold = 1.0e-7 algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold) algo.run() klresult = algo.getResult() # Create validation validation = ot.KarhunenLoeveValidation(processSample, klresult) # Check residuals residualProcessSample = validation.computeResidual() assert (type(residualProcessSample) is ot.ProcessSample) # Check standard deviation residualSigmaField = validation.computeResidualStandardDeviation() exact = ot.Sample(numberOfVertices, 1) #ott.assert_almost_equal(residualSigmaField, exact) # Check mean residualMean = validation.computeResidualMean() exact = ot.Sample(numberOfVertices, 1) #ott.assert_almost_equal(residualMean, exact) # Check graph graph0 = validation.drawValidation() graph1 = residualProcessSample.drawMarginal(0) graph2 = residualMean.drawMarginal(0) graph3 = residualSigmaField.drawMarginal(0) graph4 = validation.drawObservationWeight(0) graph5 = validation.drawObservationQuality() if 0: from openturns.viewer import View View(graph0).save('validation1.png') View(graph1).save('validation1-residual.png') View(graph2).save('validation1-residual-mean.png') View(graph3).save('validation1-residual-stddev.png') View(graph4).save('validation1-indiv-weight.png') View(graph5).save('validation1-indiv-quality.png')
def test_ZeroMean(self): # Create the KL result numberOfVertices = 10 interval = ot.Interval(-1.0, 1.0) mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval) covariance = ot.SquaredExponential() process = ot.GaussianProcess(covariance, mesh) sampleSize = 10 processSample = process.getSample(sampleSize) threshold = 0.0 algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold) algo.run() klresult = algo.getResult() # Create the KL reduction meanField = processSample.computeMean() klreduce = ot.KarhunenLoeveReduction(klresult) # Generate a trajectory and reduce it field = process.getRealization() values = field.getValues() reducedValues = klreduce(values) ott.assert_almost_equal(values, reducedValues)
def test_trend(self): N = 100 M = 1000 P = 10 mean = ot.SymbolicFunction("x", "sign(x)") cov = ot.SquaredExponential([1.0], [0.1]) mesh = ot.IntervalMesher([N]).build(ot.Interval(-2.0, 2.0)) process = ot.GaussianProcess(ot.TrendTransform(mean, mesh), cov, mesh) sample = process.getSample(M) algo = ot.KarhunenLoeveSVDAlgorithm(sample, 1e-6) algo.run() result = algo.getResult() trend = ot.TrendTransform( ot.P1LagrangeEvaluation(sample.computeMean()), mesh) sample2 = process.getSample(P) sample2.setName('reduction of sign(x) w/o trend') reduced1 = ot.KarhunenLoeveReduction(result)(sample2) reduced2 = ot.KarhunenLoeveReduction(result, trend)(sample2) g = sample2.drawMarginal(0) g.setColors(["red"]) g1 = reduced1.drawMarginal(0) g1.setColors(["blue"]) drs = g1.getDrawables() for i, d in enumerate(drs): d.setLineStyle("dashed") drs[i] = d g1.setDrawables(drs) g.add(g1) g2 = reduced2.drawMarginal(0) g2.setColors(["green"]) drs = g2.getDrawables() for i, d in enumerate(drs): d.setLineStyle("dotted") drs[i] = d g2.setDrawables(drs) g.add(g2) if 0: from openturns.viewer import View View(g).save('reduction.png')
# %% # Input model print("Create the input process") # Domain bound a = 1 # Reference correlation length b = 0.5 # Number of vertices in the mesh N = 100 # Bandwidth of the smoothers h = 0.05 mesh = ot.IntervalMesher([N - 1]).build(ot.Interval(-a, a)) covariance_X = ot.AbsoluteExponential([b]) process_X = ot.GaussianProcess(covariance_X, mesh) # %% # for some pretty graphs 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$')
# which mesh is of box of dimension 2 myIndices = ot.Indices([80, 40]) myMesher = ot.IntervalMesher(myIndices) lowerBound = [0., 0.] upperBound = [2., 1.] myInterval = ot.Interval(lowerBound, upperBound) myMesh = myMesher.build(myInterval) # Define a bidimensional temporal Gaussian process on the mesh # with independent components amplitude = [1.0, 1.0] scale = [0.2, 0.3] myCovModel = ot.ExponentialModel(scale, amplitude) myXtProcess_temp = ot.GaussianProcess(myCovModel, myMesh) # Non linear transformation of myXtProcess # to get a positive process g2 = ot.SymbolicFunction(['x1', 'x2'], ['x1^2', 'abs(x2)']) myDynTransform = ot.ValueFunction(g2, 2) myXtProcess = ot.CompositeProcess(myDynTransform, myXtProcess_temp) # Create the image Y myYtProcess = ot.CompositeProcess(myDynFunc, myXtProcess) # Get the antecedent : myXtProcess print('My antecedent process = ', myYtProcess.getAntecedent()) # Get the dynamical function # which performs the transformation
# Set Numerical precision to 4 ot.PlatformInfo.SetNumericalPrecision(4) sampleSize = 40 inputDimension = 1 # Create the function to estimate model = ot.SymbolicFunction(["x0"], ["x0"]) X = ot.Sample(sampleSize, inputDimension) for i in range(sampleSize): X[i, 0] = 3.0 + (8.0 * i) / sampleSize Y = model(X) # Add a small noise to data Y += ot.GaussianProcess(ot.AbsoluteExponential([0.1], [0.2]), ot.Mesh(X)).getRealization().getValues() basis = ot.LinearBasisFactory(inputDimension).build() # Case of a misspecified covariance model covarianceModel = ot.DiracCovarianceModel(inputDimension) print("===================================================\n") algo = ot.GeneralLinearModelAlgorithm(X, Y, covarianceModel, basis) algo.run() result = algo.getResult() print("\ncovariance (dirac, optimized)=", result.getCovarianceModel()) print("trend (dirac, optimized)=", result.getTrendCoefficients()) print("===================================================\n") # Now without estimating covariance parameters basis = ot.LinearBasisFactory(inputDimension).build()
from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) # %% # Create a time grid tMin = 0.0 timeStep = 0.1 n = 100 tgrid = ot.RegularGrid(tMin, timeStep, n) # %% # Create a normal process amplitude = [5.0] scale = [3.0] model = ot.ExponentialModel(scale, amplitude) process = ot.GaussianProcess(model, tgrid) # %% # Create the 1-d domain A: [2.,5.] lowerBound = [2.0] upperBound = [5.0] domain = ot.Interval(lowerBound, upperBound) # %% # Create an event from a Process and a Domain event = ot.ProcessEvent(process, domain) # %% # Create the Monte-Carlo algorithm montecarlo = ot.ProbabilitySimulationAlgorithm(event)
# # %% 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 Gaussian process numberOfVertices = 20 interval = ot.Interval(-1.0, 1.0) mesh = ot.IntervalMesher([numberOfVertices - 1]).build(interval) covariance = ot.SquaredExponential() process = ot.GaussianProcess(covariance, mesh) # %% # decompose it using KL-SVD sampleSize = 100 processSample = process.getSample(sampleSize) threshold = 1.0e-7 algo = ot.KarhunenLoeveSVDAlgorithm(processSample, threshold) algo.run() klresult = algo.getResult() # %% # Instanciate the validation service validation = ot.KarhunenLoeveValidation(processSample, klresult) # %%
def _exec(self, X): f = ot.Function( ot.PiecewiseLinearEvaluation( [x[0] for x in self.getInputMesh().getVertices()], X)) outputValues = ot.Sample(0, 1) for t in self.getOutputMesh().getVertices(): kernel = ot.Normal(t[0], 0.05) def pdf(X): return [kernel.computePDF(X)] weight = ot.Function(ot.PythonFunction(1, 1, pdf)) outputValues.add( self.algo_.integrate(weight * f, kernel.getRange())) return outputValues N = 5 X = ot.GaussianProcess(ot.GeneralizedExponential([0.1], 1.0), mesh) f = ot.FieldFunction(GaussianConvolution()) Y = ot.CompositeProcess(f, X) x_graph = X.getSample(N).drawMarginal(0) y_graph = Y.getSample(N).drawMarginal(0) fig = plt.figure(figsize=(10, 4)) plt.suptitle("Composite process") x_axis = fig.add_subplot(121) y_axis = fig.add_subplot(122) View(x_graph, figure=fig, axes=[x_axis], add_legend=False) View(y_graph, figure=fig, axes=[y_axis], add_legend=False)
amplitude = [1.0, 2.0, 3.0] # %% # We define a spatial correlation : spatialCorrelation = ot.CorrelationMatrix(3) spatialCorrelation[0, 1] = 0.8 spatialCorrelation[0, 2] = 0.6 spatialCorrelation[1, 2] = 0.1 # %% # The covariance model is now created with : myCovarianceModel = ot.ExponentialModel(scale, amplitude, spatialCorrelation) # %% # Eventually, the process is built with : process = ot.GaussianProcess(myCovarianceModel, time_grid) # %% # The dimension d of the process may be retrieved by dim = process.getOutputDimension() print("Dimension : %d" % dim) # %% # The underlying mesh of the process is obtained with the `getMesh` method : mesh = process.getMesh() # %% # We have access to peculiar data of the mesh such as the corners : minMesh = mesh.getVertices().getMin()[0] maxMesh = mesh.getVertices().getMax()[0]
# # %% import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt import math as m ot.Log.Show(ot.Log.NONE) # %% # Create a process grid = ot.RegularGrid(0.0, 0.1, 10) amplitude = [5.0] scale = [0.2] covModel = ot.ExponentialModel(scale, amplitude) X = ot.GaussianProcess(covModel, grid) # %% # Draw a sample sample = X.getSample(6) sample.setName('X') graph = sample.drawMarginal(0) view = viewer.View(graph) # %% # Define a trend function f = ot.SymbolicFunction(['t'], ['30*t']) fTrend = ot.TrendTransform(f, grid) # %% # Add it to the process
tmax = myMesh.getEnd() # Create the collection of HermitianMatrix covariance = ot.CovarianceMatrix(N) for k in range(N): s = myMesh.getValue(k) for l in range(k + 1): t = myMesh.getValue(l) covariance[k, l] = C(s, t) # Create the covariance model myCovarianceModel = ot.UserDefinedCovarianceModel(myMesh, covariance) # Create the non stationary Gaussian process with # that covariance model myProcess = ot.GaussianProcess(myCovarianceModel, myMesh) # Create a sample of fields size = 10**4 myFieldSample = myProcess.getSample(size) # Build a covariance model factory myFactory = ot.NonStationaryCovarianceModelFactory() # Estimation on a the ProcessSample myEstimatedModel = myFactory.build(myFieldSample) # Define the python function associated to myCovarianceModel def covMod(X):
# Sample [int64] indexing s0 = ot.Sample(5, 3) idx = np.array([1, 3, 4]) print('sample[[int64]]:', s0[idx]) s0[idx] = ot.Normal(3).getSample(3) print('sample[[int64]]=Sample:', s0) # generic int64 indexing s0 = ot.Description(5, 'aa') idx = np.int64(2) print('Description[int64]:', s0[idx]) s0[idx] = 'zou' print('Description[int64]=str', s0[idx]) # generic [int64] indexing s0 = ot.Description(5, 'aa') idx = np.array([1, 3, 4]) print('Description[[int64]]:', s0[idx]) s0[idx] = ['zou'] * 3 print('Description[[int64]]=str', s0[idx]) # Field int64 indexing mesher = ot.IntervalMesher([10, 5]) mesh = mesher.build(ot.Interval([0.0, 0.0], [2.0, 1.0])) process = ot.GaussianProcess(ot.ExponentialModel([0.2] * 2, [1.0]), mesh) field = process.getRealization() idx = np.int64(2) print('Field[int64]', field[idx]) field[idx] = [6.0] print('Field[int64]=Point', field[idx])
amplitude = [1.0] * outputDimension # Scale values scale = [1.0] * inputDimension tmin = 0.0 step = 0.1 n = 11 myTimeGrid = ot.RegularGrid(tmin, step, n) size = 25 # Second order model with parameters myCovModel = ot.ExponentialModel(scale, amplitude) print("myCovModel = ", myCovModel) myProcess1 = ot.GaussianProcess(myCovModel, myTimeGrid) print("myProcess1 = ", myProcess1) print("is stationary? ", myProcess1.isStationary()) myProcess1.setSamplingMethod(ot.GaussianProcess.CHOLESKY) print("mean over ", size, " realizations = ", myProcess1.getSample(size).computeMean()) myProcess1.setSamplingMethod(ot.GaussianProcess.GIBBS) print("mean over ", size, " realizations = ", myProcess1.getSample(size).computeMean()) # With constant trend trend = ot.TrendTransform(ot.SymbolicFunction("t", "4.0"), myTimeGrid) myProcess2 = ot.GaussianProcess(trend, myCovModel, myTimeGrid) myProcess2.setSamplingMethod(ot.GaussianProcess.GIBBS) print("myProcess2 = ", myProcess2) print("is stationary? ", myProcess2.isStationary())
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View # Create a bivariate Gaussian process myMesh = ot.IntervalMesher([39, 39]).build(ot.Interval([0.0] * 2, [1.0] * 2)) myCov = ot.GeneralizedExponential(2 * [0.1], 1.3) myProcess = ot.GaussianProcess(myCov, myMesh) myField = myProcess.getRealization() graph = myField.drawMarginal(0, False) fig = plt.figure(figsize=(8, 4)) plt.suptitle("A field") axis = fig.add_subplot(111) axis.set_xlim(auto=True) View(graph, figure=fig, axes=[axis], add_legend=True)
ot.Log.Show(ot.Log.NONE) # %% # define a covariance model defaultDimension = 1 # Amplitude values amplitude = [1.0] * defaultDimension # Scale values scale = [1.0] * defaultDimension # Covariance model myModel = ot.AbsoluteExponential(scale, amplitude) # %% # define a mesh tmin = 0.0 step = 0.1 n = 11 myTimeGrid = ot.RegularGrid(tmin, step, n) # %% # create the process process = ot.GaussianProcess(myModel, myTimeGrid) print(process) # %% # draw a sample sample = process.getSample(6) graph = sample.drawMarginal(0) view = viewer.View(graph) plt.show()
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View # Create a process on a regular grid myGrid = ot.RegularGrid(0.0, 0.1, 100) amplitude = [5.0] scale = [0.2] myCovModel = ot.ExponentialModel(scale, amplitude) myXProcess = ot.GaussianProcess(myCovModel, myGrid) # Create a trend fTrend = ot.SymbolicFunction(["t"], ["1+2*t+t^2"]) fTemp = ot.TrendTransform(fTrend, myGrid) # Add the trend to the process and get a field myYProcess = ot.CompositeProcess(fTemp, myXProcess) myYField = myYProcess.getRealization() # Create a TrendFactory myBasisSequenceFactory = ot.LARS() myFittingAlgorithm = ot.KFold() func1 = ot.SymbolicFunction(["t"], ["1"]) func2 = ot.SymbolicFunction(["t"], ["t"]) func3 = ot.SymbolicFunction(["t"], ["t^2"]) myBasis = ot.Basis([func1, func2, func3]) myTrendFactory = ot.TrendFactory(myBasisSequenceFactory, myFittingAlgorithm) # Estimate the trend
# %% # Define a 2-d mesh indices = ot.Indices([40, 20]) mesher = ot.IntervalMesher(indices) lowerBound = [0., 0.] upperBound = [2., 1.] interval = ot.Interval(lowerBound, upperBound) mesh = mesher.build(interval) # %% # Create the covariance model amplitude = [1.0, 2.0, 3.0] scale = [4.0, 5.0] spatialCorrelation = ot.CorrelationMatrix(3) spatialCorrelation[0, 1] = 0.8 spatialCorrelation[0, 2] = 0.6 spatialCorrelation[1, 2] = 0.1 covmodel = ot.ExponentialModel(scale, amplitude, spatialCorrelation) # Create a normal process process = ot.GaussianProcess(covmodel, mesh) # %% # Create a domain A in R^3: [0.8; 1.2]*[1.5; 1.6]*[0.5; 0.7] lowerBound = [0.8, 1.5, 0.5] upperBound = [1.2, 1.6, 0.7] domain = ot.Interval(lowerBound, upperBound) # Create the event event = ot.ProcessEvent(process, domain)
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View from math import sqrt mesh = ot.IntervalMesher([128]).build(ot.Interval(-1.0, 1.0)) threshold = 0.001 model = ot.AbsoluteExponential([1.0]) sample = ot.GaussianProcess(model, mesh).getSample(100) algo = ot.KarhunenLoeveSVDAlgorithm(sample, threshold) algo.run() ev = algo.getResult().getEigenValues() modes = algo.getResult().getScaledModesAsProcessSample() g = modes.drawMarginal(0) g.setXTitle("$t$") g.setYTitle("$\sqrt{\lambda_n}\phi_n$") fig = plt.figure(figsize=(6, 4)) plt.suptitle("SVD 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)
#! /usr/bin/env python from __future__ import print_function import openturns as ot mesh = ot.IntervalMesher([9]).build(ot.Interval(-1.0, 1.0)) cov1D = ot.AbsoluteExponential([1.0]) algo = ot.KarhunenLoeveP1Algorithm(mesh, cov1D, 0.0) algo.run() result = algo.getResult() lambd = result.getEigenvalues() KLModes = result.getModesAsProcessSample() print("KL modes=", KLModes) print("KL eigenvalues=", lambd) process = ot.GaussianProcess(cov1D, KLModes.getMesh()) coefficients = result.project(process.getSample(10)) print("KL coefficients=", coefficients) KLFunctions = result.getModes() print("KL functions=", KLFunctions) print("KL lift=", result.lift(coefficients[0])) print("KL lift as field=", result.liftAsField(coefficients[0])) R = ot.CorrelationMatrix(2) R[0, 1] = 0.5 scale = [1.0] amplitude = [1.0, 2.0] cov2D = ot.ExponentialModel(scale, amplitude, R) algo = ot.KarhunenLoeveP1Algorithm(mesh, cov2D, 0.0) algo.run() result = algo.getResult() lambd = result.getEigenvalues()
import openturns as ot from matplotlib import pyplot as plt from openturns.viewer import View if ot.WhiteNoise().__class__.__name__ == 'Process': # default to Gaussian for the interface class process = ot.GaussianProcess() elif ot.WhiteNoise().__class__.__name__ == 'DiscreteMarkovChain': process = ot.WhiteNoise() process.setTransitionMatrix(ot.SquareMatrix([[0.0,0.5,0.5],[0.7,0.0,0.3],[0.8,0.0,0.2]])) origin = 0 process.setOrigin(origin) else: process = ot.WhiteNoise() process.setTimeGrid(ot.RegularGrid(0.0, 0.02, 50)) process.setDescription(['$x$']) sample = process.getSample(6) sample_graph = sample.drawMarginal(0) sample_graph.setTitle(str(process)) fig = plt.figure(figsize=(10, 4)) sample_axis = fig.add_subplot(111) View(sample_graph, figure=fig, axes=[sample_axis], add_legend=False)
amplitude = [1.0] * dimension scale = [1] * dimension covarianceModel = ot.GeneralizedExponential(scale, amplitude, 2) # %% # We define the time grid on which we want to sample the Gaussian process. # %% tmin = 0.0 step = 0.01 n = 10001 timeGrid = ot.RegularGrid(tmin, step, n) # %% # Finally we define the Gaussian process. process = ot.GaussianProcess(covarianceModel, timeGrid) print(process) # %% # Basics on the HMatrix algebra # ----------------------------- # # The `HMatrix` framework uses efficient linear algebra techniques to speed-up the # (Cholesky) factorization of the covariance matrix. # This method can be tuned with several parameters. We should concentrate on the easiest ones. # %% # We set the sampling method to `HMAT` (default is the classical/dense case). process.setSamplingMethod(ot.GaussianProcess.HMAT) # %%
domain = ot.Interval(-1.0, 1.0) basis = ot.OrthogonalProductPolynomialFactory([ot.LegendreFactory()]) basisSize = 5 experiment = ot.LHSExperiment(basis.getMeasure(), 100) mustScale = False threshold = 0.0001 model = ot.AbsoluteExponential([1.0]) algo = ot.KarhunenLoeveQuadratureAlgorithm( domain, model, experiment, basis, basisSize, mustScale, threshold) algo.run() result = algo.getResult() lambd = result.getEigenValues() KLModes = result.getModesAsProcessSample() print("KL modes=", KLModes) print("KL eigenvalues=", lambd) process = ot.GaussianProcess(model, KLModes.getMesh()) sample = process.getSample(10) coefficients = result.project(sample) print("KL coefficients=", coefficients) KLFunctions = result.getModes() print("KL functions=", KLFunctions) print("KL lift=", result.lift(coefficients[0])) print("KL lift as field=", result.liftAsField(coefficients[0])) # Now using Legendre/Gauss quadrature marginalDegree = 5 algo = ot.KarhunenLoeveQuadratureAlgorithm( domain, model, marginalDegree, threshold) algo.run() result = algo.getResult() lambd = result.getEigenValues() KLModes = result.getScaledModesAsProcessSample()
#! /usr/bin/env python from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() mesh = ot.IntervalMesher([9]).build(ot.Interval(-1.0, 1.0)) # 1D mesh, 1D covariance, uniform weight, automatic centering, more samples # than vertices cov1D = ot.AbsoluteExponential([1.0]) sample = ot.GaussianProcess(cov1D, mesh).getSample(16) algo = ot.KarhunenLoeveSVDAlgorithm(sample, 0.0) algo.run() result = algo.getResult() lambd = result.getEigenvalues() KLModes = result.getModesAsProcessSample() print("KL modes=", KLModes) print("KL eigenvalues=", lambd) coefficients = result.project(sample) print("KL coefficients=", coefficients) KLFunctions = result.getModes() print("KL functions=", KLFunctions) print("KL lift=", result.lift(coefficients[0])) print("KL lift as field=", result.liftAsField(coefficients[0])) # 1D mesh, 1D covariance, uniform weight, automatic centering sample = ot.GaussianProcess(cov1D, mesh).getSample(6) algo = ot.KarhunenLoeveSVDAlgorithm(sample, 0.0) algo.run() result = algo.getResult() lambd = result.getEigenvalues()
# Define a bi dimensional mesh as a box myIndices = ot.Indices([40, 20]) myMesher = ot.IntervalMesher(myIndices) lowerBound = [0.0, 0.0] upperBound = [2.0, 1.0] myInterval = ot.Interval(lowerBound, upperBound) myMesh = myMesher.build(myInterval) # Define a scalar temporal Gaussian process on the mesh # this process is stationary # myXproc R^2 --> R amplitude = [1.0] scale = [0.2, 0.2] myCovModel = ot.ExponentialModel(scale, amplitude) myXproc = ot.GaussianProcess(myCovModel, myMesh) # Transform myXproc to make its variance depend on the vertex (s,t) # and to get a positive process # 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("")
# %% import openturns as ot from openturns.viewer import View # %% # First build a process to generate the input data. # We assemble a 4-d process from functional and Gaussian processes. T = 3.0 NT = 32 tg = ot.RegularGrid(0.0, T / NT, NT) f1 = ot.SymbolicFunction(['t'], ['sin(t)']) f2 = ot.SymbolicFunction(['t'], ['cos(t)^2']) coeff1_dist = ot.Normal([1.0] * 2, [0.6] * 2, ot.CorrelationMatrix(2)) p1 = ot.FunctionalBasisProcess(coeff1_dist, ot.Basis([f1, f2]), tg) p2 = ot.GaussianProcess(ot.SquaredExponential([1.0], [T / 4.0]), tg) coeff3_dist = ot.ComposedDistribution([ot.Uniform(), ot.Normal()]) f1 = ot.SymbolicFunction(["t"], ["1", "0"]) f2 = ot.SymbolicFunction(["t"], ["0", "1"]) p3 = ot.FunctionalBasisProcess(coeff3_dist, ot.Basis([f1, f2])) X = ot.AggregatedProcess([p1, p2, p3]) X.setMesh(tg) # %% # Draw some input trajectories from our process ot.RandomGenerator.SetSeed(0) x = X.getSample(10) graph = x.drawMarginal(0) graph.setTitle(f'{x.getSize()} input trajectories') _ = View(graph)