import numpy as np import pandas as pd import torch import torch.nn as nn import xgboost as xgb from sklearn.model_selection import train_test_split import matplotlib.pyplot as plt import cv2 from torchvision import transforms from PIL import Image # ---------- LSTM Autoencoder ---------- class LSTMAutoencoder(nn.Module): def __init__(self, input_dim, hidden_dim): super(LSTMAutoencoder, self).__init__() self.encoder = nn.LSTM(input_dim, hidden_dim, batch_first=True) self.decoder = nn.LSTM(hidden_dim, input_dim, batch_first=True) def forward(self, x): _, (hidden, _) = self.encoder(x) output, _ = self.decoder(hidden.repeat(x.size(1), 1, 1).permute(1, 0, 2)) return output def detect_anomaly(csv_path): df = pd.read_csv(csv_path) data = torch.tensor(df.values, dtype=torch.float32).unsqueeze(0) model = LSTMAutoencoder(input_dim=data.shape[2], hidden_dim=16) output = model(data) loss = torch.mean((output - data) ** 2, dim=(0, 2)).detach().numpy() threshold = np.mean(loss) + 3 * np.std(loss) status = "Anomaly Detected" if np.any(loss > threshold) else "Healthy" plt.figure() plt.plot(loss, label="Reconstruction Error") plt.axhline(threshold, color='r', linestyle='--', label='Threshold') plt.legend() plt.title("Anomaly Detection") return status, plt.gcf() # ---------- XGBoost RUL ---------- def train_rul_model(): X = np.random.rand(500, 5) y = 100 + 50 * np.random.rand(500) X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2) model = xgb.XGBRegressor() model.fit(X_train, y_train) return model def predict_rul(csv_path, model): df = pd.read_csv(csv_path) pred = model.predict(df.values) return f"Predicted RUL: {pred[0]:.2f} hrs" # ---------- CNN Defect Detection ---------- class SimpleCNN(nn.Module): def __init__(self): super(SimpleCNN, self).__init__() self.conv = nn.Sequential( nn.Conv2d(3, 8, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(8, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2) ) self.fc = nn.Linear(16 * 32 * 32, 2) def forward(self, x): x = self.conv(x) return self.fc(x.view(x.size(0), -1)) def classify_defect(image, model): transform = transforms.Compose([ transforms.Resize((128, 128)), transforms.ToTensor() ]) img_tensor = transform(image).unsqueeze(0) out = model(img_tensor) label = torch.argmax(out, dim=1).item() result = "Defective" if label else "Acceptable" heatmap = np.array(image) if label: heatmap = cv2.applyColorMap(cv2.cvtColor(np.array(image), cv2.COLOR_RGB2GRAY), cv2.COLORMAP_JET) return result, Image.fromarray(heatmap)