Exemplo n.º 1
0
# 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()))

crit = result.drawHistoryCriterion()
proba = result.drawHistoryProbability()
temp = result.drawHistoryTemperature()

pp = PdfPages('small_OTLHS.pdf')
Exemplo n.º 2
0
            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"
      f"-> LHS opt: {Space.discrepancy(sample_lhs_opt, method='WD')}\n"
      f"-> LHS: {Space.discrepancy(sample_lhs, method='WD')}\n"
Exemplo n.º 3
0
criterionGraph = result.drawHistoryCriterion()
# criterionGraph.draw("MC_PhiP_Criterion")

# --------------------------------------------------#
# ------------- Simulated annealing  ------------- #
# --------------------------------------------------#
# Defining temperature profil ==> TO, iterations...
T0 = 10.0
iMax = 2000
c = 0.95
# Care, c should be in ]0,1[
# Geometric profil
geomProfile = ot.GeometricProfile(T0, c, iMax)

# 3) Simulated Annealing LHS with geometric temperature, C2 optimization
optimalLHSAlgorithm = ot.SimulatedAnnealingLHS(lhs, geomProfile,
                                               spaceFillingC2)
print("lhs=", optimalLHSAlgorithm)
design = optimalLHSAlgorithm.generate()
print(
    "Generating design using SimulatedAnnealing geometric temperature & C2 criterion=",
    design)
result = optimalLHSAlgorithm.getResult()
history = result.getAlgoHistory()
print("History criterion=", history[:, 0])
print("History temperature=", history[:, 1])
print("History probability=", history[:, 2])
print("Final criteria: C2=%f, PhiP=%f" % (result.getC2(), result.getPhiP()))

# Criteria drawing
# SA algorithms returns also Probability & temperature
criterionGraph = result.drawHistoryCriterion()
# print the criteria on this design
print("PhiP=%f, C2=%f" % (ot.SpaceFillingPhiP().evaluate(design),
                          ot.SpaceFillingC2().evaluate(design)))

# --------------------------------------------------#
# ------------- Simulated annealing  ------------- #
# --------------------------------------------------#
# Geometric profile
T0 = 10.0
iMax = 2000
c = 0.95
geomProfile = ot.GeometricProfile(T0, c, iMax)

# 1) Simulated Annealing LHS with geometric temperature profile, C2
# optimization
optimalLHSAlgorithm = ot.SimulatedAnnealingLHS(lhs, spaceFillingC2,
                                               geomProfile)
print("lhs=", optimalLHSAlgorithm)
design = optimalLHSAlgorithm.generate()
print("Generating design using geometric temperature profile & C2 criterion=",
      design)
result = optimalLHSAlgorithm.getResult()
print("Final criteria: C2=%f, PhiP=%f, MinDist=%f" %
      (result.getC2(), result.getPhiP(), result.getMinDist()))

# Linear profile
linearProfile = ot.LinearProfile(T0, iMax)

# 2) Simulated Annealing LHS with linear temperature profile, PhiP optimization
optimalLHSAlgorithm = ot.SimulatedAnnealingLHS(lhs, spaceFillingPhiP,
                                               linearProfile)
print("lhs=", optimalLHSAlgorithm)
# %%
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

# %%
starting_points.getMin(), starting_points.getMax()

# %%
Exemplo n.º 6
0
# 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)
# Retrieve optimal design
input_database = algo.generate()

result = algo.getResult()

print('initial design computed')

# Response of the model
print('sampling size = ', N)
output_database = ishigami_model(input_database)

