{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Control algorithm termination"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this examples we are going to expose ways to control the termination of optimization and simulation algorithms using callbacks.\n",
    "    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "from __future__ import print_function\n",
    "import openturns as ot\n",
    "import math as m\n",
    "import time"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Define an event to compute a probability\n",
    "myFunction = ot.SymbolicFunction(['E', 'F', 'L', 'I'], ['-F*L^3/(3.0*E*I)'])\n",
    "dim = myFunction.getInputDimension()\n",
    "mean = [50.0, 1.0, 10.0, 5.0]\n",
    "sigma = [1.0] * dim\n",
    "R = ot.IdentityMatrix(dim)\n",
    "myDistribution = ot.Normal(mean, sigma, R)\n",
    "vect = ot.RandomVector(myDistribution)\n",
    "output = ot.RandomVector(myFunction, vect)\n",
    "myEvent = ot.Event(output, ot.Less(), -3.0)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Stop a FORM algorithm using a calls number limit**\n",
    "\n",
    "A FORM algorithm termination can be controlled by the maximum number of iterations\n",
    "\n",
    "of its underlying optimization solver, but not directly by a maximum number of evaluations."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create the optimization algorithm\n",
    "myCobyla = ot.Cobyla()\n",
    "myCobyla.setMaximumIterationNumber(400)\n",
    "myCobyla.setMaximumAbsoluteError(1.0e-10)\n",
    "myCobyla.setMaximumRelativeError(1.0e-10)\n",
    "myCobyla.setMaximumResidualError(1.0e-10)\n",
    "myCobyla.setMaximumConstraintError(1.0e-10)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Define the stopping criterion\n",
    "def stop():\n",
    "    return myFunction.getCallsNumber() > 100\n",
    "myCobyla.setStopCallback(stop)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "event probability: 0.15642619199519514\n",
      "calls number: 102\n"
     ]
    }
   ],
   "source": [
    "# Run FORM\n",
    "myAlgo = ot.FORM(myCobyla, myEvent, mean)\n",
    "myAlgo.run()\n",
    "result = myAlgo.getResult()\n",
    "print('event probability:', result.getEventProbability())\n",
    "print('calls number:', myFunction.getCallsNumber())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Stop a simulation algorithm using a time limit**\n",
    "\n",
    "Here we will create a callback to not exceed a specified simulation time."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Create simulation\n",
    "experiment = ot.MonteCarloExperiment()\n",
    "myAlgo = ot.ProbabilitySimulationAlgorithm(myEvent, experiment)\n",
    "myAlgo.setMaximumOuterSampling(1000000)\n",
    "myAlgo.setMaximumCoefficientOfVariation(-1.0)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# Define the stopping criterion\n",
    "def TimerStop(duration):\n",
    "    def inner():\n",
    "        delta = time.clock() - inner.t0\n",
    "        return delta > duration\n",
    "    inner.t0 = time.clock()\n",
    "    return inner\n",
    "myAlgo.setStopCallback(TimerStop(0.01))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "event probability: 0.17045454545454541\n",
      "calls number: 190\n"
     ]
    }
   ],
   "source": [
    "# Run algorithm\n",
    "myAlgo.run()\n",
    "result = myAlgo.getResult()\n",
    "print('event probability:', result.getProbabilityEstimate())\n",
    "print('calls number:', myFunction.getCallsNumber())"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
