l = 10

b = 0.01

mu_R = 5.0
sigma_R = 0.3
R = ot.Normal(mu_R, sigma_R)

covariance = ot.SquaredExponential([l / sqrt(2)], [sigma_S])

t0 = 0.0
t1 = 50.0
N = 26

# Get all the time steps t
times = ot.RegularGrid(t0, (t1 - t0) / (N - 1.0), N).getVertices()

delta_t = 1e-1

# %%
# Use all the methods previously described:
#
# - Monte Carlo: values in values_MC
# - Low discrepancy suites: values in values_QMC
# - FORM: values in values_FORM
#

# %%
values_MC = list()
values_QMC = list()
values_FORM = list()
print('ts1=', ts1)

ts2 = ot.TimeSeries(10, dim)
print('ts2=', ts2)

# ts2[5] = point2
# print 'ts2=', ts2

try:
    # We get the tenth element of the ts
    # THIS SHOULD NORMALLY FAIL
    tenthElement = ts1.at(9)
except:
    print('Expected failure')

tg1 = ot.RegularGrid(0.0, 0.1, 11)
ts3 = ot.TimeSeries(tg1, dim)
print('ts3=', ts3)

tg2 = ot.RegularGrid(0.0, 0.2, 6)
ts4 = ot.TimeSeries(tg2, dim)
print('ts4=', ts4)

# We append a sample to a time series
ts5 = ot.TimeSeries(3, dim)
ns1 = ot.Sample(3, [99.9] * dim)
print('ts5=', ts5)
ts5.add(ns1)
print('ts5=', ts5)

# We retrieve the values of the time series as a sample
Example #3
0

# Default dimension parameter to evaluate the model
inputDimension = 1
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())
Example #4
0
simplicies = [[]] * 6
simplicies[0] = [0, 1, 2, 4]
simplicies[1] = [3, 5, 6, 7]
simplicies[2] = [1, 2, 3, 6]
simplicies[3] = [1, 2, 4, 6]
simplicies[4] = [1, 3, 5, 6]
simplicies[5] = [1, 4, 5, 6]

mesh3D = ot.Mesh(vertices, simplicies)
tree = ot.KDTree(vertices)
print("3D mesh=", mesh3D)
print("volume=", "%.3f" % mesh3D.getVolume())
print("simplices volume=", mesh3D.computeSimplicesVolume())
point = [1.8] * 3
print("Nearest index(", point, ")=", tree.query(point))
points = [[-0.25] * 3, [2.25] * 3]
print("Nearest index(", points, ")=", tree.query(points))
print("P1 gram=\n", mesh3D.computeP1Gram())
rotation = ot.SquareMatrix(3)
rotation[0, 0] = m.cos(m.pi / 3.0)
rotation[0, 1] = m.sin(m.pi / 3.0)
rotation[1, 0] = -m.sin(m.pi / 3.0)
rotation[1, 1] = m.cos(m.pi / 3.0)
rotation[2, 2] = 1.0

# isregular bug
time_grid = ot.RegularGrid(0.0, 0.2, 40963)
mesh = ot.Mesh(time_grid)
print(mesh.isRegular())
Example #5
0
import openturns as ot
from matplotlib import pyplot as plt
from openturns.viewer import View
if ot.SpectralGaussianProcess().__class__.__name__ == 'Process':
    # default to Gaussian for the interface class
    process = ot.GaussianProcess()
elif ot.SpectralGaussianProcess().__class__.__name__ == 'DiscreteMarkovChain':
    process = ot.SpectralGaussianProcess()
    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.SpectralGaussianProcess()
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)
from __future__ import print_function
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 an ARMA process

# Create the mesh
tMin = 0.
time_step = 0.1
n = 100
time_grid = ot.RegularGrid(tMin, time_step, n)

# Create the distribution of dimension 1 or 3
# Care : the mean must be NULL
myDist_1 = ot.Triangular(-1., 0.0, 1.)

