Example #1
0
def random_uniform_ring(
        center=np.array([0, 0]), r_outer=1, r_inner=0, n_samples=1):
    """Generate point uniformly distributed in a ring.

    Muller, M. E. "A Note on a Method for Generating Points Uniformly on
    n-Dimensional Spheres." Comm. Assoc. Comput. Mach. 2, 19-20, Apr. 1959.
    """
    center = np.asarray(center).reshape(1, -1)
    nd = center.shape[1]
    x = np.random.normal(size=(n_samples, nd))

    # dists = [ot.Normal(0, 1) for _ in range(nd)]
    # dists = ot.ComposedDistribution(dists)
    # lhs = ot.LHSExperiment(dists, n_samples, True, True)
    # x = np.array(ot.SimulatedAnnealingLHS(lhs, ot.GeometricProfile(),
    #                                       ot.SpaceFillingC2()).generate())
    # x = np.array(ot.LowDiscrepancyExperiment(ot.SobolSequence(), dists, n_samples).generate())

    x /= np.linalg.norm(x, axis=1)[:, np.newaxis]  # generate on unit sphere

    # using the inverse cdf method
    # u = np.random.uniform(size=(n_samples))
    u = np.array(
        ot.LHSExperiment(ot.Uniform(0, 1), n_samples, True,
                         True).generate()).flatten()

    # this is inverse the cdf of ring volume as a function of radius
    sc = (u * (r_outer**nd - r_inner**nd) + r_inner**nd)**(1. / nd)
    return x * sc[:, None] + center
Example #2
0
def check_if_stop_iteration(dist, series, model_all, model_fold,
                            num_feval_total, analysis_hparams):
    flag_stop = False
    num_pnt_mcs = analysis_hparams['num_pnt_mcs']
    num_feval_max = analysis_hparams['num_feval_max']
    epsilon_pf = analysis_hparams['epsilon_pf']
    X = np.array(ot.LHSExperiment(dist, num_pnt_mcs).generate())
    y_hat_all = model_all.predict(X, False, False)
    pf_hat = calc_pf_mcs(y_hat_all, series)
    if pf_hat == 0:
        return None, None, flag_stop
    else:
        pf_hat_fold = []
        for tmp_model in model_fold:
            tmp_y_hat = tmp_model.predict(X, False, False)
            pf_hat_fold.append(calc_pf_mcs(tmp_y_hat, series))
        if max(abs(np.array(pf_hat_fold) - pf_hat)) / pf_hat <= epsilon_pf:
            print('Stopped. Epsilon of the failure probability is small.')
            flag_stop = True
        elif num_feval_total > num_feval_max:
            print(
                'Stopped. The total number of function evaluations exceeds num_feval_max={}'
                .format(num_feval_max))
            flag_stop = True
        return pf_hat, pf_hat_fold, flag_stop
def LHSdesign(Z, Wgt, mode, N):
    '''
    Create a LHS design for a mixture of Uniform
    '''
    dim = len(Z)
    Pos = [[]] * dim
    Part = [[]] * dim
    Design = np.zeros((N, 4))
    for i in range(dim):
        Z[i].append(mode[i])
        Z[i].sort()
        Pos[i] = int(Z[i].index(mode[i]))
        Part[i] = [[]] * (len(Z[i]) - 1)
        for j in range(Pos[i]):
            Part[i][j] = int((N + 1) * (Z[i][j + 1] - Z[i][j]) * sum(
                [Wgt[i][k] / (Z[i][Pos[i]] - Z[i][k]) for k in range(j + 1)]))
        for j in range(Pos[i] + 1, len(Z[i])):
            Part[i][j - 1] = int((N + 1) * (Z[i][j] - Z[i][j - 1]) * sum([
                Wgt[i][k - 1] / (Z[i][k] - Z[i][Pos[i]])
                for k in range(j, len(Z[i]))
            ]))
        if sum(Part[i]) != N:
            # print('Error, decomposition lead to different number of design point')
            Part[i][len(Part[i]) - 1] += int(N - sum(Part[i]))
        for j in range(len(Z[i]) - 1):
            if Part[i][j] != 0:
                Design[sum(Part[i][0:j]):sum(Part[i][0:j + 1]), i] = list(
                    np.array(
                        ot.LHSExperiment(ot.Uniform(Z[i][j], Z[i][j + 1]),
                                         Part[i][j]).generate()))
        shuffle(Design[:, i])

    return Design
Example #4
0
def sobolTotal(nCases):

    X0 = ot.Uniform(0.0, 1.0)
    X1 = ot.Uniform(0.0, 1.0)
    X2 = ot.Uniform(0.0, 1.0)
    X3 = ot.Uniform(0.0, 1.0)
    X4 = ot.Uniform(0.0, 1.0)
    X5 = ot.Uniform(0.0, 1.0)
    X6 = ot.Uniform(0.0, 1.0)

    inList = [X0, X1, X2, X3, X4, X5, X6]

    dim = len(inList)  #number of random variables
    myDistribution, VectX = setInputRandomVector(inList)

    f = myfunTotal
    model = ot.PythonFunction(dim, 1, f)

    ot.RandomGenerator.SetSeed(10)
    myRandomExp1 = ot.LHSExperiment(myDistribution, nCases)
    inp1 = myRandomExp1.generate()

    ot.RandomGenerator.SetSeed(75)
    myRandomExp2 = ot.LHSExperiment(myDistribution, nCases)
    inp2 = myRandomExp2.generate()

    #myRandomExp3 = LHSExperiment(myDistribution,nCases)
    #inp3 = myRandomExp3.generate()
    sensAnalysis = ot.mySensitivityAnalysis(inp1, inp2, model)

    sensAnalysis.setBlockSize(1)
    print '########################'
    print 'Starting Computations'
    #secondOrderIndices = sensAnalysis.getSecondOrderIndices()
    firstOrderIndices = sensAnalysis.getFirstOrderIndices()
    totalOrderIndices = sensAnalysis.getTotalOrderIndices()
    print 'Done withSobol'
    out1 = sensAnalysis.getOutVals1()
    print 'Mean', out1.computeMean()
    print 'STD', out1.computeStandardDeviation()
    out2 = sensAnalysis.getOutVals2()

    print 'First', firstOrderIndices
    print 'Total', totalOrderIndices
    #print 'Second',secondOrderIndices
    return [firstOrderIndices, totalOrderIndices]  #,secondOrderIndices,out1]
Example #5
0
def sklearn_q2(dists, model, surrogate):
    dists = ot.ComposedDistribution(dists)
    experiment = ot.LHSExperiment(dists, 1000)
    sample = np.array(experiment.generate())
    ref = model(sample)
    pred = surrogate(sample)

    return r2_score(ref, pred, multioutput='uniform_average')
Example #6
0
def test_corr_cov(mock_show, mascaret_data, tmp):
    func = mascaret_data.func
    dist = ot.ComposedDistribution(mascaret_data.dists)
    sample = np.array(ot.LHSExperiment(dist, 500).generate())
    data = func(sample)
    corr_cov(data,
             sample,
             func.x,
             interpolation='lanczos',
             plabels=['Ks', 'Q'])
    corr_cov(data, sample, func.x, fname=os.path.join(tmp, 'corr_cov.pdf'))
def myOptimalLHSExperiment(distribution, size, model):
    # Build standard randomized LHS algorithm
    lhs = ot.LHSExperiment(distribution, size)
    #lhs.setAlwaysShuffle(False) # randomized
    # Defining space fillings
    spaceFilling = ot.SpaceFillingC2()
    # RandomBruteForce MonteCarlo with N designs (LHS with C2 optimization)
    N = 10000
    optimalLHSAlgorithm = ot.MonteCarloLHS(lhs, N, spaceFilling)
    experiment = optimalLHSAlgorithm.getLHS()
    sensitivity_algorithm = ot.SaltelliSensitivityAlgorithm(experiment, model)
    return sensitivity_algorithm
