Control algorithm termination

In this examples we are going to expose ways to control the termination of optimization and simulation algorithms using callbacks.

In [1]:
from __future__ import print_function
import openturns as ot
import math as m
import time
In [2]:
# Define an event to compute a probability
myFunction = ot.SymbolicFunction(['E', 'F', 'L', 'I'], ['-F*L^3/(3.0*E*I)'])
dim = myFunction.getInputDimension()
mean = [50.0, 1.0, 10.0, 5.0]
sigma = [1.0] * dim
R = ot.IdentityMatrix(dim)
myDistribution = ot.Normal(mean, sigma, R)
vect = ot.RandomVector(myDistribution)
output = ot.RandomVector(myFunction, vect)
myEvent = ot.Event(output, ot.Less(), -3.0)

1. 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.

In [3]:
# Create the optimization algorithm
myCobyla = ot.Cobyla()
In [4]:
# Define the stopping criterion
def stop():
    return myFunction.getCallsNumber() > 100
In [5]:
# Run FORM
myAlgo = ot.FORM(myCobyla, myEvent, mean)
result = myAlgo.getResult()
print('event probability:', result.getEventProbability())
print('calls number:', myFunction.getCallsNumber())
event probability: 0.15642619199519514
calls number: 102

2. Stop a simulation algorithm using a time limit

Here we will create a callback to not exceed a specified simulation time.

In [6]:
# Create simulation
experiment = ot.MonteCarloExperiment()
myAlgo = ot.ProbabilitySimulationAlgorithm(myEvent, experiment)
In [7]:
# Define the stopping criterion
def TimerStop(duration):
    def inner():
        delta = time.clock() - inner.t0
        return delta > duration
    inner.t0 = time.clock()
    return inner
In [8]:
# Run algorithm
result = myAlgo.getResult()
print('event probability:', result.getProbabilityEstimate())
print('calls number:', myFunction.getCallsNumber())
event probability: 0.16666666666666669
calls number: 276