# Create  a white noise of dimension 1
myWN_1d = ot.WhiteNoise(myDist_1, time_grid)

# Create the ARMA model : ARMA(4,2) in dimension 1
myARCoef = ot.ARMACoefficients([0.4, 0.3, 0.2, 0.1])
myMACoef = ot.ARMACoefficients([0.4, 0.3])
arma = ot.ARMA(myARCoef, myMACoef, myWN_1d)

# %%
# Check the linear recurrence
Example #7
0
# %%
defaultDimension = 1
# Amplitude values
amplitude = [1.0] * defaultDimension
# Scale values
scale = [1.0] * defaultDimension
# Covariance model
myModel = ot.AbsoluteExponential(scale, amplitude)

# %%
# We define a mesh,
tmin = 0.0
step = 0.1
n = 11
myTimeGrid = ot.RegularGrid(tmin, step, n)

# %%
# and create the process :
process = ot.GaussianProcess(myModel, myTimeGrid)
print(process)

# %%
# We draw the first marginal of a sample of size 6 :
sample = process.getSample(6)
graph = sample.drawMarginal(0)
graph.setTitle("First marginal of six realizations of the process")
view = viewer.View(graph)

# %%
# Create a gaussian process from spectral density
Example #8
0
from __future__ import print_function
import openturns as ot
import math as m

ot.TESTPREAMBLE()

f = ot.Function(['t', 'y0', 'y1'], ['dy0', 'dy1'], ['t - y0', 'y1 + t^2'])
phi = ot.VertexValueFunction(f)
solver = ot.RungeKutta(phi)
print('ODE solver=', solver)
initialState = [1.0, -1.0]
nt = 100
timeGrid = [(i**2.0) / (nt - 1.0)**2.0 for i in range(nt)]
print('time grid=', ot.Point(timeGrid))
result = solver.solve(initialState, timeGrid)
print('result=', result)
print('last value=', result[nt - 1])
t = timeGrid[nt - 1]
ref = ot.Point(2)
ref[0] = -1.0 + t + 2.0 * m.exp(-t)
ref[1] = -2.0 + -2.0 * t - t * t + m.exp(t)
print('ref. value=', ref)
grid = ot.RegularGrid(0.0, 0.01, nt)
result = solver.solve(initialState, grid)
print('result=', result)
print('last value=', result[nt - 1])
t = grid.getValue(nt - 1)
ref[0] = -1.0 + t + 2.0 * m.exp(-t)
ref[1] = -2.0 + -2.0 * t - t * t + m.exp(t)
print('ref. value=', ref)
# %%
x_train = ot.Sample([[x] for x in [1., 3., 4., 6., 7.9, 11., 11.5]])
y_train = g(x_train)
n_train = x_train.getSize()
n_train

# %%
# In order to compare the function and its metamodel, we use a test (i.e. validation) design of experiments made of a regular grid of 100 points from 0 to 12. Then we convert this grid into a `Sample` and we compute the outputs of the function on this sample.

# %%
xmin = 0.
xmax = 12.
n_test = 100
step = (xmax - xmin) / (n_test - 1)
myRegularGrid = ot.RegularGrid(xmin, step, n_test)
x_test = myRegularGrid.getVertices()
y_test = g(x_test)

# %%
# In order to observe the function and the location of the points in the input design of experiments, we define the following functions which plots the data.


# %%
def plot_data_train(x_train, y_train):
    """Plot the data (x_train,y_train) as a Cloud, in red"""
    graph_train = ot.Cloud(x_train, y_train)
    graph_train.setColor("red")
    graph_train.setLegend("Data")
    return graph_train
Example #10
0
import openturns as ot
from math import exp
from matplotlib import pyplot as plt
from openturns.viewer import View


def C(s, t):
    return exp(-4.0 * abs(s - t) / (1 + (s * s + t * t)))


N = 64
a = 4.0
# myMesh = ot.IntervalMesher([N]).build(ot.Interval(-a, a))
myMesh = ot.RegularGrid(-a, 2 * a / N, N + 1)