Example #8
0
def sobolFun3(nCases):
    X0 = ot.Uniform(0.0, 1.0)
    X1 = ot.Uniform(0.0, 1.0)
    inList = [X0, X1]
    dim = len(inList)  #number of random variables
    myDistribution, VectX = setInputRandomVector(inList)
    ot.RandomGenerator.SetSeed(3)
    myRandomExp1 = ot.LHSExperiment(myDistribution, nCases)
    inp1 = myRandomExp1.generate()

    ot.RandomGenerator.SetSeed(6)
    myRandomExp2 = ot.LHSExperiment(myDistribution, nCases)
    inp2 = myRandomExp2.generate()

    f = myfun3
    model = ot.PythonFunction(dim, 1, f)
    sensAnalysis = ot.mySensitivityAnalysis(inp1, inp2, model)
    #secondOrderIndices = sensAnalysis.getSecondOrderIndices()
    firstOrderIndices = sensAnalysis.getFirstOrderIndices()
    totalOrderIndices = sensAnalysis.getTotalOrderIndices()
    out1 = sensAnalysis.getOutVals1()
    out2 = sensAnalysis.getOutVals2()
    return [firstOrderIndices, totalOrderIndices, out1]
Example #9
0
    def _generateSample(self, **kwargs):
        """Generation of two samples A and B using diverse methods
        """
        distribution = self.composedDistribution
        if 'method' in kwargs :
            method = kwargs['method']
        else :
            method = 'MonteCarlo'
        N2 = 2 * self.size
        if method == 'MonteCarlo':
            sample = distribution.getSample(N2)
        elif method == 'LHS':
            lhsExp = ot.LHSExperiment(distribution,
                                             N2,
                                             False,  # alwaysShuffle
                                             True)  # randomShift
            sample = lhsExp.generate()
        elif method == 'QMC':
            restart = True
            if 'sequence' in kwargs:
                if kwargs['sequence'] == 'Faure':
                    seq = ot.FaureSequence
                if kwargs['sequence'] == 'Halton':
                    seq = ot.HaltonSequence
                if kwargs['sequence'] == 'ReverseHalton':
                    seq = ot.ReverseHaltonSequence
                if kwargs['sequence'] == 'Haselgrove':
                    seq = ot.HaselgroveSequence
                if kwargs['sequence'] == 'Sobol':
                    seq = ot.SobolSequence
            else:
                print(
'sequence undefined for low discrepancy experiment, default: SobolSequence')
                print(
"'sequence' arguments: 'Faure','Halton','ReverseHalton','Haselgrove','Sobol'")
                seq = ot.SobolSequence
            LDExperiment = ot.LowDiscrepancyExperiment(seq(),
                                                       distribution,
                                                       N2,
                                                       True)
            LDExperiment.setRandomize(False)
            sample = LDExperiment.generate()
        sample = ot.Sample(sample)
        self._sample_A = sample[:self.size, :]
        self._sample_B = sample[self.size:, :]
Example #10
0
    def sample(self, n_samples : int, space : Space, **kwargs):

        if (self.cached_space is not None and space == self.cached_space):
            distribution = self.cached_distribution
        else:
            distributions = [ot.Uniform(*d.transformed_bounds) for d in space.dimensions]
            distribution  = ot.ComposedDistribution(distributions)
            # Caching space and distribution to speed-up future samplings, especially if invoked by the sample_constrained method.
            self.cached_space = space
            self.cached_distribution = distribution 

        lhs = ot.LHSExperiment(distribution, n_samples)
        lhs.setAlwaysShuffle(True) # randomized

        S = lhs.generate()
        S = np.array(S)
        S.reshape((n_samples, len(space)))

        return S
def generateByLHS(distribution, size, computeSecondOrder=False):
    '''
    Generates the input DOE for the estimator of the Sobol' sensitivity 
    indices.
    Uses a LHS design.
    '''
    dimension = distribution.getDimension()
    # Create a doubled distribution
    marginalList = [distribution.getMarginal(p) for p in range(dimension)]
    twiceDistribution = ot.ComposedDistribution(marginalList*2)
    # Generates a LHS in twice the dimension
    experiment = ot.LHSExperiment(twiceDistribution, size)
    fullDesign = experiment.generate()
    # Split the A and B designs
    A = fullDesign[:,0:dimension] # A
    B = fullDesign[:,dimension:2*dimension] # B
    # Uses the kernel to generate the sample
    design = generateSampleKernel(A,B,computeSecondOrder)
    return design
