Пример #1
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

covarianceModel = ot.ExponentialModel()
if covarianceModel.getSpatialDimension() == 1:
    scale = covarianceModel.getScale()[0]
    if covarianceModel.isStationary():

        def f(x):
            return [covarianceModel(x)[0, 0]]

        func = ot.PythonFunction(1, 1, f)
        func.setDescription(['$tau$', '$cov$'])
        cov_graph = func.draw(-3.0 * scale, 3.0 * scale, 129)
        fig = plt.figure(figsize=(10, 4))
        plt.suptitle(str(covarianceModel))
        cov_axis = fig.add_subplot(111)
        View(cov_graph, figure=fig, axes=[cov_axis], add_legend=False)
    else:

        def f(x):
            return [covarianceModel([x[0]], [x[1]])[0, 0]]

        func = ot.PythonFunction(2, 1, f)
        func.setDescription(['$s$', '$t$', '$cov$'])
        cov_graph = func.draw([-3.0 * scale] * 2, [3.0 * scale] * 2, [129] * 2)
        fig = plt.figure(figsize=(10, 4))
        plt.suptitle(str(covarianceModel))
        cov_axis = fig.add_subplot(111)
        View(cov_graph, figure=fig, axes=[cov_axis], add_legend=False)
Пример #2
0
test_model(myModel, x1=[0.5, 0.0], x2=[0.5, 0.0])

myDefautModel = ot.ProductCovarianceModel()
print('myDefautModel = ', myDefautModel)
test_model(myDefautModel)

cov1 = ot.AbsoluteExponential([2.0], [3.0])
cov2 = ot.SquaredExponential([2.0], [3.0])
myModel = ot.ProductCovarianceModel([cov1, cov2])
test_model(myModel)

# Collection ==> add covariance models
# Add AbsoluteExponentialModel to the collection
myAbsoluteExponential = ot.AbsoluteExponential([2.0] * inputDimension, [3.0])
mySquaredExponential = ot.SquaredExponential([2.0] * inputDimension, [3.0])
# Add exponentialModel to the collection
amplitude = [4.0, 2.0]
scale = [1.0] * inputDimension
# Define a spatial correlation
spatialCorrelation = ot.CorrelationMatrix(inputDimension)
spatialCorrelation[1, 0] = 0.3
myExponentialModel = ot.ExponentialModel(scale, amplitude, spatialCorrelation)
# Build TensorizedCovarianceModel with scale = [1,..,1]
myModel = ot.TensorizedCovarianceModel(
    [myAbsoluteExponential, mySquaredExponential, myExponentialModel])
test_model(myModel, test_grad=False)
# Define new scale
scale = [2.5, 1.5]
myModel.setScale(scale)
test_model(myModel, test_grad=False)
Пример #3
0
# Create a process X: R^2 --> R^2

# 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 normal process on the mesh
# this process is stationary
# myXproc R^2 --> R
amplitude = [1.0]
scale = [0.2, 0.2]
myCovModel = ot.ExponentialModel(myMesh.getDimension(), amplitude, scale)
myXproc = ot.TemporalNormalProcess(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.NumericalMathFunction(['x1'], ['exp(x1)'])
myDynTransform = ot.SpatialFunction(g, 2)
myXtProcess = ot.CompositeProcess(myDynTransform, myXproc)

myField = myXtProcess.getRealization()
graphMarginal1 = ot.KernelSmoothing().build(myField.getValues()).drawPDF()
graphMarginal1.setTitle("")
graphMarginal1.setXTitle("X")
graphMarginal1.setLegendPosition("")
outputDimension = 1

# Amplitude values
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)
Пример #5
0
### The 1D Mesh :

elems_1D = [99]
mesher_1D = ot.IntervalMesher(elems_1D)
lowerBound_1D = [0]
upperBound_1D = [100]
interval_1D = ot.Interval(lowerBound_1D, upperBound_1D)
mesh_1D = mesher_1D.build(interval_1D)

print('The 1D mesh is\n', mesh_1D, '\n')
print('The 2D mesh is\n', mesh_2D, '\n')

## Now let's define the covariance models of both processes.
## we will for both use exponential models with the same base parameters
### The 1D cova model:
model_1D = ot.ExponentialModel([10], [1])

### The 2D cova model:
model_2D = ot.ExponentialModel([1, 1], [1])

