{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "af7c3ca8",
   "metadata": {},
   "source": [
    "# Power Output Prediction\n",
    "\n",
    "**AIMPACT peer-learning baseline**  \n",
    "**Dataset:** UCI Combined Cycle Power Plant  \n",
    "**Source:** https://archive.ics.uci.edu/dataset/294/combined%2Bcycle%2Bpower%2Bplant  \n",
    "**Task:** Regression  \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": "8b081360",
   "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": "f6cd4424",
   "metadata": {},
   "outputs": [],
   "source": [
    "# Optional: set DATA_FILE to a local CSV/XLSX downloaded from the UCI source.\n",
    "DATA_FILE = \"\"  # e.g. \"Folds5x2_pp.xlsx\"\n",
    "if DATA_FILE:\n",
    "    path = Path(DATA_FILE)\n",
    "    df = pd.read_excel(path) if path.suffix.lower() in {\".xls\", \".xlsx\"} else pd.read_csv(path)\n",
    "    df.columns = [str(c).strip().upper() for c in df.columns]\n",
    "    expected = [\"AT\", \"V\", \"AP\", \"RH\", \"PE\"]\n",
    "    if not set(expected).issubset(df.columns):\n",
    "        raise ValueError(f\"Expected columns: {expected}\")\n",
    "    df = df[expected].copy()\n",
    "    data_origin = \"UCI local file\"\n",
    "else:\n",
    "    n=1200\n",
    "    at=rng.uniform(2,37,n); vacuum=rng.uniform(25,82,n)\n",
    "    pressure=rng.normal(1013,11,n); humidity=rng.uniform(25,100,n)\n",
    "    output=485-1.8*at-.20*vacuum+.06*(pressure-1013)-.06*humidity+rng.normal(0,5,n)\n",
    "    df=pd.DataFrame({\"AT\":at,\"V\":vacuum,\"AP\":pressure,\"RH\":humidity,\"PE\":output})\n",
    "    data_origin=\"SYNTHETIC DEMONSTRATION DATA — not real plant performance\"\n",
    "print(data_origin,df.shape)\n",
    "display(df.head())\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3c1364ed",
   "metadata": {},
   "outputs": [],
   "source": [
    "X=df[[\"AT\",\"V\",\"AP\",\"RH\"]]; y=df[\"PE\"]\n",
    "X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2,random_state=RANDOM_STATE)\n",
    "model=Pipeline([(\"impute\",SimpleImputer(strategy=\"median\")),(\"rf\",RandomForestRegressor(n_estimators=100,min_samples_leaf=2,random_state=RANDOM_STATE,n_jobs=-1))])\n",
    "model.fit(X_train,y_train)\n",
    "pred=model.predict(X_test)\n",
    "print(\"MAE:\",round(mean_absolute_error(y_test,pred),3))\n",
    "print(\"RMSE:\",round(np.sqrt(mean_squared_error(y_test,pred)),3))\n",
    "print(\"R²:\",round(r2_score(y_test,pred),3))\n",
    "print(\"Feature importance:\",dict(zip(X.columns,model.named_steps[\"rf\"].feature_importances_.round(3))))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "164c7fe6",
   "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
}