if 'VarianceMeasure' == 'JointChanceMeasure':
    measure = otrobopt.JointChanceMeasure(f, thetaDist, ot.GreaterOrEqual(),
                                          0.95)
elif 'VarianceMeasure' == 'IndividualChanceMeasure':
    measure = otrobopt.IndividualChanceMeasure(f, thetaDist,
                                               ot.GreaterOrEqual(), [0.95])
elif 'VarianceMeasure' == 'MeanStandardDeviationTradeoffMeasure':
    measure = otrobopt.MeanStandardDeviationTradeoffMeasure(
        f, thetaDist, [0.8])
elif 'VarianceMeasure' == 'QuantileMeasure':
    measure = otrobopt.QuantileMeasure(f, thetaDist, 0.99)
else:
    measure = otrobopt.VarianceMeasure(f, thetaDist)

N = 10
experiment = ot.LHSExperiment(N)
factory = otrobopt.MeasureFactory(experiment)
discretizedMeasure = factory.build(measure)

continuous_measure = otrobopt.MeasureFunction(measure)
discretized_measure = otrobopt.MeasureFunction(discretizedMeasure)

x_min = -2.0
x_max = 2.0
n_points = 128

parametric_graph = f.draw(x_min, x_max, n_points)
continuous_graph = continuous_measure.draw(x_min, x_max, n_points)
discretized_graph = discretized_measure.draw(x_min, x_max, n_points)

parametric_curve = parametric_graph.getDrawable(0)
dimension = 1

# %%
# Define the function.

# %%
g = ot.SymbolicFunction(['x'], ['0.5*x^2 + sin(2.5*x)'])

# %%
# Create the design of experiments.

# %%
xMin = -0.9
xMax = 1.9
X_distr = ot.Uniform(xMin, xMax)
X = ot.LHSExperiment(X_distr, sampleSize, False, False).generate()
Y = g(X)

# %%
graph = g.draw(xMin, xMax)
data = ot.Cloud(X, Y)
data.setColor("red")
graph.add(data)
view = viewer.View(graph)

# %%
# Create the algorithms
# ---------------------


# %%
Example #14
0
from matplotlib.backends.backend_pdf import PdfPages
from openturns.viewer import View
import time

ot.RandomGenerator.SetSeed(0)
ot.Log.Show(ot.Log.INFO)

# Bounds are [0,1]^dimension
dimension = 2
bounds = ot.Interval(dimension)

# Size of sample
size = 10

# Factory: lhs generates
lhsDesign = ot.LHSExperiment(
    ot.ComposedDistribution([ot.Uniform(0.0, 1.0)] * dimension), size)
lhsDesign.setAlwaysShuffle(True)  # randomized

geomProfile = ot.GeometricProfile(10.0, 0.999, 50000)
c2 = ot.SpaceFillingC2()
sa = ot.SimulatedAnnealingLHS(lhsDesign, geomProfile, c2)
tic = time.time()
result = sa.generate()
toc = time.time()
dt1 = toc - tic
print("time=%f" % dt1)
print("dimension=%d, size=%d,sa=%s" % (dimension, size, sa))
print(
    str(result.getOptimalValue()) + " c2=" + str(result.getC2()) + " phiP=" +
    str(result.getPhiP()) + " minDist=" + str(result.getMinDist()))
Example #15
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

ot.TESTPREAMBLE()

# Defining parameters
dimension = 3
size = 100

# Build standard LHS algorithm
distribution = ot.ComposedDistribution([ot.Uniform(0.0, 1.0)] * dimension)
lhs = ot.LHSExperiment(distribution, size)
lhs.setRandomShift(False)  # centered
lhs.setAlwaysShuffle(True)  # randomized

# print the object
print("lhs=", lhs)
bounds = distribution.getRange()
print("Bounds of uniform distributions=", bounds)

# Generate design without optimization
design = lhs.generate()
print("design=", design)

# Defining space fillings
spaceFillingC2 = ot.SpaceFillingC2()
spaceFillingPhiP = ot.SpaceFillingPhiP()

# print the criteria on this design
basis = ot.ConstantBasisFactory(dim).build()
print(basis)