##Now finally let's get our two processes and the ditribution.
### The 1D Gaussian process
process_1D = ot.GaussianProcess(model_1D, mesh_1D)

### The 2D Gaussian process
process_2D = ot.GaussianProcess(model_2D, mesh_2D)

### The normal distribution:
scalar_distribution = ot.Normal()

## Now the we have our processes and distributions, let's first evaluate the function
# Scale vector (input dimension 1)
scale = [4.0]

# spatialCorrelation
spatialCorrelation = ot.CorrelationMatrix(3)
spatialCorrelation[0, 1] = 0.8
spatialCorrelation[0, 2] = 0.6
spatialCorrelation[1, 2] = 0.1

# spatialCovariance
spatialCovariance = ot.CovarianceMatrix(3)
spatialCovariance[0, 0] = 4.0
spatialCovariance[1, 1] = 5.0
spatialCovariance[2, 2] = 6.0
spatialCovariance[0, 1] = 1.2
spatialCovariance[0, 2] = 0.9
spatialCovariance[1, 2] = -0.2

# %%
# Create the covariance model from the amplitude and scale, no spatial correlation
ot.ExponentialModel(scale, amplitude)

# %%
# or from the amplitude, scale and spatialCovariance
ot.ExponentialModel(scale, amplitude, spatialCorrelation)

# %%
# or from the scale and spatialCovariance
ot.ExponentialModel(scale, spatialCovariance)
Пример #7
0
# 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])
Пример #8
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View
if ot.MaternModel().__class__.__name__ == 'ExponentialModel':
    covarianceModel = ot.ExponentialModel([0.5], [5.0])
elif ot.MaternModel().__class__.__name__ == 'GeneralizedExponential':
    covarianceModel = ot.GeneralizedExponential([2.0], [3.0], 1.5)
elif ot.MaternModel().__class__.__name__ == 'ProductCovarianceModel':
    amplitude = [1.0]
    scale1 = [4.0]
    scale2 = [4.0]
    cov1 = ot.ExponentialModel(scale1, amplitude)
    cov2 = ot.ExponentialModel(scale2, amplitude)
    covarianceModel = ot.ProductCovarianceModel([cov1, cov2])
elif ot.MaternModel().__class__.__name__ == 'RankMCovarianceModel':
    variance = [1.0, 2.0]
    basis = ot.LinearBasisFactory().build()
    covarianceModel = ot.RankMCovarianceModel(variance, basis)
else:
    covarianceModel = ot.MaternModel()
title = str(covarianceModel)[:100]
if covarianceModel.getInputDimension() == 1:
    scale = covarianceModel.getScale()[0]
    if covarianceModel.isStationary():

        def f(x):
            return [covarianceModel(x)[0, 0]]

        func = ot.PythonFunction(1, 1, f)
        func.setDescription(['$tau$', '$cov$'])
        cov_graph = func.draw(-3.0 * scale, 3.0 * scale, 129)
Пример #9
0
import openturns as ot
from math import exp
from matplotlib import pyplot as plt
from openturns.viewer import View

N = 512
a = 20.0
# myMesh = ot.IntervalMesher([N]).build(ot.Interval(-a, a))
myMesh = ot.RegularGrid(0.0, 2 * a / N, N + 1)
covarianceModel = ot.ExponentialModel([1.0], [1.0])

myProcess = ot.GaussianProcess(covarianceModel, myMesh)

mySample = myProcess.getSample(1000)

myCovarianceFactory = ot.StationaryCovarianceModelFactory()

myEstimatedModel = myCovarianceFactory.build(mySample)


def f(x):
    res = covarianceModel(x)[0, 0]
    return [res]


func = ot.PythonFunction(1, 1, f)
func.setDescription(['$t$', '$cov$'])


def fEst(X):
    res = myEstimatedModel(X)[0, 0]
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View

# Create a bivariate normal process
myTG = ot.RegularGrid(0.0, 0.01, 100)
myCov = ot.ExponentialModel([3.0], [1.2])
myProcess = ot.GaussianProcess(myCov, myTG)

myTS = myProcess.getRealization()

graph = myTS.drawMarginal(0)

fig = plt.figure(figsize=(8, 4))
plt.suptitle("A time series")
axis = fig.add_subplot(111)
axis.set_xlim(auto=True)

View(graph, figure=fig, axes=[axis], add_legend=True)
Пример #11
0
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(1, amplitude, scale)
myXProcess = ot.TemporalNormalProcess(myCovModel, myGrid)