myCovarianceCollection = ot.CovarianceMatrixCollection()
for k in range(myMesh.getVerticesNumber()):
    t = myMesh.getVertices()[k]
    for l in range(k + 1):
        s = myMesh.getVertices()[l]
        matrix = ot.CovarianceMatrix(1)
        matrix[0, 0] = C(s[0], t[0])
        myCovarianceCollection.add(matrix)

covarianceModel = ot.UserDefinedCovarianceModel(myMesh, myCovarianceCollection)


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

from __future__ import print_function
import openturns as ot

ot.TESTPREAMBLE()

# size of timeGrid
size = 6
dimension = 1
sample = ot.Sample(size, dimension)
for i in range(size):
    for j in range(dimension):
        sample[i, j] = i + j + 1

# TimeGrid
timeGrid = ot.RegularGrid(0.0, 1.0 / (size - 1), size)

# TimeSeries
timeSeries = ot.TimeSeries(timeGrid, sample)

# We create an empty ProcessSample with default constructor
psample0 = ot.ProcessSample()
psample0.setName("PSample0")
print("Default constructor")
print("psample0=", psample0)

# We create an empty ProcessSample with timeGrid, size and dimension
# arguments
psample1 = ot.ProcessSample(timeGrid, 4, dimension)
psample1.setName("PSample1")
print("Constructor based on size, dimension and timeGrid")
import openturns.viewer as viewer
from matplotlib import pylab as plt
ot.Log.Show(ot.Log.NONE)

# %%
# Define the origin
origin = ot.Dirac(0.0)

# %%
# Define the transition matrix
transition = ot.SquareMatrix([[0.1, 0.3, 0.6], [0.7, 0.1, 0.2],
                              [0.5, 0.3, 0.2]])

# %%
# Define an 1-d mesh
tgrid = ot.RegularGrid(0.0, 1.0, 50)

# %%
# Markov chain definition and realization
process = ot.DiscreteMarkovChain(origin, transition, tgrid)
real = process.getRealization()
graph = real.drawMarginal(0)
graph.setTitle('Discrete Markov chain')
view = viewer.View(graph)

# %%
# Get several realizations
process.setTimeGrid(ot.RegularGrid(0.0, 1.0, 20))
reals = process.getSample(3)
graph = reals.drawMarginal(0)
graph.setTitle('Discrete Markov chain, 3 realizations')
#
# .. math::
#    X_{0,t} + 0.4 X_{0,t-1} + 0.3 X_{0,t-2} + 0.2 X_{0,t-3} + 0.1 X_{0,t-4} = E_{0,t} + 0.4 E_{0,t-1} + 0.3 E_{0,t-2}
#
# where the white noise :math:`E_t` is defined by :math:`E_t \approx \mathrm{Triangular}(a = -1, m = 0, b = 1)`.
#

# %%
# The definition of the recurrence coefficients AR, MA (4,2) is simple :
myARCoef = ot.ARMACoefficients([0.4, 0.3, 0.2, 0.1])
myMACoef = ot.ARMACoefficients([0.4, 0.3])

# %%
# We build a regular time discretization of the interval [0,1] with 10 time steps.
# We also set up the white noise distribution of the recurrence relation :
myTimeGrid = ot.RegularGrid(0.0, 0.1, 10)
myWhiteNoise = ot.WhiteNoise(ot.Triangular(-1.0, 0.0, 1.0), myTimeGrid)

# %%
# We are now ready to create the ARMA-process :
process = ot.ARMA(myARCoef, myMACoef, myWhiteNoise)
print(process)

# %%
# ARMA process manipulation
# -------------------------
#
# In this paragraph we shall expose some of the services exposed by an :math:`ARMA(p,q)` object, namely :
#
# -  its AR and MA coefficients thanks to the methods *getARCoefficients,
#    getMACoefficients*,
Example #14
0
dim = 2
distribution = ot.Normal(dim)
Xvector = ot.RandomVector(distribution)
f = ot.SymbolicFunction(['x0', 'x1'], ['x0+x1'])
Yvector = ot.CompositeRandomVector(f, Xvector)
s = 1.0
event1 = ot.Event(Yvector, ot.Greater(), s)
description.add('composite vector/domain event')
domain1D = ot.LevelSet(ot.SymbolicFunction(['x0'], ['sin(x0)']),
                       ot.LessOrEqual(), -0.5)
