1#! /usr/bin/env python
2
3from __future__ import print_function
4import openturns as ot
5
6ot.ResourceMap.SetAsScalar(
7    "LinearCombinationEvaluation-SmallCoefficient", 1.0e-10)
8domain = ot.Interval(-1.0, 1.0)
9basis = ot.OrthogonalProductPolynomialFactory([ot.LegendreFactory()])
10basisSize = 5
11functions = [basis.build(i) for i in range(basisSize)]
12experiment = ot.LHSExperiment(basis.getMeasure(), 100)
13mustScale = False
14threshold = 0.0001
15model = ot.AbsoluteExponential([1.0])
16algo = ot.KarhunenLoeveQuadratureAlgorithm(
17    domain, domain, model, experiment, functions, mustScale, threshold)
18algo.run()
19result = algo.getResult()
20lambd = result.getEigenvalues()
21KLModes = result.getModesAsProcessSample()
22print("KL modes=", KLModes)
23print("KL eigenvalues=", lambd)
24process = ot.GaussianProcess(model, KLModes.getMesh())
25sample = process.getSample(10)
26coefficients = result.project(sample)
27print("KL coefficients=", coefficients)
28KLFunctions = result.getModes()
29print("KL functions=", KLFunctions)
30print("KL lift=", result.lift(coefficients[0]))
31print("KL lift as field=", result.liftAsField(coefficients[0]))
32# Now using Legendre/Gauss quadrature
33marginalDegree = 5
34algo = ot.KarhunenLoeveQuadratureAlgorithm(
35    domain, domain, model, marginalDegree, threshold)
36algo.run()
37result = algo.getResult()
38lambd = result.getEigenvalues()
39KLModes = result.getScaledModesAsProcessSample()
40# Due to symmetry many results can have a sign switch depending on the CPU/compiler/BLAS used
41# print("KL modes=", KLModes)
42print("KL eigenvalues=", lambd)
43coefficients = result.project(sample)
44# print("KL coefficients=", coefficients)
45KLFunctions = result.getModes()
46# print("KL functions=", KLFunctions)
47lifted = result.lift(coefficients[0])
48# print("KL lift=", lifted)
49liftedAsField = result.liftAsField(coefficients[0])
50# print("KL lift as field=", liftedAsField)
51