# 2. covariance model
cov = ot.MaternModel([1.], [2.5], 1.5)
print(cov)

# 3. kriging algorithm
algokriging = ot.KrigingAlgorithm(x, y, cov, basis)

## error measure
#algokriging.setNoise([5*1e-1]*n_pt)

# 4. Optimization
# algokriging.setOptimizationAlgorithm(ot.NLopt('GN_DIRECT'))
startingPoint = ot.LHSExperiment(ot.Uniform(1e-1, 1e2), 50).generate()
algokriging.setOptimizationAlgorithm(ot.MultiStart(ot.TNC(), startingPoint))
algokriging.setOptimizationBounds(ot.Interval([0.1], [1e2]))

# if we choose not to optimize parameters
#algokriging.setOptimizeParameters(False)

# 5. run the algorithm
algokriging.run()

# %%
# Results
# -------

# %%
# get some results
polyColl = ot.PolynomialFamilyCollection(dim)
for i in range(dim):
	polyColl[i] = ot.HermiteFactory()

enumerateFunction = ot.LinearEnumerateFunction(dim)
multivariateBasis = ot.OrthogonalProductPolynomialFactory(polyColl, enumerateFunction)

basisSequenceFactory = ot.LARS()
fittingAlgorithm = ot.CorrectedLeaveOneOut()
approximationAlgorithm = ot.LeastSquaresMetaModelSelectionFactory(basisSequenceFactory, fittingAlgorithm)

# Génération du plan d'expériences
N = 200
ot.RandomGenerator.SetSeed(77)
Liste_test = ot.LHSExperiment(myDistribution, N)
InputSample = Liste_test.generate()


# Ecriture du fichier de données d'entrées
fidResult=open('IT'+IT0+'/IT'+IT0+'_TIRAGE_200.txt',"a")
for i in range(N):
	fidResult.write(
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,0])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,1])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,2])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,3])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,4])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,5])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,6])))+"\t"+
	'{0:>8s}'.format(str('{0:.3f}'.format(InputSample[i,7])))+"\t"+
basis = ot.ConstantBasisFactory(dim).build()
print(basis)

# 2. covariance model
cov = ot.MaternModel([1.], [2.5], 1.5)
print(cov)

# 3. kriging algorithm
algokriging = ot.KrigingAlgorithm(x, y, cov, basis)

## error measure
#algokriging.setNoise([5*1e-1]*n_pt)

# 4. Optimization
# algokriging.setOptimizationAlgorithm(ot.NLopt('GN_DIRECT'))
lhsExperiment = ot.LHSExperiment(ot.Uniform(1e-1, 1e2), 50)
algokriging.setOptimizationAlgorithm(
    ot.MultiStart(ot.TNC(), lhsExperiment.generate()))
algokriging.setOptimizationBounds(ot.Interval([0.1], [1e2]))

# if we choose not to optimize parameters
#algokriging.setOptimizeParameters(False)

# 5. run the algorithm
algokriging.run()

# %%
# Results
# -------

# %%
# %%
# First, we create a multivariate distribution, based on independent `Uniform` marginals which have the bounds required by the covariance model.

# %%
distributions = ot.DistributionCollection()
for i in range(dim):
    distributions.add(ot.Uniform(lbounds[i], ubounds[i]))
boundedDistribution = ot.ComposedDistribution(distributions)

# %%
# We first generate a Latin Hypercube Sampling (LHS) design made of 25 points in the sample space. This LHS is optimized so as to fill the space.

# %%
K = 25 # design size
LHS = ot.LHSExperiment(boundedDistribution, K)
LHS.setAlwaysShuffle(True)
SA_profile = ot.GeometricProfile(10., 0.95, 20000)
LHS_optimization_algo = ot.SimulatedAnnealingLHS(LHS, SA_profile, ot.SpaceFillingC2())
LHS_optimization_algo.generate()
LHS_design = LHS_optimization_algo.getResult()
starting_points = LHS_design.getOptimalDesign()
starting_points.getSize()

# %%
# We can check that the minimum and maximum in the sample correspond to the bounds of the design of experiment.

# %%
lbounds, ubounds

