{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "c89a63e5",
   "metadata": {},
   "source": [
    "# Equipment Failure Classification\n",
    "\n",
    "**AIMPACT peer-learning baseline**  \n",
    "**Dataset:** AI4I 2020  \n",
    "**Source:** https://archive.ics.uci.edu/dataset/601/ai4i%2B2020%2B  \n",
    "**Task:** Classification  \n",
    "**Status:** runnable demonstration with synthetic fallback, not a validated plant or project model.\n",
    "\n",
    "Install `numpy pandas scikit-learn openpyxl notebook` first. Set `DATA_FILE` to a local file to run against a compatible dataset where supported. Check source terms and permissions before use."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "67172ee7",
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import pandas as pd\n",
    "from pathlib import Path\n",
    "from sklearn.ensemble import RandomForestRegressor, RandomForestClassifier\n",
    "from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score, classification_report, confusion_matrix\n",
    "from sklearn.model_selection import train_test_split\n",
    "from sklearn.pipeline import Pipeline\n",
    "from sklearn.impute import SimpleImputer\n",
    "RANDOM_STATE = 42\n",
    "rng = np.random.default_rng(RANDOM_STATE)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2c674b4e",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Optional: set DATA_FILE to a downloaded AI4I CSV.\n",
    "DATA_FILE = \"\"  # e.g. \"ai4i2020.csv\"\n",
    "if DATA_FILE:\n",
    "    df=pd.read_csv(DATA_FILE)\n",
    "    features=[\"Air temperature [K]\",\"Process temperature [K]\",\"Rotational speed [rpm]\",\"Torque [Nm]\",\"Tool wear [min]\"]\n",
    "    target=\"Machine failure\"\n",
    "    if not set(features+[target]).issubset(df.columns):\n",
    "        raise ValueError(f\"Expected columns: {features+[target]}\")\n",
    "    df=df[features+[target]].copy()\n",
    "    data_origin=\"AI4I local file (synthetic benchmark)\"\n",
    "else:\n",
    "    n=2500\n",
    "    air=rng.normal(300,2,n); proc=air+rng.normal(10,1,n)\n",
    "    rpm=rng.normal(1500,280,n).clip(900,2800)\n",
    "    torque=rng.normal(40,12,n).clip(5,90)\n",
    "    wear=rng.uniform(0,250,n)\n",
    "    score=-3.6+.035*(torque-40)+.015*(wear-100)+.002*(1500-rpm)+.1*(proc-air-10)\n",
    "    failure=rng.binomial(1,1/(1+np.exp(-score)))\n",
    "    features=[\"Air temperature [K]\",\"Process temperature [K]\",\"Rotational speed [rpm]\",\"Torque [Nm]\",\"Tool wear [min]\"]\n",
    "    target=\"Machine failure\"\n",
    "    df=pd.DataFrame(dict(zip(features,[air,proc,rpm,torque,wear])));df[target]=failure\n",
    "    data_origin=\"SYNTHETIC DEMONSTRATION DATA — not actual equipment data\"\n",
    "print(data_origin,df.shape,\"Failure fraction:\",round(df[target].mean(),3))\n",
    "display(df.head())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "eb5fcffb",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=df[features];y=df[target].astype(int)\n",
    "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=.25,stratify=y,random_state=RANDOM_STATE)\n",
    "model=Pipeline([(\"impute\",SimpleImputer(strategy=\"median\")),(\"rf\",RandomForestClassifier(n_estimators=120,class_weight=\"balanced\",min_samples_leaf=3,random_state=RANDOM_STATE,n_jobs=-1))])\n",
    "model.fit(X_train,y_train)\n",
    "pred=model.predict(X_test)\n",
    "print(classification_report(y_test,pred,zero_division=0))\n",
    "print(\"Confusion matrix:\\n\",confusion_matrix(y_test,pred))\n",
    "print(\"Important: false negatives may be costly; calibrate thresholds and validate on site-specific data before any operational use.\")\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "efb6522a",
   "metadata": {},
   "source": [
    "## Peer review checklist\n",
    "\n",
    "- Check data provenance, license, missing values and representativeness.\n",
    "- Confirm whether target values would actually be known at prediction time.\n",
    "- Use chronological, site-held-out or project-held-out testing for real deployments.\n",
    "- Compare against a simple baseline and report uncertainty and failure cases.\n",
    "- Do not connect experimental models to plant controls or safety-critical decisions.\n",
    "- Document reviewer comments and proposed next experiments."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