# Create a trend
fTrend = ot.NumericalMathFunction(["t"], ["1+2*t+t^2"])
fTemp = ot.TrendTransform(fTrend)

# Add the trend to the process and get a field
myYProcess = ot.CompositeProcess(fTemp, myXProcess)
myYField = myYProcess.getRealization()

# Create a TrendFactory
myBasisSequenceFactory = ot.LAR()
myFittingAlgorithm = ot.KFold()
func1 = ot.NumericalMathFunction(["t"], ["1"])
func2 = ot.NumericalMathFunction(["t"], ["t"])
func3 = ot.NumericalMathFunction(["t"], ["t^2"])
myBasis = ot.Basis([func1, func2, func3])

myTrendFactory = ot.TrendFactory(myBasisSequenceFactory, myFittingAlgorithm)

# Estimate the trend
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View
if ot.ExponentialModel().__class__.__name__ == 'ExponentialModel':
    covarianceModel = ot.ExponentialModel([0.5], [5.0])
elif ot.ExponentialModel().__class__.__name__ == 'GeneralizedExponential':
    covarianceModel = ot.GeneralizedExponential([2.0], [3.0], 1.5)
elif ot.ExponentialModel().__class__.__name__ == 'ProductCovarianceModel':
    amplitude = [1.0]
    scale1 = [4.0]
    scale2 = [4.0]
    cov1 = ot.ExponentialModel(scale1, amplitude)
    cov2 = ot.ExponentialModel(scale2, amplitude)
    covarianceModel = ot.ProductCovarianceModel([cov1, cov2])
elif ot.ExponentialModel().__class__.__name__ == 'RankMCovarianceModel':
    variance = [1.0, 2.0]
    basis = ot.LinearBasisFactory().build()
    covarianceModel = ot.RankMCovarianceModel(variance, basis)
else:
    covarianceModel = ot.ExponentialModel()
title = str(covarianceModel)[:100]
if covarianceModel.getInputDimension() == 1:
    scale = covarianceModel.getScale()[0]
    if covarianceModel.isStationary():
        def f(x):
            return [covarianceModel(x)[0, 0]]
        func = ot.PythonFunction(1, 1, f)
        func.setDescription(['$tau$', '$cov$'])
        cov_graph = func.draw(-3.0 * scale, 3.0 * scale, 129)
        cov_graph.setTitle(title)
        fig = plt.figure(figsize=(10, 4))
Пример #13
0
    print('no')

# check that hmat library was found
print('7: HMatrix (hmat-oss)'.ljust(width), end=' ')
try:
    # This is a little bit tricky because HMat 1.0 fails with 1x1 matrices
    ot.ResourceMap.SetAsUnsignedInteger('TemporalNormalProcess-SamplingMethod',
                                        1)
    vertices = [[0.0, 0.0, 0.0]]
    vertices.append([1.0, 0.0, 0.0])
    vertices.append([0.0, 1.0, 0.0])
    vertices.append([0.0, 0.0, 1.0])
    simplices = [[0, 1, 2, 3]]
    # Discard messages from HMat
    ot.Log.Show(0)
    process = ot.TemporalNormalProcess(ot.ExponentialModel(3),
                                       ot.Mesh(vertices, simplices))
    f = process.getRealization()
    print('OK')
except:
    print('no')

# check that nlopt library was found
print('8: optimization (NLopt)'.ljust(width), end=' ')
try:
    problem = ot.OptimizationProblem()
    algo = ot.SLSQP()
    algo.setProblem(problem)
    print('OK')
except:
    print('no')
Пример #14
0
hmat.gemv('N', 1.0, x, 3.0, y)
print('y=', y)


# block assembly
class TestHMatrixTensorRealAssemblyFunction(object):
    def __init__(self, covarianceModel, vertices):
        self.covarianceModel = covarianceModel
        self.vertices = vertices

    def __call__(self, i, j):
        pt1 = self.vertices[i]
        pt2 = self.vertices[j]
        val = self.covarianceModel(pt1, pt2)
        return val


covarianceModel = ot.ExponentialModel([0.1] * 2, [1.0] * 2)
hmat = factory.build(vertices, covarianceModel.getDimension(), True,
                     parameters)
blockAssembly = TestHMatrixTensorRealAssemblyFunction(covarianceModel,
                                                      vertices)