# %%
Example #20
0
dimension = 3
a = 7.0
b = 0.1
input_variables = ['xi1', 'xi2', 'xi3', 'a', 'b']
formula = ['sin(xi1) + a * (sin(xi2)) ^ 2 + b * xi3^4 * sin(xi1)']
full = ot.SymbolicFunction(input_variables, formula)
ishigami_model = ot.ParametricFunction(full, [3, 4], [a, b])

#  Generating a design of size
N = 150
# Considering independent Uniform distributions of dimension 3
# Bounds are (-pi,pi), (-pi,pi) and (-pi,pi)
distribution = ot.ComposedDistribution([ot.Uniform(-pi, pi)] * dimension)
bounds = distribution.getRange()
# Random LHS
lhs = ot.LHSExperiment(distribution, N)
lhs.setAlwaysShuffle(True)  # randomized
# Fixing C2 crit
space_filling = ot.SpaceFillingC2()
# Defining a temperature profile
temperatureProfile = ot.GeometricProfile()
# Pre conditionning : generate an optimal design with MC
nSimu = 100
algo = ot.MonteCarloLHS(lhs, nSimu, space_filling)
initialDesign = algo.generate()
result = algo.getResult()

print('initial design pre-computed. Performing SA optimization...')
# Use of initial design
algo = ot.SimulatedAnnealingLHS(initialDesign, distribution,
                                temperatureProfile, space_filling)
a = 7.0
b = 0.1
# Create the Ishigami function
inputVariables = ["xi1", "xi2", "xi3"]
formula = [
    "sin(xi1) + (" + str(a) + ") * (sin(xi2)) ^ 2 + (" + str(b) + ") * xi3^4 * sin(xi1)"]
model = ot.SymbolicFunction(inputVariables, formula)

# Create the input distribution
distribution = ot.ComposedDistribution([ot.Uniform(-pi, pi)] * dimension)

# Fix sampling size
samplingSize = 100

# Get input & output sample
lhs = ot.LHSExperiment(distribution, samplingSize)
inputSample = lhs.generate()
outputSample = model(inputSample)

# Validation of results on independent samples
validationSize = 10
inputValidation = distribution.getSample(validationSize)
outputValidation = model(inputValidation)

# 1) SPC algorithm
# Create the orthogonal basis
polynomialCollection = [ot.LegendreFactory()] * dimension

enumerateFunction = ot.LinearEnumerateFunction(dimension)
productBasis = ot.OrthogonalProductPolynomialFactory(
    polynomialCollection, enumerateFunction)
Example #22
0
import openturns as ot
from openturns.viewer import View

# LHS
d = ot.LHSExperiment(ot.ComposedDistribution([ot.Uniform()] * 3), 32)
s = d.generate()
s.setDescription(["X1", "X2", "X3"])
g = ot.Graph()
g.setTitle("LHS experiment")
g.setGridColor("black")
p = ot.Pairs(s)
g.add(p)
View(g)
# In this example we are going to expose the available probabilistic design of experiments generated according to a specified distribution and a specified number of points.

# %%
from __future__ import print_function
import openturns as ot
import math as m
import openturns.viewer as viewer
from matplotlib import pylab as plt

ot.Log.Show(ot.Log.NONE)

# %%
# Create the target distribution
distribution = ot.Normal(2)
N = 300

# %%
# 1. Monte Carlo
experiment = ot.MonteCarloExperiment(distribution, N)
sample = experiment.generate()
graph = ot.Cloud(sample)
view = viewer.View(graph)

# %%
# 2. LHS
experiment = ot.LHSExperiment(distribution, N)
sample = experiment.generate()
graph = ot.Cloud(sample)
view = viewer.View(graph)
plt.show()
anOTStudy.add(aDesign2)

aDesign2.run()
print('outs=', aDesign2.getResult().getDesignOfExperiment().getOutputSample())

# Design of Experiment ##
aDesign3 = persalys.ProbabilisticDesignOfExperiment('aDesign_3', model, 10,
                                                    'QUASI_MONTE_CARLO')
anOTStudy.add(aDesign3)

aDesign3.run()
print('outs=', aDesign3.getResult().getDesignOfExperiment().getOutputSample())

