Upload 4 files
Browse files- HF_UPLOAD_INSTRUCTIONS.md +7 -0
- README.md +31 -7
- app.py +1344 -0
- requirements.txt +8 -0
HF_UPLOAD_INSTRUCTIONS.md
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Hugging Face Upload Instructions
|
| 2 |
+
|
| 3 |
+
1. Create a new Hugging Face Space.
|
| 4 |
+
2. Select SDK: Streamlit.
|
| 5 |
+
3. Upload all files/folders from this ZIP.
|
| 6 |
+
4. Make sure `app.py`, `requirements.txt`, and `README.md` are at the root.
|
| 7 |
+
5. The app should start automatically.
|
README.md
CHANGED
|
@@ -1,11 +1,35 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
-
sdk:
|
|
|
|
|
|
|
| 7 |
pinned: false
|
| 8 |
-
short_description: 'Predictive Preventive Maintenance dashboard for generator '
|
| 9 |
---
|
| 10 |
|
| 11 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
+
title: Generator PM Reliability Dashboard
|
| 3 |
+
emoji: ⚙️
|
| 4 |
+
colorFrom: red
|
| 5 |
+
colorTo: blue
|
| 6 |
+
sdk: streamlit
|
| 7 |
+
sdk_version: 1.40.0
|
| 8 |
+
app_file: app.py
|
| 9 |
pinned: false
|
|
|
|
| 10 |
---
|
| 11 |
|
| 12 |
+
# Generator Preventive Maintenance Reliability Dashboard
|
| 13 |
+
|
| 14 |
+
This Hugging Face Space demonstrates a predictive preventive maintenance workflow for generator reliability.
|
| 15 |
+
|
| 16 |
+
## Features
|
| 17 |
+
|
| 18 |
+
- PM-to-failure linking
|
| 19 |
+
- Days-to-next-failure analytics
|
| 20 |
+
- Executive KPIs
|
| 21 |
+
- Failure cost and downtime analysis
|
| 22 |
+
- Telemetry risk analysis
|
| 23 |
+
- Predictive ML and PM strategy
|
| 24 |
+
- Logistic Regression baseline
|
| 25 |
+
- Random Forest advanced model
|
| 26 |
+
- Failure-within-14-days and failure-within-30-days prediction
|
| 27 |
+
- Asset-level risk bands and recommended maintenance actions
|
| 28 |
+
|
| 29 |
+
## Data note
|
| 30 |
+
|
| 31 |
+
The included dataset is synthetic proof-of-concept data. It is not real production/customer data. It simulates the structure needed for production: asset master, PM events, failure tickets, telemetry signals, PM-to-failure output, and business impact fields.
|
| 32 |
+
|
| 33 |
+
## Upload your own data
|
| 34 |
+
|
| 35 |
+
Use the sidebar upload option to upload your own CSVs or ZIP.
|
app.py
ADDED
|
@@ -0,0 +1,1344 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import math
|
| 4 |
+
import zipfile
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Dict, Optional, Tuple
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
import pandas as pd
|
| 10 |
+
import plotly.express as px
|
| 11 |
+
import plotly.graph_objects as go
|
| 12 |
+
import streamlit as st
|
| 13 |
+
from sklearn.compose import ColumnTransformer
|
| 14 |
+
from sklearn.pipeline import Pipeline
|
| 15 |
+
from sklearn.preprocessing import OneHotEncoder, StandardScaler
|
| 16 |
+
from sklearn.impute import SimpleImputer
|
| 17 |
+
from sklearn.model_selection import train_test_split
|
| 18 |
+
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score, roc_auc_score, confusion_matrix
|
| 19 |
+
from sklearn.linear_model import LogisticRegression
|
| 20 |
+
from sklearn.ensemble import RandomForestClassifier
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
APP_DIR = Path(__file__).resolve().parent
|
| 24 |
+
DEFAULT_DATA_DIR = APP_DIR / "data" / "processed"
|
| 25 |
+
OUTPUT_FIG_DIR = APP_DIR / "outputs" / "figures"
|
| 26 |
+
OUTPUT_TABLE_DIR = APP_DIR / "outputs" / "tables"
|
| 27 |
+
RAW_DATA_DIR = APP_DIR / "data" / "raw"
|
| 28 |
+
DEFAULT_RAW_TELEMETRY_PATH = RAW_DATA_DIR / "generator_telemetry_with_labels.csv"
|
| 29 |
+
WSL_PROJECT_ROOT = Path("/mnt/c/Users/AnubhaAnubha/OneDrive - Pearce Services, LLC/onedrive_ubuntu/project/Predictive_Preventive_Maintenance_for_Generator_Reliability")
|
| 30 |
+
EXTERNAL_WSL_RAW_TELEMETRY_PATH = WSL_PROJECT_ROOT / "data" / "raw" / "generator_telemetry_with_labels.csv"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
# Snowflake Streamlit does not support page_title/page_icon in st.set_page_config.
|
| 34 |
+
# Keep layout only and continue safely if the runtime ignores this call.
|
| 35 |
+
try:
|
| 36 |
+
st.set_page_config(layout="wide", initial_sidebar_state="expanded")
|
| 37 |
+
except Exception:
|
| 38 |
+
pass
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# -----------------------------
|
| 42 |
+
# Utility helpers
|
| 43 |
+
# -----------------------------
|
| 44 |
+
def money(x):
|
| 45 |
+
try:
|
| 46 |
+
if pd.isna(x):
|
| 47 |
+
return "$0"
|
| 48 |
+
return f"${float(x):,.0f}"
|
| 49 |
+
except Exception:
|
| 50 |
+
return "$0"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def num(x, decimals=0):
|
| 54 |
+
try:
|
| 55 |
+
if pd.isna(x):
|
| 56 |
+
return "0"
|
| 57 |
+
return f"{float(x):,.{decimals}f}"
|
| 58 |
+
except Exception:
|
| 59 |
+
return "0"
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
def pct(x, decimals=1):
|
| 63 |
+
try:
|
| 64 |
+
if pd.isna(x):
|
| 65 |
+
return "0%"
|
| 66 |
+
return f"{float(x) * 100:.{decimals}f}%"
|
| 67 |
+
except Exception:
|
| 68 |
+
return "0%"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def read_csv_safely(path_or_buffer) -> pd.DataFrame:
|
| 72 |
+
return pd.read_csv(path_or_buffer)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def parse_date_cols(df: pd.DataFrame, cols) -> pd.DataFrame:
|
| 76 |
+
out = df.copy()
|
| 77 |
+
for c in cols:
|
| 78 |
+
if c in out.columns:
|
| 79 |
+
out[c] = pd.to_datetime(out[c], errors="coerce")
|
| 80 |
+
return out
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
@st.cache_data(show_spinner=False)
|
| 84 |
+
def load_default_tables() -> Dict[str, pd.DataFrame]:
|
| 85 |
+
tables = {}
|
| 86 |
+
files = {
|
| 87 |
+
"asset_master": "asset_master.csv",
|
| 88 |
+
"pm_events": "pm_events.csv",
|
| 89 |
+
"failure_events": "failure_events.csv",
|
| 90 |
+
"business_impact": "business_impact.csv",
|
| 91 |
+
"pm_failure_linked": "pm_failure_linked.csv",
|
| 92 |
+
"telemetry_weekly": "telemetry_weekly.csv",
|
| 93 |
+
}
|
| 94 |
+
for key, filename in files.items():
|
| 95 |
+
path = DEFAULT_DATA_DIR / filename
|
| 96 |
+
if path.exists():
|
| 97 |
+
tables[key] = pd.read_csv(path)
|
| 98 |
+
else:
|
| 99 |
+
tables[key] = pd.DataFrame()
|
| 100 |
+
|
| 101 |
+
tables["asset_master"] = parse_date_cols(tables["asset_master"], ["install_date"])
|
| 102 |
+
tables["pm_events"] = parse_date_cols(tables["pm_events"], ["scheduled_date", "completed_date", "pm_date"])
|
| 103 |
+
tables["failure_events"] = parse_date_cols(
|
| 104 |
+
tables["failure_events"], ["failure_date", "ticket_open_date", "ticket_close_date"]
|
| 105 |
+
)
|
| 106 |
+
tables["business_impact"] = parse_date_cols(tables["business_impact"], ["event_date"])
|
| 107 |
+
tables["pm_failure_linked"] = parse_date_cols(tables["pm_failure_linked"], ["pm_date", "next_failure_date"])
|
| 108 |
+
tables["telemetry_weekly"] = parse_date_cols(tables["telemetry_weekly"], ["timestamp"])
|
| 109 |
+
return tables
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
@st.cache_data(show_spinner=False)
|
| 113 |
+
def load_default_raw_telemetry() -> Tuple[pd.DataFrame, str]:
|
| 114 |
+
"""Load the raw telemetry file. On Hugging Face, use the packaged data folder first."""
|
| 115 |
+
if DEFAULT_RAW_TELEMETRY_PATH.exists():
|
| 116 |
+
df = pd.read_csv(DEFAULT_RAW_TELEMETRY_PATH)
|
| 117 |
+
return parse_date_cols(df, ["timestamp"]), str(DEFAULT_RAW_TELEMETRY_PATH)
|
| 118 |
+
if EXTERNAL_WSL_RAW_TELEMETRY_PATH.exists():
|
| 119 |
+
df = pd.read_csv(EXTERNAL_WSL_RAW_TELEMETRY_PATH)
|
| 120 |
+
return parse_date_cols(df, ["timestamp"]), str(EXTERNAL_WSL_RAW_TELEMETRY_PATH)
|
| 121 |
+
return pd.DataFrame(), "No raw telemetry file found"
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def dataframe_profile(df: pd.DataFrame, source_path: str) -> pd.DataFrame:
|
| 125 |
+
if df.empty:
|
| 126 |
+
return pd.DataFrame({"Metric": ["Source path", "Rows", "Columns"], "Value": [source_path, "0", "0"]})
|
| 127 |
+
values = {
|
| 128 |
+
"Source path": source_path,
|
| 129 |
+
"Rows": f"{len(df):,}",
|
| 130 |
+
"Columns": f"{len(df.columns):,}",
|
| 131 |
+
"Date range": "Not available",
|
| 132 |
+
"Duplicate rows": f"{int(df.duplicated().sum()):,}",
|
| 133 |
+
"Missing values": f"{int(df.isna().sum().sum()):,}",
|
| 134 |
+
}
|
| 135 |
+
if "timestamp" in df.columns:
|
| 136 |
+
ts = pd.to_datetime(df["timestamp"], errors="coerce")
|
| 137 |
+
if ts.notna().any():
|
| 138 |
+
values["Date range"] = f"{ts.min().date()} to {ts.max().date()}"
|
| 139 |
+
return pd.DataFrame({"Metric": list(values.keys()), "Value": list(values.values())})
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
def enrich_algorithm_output(raw_df: pd.DataFrame) -> pd.DataFrame:
|
| 143 |
+
"""Create a transparent demo algorithm output from raw telemetry columns."""
|
| 144 |
+
if raw_df.empty:
|
| 145 |
+
return pd.DataFrame()
|
| 146 |
+
out = raw_df.copy()
|
| 147 |
+
if "timestamp" in out.columns:
|
| 148 |
+
out["timestamp"] = pd.to_datetime(out["timestamp"], errors="coerce")
|
| 149 |
+
for c in ["anomaly_score", "days_since_last_pm", "failure_within_30d", "failure_within_14d"]:
|
| 150 |
+
if c in out.columns:
|
| 151 |
+
out[c] = pd.to_numeric(out[c], errors="coerce")
|
| 152 |
+
if "anomaly_score" not in out.columns:
|
| 153 |
+
numeric_cols = out.select_dtypes(include=[np.number]).columns.tolist()
|
| 154 |
+
if numeric_cols:
|
| 155 |
+
z = out[numeric_cols].fillna(out[numeric_cols].median(numeric_only=True))
|
| 156 |
+
out["anomaly_score"] = ((z - z.mean()) / z.std(ddof=0)).abs().mean(axis=1).rank(pct=True) * 100
|
| 157 |
+
else:
|
| 158 |
+
out["anomaly_score"] = 0
|
| 159 |
+
conditions = [
|
| 160 |
+
out["anomaly_score"] >= 80,
|
| 161 |
+
out["anomaly_score"] >= 60,
|
| 162 |
+
out["anomaly_score"] >= 40,
|
| 163 |
+
]
|
| 164 |
+
choices = ["Critical", "High", "Watch"]
|
| 165 |
+
out["algorithm_risk_band"] = np.select(conditions, choices, default="Low")
|
| 166 |
+
pm_age = pd.to_numeric(out.get("days_since_last_pm", pd.Series(0, index=out.index)), errors="coerce").fillna(0)
|
| 167 |
+
out["algorithm_failure_risk_score"] = np.clip((out["anomaly_score"].fillna(0) * 0.75) + np.minimum(pm_age, 180) / 180 * 25, 0, 100).round(2)
|
| 168 |
+
out["algorithm_predicted_failure_within_30d"] = (out["algorithm_failure_risk_score"] >= 70).astype(int)
|
| 169 |
+
out["recommended_action"] = np.select(
|
| 170 |
+
[out["algorithm_risk_band"].eq("Critical"), out["algorithm_risk_band"].eq("High"), out["algorithm_risk_band"].eq("Watch")],
|
| 171 |
+
["Immediate inspection / corrective work order", "Schedule PM within 7 days", "Monitor and plan PM",],
|
| 172 |
+
default="Normal monitoring",
|
| 173 |
+
)
|
| 174 |
+
sort_cols = [c for c in ["timestamp", "algorithm_failure_risk_score"] if c in out.columns]
|
| 175 |
+
if sort_cols:
|
| 176 |
+
out = out.sort_values(sort_cols, ascending=[False, False] if len(sort_cols) == 2 else False)
|
| 177 |
+
return out
|
| 178 |
+
|
| 179 |
+
|
| 180 |
+
def summarize_algorithm_by_asset(algo_df: pd.DataFrame) -> pd.DataFrame:
|
| 181 |
+
if algo_df.empty or "asset_id" not in algo_df.columns:
|
| 182 |
+
return pd.DataFrame()
|
| 183 |
+
df = algo_df.copy()
|
| 184 |
+
if "timestamp" in df.columns:
|
| 185 |
+
df = df.sort_values("timestamp")
|
| 186 |
+
latest = df.groupby("asset_id", as_index=False).tail(1).copy()
|
| 187 |
+
keep_cols = [c for c in ["asset_id", "timestamp", "model", "region", "criticality", "environment_type", "days_since_last_pm", "anomaly_score", "algorithm_failure_risk_score", "algorithm_risk_band", "algorithm_predicted_failure_within_30d", "recommended_action"] if c in latest.columns]
|
| 188 |
+
return latest[keep_cols].sort_values("algorithm_failure_risk_score", ascending=False)
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
|
| 192 |
+
# -----------------------------
|
| 193 |
+
# Machine Learning helpers
|
| 194 |
+
# -----------------------------
|
| 195 |
+
@st.cache_data(show_spinner=False)
|
| 196 |
+
def prepare_ml_frame(raw_df: pd.DataFrame, target_col: str = "failure_within_30d", max_rows: int = 90000):
|
| 197 |
+
"""Prepare telemetry data for supervised failure-risk modeling."""
|
| 198 |
+
if raw_df.empty or target_col not in raw_df.columns:
|
| 199 |
+
return pd.DataFrame(), [], []
|
| 200 |
+
|
| 201 |
+
use_cols = [
|
| 202 |
+
"asset_id", "age_years", "days_since_last_pm", "runtime_hours_week", "avg_load_pct", "oil_temp_c",
|
| 203 |
+
"coolant_temp_c", "battery_voltage", "vibration_mm_s", "fuel_rate_lph", "alarm_count", "anomaly_score",
|
| 204 |
+
"model", "region", "criticality", "environment_type", target_col, "timestamp"
|
| 205 |
+
]
|
| 206 |
+
use_cols = [c for c in use_cols if c in raw_df.columns]
|
| 207 |
+
df = raw_df[use_cols].copy().dropna(subset=[target_col])
|
| 208 |
+
if "timestamp" in df.columns:
|
| 209 |
+
df["timestamp"] = pd.to_datetime(df["timestamp"], errors="coerce")
|
| 210 |
+
df = df.sort_values("timestamp")
|
| 211 |
+
|
| 212 |
+
# Keep the app fast in Snowflake by training on a balanced sample.
|
| 213 |
+
if len(df) > max_rows:
|
| 214 |
+
pos = df[df[target_col] == 1]
|
| 215 |
+
neg = df[df[target_col] == 0]
|
| 216 |
+
n_pos = min(len(pos), max_rows // 3)
|
| 217 |
+
n_neg = max_rows - n_pos
|
| 218 |
+
df = pd.concat([
|
| 219 |
+
pos.sample(n=n_pos, random_state=42) if len(pos) > n_pos else pos,
|
| 220 |
+
neg.sample(n=n_neg, random_state=42) if len(neg) > n_neg else neg,
|
| 221 |
+
], axis=0).sample(frac=1, random_state=42)
|
| 222 |
+
|
| 223 |
+
feature_cols = [c for c in df.columns if c not in [target_col, "timestamp"]]
|
| 224 |
+
numeric_cols = [c for c in feature_cols if pd.api.types.is_numeric_dtype(df[c])]
|
| 225 |
+
categorical_cols = [c for c in feature_cols if c not in numeric_cols]
|
| 226 |
+
return df, numeric_cols, categorical_cols
|
| 227 |
+
|
| 228 |
+
|
| 229 |
+
@st.cache_resource(show_spinner=False)
|
| 230 |
+
def train_failure_models(df: pd.DataFrame, numeric_cols, categorical_cols, target_col: str = "failure_within_30d"):
|
| 231 |
+
"""Train baseline and advanced ML classifiers for near-term failure prediction."""
|
| 232 |
+
X = df[numeric_cols + categorical_cols]
|
| 233 |
+
y = df[target_col].astype(int)
|
| 234 |
+
X_train, X_test, y_train, y_test = train_test_split(
|
| 235 |
+
X, y, test_size=0.25, random_state=42, stratify=y
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
numeric_transformer = Pipeline(steps=[
|
| 239 |
+
("imputer", SimpleImputer(strategy="median")),
|
| 240 |
+
("scaler", StandardScaler()),
|
| 241 |
+
])
|
| 242 |
+
categorical_transformer = Pipeline(steps=[
|
| 243 |
+
("imputer", SimpleImputer(strategy="most_frequent")),
|
| 244 |
+
("onehot", OneHotEncoder(handle_unknown="ignore")),
|
| 245 |
+
])
|
| 246 |
+
preprocessor = ColumnTransformer(
|
| 247 |
+
transformers=[
|
| 248 |
+
("num", numeric_transformer, numeric_cols),
|
| 249 |
+
("cat", categorical_transformer, categorical_cols),
|
| 250 |
+
]
|
| 251 |
+
)
|
| 252 |
+
|
| 253 |
+
models = {
|
| 254 |
+
"Logistic Regression baseline": LogisticRegression(max_iter=500, class_weight="balanced"),
|
| 255 |
+
"Random Forest advanced model": RandomForestClassifier(
|
| 256 |
+
n_estimators=160,
|
| 257 |
+
max_depth=12,
|
| 258 |
+
min_samples_leaf=5,
|
| 259 |
+
random_state=42,
|
| 260 |
+
n_jobs=-1,
|
| 261 |
+
class_weight="balanced_subsample",
|
| 262 |
+
),
|
| 263 |
+
}
|
| 264 |
+
|
| 265 |
+
results = {}
|
| 266 |
+
for name, model in models.items():
|
| 267 |
+
pipe = Pipeline(steps=[("preprocessor", preprocessor), ("model", model)])
|
| 268 |
+
pipe.fit(X_train, y_train)
|
| 269 |
+
proba = pipe.predict_proba(X_test)[:, 1]
|
| 270 |
+
pred = (proba >= 0.5).astype(int)
|
| 271 |
+
results[name] = {
|
| 272 |
+
"pipeline": pipe,
|
| 273 |
+
"accuracy": accuracy_score(y_test, pred),
|
| 274 |
+
"precision": precision_score(y_test, pred, zero_division=0),
|
| 275 |
+
"recall": recall_score(y_test, pred, zero_division=0),
|
| 276 |
+
"f1": f1_score(y_test, pred, zero_division=0),
|
| 277 |
+
"roc_auc": roc_auc_score(y_test, proba),
|
| 278 |
+
"confusion_matrix": confusion_matrix(y_test, pred),
|
| 279 |
+
}
|
| 280 |
+
return results
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def get_ml_feature_importance(pipeline, model_name: str, top_n: int = 15) -> pd.DataFrame:
|
| 284 |
+
preprocessor = pipeline.named_steps["preprocessor"]
|
| 285 |
+
feature_names = preprocessor.get_feature_names_out()
|
| 286 |
+
model = pipeline.named_steps["model"]
|
| 287 |
+
if "Logistic" in model_name:
|
| 288 |
+
values = np.abs(model.coef_[0])
|
| 289 |
+
else:
|
| 290 |
+
values = model.feature_importances_
|
| 291 |
+
out = pd.DataFrame({"feature": feature_names, "importance": values})
|
| 292 |
+
out["feature"] = out["feature"].str.replace("num__", "", regex=False).str.replace("cat__", "", regex=False)
|
| 293 |
+
return out.sort_values("importance", ascending=False).head(top_n)
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def score_latest_asset_risk(telemetry_df: pd.DataFrame, pipeline) -> pd.DataFrame:
|
| 297 |
+
latest = telemetry_df.copy()
|
| 298 |
+
if latest.empty or "asset_id" not in latest.columns:
|
| 299 |
+
return pd.DataFrame()
|
| 300 |
+
if "timestamp" in latest.columns:
|
| 301 |
+
latest["timestamp"] = pd.to_datetime(latest["timestamp"], errors="coerce")
|
| 302 |
+
latest = latest.sort_values("timestamp").groupby("asset_id", as_index=False).tail(1)
|
| 303 |
+
|
| 304 |
+
feature_cols = [
|
| 305 |
+
"asset_id", "age_years", "days_since_last_pm", "runtime_hours_week", "avg_load_pct", "oil_temp_c",
|
| 306 |
+
"coolant_temp_c", "battery_voltage", "vibration_mm_s", "fuel_rate_lph", "alarm_count", "anomaly_score",
|
| 307 |
+
"model", "region", "criticality", "environment_type"
|
| 308 |
+
]
|
| 309 |
+
feature_cols = [c for c in feature_cols if c in latest.columns]
|
| 310 |
+
latest = latest.copy()
|
| 311 |
+
latest["ml_predicted_failure_risk"] = pipeline.predict_proba(latest[feature_cols])[:, 1]
|
| 312 |
+
latest["ml_risk_band"] = pd.cut(
|
| 313 |
+
latest["ml_predicted_failure_risk"],
|
| 314 |
+
bins=[-0.01, 0.30, 0.60, 0.80, 1.0],
|
| 315 |
+
labels=["Low", "Medium", "High", "Critical"],
|
| 316 |
+
)
|
| 317 |
+
latest["ml_recommended_action"] = np.select(
|
| 318 |
+
[
|
| 319 |
+
latest["ml_predicted_failure_risk"] >= 0.80,
|
| 320 |
+
latest["ml_predicted_failure_risk"] >= 0.60,
|
| 321 |
+
latest["ml_predicted_failure_risk"] >= 0.30,
|
| 322 |
+
],
|
| 323 |
+
[
|
| 324 |
+
"Immediate inspection / PM within 3 days",
|
| 325 |
+
"Schedule PM within 7 days",
|
| 326 |
+
"Watch list / inspect soon",
|
| 327 |
+
],
|
| 328 |
+
default="Normal monitoring",
|
| 329 |
+
)
|
| 330 |
+
keep = [c for c in [
|
| 331 |
+
"asset_id", "timestamp", "model", "region", "criticality", "days_since_last_pm",
|
| 332 |
+
"anomaly_score", "battery_voltage", "vibration_mm_s", "alarm_count",
|
| 333 |
+
"ml_predicted_failure_risk", "ml_risk_band", "ml_recommended_action"
|
| 334 |
+
] if c in latest.columns]
|
| 335 |
+
return latest[keep].sort_values("ml_predicted_failure_risk", ascending=False)
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
def build_prescriptive_pm_plan(ml_risk_df: pd.DataFrame, linked_df: pd.DataFrame, business_df: pd.DataFrame) -> pd.DataFrame:
|
| 339 |
+
if ml_risk_df.empty:
|
| 340 |
+
return pd.DataFrame()
|
| 341 |
+
plan = ml_risk_df.copy()
|
| 342 |
+
if not linked_df.empty and {"asset_id", "days_to_next_failure"}.issubset(linked_df.columns):
|
| 343 |
+
hist = linked_df.copy()
|
| 344 |
+
hist["days_to_next_failure"] = pd.to_numeric(hist["days_to_next_failure"], errors="coerce")
|
| 345 |
+
hist = hist.groupby("asset_id", as_index=False)["days_to_next_failure"].median()
|
| 346 |
+
hist = hist.rename(columns={"days_to_next_failure": "historical_median_days_to_failure"})
|
| 347 |
+
plan = plan.merge(hist, on="asset_id", how="left")
|
| 348 |
+
|
| 349 |
+
avg_failure_cost = 0.0
|
| 350 |
+
if not business_df.empty:
|
| 351 |
+
if "repair_cost" in business_df.columns:
|
| 352 |
+
avg_failure_cost += pd.to_numeric(business_df["repair_cost"], errors="coerce").fillna(0).mean()
|
| 353 |
+
if "truck_roll_cost" in business_df.columns:
|
| 354 |
+
avg_failure_cost += pd.to_numeric(business_df["truck_roll_cost"], errors="coerce").fillna(0).mean()
|
| 355 |
+
plan["estimated_failure_cost_exposure"] = avg_failure_cost
|
| 356 |
+
|
| 357 |
+
plan["prescriptive_pm_action"] = np.select(
|
| 358 |
+
[
|
| 359 |
+
plan["ml_predicted_failure_risk"] >= 0.80,
|
| 360 |
+
(plan["ml_predicted_failure_risk"] >= 0.60) | (pd.to_numeric(plan.get("days_since_last_pm", 0), errors="coerce").fillna(0) > 120),
|
| 361 |
+
plan["ml_predicted_failure_risk"] >= 0.30,
|
| 362 |
+
],
|
| 363 |
+
[
|
| 364 |
+
"Create urgent work order and inspect immediately",
|
| 365 |
+
"Plan PM in next 7 days and review alarms / vibration",
|
| 366 |
+
"Increase monitoring and inspect in next PM window",
|
| 367 |
+
],
|
| 368 |
+
default="Maintain current PM cycle",
|
| 369 |
+
)
|
| 370 |
+
plan["priority_rank"] = plan["ml_predicted_failure_risk"].rank(method="dense", ascending=False).astype(int)
|
| 371 |
+
return plan.sort_values("priority_rank")
|
| 372 |
+
|
| 373 |
+
def identify_uploaded_zip(uploaded_zip) -> Dict[str, pd.DataFrame]:
|
| 374 |
+
"""Accepts a zip containing CSVs with expected names."""
|
| 375 |
+
tables = {}
|
| 376 |
+
if uploaded_zip is None:
|
| 377 |
+
return tables
|
| 378 |
+
|
| 379 |
+
expected = {
|
| 380 |
+
"asset_master": "asset_master.csv",
|
| 381 |
+
"pm_events": "pm_events.csv",
|
| 382 |
+
"failure_events": "failure_events.csv",
|
| 383 |
+
"business_impact": "business_impact.csv",
|
| 384 |
+
"pm_failure_linked": "pm_failure_linked.csv",
|
| 385 |
+
"telemetry_weekly": "telemetry_weekly.csv",
|
| 386 |
+
}
|
| 387 |
+
|
| 388 |
+
with zipfile.ZipFile(uploaded_zip) as z:
|
| 389 |
+
names = z.namelist()
|
| 390 |
+
for key, filename in expected.items():
|
| 391 |
+
match = [n for n in names if n.endswith(filename)]
|
| 392 |
+
if match:
|
| 393 |
+
with z.open(match[0]) as f:
|
| 394 |
+
tables[key] = pd.read_csv(f)
|
| 395 |
+
return tables
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
def build_pm_failure_linked(pm_df: pd.DataFrame, failure_df: pd.DataFrame) -> pd.DataFrame:
|
| 399 |
+
required_pm = {"pm_event_id", "asset_id", "pm_date"}
|
| 400 |
+
required_fail = {"failure_event_id", "asset_id", "failure_date"}
|
| 401 |
+
|
| 402 |
+
if pm_df.empty or failure_df.empty:
|
| 403 |
+
return pd.DataFrame()
|
| 404 |
+
if not required_pm.issubset(pm_df.columns) or not required_fail.issubset(failure_df.columns):
|
| 405 |
+
return pd.DataFrame()
|
| 406 |
+
|
| 407 |
+
pm = parse_date_cols(pm_df, ["pm_date"]).copy()
|
| 408 |
+
failures = parse_date_cols(failure_df, ["failure_date"]).copy()
|
| 409 |
+
|
| 410 |
+
failure_groups = {}
|
| 411 |
+
for asset_id, g in failures.dropna(subset=["failure_date"]).sort_values("failure_date").groupby("asset_id"):
|
| 412 |
+
failure_groups[asset_id] = g.reset_index(drop=True)
|
| 413 |
+
|
| 414 |
+
rows = []
|
| 415 |
+
for _, row in pm.dropna(subset=["pm_date"]).iterrows():
|
| 416 |
+
asset_id = row["asset_id"]
|
| 417 |
+
pm_date = row["pm_date"]
|
| 418 |
+
next_fail = None
|
| 419 |
+
if asset_id in failure_groups:
|
| 420 |
+
g = failure_groups[asset_id]
|
| 421 |
+
pos = np.searchsorted(g["failure_date"].values.astype("datetime64[ns]"), np.datetime64(pm_date), side="right")
|
| 422 |
+
if pos < len(g):
|
| 423 |
+
next_fail = g.iloc[int(pos)]
|
| 424 |
+
|
| 425 |
+
if next_fail is not None:
|
| 426 |
+
days = (next_fail["failure_date"] - pm_date).days
|
| 427 |
+
rows.append({
|
| 428 |
+
"pm_event_id": row.get("pm_event_id"),
|
| 429 |
+
"asset_id": asset_id,
|
| 430 |
+
"pm_date": pm_date,
|
| 431 |
+
"next_failure_event_id": next_fail.get("failure_event_id"),
|
| 432 |
+
"next_failure_date": next_fail.get("failure_date"),
|
| 433 |
+
"days_to_next_failure": days,
|
| 434 |
+
"failure_found_flag": 1,
|
| 435 |
+
"ontime_flag": row.get("ontime_flag", np.nan),
|
| 436 |
+
"delay_days": row.get("delay_days", np.nan),
|
| 437 |
+
"pm_total_cost": row.get("total_cost", np.nan),
|
| 438 |
+
"failure_total_cost": next_fail.get("total_cost", np.nan),
|
| 439 |
+
"failure_category": next_fail.get("failure_category", "Unknown"),
|
| 440 |
+
})
|
| 441 |
+
else:
|
| 442 |
+
rows.append({
|
| 443 |
+
"pm_event_id": row.get("pm_event_id"),
|
| 444 |
+
"asset_id": asset_id,
|
| 445 |
+
"pm_date": pm_date,
|
| 446 |
+
"next_failure_event_id": None,
|
| 447 |
+
"next_failure_date": pd.NaT,
|
| 448 |
+
"days_to_next_failure": np.nan,
|
| 449 |
+
"failure_found_flag": 0,
|
| 450 |
+
"ontime_flag": row.get("ontime_flag", np.nan),
|
| 451 |
+
"delay_days": row.get("delay_days", np.nan),
|
| 452 |
+
"pm_total_cost": row.get("total_cost", np.nan),
|
| 453 |
+
"failure_total_cost": np.nan,
|
| 454 |
+
"failure_category": None,
|
| 455 |
+
})
|
| 456 |
+
|
| 457 |
+
return pd.DataFrame(rows)
|
| 458 |
+
|
| 459 |
+
|
| 460 |
+
def apply_asset_filters(tables: Dict[str, pd.DataFrame], regions, models, criticalities) -> Dict[str, pd.DataFrame]:
|
| 461 |
+
assets = tables.get("asset_master", pd.DataFrame()).copy()
|
| 462 |
+
if assets.empty:
|
| 463 |
+
return tables
|
| 464 |
+
|
| 465 |
+
mask = pd.Series(True, index=assets.index)
|
| 466 |
+
if regions and "region" in assets.columns:
|
| 467 |
+
mask &= assets["region"].isin(regions)
|
| 468 |
+
if models and "model" in assets.columns:
|
| 469 |
+
mask &= assets["model"].isin(models)
|
| 470 |
+
if criticalities and "criticality" in assets.columns:
|
| 471 |
+
mask &= assets["criticality"].isin(criticalities)
|
| 472 |
+
|
| 473 |
+
keep_assets = set(assets.loc[mask, "asset_id"].astype(str))
|
| 474 |
+
out = {}
|
| 475 |
+
for key, df in tables.items():
|
| 476 |
+
if isinstance(df, pd.DataFrame) and not df.empty and "asset_id" in df.columns:
|
| 477 |
+
out[key] = df[df["asset_id"].astype(str).isin(keep_assets)].copy()
|
| 478 |
+
else:
|
| 479 |
+
out[key] = df.copy() if isinstance(df, pd.DataFrame) else df
|
| 480 |
+
return out
|
| 481 |
+
|
| 482 |
+
|
| 483 |
+
def survival_curve(linked: pd.DataFrame) -> pd.DataFrame:
|
| 484 |
+
if linked.empty or "days_to_next_failure" not in linked.columns:
|
| 485 |
+
return pd.DataFrame(columns=["days", "failure_free_probability"])
|
| 486 |
+
d = linked.loc[linked["days_to_next_failure"].notna(), "days_to_next_failure"].astype(float)
|
| 487 |
+
if d.empty:
|
| 488 |
+
return pd.DataFrame(columns=["days", "failure_free_probability"])
|
| 489 |
+
days_grid = np.arange(0, max(30, int(d.max()) + 30), 30)
|
| 490 |
+
n = len(d)
|
| 491 |
+
vals = []
|
| 492 |
+
for day in days_grid:
|
| 493 |
+
vals.append({
|
| 494 |
+
"days": int(day),
|
| 495 |
+
"failure_free_probability": float((d > day).sum() / n)
|
| 496 |
+
})
|
| 497 |
+
return pd.DataFrame(vals)
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def make_download_zip(tables: Dict[str, pd.DataFrame]) -> bytes:
|
| 501 |
+
mem = io.BytesIO()
|
| 502 |
+
with zipfile.ZipFile(mem, "w", compression=zipfile.ZIP_DEFLATED) as z:
|
| 503 |
+
for name, df in tables.items():
|
| 504 |
+
if isinstance(df, pd.DataFrame) and not df.empty:
|
| 505 |
+
z.writestr(f"{name}.csv", df.to_csv(index=False))
|
| 506 |
+
mem.seek(0)
|
| 507 |
+
return mem.read()
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def metric_card(label, value, help_text=None):
|
| 511 |
+
st.metric(label, value, help=help_text)
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
# -----------------------------
|
| 515 |
+
# Sidebar: data loading
|
| 516 |
+
# -----------------------------
|
| 517 |
+
st.sidebar.title("⚙️ Dashboard Controls")
|
| 518 |
+
|
| 519 |
+
st.sidebar.markdown(
|
| 520 |
+
"""
|
| 521 |
+
**Data mode**
|
| 522 |
+
- Default mode loads the included generator PM demo dataset.
|
| 523 |
+
- Upload mode lets you override one or more CSVs.
|
| 524 |
+
"""
|
| 525 |
+
)
|
| 526 |
+
|
| 527 |
+
data_mode = st.sidebar.radio(
|
| 528 |
+
"Choose data source",
|
| 529 |
+
["Use included default dataset", "Upload my own CSVs / ZIP"],
|
| 530 |
+
index=0,
|
| 531 |
+
)
|
| 532 |
+
|
| 533 |
+
tables = load_default_tables()
|
| 534 |
+
raw_telemetry_df, raw_telemetry_source_path = load_default_raw_telemetry()
|
| 535 |
+
|
| 536 |
+
if data_mode == "Upload my own CSVs / ZIP":
|
| 537 |
+
st.sidebar.info("Upload a ZIP with expected CSV names, or upload individual CSVs below. Missing files fall back to default data.")
|
| 538 |
+
|
| 539 |
+
uploaded_zip = st.sidebar.file_uploader(
|
| 540 |
+
"Optional: upload full data ZIP",
|
| 541 |
+
type=["zip"],
|
| 542 |
+
help="ZIP may contain asset_master.csv, pm_events.csv, failure_events.csv, telemetry_weekly.csv, business_impact.csv, pm_failure_linked.csv",
|
| 543 |
+
)
|
| 544 |
+
try:
|
| 545 |
+
zip_tables = identify_uploaded_zip(uploaded_zip)
|
| 546 |
+
for k, v in zip_tables.items():
|
| 547 |
+
tables[k] = v
|
| 548 |
+
except Exception as e:
|
| 549 |
+
st.sidebar.error(f"Could not read ZIP: {e}")
|
| 550 |
+
|
| 551 |
+
upload_specs = {
|
| 552 |
+
"asset_master": "asset_master.csv",
|
| 553 |
+
"pm_events": "pm_events.csv",
|
| 554 |
+
"failure_events": "failure_events.csv",
|
| 555 |
+
"business_impact": "business_impact.csv",
|
| 556 |
+
"pm_failure_linked": "pm_failure_linked.csv",
|
| 557 |
+
"telemetry_weekly": "telemetry_weekly.csv",
|
| 558 |
+
}
|
| 559 |
+
|
| 560 |
+
with st.sidebar.expander("Upload individual CSVs"):
|
| 561 |
+
for key, label in upload_specs.items():
|
| 562 |
+
f = st.file_uploader(label, type=["csv"], key=f"upload_{key}")
|
| 563 |
+
if f is not None:
|
| 564 |
+
try:
|
| 565 |
+
tables[key] = pd.read_csv(f)
|
| 566 |
+
except Exception as e:
|
| 567 |
+
st.error(f"Could not read {label}: {e}")
|
| 568 |
+
|
| 569 |
+
with st.sidebar.expander("Upload raw telemetry CSV"):
|
| 570 |
+
raw_file = st.file_uploader(
|
| 571 |
+
"generator_telemetry_with_labels.csv",
|
| 572 |
+
type=["csv"],
|
| 573 |
+
key="upload_raw_telemetry",
|
| 574 |
+
help="Optional raw telemetry file before algorithm enrichment. If omitted, dashboard uses the WSL path when found, otherwise the included package file.",
|
| 575 |
+
)
|
| 576 |
+
if raw_file is not None:
|
| 577 |
+
try:
|
| 578 |
+
raw_telemetry_df = parse_date_cols(pd.read_csv(raw_file), ["timestamp"])
|
| 579 |
+
raw_telemetry_source_path = "Uploaded file: generator_telemetry_with_labels.csv"
|
| 580 |
+
except Exception as e:
|
| 581 |
+
st.error(f"Could not read raw telemetry CSV: {e}")
|
| 582 |
+
# Parse dates after custom upload.
|
| 583 |
+
tables["asset_master"] = parse_date_cols(tables.get("asset_master", pd.DataFrame()), ["install_date"])
|
| 584 |
+
tables["pm_events"] = parse_date_cols(tables.get("pm_events", pd.DataFrame()), ["scheduled_date", "completed_date", "pm_date"])
|
| 585 |
+
tables["failure_events"] = parse_date_cols(tables.get("failure_events", pd.DataFrame()), ["failure_date", "ticket_open_date", "ticket_close_date"])
|
| 586 |
+
tables["business_impact"] = parse_date_cols(tables.get("business_impact", pd.DataFrame()), ["event_date"])
|
| 587 |
+
tables["pm_failure_linked"] = parse_date_cols(tables.get("pm_failure_linked", pd.DataFrame()), ["pm_date", "next_failure_date"])
|
| 588 |
+
tables["telemetry_weekly"] = parse_date_cols(tables.get("telemetry_weekly", pd.DataFrame()), ["timestamp"])
|
| 589 |
+
raw_telemetry_df = parse_date_cols(raw_telemetry_df, ["timestamp"])
|
| 590 |
+
algorithm_output_df = enrich_algorithm_output(raw_telemetry_df)
|
| 591 |
+
algorithm_asset_summary_df = summarize_algorithm_by_asset(algorithm_output_df)
|
| 592 |
+
|
| 593 |
+
# If the user uploaded PM/failure but not linked, rebuild it.
|
| 594 |
+
if tables.get("pm_failure_linked", pd.DataFrame()).empty and not tables.get("pm_events", pd.DataFrame()).empty and not tables.get("failure_events", pd.DataFrame()).empty:
|
| 595 |
+
tables["pm_failure_linked"] = build_pm_failure_linked(tables["pm_events"], tables["failure_events"])
|
| 596 |
+
|
| 597 |
+
# Also allow forced rebuild.
|
| 598 |
+
if st.sidebar.button("Rebuild PM → Failure Links"):
|
| 599 |
+
tables["pm_failure_linked"] = build_pm_failure_linked(tables["pm_events"], tables["failure_events"])
|
| 600 |
+
st.sidebar.success("Rebuilt pm_failure_linked from PM and failure tables.")
|
| 601 |
+
|
| 602 |
+
assets = tables.get("asset_master", pd.DataFrame())
|
| 603 |
+
regions = []
|
| 604 |
+
models = []
|
| 605 |
+
criticalities = []
|
| 606 |
+
if not assets.empty:
|
| 607 |
+
if "region" in assets.columns:
|
| 608 |
+
all_regions = sorted([x for x in assets["region"].dropna().unique().tolist()])
|
| 609 |
+
regions = st.sidebar.multiselect("Filter region", all_regions, default=all_regions)
|
| 610 |
+
if "model" in assets.columns:
|
| 611 |
+
all_models = sorted([x for x in assets["model"].dropna().unique().tolist()])
|
| 612 |
+
models = st.sidebar.multiselect("Filter model", all_models, default=all_models)
|
| 613 |
+
if "criticality" in assets.columns:
|
| 614 |
+
all_criticality = sorted([x for x in assets["criticality"].dropna().unique().tolist()])
|
| 615 |
+
criticalities = st.sidebar.multiselect("Filter criticality", all_criticality, default=all_criticality)
|
| 616 |
+
|
| 617 |
+
sample_limit = st.sidebar.slider("Telemetry chart sample size", 1_000, 50_000, 10_000, step=1_000)
|
| 618 |
+
|
| 619 |
+
filtered = apply_asset_filters(tables, regions, models, criticalities)
|
| 620 |
+
|
| 621 |
+
asset_df = filtered.get("asset_master", pd.DataFrame())
|
| 622 |
+
pm_df = filtered.get("pm_events", pd.DataFrame())
|
| 623 |
+
failure_df = filtered.get("failure_events", pd.DataFrame())
|
| 624 |
+
business_df = filtered.get("business_impact", pd.DataFrame())
|
| 625 |
+
linked_df = filtered.get("pm_failure_linked", pd.DataFrame())
|
| 626 |
+
telemetry_df = filtered.get("telemetry_weekly", pd.DataFrame())
|
| 627 |
+
|
| 628 |
+
# -----------------------------
|
| 629 |
+
# Header
|
| 630 |
+
# -----------------------------
|
| 631 |
+
st.title("⚙️ Generator Preventive Maintenance Reliability Dashboard")
|
| 632 |
+
st.caption("Upload your own maintenance data or use the included demo dataset to analyze PM effectiveness, failure risk, and business impact.")
|
| 633 |
+
|
| 634 |
+
with st.expander("Expected CSV inputs", expanded=False):
|
| 635 |
+
st.markdown(
|
| 636 |
+
"""
|
| 637 |
+
**Recommended CSVs**
|
| 638 |
+
- `asset_master.csv`: one row per generator/asset
|
| 639 |
+
- `pm_events.csv`: preventive maintenance events
|
| 640 |
+
- `failure_events.csv`: unplanned repair/failure tickets
|
| 641 |
+
- `pm_failure_linked.csv`: optional; dashboard can rebuild it
|
| 642 |
+
- `telemetry_weekly.csv`: optional sensor/risk history
|
| 643 |
+
- `generator_telemetry_with_labels.csv`: optional ML training table with `failure_within_14d` and `failure_within_30d`
|
| 644 |
+
- `business_impact.csv`: optional downtime, repair cost, customer impact
|
| 645 |
+
|
| 646 |
+
**Minimum required for PM-to-failure analysis**
|
| 647 |
+
- `pm_events.csv` with `pm_event_id`, `asset_id`, `pm_date`
|
| 648 |
+
- `failure_events.csv` with `failure_event_id`, `asset_id`, `failure_date`
|
| 649 |
+
"""
|
| 650 |
+
)
|
| 651 |
+
|
| 652 |
+
# -----------------------------
|
| 653 |
+
# Tabs
|
| 654 |
+
# -----------------------------
|
| 655 |
+
tabs = st.tabs([
|
| 656 |
+
"Problem & Solution",
|
| 657 |
+
"Dataset & Raw → Algorithm",
|
| 658 |
+
"Executive KPIs",
|
| 659 |
+
"PM Effectiveness",
|
| 660 |
+
"Failures & Cost",
|
| 661 |
+
"Telemetry Risk",
|
| 662 |
+
"Predictive ML & PM Strategy",
|
| 663 |
+
"Saved Outputs",
|
| 664 |
+
"Data Explorer & Export",
|
| 665 |
+
])
|
| 666 |
+
|
| 667 |
+
|
| 668 |
+
# -----------------------------
|
| 669 |
+
# Problem & Solution tab
|
| 670 |
+
# -----------------------------
|
| 671 |
+
with tabs[0]:
|
| 672 |
+
st.header("Problem Statement")
|
| 673 |
+
st.markdown(
|
| 674 |
+
"""
|
| 675 |
+
Telecom and field-service teams need to know whether **preventive maintenance is actually preventing generator failures**.
|
| 676 |
+
|
| 677 |
+
The key business question is:
|
| 678 |
+
|
| 679 |
+
> After a PM is completed, how long does a generator typically run before the next failure or repair ticket?
|
| 680 |
+
|
| 681 |
+
Without this, teams cannot confidently answer:
|
| 682 |
+
- Which PMs are effective?
|
| 683 |
+
- Which assets are becoming risky?
|
| 684 |
+
- How much downtime and cost can be avoided?
|
| 685 |
+
- Which regions, models, or environments need more attention?
|
| 686 |
+
"""
|
| 687 |
+
)
|
| 688 |
+
|
| 689 |
+
st.header("Solution Provided")
|
| 690 |
+
st.markdown(
|
| 691 |
+
"""
|
| 692 |
+
This dashboard converts maintenance records into a reliability workflow:
|
| 693 |
+
|
| 694 |
+
1. **Load data**
|
| 695 |
+
Use the included generator demo dataset or upload your own CSVs.
|
| 696 |
+
|
| 697 |
+
2. **Link PM to next failure**
|
| 698 |
+
For every PM event, the dashboard finds the first later failure ticket for the same asset.
|
| 699 |
+
|
| 700 |
+
3. **Measure PM effectiveness**
|
| 701 |
+
It calculates `days_to_next_failure`, failure-free rate, and on-time vs delayed PM comparisons.
|
| 702 |
+
|
| 703 |
+
4. **Analyze failure cost and downtime**
|
| 704 |
+
It summarizes repair cost, truck-roll cost, downtime, SLA impact, and customer impact.
|
| 705 |
+
|
| 706 |
+
5. **Train ML failure-risk models**
|
| 707 |
+
Logistic Regression and Random Forest predict whether a generator may fail within 14 or 30 days.
|
| 708 |
+
|
| 709 |
+
6. **Prescribe PM actions**
|
| 710 |
+
ML risk scores are converted into priority bands and recommended maintenance actions.
|
| 711 |
+
|
| 712 |
+
7. **Export outputs**
|
| 713 |
+
KPI tables and processed datasets can be downloaded for Power BI, Excel, Streamlit sharing, or a client deck.
|
| 714 |
+
"""
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
st.subheader("Architecture")
|
| 718 |
+
st.code(
|
| 719 |
+
"""
|
| 720 |
+
PM Events + Failure Tickets + Asset Master
|
| 721 |
+
│
|
| 722 |
+
▼
|
| 723 |
+
PM → Next Failure Linker
|
| 724 |
+
│
|
| 725 |
+
├── PM effectiveness KPIs
|
| 726 |
+
├── Failure-free survival curve
|
| 727 |
+
├── On-time vs delayed PM comparison
|
| 728 |
+
├── Failure cost and downtime view
|
| 729 |
+
└── Telemetry risk overlay
|
| 730 |
+
""",
|
| 731 |
+
language="text",
|
| 732 |
+
)
|
| 733 |
+
|
| 734 |
+
st.subheader("Dataset currently loaded")
|
| 735 |
+
c1, c2, c3, c4, c5 = st.columns(5)
|
| 736 |
+
c1.metric("Assets", f"{len(asset_df):,}")
|
| 737 |
+
c2.metric("PM events", f"{len(pm_df):,}")
|
| 738 |
+
c3.metric("Failure tickets", f"{len(failure_df):,}")
|
| 739 |
+
c4.metric("Telemetry rows", f"{len(telemetry_df):,}")
|
| 740 |
+
c5.metric("Linked PM rows", f"{len(linked_df):,}")
|
| 741 |
+
|
| 742 |
+
|
| 743 |
+
# -----------------------------
|
| 744 |
+
# -----------------------------
|
| 745 |
+
# Dataset and Raw → Algorithm tab
|
| 746 |
+
# -----------------------------
|
| 747 |
+
with tabs[1]:
|
| 748 |
+
st.header("Dataset Used: Raw → Algorithm Output")
|
| 749 |
+
st.markdown(
|
| 750 |
+
"""
|
| 751 |
+
This page explains exactly what data is being used, where it is expected in WSL, what the raw file looks like before the algorithm, and what the algorithm produces after enrichment.
|
| 752 |
+
|
| 753 |
+
**Primary raw dataset expected by the project:**
|
| 754 |
+
"""
|
| 755 |
+
)
|
| 756 |
+
st.code(str(EXTERNAL_WSL_RAW_TELEMETRY_PATH), language="bash")
|
| 757 |
+
st.markdown("**Package fallback raw dataset:**")
|
| 758 |
+
st.code(str(DEFAULT_RAW_TELEMETRY_PATH), language="bash")
|
| 759 |
+
|
| 760 |
+
st.info(
|
| 761 |
+
f"Currently loaded raw telemetry source: {raw_telemetry_source_path}\n\n"
|
| 762 |
+
"The dashboard first checks the WSL project path you provided. If that file is not present, it uses the packaged demo raw file."
|
| 763 |
+
)
|
| 764 |
+
|
| 765 |
+
st.subheader("1) Raw dataset profile before algorithm")
|
| 766 |
+
st.dataframe(dataframe_profile(raw_telemetry_df, raw_telemetry_source_path), use_container_width=True)
|
| 767 |
+
|
| 768 |
+
if raw_telemetry_df.empty:
|
| 769 |
+
st.warning("Raw telemetry dataset is not available. Place generator_telemetry_with_labels.csv at the WSL path above or upload it from the sidebar.")
|
| 770 |
+
else:
|
| 771 |
+
c1, c2 = st.columns([2, 1])
|
| 772 |
+
with c1:
|
| 773 |
+
st.markdown("**Raw telemetry preview**")
|
| 774 |
+
st.dataframe(raw_telemetry_df.head(1000), use_container_width=True)
|
| 775 |
+
with c2:
|
| 776 |
+
missing = raw_telemetry_df.isna().sum().sort_values(ascending=False).head(12).reset_index()
|
| 777 |
+
missing.columns = ["column", "missing_count"]
|
| 778 |
+
fig = px.bar(missing, x="missing_count", y="column", orientation="h", title="Raw missing values by column")
|
| 779 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 780 |
+
|
| 781 |
+
st.markdown("**Raw signal visualizations before algorithm**")
|
| 782 |
+
c3, c4 = st.columns(2)
|
| 783 |
+
with c3:
|
| 784 |
+
if "anomaly_score" in raw_telemetry_df.columns:
|
| 785 |
+
fig = px.histogram(raw_telemetry_df, x="anomaly_score", nbins=50, title="Raw anomaly score distribution")
|
| 786 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 787 |
+
elif "runtime_hours_week" in raw_telemetry_df.columns:
|
| 788 |
+
fig = px.histogram(raw_telemetry_df, x="runtime_hours_week", nbins=50, title="Raw weekly runtime distribution")
|
| 789 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 790 |
+
with c4:
|
| 791 |
+
signal_cols = [c for c in ["oil_temp_c", "coolant_temp_c", "battery_voltage", "vibration_mm_s", "fuel_rate_lph", "runtime_hours_week"] if c in raw_telemetry_df.columns]
|
| 792 |
+
if signal_cols and "timestamp" in raw_telemetry_df.columns:
|
| 793 |
+
sample_asset = raw_telemetry_df["asset_id"].iloc[0] if "asset_id" in raw_telemetry_df.columns else None
|
| 794 |
+
signal = signal_cols[0]
|
| 795 |
+
plot_df = raw_telemetry_df[raw_telemetry_df["asset_id"].eq(sample_asset)].copy() if sample_asset and "asset_id" in raw_telemetry_df.columns else raw_telemetry_df.head(200)
|
| 796 |
+
fig = px.line(plot_df.sort_values("timestamp"), x="timestamp", y=signal, title=f"Raw signal trend example: {signal}")
|
| 797 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 798 |
+
|
| 799 |
+
st.subheader("2) Algorithm applied")
|
| 800 |
+
st.markdown(
|
| 801 |
+
"""
|
| 802 |
+
The dashboard creates a transparent demo algorithm layer from the raw telemetry:
|
| 803 |
+
|
| 804 |
+
- Uses `anomaly_score` as the main health signal.
|
| 805 |
+
- Adds PM-age pressure using `days_since_last_pm`.
|
| 806 |
+
- Produces `algorithm_failure_risk_score` on a 0–100 scale.
|
| 807 |
+
- Converts risk score into `Low`, `Watch`, `High`, or `Critical` bands.
|
| 808 |
+
- Adds `algorithm_predicted_failure_within_30d` and a recommended maintenance action.
|
| 809 |
+
|
| 810 |
+
This is intentionally explainable for a business demo. When real client data is available, this layer can be replaced by a trained classifier, survival model, or remaining-useful-life model.
|
| 811 |
+
"""
|
| 812 |
+
)
|
| 813 |
+
|
| 814 |
+
st.code(
|
| 815 |
+
"""
|
| 816 |
+
algorithm_failure_risk_score = 0.75 * anomaly_score + 0.25 * normalized_days_since_last_pm
|
| 817 |
+
risk bands:
|
| 818 |
+
Low < 40
|
| 819 |
+
Watch 40–59
|
| 820 |
+
High 60–79
|
| 821 |
+
Critical >= 80
|
| 822 |
+
prediction:
|
| 823 |
+
predicted_failure_within_30d = 1 when risk_score >= 70
|
| 824 |
+
""".strip(),
|
| 825 |
+
language="text",
|
| 826 |
+
)
|
| 827 |
+
|
| 828 |
+
st.subheader("3) After algorithm: enriched output")
|
| 829 |
+
if algorithm_output_df.empty:
|
| 830 |
+
st.warning("Algorithm output is empty because no raw telemetry was loaded.")
|
| 831 |
+
else:
|
| 832 |
+
c5, c6, c7, c8 = st.columns(4)
|
| 833 |
+
c5.metric("Raw rows processed", f"{len(raw_telemetry_df):,}")
|
| 834 |
+
c6.metric("Algorithm output rows", f"{len(algorithm_output_df):,}")
|
| 835 |
+
c7.metric("Assets scored", f"{algorithm_output_df['asset_id'].nunique():,}" if "asset_id" in algorithm_output_df.columns else "0")
|
| 836 |
+
c8.metric("Predicted 30-day failures", f"{int(algorithm_output_df.get('algorithm_predicted_failure_within_30d', pd.Series(dtype=int)).sum()):,}")
|
| 837 |
+
|
| 838 |
+
c9, c10 = st.columns(2)
|
| 839 |
+
with c9:
|
| 840 |
+
risk_counts = algorithm_output_df["algorithm_risk_band"].value_counts().reindex(["Low", "Watch", "High", "Critical"]).dropna().reset_index()
|
| 841 |
+
risk_counts.columns = ["risk_band", "row_count"]
|
| 842 |
+
fig = px.bar(risk_counts, x="risk_band", y="row_count", title="After algorithm: risk-band distribution")
|
| 843 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 844 |
+
with c10:
|
| 845 |
+
if {"region", "algorithm_predicted_failure_within_30d"}.issubset(algorithm_output_df.columns):
|
| 846 |
+
region_risk = algorithm_output_df.groupby("region", as_index=False)["algorithm_predicted_failure_within_30d"].sum()
|
| 847 |
+
fig = px.bar(region_risk, x="region", y="algorithm_predicted_failure_within_30d", title="Predicted 30-day failures by region")
|
| 848 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 849 |
+
|
| 850 |
+
st.markdown("**Algorithm output preview**")
|
| 851 |
+
output_cols = [c for c in ["asset_id", "timestamp", "model", "region", "criticality", "days_since_last_pm", "anomaly_score", "algorithm_failure_risk_score", "algorithm_risk_band", "algorithm_predicted_failure_within_30d", "recommended_action"] if c in algorithm_output_df.columns]
|
| 852 |
+
st.dataframe(algorithm_output_df[output_cols].head(2000), use_container_width=True)
|
| 853 |
+
|
| 854 |
+
st.markdown("**Latest asset-level output after algorithm**")
|
| 855 |
+
st.dataframe(algorithm_asset_summary_df.head(500), use_container_width=True)
|
| 856 |
+
|
| 857 |
+
st.download_button(
|
| 858 |
+
"Download algorithm_output.csv",
|
| 859 |
+
data=algorithm_output_df.to_csv(index=False),
|
| 860 |
+
file_name="algorithm_output.csv",
|
| 861 |
+
mime="text/csv",
|
| 862 |
+
)
|
| 863 |
+
st.download_button(
|
| 864 |
+
"Download latest_asset_risk_summary.csv",
|
| 865 |
+
data=algorithm_asset_summary_df.to_csv(index=False),
|
| 866 |
+
file_name="latest_asset_risk_summary.csv",
|
| 867 |
+
mime="text/csv",
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
st.subheader("4) WSL commands to run dashboard")
|
| 871 |
+
st.code(
|
| 872 |
+
"""
|
| 873 |
+
cd "/mnt/c/Users/AnubhaAnubha/OneDrive - Pearce Services, LLC/onedrive_ubuntu/project/Predictive_Preventive_Maintenance_for_Generator_Reliability"
|
| 874 |
+
pip install -r requirements.txt
|
| 875 |
+
streamlit run app.py
|
| 876 |
+
""".strip(),
|
| 877 |
+
language="bash",
|
| 878 |
+
)
|
| 879 |
+
|
| 880 |
+
# Executive KPIs tab
|
| 881 |
+
# -----------------------------
|
| 882 |
+
with tabs[2]:
|
| 883 |
+
st.header("Executive KPIs")
|
| 884 |
+
|
| 885 |
+
valid_days = pd.Series(dtype=float)
|
| 886 |
+
if not linked_df.empty and "days_to_next_failure" in linked_df.columns:
|
| 887 |
+
valid_days = pd.to_numeric(linked_df["days_to_next_failure"], errors="coerce").dropna()
|
| 888 |
+
|
| 889 |
+
avg_days = valid_days.mean() if not valid_days.empty else np.nan
|
| 890 |
+
median_days = valid_days.median() if not valid_days.empty else np.nan
|
| 891 |
+
fail_30 = (valid_days <= 30).mean() if not valid_days.empty else np.nan
|
| 892 |
+
fail_90 = (valid_days <= 90).mean() if not valid_days.empty else np.nan
|
| 893 |
+
|
| 894 |
+
total_downtime = pd.to_numeric(failure_df.get("downtime_hours", pd.Series(dtype=float)), errors="coerce").sum()
|
| 895 |
+
total_failure_cost = pd.to_numeric(failure_df.get("total_cost", pd.Series(dtype=float)), errors="coerce").sum()
|
| 896 |
+
|
| 897 |
+
total_revenue_loss = 0
|
| 898 |
+
total_customers = 0
|
| 899 |
+
if not business_df.empty:
|
| 900 |
+
total_revenue_loss = pd.to_numeric(business_df.get("estimated_revenue_loss", pd.Series(dtype=float)), errors="coerce").sum()
|
| 901 |
+
total_customers = pd.to_numeric(business_df.get("estimated_customers_impacted", pd.Series(dtype=float)), errors="coerce").sum()
|
| 902 |
+
|
| 903 |
+
c1, c2, c3, c4 = st.columns(4)
|
| 904 |
+
c1.metric("Avg days PM → failure", num(avg_days, 1))
|
| 905 |
+
c2.metric("Median days PM → failure", num(median_days, 1))
|
| 906 |
+
c3.metric("Failure within 30 days", pct(fail_30))
|
| 907 |
+
c4.metric("Failure within 90 days", pct(fail_90))
|
| 908 |
+
|
| 909 |
+
c5, c6, c7, c8 = st.columns(4)
|
| 910 |
+
c5.metric("Total downtime hours", num(total_downtime, 1))
|
| 911 |
+
c6.metric("Failure repair cost", money(total_failure_cost))
|
| 912 |
+
c7.metric("Estimated revenue loss", money(total_revenue_loss))
|
| 913 |
+
c8.metric("Customer impact count", num(total_customers, 0))
|
| 914 |
+
|
| 915 |
+
st.divider()
|
| 916 |
+
|
| 917 |
+
st.subheader("Executive interpretation")
|
| 918 |
+
st.markdown(
|
| 919 |
+
f"""
|
| 920 |
+
- The loaded data contains **{len(asset_df):,} assets**, **{len(pm_df):,} PM events**, and **{len(failure_df):,} failure/repair tickets**.
|
| 921 |
+
- The average observed time from PM to the next failure is **{num(avg_days, 1)} days**.
|
| 922 |
+
- **{pct(fail_30)}** of linked PM events are followed by a failure within 30 days.
|
| 923 |
+
- The failure records represent approximately **{num(total_downtime, 1)} downtime hours** and **{money(total_failure_cost)}** in repair cost.
|
| 924 |
+
"""
|
| 925 |
+
)
|
| 926 |
+
|
| 927 |
+
if not linked_df.empty and "failure_found_flag" in linked_df.columns:
|
| 928 |
+
status_counts = linked_df["failure_found_flag"].value_counts().rename(index={0: "No later failure observed", 1: "Later failure observed"})
|
| 929 |
+
fig = px.pie(
|
| 930 |
+
values=status_counts.values,
|
| 931 |
+
names=status_counts.index,
|
| 932 |
+
title="Linked PM events with later failure observed",
|
| 933 |
+
hole=0.35,
|
| 934 |
+
)
|
| 935 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 936 |
+
|
| 937 |
+
|
| 938 |
+
# -----------------------------
|
| 939 |
+
# PM Effectiveness tab
|
| 940 |
+
# -----------------------------
|
| 941 |
+
with tabs[3]:
|
| 942 |
+
st.header("Preventive Maintenance Effectiveness")
|
| 943 |
+
|
| 944 |
+
if linked_df.empty or "days_to_next_failure" not in linked_df.columns:
|
| 945 |
+
st.warning("No PM-to-failure linked data found. Upload PM and failure CSVs, then click 'Rebuild PM → Failure Links'.")
|
| 946 |
+
else:
|
| 947 |
+
linked_plot = linked_df.copy()
|
| 948 |
+
linked_plot["days_to_next_failure"] = pd.to_numeric(linked_plot["days_to_next_failure"], errors="coerce")
|
| 949 |
+
|
| 950 |
+
c1, c2 = st.columns(2)
|
| 951 |
+
|
| 952 |
+
with c1:
|
| 953 |
+
fig = px.histogram(
|
| 954 |
+
linked_plot.dropna(subset=["days_to_next_failure"]),
|
| 955 |
+
x="days_to_next_failure",
|
| 956 |
+
nbins=50,
|
| 957 |
+
title="Distribution: Days from PM to next failure",
|
| 958 |
+
labels={"days_to_next_failure": "Days to next failure"},
|
| 959 |
+
)
|
| 960 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 961 |
+
|
| 962 |
+
with c2:
|
| 963 |
+
surv = survival_curve(linked_plot)
|
| 964 |
+
if not surv.empty:
|
| 965 |
+
fig = px.line(
|
| 966 |
+
surv,
|
| 967 |
+
x="days",
|
| 968 |
+
y="failure_free_probability",
|
| 969 |
+
markers=True,
|
| 970 |
+
title="Failure-free probability after PM",
|
| 971 |
+
labels={"days": "Days after PM", "failure_free_probability": "Failure-free probability"},
|
| 972 |
+
)
|
| 973 |
+
fig.update_yaxes(tickformat=".0%")
|
| 974 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 975 |
+
|
| 976 |
+
c3, c4 = st.columns(2)
|
| 977 |
+
with c3:
|
| 978 |
+
if "ontime_flag" in linked_plot.columns:
|
| 979 |
+
temp = linked_plot.dropna(subset=["ontime_flag", "days_to_next_failure"]).copy()
|
| 980 |
+
if not temp.empty:
|
| 981 |
+
temp["PM status"] = temp["ontime_flag"].map({1: "On-time PM", 0: "Delayed PM"}).fillna("Unknown")
|
| 982 |
+
fig = px.box(
|
| 983 |
+
temp,
|
| 984 |
+
x="PM status",
|
| 985 |
+
y="days_to_next_failure",
|
| 986 |
+
points="outliers",
|
| 987 |
+
title="On-time vs delayed PM: Days to next failure",
|
| 988 |
+
)
|
| 989 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 990 |
+
|
| 991 |
+
with c4:
|
| 992 |
+
if "delay_days" in linked_plot.columns:
|
| 993 |
+
temp = linked_plot.dropna(subset=["delay_days", "days_to_next_failure"]).copy()
|
| 994 |
+
if not temp.empty:
|
| 995 |
+
fig = px.scatter(
|
| 996 |
+
temp.sample(min(len(temp), 5000), random_state=42),
|
| 997 |
+
x="delay_days",
|
| 998 |
+
y="days_to_next_failure",
|
| 999 |
+
trendline="ols",
|
| 1000 |
+
title="PM delay vs days to next failure",
|
| 1001 |
+
labels={"delay_days": "PM delay days", "days_to_next_failure": "Days to next failure"},
|
| 1002 |
+
)
|
| 1003 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1004 |
+
|
| 1005 |
+
st.subheader("PM effectiveness data")
|
| 1006 |
+
st.dataframe(linked_plot.head(1000), use_container_width=True)
|
| 1007 |
+
|
| 1008 |
+
|
| 1009 |
+
# -----------------------------
|
| 1010 |
+
# Failures & Cost tab
|
| 1011 |
+
# -----------------------------
|
| 1012 |
+
with tabs[4]:
|
| 1013 |
+
st.header("Failure Patterns, Cost, and Downtime")
|
| 1014 |
+
|
| 1015 |
+
if failure_df.empty:
|
| 1016 |
+
st.warning("No failure_events.csv data found.")
|
| 1017 |
+
else:
|
| 1018 |
+
c1, c2 = st.columns(2)
|
| 1019 |
+
|
| 1020 |
+
with c1:
|
| 1021 |
+
if "failure_category" in failure_df.columns:
|
| 1022 |
+
cat = failure_df["failure_category"].fillna("Unknown").value_counts().reset_index()
|
| 1023 |
+
cat.columns = ["failure_category", "count"]
|
| 1024 |
+
fig = px.bar(cat, x="failure_category", y="count", title="Failures by category")
|
| 1025 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1026 |
+
|
| 1027 |
+
with c2:
|
| 1028 |
+
if "severity" in failure_df.columns:
|
| 1029 |
+
sev = failure_df["severity"].fillna("Unknown").value_counts().reset_index()
|
| 1030 |
+
sev.columns = ["severity", "count"]
|
| 1031 |
+
fig = px.bar(sev, x="severity", y="count", title="Failures by severity")
|
| 1032 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1033 |
+
|
| 1034 |
+
c3, c4 = st.columns(2)
|
| 1035 |
+
|
| 1036 |
+
with c3:
|
| 1037 |
+
if {"region", "total_cost"}.issubset(failure_df.columns):
|
| 1038 |
+
temp = failure_df.copy()
|
| 1039 |
+
temp["total_cost"] = pd.to_numeric(temp["total_cost"], errors="coerce")
|
| 1040 |
+
reg = temp.groupby("region", as_index=False)["total_cost"].sum()
|
| 1041 |
+
fig = px.bar(reg, x="region", y="total_cost", title="Repair cost by region")
|
| 1042 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1043 |
+
|
| 1044 |
+
with c4:
|
| 1045 |
+
if {"model", "downtime_hours"}.issubset(failure_df.columns):
|
| 1046 |
+
temp = failure_df.copy()
|
| 1047 |
+
temp["downtime_hours"] = pd.to_numeric(temp["downtime_hours"], errors="coerce")
|
| 1048 |
+
mod = temp.groupby("model", as_index=False)["downtime_hours"].sum().sort_values("downtime_hours", ascending=False)
|
| 1049 |
+
fig = px.bar(mod, x="model", y="downtime_hours", title="Downtime hours by model")
|
| 1050 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1051 |
+
|
| 1052 |
+
if not business_df.empty:
|
| 1053 |
+
st.subheader("Business impact")
|
| 1054 |
+
b1, b2, b3 = st.columns(3)
|
| 1055 |
+
b1.metric("Truck-roll cost", money(pd.to_numeric(business_df.get("truck_roll_cost", pd.Series(dtype=float)), errors="coerce").sum()))
|
| 1056 |
+
b2.metric("Revenue loss", money(pd.to_numeric(business_df.get("estimated_revenue_loss", pd.Series(dtype=float)), errors="coerce").sum()))
|
| 1057 |
+
b3.metric("SLA breach events", num(pd.to_numeric(business_df.get("sla_breach_flag", pd.Series(dtype=float)), errors="coerce").sum(), 0))
|
| 1058 |
+
|
| 1059 |
+
if {"event_date", "estimated_revenue_loss"}.issubset(business_df.columns):
|
| 1060 |
+
temp = business_df.copy()
|
| 1061 |
+
temp["event_month"] = pd.to_datetime(temp["event_date"], errors="coerce").dt.to_period("M").astype(str)
|
| 1062 |
+
temp["estimated_revenue_loss"] = pd.to_numeric(temp["estimated_revenue_loss"], errors="coerce")
|
| 1063 |
+
month = temp.groupby("event_month", as_index=False)["estimated_revenue_loss"].sum()
|
| 1064 |
+
fig = px.line(month, x="event_month", y="estimated_revenue_loss", markers=True, title="Estimated revenue loss over time")
|
| 1065 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1066 |
+
|
| 1067 |
+
|
| 1068 |
+
# -----------------------------
|
| 1069 |
+
# Telemetry Risk tab
|
| 1070 |
+
# -----------------------------
|
| 1071 |
+
with tabs[5]:
|
| 1072 |
+
st.header("Telemetry and Failure Risk")
|
| 1073 |
+
|
| 1074 |
+
if telemetry_df.empty:
|
| 1075 |
+
st.warning("No telemetry_weekly.csv data found.")
|
| 1076 |
+
else:
|
| 1077 |
+
tele = telemetry_df.copy()
|
| 1078 |
+
for col in ["anomaly_score", "days_since_last_pm", "days_to_next_failure", "failure_within_30d"]:
|
| 1079 |
+
if col in tele.columns:
|
| 1080 |
+
tele[col] = pd.to_numeric(tele[col], errors="coerce")
|
| 1081 |
+
|
| 1082 |
+
high_risk = pd.DataFrame()
|
| 1083 |
+
if "anomaly_score" in tele.columns:
|
| 1084 |
+
latest = tele.sort_values("timestamp").groupby("asset_id", as_index=False).tail(1)
|
| 1085 |
+
high_risk = latest.sort_values("anomaly_score", ascending=False).head(25)
|
| 1086 |
+
|
| 1087 |
+
c1, c2, c3 = st.columns(3)
|
| 1088 |
+
c1.metric("Latest high-risk assets shown", f"{len(high_risk):,}")
|
| 1089 |
+
c2.metric("Avg anomaly score", num(tele["anomaly_score"].mean(), 1))
|
| 1090 |
+
if "failure_within_30d" in tele.columns:
|
| 1091 |
+
c3.metric("Rows labeled failure within 30d", f"{int(tele['failure_within_30d'].sum()):,}")
|
| 1092 |
+
|
| 1093 |
+
c1, c2 = st.columns(2)
|
| 1094 |
+
|
| 1095 |
+
with c1:
|
| 1096 |
+
if {"days_since_last_pm", "anomaly_score"}.issubset(tele.columns):
|
| 1097 |
+
sample = tele.dropna(subset=["days_since_last_pm", "anomaly_score"])
|
| 1098 |
+
sample = sample.sample(min(len(sample), sample_limit), random_state=42) if len(sample) > sample_limit else sample
|
| 1099 |
+
color_col = "failure_within_30d" if "failure_within_30d" in sample.columns else None
|
| 1100 |
+
fig = px.scatter(
|
| 1101 |
+
sample,
|
| 1102 |
+
x="days_since_last_pm",
|
| 1103 |
+
y="anomaly_score",
|
| 1104 |
+
color=color_col,
|
| 1105 |
+
hover_data=["asset_id"] if "asset_id" in sample.columns else None,
|
| 1106 |
+
title="Anomaly score vs days since last PM",
|
| 1107 |
+
)
|
| 1108 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1109 |
+
|
| 1110 |
+
with c2:
|
| 1111 |
+
if {"days_since_last_pm", "anomaly_score"}.issubset(tele.columns):
|
| 1112 |
+
temp = tele.dropna(subset=["days_since_last_pm", "anomaly_score"]).copy()
|
| 1113 |
+
temp["pm_age_bucket"] = pd.cut(temp["days_since_last_pm"], bins=[0, 30, 60, 90, 120, 180, 365, 10000])
|
| 1114 |
+
bucket = temp.groupby("pm_age_bucket", observed=True, as_index=False)["anomaly_score"].mean()
|
| 1115 |
+
bucket["pm_age_bucket"] = bucket["pm_age_bucket"].astype(str)
|
| 1116 |
+
fig = px.bar(bucket, x="pm_age_bucket", y="anomaly_score", title="Average anomaly score by PM age bucket")
|
| 1117 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1118 |
+
|
| 1119 |
+
st.subheader("Top risky assets by latest anomaly score")
|
| 1120 |
+
if not high_risk.empty:
|
| 1121 |
+
st.dataframe(high_risk, use_container_width=True)
|
| 1122 |
+
|
| 1123 |
+
|
| 1124 |
+
|
| 1125 |
+
# -----------------------------
|
| 1126 |
+
# Predictive ML & PM Strategy tab
|
| 1127 |
+
# -----------------------------
|
| 1128 |
+
with tabs[6]:
|
| 1129 |
+
st.header("Predictive ML and Prescriptive PM Strategy")
|
| 1130 |
+
st.markdown(
|
| 1131 |
+
"""
|
| 1132 |
+
This is the **machine-learning section** of the dashboard. It trains real supervised ML models on telemetry records,
|
| 1133 |
+
compares their performance, scores each asset, and converts the score into maintenance actions.
|
| 1134 |
+
|
| 1135 |
+
**Three-phase flow:**
|
| 1136 |
+
1. **Phase 1 - Reliability analytics:** PM completed → next failure → days to next failure.
|
| 1137 |
+
2. **Phase 2 - Predictive ML:** telemetry + PM recency → failure probability within 14 or 30 days.
|
| 1138 |
+
3. **Phase 3 - Prescriptive PM:** failure probability + business impact → recommended maintenance action.
|
| 1139 |
+
"""
|
| 1140 |
+
)
|
| 1141 |
+
|
| 1142 |
+
# Prefer full raw telemetry with model/region/criticality if available. Otherwise use telemetry_weekly.
|
| 1143 |
+
ml_source_df = raw_telemetry_df.copy() if not raw_telemetry_df.empty else telemetry_df.copy()
|
| 1144 |
+
if ml_source_df.empty:
|
| 1145 |
+
st.warning("No telemetry dataset found for ML training.")
|
| 1146 |
+
else:
|
| 1147 |
+
c1, c2, c3 = st.columns(3)
|
| 1148 |
+
target_col = c1.selectbox("ML prediction target", ["failure_within_30d", "failure_within_14d"], index=0)
|
| 1149 |
+
max_rows = c2.slider("Training sample size", min_value=20000, max_value=120000, value=90000, step=10000)
|
| 1150 |
+
c3.metric("ML source rows", f"{len(ml_source_df):,}")
|
| 1151 |
+
|
| 1152 |
+
st.subheader("ML inputs")
|
| 1153 |
+
st.markdown(
|
| 1154 |
+
"""
|
| 1155 |
+
The model uses telemetry and asset-context features including:
|
| 1156 |
+
`days_since_last_pm`, `runtime_hours_week`, `avg_load_pct`, `oil_temp_c`, `coolant_temp_c`,
|
| 1157 |
+
`battery_voltage`, `vibration_mm_s`, `fuel_rate_lph`, `alarm_count`, `anomaly_score`,
|
| 1158 |
+
`model`, `region`, `criticality`, and `environment_type`.
|
| 1159 |
+
"""
|
| 1160 |
+
)
|
| 1161 |
+
|
| 1162 |
+
ml_frame, numeric_cols, categorical_cols = prepare_ml_frame(ml_source_df, target_col=target_col, max_rows=max_rows)
|
| 1163 |
+
if ml_frame.empty:
|
| 1164 |
+
st.error(f"Cannot train ML model because `{target_col}` is not available in the telemetry dataset.")
|
| 1165 |
+
else:
|
| 1166 |
+
with st.spinner("Training Logistic Regression and Random Forest models..."):
|
| 1167 |
+
ml_results = train_failure_models(ml_frame, numeric_cols, categorical_cols, target_col=target_col)
|
| 1168 |
+
|
| 1169 |
+
perf_df = pd.DataFrame([
|
| 1170 |
+
{
|
| 1171 |
+
"Model": model_name,
|
| 1172 |
+
"Accuracy": result["accuracy"],
|
| 1173 |
+
"Precision": result["precision"],
|
| 1174 |
+
"Recall": result["recall"],
|
| 1175 |
+
"F1": result["f1"],
|
| 1176 |
+
"ROC AUC": result["roc_auc"],
|
| 1177 |
+
}
|
| 1178 |
+
for model_name, result in ml_results.items()
|
| 1179 |
+
]).sort_values("ROC AUC", ascending=False)
|
| 1180 |
+
|
| 1181 |
+
st.subheader("Phase 2 output: trained ML model comparison")
|
| 1182 |
+
st.dataframe(
|
| 1183 |
+
perf_df.style.format({"Accuracy": "{:.3f}", "Precision": "{:.3f}", "Recall": "{:.3f}", "F1": "{:.3f}", "ROC AUC": "{:.3f}"}),
|
| 1184 |
+
use_container_width=True,
|
| 1185 |
+
)
|
| 1186 |
+
best_model_name = perf_df.iloc[0]["Model"]
|
| 1187 |
+
best_model = ml_results[best_model_name]["pipeline"]
|
| 1188 |
+
st.success(f"Best model for the current data/filter selection: **{best_model_name}**")
|
| 1189 |
+
|
| 1190 |
+
left, right = st.columns(2)
|
| 1191 |
+
with left:
|
| 1192 |
+
st.subheader("Confusion matrix")
|
| 1193 |
+
cm = ml_results[best_model_name]["confusion_matrix"]
|
| 1194 |
+
cm_df = pd.DataFrame(cm, index=["Actual 0", "Actual 1"], columns=["Predicted 0", "Predicted 1"])
|
| 1195 |
+
fig = px.imshow(cm_df, text_auto=True, title=f"Confusion matrix - {best_model_name}")
|
| 1196 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1197 |
+
with right:
|
| 1198 |
+
st.subheader("Top predictive drivers")
|
| 1199 |
+
fi = get_ml_feature_importance(best_model, best_model_name, top_n=15)
|
| 1200 |
+
fig = px.bar(fi.sort_values("importance"), x="importance", y="feature", orientation="h", title="Feature importance")
|
| 1201 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1202 |
+
|
| 1203 |
+
st.subheader("Phase 2 output: asset-level ML failure risk")
|
| 1204 |
+
latest_risk = score_latest_asset_risk(ml_source_df, best_model)
|
| 1205 |
+
if latest_risk.empty:
|
| 1206 |
+
st.info("No latest asset risk records available.")
|
| 1207 |
+
else:
|
| 1208 |
+
st.dataframe(
|
| 1209 |
+
latest_risk.head(30).style.format({"ml_predicted_failure_risk": "{:.2%}"}),
|
| 1210 |
+
use_container_width=True,
|
| 1211 |
+
)
|
| 1212 |
+
|
| 1213 |
+
if "ml_risk_band" in latest_risk.columns:
|
| 1214 |
+
band = latest_risk["ml_risk_band"].astype(str).value_counts().reset_index()
|
| 1215 |
+
band.columns = ["risk_band", "asset_count"]
|
| 1216 |
+
fig = px.bar(band, x="risk_band", y="asset_count", title="Asset count by ML risk band")
|
| 1217 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1218 |
+
|
| 1219 |
+
st.subheader("Phase 3 output: prescriptive PM action plan")
|
| 1220 |
+
action_plan = build_prescriptive_pm_plan(latest_risk, linked_df, business_df)
|
| 1221 |
+
if action_plan.empty:
|
| 1222 |
+
st.info("No action plan could be generated.")
|
| 1223 |
+
else:
|
| 1224 |
+
p1, p2, p3 = st.columns(3)
|
| 1225 |
+
p1.metric("Critical assets", f"{int((action_plan['ml_predicted_failure_risk'] >= 0.8).sum()):,}")
|
| 1226 |
+
p2.metric("High-risk assets", f"{int(((action_plan['ml_predicted_failure_risk'] >= 0.6) & (action_plan['ml_predicted_failure_risk'] < 0.8)).sum()):,}")
|
| 1227 |
+
p3.metric("Top-20 cost exposure", money(action_plan.head(20).get("estimated_failure_cost_exposure", pd.Series(dtype=float)).sum()))
|
| 1228 |
+
|
| 1229 |
+
st.dataframe(
|
| 1230 |
+
action_plan.head(30).style.format({
|
| 1231 |
+
"ml_predicted_failure_risk": "{:.2%}",
|
| 1232 |
+
"estimated_failure_cost_exposure": "${:,.0f}",
|
| 1233 |
+
"historical_median_days_to_failure": "{:.0f}",
|
| 1234 |
+
}),
|
| 1235 |
+
use_container_width=True,
|
| 1236 |
+
)
|
| 1237 |
+
|
| 1238 |
+
if "prescriptive_pm_action" in action_plan.columns:
|
| 1239 |
+
actions = action_plan["prescriptive_pm_action"].value_counts().reset_index()
|
| 1240 |
+
actions.columns = ["action", "asset_count"]
|
| 1241 |
+
fig = px.bar(actions, x="asset_count", y="action", orientation="h", title="Recommended PM actions from ML risk")
|
| 1242 |
+
st.plotly_chart(fig, use_container_width=True)
|
| 1243 |
+
|
| 1244 |
+
st.subheader("What this ML proves")
|
| 1245 |
+
st.markdown(
|
| 1246 |
+
"""
|
| 1247 |
+
- The dashboard is no longer only rule-based. It now **trains supervised ML models** on telemetry labels.
|
| 1248 |
+
- Logistic Regression provides an explainable baseline.
|
| 1249 |
+
- Random Forest captures nonlinear failure patterns from vibration, battery voltage, alarms, anomaly score, and PM recency.
|
| 1250 |
+
- The output is not just a chart; it is an asset-level probability of near-term failure and a PM recommendation.
|
| 1251 |
+
"""
|
| 1252 |
+
)
|
| 1253 |
+
|
| 1254 |
+
# -----------------------------
|
| 1255 |
+
# Saved Outputs tab
|
| 1256 |
+
# -----------------------------
|
| 1257 |
+
with tabs[7]:
|
| 1258 |
+
st.header("Saved Outputs Included in Package")
|
| 1259 |
+
st.markdown("These are pre-generated figures and tables from the notebook workflow.")
|
| 1260 |
+
|
| 1261 |
+
fig_files = sorted([p for p in OUTPUT_FIG_DIR.glob("*.png")]) if OUTPUT_FIG_DIR.exists() else []
|
| 1262 |
+
if fig_files:
|
| 1263 |
+
for p in fig_files:
|
| 1264 |
+
st.subheader(p.stem.replace("_", " ").title())
|
| 1265 |
+
st.image(str(p), use_container_width=True)
|
| 1266 |
+
else:
|
| 1267 |
+
st.info("No saved PNG figures found in outputs/figures.")
|
| 1268 |
+
|
| 1269 |
+
st.divider()
|
| 1270 |
+
table_files = sorted([p for p in OUTPUT_TABLE_DIR.glob("*.csv")]) if OUTPUT_TABLE_DIR.exists() else []
|
| 1271 |
+
if table_files:
|
| 1272 |
+
st.subheader("Saved output tables")
|
| 1273 |
+
for p in table_files:
|
| 1274 |
+
with st.expander(p.name):
|
| 1275 |
+
try:
|
| 1276 |
+
df = pd.read_csv(p)
|
| 1277 |
+
st.dataframe(df.head(500), use_container_width=True)
|
| 1278 |
+
st.download_button(
|
| 1279 |
+
f"Download {p.name}",
|
| 1280 |
+
data=df.to_csv(index=False),
|
| 1281 |
+
file_name=p.name,
|
| 1282 |
+
mime="text/csv",
|
| 1283 |
+
)
|
| 1284 |
+
except Exception as e:
|
| 1285 |
+
st.error(f"Could not read {p.name}: {e}")
|
| 1286 |
+
else:
|
| 1287 |
+
st.info("No saved CSV tables found in outputs/tables.")
|
| 1288 |
+
|
| 1289 |
+
|
| 1290 |
+
# -----------------------------
|
| 1291 |
+
# Data Explorer & Export tab
|
| 1292 |
+
# -----------------------------
|
| 1293 |
+
with tabs[8]:
|
| 1294 |
+
st.header("Data Explorer and Export")
|
| 1295 |
+
|
| 1296 |
+
table_options = {
|
| 1297 |
+
"asset_master": asset_df,
|
| 1298 |
+
"pm_events": pm_df,
|
| 1299 |
+
"failure_events": failure_df,
|
| 1300 |
+
"business_impact": business_df,
|
| 1301 |
+
"pm_failure_linked": linked_df,
|
| 1302 |
+
"telemetry_weekly": telemetry_df,
|
| 1303 |
+
"raw_telemetry_before_algorithm": raw_telemetry_df,
|
| 1304 |
+
"algorithm_output_after_algorithm": algorithm_output_df,
|
| 1305 |
+
"latest_asset_risk_summary": algorithm_asset_summary_df,
|
| 1306 |
+
}
|
| 1307 |
+
|
| 1308 |
+
selected = st.selectbox("Choose table", list(table_options.keys()))
|
| 1309 |
+
df = table_options[selected]
|
| 1310 |
+
|
| 1311 |
+
if df.empty:
|
| 1312 |
+
st.warning(f"{selected} is empty.")
|
| 1313 |
+
else:
|
| 1314 |
+
st.write(f"Rows: **{len(df):,}** | Columns: **{len(df.columns):,}**")
|
| 1315 |
+
st.dataframe(df.head(5000), use_container_width=True)
|
| 1316 |
+
st.download_button(
|
| 1317 |
+
f"Download filtered {selected}.csv",
|
| 1318 |
+
data=df.to_csv(index=False),
|
| 1319 |
+
file_name=f"{selected}_filtered.csv",
|
| 1320 |
+
mime="text/csv",
|
| 1321 |
+
)
|
| 1322 |
+
|
| 1323 |
+
st.divider()
|
| 1324 |
+
st.subheader("Download all currently filtered dashboard tables")
|
| 1325 |
+
zip_bytes = make_download_zip(table_options)
|
| 1326 |
+
st.download_button(
|
| 1327 |
+
"Download filtered dashboard data ZIP",
|
| 1328 |
+
data=zip_bytes,
|
| 1329 |
+
file_name="filtered_generator_pm_dashboard_data.zip",
|
| 1330 |
+
mime="application/zip",
|
| 1331 |
+
)
|
| 1332 |
+
|
| 1333 |
+
st.subheader("Data quality checklist")
|
| 1334 |
+
checks = []
|
| 1335 |
+
checks.append(("PM table has asset_id", "asset_id" in pm_df.columns if not pm_df.empty else False))
|
| 1336 |
+
checks.append(("PM table has pm_date", "pm_date" in pm_df.columns if not pm_df.empty else False))
|
| 1337 |
+
checks.append(("Failure table has asset_id", "asset_id" in failure_df.columns if not failure_df.empty else False))
|
| 1338 |
+
checks.append(("Failure table has failure_date", "failure_date" in failure_df.columns if not failure_df.empty else False))
|
| 1339 |
+
checks.append(("Linked table available", not linked_df.empty))
|
| 1340 |
+
checks.append(("Telemetry table available", not telemetry_df.empty))
|
| 1341 |
+
checks.append(("Business impact table available", not business_df.empty))
|
| 1342 |
+
|
| 1343 |
+
check_df = pd.DataFrame(checks, columns=["Check", "Passed"])
|
| 1344 |
+
st.dataframe(check_df, use_container_width=True)
|
requirements.txt
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
streamlit
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
plotly
|
| 5 |
+
scikit-learn
|
| 6 |
+
matplotlib
|
| 7 |
+
altair
|
| 8 |
+
pyyaml
|