{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Sprint Bottleneck Predictor — XGBoost + SHAP (M11)\n", "\n", "Trains an **XGBoost multiclass classifier** to predict sprint bottleneck risk levels,\n", "with a **rule-based bottleneck detector** and **recommendation engine** layered on top.\n", "\n", "- **Input:** 18-feature sprint snapshot (task distribution, workload, velocity)\n", "- **Output:** Risk level (low/medium/high/critical) + specific bottlenecks + recommendations\n", "- **Hardware:** CPU only (~5-10 minutes training)\n", "- **Target:** >82% accuracy, <10ms inference per sprint" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 1. Setup & Dependencies\n", "\n", "Install XGBoost, scikit-learn, SHAP for explainability, and matplotlib for visualization." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "import subprocess\n", "import sys\n", "\n", "def install(package):\n", " subprocess.check_call([sys.executable, \"-m\", \"pip\", \"install\", \"-q\", package])\n", "\n", "install(\"xgboost>=2.0.3\")\n", "install(\"scikit-learn>=1.5.0\")\n", "install(\"pandas>=2.2.0\")\n", "install(\"numpy>=1.26.0\")\n", "install(\"joblib>=1.4.0\")\n", "install(\"matplotlib>=3.8.0\")\n", "install(\"shap>=0.45.0\")\n", "\n", "import os\n", "import json\n", "import time\n", "import random\n", "import warnings\n", "from pathlib import Path\n", "\n", "import numpy as np\n", "import pandas as pd\n", "import joblib\n", "import xgboost as xgb\n", "import matplotlib\n", "matplotlib.use(\"Agg\")\n", "import matplotlib.pyplot as plt\n", "import shap\n", "from sklearn.model_selection import (\n", " GridSearchCV,\n", " StratifiedKFold,\n", " train_test_split,\n", ")\n", "from sklearn.preprocessing import StandardScaler, LabelEncoder\n", "from sklearn.metrics import (\n", " accuracy_score,\n", " f1_score,\n", " classification_report,\n", " confusion_matrix,\n", ")\n", "\n", "warnings.filterwarnings(\"ignore\", category=FutureWarning)\n", "\n", "# Reproducibility\n", "SEED = 42\n", "random.seed(SEED)\n", "np.random.seed(SEED)\n", "\n", "print(\"Dependencies loaded successfully\")\n", "print(f\"XGBoost version: {xgb.__version__}\")\n", "print(f\"SHAP version: {shap.__version__}\")\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 2. Synthetic Dataset Generation\n", "\n", "Generate 8000 sprint snapshots with 18 features and balanced risk labels (low/medium/high/critical).\n", "\n", "**Labeling rules:**\n", "- **critical:** completion <20% with <3 days, OR >3 overloaded members\n", "- **high:** completion <40% with <5 days, OR >4 blocked tasks\n", "- **medium:** velocity vs plan <0.7, OR workload std dev >0.4\n", "- **low:** everything else" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# - **medium:** velocity vs plan <0.7, OR workload std dev >0.4\n", "# - **low:** everything else\n", "\n", "print(\"\\n\" + \"=\" * 60)\n", "print(\"SECTION 2: Generating synthetic sprint data\")\n", "print(\"=\" * 60)\n", "\n", "FEATURE_NAMES = [\n", " # Sprint-level\n", " \"days_remaining\",\n", " \"completion_rate\",\n", " \"story_points_completed\",\n", " \"story_points_remaining\",\n", " \"capacity_utilization\",\n", " \"past_velocity_avg\",\n", " # Task distribution\n", " \"blocked_task_count\",\n", " \"critical_task_count\",\n", " \"unassigned_task_count\",\n", " \"overdue_task_count\",\n", " \"tasks_without_estimates\",\n", " # Member workload\n", " \"max_member_workload\",\n", " \"workload_std_dev\",\n", " \"avg_member_utilization\",\n", " \"overloaded_member_count\",\n", " # Velocity trend\n", " \"velocity_trend\",\n", " \"velocity_vs_plan\",\n", " # Derived\n", " \"scope_change_ratio\",\n", "]\n", "\n", "RISK_LEVELS = [\"low\", \"medium\", \"high\", \"critical\"]\n", "\n", "\n", "def label_sprint(f: dict) -> str:\n", " \"\"\"Apply deterministic labeling rules to assign a risk level.\"\"\"\n", " # Critical conditions\n", " if f[\"completion_rate\"] < 0.2 and f[\"days_remaining\"] < 3:\n", " return \"critical\"\n", " if f[\"overloaded_member_count\"] > 3:\n", " return \"critical\"\n", " if f[\"blocked_task_count\"] > 6 and f[\"days_remaining\"] < 4:\n", " return \"critical\"\n", "\n", " # High conditions\n", " if f[\"completion_rate\"] < 0.4 and f[\"days_remaining\"] < 5:\n", " return \"high\"\n", " if f[\"blocked_task_count\"] > 4:\n", " return \"high\"\n", " if f[\"overloaded_member_count\"] > 2 and f[\"velocity_vs_plan\"] < 0.6:\n", " return \"high\"\n", " if f[\"critical_task_count\"] > 3 and f[\"unassigned_task_count\"] > 2:\n", " return \"high\"\n", "\n", " # Medium conditions\n", " if f[\"velocity_vs_plan\"] < 0.7:\n", " return \"medium\"\n", " if f[\"workload_std_dev\"] > 0.4:\n", " return \"medium\"\n", " if f[\"overdue_task_count\"] > 3:\n", " return \"medium\"\n", " if f[\"capacity_utilization\"] > 1.1:\n", " return \"medium\"\n", " if f[\"unassigned_task_count\"] > 3:\n", " return \"medium\"\n", "\n", " return \"low\"\n", "\n", "\n", "def generate_sprint(bias: str | None = None) -> dict:\n", " \"\"\"Generate a single sprint snapshot with realistic feature values.\n", "\n", " Args:\n", " bias: optionally bias toward a specific risk level to balance the dataset.\n", " \"\"\"\n", " # Sprint-level features\n", " sprint_length = random.choice([7, 10, 14]) # days\n", " total_tasks = random.randint(8, 40)\n", " total_sp = random.randint(20, 80)\n", " capacity = random.randint(30, 80)\n", " team_size = random.randint(3, 10)\n", "\n", " if bias == \"critical\":\n", " days_remaining = random.uniform(0.5, 3.0)\n", " completion_rate = random.uniform(0.05, 0.25)\n", " overloaded_count = random.randint(2, 5)\n", " blocked = random.randint(3, 8)\n", " elif bias == \"high\":\n", " days_remaining = random.uniform(1.5, 5.5)\n", " completion_rate = random.uniform(0.15, 0.45)\n", " overloaded_count = random.randint(1, 3)\n", " blocked = random.randint(2, 7)\n", " elif bias == \"medium\":\n", " days_remaining = random.uniform(3.0, 8.0)\n", " completion_rate = random.uniform(0.3, 0.65)\n", " overloaded_count = random.randint(0, 2)\n", " blocked = random.randint(0, 4)\n", " else: # low\n", " days_remaining = random.uniform(5.0, 12.0)\n", " completion_rate = random.uniform(0.5, 0.95)\n", " overloaded_count = random.randint(0, 1)\n", " blocked = random.randint(0, 2)\n", "\n", " sp_completed = round(total_sp * completion_rate, 1)\n", " sp_remaining = round(total_sp - sp_completed, 1)\n", " capacity_util = round(total_sp / max(capacity, 1), 2)\n", "\n", " # Past velocity\n", " past_velocities = [random.uniform(15, 60) for _ in range(3)]\n", " past_velocity_avg = round(np.mean(past_velocities), 1)\n", "\n", " # Task distribution\n", " critical_tasks = random.randint(0, max(1, total_tasks // 4))\n", " unassigned = random.randint(0, max(1, total_tasks // 3))\n", " overdue = random.randint(0, max(1, int(total_tasks * (1 - completion_rate) * 0.5)))\n", " no_estimates = random.randint(0, max(1, total_tasks // 5))\n", "\n", " # Member workload\n", " member_workloads = [random.uniform(5, 30) for _ in range(team_size)]\n", " max_workload = round(max(member_workloads), 1)\n", " workload_std = round(float(np.std(member_workloads) / max(np.mean(member_workloads), 1)), 3)\n", " avg_util = round(float(np.mean(member_workloads)) / max(capacity / team_size, 1), 3)\n", "\n", " # Velocity trend\n", " if len(past_velocities) >= 2:\n", " trend = round((past_velocities[-1] - past_velocities[0]) / max(past_velocities[0], 1), 3)\n", " else:\n", " trend = 0.0\n", "\n", " # Velocity vs plan: are we on pace?\n", " if days_remaining > 0 and sprint_length > 0:\n", " elapsed_fraction = (sprint_length - days_remaining) / sprint_length\n", " expected_completion = elapsed_fraction\n", " velocity_vs_plan = round(completion_rate / max(expected_completion, 0.01), 3)\n", " velocity_vs_plan = min(2.0, velocity_vs_plan)\n", " else:\n", " velocity_vs_plan = round(completion_rate / 0.9, 3)\n", "\n", " # Scope change ratio\n", " scope_change = round(random.uniform(-0.1, 0.3), 3)\n", "\n", " features = {\n", " \"days_remaining\": round(days_remaining, 1),\n", " \"completion_rate\": round(completion_rate, 3),\n", " \"story_points_completed\": sp_completed,\n", " \"story_points_remaining\": sp_remaining,\n", " \"capacity_utilization\": capacity_util,\n", " \"past_velocity_avg\": past_velocity_avg,\n", " \"blocked_task_count\": blocked,\n", " \"critical_task_count\": critical_tasks,\n", " \"unassigned_task_count\": unassigned,\n", " \"overdue_task_count\": overdue,\n", " \"tasks_without_estimates\": no_estimates,\n", " \"max_member_workload\": max_workload,\n", " \"workload_std_dev\": workload_std,\n", " \"avg_member_utilization\": avg_util,\n", " \"overloaded_member_count\": overloaded_count,\n", " \"velocity_trend\": trend,\n", " \"velocity_vs_plan\": velocity_vs_plan,\n", " \"scope_change_ratio\": scope_change,\n", " }\n", "\n", " return features\n", "\n", "\n", "def generate_dataset(n: int = 8000) -> pd.DataFrame:\n", " \"\"\"Generate n sprint examples with balanced class distribution.\"\"\"\n", " # Generate with class bias for balance\n", " per_class = n // 4\n", " examples = []\n", "\n", " for risk_class in RISK_LEVELS:\n", " count = 0\n", " attempts = 0\n", " while count < per_class and attempts < per_class * 10:\n", " features = generate_sprint(bias=risk_class)\n", " label = label_sprint(features)\n", " # Accept if label matches bias (or close enough after many tries)\n", " if label == risk_class or attempts > per_class * 5:\n", " features[\"risk_level\"] = label\n", " examples.append(features)\n", " count += 1\n", " attempts += 1\n", "\n", " random.shuffle(examples)\n", " df = pd.DataFrame(examples)\n", "\n", " # Add some noise: flip 5% of labels to make it harder\n", " flip_indices = random.sample(range(len(df)), int(0.05 * len(df)))\n", " for idx in flip_indices:\n", " current = df.at[idx, \"risk_level\"]\n", " alternatives = [r for r in RISK_LEVELS if r != current]\n", " # Prefer adjacent risk levels\n", " if current == \"low\":\n", " df.at[idx, \"risk_level\"] = \"medium\"\n", " elif current == \"critical\":\n", " df.at[idx, \"risk_level\"] = \"high\"\n", " else:\n", " df.at[idx, \"risk_level\"] = random.choice(alternatives)\n", "\n", " return df\n", "\n", "\n", "print(\"Generating 8000 sprint examples...\")\n", "df = generate_dataset(8000)\n", "\n", "print(f\"\\nDataset shape: {df.shape}\")\n", "print(f\"\\nRisk level distribution:\")\n", "print(df[\"risk_level\"].value_counts().sort_index().to_string())\n", "print(f\"\\nFeature statistics:\")\n", "print(df[FEATURE_NAMES].describe().round(3).to_string())\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 3. Model Training\n", "\n", "XGBoost multiclass classifier with GridSearchCV hyperparameter tuning.\n", "- n_estimators: [100, 200, 300]\n", "- max_depth: [3, 4, 5]\n", "- learning_rate: [0.05, 0.1, 0.2]\n", "\n", "Target: >82% accuracy." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"=\" * 60)\n", "\n", "# Prepare features and labels\n", "X = df[FEATURE_NAMES].values.astype(np.float32)\n", "le = LabelEncoder()\n", "y = le.fit_transform(df[\"risk_level\"])\n", "class_names = le.classes_.tolist()\n", "\n", "print(f\"Classes: {class_names}\")\n", "print(f\"Label encoding: {dict(zip(class_names, le.transform(class_names)))}\")\n", "\n", "# Scale features\n", "scaler = StandardScaler()\n", "X_scaled = scaler.fit_transform(X)\n", "\n", "# Train/test split\n", "X_train, X_test, y_train, y_test = train_test_split(\n", " X_scaled, y, test_size=0.2, random_state=SEED, stratify=y,\n", ")\n", "print(f\"\\nTrain: {X_train.shape[0]}, Test: {X_test.shape[0]}\")\n", "\n", "# Hyperparameter grid\n", "param_grid = {\n", " \"n_estimators\": [100, 200, 300],\n", " \"max_depth\": [3, 4, 5],\n", " \"learning_rate\": [0.05, 0.1, 0.2],\n", "}\n", "\n", "base_model = xgb.XGBClassifier(\n", " objective=\"multi:softprob\",\n", " num_class=len(class_names),\n", " eval_metric=\"mlogloss\",\n", " use_label_encoder=False,\n", " random_state=SEED,\n", " verbosity=0,\n", ")\n", "\n", "print(f\"\\nRunning GridSearchCV with {len(param_grid['n_estimators']) * len(param_grid['max_depth']) * len(param_grid['learning_rate'])} parameter combinations...\")\n", "print(\"This may take 3-8 minutes on CPU...\")\n", "\n", "cv = StratifiedKFold(n_splits=5, shuffle=True, random_state=SEED)\n", "\n", "t0 = time.time()\n", "grid_search = GridSearchCV(\n", " base_model,\n", " param_grid,\n", " cv=cv,\n", " scoring=\"f1_macro\",\n", " n_jobs=-1,\n", " verbose=0,\n", " refit=True,\n", ")\n", "grid_search.fit(X_train, y_train)\n", "search_time = time.time() - t0\n", "\n", "print(f\"\\nGrid search completed in {search_time:.1f}s\")\n", "print(f\"Best parameters: {grid_search.best_params_}\")\n", "print(f\"Best CV F1 (macro): {grid_search.best_score_:.4f}\")\n", "\n", "# Evaluate on test set\n", "best_model = grid_search.best_estimator_\n", "y_pred = best_model.predict(X_test)\n", "\n", "test_acc = accuracy_score(y_test, y_pred)\n", "test_f1 = f1_score(y_test, y_pred, average=\"macro\")\n", "print(f\"\\n--- Test Set Results ---\")\n", "print(f\"Accuracy: {test_acc:.4f}\")\n", "print(f\"Macro F1: {test_f1:.4f}\")\n", "\n", "if test_acc >= 0.82:\n", " print(f\"TARGET MET: accuracy {test_acc:.4f} >= 0.82\")\n", "else:\n", " print(f\"TARGET NOT MET: accuracy {test_acc:.4f} < 0.82\")\n", "\n", "print(f\"\\n--- Classification Report ---\")\n", "print(classification_report(y_test, y_pred, target_names=class_names))\n", "\n", "print(f\"\\n--- Confusion Matrix ---\")\n", "cm = confusion_matrix(y_test, y_pred)\n", "cm_df = pd.DataFrame(cm, index=class_names, columns=class_names)\n", "print(cm_df.to_string())\n", "\n", "# XGBoost built-in feature importance\n", "print(f\"\\n--- XGBoost Feature Importance (gain) ---\")\n", "importance = best_model.feature_importances_\n", "for name, imp in sorted(zip(FEATURE_NAMES, importance), key=lambda x: -x[1])[:10]:\n", " bar = \"#\" * int(imp * 80)\n", " print(f\" {name:30s} {imp:.4f} {bar}\")\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 4. Explainability with SHAP\n", "\n", "SHAP (SHapley Additive exPlanations) shows which features drive each prediction.\n", "We compute a SHAP explainer for inference-time explanations." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Use a sample for SHAP computation (faster than full dataset)\n", "X_shap_sample = X_test[:500]\n", "explainer = shap.TreeExplainer(best_model)\n", "shap_values = explainer.shap_values(X_shap_sample)\n", "\n", "shap_time = time.time() - t0\n", "print(f\"SHAP computation completed in {shap_time:.1f}s\")\n", "\n", "# Feature importance from SHAP (mean |SHAP| across all classes)\n", "shap_arr = np.array(shap_values)\n", "if shap_arr.ndim == 3:\n", " # Multi-class: shape (n_classes, n_samples, n_features) or (n_samples, n_features, n_classes)\n", " # Average across classes and samples to get per-feature importance\n", " mean_shap = np.abs(shap_arr).mean(axis=(0, 1)) if shap_arr.shape[0] < shap_arr.shape[1] else np.abs(shap_arr).mean(axis=0).mean(axis=-1)\n", "elif isinstance(shap_values, list):\n", " mean_shap = np.mean([np.abs(sv).mean(axis=0) for sv in shap_values], axis=0)\n", "else:\n", " mean_shap = np.abs(shap_arr).mean(axis=0)\n", "# Ensure mean_shap is 1D (one value per feature)\n", "mean_shap = np.array(mean_shap).flatten()[:len(FEATURE_NAMES)]\n", "\n", "print(f\"\\n--- SHAP Feature Importance (top 10) ---\")\n", "shap_importance = sorted(zip(FEATURE_NAMES, mean_shap), key=lambda x: -x[1])\n", "for name, imp in shap_importance[:10]:\n", " bar = \"#\" * int(imp * 100)\n", " print(f\" {name:30s} {imp:.4f} {bar}\")\n", "\n", "# Plot SHAP summary\n", "try:\n", " fig, ax = plt.subplots(figsize=(10, 6))\n", " # Use class 0 (or combined) for summary plot\n", " if isinstance(shap_values, list):\n", " shap.summary_plot(\n", " shap_values[0],\n", " X_shap_sample,\n", " feature_names=FEATURE_NAMES,\n", " show=False,\n", " plot_size=(10, 6),\n", " )\n", " else:\n", " shap.summary_plot(\n", " shap_values,\n", " X_shap_sample,\n", " feature_names=FEATURE_NAMES,\n", " show=False,\n", " plot_size=(10, 6),\n", " )\n", " plt.tight_layout()\n", " plt.savefig(\"shap_feature_importance.png\", dpi=150, bbox_inches=\"tight\")\n", " print(\"\\nSaved SHAP plot: shap_feature_importance.png\")\n", " plt.close()\n", "except Exception as e:\n", " print(f\"Could not create SHAP plot: {e}\")\n", "\n", "# Bar chart of top 10 features\n", "try:\n", " fig, ax = plt.subplots(figsize=(8, 5))\n", " top_features = shap_importance[:10]\n", " names = [f[0] for f in top_features]\n", " values = [f[1] for f in top_features]\n", " bars = ax.barh(range(len(names)), values, color=\"#7c3aed\")\n", " ax.set_yticks(range(len(names)))\n", " ax.set_yticklabels(names, fontsize=9)\n", " ax.invert_yaxis()\n", " ax.set_xlabel(\"Mean |SHAP value|\")\n", " ax.set_title(\"Top 10 Features — Sprint Risk Prediction\")\n", " plt.tight_layout()\n", " plt.savefig(\"top_features_bar.png\", dpi=150, bbox_inches=\"tight\")\n", " print(\"Saved feature importance bar chart: top_features_bar.png\")\n", " plt.close()\n", "except Exception as e:\n", " print(f\"Could not create bar chart: {e}\")\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 5. Bottleneck Detector — Rule-Based Layer\n", "\n", "Deterministic rules that always fire regardless of ML risk score.\n", "Identify specific bottleneck types: member overload, blocked tasks, deadline risk, etc." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def detect_bottlenecks(sprint_data: dict) -> list[dict]:\n", " \"\"\"Identify specific bottleneck types in a sprint snapshot.\n", "\n", " Always runs regardless of ML risk prediction. Returns a list of\n", " bottleneck dicts with type, description, severity, and affected context.\n", "\n", " Args:\n", " sprint_data: dict with sprint feature values + optional task/member details.\n", " \"\"\"\n", " bottlenecks = []\n", "\n", " # 1. Member overload\n", " overloaded = sprint_data.get(\"overloaded_member_count\", 0)\n", " if overloaded > 0:\n", " severity = \"critical\" if overloaded > 3 else \"high\" if overloaded > 1 else \"medium\"\n", " bottlenecks.append({\n", " \"type\": \"member_overload\",\n", " \"description\": f\"{overloaded} team member{'s' if overloaded > 1 else ''} \"\n", " f\"{'are' if overloaded > 1 else 'is'} over 80% capacity\",\n", " \"severity\": severity,\n", " \"affected_task_ids\": sprint_data.get(\"overloaded_member_task_ids\", []),\n", " })\n", "\n", " # 2. Blocked tasks\n", " blocked = sprint_data.get(\"blocked_task_count\", 0)\n", " if blocked > 2:\n", " severity = \"critical\" if blocked > 5 else \"high\" if blocked > 3 else \"medium\"\n", " bottlenecks.append({\n", " \"type\": \"blocked_tasks\",\n", " \"description\": f\"{blocked} tasks are blocked and need resolution\",\n", " \"severity\": severity,\n", " \"affected_task_ids\": sprint_data.get(\"blocked_task_ids\", []),\n", " })\n", "\n", " # 3. Unassigned critical tasks\n", " unassigned_critical = sprint_data.get(\"unassigned_critical_tasks\", 0)\n", " if unassigned_critical is None:\n", " # Estimate from features\n", " critical = sprint_data.get(\"critical_task_count\", 0)\n", " unassigned = sprint_data.get(\"unassigned_task_count\", 0)\n", " unassigned_critical = min(critical, unassigned)\n", " if unassigned_critical > 0:\n", " bottlenecks.append({\n", " \"type\": \"unassigned_critical\",\n", " \"description\": f\"{unassigned_critical} critical task{'s' if unassigned_critical > 1 else ''} \"\n", " f\"{'are' if unassigned_critical > 1 else 'is'} unassigned\",\n", " \"severity\": \"high\",\n", " \"affected_task_ids\": sprint_data.get(\"unassigned_critical_task_ids\", []),\n", " })\n", "\n", " # 4. Velocity lag\n", " velocity_vs_plan = sprint_data.get(\"velocity_vs_plan\", 1.0)\n", " if velocity_vs_plan < 0.6:\n", " severity = \"high\" if velocity_vs_plan < 0.4 else \"medium\"\n", " pct = int((1 - velocity_vs_plan) * 100)\n", " bottlenecks.append({\n", " \"type\": \"velocity_lag\",\n", " \"description\": f\"Sprint velocity is {pct}% behind planned pace\",\n", " \"severity\": severity,\n", " \"affected_task_ids\": [],\n", " })\n", "\n", " # 5. Deadline risk\n", " days_remaining = sprint_data.get(\"days_remaining\", 999)\n", " completion_rate = sprint_data.get(\"completion_rate\", 1.0)\n", " if days_remaining < 2 and completion_rate < 0.7:\n", " remaining_pct = int((1 - completion_rate) * 100)\n", " bottlenecks.append({\n", " \"type\": \"deadline_risk\",\n", " \"description\": f\"Sprint ends in {days_remaining:.0f} day{'s' if days_remaining != 1 else ''} \"\n", " f\"with {remaining_pct}% of work remaining\",\n", " \"severity\": \"critical\",\n", " \"affected_task_ids\": [],\n", " })\n", "\n", " # 6. Scope creep\n", " capacity_util = sprint_data.get(\"capacity_utilization\", 0)\n", " if capacity_util > 1.2:\n", " overcommit_pct = int((capacity_util - 1.0) * 100)\n", " bottlenecks.append({\n", " \"type\": \"scope_creep\",\n", " \"description\": f\"Sprint is {overcommit_pct}% over capacity\",\n", " \"severity\": \"high\" if capacity_util > 1.4 else \"medium\",\n", " \"affected_task_ids\": [],\n", " })\n", "\n", " # 7. Workload imbalance\n", " workload_std = sprint_data.get(\"workload_std_dev\", 0)\n", " if workload_std > 0.5:\n", " bottlenecks.append({\n", " \"type\": \"workload_imbalance\",\n", " \"description\": \"Significant workload imbalance across team members\",\n", " \"severity\": \"medium\",\n", " \"affected_task_ids\": [],\n", " })\n", "\n", " # 8. Overdue tasks\n", " overdue = sprint_data.get(\"overdue_task_count\", 0)\n", " if overdue > 3:\n", " bottlenecks.append({\n", " \"type\": \"overdue_tasks\",\n", " \"description\": f\"{overdue} tasks are past their due date\",\n", " \"severity\": \"high\" if overdue > 5 else \"medium\",\n", " \"affected_task_ids\": sprint_data.get(\"overdue_task_ids\", []),\n", " })\n", "\n", " return bottlenecks\n", "\n", "\n", "# Test the detector\n", "print(\"Testing bottleneck detector on sample sprints...\")\n", "\n", "test_sprints = [\n", " {\"overloaded_member_count\": 4, \"blocked_task_count\": 6, \"unassigned_critical_tasks\": 2,\n", " \"velocity_vs_plan\": 0.3, \"days_remaining\": 1, \"completion_rate\": 0.2,\n", " \"capacity_utilization\": 1.5, \"workload_std_dev\": 0.6, \"overdue_task_count\": 5},\n", " {\"overloaded_member_count\": 0, \"blocked_task_count\": 1, \"unassigned_critical_tasks\": 0,\n", " \"velocity_vs_plan\": 1.1, \"days_remaining\": 7, \"completion_rate\": 0.7,\n", " \"capacity_utilization\": 0.8, \"workload_std_dev\": 0.2, \"overdue_task_count\": 0},\n", "]\n", "\n", "for i, sprint in enumerate(test_sprints):\n", " bns = detect_bottlenecks(sprint)\n", " print(f\"\\n Sprint {i+1}: {len(bns)} bottleneck{'s' if len(bns) != 1 else ''}\")\n", " for bn in bns:\n", " print(f\" [{bn['severity']:8s}] {bn['type']:25s} — {bn['description']}\")\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 6. Recommendation Engine\n", "\n", "Maps bottleneck types to actionable recommendations.\n", "Each recommendation includes action, reason, and priority." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def generate_recommendations(bottlenecks: list[dict], sprint_data: dict) -> list[dict]:\n", " \"\"\"Generate actionable recommendations from detected bottlenecks.\n", "\n", " Returns a list of recommendation dicts with action, reason, and priority.\n", " \"\"\"\n", " recommendations = []\n", "\n", " for bn in bottlenecks:\n", " bn_type = bn[\"type\"]\n", " severity = bn[\"severity\"]\n", "\n", " if bn_type == \"member_overload\":\n", " recommendations.append({\n", " \"action\": \"Redistribute tasks from overloaded members to team members with available capacity\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\" if severity in (\"high\", \"critical\") else \"medium\",\n", " })\n", " if severity == \"critical\":\n", " recommendations.append({\n", " \"action\": \"Consider pulling in additional team members or extending the sprint\",\n", " \"reason\": \"Multiple team members are critically overloaded\",\n", " \"priority\": \"high\",\n", " })\n", "\n", " elif bn_type == \"blocked_tasks\":\n", " recommendations.append({\n", " \"action\": \"Schedule an immediate blocker resolution meeting\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\" if severity in (\"high\", \"critical\") else \"medium\",\n", " })\n", " if severity == \"critical\":\n", " recommendations.append({\n", " \"action\": \"Escalate blocking issues to project lead for immediate intervention\",\n", " \"reason\": \"Blocked tasks are critically impacting sprint progress\",\n", " \"priority\": \"high\",\n", " })\n", "\n", " elif bn_type == \"unassigned_critical\":\n", " recommendations.append({\n", " \"action\": \"Immediately assign all unassigned critical tasks to available team members\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\",\n", " })\n", "\n", " elif bn_type == \"velocity_lag\":\n", " recommendations.append({\n", " \"action\": \"Consider reducing sprint scope — move low-priority tasks to the backlog\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\" if severity == \"high\" else \"medium\",\n", " })\n", " recommendations.append({\n", " \"action\": \"Hold a focused standup to identify and remove impediments slowing the team\",\n", " \"reason\": \"Team is behind planned velocity\",\n", " \"priority\": \"medium\",\n", " })\n", "\n", " elif bn_type == \"deadline_risk\":\n", " recommendations.append({\n", " \"action\": \"Escalate sprint risk to project lead — sprint is at risk of missing deadline\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\",\n", " })\n", " recommendations.append({\n", " \"action\": \"Identify must-have vs nice-to-have tasks and defer non-essential items\",\n", " \"reason\": \"Limited time remaining requires scope prioritization\",\n", " \"priority\": \"high\",\n", " })\n", "\n", " elif bn_type == \"scope_creep\":\n", " over_pct = sprint_data.get(\"capacity_utilization\", 1.0)\n", " recommendations.append({\n", " \"action\": f\"Move lowest-priority tasks to backlog to bring sprint within capacity\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"medium\",\n", " })\n", "\n", " elif bn_type == \"workload_imbalance\":\n", " recommendations.append({\n", " \"action\": \"Rebalance task assignments to distribute workload more evenly across the team\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"medium\",\n", " })\n", "\n", " elif bn_type == \"overdue_tasks\":\n", " recommendations.append({\n", " \"action\": \"Review all overdue tasks and update due dates or reassign to unblock progress\",\n", " \"reason\": bn[\"description\"],\n", " \"priority\": \"high\" if severity == \"high\" else \"medium\",\n", " })\n", "\n", " # Deduplicate by action\n", " seen = set()\n", " unique = []\n", " for rec in recommendations:\n", " if rec[\"action\"] not in seen:\n", " seen.add(rec[\"action\"])\n", " unique.append(rec)\n", "\n", " # Sort by priority (high first)\n", " priority_order = {\"high\": 0, \"medium\": 1, \"low\": 2}\n", " unique.sort(key=lambda r: priority_order.get(r[\"priority\"], 2))\n", "\n", " return unique\n", "\n", "\n", "# Test the recommendation engine\n", "print(\"Testing recommendation engine...\")\n", "for i, sprint in enumerate(test_sprints):\n", " bns = detect_bottlenecks(sprint)\n", " recs = generate_recommendations(bns, sprint)\n", " print(f\"\\n Sprint {i+1}: {len(recs)} recommendation{'s' if len(recs) != 1 else ''}\")\n", " for rec in recs[:5]:\n", " print(f\" [{rec['priority']:6s}] {rec['action'][:80]}\")\n", "\n", "\n", "# ============================================================================" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## 7. Save & Export\n", "\n", "Save XGBoost model, scaler, SHAP explainer, label encoder, and metadata.\n", "Benchmark inference time (target: <10ms per sprint)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"SECTION 7: Save & Export\")\n", "print(\"=\" * 60)\n", "\n", "SAVE_DIR = Path(\"/content/optimizer-model\") if Path(\"/content\").exists() else Path(\"./optimizer-model\")\n", "SAVE_DIR.mkdir(parents=True, exist_ok=True)\n", "\n", "# Save XGBoost model\n", "model_path = SAVE_DIR / \"optimizer_model.pkl\"\n", "joblib.dump(best_model, model_path)\n", "model_size = model_path.stat().st_size\n", "print(f\"Saved XGBoost model: {model_path} ({model_size / 1e6:.2f} MB)\")\n", "\n", "# Save scaler\n", "scaler_path = SAVE_DIR / \"optimizer_scaler.pkl\"\n", "joblib.dump(scaler, scaler_path)\n", "print(f\"Saved scaler: {scaler_path} ({scaler_path.stat().st_size / 1e3:.1f} KB)\")\n", "\n", "# Save SHAP explainer\n", "explainer_path = SAVE_DIR / \"optimizer_explainer.pkl\"\n", "joblib.dump(explainer, explainer_path)\n", "explainer_size = explainer_path.stat().st_size\n", "print(f\"Saved SHAP explainer: {explainer_path} ({explainer_size / 1e6:.2f} MB)\")\n", "\n", "# Save label encoder\n", "le_path = SAVE_DIR / \"optimizer_label_encoder.pkl\"\n", "joblib.dump(le, le_path)\n", "print(f\"Saved label encoder: {le_path}\")\n", "\n", "# Save SHAP plot if it was created\n", "for plot_file in [\"shap_feature_importance.png\", \"top_features_bar.png\"]:\n", " if os.path.isfile(plot_file):\n", " import shutil\n", " shutil.copy(plot_file, SAVE_DIR / plot_file)\n", " print(f\"Saved plot: {SAVE_DIR / plot_file}\")\n", "\n", "# Benchmark inference time\n", "print(\"\\nBenchmarking inference time...\")\n", "dummy = np.random.randn(1, len(FEATURE_NAMES)).astype(np.float32)\n", "dummy_scaled = scaler.transform(dummy)\n", "\n", "# Warm up\n", "for _ in range(20):\n", " best_model.predict_proba(dummy_scaled)\n", "\n", "times = []\n", "for _ in range(200):\n", " t0 = time.perf_counter()\n", " best_model.predict_proba(dummy_scaled)\n", " times.append(time.perf_counter() - t0)\n", "\n", "avg_ms = np.mean(times) * 1000\n", "p99_ms = np.percentile(times, 99) * 1000\n", "print(f\" XGBoost predict: avg={avg_ms:.3f}ms, p99={p99_ms:.3f}ms\")\n", "\n", "# SHAP inference time\n", "shap_times = []\n", "for _ in range(50):\n", " t0 = time.perf_counter()\n", " explainer.shap_values(dummy_scaled)\n", " shap_times.append(time.perf_counter() - t0)\n", "\n", "shap_avg_ms = np.mean(shap_times) * 1000\n", "print(f\" SHAP explain: avg={shap_avg_ms:.2f}ms\")\n", "print(f\" Total per sprint: ~{avg_ms + shap_avg_ms:.1f}ms\")\n", "\n", "target_met = (avg_ms + shap_avg_ms) < 10\n", "if target_met:\n", " print(f\" TARGET MET: <10ms per sprint prediction\")\n", "else:\n", " print(f\" Note: SHAP adds latency. Consider computing SHAP only on-demand.\")\n", "\n", "# Save metadata\n", "metadata = {\n", " \"model_type\": \"XGBClassifier\",\n", " \"model_version\": \"optimizer-v1\",\n", " \"best_params\": grid_search.best_params_,\n", " \"feature_names\": FEATURE_NAMES,\n", " \"feature_count\": len(FEATURE_NAMES),\n", " \"risk_levels\": RISK_LEVELS,\n", " \"training_examples\": len(df),\n", " \"test_accuracy\": round(test_acc, 4),\n", " \"test_f1_macro\": round(test_f1, 4),\n", " \"cv_f1_macro\": round(grid_search.best_score_, 4),\n", " \"top_features_shap\": [\n", " {\"name\": name, \"importance\": round(float(imp), 4)}\n", " for name, imp in shap_importance[:10]\n", " ],\n", " \"top_features_xgboost\": [\n", " {\"name\": name, \"importance\": round(float(imp), 4)}\n", " for name, imp in sorted(zip(FEATURE_NAMES, importance), key=lambda x: -x[1])[:10]\n", " ],\n", " \"bottleneck_types\": [\n", " \"member_overload\", \"blocked_tasks\", \"unassigned_critical\",\n", " \"velocity_lag\", \"deadline_risk\", \"scope_creep\",\n", " \"workload_imbalance\", \"overdue_tasks\",\n", " ],\n", " \"inference_time_ms\": round(avg_ms, 3),\n", " \"shap_time_ms\": round(shap_avg_ms, 2),\n", " \"model_size_mb\": round(model_size / 1e6, 2),\n", "}\n", "\n", "metadata_path = SAVE_DIR / \"training_metadata.json\"\n", "with open(metadata_path, \"w\") as f:\n", " json.dump(metadata, f, indent=2)\n", "print(f\"\\nSaved metadata: {metadata_path}\")\n", "\n", "# List saved files\n", "print(f\"\\nSaved files in {SAVE_DIR}:\")\n", "total_size = 0\n", "for fp in sorted(SAVE_DIR.iterdir()):\n", " size = fp.stat().st_size\n", " total_size += size\n", " label = f\"{size / 1e6:.2f} MB\" if size > 1e6 else f\"{size / 1e3:.1f} KB\"\n", " print(f\" {fp.name}: {label}\")\n", "print(f\" Total: {total_size / 1e6:.2f} MB\")\n", "\n", "# Zip for download\n", "import shutil\n", "zip_path = shutil.make_archive(\n", " base_name=str(SAVE_DIR),\n", " format=\"zip\",\n", " root_dir=str(SAVE_DIR.parent),\n", " base_dir=SAVE_DIR.name,\n", ")\n", "zip_size = os.path.getsize(zip_path)\n", "print(f\"\\nZip archive: {zip_path} ({zip_size / 1e6:.2f} MB)\")\n", "\n", "# Download in Colab\n", "try:\n", " from google.colab import files\n", " print(\"Downloading zip to your browser...\")\n", " files.download(zip_path)\n", "except ImportError:\n", " print(f\"Not in Colab — zip saved locally at: {zip_path}\")\n", "\n", "print(\"\\n\" + \"=\" * 60)\n", "print(\"TRAINING COMPLETE\")\n", "print(\"=\" * 60)\n", "print(f\"\\nModel: XGBClassifier ({grid_search.best_params_})\")\n", "print(f\"Accuracy: {test_acc:.4f}\")\n", "print(f\"Macro F1: {test_f1:.4f}\")\n", "print(f\"Inference: {avg_ms:.3f}ms per sprint\")\n", "print(f\"\\nTop 5 most important features:\")\n", "for name, imp in shap_importance[:5]:\n", " print(f\" {name}: {imp:.4f}\")\n", "print(f\"\\nTo deploy in AI server:\")\n", "print(f\" 1. Unzip optimizer-model.zip\")\n", "print(f\" 2. Copy contents to ai-server/model_weights/optimizer/\")\n", "print(f\" 3. Restart the AI server\")\n", "print(f\" 4. /health should show \\\"optimizer\\\": true\")" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.10.0" } }, "nbformat": 4, "nbformat_minor": 4 }