def test_UseCaseFORM(self): problem = otb.ReliabilityProblem14() event = problem.getEvent() distribution = event.getAntecedent().getDistribution() # We create a NearestPoint algorithm myCobyla = ot.Cobyla() # Resolution options: eps = 1e-3 myCobyla.setMaximumEvaluationNumber(100) myCobyla.setMaximumAbsoluteError(eps) myCobyla.setMaximumRelativeError(eps) myCobyla.setMaximumResidualError(eps) myCobyla.setMaximumConstraintError(eps) # For statistics about the algorithm algo = ot.FORM(myCobyla, event, distribution.getMean()) algo.run() resultFORM = algo.getResult() # Combine with Importance Sampling standardSpaceDesignPoint = resultFORM.getStandardSpaceDesignPoint() dimension = distribution.getDimension() myImportance = ot.Normal(dimension) myImportance.setMean(standardSpaceDesignPoint) experiment = ot.ImportanceSamplingExperiment(myImportance) standardEvent = ot.StandardEvent(event) algo = ot.ProbabilitySimulationAlgorithm(standardEvent, experiment) algo.setMaximumCoefficientOfVariation(0.01) algo.setBlockSize(int(1.0e3)) algo.setMaximumOuterSampling(int(1e3)) algo.run() result = algo.getResult() computed_pf = result.getProbabilityEstimate() exact_pf = problem.getProbability() print("exact_pf=", exact_pf) print("computed_pf=", computed_pf) samplesize = result.getOuterSampling() * result.getBlockSize() alpha = 0.05 pflen = result.getConfidenceLength(1 - alpha) print( "%.2f%% confidence interval = [%f,%f]" % ((1 - alpha) * 100, computed_pf - pflen / 2, computed_pf + pflen / 2) ) print("Sample size : ", samplesize) atol = 1.0e1 / np.sqrt(samplesize) np.testing.assert_allclose(computed_pf, exact_pf, atol=atol)
def buildFORMIS(self, problem, nearestPointAlgorithm): """ Creates a FORM-IS algorithm. We first create a FORM object based on the AbdoRackwitz and run it to get the design point in the standard space. Then we create an ImportanceSamplingExperiment based on the gaussian distribution, centered on the design point. Finally, we create a ProbabilitySimulationAlgorithm. Parameters ---------- problem : ot.ReliabilityBenchmarkProblem The problem. nearestPointAlgorithm : ot.OptimizationAlgorithm Optimization algorithm used to search the design point. Returns ---------- algo : ot.ProbabilitySimulationAlgorithm The FORM-IS algorithm for estimating the probability. """ event = problem.getEvent() inputVector = event.getAntecedent() myDistribution = inputVector.getDistribution() physicalStartingPoint = myDistribution.getMean() algoFORM = ot.FORM(nearestPointAlgorithm, event, physicalStartingPoint) algoFORM.run() resultFORM = algoFORM.getResult() standardSpaceDesignPoint = resultFORM.getStandardSpaceDesignPoint() d = myDistribution.getDimension() myImportance = ot.Normal(d) myImportance.setMean(standardSpaceDesignPoint) experiment = ot.ImportanceSamplingExperiment(myImportance) standardEvent = ot.StandardEvent(event) algo = ot.ProbabilitySimulationAlgorithm(standardEvent, experiment) return algo
eps = 1e-3 myCobyla.setMaximumEvaluationNumber(100) myCobyla.setMaximumAbsoluteError(eps) myCobyla.setMaximumRelativeError(eps) myCobyla.setMaximumResidualError(eps) myCobyla.setMaximumConstraintError(eps) # %% # For statistics about the algorithm initialNumberOfCall = limitStateFunction.getEvaluationCallsNumber() # %% # We create a FORM algorithm. The first parameter is a NearestPointAlgorithm. The second parameter is an event. The third parameter is a starting point for the design point research. # %% algoFORM = ot.FORM(myCobyla, myEvent, myDistribution.getMean()) # %% # Perform the analysis. # %% algoFORM.run() # %% resultFORM = algoFORM.getResult() numberOfFunctionEvaluationsFORM = limitStateFunction.getEvaluationCallsNumber() - \ initialNumberOfCall probabilityFORM = resultFORM.getEventProbability() print('Number of calls to the limit state =', numberOfFunctionEvaluationsFORM) print('Pf =', probabilityFORM)
#create the event we want to estimate the probability vect = ot.RandomVector(distribution) G = ot.CompositeRandomVector(dijk.Z_function, vect) event = ot.Event(G, ot.Less(), 0.0) event.setName('overall failure') #define a solver optimAlgo = ot.Cobyla() optimAlgo.setMaximumEvaluationNumber(n) optimAlgo.setMaximumAbsoluteError(1.0e-10) optimAlgo.setMaximumRelativeError(1.0e-10) optimAlgo.setMaximumResidualError(1.0e-10) optimAlgo.setMaximumConstraintError(1.0e-10) #set-up algorithm algo_u = ot.FORM(optimAlgo, event_u, distribution_u.getMean()) algo_h = ot.FORM(optimAlgo, event_h, distribution_h.getMean()) algo_p = ot.FORM(optimAlgo, event_p, distribution_p.getMean()) algo = ot.FORM(optimAlgo, event, distribution.getMean()) for h in data_h: dijk.h = h initialNumberOfCall_u = dijk.Z_u_function.getEvaluationCallsNumber() initialNumberOfCall_h = dijk.Z_h_function.getEvaluationCallsNumber() initialNumberOfCall_p = dijk.Z_p_function.getEvaluationCallsNumber() initialNumberOfCall = dijk.Z_function.getEvaluationCallsNumber() #%% FORM #run FORM uplift
ot.Interval([low] * 2, [up] * 2, [False, True], [True, False]), ot.Interval([low] * 2, [up] * 2, [False, True], [False, True]), ot.Interval([low] * 2, [up] * 2, [False, True], [False, False]), ot.Interval([low] * 2, [up] * 2, [False, False], [True, True]), ot.Interval([low] * 2, [up] * 2, [False, False], [True, False]), ot.Interval([low] * 2, [up] * 2, [False, False], [False, True]), ot.Interval([low] * 2, [up] * 2, [False, False], [False, False]) ] for domain in intervals: print('#' * 50) print('domain=\n', domain) outDim = domain.getDimension() f = ot.SymbolicFunction(inVars, inVars[0:outDim]) Y = ot.CompositeRandomVector(f, X) event = ot.ThresholdEvent(Y, domain) ot.RandomGenerator.SetSeed(0) # algo = getattr(openturns, algoName)(event) algo = ot.ProbabilitySimulationAlgorithm(event, ot.MonteCarloExperiment()) algo.run() res = algo.getResult().getProbabilityEstimate() print('MC p=%.6g' % res) ot.RandomGenerator.SetSeed(0) # algo = getattr(openturns, algoName)(event) algo = ot.FORM(ot.Cobyla(), event, X.getMean()) algo.run() res = algo.getResult().getEventProbability() print('FORM p=%.2f' % res)
algo.run() result = algo.getResult() print('x^=', printNumericalPoint( result.getOptimalPoint(), 3)) except: print('-- Not supported: algo=', algoName, 'inequality=', inequality, 'equality=', equality) # FORM f = ot.NumericalMathFunction( ["E", "F", "L", "I"], ["d"], ["-F*L^3/(3*E*I)"]) dim = f.getInputDimension() mean = [50.0, 1.0, 10.0, 5.0] sigma = ot.NumericalPoint(dim, 1.0) R = ot.IdentityMatrix(dim) distribution = ot.Normal(mean, sigma, R) vect = ot.RandomVector(distribution) output = ot.RandomVector(f, vect) myEvent = ot.Event(output, ot.Less(), -3.0) solver = ot.NLopt('LD_AUGLAG') solver.setMaximumIterationNumber(400) solver.setMaximumAbsoluteError(1.0e-10) solver.setMaximumRelativeError(1.0e-10) solver.setMaximumResidualError(1.0e-10) solver.setMaximumConstraintError(1.0e-10) algo = ot.FORM(solver, myEvent, mean) algo.run() result = algo.getResult() print('generalized reliability index=%.6f' % result.getGeneralisedReliabilityIndex())
output = ot.CompositeRandomVector(model, inputVector) output.setName("MyOutputY") # %% # Create the physical event Y > 4 threshold = 4 myEvent = ot.ThresholdEvent(output, ot.Greater(), threshold) # Create the associated standard event in the standard space myStandardEvent = ot.StandardEvent(myEvent) # %% # First : FORM analyses to get the design point myCobyla = ot.Cobyla() myStartingPoint = inputDist.getMean() myAlgoFORM = ot.FORM(myCobyla, myEvent, myStartingPoint) myAlgoFORM.run() FORMResult = myAlgoFORM.getResult() standardSpaceDesignPoint = FORMResult.getStandardSpaceDesignPoint() # %% # Fix the importance level epsilon of the test # Care : 0<epsilon<1 importanceLevel = 0.15 # Fix the accuracy level tau of the test # Care : tau >0 # It is recommended that tau <4 accuracyLevel = 3.0 # Fix the confidence level (1-q) of the test
f = ot.SymbolicFunction(['E', 'F', 'L', 'I'], ['-F*L^3/(3*E*I)']) dim = f.getInputDimension() mean = [50.0, 1.0, 10.0, 5.0] sigma = ot.Point(dim, 1.0) R = ot.IdentityMatrix(dim) distribution = ot.Normal(mean, sigma, R) vect = ot.RandomVector(distribution) output = ot.CompositeRandomVector(f, vect) event = ot.ThresholdEvent(output, ot.Less(), -3.0) solver = ot.Cobyla() solver.setMaximumEvaluationNumber(400) solver.setMaximumAbsoluteError(1.0e-10) solver.setMaximumRelativeError(1.0e-10) solver.setMaximumResidualError(1.0e-10) solver.setMaximumConstraintError(1.0e-10) algo = ot.FORM(solver, event, mean) algo.run() result = algo.getResult() marginalSensitivity, otherSensitivity = result.drawHasoferReliabilityIndexSensitivity( ) view = View(marginalSensitivity) # Optimization error history opt_result = result.getOptimizationResult() graph = opt_result.drawErrorHistory() view = View(graph) view.ShowAll(block=True) # GridLayout grid = ot.GridLayout(2, 3) palette = ot.Drawable.BuildDefaultPalette(10)
inputDist = ot.Normal([0., 0.], R) inputDist.setDescription(['X1', 'X2']) inputVector = ot.RandomVector(inputDist) # Create the output random vector Y=model(X) Y = ot.CompositeRandomVector(model, inputVector) # Create the event Y > 4 threshold = 4.0 event = ot.ThresholdEvent(Y, ot.Greater(), threshold) # %% # Create a FORM algorithm solver = ot.Cobyla() startingPoint = inputDist.getMean() algo = ot.FORM(solver, event, startingPoint) # Run the algorithm and retrieve the result algo.run() result_form = algo.getResult() # %% # Create the post analytical importance sampling simulation algorithm algo = ot.PostAnalyticalImportanceSampling(result_form) algo.run() algo.getResult() # %% # Create the post analytical controlled importance sampling simulation algorithm algo = ot.PostAnalyticalControlledImportanceSampling(result_form) algo.run()
mpfp_search_algorithm.setMaximumIterationNumber(int(1e3)) mpfp_search_algorithm.setMaximumAbsoluteError(1e-10) mpfp_search_algorithm.setMaximumRelativeError(1e-10) mpfp_search_algorithm.setMaximumResidualError(1e-10) mpfp_search_algorithm.setMaximumConstraintError(1e-10) print(mpfp_search_algorithm) # ## *First-order-reliability-method* (FORM) # In[24]: g.clearHistory() # In[25]: FORM_algorithm = ot.FORM(mpfp_search_algorithm, event, X_distribution.getMean()) FORM_algorithm.run() FORM_result = FORM_algorithm.getResult() # In[26]: mpfp_search_result = FORM_result.getOptimizationResult() _ = View(mpfp_search_result.drawErrorHistory()) # In[27]: print("Standard space design point: %s" % FORM_result.getStandardSpaceDesignPoint()) print("Physical space design point: %s" % FORM_result.getPhysicalSpaceDesignPoint()) print("Hasofer-Lind reliability index: %.2f" %
myEvent = ot.ThresholdEvent(output, ot.Less(), -3.0) # We create a NearestPoint algorithm myCobyla = ot.Cobyla() myCobyla.setMaximumEvaluationNumber(400) myCobyla.setMaximumAbsoluteError(1.0e-10) myCobyla.setMaximumRelativeError(1.0e-10) myCobyla.setMaximumResidualError(1.0e-10) myCobyla.setMaximumConstraintError(1.0e-10) print("myCobyla=", myCobyla) # We create a FORM algorithm # The first parameter is an OptimizationAlgorithm # The second parameter is an event # The third parameter is a starting point for the design point research myAlgo = ot.FORM(myCobyla, myEvent, mean) print("FORM=", myAlgo) # Perform the simulation myAlgo.run() # Stream out the iresult result = myAlgo.getResult() digits = 5 print("event probability=%.6f" % result.getEventProbability()) print("generalized reliability index=%.6f" % result.getGeneralisedReliabilityIndex()) print("standard space design point=", printPoint(result.getStandardSpaceDesignPoint(), digits)) print("physical space design point=",
def run_FORM_simple( event, inputDistribution, nearestPointAlgo="AbdoRackwitz", NmaxIteration=100, eps=[1e-5] * 4, physicalStartingPoint=None, seed=1234, verbose=False, ): """ Run a FORM approximation. Parameters ---------- event : openturns.Event The failure event. inputDistribution : openturns.distribution The distribution of the event. nearestPointAlgo : str Type of the optimization algorithm. It must be 'AbdoRackwitz', 'SQP' or 'Cobyla'. NmaxIteration : int The maximum number of iterations. eps = sequence of float The stopping criterion value of the optimization algorithm. Order is absolute error, relative error, residual error, constraint error. physicalStartingPoint : sequence of float The starting point of the algorithm. Default is the median values. seed : int Seed for the openturns random generator. logfile : bool Enable or not to write the log in FORM.log file. verbose : bool Enable or not the display of the result. activeCache : bool Enable or not the cache mechanism of the NumericalMathFunction. activeHistory : bool Enable or not the history mechanism of the NumericalMathFunction. """ # Initialize the random generator ot.RandomGenerator.SetSeed(seed) # Defintion of the nearest point algorithm if nearestPointAlgo == "AbdoRackwitz": solver = ot.AbdoRackwitz() # spec = algo.getSpecificParameters() # spec.setTau(0.5) # algo.setSpecificParameters(spec) elif nearestPointAlgo == "Cobyla": solver = ot.Cobyla() elif nearestPointAlgo == "SQP": solver = ot.SQP() else: raise NameError("Nearest point algorithm name must be \ 'AbdoRackwitz', 'Cobyla' or 'SQP'.") eps = np.array(eps) solver.setMaximumAbsoluteError(eps[0]) solver.setMaximumRelativeError(eps[1]) solver.setMaximumResidualError(eps[2]) solver.setMaximumConstraintError(eps[3]) solver.setMaximumIterationNumber(NmaxIteration) # Set the physical starting point of the Nearest point # algorithm to the mediane value if physicalStartingPoint is None: physicalStartingPoint = inputDistribution.getMean() # Run FORM method approximation = ot.FORM(solver, event, physicalStartingPoint) approximation.run() result = approximation.getResult() optimResult = result.getOptimizationResult() iter_number = optimResult.getIterationNumber() dfResult = pd.DataFrame() dfResult = dfResult.append( pd.DataFrame([result.getEventProbability()], index=["Probability of failure"])) dfResult = dfResult.append( pd.DataFrame( [result.getGeneralisedReliabilityIndex()], index=["Generalised reliability index"], )) dfResult = dfResult.append( pd.DataFrame([iter_number], index=["Number of iterations"])) dfResult = dfResult.append( pd.DataFrame( [result.getStandardSpaceDesignPoint()], index=["Standard space design point"], )) dfResult = dfResult.append( pd.DataFrame( [result.getPhysicalSpaceDesignPoint()], index=["Physical space design point"], )) dfResult = dfResult.reset_index() dfResult.columns = ["", "Results - FORM (" + nearestPointAlgo + ")"] pd.options.display.float_format = "{:,.2E}".format if verbose: print(dfResult, "\n") return approximation
from __future__ import print_function import openturns as ot ot.TESTPREAMBLE() model = ot.SymbolicFunction(['x0', 'x1', 'x2', 'x3'], ['-(6+x0^2-x1+x2+3*x3)']) dim = model.getInputDimension() marginals = [ot.Normal(5.0, 3.0) for i in range(dim)] distribution = ot.ComposedDistribution( marginals, ot.ComposedCopula([ot.ClaytonCopula(), ot.NormalCopula()])) #distribution = ot.Normal([5]*dim, [3]*dim, ot.CorrelationMatrix(dim)) #distribution = ot.ComposedDistribution(marginals, ot.IndependentCopula(dim)) distribution.setDescription(['marginal' + str(i) for i in range(dim)]) vect = ot.RandomVector(distribution) output = ot.CompositeRandomVector(model, vect) event = ot.Event(output, ot.Greater(), 0.0) solver = ot.Cobyla() solver.setMaximumEvaluationNumber(200) solver.setMaximumAbsoluteError(1.0e-10) solver.setMaximumRelativeError(1.0e-10) solver.setMaximumResidualError(1.0e-10) solver.setMaximumConstraintError(1.0e-10) algo = ot.FORM(solver, event, distribution.getMean()) algo.run() result = algo.getResult() hasoferReliabilityIndexSensitivity = result.getHasoferReliabilityIndexSensitivity( ) print(hasoferReliabilityIndexSensitivity)
G = ot.CompositeRandomVector(model, vect) event = ot.ThresholdEvent(G, ot.Greater(), 0.3) event.setName("deviation") # %% # Define a solver optimAlgo = ot.Cobyla() optimAlgo.setMaximumEvaluationNumber(1000) optimAlgo.setMaximumAbsoluteError(1.0e-10) optimAlgo.setMaximumRelativeError(1.0e-10) optimAlgo.setMaximumResidualError(1.0e-10) optimAlgo.setMaximumConstraintError(1.0e-10) # %% # Run FORM algo = ot.FORM(optimAlgo, event, distribution.getMean()) algo.run() result = algo.getResult() # %% # Probability result.getEventProbability() # %% # Hasofer reliability index result.getHasoferReliabilityIndex() # %% # Design point in the standard U* space. # %%
# minimization problem under constraints. # # %% # We configure the Cobyla solver that we use for the optimization : solver = ot.Cobyla() solver.setMaximumIterationNumber(10000) solver.setMaximumAbsoluteError(1.0e-3) solver.setMaximumRelativeError(1.0e-3) solver.setMaximumResidualError(1.0e-3) solver.setMaximumConstraintError(1.0e-3) # %% # We build the FORM algorithm with its basic constructor. The starting point for the optimization # algorithm is the mean of the input variables. algoFORM = ot.FORM(solver, event, distX.getMean()) # %% # We are ready to run the algorithm and store the result : algoFORM.run() result = algoFORM.getResult() # %% # The design point can be retrieved in both physical and standard space with respectively the # `getPhysicalSpaceDesignPoint` and `getStandardSpaceDesignPoint` methods. designPointPhysicalSpace = result.getPhysicalSpaceDesignPoint() designPointStandardSpace = result.getStandardSpaceDesignPoint() print("Design point in physical space : ", designPointPhysicalSpace) print("Design point in standard space : ", designPointStandardSpace) # %%
myCobyla.setMaximumEvaluationNumber(400) myCobyla.setMaximumAbsoluteError(1.0e-10) myCobyla.setMaximumRelativeError(1.0e-10) myCobyla.setMaximumResidualError(1.0e-10) myCobyla.setMaximumConstraintError(1.0e-10) # %% # Define the stopping criterion def stop(): return myFunction.getCallsNumber() > 100 myCobyla.setStopCallback(stop) # %% # Run FORM myAlgo = ot.FORM(myCobyla, myEvent, mean) myAlgo.run() result = myAlgo.getResult() print('event probability:', result.getEventProbability()) print('calls number:', myFunction.getCallsNumber()) # %% # **Stop a simulation algorithm using a time limit** # # Here we will create a callback to not exceed a specified simulation time. # %% # Create simulation experiment = ot.MonteCarloExperiment() myAlgo = ot.ProbabilitySimulationAlgorithm(myEvent, experiment) myAlgo.setMaximumOuterSampling(1000000)
# Define a solver. # %% optimAlgo = ot.Cobyla() optimAlgo.setMaximumEvaluationNumber(1000) optimAlgo.setMaximumAbsoluteError(1.0e-10) optimAlgo.setMaximumRelativeError(1.0e-10) optimAlgo.setMaximumResidualError(1.0e-10) optimAlgo.setMaximumConstraintError(1.0e-10) # %% # Run FORM. # %% startingPoint = distribution.getMean() algo = ot.FORM(optimAlgo, event, startingPoint) algo.run() result = algo.getResult() standardSpaceDesignPoint = result.getStandardSpaceDesignPoint() # %% # Retrieve results. # %% result = algo.getResult() probability = result.getEventProbability() print('Pf=', probability) # %% # Importance factors.