Download utils.py from Gangadhar123/CNC_Predictive_Maintenance: direct link, hf CLI and curl.
- Browser
- Download file 6.26 kB
-
https://huggingface.co/spaces/Gangadhar123/CNC_Predictive_Maintenance/resolve/main/utils.py
- Command line
-
hf download hf://spaces/Gangadhar123/CNC_Predictive_Maintenance/utils.py
-
curl -L -o utils.py https://huggingface.co/spaces/Gangadhar123/CNC_Predictive_Maintenance/resolve/main/utils.py
6.26 kB
| # utils.py – Enhanced for CNC AI App with Executive Summary Insights | |
| import pandas as pd | |
| import numpy as np | |
| import torch | |
| import torch.nn as nn | |
| import joblib | |
| import seaborn as sns | |
| import matplotlib.pyplot as plt | |
| import shap | |
| from xgboost import XGBRegressor, XGBClassifier | |
| from sklearn.preprocessing import MinMaxScaler | |
| # === GRU Autoencoder Definition === | |
| class GRUAutoencoder(nn.Module): | |
| def __init__(self, input_dim=9, hidden_dim=32): | |
| super(GRUAutoencoder, self).__init__() | |
| self.encoder = nn.GRU(input_dim, hidden_dim, batch_first=True) | |
| self.decoder = nn.GRU(hidden_dim, input_dim, batch_first=True) | |
| def forward(self, x): | |
| _, h = self.encoder(x) | |
| out, _ = self.decoder(h.repeat(x.size(1), 1, 1).transpose(0, 1)) | |
| return out | |
| # === Load Models === | |
| gru_checkpoint = torch.load("gru_autoencoder.pt", map_location=torch.device("cpu")) | |
| gru_model = GRUAutoencoder( | |
| input_dim=gru_checkpoint.get("input_dim", 9), | |
| hidden_dim=gru_checkpoint.get("hidden_dim", 32) | |
| ) | |
| gru_model.load_state_dict(gru_checkpoint["model_state"]) | |
| gru_model.eval() | |
| gru_scaler = joblib.load("gru_scaler.pkl") | |
| rul_model = joblib.load("xgb_rul_model.pkl") | |
| quality_model = joblib.load("xgb_quality_model.pkl") | |
| quality_scaler = joblib.load("xgb_quality_scaler.pkl") | |
| FEATURE_COLUMNS = [ | |
| 'temperature', 'pressure', 'vibration', 'motor_current_amp', 'acoustic_db', | |
| 'spindle_speed', 'tool_wear', 'groove_depth_mm', 'surface_finish_microns' | |
| ] | |
| # === Anomaly Detection === | |
| def detect_anomalies(df): | |
| X = df[FEATURE_COLUMNS].values | |
| X_scaled = gru_scaler.transform(X) | |
| X_tensor = torch.tensor(X_scaled, dtype=torch.float32).unsqueeze(1) | |
| with torch.no_grad(): | |
| recon = gru_model(X_tensor) | |
| recon_error = ((X_tensor - recon) ** 2).mean(dim=(1, 2)).numpy() | |
| threshold = np.percentile(recon_error, 95) | |
| df["anomaly_score"] = recon_error | |
| df["is_anomaly"] = recon_error > threshold | |
| return df, plot_anomalies(df, threshold) | |
| def plot_anomalies(df, threshold): | |
| df["timestamp"] = pd.to_datetime(df["timestamp"]) | |
| df["hour"] = df["timestamp"].dt.floor("H") | |
| # Group by hour + machine | |
| hourly_df = ( | |
| df.groupby(["hour", "machine_name"])["anomaly_score"] | |
| .mean() | |
| .reset_index() | |
| .rename(columns={"hour": "timestamp"}) | |
| ) | |
| fig, ax = plt.subplots(figsize=(10, 4)) | |
| sns.lineplot(data=hourly_df, x="timestamp", y="anomaly_score", hue="machine_name", ax=ax) | |
| ax.axhline(threshold, color="red", linestyle="--", label="95th Percentile Threshold") | |
| ax.set_title("Hourly Avg Anomaly Score per Machine") | |
| ax.set_ylabel("Anomaly Score (Mean / Hour)") | |
| ax.legend() | |
| return fig | |
| # === RUL Prediction === | |
| def predict_rul(df): | |
| rul_input = df.groupby("machine_name")[FEATURE_COLUMNS].mean().reset_index() | |
| if rul_input.empty: | |
| return pd.DataFrame(), None | |
| rul_preds = rul_model.predict(rul_input[FEATURE_COLUMNS]) | |
| rul_preds = np.clip(rul_preds, 1, None) | |
| rul_input["predicted_rul"] = rul_preds | |
| return rul_input, plot_rul_stacked_bar(rul_input) | |
| def plot_rul_stacked_bar(rul_df): | |
| fig, ax = plt.subplots(figsize=(10, 5)) | |
| sorted_df = rul_df.sort_values("predicted_rul") | |
| ax.bar(sorted_df["machine_name"], sorted_df["predicted_rul"], color="skyblue") | |
| ax.set_ylabel("Predicted RUL (days)") | |
| ax.set_xlabel("Machine") | |
| ax.set_title("Remaining Useful Life") | |
| plt.xticks(rotation=45) | |
| return fig | |
| # === Quality Prediction === | |
| def predict_quality(df): | |
| X = quality_scaler.transform(df[FEATURE_COLUMNS]) | |
| df["quality"] = quality_model.predict(X) | |
| return df, plot_quality_chart(df) | |
| def plot_quality_chart(df): | |
| fig, ax = plt.subplots() | |
| labels = df["quality"].value_counts().index | |
| sizes = df["quality"].value_counts().values | |
| ax.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=90) | |
| ax.axis('equal') | |
| ax.set_title("Quality Distribution") | |
| return fig | |
| # === Root Cause Analysis === | |
| def root_cause_analysis(df): | |
| X_scaled = quality_scaler.transform(df[FEATURE_COLUMNS]) | |
| explainer = shap.Explainer(quality_model) | |
| shap_values = explainer(X_scaled[:100]) | |
| shap_summary = np.abs(shap_values.values).mean(axis=0) | |
| importance_df = pd.DataFrame({ | |
| "Feature": FEATURE_COLUMNS, | |
| "Mean Contribution": shap_summary | |
| }).sort_values(by="Mean Contribution", ascending=False) | |
| top3 = importance_df.head(3) | |
| summary = "Top contributing features to quality drop:\n" | |
| for _, row in top3.iterrows(): | |
| summary += f"• {row['Feature']}: {row['Mean Contribution']:.3f}\n" | |
| return importance_df, summary | |
| # === Executive Summary Helpers === | |
| def summarize_anomalies(df): | |
| if "is_anomaly" not in df.columns: | |
| return "No anomaly details available." | |
| reasons = [] | |
| for col in FEATURE_COLUMNS: | |
| high = df[df["is_anomaly"]][col] > df[col].quantile(0.9) | |
| count = high.sum() | |
| if count > 0: | |
| reasons.append(f"• {count} × High {col.replace('_', ' ').title()}") | |
| return ( | |
| f"<b>Anomaly Breakdown (rows flagged: {df['is_anomaly'].sum()}):</b><br>" | |
| + "<br>".join(reasons) | |
| ) if reasons else "No distinct causes found." | |
| def get_rul_explanations(rul_df, base_df): | |
| reasons = [] | |
| for _, row in rul_df[rul_df['predicted_rul'] <= 5].iterrows(): | |
| machine = row['machine_name'] | |
| recent = base_df[base_df['machine_name'] == machine] | |
| if recent.empty: | |
| continue | |
| top_feature = recent[FEATURE_COLUMNS].mean().sort_values(ascending=False).index[0] | |
| reasons.append( | |
| f"<li><span title='High {top_feature}'>🔴 {machine} – {row['predicted_rul']:.1f} days</span></li>" | |
| ) | |
| return "<b>RUL Warnings:</b><ul>" + "".join(reasons) + "</ul>" if reasons else "All machines healthy." | |
| def estimate_loss_breakdown(anomalies, bad_quality_count, cost_per_anomaly=300, cost_per_bad=150): | |
| anomaly_loss = anomalies * cost_per_anomaly | |
| quality_loss = bad_quality_count * cost_per_bad | |
| total = anomaly_loss + quality_loss | |
| return ( | |
| f"💸 <b>Loss Breakdown:</b><br>" | |
| f"• ${quality_loss} from low quality<br>" | |
| f"• ${anomaly_loss} from anomalies<br>" | |
| f"<b>Total:</b> ${total}" | |
| ) | |