def test_UseCaseMonteCarlo(self): problem = otb.ReliabilityProblem14() event = problem.getEvent() # Create a Monte Carlo algorithm experiment = ot.MonteCarloExperiment() algo = ot.ProbabilitySimulationAlgorithm(event, experiment) algo.setMaximumCoefficientOfVariation(0.01) algo.setBlockSize(int(1.0e3)) algo.setMaximumOuterSampling(int(1e3)) algo.run() # Retrieve results 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.0e2 / np.sqrt(samplesize) np.testing.assert_allclose(computed_pf, exact_pf, atol=atol)
def create_monte_carlo(model, inputRandomVector, coefficient_variation): """Create a Monte Carlo algorithm. Parameters ---------- model : OpenTURNS Function. inputRandomVector : OpenTURNS RandomVector, vector of random inputs. coefficient_variation : Float, target for the coefficient of variation of the estimator. """ outputVariableOfInterest = ot.CompositeRandomVector(model, inputRandomVector) # Create an Event from this RandomVector threshold = 30 myEvent = ot.ThresholdEvent(outputVariableOfInterest, ot.Greater(), threshold) myEvent.setName("Deviation > %g cm" % threshold) # Create a Monte Carlo algorithm experiment = ot.MonteCarloExperiment() myAlgoMonteCarlo = ot.ProbabilitySimulationAlgorithm(myEvent, experiment) myAlgoMonteCarlo.setBlockSize(100) myAlgoMonteCarlo.setMaximumCoefficientOfVariation(coefficient_variation) return myAlgoMonteCarlo
def computeCrossingProbability_MonteCarlo(b, t, mu_S, covariance, R, delta_t, n_block, n_iter, CoV): X, event = getXEvent(b, t, mu_S, covariance, R, delta_t) algo = ot.ProbabilitySimulationAlgorithm(event, ot.MonteCarloExperiment()) algo.setBlockSize(n_block) algo.setMaximumOuterSampling(n_iter) algo.setMaximumCoefficientOfVariation(CoV) algo.run() return algo.getResult().getProbabilityEstimate() / delta_t
def sim_event(ev): experiment = ot.MonteCarloExperiment() algo = ot.ProbabilitySimulationAlgorithm(ev, experiment) algo.setMaximumOuterSampling(2500) algo.setBlockSize(4) algo.setMaximumCoefficientOfVariation(-1.0) algo.run() result = algo.getResult() return result.getProbabilityEstimate()
def computeCrossingProbability_QMC(b, t, mu_S, covariance, R, delta_t, n_block, n_iter, CoV): X, event = getXEvent(b, t, mu_S, covariance, R, delta_t) algo = ot.ProbabilitySimulationAlgorithm( event, ot.LowDiscrepancyExperiment(ot.SobolSequence(X.getDimension()), n_block, False)) algo.setBlockSize(n_block) algo.setMaximumOuterSampling(n_iter) algo.setMaximumCoefficientOfVariation(CoV) algo.run() return algo.getResult().getProbabilityEstimate() / delta_t
def _runMonteCarlo(self, defect): # set a parametric function where the first parameter = given defect g = ot.ParametricFunction(self._metamodel, [0], [defect]) g = ot.MemoizeFunction(g) g.enableHistory() g.clearHistory() g.clearCache() output = ot.CompositeRandomVector(g, ot.RandomVector(self._distribution)) event = ot.ThresholdEvent(output, ot.Greater(), self._detectionBoxCox) ##### Monte Carlo ######## algo_MC = ot.ProbabilitySimulationAlgorithm(event) algo_MC.setMaximumOuterSampling(self._samplingSize) # set negative coef of variation to be sure the stopping criterion is the sampling size algo_MC.setMaximumCoefficientOfVariation(-1) algo_MC.run() return algo_MC.getResult()
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 buildMonteCarlo(self, problem): """ Creates a Monte-Carlo algorithm. We create a MonteCarloExperiment and we create a ProbabilitySimulationAlgorithm based on the problem event. Parameters ---------- problem : ot.ReliabilityBenchmarkProblem The problem. Returns ---------- algo : ot.ProbabilitySimulationAlgorithm The Monte-Carlo algorithm for estimating the probability. """ myEvent = problem.getEvent() experiment = ot.MonteCarloExperiment() algo = ot.ProbabilitySimulationAlgorithm(myEvent, experiment) return algo
def test_UseCase(self): problem = otb.ReliabilityProblem60() event = problem.getEvent() # Create a Monte Carlo algorithm experiment = ot.MonteCarloExperiment() algo = ot.ProbabilitySimulationAlgorithm(event, experiment) algo.setMaximumCoefficientOfVariation(0.05) algo.setMaximumOuterSampling(int(1e5)) algo.run() # Retrieve results 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() print("Sample size : ", samplesize) atol = 1.0 / 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
# %% # From the previous figures we easily deduce that the event :math:`E_6 = E_1 \bigcup (E_2 \bigcap E_3)` # is the event :math:`E_5` and the probability is :math:`P_{E_6} = 3/4`. We can use a basic estimator and get : print("Probability of e6 : %.4f" % e6.getSample(10000).computeMean()[0]) # %% # Usage with a Monte-Carlo algorithm # ---------------------------------- # # Of course, we can use simulation algorithms with this kind of events. # %% # We set up a :class:`~openturns.MonteCarloExperiment` and a :class:`~openturns.ProbabilitySimulationAlgorithm` on the event :math:`E_6`. experiment = ot.MonteCarloExperiment() algo = ot.ProbabilitySimulationAlgorithm(e6, experiment) algo.setMaximumOuterSampling(2500) algo.setBlockSize(4) algo.setMaximumCoefficientOfVariation(-1.0) algo.run() # %% # We retrieve the results and display the approximate probability and a confidence interval : result = algo.getResult() prb = result.getProbabilityEstimate() print("Probability of e6 through MC : %.4f" % prb) cl = result.getConfidenceLength() print("Confidence interval MC : [%.4f, %.4f]" % (prb - 0.5 * cl, prb + 0.5 * cl)) # %%
# MinimumVolumeInterval probability = 0.9 interval = distribution.computeMinimumVolumeIntervalWithMarginalProbability(probability)[ 0] CDF_up = distribution.computeCDF(interval.getUpperBound()) CDF_low = distribution.computeCDF(interval.getLowerBound()) computed_probability = CDF_up - CDF_low ott.assert_almost_equal( probability, computed_probability, 1e-5, 1e-5, str(distribution)) # MinimumVolumeLevelSet probability = 0.9 levelSet, threshold = distribution.computeMinimumVolumeLevelSetWithThreshold( probability) event = ot.DomainEvent(ot.RandomVector(distribution), levelSet) algo = ot.ProbabilitySimulationAlgorithm(event) algo.setBlockSize(int(1e6)) algo.setMaximumOuterSampling(1) algo.run() p = algo.getResult().getProbabilityEstimate() if distribution.getName() != 'Histogram': ott.assert_almost_equal(p, probability, 1e-3, 1e-3, str(distribution)) # parameters p = distribution.getParameter() pd = distribution.getParameterDescription() pc = distribution.getParametersCollection() assert len(p) == len(pd), "len p/pd" assert len(pc) == 1, "len(pc)" assert len(p) == len(pc[0]), "len p/pc"
model = ot.ExponentialModel(scale, amplitude) process = ot.GaussianProcess(model, tgrid) # %% # Create the 1-d domain A: [2.,5.] lowerBound = [2.0] upperBound = [5.0] domain = ot.Interval(lowerBound, upperBound) # %% # Create an event from a Process and a Domain event = ot.ProcessEvent(process, domain) # %% # Create the Monte-Carlo algorithm montecarlo = ot.ProbabilitySimulationAlgorithm(event) # Define the maximum number of simulations montecarlo.setMaximumOuterSampling(1000) # Define the block size montecarlo.setBlockSize(100) # Define the maximum coefficient of variation montecarlo.setMaximumCoefficientOfVariation(0.0025) # Run the algorithm montecarlo.run() # Get the result montecarlo.getResult()
def run_MonteCarlo( event, coefVar=0.1, outerSampling=10000, blockSize=10, seed=1234, verbose=False, failure_domain=None, ): """ Run a Monte Carlo simulation. Parameters ---------- event : openturns.Event The failure event or a list of failure event. coefVar : float The target coefficient of variation. outerSampling : int The maximum number of outer iterations. Nb of iterations = outerSampling x blockSize. blockSize : int The number of samples send to evaluate simultaneously. seed : int Seed for the openturns random generator. logfile : bool Enable or not to write the log in MonteCarlo.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. failure_domain : string Type of failure domain form : either 'union' or 'intersection'. Only needed if the event is a list. """ # case with the limit state defined as an intersection or a # union of the event if type(event) is list: n_event = len(event) antecedent = event[0].getAntecedent() if failure_domain == "union": def function_union(X): sample = ot.NumericalSample(X.getSize(), n_event) for i in range(n_event): sample[:, i] = event[i].getFunction()(X) sample = np.array(sample) for i in range(n_event): if (event[i].getOperator().getImplementation( ).getClassName() == "Less" or event[i].getOperator( ).getImplementation().getClassName() == "LessOrEqual"): sample[:, i] = sample[:, i] < event[i].getThreshold() if (event[i].getOperator().getImplementation( ).getClassName() == "Greater" or event[i].getOperator( ).getImplementation().getClassName() == "GreaterOrEqual"): sample[:, i] = sample[:, i] >= event[i].getThreshold() return np.atleast_2d(sample.sum(axis=1)).T model = ot.PythonFunction( event[0].getFunction().getInputDimension(), event[0].getFunction().getOutputDimension(), func_sample=function_union, ) output = ot.RandomVector(model, antecedent) event = ot.ThresholdEvent(output, ot.Greater(), 0.0) elif failure_domain == "intersection": def function_intersection(X): sample = ot.NumericalSample(X.getSize(), n_event) for i in range(n_event): sample[:, i] = event[i].getFunction()(X) sample = np.array(sample) for i in range(n_event): if (event[i].getOperator().getImplementation( ).getClassName() == "Less" or event[i].getOperator( ).getImplementation().getClassName() == "LessOrEqual"): sample[:, i] = sample[:, i] < event[i].getThreshold() if (event[i].getOperator().getImplementation( ).getClassName() == "Greater" or event[i].getOperator( ).getImplementation().getClassName() == "GreaterOrEqual"): sample[:, i] = sample[:, i] >= event[i].getThreshold() return np.atleast_2d(sample.prod(axis=1)).T model = ot.PythonFunction( event[0].getFunction().getInputDimension(), event[0].getFunction().getOutputDimension(), func_sample=function_intersection, ) output = ot.RandomVector(model, antecedent) new_event = ot.ThresholdEvent(output, ot.Greater(), 0.0) else: model = event.getFunction() new_event = event # Initialize the random generator ot.RandomGenerator.SetSeed(seed) # Run Monte Carlo simulation experiment = ot.MonteCarloExperiment() simulation = ot.ProbabilitySimulationAlgorithm(new_event, experiment) simulation.setMaximumCoefficientOfVariation(coefVar) simulation.setMaximumOuterSampling(outerSampling) simulation.setBlockSize(blockSize) # try: simulation.run() # except Exception as e: # dump_cache(model, 'Cache/physicalModelMathFunction') # raise e result = simulation.getResult() dfResult = pd.DataFrame() dfResult = dfResult.append( pd.DataFrame([result.getProbabilityEstimate()], index=["Probability of failure"])) dfResult = dfResult.append( pd.DataFrame( [result.getCoefficientOfVariation()], index=["Coefficient of varation"], )) dfResult = dfResult.append( pd.DataFrame([result.getConfidenceLength()], index=["95 % Confidence length"])) dfResult = dfResult.append( pd.DataFrame( [result.getOuterSampling() * result.getBlockSize()], index=["Number of calls"], )) dfResult = dfResult.reset_index() dfResult.columns = ["", "Results - Monte Carlo"] if verbose: print(dfResult, "\n") return simulation
def run_ImportanceSampling( event, pstar, sd=1.0, coefVar=0.05, outerSampling=1000, blockSize=10, seed=1234, verbose=False, failure_domain=None, ): """ Run an importance sampling simulation. Parameters ---------- event : openturns.Event The failure event. pstar : list of points Design points in the standard space where to centered the instrumental distribution. sd : positive float The standard deviation of the instrumental distribution. coefVar : float The target coefficient of variation. outerSampling : int The maximum number of outer iterations. Nb of iterations = outerSampling x blockSize. blockSize : int The number of samples send to evaluate simultaneously. seed : int Seed for the openturns random generator. logfile : bool Enable or not to write the log in ImportanceSampling.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. failure_domain : string Type of failure domain form : either 'union' or 'intersection'. Only needed if the event is a list. """ # case with the limit state defined as an intersection # or a union of the event if type(event) is list: n_event = len(event) antecedent = event[0].getAntecedent() if failure_domain == "union": def function_union(X): sample = ot.NumericalSample(X.getSize(), n_event) for i in range(n_event): sample[:, i] = event[i].getFunction()(X) sample = np.array(sample) for i in range(n_event): if (event[i].getOperator().getImplementation( ).getClassName() == "Less" or event[i].getOperator( ).getImplementation().getClassName() == "LessOrEqual"): sample[:, i] = sample[:, i] < event[i].getThreshold() if (event[i].getOperator().getImplementation( ).getClassName() == "Greater" or event[i].getOperator( ).getImplementation().getClassName() == "GreaterOrEqual"): sample[:, i] = sample[:, i] >= event[i].getThreshold() return np.atleast_2d(sample.sum(axis=1)).T model = ot.PythonFunction( event[0].getFunction().getInputDimension(), event[0].getFunction().getOutputDimension(), func_sample=function_union, ) output = ot.RandomVector(model, antecedent) event = ot.ThresholdEvent(output, ot.Greater(), 0.0) elif failure_domain == "intersection": def function_intersection(X): sample = ot.NumericalSample(X.getSize(), n_event) for i in range(n_event): sample[:, i] = event[i].getFunction()(X) sample = np.array(sample) for i in range(n_event): if (event[i].getOperator().getImplementation( ).getClassName() == "Less" or event[i].getOperator( ).getImplementation().getClassName() == "LessOrEqual"): sample[:, i] = sample[:, i] < event[i].getThreshold() if (event[i].getOperator().getImplementation( ).getClassName() == "Greater" or event[i].getOperator( ).getImplementation().getClassName() == "GreaterOrEqual"): sample[:, i] = sample[:, i] >= event[i].getThreshold() return np.atleast_2d(sample.prod(axis=1)).T model = ot.PythonFunction( event[0].getFunction().getInputDimension(), event[0].getFunction().getOutputDimension(), func_sample=function_intersection, ) output = ot.RandomVector(model, antecedent) new_event = ot.ThresholdEvent(output, ot.Greater(), 0.0) else: model = event.getFunction() new_event = event # Initialize the random generator ot.RandomGenerator.SetSeed(seed) dim = model.getInputDimension() pstar = np.atleast_2d(pstar) nPoint = pstar.shape[0] stdev = [sd] * dim corr = ot.IdentityMatrix(dim) if nPoint > 1: distribution_list = list() for point in pstar: distribution_list.append(ot.Normal(point, stdev, corr)) instrumental_distribution = ot.Mixture(distribution_list) elif nPoint == 1: instrumental_distribution = ot.Normal(pstar[0], stdev, corr) # Run importance sampling simulation experiment = ot.ImportanceSamplingExperiment(instrumental_distribution) simulation = ot.ProbabilitySimulationAlgorithm(ot.StandardEvent(new_event), experiment) simulation.setMaximumOuterSampling(outerSampling) simulation.setBlockSize(blockSize) simulation.setMaximumCoefficientOfVariation(coefVar) # try: simulation.run() # except Exception as e: # dump_cache(model, 'Cache/physicalModelMathFunction') # raise e result = simulation.getResult() dfResult = pd.DataFrame() dfResult = dfResult.append( pd.DataFrame([result.getProbabilityEstimate()], index=["Probability of failure"])) dfResult = dfResult.append( pd.DataFrame( [result.getCoefficientOfVariation()], index=["Coefficient of varation"], )) dfResult = dfResult.append( pd.DataFrame([result.getConfidenceLength()], index=["95 % Confidence length"])) dfResult = dfResult.append( pd.DataFrame( [result.getOuterSampling() * result.getBlockSize()], index=["Number of calls"], )) dfResult = dfResult.reset_index() dfResult.columns = ["", "Results - Importance Sampling"] if verbose: print(dfResult, "\n") return simulation
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)
# # Estimation of the event probability using (crude) Monte Carlo sampling # In[18]: g.clearHistory() # In[19]: ot.RandomGenerator.SetSeed(0) # In[20]: # create a Monte Carlo algorithm experiment = ot.MonteCarloExperiment() MCS_algorithm = ot.ProbabilitySimulationAlgorithm(event, experiment) MCS_algorithm.setMaximumCoefficientOfVariation(.1) MCS_algorithm.setMaximumOuterSampling(40000) MCS_algorithm.setBlockSize(100) MCS_algorithm.run() MCS_results = MCS_algorithm.getResult() MCS_evaluation_number = g.getInputHistory().getSize() # In[21]: print('Probability estimate: %.3e' % MCS_results.getProbabilityEstimate()) print('Coefficient of variation: %.2f' % MCS_results.getCoefficientOfVariation()) print('Number of evaluations: %d' % MCS_evaluation_number) # In[22]:
# %% inputRandomVector = ot.RandomVector(myDistribution) outputRandomVector = ot.CompositeRandomVector( limitStateFunction, inputRandomVector) myEvent = ot.ThresholdEvent(outputRandomVector, ot.Less(), 0.0) # %% # Using Monte Carlo simulations # ----------------------------- # %% cv = 0.05 NbSim = 100000 experiment = ot.MonteCarloExperiment() algoMC = ot.ProbabilitySimulationAlgorithm(myEvent, experiment) algoMC.setMaximumOuterSampling(NbSim) algoMC.setBlockSize(1) algoMC.setMaximumCoefficientOfVariation(cv) # %% # For statistics about the algorithm initialNumberOfCall = limitStateFunction.getEvaluationCallsNumber() # %% # Perform the analysis. # %% algoMC.run() # %%
# vect = ot.RandomVector(myDistribution) output = ot.CompositeRandomVector(limitState, vect) myEvent = ot.ThresholdEvent(output, ot.Less(), 0.0) # # Computation # bs = 1 # Monte Carlo experiment = ot.MonteCarloExperiment() myMC = ot.ProbabilitySimulationAlgorithm(myEvent, experiment) myMC.setMaximumOuterSampling(int(1e6) // bs) myMC.setBlockSize(bs) myMC.setMaximumCoefficientOfVariation(-1.0) myMC.run() # # SubsetSampling mySS = ot.SubsetSampling(myEvent) mySS.setMaximumOuterSampling(10000 // bs) mySS.setBlockSize(bs) mySS.setKeepEventSample(True) mySS.run() # # Results
# 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) myAlgo.setMaximumCoefficientOfVariation(-1.0) # %% # Define the stopping criterion timer = ot.TimerCallback(0.01) myAlgo.setStopCallback(timer) # %% # Run algorithm myAlgo.run() result = myAlgo.getResult() print('event probability:', result.getProbabilityEstimate()) print('calls number:', myFunction.getCallsNumber())
# 1. Composite/Composite f1 = ot.SymbolicFunction(['x'+str(i) for i in range(dim)], ['x0']) f2 = ot.SymbolicFunction(['x'+str(i) for i in range(dim)], ['x1']) Y1 = ot.CompositeRandomVector(f1, X) Y2 = ot.CompositeRandomVector(f2, X) e1 = ot.Event(Y1, ot.Less(), 0.0) e2 = ot.Event(Y2, ot.Greater(), 0.0) e3 = e1.intersect(e2) #print('e3=', e3) # sampling test algo = ot.ProbabilitySimulationAlgorithm(e3) algo.setMaximumOuterSampling(250) algo.setBlockSize(4) algo.setMaximumCoefficientOfVariation(-0.1) algo.run() print("proba_e3 = %.3g" % algo.getResult().getProbabilityEstimate()) e4 = e1.join(e2) #print('e4=', e4) # sampling test algo = ot.ProbabilitySimulationAlgorithm(e4) algo.setMaximumOuterSampling(250) algo.setBlockSize(4) algo.setMaximumCoefficientOfVariation(-0.1)