event2 = ot.Event(Yvector, domain1D)
description.add('composite vector/interval event')
interval = ot.Interval(0.5, 1.5)
event3 = ot.Event(Yvector, interval)
description.add('process/domain event')
Xprocess = ot.WhiteNoise(distribution, ot.RegularGrid(0.0, 0.1, 10))
domain2D = ot.LevelSet(ot.SymbolicFunction(['x0', 'x1'], ['(x0-1)^2+x1^2']),
                       ot.LessOrEqual(), 1.0)
event4 = ot.Event(Xprocess, domain2D)
all_events = [event1, event2, event3, event4]
for i, event in enumerate(all_events):
    print(description[i])
    if event.isComposite():
        experiment = ot.MonteCarloExperiment()
        myAlgo = ot.ProbabilitySimulationAlgorithm(event, experiment)
    else:
        myAlgo = ot.ProbabilitySimulationAlgorithm(event)
    myAlgo.setMaximumOuterSampling(250)
    myAlgo.setBlockSize(4)
    myAlgo.setMaximumCoefficientOfVariation(0.1)
    myAlgo.run()
#! /usr/bin/env python

import openturns as ot
import os

ot.TESTPREAMBLE()

grids = [
    ot.RegularGrid(1.0, 0.1, 20),
    ot.RegularGrid(-3.0, 0.1, 20),
    ot.RegularGrid(3.0, -0.1, 20),
    ot.RegularGrid(-1.0, -0.1, 20),
    ot.RegularGrid(-1.0, 0.13, 20),
    ot.RegularGrid(1.0, -0.13, 20)
]

for regularGrid in grids:
    lowerBound = regularGrid.getLowerBound()[0]
    upperBound = regularGrid.getUpperBound()[0]
    n = regularGrid.getSimplicesNumber()
    print("regularGrid=", regularGrid, "lowerBound=", lowerBound,
          "upperBound=", upperBound, n, "simplices")
    algo = ot.RegularGridEnclosingSimplex(regularGrid)

    ot.RandomGenerator.SetSeed(0)
    test = ot.Sample(
        ot.Uniform(lowerBound - 0.2 * (upperBound - lowerBound), upperBound +
                   0.2 * (upperBound - lowerBound)).getSample(1000))

    vertices = regularGrid.getVertices()
    for vertex in test:
Example #16
0
print("transition matrix =")
print(transitionMatrix)

origin = 1
print("origin =")
print(origin)

process.setTransitionMatrix(transitionMatrix)
print("Transition matrix accessor : process = ")
print(process)

process.setOrigin(origin)
print("Origin accessor : process = ")
print(process)

process.setTimeGrid(ot.RegularGrid(0, 1, 20))
print("Time grid accessor : process = ")
print(process)

real = process.getRealization()
print("Realization :")
print(real)

future = process.getFuture(20)
print("One future :")
print(future)

futures = process.getFuture(20, 3)
print("3 different futures :")
print(futures)
Example #17
0
# where :math:`k`  is such that :math:`\underline{\tau}_k` is the  vertex of :math:`\mathcal{M}` the nearest to :math:`\underline{t}.`

# %%
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)

# %%
# We detail the example described in the documentation
# Create the time grid
t0 = 0.0
dt = 0.5
N = int((20.0 - t0) / dt)
mesh = ot.RegularGrid(t0, dt, N)

# Create the covariance function


def gamma(tau):
    return 1.0 / (1.0 + tau * tau)


# Create the collection of HermitianMatrix
coll = ot.SquareMatrixCollection()
for k in range(N):
    t = mesh.getValue(k)
    matrix = ot.SquareMatrix([[gamma(t)]])
    coll.add(matrix)