hmat.assembleTensor(blockAssembly, covarianceModel.getDimension(), 'L')
hmatRef = ot.HMatrix(hmat)
hmat.factorize('LLt')
hmatRef.gemm('N', 'T', -1.0, hmat, hmat, 1.0)
if hmatRef.norm() < 1e-10:
    print('norm(A-LLt) < 1e-10')
else:
    print('norm(A-LLt) =', hmatRef.norm())
Пример #15
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View


# Create a bivariate normal process
myTG = ot.RegularGrid(0.0, 0.01, 100)
myCov = ot.ExponentialModel(1, [1.2], [3.0])
myProcess = ot.TemporalNormalProcess(myCov, myTG)

myTS = myProcess.getRealization()

graph = myTS.drawMarginal(0)

fig = plt.figure(figsize=(8, 4))
plt.suptitle("A time series")
axis = fig.add_subplot(111)
axis.set_xlim(auto=True)

View(graph, figure=fig, axes=[axis], add_legend=True)
    lambd = result.getEigenValues()
    KLModes = result.getModesAsProcessSample()
    print("KL modes=", KLModes)
    print("KL eigenvalues=", lambd)
    process = ot.TemporalNormalProcess(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()
    KLModes = result.getModesAsProcessSample()
    print("KL modes=", KLModes)
    print("KL eigenvalues=", lambd)
    process = ot.TemporalNormalProcess(cov2D, 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]))
except:
Пример #17
0
ott.assert_almost_equal(oneDimensionalCovMatrix[1, 1], 2.250000000002, 1e-12,
                        0.0)
ott.assert_almost_equal(isotropicCovMatrix[0, 0], 2.250000000002, 1e-12, 0.0)
ott.assert_almost_equal(isotropicCovMatrix[1, 1], 2.250000000002, 1e-12, 0.0)
ott.assert_almost_equal(oneDimensionalCovMatrix[0, 1], 1.992315565746, 1e-12,
                        0.0)
ott.assert_almost_equal(isotropicCovMatrix[0, 1], 1.992315565746, 1e-12, 0.0)

# Exponential covariance model
inputDimension = 2
scale = [4, 5]
spatialCovariance = ot.CovarianceMatrix(inputDimension)
spatialCovariance[0, 0] = 4
spatialCovariance[1, 1] = 5
spatialCovariance[1, 0] = 1.2
myModel = ot.ExponentialModel(scale, spatialCovariance)
test_model(myModel)
# assert that spatialCovariance is taken into account
checkDiag = spatialCovariance.isDiagonal() == myModel.isDiagonal()
if (not checkDiag):
    raise Exception(
        "isDiagonal differ between spatial covariance & covariance model")
rho = spatialCovariance[1, 0] / sqrt(
    spatialCovariance[0, 0] * spatialCovariance[1, 1])
ott.assert_almost_equal(myModel.getOutputCorrelation()[0, 1], rho, 0, 0,
                        "in ExponentialModel correlation")

# Kronecker covariance model

# rho correlation
scale = [4, 5]
Пример #18
0
# Create a process X: R^2 --> R^2

# 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("")
Пример #19
0
coll = ot.CovarianceModelCollection()
coll.add(ot.AbsoluteExponential(1, 3.0))
coll.add(ot.SquaredExponential(1, 2.0))
myModel = ot.ProductCovarianceModel(coll)
test_model(myModel)

collection = ot.CovarianceModelCollection()
# Collection ==> add covariance models
# Add AbsoluteExponentialModel to the collection
myAbsoluteExponential = ot.AbsoluteExponential(spatialDimension, 3.0)
collection.add(myAbsoluteExponential)
# Add SquaredExponentialModel to the collection
mySquaredExponential = ot.SquaredExponential(spatialDimension, 2.0)
collection.add(mySquaredExponential)
# Add exponentialModel to the collection
amplitude = [4.0, 2.0]
scale = [1.0] * spatialDimension
# Define a spatial correlation
spatialCorrelation = ot.CorrelationMatrix(spatialDimension)
spatialCorrelation[1,0] = 0.3
myExponentialModel = ot.ExponentialModel(spatialDimension, amplitude, scale, spatialCorrelation)
collection.add(myExponentialModel)
# Build TensorizedCovarianceModel with scale = [1,..,1]
myModel = ot.TensorizedCovarianceModel(collection)
test_model(myModel)
# Define new scale
scale = [2.5, 1.5]
myModel.setScale(scale)
test_model(myModel)