# Design of Experiment ##
aDesign4 = persalys.FixedDesignOfExperiment('aDesign_4', model)
inputSample = ot.LHSExperiment(model.getDistribution(), 10).generate()
#inputSample.stack(ot.Sample(10, [0.5, 1.3]))
aDesign4.setOriginalInputSample(inputSample)
anOTStudy.add(aDesign4)

aDesign4.run()

print('outs=', aDesign4.getResult().getDesignOfExperiment().getOutputSample())

# 3D Model to test Space filling algos
X0 = persalys.Input('X0', 1, ot.Normal())
X1 = persalys.Input('X1', 2, ot.Normal())
X2 = persalys.Input('X2', 3, ot.Normal())
Y0 = persalys.Output('Y0')

model = persalys.SymbolicPhysicalModel('aModelPhys', [X0, X1, X2], [Y0],
Example #25
0
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

# Defining parameters
dimension = 5
size = 100

# Build OT LHS algorithm
lhs = ot.LHSExperiment(ot.ComposedDistribution([ot.Uniform()] * dimension),
                       size)

# Generate design without optimization
design = lhs.generate()

# Defining space fillings
spaceFillingC2 = ot.SpaceFillingC2()
spaceFillingMinDist = ot.SpaceFillingMinDist()
spaceFillingPhiP = ot.SpaceFillingPhiP()
spaceFillingPhiP50 = ot.SpaceFillingPhiP(50)

# print the criteria on this design
print("C2=%f MinDist=%f PhiP=%f, PhiP(50)=%f" % tuple([
    sf.evaluate(design) for sf in [
        spaceFillingC2, spaceFillingMinDist, spaceFillingPhiP,
        spaceFillingPhiP50
    ]
]))
Example #26
0
# Number of trajectories
r = 5
# Define experiments in [0,1]^2
print("Use Case #1 : generate trajectories from regular grid")
levels = ot.Indices(2)
levels.fill(5, 0)
morris_experiment = otmorris.MorrisExperimentGrid(levels, r)
grid_bound = morris_experiment.getBounds()
sample1 = morris_experiment.generate()
print("Morris experiment generated from grid = ", sample1)

print("Use Case #2 : generate trajectories from initial lhs design")
size = 20
# Generate an LHS design
dist = ot.ComposedDistribution(2 * [ot.Uniform(0, 1)])
experiment = ot.LHSExperiment(dist, size, True, False)
lhsDesign = experiment.generate()
print("Initial LHS design = ", lhsDesign)
# Generate designs
morris_experiment_lhs = otmorris.MorrisExperimentLHS(lhsDesign, r)
lhs_bound = morris_experiment_lhs.getBounds()
sample2 = morris_experiment.generate()
print("Morris experiment generated from LHS = ", sample2)

# Define model
model = ot.SymbolicFunction(["x", "y"], ["cos(x)*y + sin(y)*x + x*y -0.1"])

# Define Morris method with two designs
morrisEE1 = otmorris.Morris(sample1, model(sample1), grid_bound)
morrisEE2 = otmorris.Morris(sample2, model(sample2), lhs_bound)
print("Using level grid, E(|EE|)  = ",
Example #27
0
    x_c, y, q = fl(x_train1[i])
    y_train1.append(y)

for i in range(len(x_trainr)):
    print("Reference case for LC metrics (y_trainr) Study#" + str(i))
    x_c, y, q = fl(x_trainr[i])
    y_trainr.append(y)

# Build the test sample

test_size = 1000  # test size
dists = [
    'Uniform(20., 40.)', 'BetaMuSigma(2000, 500, 1000, 3000).getDistribution()'
]
dists_ot = dists_to_ot(dists)
x_test = ot.LHSExperiment(ot.ComposedDistribution(dists_ot), test_size, True,
                          True).generate()
x_test = np.array(x_test)

#Buil the ouput test data
for i in range(len(x_test)):
    print("Test#" + str(i))
    x_c, y, q = fl(x_test[i])
    y_test.append(y)

# Surrogate

## Polynomial Chaos

### Quad

#Changing degree for truncation error
Example #28
0
def get_ed(func,
           jpdf,
           no_samples,
           sample_type='R',
           knots=[],
           values=[],
           ed_file=None,
           ed_fevals_file=None):
    """Returns randomly drawn knots and the corresponding evaluations.
    If knots!=0 in handle and the selected sequence is pseudo-random,
    or nested, only the additional knots to reach no_samples are computed
    func: function to be evaluated
    M: Number of samples
    jpdf: joint probabilty density function
    sample_type: choose sequence samples are drawn from
                 R - random (Monte Carlo) sampling
                 L - latin hypercube sampling
    knots: already excisting knots
    values: already excisting values"""

    if ed_file != None:
        knots_pool = np.genfromtxt(ed_file, delimiter=',')
        fvalues_pool = np.genfromtxt(ed_fevals_file)
    if knots == []:
        if ed_file != None:
            if no_samples <= knots_pool.shape[0]:
                knots = knots_pool[:no_samples, :]
                values = fvalues_pool[:no_samples]
                return knots, values
            else:
                knots = knots_pool
                values = fvalues_pool
                knots, values = get_ed(func, no_samples, jpdf, sample_type,
                                       knots, values)
                return knots, values
        else:
            if sample_type == 'R':
                knots = np.array(jpdf.getSample(no_samples))
            elif sample_type == 'L':
                knots = np.array(ot.LHSExperiment(jpdf, no_samples).generate())
            else:
                print('sample type not implemented')
                return
            values = np.asarray([func(knot) for knot in knots])
            return (knots, values)
    elif no_samples == knots.shape[0]:
        return (knots, values)
    else:
        if ed_file != None:
            if no_samples <= knots_pool.shape[0]:
                knots = knots_pool[:no_samples, :]
                values = fvalues_pool[:no_samples]
                return knots, values
            else:
                knots, values = get_ed(func, no_samples, jpdf, sample_type,
                                       knots, values)
                return knots, values
        else:
            if sample_type == 'R':
                knots_to_comp = np.array(
                    jpdf.getSample(no_samples - knots.shape[0]))
            elif sample_type == 'L':
                knots_to_comp = np.array(
                    ot.LHSExperiment(jpdf,
                                     no_samples - knots.shape[0]).generate())
            else:
                print('sample type not implemented')
                return
            knots_all = np.zeros((no_samples, knots.shape[1]))
            knots_all[:knots.shape[0], :] = knots
            knots_all[knots.shape[0]:, :] = knots_to_comp
            knots = knots_all
            values_new = np.asarray([func(knot) for knot in knots_to_comp])
            values = np.append(values, values_new)
    return (knots, values)
#! /usr/bin/env python

from __future__ import print_function
import openturns as ot

try:
    ot.ResourceMap.SetAsScalar(
        "LinearCombinationEvaluation-SmallCoefficient", 1.0e-10)
    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]))