#!/usr/bin/env python

import openturns as ot
import openturns.testing as ott

ot.TESTPREAMBLE()
#ot.Log.Show(ot.Log.INFO)

# Time grid parameters
T = 3.0
NT = 32
tg = ot.RegularGrid(0.0, T / NT, NT)

# Toy function to link input processes to the output process
in_dim = 4
out_dim = 1
spatial_dim = 1


class pyf2p(ot.OpenTURNSPythonFieldToPointFunction):
    def __init__(self, mesh):
        super(pyf2p, self).__init__(mesh, in_dim, out_dim)
        self.setInputDescription(["x1", "x2", "x3", "x4"])
        self.setOutputDescription(['g'])

    def _exec(self, X):
        Xs = ot.Sample(X)
        x1, x2, x3, x4 = Xs.computeMean()
        y = x1 + x2 + x3 - x4 + x1 * x2 - x3 * x4 - 0.1 * x1 * x2 * x3
        return [y]
Example #19
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

# Time grid creation and White Noise
Tmin = 0.0
deltaT = 0.1
steps = 11

# Initialization of the TimeGrid timeGrid
timeGrid = ot.RegularGrid(Tmin, deltaT, steps)

# Creation of the Antecedent
myARMAProcess = ot.ARMA()
myARMAProcess.setTimeGrid(timeGrid)
print('myAntecedentProcess = ', myARMAProcess)

# Creation of a function
f = ot.SymbolicFunction(['t', 'x'], ['t+0.1*x^2'])

# We build a dynamical function
myFieldFunction = ot.FieldFunction(ot.VertexValueFunction(f, timeGrid))

# finally we get the compsite process
myCompositeProcess = ot.CompositeProcess(myFieldFunction, myARMAProcess)
print('myCompositeProcess = ', repr(myCompositeProcess))

# Test realization
print('One realization= ')
print(myCompositeProcess.getRealization())
Example #20
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

# ARMA(p, q)
p = 2
q = 1
dim = 2

# Make a realization of an ARMA model
# Tmin , Tmax and N points for TimeGrid
dt = 1.0
size = 400
timeGrid = ot.RegularGrid(0.0, dt, size)

# white noise
cov = ot.CovarianceMatrix([[0.1, 0.0], [0.0, 0.2]])
whiteNoise = ot.WhiteNoise(ot.Normal([0.0] * dim, cov), timeGrid)

# AR/MA coefficients
ar = ot.ARMACoefficients(p, dim)
ar[0] = ot.SquareMatrix([[-0.5, -0.1], [-0.4, -0.5]])
ar[1] = ot.SquareMatrix([[0.0, 0.0], [-0.25, 0.0]])

ma = ot.ARMACoefficients(q, dim)
ma[0] = ot.SquareMatrix([[-0.4, 0.0], [0.0, -0.4]])

# ARMA model creation
myARMA = ot.ARMA(ar, ma, whiteNoise)
# %%
import openturns as ot
import openturns.viewer as viewer
from matplotlib import pylab as plt
ot.Log.Show(ot.Log.NONE)

# %%
# generate some data

# Create the time grid
# In the context of the spectral estimate or Fourier transform use,
# we use data blocs with size of form 2^p
tMin = 0.
tstep = 0.1
size = 2**12
tgrid = ot.RegularGrid(tMin, tstep, size)

# We fix the parameter of the Cauchy model
amplitude = [5.0]
scale = [3.0]
model = ot.CauchyModel(amplitude, scale)
process = ot.SpectralGaussianProcess(model, tgrid)

# Get a time series or a sample of time series
tseries = process.getRealization()
sample = process.getSample(1000)

# %%
# Build a spectral model factory
segmentNumber = 10
overlapSize = 0.3
Example #22
0
from __future__ import print_function
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)

# %%
# Define the distribution
sigma = 1.0
dist = ot.Normal(0.0, sigma)

