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)
else: sep = "," if m.fabs(point[i]) < eps: oss += sep + format % m.fabs(point[i]) else: oss += sep + format % point[i] sep = "," oss += "]" return oss # linear levelFunction = ot.NumericalMathFunction(["x1", "x2", "x3", "x4"], ["y1"], ["x1+2*x2-3*x3+4*x4"]) startingPoint = ot.NumericalPoint(4, 0.0) algo = ot.Cobyla(ot.OptimizationProblem(levelFunction, 3.0)) algo.setStartingPoint(startingPoint) print('algo=', algo) algo.run() result = algo.getResult() print('x^=', printNumericalPoint(result.getOptimalPoint(), 4)) # non-linear levelFunction = ot.NumericalMathFunction(["x1", "x2", "x3", "x4"], ["y1"], ["x1*cos(x1)+2*x2*x3-3*x3+4*x3*x4"]) startingPoint = ot.NumericalPoint(4, 0.0) algo = ot.Cobyla(ot.OptimizationProblem(levelFunction, 3.0)) algo.setStartingPoint(startingPoint) algo.setMaximumIterationNumber(400) algo.setMaximumAbsoluteError(1.0e-10) algo.setMaximumRelativeError(1.0e-10)
R = ot.IdentityMatrix(dim) myDistribution = ot.Normal(mean, sigma, R) vect = ot.RandomVector(myDistribution) output = ot.CompositeRandomVector(myFunction, vect) myEvent = ot.ThresholdEvent(output, ot.Less(), -3.0) # %% # **Stop a FORM algorithm using a calls number limit** # # A FORM algorithm termination can be controlled by the maximum number of iterations # # of its underlying optimization solver, but not directly by a maximum number of evaluations. # %% # Create the optimization 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) # %% # Define the stopping criterion def stop(): return myFunction.getCallsNumber() > 100 myCobyla.setStopCallback(stop) # %% # Run FORM
# %% # We define the model model = cb.model # %% # Create the event whose probability we want to estimate. # %% vect = ot.RandomVector(distribution) 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()
# Create the problem and set the optimization algorithm # ----------------------------------------------------- # %% problem = ot.OptimizationProblem(rastrigin) # %% # We use the :class:`~openturns.Cobyla` algorithm and run it from multiple starting points selected by a :class:`~openturns.LowDiscrepancyExperiment`. # %% size = 64 distribution = ot.ComposedDistribution( [ot.Uniform(lowerbound[0], upperbound[0])] * dim) experiment = ot.LowDiscrepancyExperiment( ot.SobolSequence(), distribution, size) solver = ot.MultiStart(ot.Cobyla(problem), experiment.generate()) # %% # Visualize the starting points of the optimization algorithm # ----------------------------------------------------------- # %% startingPoints = solver.getStartingSample() graph = rastrigin.draw(lowerbound, upperbound, [100]*dim) graph.setTitle("Rastrigin function") cloud = ot.Cloud(startingPoints) cloud.setPointStyle("bullet") cloud.setColor("black") graph.add(cloud) graph.setLegends([""]) # sphinx_gallery_thumbnail_number = 2
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)
graph = rosenbrock.draw(lowerbound, upperbound, [100] * 2) graph.setTitle("Rosenbrock function") view = viewer.View(graph) # %% # We see that the minimum is on the top right of the picture and the starting point is on the top left of the picture. Since the function has a long valley following the curve :math:`x_2 - x^2=0`, the algorithm generally have to follow the bottom of the valley. # %% # Create and solve the optimization problem # ----------------------------------------- # %% problem = ot.OptimizationProblem(rosenbrock) # %% algo = ot.Cobyla(problem) algo.setMaximumRelativeError(1.e-1) # on x algo.setMaximumEvaluationNumber(50000) algo.setStartingPoint(x0) algo.run() # %% result = algo.getResult() # %% xoptim = result.getOptimalPoint() xoptim # %% delta = xexact - xoptim absoluteError = delta.norm()
# %% # define the problem bounds dim = objective.getInputDimension() bounds = ot.Interval([-3.] * dim, [5.] * dim) # %% # define the problem problem = ot.OptimizationProblem(objective) problem.setMinimization(True) problem.setInequalityConstraint(inequality_constraint) problem.setBounds(bounds) # %% # solve the problem algo = ot.Cobyla() algo.setProblem(problem) startingPoint = [0.0] * dim algo.setStartingPoint(startingPoint) algo.run() # %% # retrieve results result = algo.getResult() print('x^=', result.getOptimalPoint()) # %% # draw optimal value history graph = result.drawOptimalValueHistory() view = viewer.View(graph) plt.show()
# BipartiteGraph.draw graph = ot.BipartiteGraph([[0, 1, 2], [0, 1, 2]]).draw() view = View(graph) # FORM reliability index marginal parameter sensitivity 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()
else: sep = "," if m.fabs(point[i]) < eps: oss += sep + format % m.fabs(point[i]) else: oss += sep + format % point[i] sep = "," oss += "]" return oss # linear levelFunction = ot.SymbolicFunction( ["x1", "x2", "x3", "x4"], ["x1+2*x2-3*x3+4*x4"]) startingPoint = ot.Point(4, 0.0) algo = ot.Cobyla(ot.NearestPointProblem(levelFunction, 3.0)) algo.setStartingPoint(startingPoint) print('algo=', algo) algo.run() result = algo.getResult() print('x^=', printPoint(result.getOptimalPoint(), 4)) print('f(x^)=', printPoint(result.getOptimalValue(), 4)) print('lambda^=', printPoint(result.computeLagrangeMultipliers(), 4)) # non-linear levelFunction = ot.SymbolicFunction( ["x1", "x2", "x3", "x4"], ["x1*cos(x1)+2*x2*x3-3*x3+4*x3*x4"]) startingPoint = ot.Point(4, 0.0) algo = ot.Cobyla(ot.NearestPointProblem(levelFunction, 3.0)) algo.setStartingPoint(startingPoint) algo.setMaximumEvaluationNumber(400)
mean[3] = 5.0 sigma = [1.0] * dim R = ot.IdentityMatrix(dim) myDistribution = ot.Normal(mean, sigma, R) # We create a 'usual' RandomVector from the Distribution vect = ot.RandomVector(myDistribution) # We create a composite random vector output = ot.CompositeRandomVector(myFunction, vect) # We create an Event from this RandomVector 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)
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