AI in Manufacturing
Predictive Maintenance
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from typing import Dict, List
class PredictiveMaintenanceModel:
def __init__(self, sequence_length=50, n_features=10):
self.model = nn.Sequential(
nn.LSTM(n_features, 64, num_layers=2, batch_first=True),
nn.Linear(64, 32),
nn.ReLU(),
nn.Linear(32, 1),
nn.Sigmoid()
)
def prepare_sensor_data(self, readings: pd.DataFrame) -> torch.Tensor:
features = readings[["vibration", "temperature", "pressure", "rpm", "current"]].values
normalized = (features - features.mean(axis=0)) / (features.std(axis=0) + 1e-8)
return torch.FloatTensor(normalized)
def predict_rul(self, sensor_data: torch.Tensor) -> Dict:
self.model.eval()
with torch.no_grad():
output = self.model(sensor_data.unsqueeze(0))
rul_prediction = output.item() * 1000
if rul_prediction < 100:
urgency = "critical"
action = "Immediate maintenance required"
elif rul_prediction < 300:
urgency = "warning"
action = "Schedule maintenance within 1 week"
else:
urgency = "normal"
action = "Continue monitoring"
return {
"remaining_useful_life_hours": rul_prediction,
"urgency": urgency,
"recommended_action": action,
"confidence": 0.85
}
predictor = PredictiveMaintenanceModel()
rul = predictor.predict_rul(sensor_readings)
Defect Detection
import torch
import torch.nn as nn
from torchvision import models, transforms
class DefectDetector:
def __init__(self, n_defect_types=5):
self.model = models.resnet50(pretrained=True)
self.model.fc = nn.Sequential(
nn.Linear(2048, 512),
nn.ReLU(),
nn.Dropout(0.3),
nn.Linear(512, n_defect_types)
)
self.transform = transforms.Compose([
transforms.Resize((224, 224)),
transforms.ToTensor(),
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])
])
self.defect_classes = ["scratch", "dent", "crack", "stain", "good"]
def inspect_product(self, image) -> Dict:
input_tensor = self.transform(image).unsqueeze(0)
self.model.eval()
with torch.no_grad():
output = self.model(input_tensor)
probabilities = torch.softmax(output, dim=1)
prediction = torch.argmax(probabilities, dim=1).item()
confidence = probabilities.max().item()
defect_type = self.defect_classes[prediction]
return {
"has_defect": defect_type != "good",
"defect_type": defect_type,
"confidence": confidence,
"action": "reject" if defect_type != "good" else "approve"
}
detector = DefectDetector()
result = detector.inspect_product(product_image)
Digital Twin Simulation
class DigitalTwin:
def __init__(self, machine_id: str, parameters: Dict):
self.machine_id = machine_id
self.parameters = parameters
self.state = {}
def simulate_operation(self, input_conditions: Dict, duration: int) -> pd.DataFrame:
results = []
state = self.parameters.copy()
for t in range(duration):
state["temperature"] = state.get("base_temp", 25) + \
input_conditions.get("load", 0.5) * 20 + \
np.random.normal(0, 2)
state["vibration"] = input_conditions.get("load", 0.5) * 5 + \
np.random.normal(0, 0.5)
state["wear"] = state.get("wear", 0) + \
input_conditions.get("load", 0.5) * 0.01
results.append({
"time": t,
"temperature": state["temperature"],
"vibration": state["vibration"],
"wear": state["wear"]
})
return pd.DataFrame(results)
def predict_failure(self, current_state: Dict) -> Dict:
wear = current_state.get("wear", 0)
temp = current_state.get("temperature", 25)
failure_prob = min(1.0, wear * 0.5 + (temp - 80) * 0.01)
return {
"failure_probability": failure_prob,
"estimated_time_to_failure": int((1 - wear) * 1000),
"current_wear": wear
}
twin = DigitalTwin("CNC_001", {"base_temp": 25, "max_temp": 100})
simulation = twin.simulate_operation({"load": 0.7}, duration=100)
failure_pred = twin.predict_failure({"wear": 0.3, "temperature": 75})
Supply Chain Optimization
class SupplyChainOptimizer:
def __init__(self):
self.demand_model = None
self.inventory_optimizer = None
def forecast_demand(self, historical_data: pd.DataFrame) -> np.ndarray:
from sklearn.ensemble import RandomForestRegressor
features = historical_data[["month", "day_of_week", "promotion", "price"]].values
target = historical_data["sales"].values
model = RandomForestRegressor(n_estimators=100)
model.fit(features, target)
future_features = self._prepare_future_features(30)
forecast = model.predict(future_features)
return forecast
def optimize_inventory(self, demand_forecast: np.ndarray, lead_time: int = 7) -> Dict:
avg_demand = demand_forecast.mean()
demand_std = demand_forecast.std()
safety_stock = 1.65 * demand_std * np.sqrt(lead_time)
reorder_point = avg_demand * lead_time + safety_stock
return {
"reorder_point": int(reorder_point),
"safety_stock": int(safety_stock),
"economic_order_quantity": int(avg_demand * lead_time * 2),
"avg_daily_demand": float(avg_demand)
}
optimizer = SupplyChainOptimizer()
forecast = optimizer.forecast_demand(historical_sales)
inventory = optimizer.optimize_inventory(forecast, lead_time=7)
Best Practices
- Start with high-ROI use cases (predictive maintenance)
- Integrate IoT sensors for real-time data
- Build digital twins for simulation
- Implement edge computing for real-time inspection
- Use transfer learning for limited defect data
- Monitor model performance in production