# %%
# Define the mesh
tgrid = ot.RegularGrid(0.0, 1.0, 100)

# %%
# Create the process
process = ot.WhiteNoise(dist, tgrid)
process

# %%
# Draw a realization
realization = process.getRealization()
graph = realization.drawMarginal(0)
graph.setTitle('Realization of a white noise with distribution N(0,1)')
view = viewer.View(graph)

# %%
# Draw a sample
Example #23
0
#! /usr/bin/env python

import openturns as ot
import math as m
import dill

# ensures python code is included
dill.settings['recurse'] = True

ot.TESTPREAMBLE()

mesh = ot.RegularGrid(0, 1, 100)


def g(X):
    a, b = X
    Y = [[a * m.sin(t) + b] for t in range(100)]
    return Y


f = ot.PythonPointToFieldFunction(2, mesh, 1, g)
x = [4, 5]
print(f(x))

# save
study = ot.Study()
study.setStorageManager(ot.XMLStorageManager('pyp2ff.xml'))
study.add('f', f)
study.save()
Example #24
0
import openturns as ot
from math import exp
from matplotlib import pyplot as plt
from openturns.viewer import View

mesh = ot.RegularGrid(0.0, 1.0, 4)
values = [[0.5], [1.5], [1.0], [-0.5]]
field = ot.Field(mesh, values)
func = ot.P1LagrangeEvaluationImplementation(field)
func.setDescription(['$x$', '$y$'])

graph = func.draw(-1.0, 4.0, 1024)
cloud = ot.Cloud(mesh.getVertices(), values)
cloud.setPointStyle("square")
graph.add(cloud)
graph.setColors(["blue", "red"])
fig = plt.figure(figsize=(10, 4))
plt.suptitle('P1 Lagrange interpolation')
func_axis = fig.add_subplot(111)
view = View(graph, figure=fig, axes=[func_axis], add_legend=False)

Example #25
0
ot.Log.Show(ot.Log.NONE)

# %%
# Define the coefficients distribution
mu = [2.0]*2
sigma = [5.0]*2
R = ot.CorrelationMatrix(2)
coefDist = ot.Normal(mu, sigma, R)

# %%
# Create a basis of functions
phi_1 = ot.SymbolicFunction(['t'], ['sin(t)'])
phi_2 = ot.SymbolicFunction(['t'], ['cos(t)^2'])
myBasis = ot.Basis([phi_1, phi_2])

# %%
# Create the mesh
myMesh = ot.RegularGrid(0.0, 0.1, 100)

# %%
# Create the process
process = ot.FunctionalBasisProcess(coefDist, myBasis, myMesh)

# %%
# Draw a sample
N = 6
sample = process.getSample(N)
graph = sample.drawMarginal(0)
graph.setTitle(str(N)+' realizations of functional basis process')
view = viewer.View(graph)
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

ot.TESTPREAMBLE()

# Create an intance
myFunc = ot.SymbolicFunction(["t", "x"], ["x + t^2"])
tg = ot.RegularGrid(0.0, 0.2, 6)
myTemporalFunc = ot.VertexValueFunction(myFunc, tg)

print("myTemporalFunc=", myTemporalFunc)
# Get the input and output description
print("myTemporalFunc input description=",
      myTemporalFunc.getInputDescription())
print("myTemporalFunc output description=",
      myTemporalFunc.getOutputDescription())
# Get the input and output dimension, based on description
print("myTemporalFunc input dimension=", myTemporalFunc.getInputDimension())
print("myTemporalFunc output dimension=", myTemporalFunc.getOutputDimension())
# Create a TimeSeries
data = ot.Sample(tg.getN(), myFunc.getInputDimension() - 1)
for i in range(data.getSize()):
    for j in range(data.getDimension()):
        data[i, j] = i * data.getDimension() + j
ts = ot.TimeSeries(tg, data)
print("input time series=", ts)
print("output time series=", myTemporalFunc(ts))
# Get the number of calls
print("called ", myTemporalFunc.getCallsNumber(), " times")
Example #27
0
#     E \sim Triangular(-1, 0, 1)
#

