{
 "nbformat": 4,
 "nbformat_minor": 5,
 "metadata": {
  "kernelspec": {
   "name": "python3",
   "language": "python",
   "display_name": "Python 3"
  },
  "language_info": {
   "name": "python"
  },
  "fundamentals": {
   "title": "What can unfinished endurance tests reveal about lifetime?",
   "lead": "When a test stops, a surviving bearing has supplied information. Derive the likelihood from first principles and examine how changing the observation deadline moves the rate inferred from a small batch.",
   "unit_slug": "estimating-lifetime-with-an-unfinished-test"
  }
 },
 "cells": [
  {
   "cell_type": "markdown",
   "id": "47c99d15fa01",
   "metadata": {},
   "source": [
    "# What can unfinished endurance tests reveal about lifetime?\n",
    "\n",
    "When a test stops, a surviving bearing has supplied information. Derive the likelihood from first principles and examine how changing the observation deadline moves the rate inferred from a small batch."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "94b91d56237f",
   "metadata": {
    "fundamentals": {
     "section": "derive-the-model"
    }
   },
   "source": [
    "## Count failures and add the time spent on test\n",
    "\n",
    "Assume identical bearings fail independently at a constant rate $\\lambda$ per hour. Over a short interval $dt$, the conditional probability of failure for an operating bearing is $\\lambda\\,dt+o(dt)$. This gives the differential equation $S'(t)=-\\lambda S(t)$ with $S(0)=1$ for the fraction surviving beyond $t$. Its solution is $S(t)=e^{-\\lambda t}$ and the failure-time density is\n",
    "\n",
    "$$\n",
    "f(t)=\\lambda e^{-\\lambda t}.\n",
    "$$\n",
    "\n",
    "Choose a fixed administrative deadline $c$ in advance. Each observed duration is the earlier of the failure time and $c$. Write $\\delta_i=1$ for a recorded failure, zero for an unfinished run. A failure contributes its density. An unfinished run contributes the probability of lasting at least its recorded duration. Multiplying these quantities over the bearings gives\n",
    "\n",
    "$$L(\\lambda)=\\prod_i f(t_i)^{\\delta_i}S(t_i)^{1-\\delta_i}\n",
    "             =\\lambda^d e^{-\\lambda T},\\qquad d=\\sum_i\\delta_i,\\quad T=\\sum_i t_i.$$\n",
    "\n",
    "For positive $d$, differentiating $d\\log\\lambda-\\lambda T$ gives a score $d/\\lambda-T$. It vanishes at $\\hat\\lambda=d/T$. The curvature $-d/\\lambda^2$ is negative. With zero failures the likelihood falls immediately to the right of zero, making zero the boundary maximum. A survivor contributes no failure to $d$ and still adds positive exposure to $T$. Removal triggered by a bearing's imminent failure would require a model for that mechanism. A predeclared deadline avoids this selection issue."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d6b4557da288",
   "metadata": {
    "fundamentals": {
     "section": "worked-prediction"
    }
   },
   "source": [
    "## Audit a batch stopped after seven hours\n",
    "\n",
    "Suppose the simulated complete lifetimes are 2, 4, 6, 9 and 14 hours. At seven hours the actual records are three failures and two unfinished tests. Their total exposure is $2+4+6+7+7=26$ bearing-hours. The rate estimate is $3/26=0.11538$ per hour and the fitted mean lifetime is $26/3=8.667$ hours. Discarding the two survivors leaves 12 bearing-hours and inflates the apparent rate to $3/12=0.25$ per hour.\n",
    "\n",
    "For a candidate rate of 0.20 per hour the log likelihood relative to the full-data maximum is\n",
    "\n",
    "$$3\\log(0.20/(3/26))-26(0.20-3/26)\\approx-0.550.$$\n",
    "\n",
    "This is a relative likelihood near 0.58. The absolute density changes when time units change, while this likelihood ratio is invariant. In the notebook change the deadline to five hours. Each failure that now occurs after the deadline becomes an unfinished observation. Inspect the time lines before interpreting the new estimate."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "399de7240c06",
   "metadata": {
    "fundamentals": {
     "section": "choose-inputs",
     "notebook_only": true
    }
   },
   "source": [
    "## Set the experimental inputs\n",
    "\n",
    "Edit these values, then run the calculation and both figures again."
   ]
  },
  {
   "cell_type": "code",
   "id": "ac320015ec24",
   "metadata": {},
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "teal, orange, blue = \"#19596a\", \"#aa462a\", \"#3868a0\"\n",
    "def axes(xlabel, ylabel):\n",
    "    fig, ax = plt.subplots(figsize=(7, 4), constrained_layout=True)\n",
    "    ax.set(xlabel=xlabel, ylabel=ylabel)\n",
    "    ax.grid(alpha=0.2)\n",
    "    return fig, ax"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "cf1c0f0bde19",
   "metadata": {},
   "source": [
    "deadline_hours = 7.0\n",
    "complete_hours = np.array([2.,4.,6.,9.,14.])"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "8636efdfd26c",
   "metadata": {},
   "source": [
    "assert deadline_hours > 0 and len(complete_hours) > 0\n",
    "assert np.all(np.isfinite(complete_hours)) and np.all(complete_hours>0)\n",
    "observed = np.minimum(complete_hours, deadline_hours)\n",
    "failed = complete_hours<=deadline_hours\n",
    "d = int(failed.sum()); exposure = observed.sum()\n",
    "rate = d/exposure\n",
    "failure_time = observed[failed].sum()\n",
    "naive = d/failure_time if d else np.nan\n",
    "\n",
    "def relative_log(lam, count, hours):\n",
    "    lam = np.asarray(lam)\n",
    "    if count == 0: return -hours*lam\n",
    "    best = count/hours\n",
    "    return count*np.log(lam/best)-hours*(lam-best)\n",
    "\n",
    "if d:\n",
    "    assert abs(d/rate-exposure)<1.e-8 and np.isclose(relative_log(rate,d,exposure),0.)\n",
    "    independent = np.prod(np.where(failed,.2,1.)*np.exp(-.2*observed))\n",
    "    maximum = np.prod(np.where(failed,rate,1.)*np.exp(-rate*observed))\n",
    "    assert np.isclose(np.log(independent/maximum),relative_log(.2,d,exposure))\n",
    "print(f\"{d} recorded failures, {exposure:g} bearing-hours, estimated rate {rate:.5f}/h\")\n",
    "if d: print(f\"Mean lifetime {1/rate:.4f} h; failure-only rate {naive:.5f}/h\")\n",
    "else: print(\"No failures. The one-sided 95% upper bound is\", -np.log(.05)/exposure, \"per hour.\")"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "code",
   "id": "3e5614d0983e",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "inverse-problems-inverse-problems-methods-1.png",
      "alt": "Horizontal bearing records end with either a failure cross or an open circle at the administrative deadline.",
      "caption": "Every horizontal length enters the denominator of the estimate. Only the crosses add to the failure count in its numerator."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Observed endurance time (h)\", \"Bearing number\")\n",
    "for idx,(duration,event) in enumerate(zip(observed,failed),1):\n",
    "    col = orange if event else teal\n",
    "    ax.hlines(idx,0,duration,color=col,lw=3)\n",
    "    if event: ax.scatter(duration,idx,marker=\"x\",color=col,s=75,zorder=3)\n",
    "    else: ax.scatter(duration,idx,facecolor=\"white\",edgecolor=col,s=70,zorder=3)\n",
    "ax.plot([],[],marker=\"x\",ls=\"\",color=orange,label=\"Recorded failure\")\n",
    "ax.plot([],[],marker=\"o\",ls=\"\",mfc=\"white\",color=teal,label=\"Still running\")\n",
    "ax.axvline(deadline_hours,color=blue,ls=\":\",label=\"Deadline\")\n",
    "ax.set_yticks(np.arange(1,len(observed)+1)); ax.set_ylim(.5,len(observed)+.6)\n",
    "ax.legend(fontsize=8)\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "fe0502556fea",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Every horizontal length enters the denominator of the estimate. Only the crosses add to the failure count in its numerator."
   ]
  },
  {
   "cell_type": "code",
   "id": "f0a329a6bb70",
   "metadata": {
    "fundamentals": {
     "figure": {
      "file": "inverse-problems-inverse-problems-methods-2.png",
      "alt": "Relative likelihood curves peak at different rates when unfinished observations are retained or discarded.",
      "caption": "Each curve is divided by its own maximum. Moving the deadline to before the first failure makes the complete-observation likelihood attain its maximum at a rate of zero."
     }
    }
   },
   "source": [
    "fig, ax = axes(\"Failure rate (per hour)\", \"Likelihood relative to its maximum\")\n",
    "top = max(3*rate,2*naive if d else 5/exposure)\n",
    "lam = np.linspace(0,top,241)\n",
    "usable = lam[1:] if d else lam\n",
    "full = np.exp(relative_log(usable,d,exposure))\n",
    "ax.plot(usable,full,color=teal,label=\"All observed exposure\")\n",
    "ax.scatter(rate,1.,color=teal)\n",
    "if d:\n",
    "    ax.plot(usable,np.exp(relative_log(usable,d,failure_time)),color=orange,ls=\"--\",label=\"Failures alone\")\n",
    "    ax.scatter(naive,1.,color=orange)\n",
    "ax.legend()\n",
    "plt.show()"
   ],
   "execution_count": null,
   "outputs": []
  },
  {
   "cell_type": "markdown",
   "id": "e4c816f23d62",
   "metadata": {
    "fundamentals": {
     "notebook_only": true
    }
   },
   "source": [
    "Each curve is divided by its own maximum. Moving the deadline to before the first failure makes the complete-observation likelihood attain its maximum at a rate of zero."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2306eacb2dac",
   "metadata": {
    "fundamentals": {
     "section": "problem-1"
    }
   },
   "source": [
    "## Exercise · change the stopping time\n",
    "\n",
    "What does a five-hour deadline yield for the same five bearings? Can extending the deadline without any additional failure increase the estimated rate?"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ee74ee75fb0c",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "The durations are 2, 4, 5, 5 and 5 hours with two observed failures. The new estimate is $2/21=0.09524$ per hour. While additional operating time accumulates with the same failure count, the ratio $d/T$ falls for positive $d$. The estimate can jump upward at an actual failure event. A generally increasing or decreasing trend with a moving deadline is therefore not guaranteed."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a55b57c6bdd2",
   "metadata": {
    "fundamentals": {
     "section": "problem-2"
    }
   },
   "source": [
    "## Exercise · infer an upper rate after zero failures\n",
    "\n",
    "Five fresh bearings all survive ten hours. Find the rate for which observing no failures would have probability 0.05 under the model."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "4300ea6e8281",
   "metadata": {
    "fundamentals": {
     "solution": true
    }
   },
   "source": [
    "All five must survive ten hours. Independence gives probability $e^{-50\\lambda}$. Setting this equal to 0.05 gives $\\lambda=-\\log(0.05)/50\\approx0.05991$ per hour. Inverting this zero-failure event gives a one-sided 95% upper confidence bound for the rate in this experiment. The likelihood maximum itself remains at zero."
   ]
  }
 ]
}