Example #30
0
            #                                     sample[:, j]], axis=-1), method='MD')

            disc.append(disc_)

    return np.mean(disc)


dim = 2
n_sample = 10
sigma = 0.5
sampler = KdeSampler(sample=[[0.5, 0.7]], dim=dim, bw=sigma)
sample_kde = sampler.generate(n_sample)

dists = [ot.Uniform(0, 1) for _ in range(dim)]
dists = ot.ComposedDistribution(dists)
lhs = ot.LHSExperiment(dists, n_sample)
lhs_opt = ot.SimulatedAnnealingLHS(lhs, ot.GeometricProfile(),
                                   ot.SpaceFillingC2())

sample_lhs = np.array(lhs.generate())
sample_lhs_opt = np.array(lhs_opt.generate())
sample_sobol = np.array(ot.SobolSequence(dim).generate(n_sample))

print(f'Discrepancy CD:\n'
      f'-> KDE: {ot.SpaceFillingC2().evaluate(sample_kde)}\n'
      f'-> LHS opt: {ot.SpaceFillingC2().evaluate(sample_lhs_opt)}\n'
      f'-> LHS: {ot.SpaceFillingC2().evaluate(sample_lhs)}\n'
      f'-> Sobol: {ot.SpaceFillingC2().evaluate(sample_sobol)}\n')

print(f'Discrepancy WD:\n'
      f"-> KDE: {Space.discrepancy(sample_kde, method='WD')}\n"