# %%
import openturns as ot
import matplotlib.pyplot as plt
ot.RandomGenerator.SetSeed(0)
ot.Log.Show(ot.Log.NONE)

# %%
# Create an arma process

tMin = 0.0
n = 1000
timeStep = 0.1
myTimeGrid = ot.RegularGrid(tMin, timeStep, n)

myWhiteNoise = ot.WhiteNoise(ot.Triangular(-1.0, 0.0, 1.0), myTimeGrid)
myARCoef = ot.ARMACoefficients([0.4, 0.3, 0.2, 0.1])
myMACoef = ot.ARMACoefficients([0.4, 0.3])
arma = ot.ARMA(myARCoef, myMACoef, myWhiteNoise)

tseries = ot.TimeSeries(arma.getRealization())

# Create a sample of N time series from the process
N = 100
sample = arma.getSample(N)

# %%
# CASE 1 : we specify a (p,q) order
#! /usr/bin/env python

import openturns as ot

size = 100

# ARMA parameters
arcoefficients = ot.ARMACoefficients([0.3])
macoefficients = ot.ARMACoefficients(0)
timeGrid = ot.RegularGrid(0.0, 0.1, size)

# White noise ==> gaussian
whiteNoise = ot.WhiteNoise(ot.Normal(), timeGrid)
myARMA = ot.ARMA(arcoefficients, macoefficients, whiteNoise)

# A realization of the ARMA process
# The realization is supposed to be of a stationnary process
realization = ot.TimeSeries(myARMA.getRealization())

# In the strategy of tests, one has to detect a trend tendency
# We check if the time series writes as x_t = a +b * t + c * x_{t-1}
# H0 = c is equal to one and thus
# p-value threshold : probability of the H0 reject zone : 0.05
# p-value : probability (test variable decision > test variable decision (statistic) evaluated on data)
# Test = True <=> p-value > p-value threshold
test = ot.DickeyFullerTest(realization)
print("Drift and linear trend model=",
      test.testUnitRootInDriftAndLinearTrendModel(0.05))
print("Drift model=", test.testUnitRootInDriftModel(0.05))
print("AR1 model=", test.testUnitRootInAR1Model(0.05))
Example #29
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

ot.TESTPREAMBLE()

mesh = ot.RegularGrid(0.0, 0.1, 11)


def f(X):
    size = 11
    Y = [ot.Point(X)*i for i in range(size)]
    return Y


inputDim = 2
outputDim = 2
function = ot.PythonPointToFieldFunction(inputDim, mesh, outputDim, f)
function.setInputDescription(['u1', 'u2'])
function.setOutputDescription(['v1', 'v2'])

# freeze u1=5.0
parametric = ot.ParametricPointToFieldFunction(function, [0], [5.0])

# properties
print('dim=', parametric.getInputDimension(), parametric.getOutputDimension())
print('description=', parametric.getInputDescription(),
      parametric.getOutputDescription())
print('mesh=', parametric.getOutputMesh())
        inputValues = X.getValues()
        f = ot.NumericalMathFunction(
            ot.PiecewiseLinearEvaluationImplementation(
                [x[0] for x in inputTG.getVertices()], inputValues))
        outputValues = ot.NumericalSample(0, 1)
        for t in self.outputGrid_.getVertices():
            kernel = ot.Normal(t[0], 0.05)

            def pdf(X):
                return [kernel.computePDF(X)]

            weight = ot.NumericalMathFunction(ot.PythonFunction(1, 1, pdf))
            outputValues.add(
                self.algo_.integrate(weight * f, kernel.getRange()))
        return ot.Field(self.outputGrid_, outputValues)


N = 5
X = ot.TemporalNormalProcess(ot.GeneralizedExponential([0.1], 1.0),
                             ot.RegularGrid(-5.0, 0.1, 101))
f = ot.DynamicalFunction(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)