# Learning input/output
# Usual chaos meta model
enumerate_function = ot.HyperbolicAnisotropicEnumerateFunction(dimension)
orthogonal_basis = ot.OrthogonalProductPolynomialFactory(
# Optimized LHS
# -------------

# %%
distribution = ot.ComposedDistribution([ot.Uniform()]*3)
samplesize = 10

# %%
bounds = distribution.getRange()

# %%
lhs = ot.LHSExperiment(distribution, samplesize)
lhs.setAlwaysShuffle(True) # randomized
space_filling = ot.SpaceFillingC2()
temperatureProfile = ot.GeometricProfile(10.0, 0.95, 1000)
algo = ot.SimulatedAnnealingLHS(lhs, space_filling, temperatureProfile)
# optimal design
sample = algo.generate()

# %%
fig = otv.PlotDesign(sample, bounds)
fig.set_size_inches(10, 10)

# %%
# We see that this LHS is optimized in the sense that it fills the space more evenly than a non-optimized does in general. 

# %%
# Sobol' low discrepancy sequence
# -------------------------------

# %%
Exemplo n.º 8
0
def optimizedLHS(distribution, size, seed):
    ot.RandomGenerator.SetSeed(seed)
    lhs = ot.LHSExperiment(distribution, size, True, True)
    lhs_optimise = ot.SimulatedAnnealingLHS(lhs)
    lhs_sample = lhs_optimise.generate()
    return lhs_sample
Exemplo n.º 9
0
    def __init__(self, n_samples, bounds, kind, dists=None, discrete=None):
        """Initialize the DOE generation.

        In case of :attr:`kind` is ``uniform``, :attr:`n_samples` is decimated
        in order to have the same number of points in all dimensions.

        If :attr:`kind` is ``discrete``, a join distribution between a discrete
        uniform distribution is made with continuous distributions.

        Another possibility is to set a list of PDF to sample from. Thus one
        can do: `dists=['Uniform(15., 60.)', 'Normal(4035., 400.)']`. If not
        set, uniform distributions are used.

        :param int n_samples: number of samples.
        :param array_like bounds: Space's corners [[min, n dim], [max, n dim]]
        :param str kind: Sampling Method if string can be one of
          ['halton', 'sobol', 'faure', '[o]lhs[c]', 'sobolscramble', 'uniform',
          'discrete'] otherwize can be a list of openturns distributions.
        :param lst(str) dists: List of valid openturns distributions as string.
        :param int discrete: Position of the discrete variable.
        """
        self.n_samples = n_samples
        self.bounds = np.asarray(bounds)
        self.kind = kind
        self.dim = self.bounds.shape[1]

        self.scaler = preprocessing.MinMaxScaler()
        self.scaler.fit(self.bounds)

        if dists is None:
            dists = [ot.Uniform(float(self.bounds[0][i]),
                                float(self.bounds[1][i]))
                     for i in range(self.dim)]
        else:
            dists = bat.space.dists_to_ot(dists)

        if discrete is not None:
            # Creating uniform discrete distribution for OT
            disc_list = [[i] for i in range(int(self.bounds[0, discrete]),
                                            int(self.bounds[1, discrete] + 1))]
            disc_dist = ot.UserDefined(disc_list)

            dists.pop(discrete)
            dists.insert(discrete, disc_dist)

        # Join distribution
        self.distribution = ot.ComposedDistribution(dists)

        if self.kind == 'halton':
            self.sequence_type = ot.LowDiscrepancyExperiment(ot.HaltonSequence(),
                                                             self.distribution,
                                                             self.n_samples)
        elif self.kind == 'sobol':
            self.sequence_type = ot.LowDiscrepancyExperiment(ot.SobolSequence(),
                                                             self.distribution,
                                                             self.n_samples)
        elif self.kind == 'faure':
            self.sequence_type = ot.LowDiscrepancyExperiment(ot.FaureSequence(),
                                                             self.distribution,
                                                             self.n_samples)
        elif (self.kind == 'lhs') or (self.kind == 'lhsc'):
            self.sequence_type = ot.LHSExperiment(self.distribution, self.n_samples)
        elif self.kind == 'olhs':
            lhs = ot.LHSExperiment(self.distribution, self.n_samples)
            self.sequence_type = ot.SimulatedAnnealingLHS(lhs, ot.GeometricProfile(),
                                                          ot.SpaceFillingC2())
        elif self.kind == 'saltelli':
            # Only relevant for computation of Sobol' indices
            size = self.n_samples // (2 * self.dim + 2)  # N(2*dim + 2)
            self.sequence_type = ot.SobolIndicesExperiment(self.distribution,
                                                           size, True).generate()
Exemplo n.º 10
0
#
# Starting from an LHS design, a new design is built by permuting a random coordinate of two randomly chosen sample points; this new design is also an LHS. but not necessary a more efficient design.
#
# A comparison of criteria of the two designs is done, and the new LHS is accepted with probability
#
# .. math::
#    min\left(exp{\left[-\frac{\Phi(LHS_{new}) - \Phi(LHS)}{T_i}\right]}, 1\right)
#

# %%
# Considering independent Uniform(0,1) distributions of dimension 3
distribution = ot.ComposedDistribution([ot.Uniform(0.0, 1.0)] * 3)
# Random LHS
lhs = ot.LHSExperiment(distribution, N)
lhs.setAlwaysShuffle(True)  # randomized
algo = ot.SimulatedAnnealingLHS(lhs)
design = algo.generate()

# %%
# One could also fix the criterion, the temperature profile and get more results.

# Considering independent Uniform distributions of dimension 3
# Bounds are (-1,1), (0,2) and (0, 0.5)
distribution = ot.ComposedDistribution(
    [ot.Uniform(-1.0, 1.0),
     ot.Uniform(0.0, 2.0),
     ot.Uniform(0.0, 0.5)])
# Random LHS
lhs = ot.LHSExperiment(distribution, N)
lhs.setAlwaysShuffle(True)  # randomized
# Fixing C2 crit