squares problem. Test the local and global error covariances. """ m = 10 x = [[0.5 + i] for i in range(m)] inVars = ["a", "b", "c", "x"] formulas = ["a + b * exp(c * x)", "(a * x^2 + b) / (c + x^2)"] g = ot.SymbolicFunction(inVars, formulas) trueParameter = [2.8, 1.2, 0.5] params = [0, 1, 2] model = ot.ParametricFunction(g, params, trueParameter) y = model(x) y += ot.Normal([0.0] * 2, [0.05] * 2, ot.IdentityMatrix(2)).getSample(m) candidate = [1.0] * 3 priorCovariance = ot.CovarianceMatrix(3) for i in range(3): priorCovariance[i, i] = 3.0 + (1.0 + i) * (1.0 + i) for j in range(i): priorCovariance[i, j] = 1.0 / (1.0 + i + j) errorCovariance = ot.CovarianceMatrix(2) for i in range(2): errorCovariance[i, i] = 2.0 + (1.0 + i) * (1.0 + i) for j in range(i): errorCovariance[i, j] = 1.0 / (1.0 + i + j) globalErrorCovariance = ot.CovarianceMatrix(2 * m) for i in range(2 * m): globalErrorCovariance[i, i] = 2.0 + (1.0 + i) * (1.0 + i) for j in range(i): globalErrorCovariance[i, j] = 1.0 / (1.0 + i + j)
# %% # Scale vector (input dimension 1) theta = [4.0] # Create the rho function rho = ot.MaternModel(theta, 1.5) # Create the amplitude vector (output dimension 2) sigma = [1.0, 2.0] # output correlation R = ot.CorrelationMatrix(2) R[1, 0] = 0.01 # output covariance C = ot.CovarianceMatrix(2) C[0, 0] = 4.0 C[1, 1] = 5.0 C[1, 0] = 0.5 # %% # Create the covariance model from the amplitude and correlation, no spatial correlation ot.KroneckerCovarianceModel(rho, sigma) # %% # or from the correlation function, amplitude, and spatialCovariance ot.KroneckerCovarianceModel(rho, sigma, R) # %% # or from the correlation model and spatialCovariance ot.KroneckerCovarianceModel(rho, C)
import math as m import sys ot.TESTPREAMBLE() ot.PlatformInfo.SetNumericalPrecision(3) m = 10 x = [[0.5 + i] for i in range(m)] #ot.ResourceMap.SetAsUnsignedInteger( "OptimizationAlgorithm-DefaultMaximumEvaluationNumber", 100) inVars = ["a", "b", "c", "x"] formulas = ["a + b * exp(c * x)", "(a * x^2 + b) / (c + x^2)"] model = ot.SymbolicFunction(inVars, formulas) p_ref = [2.8, 1.2, 0.5] params = [0, 1, 2] modelX = ot.ParametricFunction(model, params, p_ref) y = modelX(x) y += ot.Normal([0.0]*2, [0.05]*2, ot.IdentityMatrix(2)).getSample(m) candidate = [1.0]*3 bootstrapSizes = [0, 100] for bootstrapSize in bootstrapSizes: algo = ot.NonLinearLeastSquaresCalibration(modelX, x, y, candidate) algo.setBootstrapSize(bootstrapSize) algo.run() # To avoid discrepance between the plaforms with or without CMinpack print("result (Auto)=", algo.getResult().getParameterMAP()) algo.setOptimizationAlgorithm(ot.MultiStart(ot.TNC(), ot.LowDiscrepancyExperiment(ot.SobolSequence(), ot.Normal(candidate, ot.CovarianceMatrix(ot.Point(candidate).getDimension())), ot.ResourceMap.GetAsUnsignedInteger("NonLinearLeastSquaresCalibration-MultiStartSize")).generate())) algo.run() # To avoid discrepance between the plaforms with or without CMinpack print("result (TNC)=", algo.getResult().getParameterMAP())
#! /usr/bin/env python from __future__ import print_function import openturns as ot ref_values = [[1.0, 0.0], [0.0, 0.5]] mats = [ ot.Matrix(ref_values), ot.SquareMatrix(ref_values), ot.TriangularMatrix(ref_values), ot.SymmetricMatrix(ref_values), ot.CovarianceMatrix(ref_values), ot.CorrelationMatrix(ref_values) ] mats.extend([ ot.ComplexMatrix(ref_values), ot.HermitianMatrix(ref_values), ot.TriangularComplexMatrix(ref_values), ot.SquareComplexMatrix(ref_values) ]) for a in mats: # try conversion ref = ot.Matrix([[1.0, 0.0], [0.0, 0.5]]) iname = a.__class__.__name__ print('a=', a) # try scalar mul try:
# t_00 = time() N = 2**5 dt = (tmax - t0) / N myMesh = ot.RegularGrid(t0, dt, N) # Keep only time stamps in the time-grid tmax = myMesh.getEnd() # Create the collection of HermitianMatrix myCovarianceCollection = ot.CovarianceMatrixCollection() index = 0 for k in range(N): s = myMesh.getValue(k) for l in range(k + 1): t = myMesh.getValue(l) matrix = ot.CovarianceMatrix(1) matrix[0, 0] = C(s, t) index += 1 myCovarianceCollection.add(matrix) # Create the covariance model myCovarianceModel = ot.UserDefinedCovarianceModel(myMesh, myCovarianceCollection) # Create the non stationary Normal process with # that covariance model myProcess = ot.TemporalNormalProcess(myCovarianceModel, myMesh) # Create a sample of fields size = 10**4 myFieldSample = myProcess.getSample(size)
m0 = ot.SquareMatrix(2, t0) print("tuple", t0, "=> SquareMatrix", m0) m0 = ot.SymmetricMatrix(2, t0) print("tuple", t0, "=> SymmetricMatrix", m0) m0 = ot.Tensor(2, 2, 1, t0) print("tuple", t0, "=> Tensor", m0) m0 = ot.SymmetricTensor(2, 1, t0) print("tuple", t0, "=> SymmetricTensor", m0) m0 = ot.CorrelationMatrix(2, t0) print("tuple", t0, "=> CorrelationMatrix", m0) m0 = ot.CovarianceMatrix(2, t0) print("tuple", t0, "=> CovarianceMatrix", m0) t0c = (1. + 3.j, 2. - 5.j, 3. + 7.j, 4. - 9.j) m0 = ot.ComplexMatrix(2, 2, t0) print("tuple", t0, "=> ComplexMatrix", m0) m0 = ot.ComplexMatrix(2, 2, t0c) print("tuple", t0c, "=> ComplexMatrix", m0) m0 = ot.SquareComplexMatrix(2, t0) print("tuple", t0, "=> SquareComplexMatrix", m0) m0 = ot.SquareComplexMatrix(2, t0c) print("tuple", t0c, "=> SquareComplexMatrix", m0)
# %% # Gaussian calibration parameters # ------------------------------- # %% # The standard deviation of the observations errors. # %% sigmaStress = 1.0e7 # (Pa) # %% # Define the covariance matrix of the output Y of the model. # %% errorCovariance = ot.CovarianceMatrix(1) errorCovariance[0, 0] = sigmaStress ** 2 # %% # Define the covariance matrix of the parameters :math:`\theta` to calibrate. # %% sigmaR = 0.1 * R sigmaC = 0.1 * C sigmaGamma = 0.1 * Gamma # %% sigma = ot.CovarianceMatrix(3) sigma[0, 0] = sigmaR ** 2 sigma[1, 1] = sigmaC ** 2 sigma[2, 2] = sigmaGamma ** 2
model = ot.ParametricFunction(g, params, trueParameter) x = ot.Sample(size, 0) y = model(x) outputObservationNoiseSigma = 0.05 meanNoise = ot.Point(outputDimension) covarianceNoise = ot.Point(outputDimension, outputObservationNoiseSigma) R = ot.IdentityMatrix(outputDimension) observationOutputNoise = ot.Normal(meanNoise, covarianceNoise, R) # Add noise sampleNoise = observationOutputNoise.getSample(size) y += sampleNoise candidate = [1.0] * 3 priorCovariance = ot.CovarianceMatrix(3) for i in range(3): priorCovariance[i, i] = 3.0 + (1.0 + i) * (1.0 + i) for j in range(i): priorCovariance[i, j] = 1.0 / (1.0 + i + j) errorCovariance = ot.CovarianceMatrix(outputDimension) for i in range(outputDimension): errorCovariance[i, i] = 0.1 * (2.0 + (1.0 + i) * (1.0 + i)) for j in range(i): errorCovariance[i, j] = 0.1 / (1.0 + i + j) globalErrorCovariance = ot.CovarianceMatrix(outputDimension * size) for i in range(outputDimension * size): globalErrorCovariance[i, i] = 0.1 * (2.0 + (1.0 + i) * (1.0 + i)) for j in range(i): globalErrorCovariance[i, j] = 0.1 / (1.0 + i + j) for bootstrapSize in [0, 30]:
def run(self): """ Build the POD models. Notes ----- This method build the polynomial chaos model. First the censored data are filtered if needed. The Box Cox transformation is performed if it is enabled. Then it builds the POD models, the Monte Carlo simulation is performed for each given defect sizes. The confidence interval is computed by simulating new coefficients of the polynomial chaos, then Monte Carlo simulations are performed. """ # run the chaos algorithm and get result if not given if not self._userChaos: if self._verbose: print('Start build polynomial chaos model...') self._algoChaos = self._buildChaosAlgo(self._input, self._signals) self._algoChaos.run() if self._verbose: print('Polynomial chaos model completed') self._chaosResult = self._algoChaos.getResult() # get the metamodel self._chaosPred = self._chaosResult.getMetaModel() # get the basis, coef and transformation, needed for the confidence interval self._chaosCoefs = self._chaosResult.getCoefficients() self._reducedBasis = self._chaosResult.getReducedBasis() self._transformation = self._chaosResult.getTransformation() self._basisFunction = ot.ComposedFunction(ot.AggregatedFunction( self._reducedBasis), self._transformation) # compute the residuals and stderr inputSize = self._input.getSize() basisSize = self._reducedBasis.getSize() self._residuals = self._signals - self._chaosPred(self._input) # residuals self._stderr = np.sqrt(np.sum(np.array(self._residuals)**2) / (inputSize - basisSize - 1)) # Check the quality of the chaos model R2 = self.getR2() Q2 = self.getQ2() if self._verbose: print('Polynomial chaos validation R2 (>0.8) : {:0.4f}'.format(R2)) print('Polynomial chaos validation Q2 (>0.8) : {:0.4f}'.format(Q2)) # Compute the POD values for each defect sizes self.POD = self._computePOD(self._defectSizes, self._chaosCoefs) # create the interpolate function interpModel = interp1d(self._defectSizes, self.POD, kind='linear') self._PODmodel = ot.PythonFunction(1, 1, interpModel) ####################### confidence interval ############################ dof = inputSize - basisSize - 1 varEpsilon = (ot.ChiSquare(dof).inverse() * dof * self._stderr**2).getRealization()[0] gramBasis = ot.Matrix(self._basisFunction(self._input)).computeGram() covMatrix = gramBasis.solveLinearSystem(ot.IdentityMatrix(basisSize)) * varEpsilon self._coefsDist = ot.Normal(np.hstack(self._chaosCoefs), ot.CovarianceMatrix(covMatrix.getImplementation())) coefsRandom = self._coefsDist.getSample(self._simulationSize) self._PODPerDefect = ot.Sample(self._simulationSize, self._defectNumber) for i, coefs in enumerate(coefsRandom): self._PODPerDefect[i, :] = self._computePOD(self._defectSizes, coefs) if self._verbose: updateProgress(i, self._simulationSize, 'Computing POD per defect')
myGraphRef.setDrawable(d, i) levels[i] = d.getLevels()[0] # Create the time grid # for iN in range(2, 11): # t_00 = time() N = 2**5 dt = (tmax - t0) / N myMesh = ot.RegularGrid(t0, dt, N) # Keep only time stamps in the time-grid tmax = myMesh.getEnd() # Create the collection of HermitianMatrix covariance = ot.CovarianceMatrix(N) for k in range(N): s = myMesh.getValue(k) for l in range(k + 1): t = myMesh.getValue(l) covariance[k, l] = C(s, t) # Create the covariance model myCovarianceModel = ot.UserDefinedCovarianceModel( myMesh, covariance) # Create the non stationary Gaussian process with # that covariance model myProcess = ot.GaussianProcess(myCovarianceModel, myMesh) # Create a sample of fields
# %% import openturns as ot import openturns.viewer as viewer from matplotlib import pylab as plt ot.Log.Show(ot.Log.NONE) # %% # 1. Define a spectral density function from correlation matrix amplitude = [1.0, 2.0, 3.0] scale = [4.0, 5.0, 6.0] spatialCorrelation = ot.CorrelationMatrix(3) spatialCorrelation[0, 1] = 0.8 spatialCorrelation[0, 2] = 0.6 spatialCorrelation[1, 2] = 0.1 spectralModel_Corr = ot.CauchyModel(amplitude, scale, spatialCorrelation) spectralModel_Corr # %% # 2. Define a spectral density function from a covariance matrix 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 spectralModel_Cov = ot.CauchyModel(scale, spatialCovariance) spectralModel_Cov
ot.TruncatedNormal(2.0, 1.5, 1.0, 4.0) ] distribution = [ ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 1.0, 4.0), ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 1.0, ot.TruncatedDistribution.LOWER), ot.TruncatedDistribution(ot.Normal(2.0, 1.5), 4.0, ot.TruncatedDistribution.UPPER), ot.TruncatedDistribution(ot.Normal(2.0, 1.5), ot.Interval([1.0], [4.0], [True], [True])) ] # add a 2-d test dimension = 2 size = 70 ref = ot.Normal([2.0] * dimension, ot.CovarianceMatrix(2)) sample = ref.getSample(size) ks = ot.KernelSmoothing().build(sample) truncatedKS = ot.TruncatedDistribution( ks, ot.Interval([1.0] * dimension, [3.0] * dimension)) distribution.append(truncatedKS) referenceDistribution.append(ref) # N/A ot.RandomGenerator.SetSeed(0) for testCase in range(len(distribution)): print('Distribution ', distribution[testCase]) # Is this distribution elliptical ? print('Elliptical = ', distribution[testCase].isElliptical()) # Is this distribution continuous ?
#! /usr/bin/env python from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() matrix1 = ot.CovarianceMatrix(2) print("matrix1 (default)=" + repr(matrix1)) matrix1[0, 0] = 1.0 matrix1[1, 0] = 0.5 matrix1[1, 1] = 1.0 print("matrix1 (initialized)=" + repr(matrix1)) pt = ot.Point() pt.add(5.0) pt.add(0.0) print("pt=", repr(pt)) result = ot.Point() result = matrix1.solveLinearSystem(pt) print("result=" + repr(result)) determinant = matrix1.computeDeterminant() print("determinant=%.6f" % determinant) ev = ot.ScalarCollection(2) ev = matrix1.computeEigenValues() print("ev=" + repr(ev)) if matrix1.isPositiveDefinite():
meanNoise = ot.Point(outputDimension) covarianceNoise = ot.Point(outputDimension, outputObservationNoiseSigma) R = ot.IdentityMatrix(outputDimension) observationOutputNoise = ot.Normal(meanNoise, covarianceNoise, R) size = 100 inputObservations = ot.Sample(size, 0) # Generate exact outputs inputSample = inputRandomVector.getSample(size) outputStress = g(inputSample) # Add noise sampleNoiseH = observationOutputNoise.getSample(size) outputObservations = outputStress + sampleNoiseH priorCovariance = ot.CovarianceMatrix(inputDimension) for i in range(inputDimension): priorCovariance[i, i] = 3.0 + (1.0 + i) * (1.0 + i) for j in range(i): priorCovariance[i, j] = 1.0 / (1.0 + i + j) errorCovariance = ot.CovarianceMatrix(outputDimension) for i in range(outputDimension): errorCovariance[i, i] = 2.0 + (1.0 + i) * (1.0 + i) for j in range(i): errorCovariance[i, j] = 1.0 / (1.0 + i + j) globalErrorCovariance = ot.CovarianceMatrix(outputDimension * size) for i in range(outputDimension * size): globalErrorCovariance[i, i] = 0.1 * (2.0 + (1.0 + i) * (1.0 + i)) for j in range(i): globalErrorCovariance[i, j] = 0.1 / (1.0 + i + j)
indice, coefficient = 0, 1. / (DoF - d - 1) for j in range(d): for k in range(j + 1): assert_almost_equal(theoretical_mean_inverse[indice], coefficient * Scale[k, j]) assert_almost_equal(theoretical_mean[indice], DoF * Scale_wishart[k, j]) assert_almost_equal(mean_inverse[indice], coefficient * Scale[k, j], 0.1, 1.E-3) assert_almost_equal(mean[indice], DoF * Scale_wishart[k, j], 0.1, 1.E-3) indice += 1 # Instanciate one distribution object distribution = ot.InverseWishart(ot.CovarianceMatrix(1), 5.0) print("Distribution ", repr(distribution)) print("Distribution ", distribution) # Get mean and covariance print("Mean= ", repr(distribution.getMean())) print("Covariance= ", repr(distribution.getCovariance())) # Is this distribution elliptical ? print("Elliptical = ", distribution.isElliptical()) # Test for realization of distribution oneRealization = distribution.getRealization() print("oneRealization=", repr(oneRealization)) # Test for sampling
return y XX_input = ot.Sample([[0.1, 0], [0.32, 0], [0.6, 0], [0.9, 0], [0.07, 1], [0.1, 1], [0.4, 1], [0.5, 1], [0.85, 1]]) y_output = ot.Sample(len(XX_input), 1) for i in range(len(XX_input)): y_output[i, 0] = fun_mixte(XX_input[i]) def C(s, t): return m.exp(-4.0 * abs(s - t) / (1 + (s * s + t * t))) N = 32 a = 4.0 myMesh = ot.IntervalMesher([N]).build(ot.Interval(-a, a)) myCovariance = ot.CovarianceMatrix(myMesh.getVerticesNumber()) for k in range(myMesh.getVerticesNumber()): t = myMesh.getVertices()[k] for l in range(k + 1): s = myMesh.getVertices()[l] myCovariance[k, l] = C(s[0], t[0]) covModel_discrete = ot.UserDefinedCovarianceModel(myMesh, myCovariance) f_ = ot.SymbolicFunction(["tau", "theta", "sigma"], [ "(tau!=0) * exp(-1/theta) * sigma * sigma + (tau==0) * exp(0) * sigma * sigma" ]) rho = ot.ParametricFunction(f_, [1, 2], [0.2, 0.3]) covModel_discrete = ot.StationaryFunctionalCovarianceModel([1.0], [1.0], rho) covModel_continuous = ot.SquaredExponential([1.0], [1.0]) covarianceModel = ot.ProductCovarianceModel(
dt = deflection_tube.DeflectionTube() # %% # We create a sample out of our input distribution : sampleSize = 100 inputSample = dt.inputDistribution.getSample(sampleSize) inputSample[0:5] # %% # We take the image of our input sample by the model : outputDeflection = dt.model(inputSample) outputDeflection[0:5] # %% observationNoiseSigma = [0.1e-6, 0.05e-5, 0.05e-5] observationNoiseCovariance = ot.CovarianceMatrix(3) for i in range(3): observationNoiseCovariance[i, i] = observationNoiseSigma[i]**2 # %% noiseSigma = ot.Normal([0., 0., 0.], observationNoiseCovariance) sampleObservationNoise = noiseSigma.getSample(sampleSize) observedOutput = outputDeflection + sampleObservationNoise observedOutput[0:5] # %% observedInput = ot.Sample(sampleSize, 2) observedInput[:, 0] = inputSample[:, 0] # F observedInput[:, 1] = inputSample[:, 5] # E observedInput.setDescription(["Force", "Young Modulus"]) observedInput[0:5]
y0Noise = ot.Normal(0, 0.1).getSample(nbObs) y0Sample = ot.ParametricFunction(symbolicModel.getFunction('y0'), [1, 2], [1.2, 1.])(inObs) y0Obs = y0Sample + y0Noise y0Obs.setDescription(['y0']) obs = persalys.Observations("observations", symbolicModel, inObs, y0Obs) myStudy.add(obs) # b- calibrationAnalysis calibration = persalys.CalibrationAnalysis('calibration', obs) calibration.setCalibratedInputs(['x2'], ot.Dirac([1.2]), ['x3'], [1.1]) calibration.setMethodName('GaussianNonlinear') sigma = 0.15 errorCovariance = ot.CovarianceMatrix(1) errorCovariance[0, 0] = sigma**2 calibration.setErrorCovariance(errorCovariance) calibration.setBootStrapSize(25) calibration.setConfidenceIntervalLength(0.99) optimAlgo = calibration.getOptimizationAlgorithm() optimAlgo.setMaximumEvaluationNumber(50) optimAlgo.setMaximumAbsoluteError(1e-6) optimAlgo.setMaximumRelativeError(1e-6) optimAlgo.setMaximumResidualError(1e-6) optimAlgo.setMaximumConstraintError(1e-6) calibration.setOptimizationAlgorithm(optimAlgo) myStudy.add(calibration)
algo.run() # To avoid discrepance between the plaforms with or without CMinpack # Check MAP calibrationResult = algo.getResult() parameterMAP = calibrationResult.getParameterMAP() print("(Auto) MAP=", repr(parameterMAP)) rtol = 1.0e-2 atol = 0.0 ott.assert_almost_equal(parameterMAP, trueParameter, rtol, atol) algo.setOptimizationAlgorithm( ot.MultiStart( ot.TNC(), ot.LowDiscrepancyExperiment( ot.SobolSequence(), ot.Normal( candidate, ot.CovarianceMatrix( ot.Point(candidate).getDimension()) ), ot.ResourceMap.GetAsUnsignedInteger( "NonLinearLeastSquaresCalibration-MultiStartSize" ), ).generate(), ) ) algo.run() # To avoid discrepance between the plaforms with or without CMinpack calibrationResult = algo.getResult() parameterMAP = calibrationResult.getParameterMAP() print("(Multistart/TNC) MAP=", repr(parameterMAP)) rtol = 1.0e-2 atol = 0.0 ott.assert_almost_equal(parameterMAP, trueParameter, rtol, atol)
g = ot.PythonFunction(4, 1, flooding) Q = ot.TruncatedDistribution( ot.Gumbel(558.0, 1013.0), ot.TruncatedDistribution.LOWER) K_s = ot.Dirac(30.0) Z_v = ot.Dirac(50.0) Z_m = ot.Dirac(55.0) inputRandomVector = ot.ComposedDistribution([Q, K_s, Z_v, Z_m]) nbobs = 100 inputSample = inputRandomVector.getSample(nbobs) outputH = g(inputSample) Hobs = outputH + ot.Normal(0.0, 0.1).getSample(nbobs) Qobs = inputSample[:, 0] thetaPrior = [20, 49, 51] model = ot.ParametricFunction(g, [1, 2, 3], thetaPrior) errorCovariance = ot.CovarianceMatrix([[0.5**2]]) sigma = ot.CovarianceMatrix(3) sigma[0, 0] = 5.**2 sigma[1, 1] = 1.**2 sigma[2, 2] = 1.**2 algo = ot.GaussianNonLinearCalibration( model, Qobs, Hobs, thetaPrior, sigma, errorCovariance) algo.run() result = algo.getResult() # check that the graphs can be produced graph1 = result.drawParameterDistributions() graph2 = result.drawResiduals() graph3 = result.drawObservationsVsInputs() graph4 = result.drawObservationsVsPredictions()
R = 700 # Exact : 750 C = 2500 # Exact : 2750 Gamma = 8. # Exact : 10 thetaPrior = ot.Point([R, C, Gamma]) # The following statement create the calibrated function from the model. # The calibrated parameters Ks, Zv, Zm are at indices 1, 2, 3 in the inputs arguments of the model. calibratedIndices = [1, 2, 3] mycf = ot.ParametricFunction(g, calibratedIndices, thetaPrior) # Gaussian linear calibration # The standard deviation of the observations. sigmaStress = 10. # (Pa) # Define the covariance matrix of the output Y of the model. localErrorCovariance = ot.CovarianceMatrix(1) localErrorCovariance[0, 0] = sigmaStress**2 # Define the covariance matrix of the parameters $\theta$ to calibrate. sigmaR = 0.1 * R sigmaC = 0.1 * C sigmaGamma = 0.1 * Gamma priorCovariance = ot.CovarianceMatrix(3) priorCovariance[0, 0] = sigmaR**2 priorCovariance[1, 1] = sigmaC**2 priorCovariance[2, 2] = sigmaGamma**2 methods = ["SVD", "QR", "Cholesky"] for method in methods: print("method=", method)
ot.ResourceMap.SetAsUnsignedInteger( 'Distribution-MinimumVolumeLevelSetSamplingSize', 500) # 1-d test dists = [ot.Normal(-1.0, 1.0), ot.Normal(2.0, 1.5)] mixture = ot.Mixture(dists) # 2-d test dists = [ ot.Normal([-1.0, 2.0], [1.0] * 2, ot.CorrelationMatrix(2)), ot.Normal([1.0, -2.0], [1.5] * 2, ot.CorrelationMatrix(2)) ] mixture = ot.Mixture(dists) # 3-d test R1 = ot.CovarianceMatrix(3) R1[2, 1] = -0.25 R2 = ot.CovarianceMatrix(3) R2[1, 0] = 0.5 R2[2, 1] = -0.3 R2[0, 0] = 1.3 print(R2) dists = [ot.Normal([1.0, -2.0, 3.0], R1), ot.Normal([-1.0, 2.0, -2.0], R2)] mixture = ot.Mixture(dists, [2.0 / 3.0, 1.0 / 3.0]) sample = mixture.getSample(1000) distribution = ot.KernelSmoothing().build(sample) algo = ot.MinimumVolumeClassifier(distribution, [0.8]) threshold = algo.getThreshold() print("threshold=", threshold) assert m.fabs(threshold[0] - 0.0012555) < 1e-3, "wrong threshold"
KsInitial = 20. ZvInitial = 49. ZmInitial = 51. parameterPriorMean = [KsInitial, ZvInitial, ZmInitial] paramDim = len(parameterPriorMean) # %% # Define the covariance matrix of the parameters :math:`\vect\theta` to calibrate. # %% sigmaKs = 5. sigmaZv = 1. sigmaZm = 1. # %% parameterPriorCovariance = ot.CovarianceMatrix(paramDim) parameterPriorCovariance[0, 0] = sigmaKs**2 parameterPriorCovariance[1, 1] = sigmaZv**2 parameterPriorCovariance[2, 2] = sigmaZm**2 # %% # Define the the prior distribution :math:`\pi(\vect\theta)` of the parameter :math:`\vect\theta` # %% prior = ot.Normal(parameterPriorMean, parameterPriorCovariance) prior.setDescription(['Ks', 'Zv', 'Zm']) # %% # Define the distribution of observations :math:`\vect{y} | \vect{z}` conditional on model predictions. # # Note that its parameter dimension is the one of :math:`\vect{z}`, so the model must be adjusted accordingly. In other words, the input argument of the `setParameter` method of the conditional distribution must be equal to the dimension of the output of the `model`. Hence, we do not have to set the actual parameters: only the type of distribution is used.
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) vertices = myMesh.getVertices() myCovariance = ot.CovarianceMatrix(len(vertices)) for k in range(len(vertices)): t = vertices[k] for l in range(k + 1): s = vertices[l] myCovariance[k, l] = C(s[0], t[0]) covarianceModel = ot.UserDefinedCovarianceModel(myMesh, myCovariance) cov_graph = covarianceModel.draw(0, 0, -a, a, 512) fig = plt.figure(figsize=(10, 4)) plt.suptitle('User defined covariance model') cov_axis = fig.add_subplot(111) View(cov_graph, figure=fig, axes=[cov_axis], add_legend=False, square_axes=True)
ot.TESTPREAMBLE() ot.PlatformInfo.SetNumericalPrecision(2) m = 10 x = [[0.5 + i] for i in range(m)] inVars = ["a", "b", "c", "x"] formulas = ["a + b * exp(c * x)", "(a * x^2 + b) / (c + x^2)"] model = ot.SymbolicFunction(inVars, formulas) p_ref = [2.8, 1.2, 0.5] params = [0, 1, 2] modelX = ot.ParametricFunction(model, params, p_ref) y = modelX(x) y += ot.Normal([0.0] * 2, [0.05] * 2, ot.IdentityMatrix(2)).getSample(m) candidate = [1.0] * 3 priorCovariance = ot.CovarianceMatrix(3) for i in range(3): priorCovariance[i, i] = 3.0 + (1.0 + i) * (1.0 + i) for j in range(i): priorCovariance[i, j] = 1.0 / (1.0 + i + j) errorCovariance = ot.CovarianceMatrix(2) for i in range(2): errorCovariance[i, i] = 2.0 + (1.0 + i) * (1.0 + i) for j in range(i): errorCovariance[i, j] = 1.0 / (1.0 + i + j) globalErrorCovariance = ot.CovarianceMatrix(2 * m) for i in range(2 * m): globalErrorCovariance[i, i] = 2.0 + (1.0 + i) * (1.0 + i) for j in range(i): globalErrorCovariance[i, j] = 1.0 / (1.0 + i + j) bootstrapSizes = [0, 30]
import openturns as ot ot.Log.Show(ot.Log.NONE) # %% # Create a 2-d ARMA process p = 2 q = 1 dim = 2 # 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 arma = ot.ARMA(ar, ma, whiteNoise) arma # %%
# # Note that its parameter dimension is the one of :math:`\underline{z}`, so the model must be adjusted accordingly # %% conditional = ot.Normal() conditional # %% # - Define the mean :math:`\mu_\theta`, the covariance matrix :math:`\Sigma_\theta`, then the prior distribution :math:`\pi(\underline{\theta})` of the parameter :math:`\underline{\theta}`. # %% thetaPriorMean = [-3., 4., 1.] # %% sigma0 = [2., 1., 1.5] # standard deviations thetaPriorCovarianceMatrix = ot.CovarianceMatrix(paramDim) for i in range(paramDim): thetaPriorCovarianceMatrix[i, i] = sigma0[i]**2 prior = ot.Normal(thetaPriorMean, thetaPriorCovarianceMatrix) prior.setDescription(['theta1', 'theta2', 'theta3']) prior # %% # - Proposal distribution: uniform. # %% proposal = [ot.Uniform(-1., 1.)] * paramDim proposal # %%
refModels = [] # rho correlation scale = [4, 5] rho = ot.GeneralizedExponential(scale, 1) # Amplitude values amplitude = [1, 2] myModel = ot.KroneckerCovarianceModel(rho, amplitude) models.append(myModel) spatialCorrelation = ot.CorrelationMatrix(2) spatialCorrelation[0, 1] = 0.8 myModel = ot.KroneckerCovarianceModel(rho, amplitude, spatialCorrelation) models.append(myModel) spatialCovariance = ot.CovarianceMatrix(2) spatialCovariance[0, 0] = 4.0 spatialCovariance[1, 1] = 5.0 spatialCovariance[1, 0] = 1.2 myModel = ot.KroneckerCovarianceModel(rho, spatialCovariance) models.append(myModel) mesher = ot.IntervalMesher([5, 5]) lowerbound = [-1, -1] upperBound = [2.0, 4.0] interval = ot.Interval(lowerbound, upperBound) mesh = mesher.build(interval) vertices = mesh.getVertices() for k, myModel in enumerate(models):