{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "12ae9bb2",
   "metadata": {},
   "source": [
    "\n",
    "File: 02-monte-carlo.py\n",
    "\n",
    "\n",
    "Michel Bierlaire\n",
    "\n",
    "Tue Aug 05 2025, 15:54:04\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "b2abd7d8",
   "metadata": {},
   "source": [
    "The objective of this laboratory is to illustrate the use of Monte-Carlo integration to calculate a mixture of\n",
    "logit models."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c458e6ce",
   "metadata": {},
   "source": [
    "We consider a simple binary choice model, with the following utility\n",
    "functions:\n",
    "\n",
    "- Alternative 1: $V_class_1 = 0$\n",
    "- Alternative 2: $V_class_2 = -\\beta x$.\n",
    "\n",
    "The exact value of $\\beta$ is not known. It is known to be distributed across the population, following a normal distribution:\n",
    "$$\\beta \\sim N(-1, 3^2).$$"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "dea3e4f3",
   "metadata": {},
   "source": [
    "The following functions calculate the choice probability :\n",
    "\\[\n",
    "P(1|x) = \\int_{\\beta=-\\infty}^{+\\infty}\\frac{1}{1 + e^{-\\beta x}} f(\\beta) d\\beta,\n",
    "\\]\n",
    "where $f$ is the pdf of the normal distribution. We want to calculate\n",
    "this probability for $x=1$."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "1da2accf",
   "metadata": {},
   "source": [
    "- Calculate the value using a quadrature method. For instance,\n",
    "the `quad` method from the Python package `scipy.integrate`.\n",
    "- Approximate the value using Monte-Carlo integration with 50000 draws.\n",
    "- Plot the value of the approximation as a function of the number of draws.\n",
    "- Calculate the confidence interval, using the approximation of the variance using the formula\n",
    "$$\n",
    "\\text{Var}[g(\\beta)] \\approx \\frac{1}{R} \\sum_r g(\\beta_r)^2 - \\widehat{I}_R^2,\n",
    "$$\n",
    "where $g(x)$ is the conditional probability, and $\\widehat{I}_R$ is\n",
    "the Monte-Carlo estimation of the integral. The 95\\% confidence interval is $$[\\widehat{I}- 1.96 e_R,\n",
    "\\widehat{I}+ 1.96 e_R],$$ where $$e_R= \\sqrt{\\frac{\\text{Var}[g(\\beta)]}{R}}.$$\n",
    "- Plot again the value of the approximation as a function of the number of draws, as well as the confidence interval."
   ]
  }
 ],
 "metadata": {},
 "nbformat": 4,
 "nbformat_minor": 5
}
