---
name: pangzhenying2025/automotive-manufacturing
source: https://app.decimal.ai/s/pangzhenying2025-automotive-manufacturing@1/SKILL.md
source_sha256: ebc4bfcaee49
---

# Automotive Manufacturing

40 skill files covering manufacturing domain for automotive software engineering.

## Applicable Standards

- AIAG APQP (Advanced Product Quality Planning)
- AIAG CQI-19 - Sub-Tier Supplier Management
- AIAG Core Tools (FMEA, Control Plan, MSA)
- AIAG MMOG/LE Materials Management Logistics Evaluation
- AIAG MSA (Measurement Systems Analysis)
- AIAG MSA - Measurement Systems Analysis for AI Systems
- AIAG MSA - Measurement Systems Analysis for Vision Systems
- AIAG PPAP (Production Part Approval Process)
- AIAG Product Traceability Guidelines
- AIAG SPC Manual
- AIAG SPC Reference Manual
- ANSI/ISA-101 HMI Design Standards
- ANSI/ISA-95
- ANSI/ISA-95 Enterprise-Control Integration
- ANSI/ISA-95 Manufacturing Integration
- ANSI/ITSDF B56.5 AGV Standard
- ANSI/RIA R15.06
- ASQ Six Sigma Body of Knowledge
- ASTM B85 Aluminum Die Casting Alloys
- ASTM F3301 - Additive Manufacturing of Metals
- AWS D8.1 Automotive Weld Quality
- AutomationML (IEC 62714) for engineering data exchange
- BAT Reference Documents (BREF) for Waste Treatment
- DIN 31051 Maintenance Terminology
- DIN EN 1525 Safety of Driverless Trucks
- DVS 2902 Laser Welding Quality
- EMVA 1288 - Camera Characterization Standard
- EPA VOC Regulations (350 g/L limit)
- EU Battery Regulation 2023/1542
- EU CBAM (Carbon Border Adjustment Mechanism)
- EU CBAM Regulation - Carbon Border Adjustment Mechanism
- EU End-of-Life Vehicles Directive 2000/53/EC
- EU Industrial Emissions Directive 2010/75/EU
- EU Machinery Regulation 2023/1230
- EU Taxonomy for Sustainable Activities
- EU Waste Framework Directive 2008/98/EC
- EUCAR Hazard Level Classification
- GB/T 31485 (China EV Battery Safety)
- GB/T 38031 Chinese EV Battery Safety Standard
- GHG Protocol Corporate Standard
- GR&R (Gage Repeatability & Reproducibility)
- IATF 16949
- IATF 16949 (Environmental Compliance Clauses)
- IATF 16949 (Environmental Compliance)
- IATF 16949 (Material Handling and Traceability)
- IATF 16949 (Preventive Maintenance Requirements)
- IATF 16949 (Process Control Requirements)
- IATF 16949 (Process Monitoring and Control)
- IATF 16949 (Process Planning Clauses)
- IATF 16949 (Process Planning and Validation)
- IATF 16949 (Production Scheduling and Delivery)
- IATF 16949 (Supplier Development Requirements)
- IATF 16949 - Error-Proofing and Inspection Requirements
- IATF 16949 - Inspection and Test Requirements
- IATF 16949 - Supplier Quality Management
- IATF 16949 - Tooling Management Requirements
- IATF 16949 Quality Management System
- IEC 61131-3 PLC Programming (virtual PLC integration)
- IEC 61131-3 PLC Programming Languages
- IEC 61131-3 Programmable Controllers
- IEC 62061 Functional Safety
- IEC 62264 Enterprise-Control System Integration
- IEC 62264 Enterprise-Control System Integration (ISA-95)
- IEC 62443 Industrial Cybersecurity
- IEC 62443 Industrial Cybersecurity for Robot Networks
- IEC 62660 Secondary Lithium Cells (Performance and Safety)
- IEEE 1918.1 Tactile Internet
- ILO Labor Standards
- IMDS (International Material Data System)
- IPC-A-610 - Acceptability of Electronic Assemblies
- IPC-A-610 Electronics Assembly
- ISA-18.2 Alarm Management
- ISO 10218-1/2 Industrial Robot Safety
- ISO 10218-1/2 Robot Safety
- ISO 10218-1/2 Robot Safety Requirements
- ISO 10816 Mechanical Vibration Evaluation
- ISO 12100 Risk Assessment for Machinery
- ISO 12405 Battery Testing
- ISO 12405 Electrically Propelled Vehicles Test Specification
- ISO 12944 Corrosion Protection
- ISO 13374 Condition Monitoring
- ISO 13381 Condition Monitoring and Diagnostics -- Prognostics
- ISO 13482 Personal Care Robot Safety
- ISO 13849-1 - Safety of Machinery for Vision in Safety Applications
- ISO 13849-1 Safety Control Systems
- ISO 13849-1 Safety of Machinery (PL rating)
- ISO 14001 (Environmental Requirements for New Sites)
- ISO 14001 - Environmental Management Systems
- ISO 14001 Environmental Management Systems
- ISO 14040/14044 - Life Cycle Assessment
- ISO 14064 - Greenhouse Gas Accounting
- ISO 14064 Greenhouse Gas Accounting and Verification
- ISO 14373 Spot Welding
- ISO 14404 - Carbon Intensity of Steelmaking
- ISO 15926 Industrial Data Integration
- ISO 16220 Magnesium and Aluminum Alloys
- ISO 17359 Condition Monitoring Planning
- ISO 17359 Condition Monitoring and Diagnostics -- General Guidelines
- ISO 18436 Vibration Analysis
- ISO 22301 - Business Continuity Management
- ISO 22514 Statistical Process Control
- ISO 23247 Digital Twin Framework for Manufacturing
- ISO 2768 - General Tolerances for Linear and Angular Dimensions
- ISO 28000 - Supply Chain Security Management
- ISO 28000 Supply Chain Security
- ISO 2859 - Sampling Procedures Baseline for AI Comparison
- ISO 3691-4 AGV Safety Requirements
- ISO 3691-4 Driverless Industrial Trucks Safety
- ISO 50001 Energy Management Systems
- ISO 5393 Rotary and Impact Tools
- ISO 55000 Asset Management
- ISO 6469 EV Safety (Parts 1-4)
- ISO 8000 Data Quality
- ISO 9001
- ISO 9001 Quality Management
- ISO/ASTM 52900 - Additive Manufacturing Terminology
- ISO/ASTM 52900 Additive Manufacturing Standards
- ISO/TS 15066 Collaborative Robot Safety
- ISO/TS 15066 Collaborative Robots
- Lean Enterprise Institute Standards
- Lean Manufacturing Principles
- MESA MES Functional Model
- MSA (Measurement Systems Analysis)
- NVIDIA Jetson Platform Standards
- ODETTE Standards for Automotive Logistics
- OPC UA (IEC 62541) Information Models
- OPC UA (IEC 62541) for industrial data connectivity
- PPAP (Production Part Approval Process)
- RAMI 4.0 Reference Architecture Model
- Regional content requirements (EU Battery Regulation)
- ResponsibleSteel Certification Standard
- SAE AMS AM Standards
- SAE J2334 Paint Appearance Standards
- SAE J2464 EV Battery Abuse Testing
- SAE J2570 Tightening Strategy
- SEMI E10 Safety Guidelines
- Science Based Targets initiative (SBTi)
- TPM (Total Productive Maintenance)
- Toyota Production System (TPS)
- Toyota Production System (TPS) Principles
- UL 2580 Battery Safety
- UN 38.3 Transport of Lithium Batteries
- UN ECE R100 Battery Electric Vehicle Safety
- UN ECE R100 Electric Vehicle Safety
- USCAR Battery Testing Specifications
- USMCA Rules of Origin (automotive chapter)
- VDA 231-106 - Material Recyclability Calculation
- VDA 239-100 - Steel Flat Products for Cold Forming
- VDA 260 - Component Marking for Tooling
- VDA 4905 Delivery Schedule (DELFOR)
- VDA 4913 Delivery Notification (DESADV)
- VDA 5 - Measurement System Capability
- VDA 5050 AGV Communication Interface
- VDA 5050 AGV/AMR Communication Interface
- VDA 6.3 - Process Audit for Supplier Assessment
- VDA 6.3 Process Audit
- VDA 6.5 - Product Audit
- VDA Volume 2 (Quality Assurance)
- VDA Volume 6 Part 3
- VDI 2206 Design Methodology for Mechatronic Systems
- VDI 2862 Assembly Systems
- VDI 3405 3D Printing Quality
- VDI 3423 Availability of Machines and Production Lines
- VDI/VDE 2193 I4.0 Language for Communication
- WTO Rules of Origin
- Zero Waste to Landfill Certification (UL ECVP 2799)

## Use Cases

- Rapid prototyping for design validation
- Production tooling (jigs, fixtures, gauges)
- Metal 3D printing for complex geometries
- Conformal cooling channels in injection molds
- Spare parts on-demand manufacturing
- Material transport between production stations
- Just-in-sequence (JIS) part delivery to assembly line
- Warehouse-to-line automated material handling
- Empty container return and tote management
- Battery pack and powertrain module transport
- Deploy surface defect detection on painted body panels using deep learning
- Implement weld quality assessment from resistance welding process signatures
- Build automated optical inspection for PCB solder joints on automotive ECUs
- Create anomaly detection models for rare defects without labeled training data
- Integrate AI inspection results with MES for automated disposition decisions
- Line balancing to minimize idle time and labor cost
- Takt time synchronization with demand
- Bottleneck identification and elimination
- Workstation redesign for ergonomics and efficiency
- Model mix optimization for multi-variant production

## Topics Covered

### 3D Printing

- additive-manufacturing

### Advanced Casting

- megacasting-giga-press

### Automation Control

- plc-programming

### Body Shop

- body-shop-welding

### Carbon Neutral Assembly

- carbon-neutral-assembly

### Collaborative Robotics

- cobot-integration

### Continuous Improvement

- lean-manufacturing

### Data Management

- digital-thread-traceability

### Digital Twin

- digital-factory-twin

### Edge Computing

- edge-ai-manufacturing

### Energy Recovery

- waste-to-energy

### Ev Battery Manufacturing

- structural-battery-pack

### Ev Integration

- cell-to-chassis

### Ev Production

- battery-pack-assembly

### Final Assembly

- final-assembly-line

### Human Robot Collaboration

- human-robot-collaboration

### Industrial Metaverse

- industrial-metaverse

### Industry 4 0

- cyber-physical-production

### Maintenance

- predictive-maintenance-manufacturing

### Manufacturing Execution

- mes-integration

### Mobile Robotics

- agv-amr-navigation

### Nvidia Omniverse Factory

- nvidia-omniverse-factory

### Paint Shop

- paint-shop-automation

### Predictive Analytics

- predictive-shop-floor

### Production Logistics

- just-in-time-2

### Production Optimization

- assembly-line-optimization

### Quality Control

- machine-vision-inspection

### Quality Improvement

- six-sigma-quality

### Quality Management

- spc-quality-control

### Robotics

- robot-programming-industrial

### Supervisory Control

- scada-hmi-factory

### Supply Chain Strategy

- near-shoring-strategy

### Swarm Robotics

- swarm-robotics

### Zero Defect Manufacturing

- zero-defect-manufacturing

## Constraints

- AHSS and aluminum require specialized electrodes and higher current
- Adhesive bonding makes repair and disassembly extremely difficult
- Adhesive cure time impacts production line throughput and floor space
- Alarm floods can overwhelm operators during major faults
- Ambient lighting variation requires controlled environment or adaptive algorithms
- Anisotropic properties require orientation-specific testing
- Autonomous material handling requires clear aisle markings and traffic rules
- Battery life limits shift coverage without swap capability
- Biomechanical limits restrict robot speed and payload in collaborative mode
- Build size limited (300x300x400mm typical for metal SLM)
- Capital expenditure for electrification requires 5-10 year payback justification
- Capital investment for gasification/pyrolysis requires 3-7 year payback
- Capital investment in new tooling required for each production transfer
- Cell quality variation requires strict incoming inspection and matching
- Cement co-processing depends on proximity to cement plant

## Required Tools

- 3D platforms (NVIDIA Omniverse, Unity, Unreal Engine)
- 3D safety cameras (SICK safeVisionary2, Pilz SafetyEYE)
- 3D sensors (Keyence LJ-X series, SICK Ruler, GOM scanners)
- 3D visualization engines (Unity, Unreal Engine, NVIDIA Omniverse)
- AGV/AMR platforms (MiR, KUKA KMR, Balyo, Seegrid, Fetch)
- AM systems (Stratasys, EOS, HP MJF, Desktop Metal, GE Additive)
- AMR fleet management (MiR Fleet, OTTO Fleet Manager)
- AMR platforms (MiR, OTTO Motors, Locus Robotics, Fetch)
- Adhesive dispensing systems (Atlas Copco, Graco, Nordson)
- Atomizers (Dürr EcoBell, Sames rotary bells)
- BI/reporting tools (Power BI, Tableau, Grafana)
- Barcode/RFID hardware (Zebra, Honeywell, Impinj)
- Blockchain (Hyperledger Fabric, VeChain ToolChain)
- Building energy simulation (EnergyPlus, IES VE)
- CAD (CATIA, NX Siemens for die design)


## Instructions

### additive-manufacturing

## Core Competencies
Expert in additive manufacturing technologies for automotive applications with deep knowledge of polymer and metal AM processes, material science, topology optimization, and post-processing.
### AM Technologies
- **FDM (Fused Deposition Modeling)**: Thermoplastic extrusion (ABS, PLA, nylon, ULTEM) for prototypes, jigs - **SLA (Stereolithography)**: UV-cured resin for high-resolution prototypes, casting patterns - **SLS (Selective Laser Sintering)**: Nylon powder fusion for functional prototypes, low-volume parts - **MJF (Multi Jet Fusion)**: HP technology for production-grade nylon parts with isotropic properties - **SLM/DMLS (Selective Laser Melting/Direct Metal Laser Sintering)**: Metal powder fusion (AlSi10Mg, Ti6Al4V, stainless steel, Inconel) for production parts, tooling inserts - **Binder Jetting**: Metal powder + binder, sintering post-process for high-volume metal parts
### Metal AM Applications
- **Lightweighting**: Topology optimization generates organic shapes (30-50% weight reduction vs machined) - **Heat exchangers**: Conformal cooling channels in molds increase cycle efficiency 20-40% - **Consolidation**: Combine 10+ machined parts into single 3D-printed assembly - **Complex geometries**: Undercuts, internal channels impossible with traditional manufacturing - **Rapid tooling**: Direct metal molds for low-volume injection molding (<10K parts)
### Material Properties
- **AlSi10Mg**: 240-350 MPa tensile, lightweight, good thermal conductivity (die casting molds) - **Ti6Al4V**: 1100 MPa tensile, biocompatible, high strength-to-weight (aerospace, racing) - **17-4PH stainless**: 1000 MPa tensile, corrosion resistant (tooling, functional parts) - **Inconel 718**: High-temperature nickel alloy for exhaust, turbo components - **Nylon PA12 (SLS)**: 48 MPa tensile, chemical resistant (intake manifolds, ducting prototypes)
### Design for AM (DFAM)
- **Topology optimization**: Generative design to minimize mass while meeting stiffness/strength (Autodesk Fusion, nTopology) - **Lattice structures**: Lightweight internal fill with controlled stiffness and energy absorption - **Support minimization**: Orient parts to reduce support material (reduce post-processing time 50%) - **Consolidation**: Redesign assemblies as single parts (eliminate fasteners, interfaces) - **Self-supporting angles**: >45° overhang limit for metal SLM without supports
### Post-Processing
- **Support removal**: Manual or CNC machining for complex supports - **Heat treatment**: Stress relief (Ti: 650°C, AlSi10Mg: 300°C), solutionizing + aging for strength - **Machining**: Critical surfaces CNC machined to tight tolerances (±0.05mm vs ±0.2mm as-printed) - **Surface finishing**: Bead blasting, polishing, coating (powder coat, anodize, e-coat) - **Hot Isostatic Pressing (HIP)**: Eliminate internal porosity for fatigue-critical parts (<0.1%)
### Quality Control
- **Dimensional inspection**: CMM or laser scanning vs CAD (as-built vs as-designed) - **Porosity analysis**: CT scanning for internal voids (critical for aerospace, safety parts) - **Mechanical testing**: Tensile, fatigue per ASTM standards (orientation-dependent properties) - **Microstructure**: Metallography to verify grain structure, detect defects (lack-of-fusion) - **In-process monitoring**: Melt pool cameras, thermal imaging for defect detection during build
## Approach
1. **Application Selection**: Identify high-value use cases (complex geometry, low volume, rapid delivery) 2. **Design Optimization**: Topology optimization, lattice design, support minimization 3. **Material Selection**: Match mechanical properties, environment (temperature, chemicals), cost 4. **Build Preparation**: Nesting parts in build volume, support generation, slicing parameters 5. **Printing**: Monitor build (thermal cameras, layer imaging), pause/resume if anomalies 6. **Post-Processing**: Support removal, heat treatment, machining, surface finishing 7. **Inspection**: Dimensional, porosity (CT scan), mechanical testing for qualification 8. **Certification**: Material datasheet, build log, inspection reports for traceability
## Deliverables
- DFAM guidelines for part redesign and topology optimization - Build preparation files (STL, nesting layout, support strategy) - Material qualification reports (mechanical properties, microstructure) - Post-processing procedures (heat treatment cycles, machining operations) - Quality control plan (dimensional, CT scan, mechanical test frequency) - Cost-benefit analysis vs traditional manufacturing (break-even volume analysis) - Certification package for production parts (PPAP-style documentation)
## Best Practices
- Use topology optimization early in design phase (not as afterthought) - Build in optimal orientation: load direction aligned with layer direction for strength - Implement design rules: minimum wall thickness 0.8mm (SLM), 1.5mm (SLS) - Pre-heat build chamber to reduce thermal stress and part warping - Track powder reuse cycles (metal: <10 reuses, nylon: 50/50 virgin/used blend) - Archive build parameters with part serial numbers for traceability - Validate each new material/geometry combination with test coupons
## Integration with Automotive Workflow
- Support R&D with rapid prototyping (days vs weeks for machined prototypes) - Enable low-volume production (classic car parts, race car components) - Accelerate tooling development (conformal cooling molds, custom fixtures) - Provide spare parts on-demand (eliminate obsolete part inventory) - Enable mass customization (customer-specific brackets, trim, accessories)

### agv-amr-navigation

## Core Competencies

Expert in autonomous guided vehicle (AGV) and autonomous mobile robot (AMR) systems for automotive manufacturing logistics with expertise in navigation, fleet coordination, and VDA 5050 integration.

### Navigation Technologies

- **Laser-guided (LGV)**: Reflectors and laser triangulation, ±10mm accuracy, fixed paths
- **Magnetic tape**: Embedded magnets in floor, low cost, requires floor modification
- **Wire-guided**: Inductive wire in floor, oldest technology, rigid paths
- **Vision-guided**: Natural feature navigation, QR codes, no infrastructure modification
- **LiDAR SLAM**: Simultaneous Localization and Mapping, dynamic path planning, ±50mm accuracy
- **UWB (Ultra-Wideband)**: Real-time positioning, cm-level accuracy, multi-vehicle coordination

### Fleet Management

- **Traffic control**: Intersection management, deadlock prevention, priority rules
- **Route optimization**: Shortest path vs least congestion, battery level consideration
- **Task allocation**: Auction algorithms, nearest-neighbor, predictive assignment
- **Charging management**: Opportunity charging, battery swap stations, energy optimization
- **VDA 5050 protocol**: Standardized AGV-to-master communication for multi-vendor fleets

### Path Planning Algorithms

- **A* (A-star)**: Heuristic graph search for static environments
- **D* Lite**: Incremental replanning for dynamic obstacle avoidance
- **RRT (Rapidly-exploring Random Tree)**: High-DOF path planning for complex spaces
- **Dynamic Window Approach (DWA)**: Velocity-based local obstacle avoidance
- **Artificial Potential Fields**: Repulsive forces from obstacles, attractive to goal

### Safety Systems

- **Safety laser scanners**: Multi-zone monitoring (warning, slow, stop) per ISO 3691-4
- **Bumpers**: Mechanical contact sensors for emergency stop
- **Speed limits**: Zone-based speed reduction (pedestrian areas, intersections)
- **Safety-rated PLC**: ISO 13849-1 PLd/Cat 3 for safety function control
- **E-stop buttons**: Emergency stop on vehicle and wireless remote

### Automotive Applications

- **Tugger trains**: Pull multiple carts in assembly line material loops
- **Unit load carriers**: Transport engine blocks, transmissions, battery packs (500-2000 kg)
- **Conveyor interface**: Automatic loading from roller conveyors, lift tables
- **Pallet handling**: Fork AGVs for palletized parts (tires, seats, glass)
- **Goods-to-person**: Deliver parts to kitting stations for JIS assembly

## Approach

1. **Material Flow Analysis**: Map current forklift routes, transport frequency, payload types
2. **Navigation Infrastructure**: Install reflectors, markers, or deploy SLAM-based AMRs
3. **Fleet Sizing**: Calculate number of vehicles based on transport demand and cycle time
4. **Path Network Design**: Define lanes, intersections, charging stations, buffer zones
5. **Fleet Management Software**: Deploy VDA 5050-compliant master control system
6. **Safety Validation**: Test emergency stops, obstacle detection, pedestrian interaction
7. **MES Integration**: Connect AGV system to manufacturing execution for automatic task creation
8. **Optimization**: Monitor utilization, adjust fleet size, refine traffic rules

## Deliverables

- AGV/AMR fleet specification (vehicle count, payload capacity, navigation type)
- Factory layout with navigation infrastructure (reflectors, charging stations, traffic rules)
- VDA 5050-compliant fleet management system configuration
- Safety validation reports per ISO 3691-4 with laser scanner zone definitions
- Material flow simulation results (transport times, vehicle utilization, bottlenecks)
- Integration interfaces with MES, WMS, and ERP systems
- Operator training materials for fleet monitoring and manual intervention

## Best Practices

- Start with one well-defined route (pilot) before full fleet deployment
- Implement VDA 5050 from start for vendor flexibility and future scalability
- Use simulation to validate fleet size before capital investment
- Design bidirectional lanes where possible to avoid deadlock scenarios
- Provide manual override mode for troubleshooting and route changes
- Monitor battery health and cycle count to prevent unexpected downtime
- Establish clear pedestrian crossings with floor markings and traffic lights

## Integration with Automotive Workflow

- Interface with SAP/ERP for material call-offs from supermarket to line
- Integrate with andon system for priority material delivery during shortages
- Coordinate with just-in-sequence suppliers for direct-to-line delivery
- Support mixed-model assembly with variant-specific material routing
- Enable real-time inventory tracking via RFID or barcode scanning on AGVs

### ai-quality-inspection

# AI Quality Inspection Systems

## Overview
AI quality inspection replaces or augments human visual inspection with deep learning
models that detect defects with higher sensitivity, greater consistency, and at
production line speed. This addresses the fundamental limitations of human inspectors
including fatigue, subjectivity, and inability to inspect 100 percent of production
within takt time. The skill covers the complete lifecycle from data collection through
model training, edge deployment, MES integration, and continuous performance monitoring.

## Key Concepts

### AI versus Traditional Machine Vision
Traditional vision uses rule-based programming with edges, patterns, and templates
that are brittle to variation. Deep learning vision learns from examples, handles
variation robustly, and can detect novel defect types. AI systems achieve 98-99.5
percent accuracy in production versus 95-98 percent for traditional approaches,
with lower setup time and reduced lighting dependency.

### Deep Learning Model Types
- Classification: Pass or fail per image, simplest approach requiring balanced dataset
- Object Detection: Locate and classify defects with bounding boxes using YOLO or SSD
- Semantic Segmentation: Pixel-level defect delineation using U-Net or DeepLab
- Anomaly Detection: Detect deviations from normal without labeled defects
- Instance Segmentation: Individual defect instances with pixel masks using Mask R-CNN

### Defect Types by Process
- Paint shop: Orange peel, runs, sags, craters, dirt inclusions, color mismatch
- Body shop: Weld spatter, incomplete welds, surface dents, panel gaps
- Casting: Porosity, shrinkage, cold shuts, inclusions, cracks
- Assembly: Missing parts, wrong parts, incorrect torque, loose connectors

## Implementation Guide

### Step 1 - Data Collection Strategy
Plan systematic image collection covering all production variation.

```python
class InspectionDataCollector:
    def collection_plan(self, defect_types: list) -> dict:
        """Plan data collection for training AI inspection model."""
        plan = {
            "good_samples": {
                "count": 3000,
                "variation": "all shifts, lighting, material batches",
                "purpose": "define normal distribution",
            },
            "defect_samples": {},
        }
        for defect in defect_types:
            plan["defect_samples"][defect] = {
                "target_count": 200,
                "method": "production capture + intentional creation",
                "annotation": "bounding_box_and_severity_label",
            }
        plan["synthetic_augmentation"] = {
            "method": "CutPaste_or_Omniverse_Replicator",
            "target_images": 1000,
            "purpose": "supplement rare defect classes",
        }
        return plan
```

### Step 2 - Model Training Pipeline
Train defect detection with automotive-specific augmentation and validation.

```python
class DefectDetectionTrainer:
    def __init__(self, model_type: str = "yolov8"):
        self.model_type = model_type

    def train(self, dataset_path: str) -> dict:
        """Train defect detection model for production deployment."""
        config = {
            "architecture": self.model_type,
            "input_size": [640, 640],
            "epochs": 200,
            "augmentation": {
                "rotation": 15,
                "brightness": 0.3,
                "gaussian_noise": 0.01,
                "mosaic": True,
            },
            "early_stopping_patience": 20,
        }
        metrics = self._run_training(config, dataset_path)
        return {
            "mAP_50": metrics["mAP_50"],
            "precision": metrics["precision"],
            "recall": metrics["recall"],
            "false_positive_rate": metrics["fpr"],
            "inference_time_ms": metrics["latency"],
        }

    def validate_for_production(self, model, test_set) -> dict:
        """Validate model meets automotive production requirements."""
        results = model.evaluate(test_set)
        return {
            "detection_rate_target": 0.995,
            "false_call_rate_target": 0.02,
            "achieved_detection_rate": results["recall"],
            "achieved_false_call_rate": results["fpr"],
            "production_ready": results["recall"] >= 0.995,
        }
```

### Step 3 - MES Integration and Disposition
Connect AI inspection results to manufacturing execution system for routing.

```python
class AIDispositionEngine:
    def __init__(self, disposition_rules: dict):
        self.rules = disposition_rules

    def process_result(self, result: dict) -> dict:
        """Make disposition decision based on AI inspection result."""
        defects = result.get("defects", [])
        if not defects:
            return {"disposition": "PASS", "route": "next_station"}
        max_severity = max(d["severity"] for d in defects)
        if max_severity >= self.rules["quarantine_severity"]:
            return {
                "disposition": "QUARANTINE",
                "route": "quality_hold_area",
                "requires": "human_review",
            }
        elif max_severity >= self.rules["rework_severity"]:
            return {"disposition": "REWORK", "route": "rework_station"}
        return {"disposition": "PASS", "note": "minor_cosmetic_within_spec"}
```

### Step 4 - Staged Rollout Strategy
Deploy AI inspection through progressive autonomy phases:

```
Phase 1 (Month 1-3):  Shadow mode with AI running alongside human inspector
Phase 2 (Month 4-6):  Assist mode where AI flags defects for human decision
Phase 3 (Month 7-12): Autonomous mode with AI disposition and human audit
Phase 4 (Month 12+):  Full auto with statistical human audit sampling
```

### Step 5 - Continuous Model Monitoring
Track model performance by comparing current false positive and false negative
rates against baseline metrics. Trigger retraining when either rate exceeds 1.5x
the baseline value. Monitor false negative rate as the primary safety indicator
since missed defects reach customers.

## Best Practices
- Collect training data from actual production environments, not lab conditions
- Balance defect classes using oversampling, synthetic data, or focal loss functions
- Validate AI as measurement system using AIAG MSA methodology with Gage R&R
- Always keep human review in the loop for quarantine decisions during initial rollout
- Log every inspection image with result for audit trail and future retraining
- Monitor false negative rate obsessively as missed defects reach customers
- Deploy new model versions in shadow mode before replacing the production model
- Retrain quarterly or whenever new defect types emerge from field complaints

## Troubleshooting
- High false positive rate: Add more good sample variety to training data and verify
  lighting consistency across all camera positions on the inspection station
- Missed defects as false negatives: Verify defect class is adequately represented
  in training data with minimum 200 labeled examples per defect type
- Model works in lab but fails in production: Retrain exclusively with production
  images captured under actual factory lighting and environmental conditions
- Inference too slow for takt time: Quantize model to INT8 precision using TensorRT
  and reduce input resolution to minimum level that maintains detection accuracy
- Operators distrust AI decisions: Display confidence scores on HMI, allow easy
  override mechanism, and publish weekly AI versus human accuracy comparisons
- New defect type not detected: Collect minimum 200 samples of new defect, annotate
  with bounding boxes, retrain model incrementally, and validate before redeployment

### assembly-line-optimization

## Core Competencies

Expert in automotive assembly line optimization using industrial engineering methods, lean principles, and digital simulation to maximize throughput while minimizing cost and quality defects.

### Line Balancing Fundamentals

- **Precedence diagrams**: Task dependencies and sequence constraints
- **Cycle time**: Time allocated per workstation = Takt time / Efficiency target
- **Idle time**: Wasted capacity due to uneven workload distribution
- **Line efficiency**: (Sum of task times) / (Number of stations × Cycle time) × 100%
- **Balancing loss**: Theoretical minimum stations vs actual stations required

### Takt Time Analysis

- **Takt time calculation**: Available production time / Customer demand per shift
- **Example**: 450 min shift / 300 vehicles = 1.5 min/vehicle = 90 seconds takt
- **Pitch**: Container quantity × Takt time (e.g., 10 parts × 90 sec = 15 min)
- **Takt image**: Visual display showing planned vs actual production every takt period
- **Demand variability**: Buffer strategies for fluctuating customer orders

### Bottleneck Identification

- **Theory of Constraints (TOC)**: Identify limiting constraint and exploit it
- **Utilization analysis**: Stations running >95% are bottleneck candidates
- **Queue buildup**: WIP accumulation upstream of constrained station
- **Cycle time variance**: High variability causes dynamic bottlenecks
- **Statistical bottleneck detection**: Time-weighted analysis over production runs

### Task Allocation Methods

- **Ranked Positional Weight (RPW)**: Assign tasks with highest cumulative successor time first
- **COMSOAL (Computer Method of Sequencing Operations for Assembly Lines)**: Heuristic optimization
- **Genetic algorithms**: Evolutionary optimization for complex multi-objective problems
- **Integer linear programming**: Exact solution for small-scale problems
- **Simulation-based optimization**: Evaluate thousands of scenarios with stochastic task times

### Workstation Design

- **Work envelope**: Reach zones (primary, secondary, tertiary) per NIOSH guidelines
- **Material presentation**: Parts delivered at optimal height and orientation
- **Tool accessibility**: Ergonomic tool balancers, error-proofing (poka-yoke)
- **Visual management**: Andon boards, digital work instructions, pick-to-light
- **Standard work**: Documented best practice for each task with target time

### Model Mix Optimization

- **Heijunka (leveling)**: Smooth production mix to avoid batch-and-queue
- **Sequencing rules**: Balance paint shop load, powertrain variants, option content
- **Goal chasing**: Algorithm to meet daily mix targets while respecting line constraints
- **Buffer stock**: Strategic inventory to decouple final assembly from body shop variability
- **Flexibility analysis**: Cross-training matrix, quick changeover capability

## Approach

1. **Current State Analysis**: Time study of all tasks, document precedence constraints
2. **Bottleneck Identification**: Measure utilization, queue lengths, cycle time variability
3. **Line Balancing**: Redistribute tasks to equalize workload across stations
4. **Simulation**: Validate proposed balance with discrete event simulation (Arena, Simio)
5. **Ergonomic Assessment**: REBA/RULA scores, MTM (Methods-Time Measurement) analysis
6. **Implementation**: Kaizen events to reconfigure workstations, retrain operators
7. **Ramp-up**: Gradual speed increase with quality checks at each takt step
8. **Continuous Improvement**: Daily gemba walks, operator feedback, cycle time tracking

## Deliverables

- Line balance chart showing task assignments and station utilization
- Yamazumi chart (stacked bar chart) comparing cycle times to takt time
- Bottleneck analysis report with root cause and countermeasures
- Simulation results (throughput, WIP levels, lead time distribution)
- Ergonomic assessment with recommended workstation modifications
- Standard work documentation with visual work instructions
- Implementation plan with timeline, resource requirements, expected ROI

## Best Practices

- Involve operators in kaizen events — they know the tasks best
- Use video recording for detailed time study (avoid observer bias)
- Account for learning curve when introducing new tasks or operators
- Design for 85-90% utilization target (not 100%) to allow recovery from disruptions
- Validate simulation model against actual production before optimization
- Pilot changes on one shift before full rollout
- Track OEE (Overall Equipment Effectiveness) before and after optimization

## Integration with Automotive Workflow

- Align with body shop and paint shop cycle times for flow production
- Coordinate with logistics for just-in-sequence (JIS) part delivery
- Interface with MES for real-time production tracking and andon escalation
- Provide capacity data to supply chain planning for new model launches
- Support dual sourcing and supplier development with consistent takt requirements

### battery-pack-assembly

## Core Competencies
Expert in EV battery pack manufacturing with deep knowledge of cell handling automation, joining technologies, thermal management assembly, and quality validation.
### Assembly Sequence
- **Cell incoming inspection**: Voltage, impedance, weight screening (reject outliers >5 mV delta) - **Cell stacking**: Automated pick-and-place with vision alignment (±0.5mm precision) - **Busbar welding**: Laser welding (copper/aluminum) or ultrasonic welding (aluminum) - **Module assembly**: Stack cells, install compression plates, apply thermal interface material (TIM) - **Module testing**: Voltage, insulation resistance (>100 MΩ), leak test (if liquid-cooled) - **Pack integration**: Install modules in housing, route busbars, apply pack-level TIM - **BMS installation**: Connect sense wires, current sensors, temperature sensors - **Final sealing**: Lid laser welding or adhesive bonding, helium leak test (<1 Pa·m³/s) - **EOL test**: High-voltage insulation (500V DC), functional test (charge/discharge), flash BMS firmware
### Cell Handling Automation
- **Vision-guided pick**: 2D cameras locate cells on trays (compensate for tray variation) - **Vacuum grippers**: Soft pads to avoid cell damage (dent, puncture, short circuit risk) - **Force control**: <5N compression force during stacking (prevent swelling, damage) - **Cleanliness**: Class 100K cleanroom, ESD protection (wrist straps, ionizers) - **Traceability**: Barcode/QR scan each cell, link to pack serial number for genealogy
### Welding Technologies
- **Laser welding**: Fiber laser 1-3 kW for copper/aluminum busbars (0.3-0.5mm penetration) - **Ultrasonic welding**: High-frequency vibration for aluminum tabs (no heat, no spatter) - **Resistance welding**: Spot weld for nickel-plated steel tabs (automotive standard for cylindrical cells) - **Weld quality**: Ultrasonic inspection, peel test, electrical resistance <0.5 mΩ - **Process monitoring**: Real-time laser power, weld pool camera, acoustic emission
### Thermal Interface Materials
- **Gap fillers**: Silicone-based, 3-5 W/mK thermal conductivity, 0.5-3mm gap - **Thermal paste**: High conductivity 5-10 W/mK, <0.2mm bondline thickness - **Phase change materials (PCM)**: Solid at room temp, liquify at operating temp for conformability - **Application**: Automated dispensing with volumetric control, vision verify coverage - **Compression**: Apply controlled pressure (0.1-0.3 MPa) to achieve target bondline
### Leak Testing
- **Helium sniff test**: Spray helium, detect with mass spectrometer (sensitivity <1×10⁻⁶ mbar·L/s) - **Pressure decay**: Pressurize pack to 10 kPa, monitor pressure drop over 60 sec - **Dunk test**: Submerge in water, detect bubbles (simple but effective for gross leaks) - **Critical for liquid cooling**: Coolant leak into cells causes short circuit, thermal runaway - **Acceptance**: <1 Pa·m³/s leak rate for automotive packs
### Electrical Testing
- **Insulation resistance**: 500V DC hipot test, >100 MΩ pack-to-chassis - **Voltage verification**: Measure each parallel group, total pack voltage vs expected - **BMS functional test**: Simulate cell imbalance, verify balancing, safety disconnects - **Current sensor calibration**: Verify accuracy ±1% full scale (0-400A typical) - **Flash firmware**: Upload BMS software, configure pack parameters (capacity, limits)
## Approach
1. **Cell Selection**: Match cells within module for voltage, impedance (±5 mV, ±5 mΩ) 2. **Automation Design**: Robot cell layout, vision systems, welding stations, test fixtures 3. **Welding Development**: DOE on laser power, speed, focus for optimal weld strength 4. **TIM Validation**: Thermal resistance measurement, compression set testing per operating conditions 5. **Dry Run**: Assemble prototype packs with instrumentation (thermocouples, voltage taps) 6. **Quality Validation**: Vibration test, thermal cycling, abuse tests (crush, penetration, overcharge) 7. **Production Ramp**: Monitor KPIs (first-pass yield, weld defects, leak rate, cycle time) 8. **Continuous Improvement**: Pareto analysis of defects, kaizen on bottleneck stations
## Deliverables
- Battery pack assembly process flow with cycle times and automation level - Cell matching specification (voltage, impedance, capacity tolerances) - Welding parameters (laser power, speed, focal offset) with quality acceptance criteria - TIM application procedure with dispense pattern and compression force - EOL test specification (insulation, voltage, leak, BMS functional) - Traceability system design (cell-to-module-to-pack genealogy) - PPAP package with capability studies and validation test results
## Best Practices
- Maintain dry room (<1% RH) to prevent lithium carbonate formation on cell surfaces - Implement cell aging (24-72 hr rest after formation) before pack assembly - Use torque-angle tightening for compression plates (ensure uniform compression) - Monitor ambient temperature (20-25°C) to maintain TIM viscosity during dispense - Implement ESD protection throughout (cells sensitive to static discharge) - Design pack for serviceability: modular replacement vs scrap entire pack - Track cell supplier lots: correlate field failures to specific batches
## Integration with Automotive Workflow
- Interface with cell supplier for JIT delivery and quality agreements - Provide pack specifications to vehicle integration team (CAN protocols, thermal interface) - Coordinate with battery management system software team for calibration parameters - Support APQP with validation testing (UN 38.3 transport, UL 2580 safety) - Enable circular economy: design for disassembly and second-life repurposing

### body-shop-welding

## Core Competencies

Expert in automotive body shop welding technologies with deep knowledge of resistance spot welding (RSW), laser welding, adhesive bonding, and quality assurance for body-in-white assembly.

### Resistance Spot Welding (RSW)

- **Process**: Two copper electrodes apply pressure + current to fuse sheet metal (nugget formation)
- **Weld schedule**: Squeeze time, weld current (kA), weld time (cycles), hold time, tempering pulses
- **Nugget diameter**: 4√t to 6√t mm (where t = thinner sheet thickness in mm)
- **Joint strength**: 3-5 kN shear strength typical for 1mm steel
- **Typical parameters**: 8-12 kA, 10-20 cycles @ 60 Hz, 4 kN electrode force

### Electrode Management

- **Electrode material**: Class 2 copper-chromium (high conductivity + wear resistance)
- **Tip geometry**: Domed (general), radius (aluminum), truncated cone (high strength steel)
- **Tip dressing**: Automatic dressing every 200-500 welds (remove mushrooming, restore geometry)
- **Tip life**: 1000-5000 welds depending on material (AHSS reduces life 50%)
- **Quality monitoring**: Nugget size verification via peel test, chisel test, ultrasonic

### Advanced High Strength Steel (AHSS) Challenges

- **Higher current**: 20-50% increase vs mild steel for same nugget size
- **Expulsion risk**: Narrow process window between insufficient fusion and surface expulsion
- **Adaptive welding**: Real-time current control based on dynamic resistance feedback
- **Coating issues**: Zinc coating (galvanized) causes electrode sticking, requires frequent dressing
- **Metallurgy**: Martensite formation in heat-affected zone (HAZ) can cause hardness variation

### Laser Welding

- **Laser types**: Fiber laser (high efficiency, low maintenance), CO2 laser (legacy)
- **Power**: 3-6 kW for body-in-white seams
- **Joint types**: Lap (overlapping sheets), butt (edge-to-edge), fillet
- **Advantages**: Deep penetration, narrow HAZ, no electrodes, hermetic seals
- **Applications**: Roof seams, door frames, tailored blanks, aluminum space frames

### Weld Quality Monitoring

- **In-process**: Dynamic resistance curve analysis, force-displacement monitoring
- **Ultrasonic**: Non-destructive nugget size verification (C-scan imaging)
- **Destructive testing**: Peel test, chisel test, cross-sectioning (metallography)
- **Vision systems**: Laser weld seam tracking, detect undercut, porosity
- **Adaptive control**: Adjust current/time based on measured electrode displacement

### Multi-Material Joining

- **Aluminum-steel**: Requires transition elements (rivet-bonding, laser welding with filler)
- **CFRP-metal**: Mechanical fasteners (rivets, clinching), adhesive bonding
- **Joining methods**: RSW (steel-steel), laser welding (aluminum), friction stir (aluminum), SPR (self-pierce riveting for dissimilar)

## Approach

1. **Material Characterization**: Identify base metal (HSLA, AHSS, aluminum), coating type, thickness
2. **Weld Schedule Development**: DOE to optimize current, time, force for nugget size + strength
3. **Robot Programming**: Teach weld gun approach angles, optimize air cut time between welds
4. **Electrode Selection**: Match tip geometry and material to base metal and weld count
5. **Quality Validation**: Peel test 30+ samples, confirm nugget diameter and weld strength
6. **Production Monitoring**: SPC on weld current, dynamic resistance, electrode displacement
7. **Maintenance Strategy**: Automatic tip dressing frequency, electrode replacement schedule
8. **Continuous Improvement**: Pareto analysis of weld defects, DOE for process optimization

## Deliverables

- Weld schedule database (current, time, force) for all material combinations
- Robot weld gun programming with optimized paths and approach vectors
- Electrode tip life study with dressing frequency recommendations
- Quality control plan (in-process monitoring, destructive test frequency)
- SPC charts for critical weld parameters (current, nugget size, expulsion rate)
- Adaptive welding implementation (closed-loop control system)
- Cost-benefit analysis for electrode dressing vs replacement strategies

## Best Practices

- Perform weld lobes (current vs time) to define process window for each material stack
- Use mid-frequency DC welding (1000 Hz) for consistent quality vs AC (reduced spatter)
- Implement servo weld guns for precise force control and electrode displacement feedback
- Monitor electrode condition with vision systems (tip wear, alignment, contamination)
- Design flanges for accessibility (robot reach, gun clearance, electrode access)
- Use adhesive-bonding hybrid: structural adhesive + spot welds for NVH improvement
- Validate process capability: Cpk ≥1.33 for weld strength and nugget size

## Integration with Automotive Workflow

- Coordinate with body design for weld flange geometry and accessibility
- Interface with paint shop for post-weld cleaning and e-coat corrosion protection
- Provide weld maps and locations to final assembly for build verification
- Support APQP with PPAP weld sample submission and capability studies
- Enable digital twin updates with actual weld quality data from production

### carbon-neutral-assembly

## Overview

Carbon-neutral assembly integrates energy management, process engineering, and carbon accounting
to eliminate greenhouse gas emissions from automotive manufacturing. This skill covers the full
pathway from baseline carbon footprint assessment through renewable energy deployment, process
electrification, waste heat recovery, and residual offset procurement.

Modern automotive OEMs target Scope 1 and 2 neutrality by 2030 and full Scope 3 neutrality
by 2040, requiring systematic transformation of every energy-consuming process in the plant.


## Key Concepts

### Carbon Scopes in Automotive Assembly

- **Scope 1 (Direct)**: Natural gas combustion in paint ovens, emergency generators, plant vehicles
- **Scope 2 (Indirect Energy)**: Purchased electricity for robots, conveyors, HVAC, lighting
- **Scope 3 (Value Chain)**: Upstream materials (steel, aluminum, plastics), logistics, employee commuting

### Energy Intensity Benchmarks

- **Stamping**: 40-60 kWh per vehicle (press energy, coil handling)
- **Body Shop**: 150-250 kWh per vehicle (resistance welding, laser joining)
- **Paint Shop**: 500-900 kWh per vehicle (largest consumer: ovens, booths, HVAC)
- **Final Assembly**: 80-120 kWh per vehicle (tools, test stands, conveyors)
- **Total Plant**: 800-1400 kWh per vehicle (benchmark: <900 kWh for best-in-class)

### Carbon Intensity Metrics

- **kg CO2e per vehicle**: Primary KPI, typically 200-500 kg for Scope 1+2
- **Energy carbon factor**: Grid-dependent, 0.02 (Norway) to 0.9 (Poland) kg CO2e/kWh
- **Process carbon factor**: Natural gas = 0.184 kg CO2e/kWh thermal


## Implementation Guide

### Step 1: Baseline Carbon Footprint

Conduct a comprehensive energy and emissions audit:

```python
# Carbon footprint calculation framework
class PlantCarbonFootprint:
    def __init__(self, plant_id: str):
        self.plant_id = plant_id
        self.scope1_sources = {}
        self.scope2_sources = {}
        self.scope3_sources = {}

    def calculate_scope1(self, natural_gas_mwh: float, diesel_liters: float) -> float:
        """Calculate direct emissions from fuel combustion."""
        GAS_FACTOR = 0.184  # kg CO2e per kWh thermal
        DIESEL_FACTOR = 2.68  # kg CO2e per liter
        return (natural_gas_mwh * 1000 * GAS_FACTOR) + (diesel_liters * DIESEL_FACTOR)

    def calculate_scope2(self, electricity_mwh: float, grid_factor: float) -> float:
        """Calculate indirect emissions from purchased electricity."""
        return electricity_mwh * 1000 * grid_factor

    def vehicles_per_year(self, annual_production: int, total_co2_kg: float) -> float:
        """Return kg CO2e per vehicle produced."""
        return total_co2_kg / annual_production
```

### Step 2: Renewable Energy Strategy

```yaml
# Renewable energy mix planning
renewable_portfolio:
  on_site_solar:
    capacity_mwp: 12.0
    annual_yield_mwh: 11400
    coverage_pct: 15
  power_purchase_agreement:
    type: offsite-wind
    capacity_mw: 40
    annual_yield_mwh: 105000
    coverage_pct: 70
  battery_storage:
    capacity_mwh: 20
    purpose: peak-shaving-and-solar-shift
  green_certificates:
    type: GO-REGO
    annual_mwh: 18000
    coverage_pct: 15
```

### Step 3: Process Electrification

Replace natural gas with electric alternatives:

- **Paint oven curing**: Infrared panel heaters or induction curing (60% energy reduction)
- **Pretreatment baths**: Electric immersion heaters replacing gas-fired heat exchangers
- **Building HVAC**: Industrial heat pumps using waste heat from compressors and ovens
- **Process hot water**: Solar thermal collectors with electric boost

### Step 4: Heat Recovery Network

```
Waste Heat Sources          Heat Sinks
==================          ==========
Paint oven exhaust (180C) -> Pretreatment bath heating (60C)
Weld transformer cooling  -> Building space heating (40C)
Compressor aftercoolers   -> Process hot water (55C)
RTO exhaust (300C)        -> Paint booth makeup air (25C)
```

### Step 5: Carbon Accounting System

```python
# Real-time carbon tracking integrated with MES
class CarbonTracker:
    def __init__(self, mes_connection, energy_meters: list):
        self.mes = mes_connection
        self.meters = energy_meters

    def calculate_per_vehicle_carbon(self, vehicle_vin: str) -> dict:
        """Track carbon footprint per individual vehicle."""
        energy_data = self.collect_energy_by_station(vehicle_vin)
        return {
            "vin": vehicle_vin,
            "scope1_kg": self.gas_consumption_to_co2(energy_data["gas_kwh"]),
            "scope2_kg": self.electricity_to_co2(energy_data["elec_kwh"]),
            "total_kg": None,  # computed as sum
            "timestamp": energy_data["completion_time"],
        }
```


## Best Practices

- Start with the paint shop -- it accounts for 50-70% of plant energy consumption
- Install sub-metering on every major energy consumer before optimization
- Use ISO 50001 energy management system as the governance framework
- Negotiate long-term PPAs (10-15 years) for cost-effective renewable electricity
- Design heat recovery networks with redundancy -- production cannot stop for maintenance
- Track carbon per vehicle, not just per plant, to account for production volume changes
- Validate renewable energy certificates are additional and time-matched (hourly matching by 2030)
- Engage suppliers on Scope 3 reduction -- material production dominates total lifecycle emissions


## Common Patterns

### Paint Shop Decarbonization Sequence

1. Switch to waterborne basecoats (reduces VOC, enables lower cure temperatures)
2. Install regenerative thermal oxidizers (RTO) with 95%+ heat recovery
3. Replace gas-fired ovens with IR panel heaters (zone-by-zone conversion)
4. Recover RTO exhaust heat for booth makeup air preheating
5. Electrify remaining gas loads with industrial heat pumps

### Energy Monitoring Architecture

```
Smart Meters (Modbus/BACnet)
     |
Edge Gateway (OPC UA aggregation)
     |
Energy Management Platform (ISO 50001)
     |
Carbon Dashboard (real-time kg CO2e/vehicle)
```


## Troubleshooting

- **Grid instability with high renewable share**: Deploy battery storage for frequency regulation
- **Heat pump COP drops in winter**: Size for worst-case ambient, use waste heat as source
- **Carbon accounting discrepancies**: Reconcile meter data monthly against utility invoices
- **PPA price volatility**: Use collar structures (floor/cap) in contract terms
- **Scope 3 data gaps**: Start with tier-1 suppliers using CDP questionnaires
- **Paint cure quality with IR heaters**: Validate cure window with DSC and MEK rub tests

### cell-to-chassis

## Core Competencies

Expert in cell-to-chassis (CTC) and cell-to-pack (CTP) battery integration for electric vehicles with deep knowledge of structural design, adhesive bonding, thermal management, and crashworthiness.

### CTC/CTP Architecture

- **Cell-to-Pack (CTP)**: Eliminate modules, bond cells directly into pack housing (BYD Blade, CATL Qilin)
- **Cell-to-Chassis (CTC)**: Battery pack IS the vehicle floor structure (Tesla, Nio ET5, Zeekr 001)
- **Weight reduction**: 10-20% vs traditional pack-in-chassis design
- **Volume efficiency**: 60-70% pack-level energy density vs 40-50% traditional
- **Cost reduction**: Eliminate module hardware, reduce assembly steps

### Structural Adhesive Bonding

- **Adhesive types**: Epoxy (high strength), polyurethane (flexibility, crash energy absorption)
- **Surface preparation**: Plasma treatment, primer application for aluminum and polymer surfaces
- **Dispensing**: Robotic application with volumetric control (±5% tolerance)
- **Curing**: Thermal cure (180°C 30 min) or UV cure for specific zones
- **Bond strength**: >10 MPa shear strength, withstand 5g crash loads

### Thermal Management Integration

- **Cooling plates**: Integrated into pack bottom, bonded to cell undersides
- **Thermal interface material (TIM)**: Silicone gap filler (3-5 W/mK conductivity)
- **Cold plate design**: Microchannel aluminum extrusion with glycol-water coolant
- **Thermal simulation**: CFD to verify <5°C temperature delta across pack
- **Assembly process**: Automated TIM dispensing, cell stacking with pressure control

### Crash Safety Design

- **Load paths**: Battery pack transmits side impact and floor loads (integrated structure)
- **Crush zones**: Peripheral energy-absorbing structures protect cells from intrusion
- **Cell-level protection**: Honeycomb or foam between cells to prevent propagation
- **Adhesive ductility**: Prevent brittle fracture, allow controlled deformation
- **Validation**: Pole test, side impact, bottom ball test per UN R100

### Manufacturing Process

- **Cell placement**: Vision-guided robots with ±0.5mm positioning accuracy
- **Adhesive dispensing**: 2K epoxy or PU with static mixer, bead inspection
- **Bonding pressure**: Vacuum bag or mechanical fixturing during cure (0.1-0.3 MPa)
- **Quality inspection**: Ultrasonic C-scan for bond voids, thermography for TIM coverage
- **Final sealing**: Laser welding of pack lid, leak test (helium sniffing <1 Pa·m³/s)

### Assembly Sequence

1. **Cooling plate installation**: Bond to chassis floor or pack bottom
2. **TIM application**: Automated dispense on cooling plate surface
3. **Cell stacking**: Robot places cells in array, applies compression
4. **Adhesive application**: Dispense around cell perimeter and lateral surfaces
5. **Top plate/lid**: Install with compression, route busbars, apply final adhesive
6. **Cure**: Oven cure or room-temp cure with extended fixturing time
7. **Inspection**: Electrical test, thermal imaging, ultrasonic bond check
8. **Integration**: Lift battery-chassis assembly, marry with upper body

## Approach

1. **Design Collaboration**: Integrate battery, thermal, structure, crash teams from concept phase
2. **CAE Simulation**: FEA for structural loads, CFD for thermal, crash simulation for safety
3. **Material Selection**: Trade-off adhesive strength, flexibility, cure time, cost
4. **Process Development**: DOE on adhesive amount, pressure, cure temp/time
5. **Prototype Build**: Hand assembly with instrumentation (thermocouples, strain gauges)
6. **Validation Testing**: Crash tests, thermal cycling, vibration per USCAR standards
7. **Automation Design**: Robot cell layout, adhesive dispensing equipment, fixturing
8. **Production Ramp**: Monitor quality metrics (bond voids, thermal resistance, leak rate)

## Deliverables

- CTC/CTP system architecture with CAD models and interface definitions
- Adhesive selection report with mechanical properties and process parameters
- Thermal management design with cooling plate layout and TIM specification
- Crash simulation results demonstrating intrusion limits and cell protection
- Manufacturing process flow with cycle time and automation level
- Quality control plan (ultrasonic, thermography, electrical, leak test)
- PPAP documentation for customer approval (PSW, capability studies)

## Best Practices

- Co-design battery and chassis from start (avoid bolt-on approach)
- Use structural adhesive simulation tools (Abaqus cohesive elements) for accurate prediction
- Validate TIM thermal performance with thermal test vehicles (not just datasheet values)
- Design for disassembly: modular sections for repair/recycling (bonding makes disassembly difficult)
- Implement thermal runaway mitigation: propagation barriers, venting channels
- Monitor production bond quality with statistical sampling (ultrasonic C-scan)
- Plan for second-life and recycling: adhesive debonding methods (thermal, chemical)

## Integration with Automotive Workflow

- Coordinate with megacasting team for underbody interface design
- Align with final assembly on marriage station (upper body to battery-chassis)
- Provide thermal and electrical specifications to BMS and powertrain teams
- Support APQP with DVP&R (Design Verification Plan & Report) for crash and thermal
- Enable sustainability goals: design for disassembly and circular economy

### circular-production

# Circular Production Systems

## Overview
Circular production transforms the traditional linear take-make-dispose model into
closed loops where materials are continuously recycled, components are remanufactured,
and waste streams become inputs for other processes. In automotive manufacturing, this
addresses regulatory pressure from the EU ELV Directive requiring 95 percent recovery
rate and creates economic opportunity through material value retention.

## Key Concepts

### R-Strategy Hierarchy
Circular actions ranked from highest to lowest value retention:

- R0 Refuse: Eliminate unnecessary components through design simplification
- R1 Reduce: Lightweighting and material optimization
- R2 Reuse: Direct reuse of components such as seats, ECUs, and glass
- R3 Repair: Extend vehicle life through modular repair-friendly design
- R4 Remanufacture: Full restoration to original specifications with warranty
- R5 Repurpose: Second-life applications such as EV battery to grid storage
- R6 Recycle: Material recovery for reprocessing into new products
- R7 Recover: Energy recovery from non-recyclable waste streams

### Material Flows in Automotive Production
Steel stamping generates 25 percent scrap routed to EAF steelmakers. Aluminum
stamping generates 40 percent scrap suitable for closed-loop alloy recycling.
Plastic injection molding produces 5 percent scrap for in-process regrind reuse.
Paint shops lose 50 percent of applied material as overspray requiring solvent
recovery and sludge management.

## Implementation Guide

### Step 1 - Waste Stream Analysis
Map all production waste streams with volume, composition, and recovery value.

```python
class WasteStreamAnalyzer:
    def __init__(self, plant_id: str, annual_production: int):
        self.plant_id = plant_id
        self.production = annual_production

    def map_waste_streams(self, process_data: list) -> list:
        """Map all waste streams with volume and circular pathway."""
        streams = []
        for process in process_data:
            for waste in process["waste_outputs"]:
                annual_tons = waste["kg_per_vehicle"] * self.production / 1000
                streams.append({
                    "process": process["name"],
                    "material": waste["material"],
                    "annual_tons": annual_tons,
                    "current_disposition": waste["disposition"],
                    "recovery_value_per_ton": waste["market_value"],
                    "annual_value": annual_tons * waste["market_value"],
                    "circular_opportunity": self._identify_path(waste),
                })
        return sorted(streams, key=lambda s: s["annual_value"], reverse=True)

    def _identify_path(self, waste: dict) -> str:
        if waste["material"] == "aluminum" and waste.get("alloy_known"):
            return "closed_loop_to_same_alloy_supplier"
        elif waste["material"] == "steel":
            return "sorted_scrap_to_EAF_steelmaker"
        elif waste["material"] == "plastic" and waste.get("contamination_pct", 100) < 5:
            return "regrind_reuse_in_process"
        return "external_recycler"
```

### Step 2 - Battery Circular Economy
Route batteries through optimal circular pathways based on state of health.

```python
class BatteryCircularManager:
    SOH_REMANUFACTURE_THRESHOLD = 0.80
    SOH_SECOND_LIFE_THRESHOLD = 0.60
    SOH_RECYCLE_THRESHOLD = 0.40

    def determine_path(self, battery: dict) -> dict:
        """Route battery to optimal circular pathway."""
        soh = battery["state_of_health"]
        if soh >= self.SOH_REMANUFACTURE_THRESHOLD:
            return {"path": "remanufacture", "action": "replace_degraded_cells"}
        elif soh >= self.SOH_SECOND_LIFE_THRESHOLD:
            return {"path": "second_life", "action": "repurpose_for_storage"}
        elif soh >= self.SOH_RECYCLE_THRESHOLD:
            return {"path": "recycle", "action": "hydrometallurgical_recovery"}
        return {"path": "recycle", "action": "pyrometallurgical_recovery"}
```

### Step 3 - Material Passport System
Track material composition through multiple lifecycle loops for traceability.

```python
class MaterialPassport:
    def __init__(self, vehicle_vin: str):
        self.vin = vehicle_vin
        self.materials: list[dict] = []

    def register_material(self, component: str, material: dict) -> None:
        self.materials.append({
            "component": component,
            "material_type": material["type"],
            "weight_kg": material["weight"],
            "recycled_content_pct": material["recycled_pct"],
            "recyclability_score": material["recyclability"],
        })

    def calculate_vehicle_recyclability(self) -> float:
        """Calculate overall vehicle recyclability rate (target >= 0.95)."""
        total = sum(m["weight_kg"] for m in self.materials)
        recyclable = sum(m["weight_kg"] * m["recyclability_score"] for m in self.materials)
        return recyclable / total if total > 0 else 0.0
```

### Step 4 - Factory Zero-Waste Hierarchy
Apply prioritized waste reduction strategies across all production areas:

```
Priority 1: Eliminate waste at source through design optimization
Priority 2: Reuse in process via regrind plastic and recirculated coolant
Priority 3: Closed-loop recycle to same product such as aluminum scrap to sheet
Priority 4: Open-loop recycle to different product such as steel scrap to rebar
Priority 5: Energy recovery from non-recyclable waste to cement kiln
Priority 6: Landfill as absolute last resort with target of zero
```

## Best Practices
- Segregate production scrap by alloy and grade at source to preserve recycling value
- Design snap-fit and bolted joints for disassembly instead of adhesive bonds
- Mark all plastic parts with ISO 11469 material identification codes
- Use mono-material designs where feasible and avoid multi-layer composites
- Establish take-back agreements with material suppliers for closed-loop recycling
- Track recycled content with chain-of-custody certification such as ISCC Plus
- Start remanufacturing with high-value components like power electronics and motors
- Calculate LCA for circular versus linear pathways to validate environmental benefit

## Troubleshooting
- Scrap alloy contamination: Install XRF sorters at scrap collection points to
  verify alloy grade before routing to recyclers
- Recycled plastic property degradation: Blend with virgin material at 70/30 ratio
  and add stabilizers to maintain mechanical properties
- Low remanufacturing core return rates: Incentivize returns with core deposit
  programs and easy reverse logistics channels
- Recycled content verification challenges: Use mass balance approach with annual
  third-party audits for certification compliance
- End-of-life dismantling cost exceeds material value: Redesign joints and fasteners
  for faster disassembly to improve economic viability
- Battery second-life liability concerns: Establish clear warranty terms with
  documented performance certification and degradation projections

### cobot-integration

## Core Competencies

Expert in collaborative robot integration for automotive manufacturing with deep knowledge of ISO/TS 15066 safety requirements, force/torque limiting, and human-robot workspace design.

### Cobot Platforms

- **Universal Robots (UR)**: UR3e, UR5e, UR10e, UR16e with built-in force/torque sensing
- **ABB YuMi**: Dual-arm cobot for small parts assembly, inherently force-limited
- **KUKA LBR iiwa**: 7-DOF sensitive robot with joint torque sensors for compliant motion
- **Fanuc CR series**: Collaborative versions of industrial robots with green soft covering
- **Doosan Robotics**: M-series cobots with integrated vision and force control

### ISO/TS 15066 Collaboration Modes

- **Safety-rated monitored stop**: Robot stops when operator enters shared workspace
- **Hand guiding**: Operator physically guides robot to teach positions or adjust path
- **Speed and separation monitoring (SSM)**: Robot slows/stops based on human proximity
- **Power and force limiting (PFL)**: Inherent safety via torque limits and soft surfaces

### Biomechanical Limits (ISO/TS 15066 Annex A)

- **Pressure limits**: Body region-specific (e.g., hand/fingers 140 N, forearm 160 N)
- **Transient contact**: Quasi-static vs dynamic impact force calculations
- **Clamping scenarios**: Trapped body part between robot and fixed object (stricter limits)
- **Free contact**: Robot momentum without external clamping (higher allowed forces)
- **Measurement**: Force/pressure gauges per ISO/TS 15066 test protocol

### Workspace Design

- **Shared workspace**: Zone where human and robot can operate simultaneously
- **Collaborative workspace**: Subset where intentional interaction occurs
- **Safety zones**: Protective stop, reduced speed, and warning zones with safety laser scanners
- **Layout optimization**: Minimize shared workspace, maximize ergonomic positioning
- **Visual demarcation**: Floor markings, light curtains, andon indicators

### Risk Assessment

- **ISO 12100 methodology**: Hazard identification, risk estimation, risk reduction
- **Task analysis**: Break down each operation into robot motions and human actions
- **Contact scenarios**: Identify all possible collision points (pinch, impact, crush)
- **Speed/force validation**: Measure actual forces with calibrated test equipment
- **Residual risk**: Document acceptable risks with operator training and PPE

### Application Examples

- **Screw assembly**: Cobot presents fastener, operator aligns, cobot tightens with torque control
- **Quality inspection**: Cobot holds part at ergonomic height while operator verifies dimensions
- **Kitting**: Cobot picks from bins and presents to operator in optimal orientation
- **Machine tending**: Cobot loads/unloads CNC or press while operator monitors quality
- **Adhesive dispensing**: Operator places part, cobot applies precise bead, operator removes

## Approach

1. **Task Analysis**: Define human and robot roles, sequence, and interaction points
2. **Risk Assessment**: ISO 12100 hazard identification and ISO/TS 15066 biomechanical evaluation
3. **Workspace Design**: Layout shared zones, safety sensors, and ergonomic considerations
4. **Robot Selection**: Choose payload, reach, and force sensitivity based on application
5. **Safety Validation**: Measure contact forces with test dummy per ISO/TS 15066 protocol
6. **Programming**: Implement safety functions (protective stop, speed limits, force thresholds)
7. **Operator Training**: Teach safe interaction, emergency stop procedures, error recovery
8. **Continuous Monitoring**: Log force events, near-misses, and cycle time for optimization

## Deliverables

- Risk assessment report with ISO 12100 and ISO/TS 15066 compliance documentation
- Workspace layout CAD with safety zones and sensor placement
- Force/pressure measurement results vs biomechanical limits
- Robot program with safety-rated speed and force monitoring
- Operator training materials and standard work instructions
- Safety validation test reports with video documentation
- Maintenance procedures for force/torque sensors and safety devices

## Best Practices

- Always perform force measurements on actual production setup (not simulation)
- Use worst-case scenarios for risk assessment (heaviest tool, fastest speed, hardest part)
- Document all safety parameter choices (speed limits, force thresholds) with justification
- Train operators on safe recovery from protective stops (do not defeat safety features)
- Periodically re-validate forces after program changes or tool modifications
- Implement dual-channel safety monitoring for PLd/Cat 3 per ISO 13849-1
- Provide emergency stop buttons within easy reach of all operator positions

## Integration with Automotive Workflow

- Interface with MES for work instruction download and quality data upload
- Coordinate with line balancing to allocate human vs robot tasks optimally
- Support operator assistance systems with AR overlays for cobot status
- Enable flexible redeployment of cobots across workstations for model mix changes
- Provide ergonomic improvements for aging workforce and injury reduction

### cyber-physical-production

## Overview

Cyber-physical production systems (CPPS) merge physical manufacturing equipment with
computational intelligence, creating systems where sensors, actuators, and software form
tight feedback loops that optimize production autonomously. Unlike traditional automation
where PLCs follow fixed programs, CPPS systems sense their environment, reason about
optimal actions, and adapt in real time.

In automotive manufacturing, CPPS enables welding robots that adjust parameters based on
material batch variation, paint booths that optimize atomization based on humidity,
and assembly stations that reconfigure tooling based on the next vehicle variant --
all without human intervention for routine optimization decisions.


## Key Concepts

### CPPS Architecture Layers (RAMI 4.0 aligned)

```
Layer 6: Business      (ERP, demand planning, cost optimization)
Layer 5: Functional    (MES, production scheduling, quality management)
Layer 4: Information   (Data lake, analytics, ML model serving)
Layer 3: Communication (OPC UA, MQTT, TSN Ethernet)
Layer 2: Integration   (Edge computing, protocol conversion, data aggregation)
Layer 1: Asset         (Sensors, actuators, PLCs, robots, machines)
```

### Control Loop Types

- **Real-time control** (<1ms): PLC-level, safety functions, servo drives
- **Near-real-time** (1-100ms): Edge computing, adaptive process parameters
- **Operational** (seconds-minutes): MES decisions, scheduling, quality routing
- **Tactical** (hours-days): Production planning, maintenance scheduling
- **Strategic** (weeks-months): Capacity planning, investment decisions

### Asset Administration Shell (AAS)

The Industry 4.0 digital nameplate for every physical asset:

```yaml
asset_administration_shell:
  identification:
    asset_id: "urn:factory01:robot:kuka:kr240:001"
    serial_number: "KR240-2024-001234"
  submodels:
    - nameplate: {manufacturer: "KUKA", model: "KR240 R2900"}
    - technical_data: {payload_kg: 240, reach_mm: 2900}
    - operational_data: {cycle_count: 1245000, uptime_pct: 96.3}
    - maintenance: {next_service: "2026-04-15", remaining_life_hours: 8500}
    - energy: {avg_consumption_kw: 12.5, standby_kw: 0.8}
```


## Implementation Guide

### Step 1: Sensor Layer Deployment

```python
# IoT sensor integration for CPPS
class CPPSSensorLayer:
    def __init__(self, edge_gateway_url: str):
        self.gateway = edge_gateway_url
        self.sensors = {}

    def register_sensor(self, sensor_config: dict):
        """Register sensor with edge gateway and configure data pipeline."""
        self.sensors[sensor_config["id"]] = {
            "type": sensor_config["type"],
            "protocol": sensor_config["protocol"],  # Modbus, IO-Link, EtherCAT
            "sample_rate_hz": sensor_config["sample_rate"],
            "edge_processing": sensor_config.get("edge_algo", "none"),
            "publish_topic": f"cpps/{sensor_config['equipment']}/{sensor_config['id']}",
        }

    def create_weld_monitoring_setup(self, robot_id: str) -> list:
        """Configure sensor suite for adaptive welding CPPS."""
        return [
            {"id": f"{robot_id}_current", "type": "weld_current_sensor", "sample_rate": 10000, "protocol": "EtherCAT"},
            {"id": f"{robot_id}_voltage", "type": "weld_voltage_sensor", "sample_rate": 10000, "protocol": "EtherCAT"},
            {"id": f"{robot_id}_force", "type": "electrode_force", "sample_rate": 1000, "protocol": "IO-Link"},
            {"id": f"{robot_id}_thermal", "type": "IR_pyrometer", "sample_rate": 100, "protocol": "Modbus"},
            {"id": f"{robot_id}_acoustic", "type": "acoustic_emission", "sample_rate": 50000, "protocol": "EtherCAT"},
        ]
```

### Step 2: Edge Computing Layer

```python
# Edge node for real-time process optimization
class EdgeProcessingNode:
    def __init__(self, node_id: str, ml_model_path: str):
        self.id = node_id
        self.model = self.load_model(ml_model_path)
        self.buffer = []

    def process_weld_data(self, sensor_data: dict) -> dict:
        """Real-time weld quality prediction and parameter adjustment."""
        features = self.extract_features(sensor_data)
        prediction = self.model.predict(features)
        if prediction["quality_score"] < 0.90:
            adjustment = self.calculate_adjustment(features, prediction)
            return {
                "action": "adjust_parameters",
                "current_offset_a": adjustment["current"],
                "time_offset_ms": adjustment["time"],
                "force_offset_n": adjustment["force"],
                "confidence": prediction["confidence"],
            }
        return {"action": "continue", "quality_score": prediction["quality_score"]}

    def extract_features(self, data: dict) -> list:
        """Extract ML features from raw sensor streams."""
        return [
            data["current_rms"],
            data["voltage_rms"],
            data["dynamic_resistance_slope"],
            data["electrode_force_avg"],
            data["thermal_peak_c"],
            data["acoustic_energy"],
        ]
```

### Step 3: OPC UA Information Model

```yaml
opcua_information_model:
  server: "opc.tcp://edge-node-01:4840"
  namespace: "urn:factory01:cpps:welding"
  nodes:
    welding_cell_01:
      type: WeldingCellType
      children:
        robot:
          type: RobotType
          variables:
            - joint_positions: {type: Float[], access: ReadOnly}
            - program_name: {type: String, access: ReadOnly}
            - cycle_count: {type: UInt64, access: ReadOnly}
        weld_controller:
          type: WeldControllerType
          variables:
            - current_setpoint_a: {type: Float, access: ReadWrite}
            - time_setpoint_ms: {type: Float, access: ReadWrite}
            - force_setpoint_n: {type: Float, access: ReadWrite}
            - quality_score: {type: Float, access: ReadOnly}
        methods:
          - optimize_parameters: {input: [material_batch], output: [recommended_params]}
          - start_cycle: {input: [program_id], output: [status]}
```

### Step 4: Autonomous Optimization Loop

```
Cyber-Physical Control Loop:
============================
Physical World:  Sensors measure process (current, force, temperature)
     |
Edge Layer:      ML model predicts quality from features (<10ms)
     |
Decision:        Compare prediction to target quality threshold
     |
Actuation:       Adjust process parameters for next cycle
     |
Validation:      Post-process measurement confirms improvement
     |
Learning:        Update ML model with new labeled data point
```

### Step 5: Production System Self-Configuration

```python
# Self-configuring production cell
class SelfConfiguringCell:
    def __init__(self, cell_id: str, capability_registry):
        self.id = cell_id
        self.registry = capability_registry

    def reconfigure_for_variant(self, vehicle_variant: str) -> dict:
        """Autonomously reconfigure cell for next vehicle variant."""
        required_capabilities = self.registry.get_requirements(vehicle_variant)
        current_capabilities = self.get_current_setup()
        changes_needed = self.diff_capabilities(required_capabilities, current_capabilities)
        actions = []
        for change in changes_needed:
            if change["type"] == "tool_change":
                actions.append(self.execute_tool_change(change["tool_id"]))
            elif change["type"] == "parameter_set":
                actions.append(self.load_parameter_set(change["param_id"]))
            elif change["type"] == "fixture_adjust":
                actions.append(self.adjust_fixture(change["position"]))
        return {"variant": vehicle_variant, "changes": len(actions), "time_s": sum(a["time_s"] for a in actions)}
```


## Best Practices

- Start with one control loop (e.g., weld quality) and prove value before scaling
- Use OPC UA as the standard communication layer -- avoid proprietary protocols
- Deploy edge computing for latency-critical loops, cloud for analytics and training
- Implement IEC 62443 security zones and conduits for CPPS network architecture
- Version ML models deployed at edge and enable rollback if performance degrades
- Maintain deterministic PLC control for safety functions -- ML advises, PLC decides
- Log all autonomous parameter changes for traceability and audit
- Design for graceful degradation: system must produce safely if CPPS layer fails


## Common Patterns

### CPPS Maturity Levels

```
Level 1: Connectivity    (sensors connected, data collected)
Level 2: Visibility      (dashboards showing real-time status)
Level 3: Transparency    (analytics explaining why events occur)
Level 4: Predictability  (ML models forecasting future states)
Level 5: Adaptability    (autonomous optimization closed-loop)
```

### Edge-Cloud Hierarchy

```
Sensor        Edge Node       Plant Server      Cloud
(microsec)    (millisec)      (seconds)         (minutes)
Raw data  --> Feature     --> Aggregation   --> Model training
              extraction      dashboards        fleet analytics
              ML inference    MES integration   long-term storage
              safety logic    quality records   benchmarking
```


## Troubleshooting

- **ML model makes poor adjustments**: Check for data drift, retrain with recent production data
- **OPC UA communication timeout**: Verify network bandwidth, reduce subscription interval
- **Edge node CPU overload**: Optimize model inference, reduce sensor sample rate
- **Cybersecurity alert from CPPS network**: Isolate affected zone, check IEC 62443 conduits
- **Autonomous parameter change causes quality issue**: Implement tighter change bounds, add human approval for large adjustments
- **Digital twin desynchronization**: Check OPC UA connection, verify sensor calibration

### digital-factory-twin

## Core Competencies

Expert in digital factory twin development using physics-based simulation, real-time data integration, and AI-powered optimization for automotive manufacturing facilities.

### Digital Twin Architecture

- **Geometric Model**: CAD-based factory layout with equipment placement and dimensions
- **Process Model**: Production workflows, cycle times, resource allocation, buffer sizes
- **Physical Model**: Energy consumption, thermal behavior, vibration, acoustics
- **Behavioral Model**: Machine states, failure modes, maintenance schedules, quality metrics
- **Data Model**: Real-time sensor feeds (OPC UA, MQTT), MES integration, historian databases

### Real-Time Synchronization

- **Edge computing**: On-premises data processing with <100ms latency
- **OPC UA PubSub**: Machine-to-twin communication protocol for industrial IoT
- **Time-series databases**: InfluxDB, TimescaleDB for high-frequency sensor data
- **State estimation**: Kalman filtering for sensor fusion and noise reduction
- **Digital thread**: End-to-end traceability from design (PLM) to production (MES) to field (IoT)

### Simulation Engines

- **Discrete Event Simulation (DES)**: Simio, AnyLogic, FlexSim for material flow
- **Multi-body dynamics**: Simulate robotic motion, conveyor dynamics, part handling
- **CFD (Computational Fluid Dynamics)**: Airflow in paint booths, HVAC optimization
- **FEA (Finite Element Analysis)**: Structural analysis of jigs, fixtures, tooling
- **Physics engines**: NVIDIA PhysX, Bullet for collision detection and rigid body dynamics

### Layout Optimization

- **Space utilization**: Minimize factory footprint while maximizing throughput
- **Material flow analysis**: Spaghetti diagrams, from-to charts, distance matrices
- **Ergonomic assessment**: Reach zones, worker fatigue, manual handling risk
- **AGV path planning**: Obstacle-free routing, traffic management, charging station placement
- **Safety zones**: ISO 13849 compliant safety distances, emergency egress paths

### Production Optimization

- **Line balancing**: Distribute workload across stations to minimize idle time
- **Takt time alignment**: Synchronize production rate with customer demand
- **Buffer sizing**: Optimize WIP inventory to decouple variability
- **Batch size optimization**: Balance setup time vs inventory holding cost
- **Changeover reduction**: SMED (Single Minute Exchange of Die) simulation

## Approach

1. **Data Collection**: Gather CAD layouts, process documentation, sensor inventories
2. **Model Building**: Create 3D factory model with equipment, conveyors, robots, AGVs
3. **Process Mapping**: Define production sequences, cycle times, failure distributions
4. **Data Integration**: Connect to MES, SCADA, PLCs via OPC UA for real-time feeds
5. **Validation**: Compare twin predictions vs actual production (throughput, WIP, OEE)
6. **Optimization**: Run what-if scenarios (new equipment, layout changes, demand spikes)
7. **Deployment**: Publish twin to cloud/edge platform for stakeholder access
8. **Continuous Update**: Auto-calibrate model parameters from production deviations

## Deliverables

- 3D virtual factory model with real-time machine states and material flow
- Production simulation results (throughput, cycle time, bottleneck analysis)
- Layout optimization recommendations (space savings, distance reduction)
- Energy consumption forecasts and optimization opportunities
- Predictive maintenance alerts based on twin-detected anomalies
- Virtual commissioning reports for new equipment integration
- ROI analysis for capital investments and process improvements

## Best Practices

- Start with one production line (pilot) before scaling to entire factory
- Validate cycle times and failure rates against 6 months of historical data
- Use Level-of-Detail (LOD) models: high fidelity for bottlenecks, simplified for non-critical
- Implement role-based access: operators see dashboards, engineers see detailed simulation
- Version control twin models alongside factory change management processes
- Integrate with PLM for design-to-manufacturing collaboration

## Integration with Automotive Workflow

- Connect to AUTOSAR-based manufacturing execution systems
- Interface with body shop, paint shop, assembly line twins for end-to-end visibility
- Provide production capacity data to supply chain planning systems
- Support new vehicle platform launches with virtual line configuration
- Enable remote factory monitoring for multi-site OEMs and Tier-1 suppliers

### digital-thread-traceability

## Core Competencies

Expert in digital thread implementation for automotive manufacturing with deep knowledge of PLM-MES-ERP integration, serialization, genealogy tracking, and blockchain-based traceability.

### Digital Thread Architecture

- **PLM (Product Lifecycle Management)**: Engineering BOM, CAD data, specifications (Teamcenter, Windchill)
- **MES (Manufacturing Execution System)**: As-built BOM, process parameters, quality data
- **ERP (Enterprise Resource Planning)**: Supplier lots, inventory, shipping (SAP, Oracle)
- **QMS (Quality Management System)**: Nonconformances, CAPA, customer complaints
- **Field telemetry**: Vehicle usage data, fault codes, OTA update history

### Serialization Strategies

- **VIN (Vehicle Identification Number)**: Top-level unique identifier (17 characters, ISO 3779)
- **Component serial numbers**: Engine, transmission, battery pack, ECUs (ESN, BCN, etc.)
- **Material lot numbers**: Castings, stampings, raw materials from suppliers
- **Work order numbers**: Link production batch to schedule and shift
- **Barcode/RFID**: Automatic capture at each production step

### Genealogy Data Model

- **Parent-child relationships**: VIN → battery pack SN → module SN → cell lot number
- **Process history**: Each operation records timestamp, operator, equipment, parameters
- **Material consumed**: Track which supplier lot was used for which VIN range
- **Quality events**: Link defects to specific manufacturing conditions (temperature, pressure, etc.)
- **Graph database**: Neo4j or similar to represent complex traceability networks

### Data Capture Methods

- **Barcode scanning**: 1D (Code 128) and 2D (Data Matrix, QR) at workstations
- **RFID tags**: UHF passive tags on pallets, bins, major components
- **Vision systems**: OCR to read stamped serial numbers, verify label accuracy
- **PLC integration**: Automatic logging of process parameters (torque, temperature, cycle time)
- **Operator input**: Manual data entry for non-automatable steps (touch screens, tablets)

### Traceability Use Cases

- **Recalls**: Identify all vehicles containing affected supplier lot (forward trace)
- **Root cause analysis**: Trace back from field failure to specific manufacturing conditions
- **Supplier quality**: Correlate defects to incoming material lots, drive SCAR (Supplier Corrective Action)
- **Warranty containment**: Limit warranty exposure by identifying affected production period
- **Regulatory compliance**: Demonstrate traceability per IATF 16949, FDA (medical devices)

### Blockchain Integration

- **Immutable ledger**: Cryptographic proof of manufacturing events (no tampering)
- **Multi-party trust**: OEMs, Tier-1/2/3 suppliers share traceability data without central authority
- **Smart contracts**: Automated quality gates (e.g., no assembly until supplier cert uploaded)
- **Platforms**: Hyperledger Fabric, Ethereum (private chains for automotive consortia)

## Approach

1. **Scope Definition**: Identify critical components requiring serialization (battery, ECUs, VIN)
2. **Data Model Design**: Define parent-child relationships, process checkpoints, quality gates
3. **System Integration**: Connect PLM, MES, ERP, QMS with standardized APIs (OData, REST)
4. **Hardware Deployment**: Install barcode scanners, RFID readers, vision systems at stations
5. **Workflow Configuration**: Define data capture rules (automatic vs manual, mandatory fields)
6. **Validation**: Test traceability queries (forward, backward, lateral) with pilot VINs
7. **Training**: Operators on scanning procedures, engineers on traceability reports
8. **Continuous Monitoring**: Audit data quality (missing scans, incorrect serial numbers)

## Deliverables

- Traceability data model with genealogy relationships and key attributes
- Integration architecture diagram (PLM-MES-ERP-QMS data flows)
- Barcode/RFID deployment plan with station-by-station requirements
- Traceability reports (forward trace, backward trace, genealogy tree)
- Data quality dashboard (scan compliance, duplicate serials, orphan records)
- Recall simulation test results (time to identify affected VINs)
- Training materials for operators and quality engineers

## Best Practices

- Implement serialization at earliest possible stage (casting, forging, PCB assembly)
- Use global unique identifiers (GUID) to avoid collisions across plants
- Validate serial number uniqueness in real-time to prevent duplicates
- Capture process parameters at critical control points (per IATF control plan)
- Implement data retention policies (10+ years for automotive traceability)
- Test backward and forward traceability weekly with random samples
- Automate data capture wherever possible to minimize operator error

## Integration with Automotive Workflow

- Synchronize PLM engineering BOM with MES as-planned BOM before production
- Trigger ERP material consumption backflushing from MES component scans
- Feed field fault data back to MES for correlation with manufacturing conditions
- Support customer-specific requirements (GM, Ford, VW traceability standards)
- Enable supplier portal for uploading material certs and test results

### edge-ai-manufacturing

## Core Competencies

Expert in edge AI deployment for automotive manufacturing with expertise in model optimization, edge hardware selection, MLOps for production environments, and real-time inference integration.

### Edge AI Hardware

- **NVIDIA Jetson**: AGX Orin (275 TOPS), Xavier NX (21 TOPS), Nano (472 GFLOPS) for vision
- **Intel Movidius**: VPU for low-power vision inference (Myriad X 4 TOPS)
- **Google Coral**: TPU edge accelerator (4 TOPS INT8) with dev board or USB
- **Industrial PCs**: Advantech, Beckhoff with NVIDIA GPU (RTX A4000) for multi-camera
- **Embedded FPGAs**: Xilinx Kria for ultra-low latency custom AI accelerators

### Model Optimization

- **Quantization**: FP32 → INT8 (4× smaller, 4× faster, <1% accuracy loss)
- **Pruning**: Remove low-weight connections to reduce model size by 50-90%
- **Knowledge distillation**: Train small student model from large teacher model
- **TensorRT**: NVIDIA optimization framework for inference (2-5× speedup)
- **ONNX Runtime**: Cross-platform optimized inference engine

### Deployment Frameworks

- **TensorFlow Lite**: Mobile/edge inference runtime for TF models
- **PyTorch Mobile**: Export and deploy PyTorch models to edge devices
- **OpenVINO**: Intel toolkit for CPU/GPU/VPU optimization
- **NVIDIA Triton**: Inference server for multi-model deployment and A/B testing
- **Azure IoT Edge**: Containerized modules with cloud orchestration

### Real-Time Applications

- **Vision inspection**: Run YOLOv8 at 30+ FPS for defect detection on Jetson AGX
- **Anomaly detection**: Autoencoder on vibration data with <10ms inference time
- **Predictive maintenance**: LSTM for remaining useful life prediction updated every minute
- **Adaptive control**: Reinforcement learning for process parameter optimization (welding, painting)
- **Quality prediction**: Regression model predicting final quality from in-process sensors

### Edge MLOps

- **Model versioning**: Track model weights, hyperparameters, training data provenance
- **Over-the-air updates**: Deploy new models to edge devices with rollback capability
- **A/B testing**: Run multiple model versions and compare performance metrics
- **Monitoring**: Track inference latency, accuracy drift, hardware utilization
- **Retraining pipeline**: Collect edge cases, retrain in cloud, redeploy to edge

### Data Collection at Edge

- **Selective logging**: Store only anomalies and edge cases for retraining (data efficiency)
- **Privacy**: Keep sensitive data on-premises, send only aggregated metrics to cloud
- **Bandwidth**: Reduce cloud upload by 100× with edge filtering and summarization
- **Latency**: Enable real-time decisions without round-trip to cloud (critical for safety)

## Approach

1. **Use Case Definition**: Identify high-value application (quality, safety, cost reduction)
2. **Model Development**: Train model in cloud with representative dataset (>1000 samples)
3. **Optimization**: Quantize to INT8, prune, validate accuracy degradation <1%
4. **Hardware Selection**: Match edge device to inference requirements (FPS, latency, power)
5. **Integration**: Connect edge device to PLC, vision cameras, sensors via Ethernet/GPIO
6. **Deployment**: Containerize model with Docker, deploy via IoT Edge or Kubernetes
7. **Monitoring**: Track KPIs (false positives, latency, uptime), collect failure cases
8. **Continuous Improvement**: Retrain monthly with new edge data, A/B test before full rollout

## Deliverables

- Edge AI hardware specification (device, accelerator, I/O interfaces)
- Optimized model (quantized, pruned) with benchmark results (latency, accuracy, FPS)
- Deployment container (Docker) with inference server and preprocessing pipeline
- Integration documentation (PLC communication, camera triggering, result logging)
- Monitoring dashboard (inference latency, model accuracy, device health)
- Retraining pipeline documentation with data collection and versioning process
- Cost-benefit analysis (cloud cost savings, quality improvement, downtime reduction)

## Best Practices

- Always benchmark on target edge hardware before deployment (cloud ≠ edge performance)
- Implement fallback logic when model confidence is low (manual review queue)
- Use hardware watchdog timers to recover from edge device crashes
- Collect diverse training data (all lighting conditions, part variations, defect types)
- Monitor model accuracy drift over time (production data may differ from training)
- Separate inference network from factory IT network (cybersecurity isolation)
- Test edge device under temperature extremes (0-50°C typical in factory)

## Integration with Automotive Workflow

- Interface with MES to log quality predictions and trigger work orders for rework
- Connect to SCADA for real-time visualization of AI model outputs
- Provide feedback to digital twin for process optimization
- Support IATF 16949 quality requirements with AI-augmented inspection records
- Enable predictive maintenance to reduce unplanned downtime by 30-50%

### final-assembly-line

## Core Competencies
Expert in automotive final assembly process design with deep knowledge of ergonomic workstation layout, powered tool control, fluid filling automation, and quality verification systems.
### Assembly Sequence
- **Underbody assembly**: Suspension, fuel tank, exhaust (or battery for EVs), brake lines - **Marriage (body drop)**: Unite body-in-white with powertrain/chassis or skateboard platform - **Cockpit module**: Install IP carrier (HVAC, wiring, airbag, infotainment) as pre-assembled module - **Closure panels**: Doors, hood, liftgate with gap/flush verification - **Interior trim**: Seats, carpets, headliner, console (often JIS delivery) - **Wheels and tires**: Torque to spec (120-140 Nm typical), torque audit verification - **Fluids**: Engine oil, coolant, brake fluid, washer fluid, fuel - **Final inspection**: Gap/flush, paint, function tests, roll test
### Marriage Station
- **Body positioning**: Overhead conveyor lowers body onto chassis with ±5mm precision - **Alignment**: Vision-guided positioning, mechanical locating pins for repeatability - **Fastening**: Automated or manual body bolts (20-30 fasteners, torque + angle tightening) - **EV skateboard**: Battery-chassis unit mates to upper body (structural CTC integration) - **Cycle time**: 60-120 seconds typical (critical takt bottleneck)
### Torque Tool Strategy
- **Tightening methods**: Torque control, angle control, torque-to-yield, ultrasonic - **Tool types**: DC electric (Desoutter, Atlas Copco), pulse (lower reaction force) - **Critical fasteners**: 100% traceability (VIN, joint ID, torque, angle, timestamp) - **Error-proofing**: Barcode verify correct tool for joint, lockout on failure - **Torque audit**: Statistically sample tightened fasteners with torque wrench (Cpk >1.67)
### Fluid Fill Automation
- **Gravimetric filling**: Load cells measure exact quantity (±20g for 5L fill) - **Volumetric filling**: Flow meters with temperature compensation - **Closed-loop systems**: Capture vapors (fuel, coolant) for environmental compliance - **Error detection**: Verify cap installation, no spills, correct fluid type (RFID tags) - **Traceability**: Log fluid lot number, quantity, VIN for warranty analysis
### End-of-Line Testing (EOBT)
- **Electrical test**: Battery voltage, alternator output, all lights, wipers, HVAC - **Brake test**: Pedal force vs deceleration on roll dynamometer - **Headlamp alignment**: Automated aim using vision system or beam setter - **Wheel alignment**: Toe, camber, caster measurement and adjustment - **Road test**: Noise, vibration, harshness (NVH), function validation (1-2 km track) - **Leak test**: Spray test for water leaks (windows, seals, sunroof)
### Quality Gates
- **Gate 1 (Underbody)**: Suspension torque audit, brake line leak test - **Gate 2 (Marriage)**: Body-to-chassis fastener verification, alignment check - **Gate 3 (Cockpit)**: Electrical connector verification (all clicked), airbag resistance - **Gate 4 (Closure)**: Gap/flush measurement, door function, latch engagement - **Gate 5 (EOBT)**: Roll test pass/fail, headlamp aim, final inspection sign-off
## Approach
1. **Line Balancing**: Distribute tasks across stations to match takt time (90 sec typical) 2. **Workstation Design**: Ergonomic height, part presentation, tool accessibility per MTM 3. **Tool Selection**: Match torque range, error-proofing level, traceability to critical joints 4. **JIS Integration**: Coordinate with suppliers for sequenced part delivery (seats, cockpits) 5. **Andon System**: Pull cords, buttons, auto-stop on quality failures with escalation 6. **Pilot Build**: Validate assembly sequence, identify fit issues, refine work instructions 7. **Operator Training**: Hands-on practice, quality awareness, error-proofing understanding 8. **Ramp-Up**: Gradual speed increase with quality checks at each takt increment
## Deliverables
- Assembly line layout with workstation assignments and takt time analysis - Powered tool specifications (torque range, tightening strategy, error-proofing) - Fluid fill system design (equipment, quantities, traceability) - EOBT station equipment list (roll test, headlamp aim, leak test booth) - Quality control plan with inspection points and reaction plans - Standard work documentation with visual work instructions - Operator training materials and competency assessment
## Best Practices
- Design for assembly (DFA): minimize fastener count, use snap-fits where possible - Implement poka-yoke: connectors unique shape, sensors verify presence before next step - Use torque tool controllers with I4.0 connectivity (OPC UA to MES for traceability) - Pre-assemble modules off-line (cockpit, front-end) to simplify main line work - Monitor first-time-quality (FTQ): track defects by station to focus kaizen - Provide adjustable lift tables and tool balancers for ergonomic posture - Implement andon with tier response times (1 min team leader, 5 min engineer)
## Integration with Automotive Workflow
- Interface with body shop and paint shop for arrival sequence and quality handoff - Coordinate with logistics for just-in-sequence (JIS) part delivery from suppliers - Connect torque tools to MES for real-time traceability and SPC monitoring - Provide EOBT data to warranty analysis system for early failure detection - Support new model introduction (NMI) with flexible tooling and mixed-model capability

### green-steel-processing

# Green Steel Processing for Automotive

## Overview
Steel constitutes 50-60 percent of vehicle mass and 20-30 percent of vehicle
manufacturing carbon footprint at Scope 3. Green steel replaces coal-based blast
furnace reduction with hydrogen direct reduction or maximizes recycled scrap through
electric arc furnaces powered by renewable electricity. This transition is critical
for OEMs targeting net-zero supply chains while maintaining demanding mechanical
property specifications for crash-critical body structures.

## Key Concepts

### Steel Production Routes Compared
Three primary production routes exist with dramatically different carbon intensities:

- Conventional BF-BOF: Iron ore plus coal coke in blast furnace at 1500C, producing
  1.8-2.2 tonnes CO2 per tonne of steel
- Scrap-EAF with renewables: Sorted steel scrap in electric arc furnace powered by
  green electricity, producing 0.1-0.3 tonnes CO2 per tonne
- Hydrogen DRI plus EAF: Iron ore reduced by hydrogen gas in shaft furnace at 900C
  then melted in EAF, producing 0.05-0.2 tonnes CO2 per tonne

### Automotive Steel Grades
Key grades used in vehicle body structures:

- Mild steel DC01-DC06: Outer panels with 140-300 MPa yield strength
- HSLA HC340-HC460: Structural reinforcements at 340-460 MPa
- Dual Phase DP500-DP1000: Crash structures at 500-1000 MPa tensile
- Press Hardened PHS 22MnB5: A and B pillars at 1500-2000 MPa after hot stamping

## Implementation Guide

### Step 1 - Scope 3 Steel Carbon Footprint Assessment
Calculate the total steel-related carbon footprint for a vehicle program.

```python
class SteelCarbonCalculator:
    ROUTE_FACTORS = {
        "BF-BOF": 2.0,
        "BF-BOF-CCS": 1.0,
        "Scrap-EAF-grid": 0.5,
        "Scrap-EAF-renewable": 0.2,
        "H-DRI-EAF-green": 0.1,
    }

    def calculate_vehicle_steel_footprint(self, bom: list) -> dict:
        """Calculate total steel carbon footprint for a vehicle BOM."""
        total_co2_kg = 0.0
        breakdown = []
        for part in bom:
            if part["material_family"] != "steel":
                continue
            route = part.get("production_route", "BF-BOF")
            co2_kg = part["weight_kg"] * self.ROUTE_FACTORS[route]
            total_co2_kg += co2_kg
            breakdown.append({
                "part": part["name"],
                "weight_kg": part["weight_kg"],
                "grade": part["grade"],
                "route": route,
                "co2_kg": round(co2_kg, 1),
            })
        total_weight = sum(p["weight_kg"] for p in breakdown)
        return {
            "total_steel_weight_kg": total_weight,
            "total_co2_kg": round(total_co2_kg, 1),
            "avg_intensity": round(total_co2_kg / max(1, total_weight), 3),
            "breakdown": breakdown,
        }
```

### Step 2 - Green Steel Supplier Qualification
Qualify green steel grades against full automotive mechanical specifications.

```python
class GreenSteelQualification:
    REQUIRED_TESTS = [
        "tensile_properties",
        "chemical_composition",
        "surface_roughness",
        "coating_weight",
        "formability_erichsen",
        "bake_hardening_bh2",
        "weldability_spot_weld_range",
        "crash_test_component_level",
    ]

    def run_qualification(self, supplier_samples: dict) -> dict:
        """Qualify green steel against automotive specification."""
        results = {}
        for test in self.REQUIRED_TESTS:
            measured = supplier_samples[test]
            spec = self._get_specification(test, supplier_samples["grade"])
            results[test] = {
                "measured": measured,
                "specification": spec,
                "pass": spec["min"] <= measured["value"] <= spec["max"],
            }
        all_passed = all(r["pass"] for r in results.values())
        return {
            "supplier": supplier_samples["supplier"],
            "grade": supplier_samples["grade"],
            "co2_intensity": supplier_samples["co2_t_per_t"],
            "status": "approved" if all_passed else "conditional",
            "test_results": results,
        }
```

### Step 3 - CBAM Impact Analysis
Calculate carbon border adjustment costs for steel imports into the EU.

```
CBAM Calculation:
  Charge = (embedded emissions - free allocation) x EU ETS carbon price

Example comparison at EUR 80 per tonne CO2:
  BF-BOF steel from Turkey: 2.0 t CO2/t x EUR 80 = EUR 160/t surcharge
  H-DRI steel from Sweden:  0.1 t CO2/t x EUR 80 = EUR 8/t surcharge
  Delta: EUR 152/t making green steel cost-competitive under CBAM
```

### Step 4 - Green Steel Adoption Roadmap
Phase the transition starting with less critical parts and advancing to crash
structures as qualification and supply capacity mature:

```
Phase 1 (2024-2025): 10% green steel in non-structural applications
Phase 2 (2026-2027): 30% green steel with structural parts qualified
Phase 3 (2028-2030): 60% green steel including crash-critical parts
Phase 4 (2030+):     100% green steel across full vehicle BOM
```

## Best Practices
- Engage with steelmakers early as green steel capacity is constrained through 2030
- Sign long-term offtake agreements of 5-10 years to secure supply
- Require ResponsibleSteel certification or equivalent third-party verification
- Test every new green steel heat against full automotive specification before approval
- Monitor hydrogen DRI steel for different residual element profiles versus conventional
- Account for CBAM when comparing sourcing options for EU-destined vehicles
- Start transition with brackets and reinforcements then advance to crash parts
- Track green steel premium cost versus carbon credit value for business case

## Troubleshooting
- Green steel surface quality differs from conventional: Adjust pickling and skin
  pass parameters to account for different oxide scale characteristics
- Weldability variation with H-DRI steel: Check residual copper and tin levels that
  may differ from blast furnace route due to scrap mix in EAF
- Limited availability of green press-hardened grades: Collaborate directly with
  steelmaker on development timeline and share qualification requirements early
- Cost premium makes business case difficult: Include CBAM savings, carbon credit
  value, and customer willingness-to-pay for sustainability in total cost analysis
- Chain of custody verification is complex: Accept mass balance approach with annual
  third-party audit rather than requiring physical segregation
- Forming simulation parameters need updating: Run new forming limit curves and
  bake hardening response tests for each green steel heat

### human-robot-collaboration

## Overview

Human-robot collaboration (HRC) enables automotive assembly operations where humans and robots
work in shared workspaces without traditional safety fencing. This skill covers the complete
lifecycle from risk assessment and cobot selection through cell design, safety validation,
and continuous performance optimization.

Industry 5.0 HRC goes beyond simple cobot deployment -- it designs truly collaborative workflows
where human cognitive skills (judgment, dexterity, adaptation) complement robot strengths
(precision, repeatability, force control) to exceed what either achieves alone.


## Key Concepts

### Collaborative Operation Modes (ISO/TS 15066)

- **Safety-Rated Monitored Stop (SMS)**: Robot stops when human enters collaborative zone
- **Hand Guiding (HG)**: Operator physically guides robot through teach or assist mode
- **Speed and Separation Monitoring (SSM)**: Robot slows/stops based on proximity to human
- **Power and Force Limiting (PFL)**: Robot limits contact force below injury thresholds

### Biomechanical Force Limits (ISO/TS 15066 Annex A)

- **Hand/Finger**: Max 140 N transient, 65 N quasi-static contact
- **Forearm**: Max 160 N transient, 110 N quasi-static contact
- **Upper arm/Shoulder**: Max 210 N transient, 150 N quasi-static contact
- **Chest**: Max 280 N transient, 140 N quasi-static contact
- **Head/Forehead**: Max 130 N transient, 65 N quasi-static contact

### Cobot Payload Classes for Automotive

- **Light (3-5 kg)**: Screw driving, small part placement, adhesive dispensing
- **Medium (10-16 kg)**: Component handling, sealant application, sensor installation
- **Heavy (20-35 kg)**: Seat installation, wheel mounting, battery module handling


## Implementation Guide

### Step 1: Task Analysis and Allocation

```python
# Human-robot task allocation scoring
class TaskAllocator:
    HUMAN_STRENGTHS = ["judgment", "dexterity", "adaptation", "inspection"]
    ROBOT_STRENGTHS = ["precision", "repeatability", "force", "endurance"]

    def score_task(self, task: dict) -> dict:
        """Score task suitability for human, robot, or collaborative execution."""
        human_score = sum(task.get(s, 0) for s in self.HUMAN_STRENGTHS)
        robot_score = sum(task.get(s, 0) for s in self.ROBOT_STRENGTHS)
        ratio = human_score / max(robot_score, 1)
        if ratio > 2.0:
            allocation = "human_only"
        elif ratio < 0.5:
            allocation = "robot_only"
        else:
            allocation = "collaborative"
        return {
            "task": task["name"],
            "allocation": allocation,
            "human_score": human_score,
            "robot_score": robot_score,
        }
```

### Step 2: Risk Assessment (ISO 12100)

```yaml
risk_assessment:
  hazard_identification:
    - contact_with_robot_arm
    - contact_with_workpiece
    - contact_with_tool_end_effector
    - clamping_between_robot_and_fixture
    - unexpected_robot_restart
  severity_levels:
    S1: minor_reversible_injury
    S2: serious_irreversible_injury
  probability_levels:
    P1: rare_exposure
    P2: frequent_exposure
  required_performance_level:
    collaborative_zone: PLd  # minimum for HRC applications
    emergency_stop: PLe
```

### Step 3: Cell Layout Design

```
+--------------------------------------------------+
|  Material     |  Collaborative Zone   | Finished  |
|  Staging      |  (No fencing)         | Parts     |
|               |                       | Buffer    |
|  [Parts Rack] |  [Cobot]  [Operator]  | [Rack]    |
|               |   F/T     Workbench   |           |
|               |  Sensor               |           |
|  Safety       |  [3D Safety Camera]   | Quality   |
|  Scanner      |                       | Check     |
+--------------------------------------------------+
     Entry/Exit with light curtain
```

### Step 4: Force/Torque Control Programming

```python
# Cobot force-controlled insertion example
class ForceControlledAssembly:
    def __init__(self, robot_controller, ft_sensor):
        self.robot = robot_controller
        self.ft = ft_sensor

    def windshield_placement(self, target_pose: list, max_force_n: float = 50.0):
        """Force-controlled windshield insertion with compliance."""
        self.robot.set_force_mode(
            frame=target_pose,
            selection_vector=[0, 0, 1, 0, 0, 0],  # compliant in Z
            wrench=[0, 0, -30, 0, 0, 0],  # 30N push force
            limits=[0.01, 0.01, 0.05, 0.05, 0.05, 0.05],
        )
        while self.ft.get_force_z() < max_force_n:
            if self.ft.get_force_z() > max_force_n * 0.8:
                self.robot.reduce_speed(factor=0.3)
        self.robot.end_force_mode()
        return self.verify_placement()
```

### Step 5: Safety System Integration

- Deploy 3D safety cameras (SICK, Pilz) for speed and separation monitoring
- Configure safety-rated soft axis limits in robot controller
- Implement safety PLC with PLd/PLe rated circuits for emergency stop
- Validate contact force with calibrated force measurement at all exposed surfaces


## Best Practices

- Always perform contact force measurement with body-region-specific test equipment
- Design end effectors with rounded edges and compliant covers (no pinch points)
- Use safety-rated 3D vision for dynamic speed scaling (not just light curtains)
- Involve operators in cell design from day one -- acceptance determines success
- Start with simple collaborative tasks and increase complexity incrementally
- Maintain minimum 250mm separation between robot path and operator head height
- Log all safety stop events and analyze for cell layout optimization
- Retrain operators quarterly on HRC safety procedures and emergency protocols


## Common Patterns

### Collaborative Assembly Sequence

1. Operator loads component onto fixture and signals ready (button or gesture)
2. Cobot approaches at reduced speed (SSM active, 250mm/s max)
3. Cobot positions component with force/torque control
4. Operator performs final quality check and confirms acceptance
5. Cobot retracts to home position; operator unloads finished assembly

### Safety System Architecture

```
3D Safety Cameras (x2, redundant)
     |
Safety PLC (Pilz PSS 4000 / Siemens F-CPU)
     |
+----+----+----+
|    |    |    |
STO  SLS  SLP  SSM
(Safe (Safe (Safe (Speed &
Torque Limited Limited Separation
Off)  Speed) Position) Monitoring)
```


## Troubleshooting

- **Frequent safety stops disrupting cycle time**: Optimize zone boundaries, adjust SSM thresholds
- **Force control oscillation during insertion**: Tune compliance gains, reduce approach speed
- **Operator fatigue despite cobot assist**: Review task allocation, check ergonomic scoring
- **Cobot TCP drift over time**: Calibrate tool center point weekly, check mounting bolts
- **Safety validation failure**: Re-measure contact forces after any end-effector change
- **Network latency in safety camera**: Use dedicated safety Ethernet, verify response time <50ms

### industrial-metaverse

## Overview

The industrial metaverse creates persistent, shared, physics-accurate 3D environments that
mirror real automotive factories. Unlike traditional CAD or simulation tools, metaverse
platforms enable multi-user collaboration, real-time data integration from IoT sensors,
and immersive interaction through VR/AR headsets or desktop clients.

For automotive manufacturing, this means engineers in Germany, operators in Mexico, and
suppliers in China can simultaneously walk through the same virtual factory, observe live
production data overlaid on 3D equipment models, and collaboratively solve problems in
context rather than through documents and video calls.


## Key Concepts

### Metaverse Technology Stack

- **3D Engine**: Real-time rendering (Unreal Engine, Unity, NVIDIA Omniverse)
- **Digital Twin Platform**: Physics simulation and IoT data integration
- **XR Devices**: VR headsets (Meta Quest Pro), AR glasses (Microsoft HoloLens 2, Magic Leap)
- **Collaboration Layer**: Multi-user session management, avatars, spatial audio
- **Data Integration**: OPC UA, MQTT, REST APIs connecting factory systems to virtual world
- **Spatial Computing**: Room-scale tracking, hand tracking, eye tracking

### Data Flow Architecture

```
Physical Factory              Industrial Metaverse
================              ====================
PLC/SCADA (OPC UA) --------> Real-time equipment state
MES (API) ------------------> Production KPIs overlay
IoT Sensors (MQTT) ---------> Environmental data (temp, vibration)
3D Scan (LiDAR) ------------> As-built geometry baseline
CAD/PLM (JT/STEP) ----------> Design intent models
ERP (SAP) ------------------> Material flow visualization
```

### Immersion Levels

- **Desktop 3D**: Lowest barrier, browser or application-based navigation
- **Tablet AR**: Overlay digital content on physical equipment via camera
- **Head-mounted AR**: Hands-free overlay with spatial anchoring (HoloLens)
- **Room-scale VR**: Full immersion for design reviews and training
- **CAVE/Powerwall**: Multi-person shared immersive viewing for management reviews


## Implementation Guide

### Step 1: Factory Digitization

Create the geometric and data foundation:

```python
# Factory digitization pipeline
class FactoryDigitizer:
    def __init__(self, lidar_scanner, cad_repository, iot_platform):
        self.scanner = lidar_scanner
        self.cad = cad_repository
        self.iot = iot_platform

    def create_baseline_scan(self, factory_zone: str) -> str:
        """Generate point cloud from LiDAR scan of physical factory."""
        point_cloud = self.scanner.scan_zone(factory_zone, resolution_mm=5)
        mesh = self.convert_to_mesh(point_cloud, decimation_ratio=0.1)
        return self.upload_to_metaverse(mesh, zone_id=factory_zone)

    def overlay_cad_models(self, zone_id: str, equipment_list: list):
        """Replace scan geometry with parametric CAD for interactive equipment."""
        for equipment in equipment_list:
            cad_model = self.cad.fetch_model(equipment["part_number"], format="USD")
            self.place_in_scene(zone_id, cad_model, equipment["transform"])

    def connect_live_data(self, zone_id: str, data_points: list):
        """Bind IoT sensor data to 3D model properties."""
        for point in data_points:
            self.iot.subscribe(point["topic"], callback=self.update_3d_property)
```

### Step 2: Multi-User Collaboration Setup

```yaml
collaboration_config:
  session_management:
    max_users_per_session: 50
    roles: [engineer, operator, manager, supplier, viewer]
    spatial_audio: true
    avatar_tracking: head_and_hands
  access_control:
    authentication: enterprise_sso
    authorization: role_based_per_zone
    data_classification: confidential_geometry_restricted
  network_requirements:
    min_bandwidth_mbps: 50
    max_latency_ms: 50
    protocol: WebRTC_with_TURN_fallback
```

### Step 3: Virtual Commissioning Workflow

```
Phase 1: Import       Phase 2: Simulate     Phase 3: Validate
===============       =================     =================
CAD geometry    -->   Physics engine    --> Cycle time check
Robot programs  -->   Motion planning   --> Collision detection
PLC logic       -->   Virtual PLC       --> Signal verification
Safety zones    -->   Zone simulation   --> Safety validation
Material flow   -->   Discrete event    --> Throughput analysis
```

### Step 4: AR-Assisted Maintenance

```python
# AR remote assistance session
class ARRemoteAssist:
    def __init__(self, ar_platform, knowledge_base):
        self.platform = ar_platform
        self.kb = knowledge_base

    def start_session(self, equipment_id: str, technician_device: str):
        """Launch AR session with contextual maintenance data."""
        equipment_twin = self.get_digital_twin(equipment_id)
        self.platform.create_session(
            device=technician_device,
            anchor=equipment_twin.spatial_anchor,
            overlays=[
                self.kb.get_maintenance_steps(equipment_id),
                equipment_twin.get_live_diagnostics(),
                equipment_twin.get_exploded_view(),
            ],
        )

    def enable_remote_expert(self, expert_id: str):
        """Allow remote expert to see technician view and annotate in 3D."""
        self.platform.add_participant(expert_id, role="annotator")
        self.platform.enable_spatial_annotations()
```


## Best Practices

- Start with high-value use cases: virtual commissioning saves 20-30% of physical commissioning time
- Use USD (Universal Scene Description) as the interchange format for 3D assets
- Maintain a single source of truth: CAD/PLM system feeds metaverse, never the reverse
- Design for the lowest common device -- desktop 3D first, then enhance for XR
- Implement data classification zones to protect proprietary geometry from supplier sessions
- Measure adoption with session analytics: time in environment, collaboration frequency
- Provide VR sickness mitigation: teleport locomotion, fixed horizon, short session limits
- Keep real-time data refresh below 1 second for operator-facing dashboards


## Common Patterns

### Factory Planning Review

1. Import updated layout from CAD into metaverse environment
2. Invite cross-functional team (production, logistics, safety, ergonomics)
3. Walk through factory floor at 1:1 scale in VR
4. Annotate issues with spatial markers (clearance, ergonomics, material flow)
5. Export annotations as action items linked to CAD coordinates

### Training Scenario Design

```
Scenario Template:
  Equipment: [robot cell / press line / paint booth]
  Objective: [normal operation / fault recovery / safety response]
  Trainee Actions: [step-by-step guided procedure]
  Assessment: [time to complete, error count, safety violations]
  Feedback: [real-time AR highlights, post-session replay]
```


## Troubleshooting

- **Low frame rate in VR**: Reduce polygon count, use LOD (level of detail) switching
- **Data synchronization lag**: Check MQTT broker capacity, use edge processing
- **Spatial anchor drift in AR**: Recalibrate with fixed QR markers on equipment
- **Multi-user desync**: Verify network latency <50ms, use server-authoritative state
- **CAD import failures**: Convert via neutral format (STEP/JT) before USD conversion
- **User adoption resistance**: Start with AR tablet (familiar), graduate to headset

### just-in-time-2

## Overview

JIT 2.0 evolves the Toyota Production System's just-in-time principles for the digital age.
While traditional JIT relies on physical Kanban cards and fixed reorder points, JIT 2.0
uses real-time demand signals from MES, AI-based consumption forecasting, and autonomous
material handling to achieve even tighter synchronization between supply and demand.

The COVID-19 pandemic and semiconductor shortages exposed JIT vulnerabilities, leading to
JIT 2.0's balanced approach: maintaining lean flow for commodity parts while building
strategic buffers for critical components, all orchestrated through digital platforms that
provide end-to-end visibility.


## Key Concepts

### JIT 2.0 vs Traditional JIT

```
Dimension         Traditional JIT        JIT 2.0
===========       ===============        =======
Signal            Physical Kanban        Digital demand sensing (MES + AI)
Sequencing        Fixed sequence board   AI-optimized dynamic sequencing
Transport         Manual milk runs       Autonomous AMR/tugger trains
Inventory         Minimize everything    Risk-stratified (lean + strategic buffer)
Visibility        Plant-level only       Multi-tier supply chain
Buffer logic      Fixed safety stock     Dynamic, ML-adjusted daily
Supplier link     EDI/fax call-offs      Real-time portal with consumption feed
```

### Material Flow Types

- **JIT**: Delivery to plant within hours of consumption (bulky: seats, bumpers, fuel tanks)
- **JIS (Just-in-Sequence)**: Delivered in exact vehicle build order (cockpits, axles, doors)
- **Kanban pull**: Replenish consumed quantity from supermarket (fasteners, clips, standard parts)
- **Kit delivery**: Pre-picked kits for each vehicle delivered to station (electrical, trim)
- **Ship-to-line**: Bypass warehouse, deliver directly to lineside point-of-use

### Demand Signal Architecture

```
Vehicle Build Schedule (MES)
     |
Sequence Planning (AI optimizer)
     |
+----+----+----+
|    |    |    |
JIS  JIT  Kanban Kit
Call Call  Pull   Pick
Off  Off   Signal Order
|    |    |      |
Supplier Portal / EDI / e-Kanban System
```


## Implementation Guide

### Step 1: Digital Demand Sensing

```python
# AI-powered demand signal generation
class DemandSensingEngine:
    def __init__(self, mes_connection, forecast_model):
        self.mes = mes_connection
        self.model = forecast_model

    def generate_signals(self, planning_horizon_hours: int = 8) -> list:
        """Generate material demand signals from production plan and consumption."""
        current_sequence = self.mes.get_build_sequence(horizon_hours=planning_horizon_hours)
        signals = []
        for vehicle in current_sequence:
            bom = self.mes.explode_bom(vehicle["model"], vehicle["options"])
            for part in bom:
                delivery_type = part["logistics_concept"]  # JIS, JIT, Kanban, Kit
                if delivery_type == "JIS":
                    signals.append(self.create_jis_signal(vehicle, part))
                elif delivery_type == "JIT":
                    signals.append(self.create_jit_signal(part, vehicle["planned_time"]))
                elif delivery_type == "Kanban":
                    if self.check_reorder_point(part):
                        signals.append(self.create_kanban_signal(part))
        return signals

    def create_jis_signal(self, vehicle: dict, part: dict) -> dict:
        """Create just-in-sequence call-off with exact build position."""
        return {
            "type": "JIS",
            "part_number": part["part_number"],
            "variant": part["variant_code"],
            "sequence_number": vehicle["sequence_number"],
            "delivery_window_start": vehicle["planned_time"] - part["lead_time_hours"] * 3600,
            "delivery_window_end": vehicle["planned_time"] - 0.5 * 3600,
            "delivery_point": part["lineside_location"],
        }
```

### Step 2: Dynamic Safety Stock Calculation

```python
# Risk-stratified inventory optimization
class DynamicSafetyStock:
    def calculate(self, part: dict) -> dict:
        """Calculate safety stock based on supply risk and demand variability."""
        demand_variability = part["demand_std_dev"] / part["demand_mean"]
        supply_risk_score = part["supply_risk_score"]  # 1-10 from risk engine
        lead_time_days = part["replenishment_lead_time_days"]

        # Base safety stock: standard statistical calculation
        service_level_z = 2.33  # 99% service level
        base_ss_days = service_level_z * demand_variability * (lead_time_days ** 0.5)

        # Risk multiplier: increase for high-risk components
        if supply_risk_score >= 8:
            risk_multiplier = 3.0  # semiconductors, single-source
        elif supply_risk_score >= 5:
            risk_multiplier = 1.5  # moderate risk
        else:
            risk_multiplier = 1.0  # low risk, pure lean

        adjusted_ss_days = base_ss_days * risk_multiplier
        return {
            "part_number": part["part_number"],
            "base_safety_stock_days": round(base_ss_days, 1),
            "risk_multiplier": risk_multiplier,
            "recommended_ss_days": round(adjusted_ss_days, 1),
            "inventory_cost_per_day": part["unit_cost"] * part["daily_demand"],
            "annual_carrying_cost": round(adjusted_ss_days * part["unit_cost"] * part["daily_demand"] * 0.20, 0),
        }
```

### Step 3: Autonomous Material Delivery

```yaml
autonomous_logistics:
  amr_milk_run:
    fleet_size: 15
    route_optimization: dynamic_based_on_consumption
    loading: automated_roller_conveyor_dock
    navigation: SLAM_with_fleet_coordination
    integration: MES_triggered_delivery_missions
  tugger_train:
    type: autonomous_lead_vehicle_with_carts
    capacity_kg: 2000
    route: fixed_with_dynamic_stop_selection
    replenishment: triggered_by_e_kanban_signal
  delivery_to_point_of_use:
    precision_m: 0.05
    handoff: operator_picks_from_AMR_shelf
    confirmation: pick_to_light_with_scan_verification
```

### Step 4: e-Kanban System

```python
# Electronic Kanban replacing physical cards
class EKanbanSystem:
    def __init__(self, mes, supplier_portal, amr_fleet):
        self.mes = mes
        self.portal = supplier_portal
        self.fleet = amr_fleet

    def process_consumption(self, scan_event: dict):
        """Process container consumption scan and trigger replenishment."""
        part = scan_event["part_number"]
        location = scan_event["lineside_location"]
        current_stock = self.get_lineside_stock(part, location)
        reorder_point = self.get_reorder_point(part)
        if current_stock <= reorder_point:
            # Internal replenishment from supermarket
            if self.supermarket_has_stock(part):
                self.fleet.dispatch_delivery(part, location)
            # External replenishment from supplier
            supermarket_stock = self.get_supermarket_stock(part)
            if supermarket_stock <= self.get_supplier_reorder_point(part):
                self.portal.send_call_off(part, quantity=self.get_order_quantity(part))
```


## Best Practices

- Classify parts by ABC-XYZ analysis before assigning logistics concepts
- Use JIS only for high-value, high-variant parts (seats, cockpits, painted bumpers)
- Maintain 2-4 hour lineside buffer for JIS parts to absorb sequence disruptions
- Run supplier integration pilot with top 5 volume suppliers before full rollout
- Monitor e-Kanban cycle time and flag anomalies indicating process breakdown
- Keep physical Kanban as fallback for system downtime (digital resilience)
- Audit supplier delivery performance weekly: on-time, in-sequence, quality
- Balance inventory reduction against production continuity risk for each part class


## Common Patterns

### Material Flow Design by Part Type

```
Part Type          Logistics Concept    Buffer      Signal
=========          =================    ======      ======
Seats              JIS                  2 hours     MES sequence
Bumpers (painted)  JIS                  3 hours     MES sequence
Wiring harness     JIT kit              4 hours     BOM explosion
Engine/Motor       JIT                  8 hours     Daily call-off
Fasteners/Clips    Kanban               2 days      e-Kanban scan
Fluids             Kanban               3 days      Level sensor
Semiconductors     Strategic buffer     8 weeks     Forecast + buffer
```

### Supplier Integration Levels

```
Level 1: EDI call-off (weekly forecast, daily firm orders)
Level 2: Supplier portal (real-time consumption visibility)
Level 3: VMI (vendor-managed inventory at consignment stock)
Level 4: Embedded supplier (on-site or adjacent, sequenced delivery)
```


## Troubleshooting

- **Line stops due to missing JIS parts**: Increase buffer window, improve sequence stability
- **e-Kanban signal delays**: Check network connectivity, add offline buffering
- **AMR congestion in aisles**: Redesign traffic flow, add one-way corridors
- **Supplier portal adoption resistance**: Demonstrate mutual value, simplify interface
- **Safety stock creep (inventory grows)**: Review and reset stock levels quarterly
- **Sequence changes after JIS call-off**: Implement freeze window (minimum 4 hours before build)

### lean-manufacturing

# Lean Manufacturing for Automotive Production

## Overview

Expert in lean manufacturing implementation for automotive production with deep expertise
in Toyota Production System principles, waste elimination, continuous improvement, and
pull-based production systems for maximizing value and minimizing waste.

## Key Concepts

The Eight Wastes (DOWNTIME) form the foundation of lean thinking.

Defects include scrap, rework, inspection failures, and warranty claims. Overproduction
means making more than customer demand and is considered the worst waste as it triggers
all other wastes. Waiting covers idle operators, machines, and WIP queues. Non-utilized
talent refers to ignored skills, creativity, and improvement ideas from the workforce.
Transportation means excessive material movement and forklift travel. Inventory excess
in raw material, WIP, and finished goods hides underlying problems. Motion covers
unnecessary operator walking, reaching, and bending. Extra processing means features
the customer does not value or rework activities.

## 5S Workplace Organization

A systematic approach to workplace organization and standardization.

Sort (Seiri) removes unnecessary items through red tag campaigns. Set in Order (Seiton)
organizes tools and parts with visual locations using shadow boards. Shine (Seiso) means
cleaning workspace and equipment while identifying leaks and wear. Standardize (Seiketsu)
documents best practices and visual standards. Sustain (Shitsuke) maintains compliance
through audits, continuous discipline, and culture building. Implementation uses 5S audit
checklists, before/after photos, and monthly scoring.

## Value Stream Mapping (VSM)

The primary tool for seeing the whole production flow and identifying improvement targets.

Current state mapping documents all process steps, cycle times, WIP inventory, and lead
time. Value-added vs non-value-added analysis separates activities the customer pays for
from waste. Key metrics include cycle time, changeover time, uptime, first-pass yield,
and WIP levels. Future state mapping designs the ideal flow with waste eliminated and
pull systems in place. Kaizen bursts mark improvement opportunities as quick wins or
projects. The implementation plan prioritizes improvements, assigns owners, and sets
deadlines.

## Kanban Pull System

Replacing push-based scheduling with demand-driven replenishment.

Supermarkets are controlled inventory points where parts are replenished as consumed.
Kanban cards or bins signal production or delivery when a container is emptied. Two-bin
systems keep one bin in use while the other is in the replenishment queue. Kanban
quantity is calculated as demand multiplied by lead time multiplied by safety factor,
divided by container size. Visual management uses color-coded bins where green means OK,
yellow means order, and red means critical.

## Kaizen (Continuous Improvement)

Structured approaches to incremental and breakthrough improvement.

Kaizen events are 3-5 day focused improvement workshops with cross-functional teams.
The PDCA cycle follows Plan-Do-Check-Act for iterative problem solving. A3 thinking
provides one-page problem solving covering background, current state, goals, analysis,
and countermeasures. Gemba walks involve going to the actual workplace to observe the
process and talk to operators. Suggestion systems capture operator improvement ideas
with recognition and rewards.

## SMED (Single-Minute Exchange of Die)

Reducing changeover time to under 10 minutes through systematic analysis.

External setup covers activities done while the machine is still running such as
preparing tools and materials. Internal setup covers activities requiring machine stop
such as removing and installing tooling. The key technique is converting internal to
external activities through pre-heating dies, pre-staging parts, and using quick-release
clamps. Standardization documents the best changeover sequence and trains all operators.

## Standard Work

The foundation for stable, repeatable, and improvable processes.

Takt time sets the pace of production to match customer demand. Work sequence documents
steps in optimal order. Standard WIP defines minimum parts between stations to maintain
flow. Visual aids include job instruction sheets, photos, and videos at each workstation.
Standard work is updated whenever kaizen improves the process.

## Implementation Guide

1. Leadership Commitment - Train executives on lean principles and secure resources
2. Pilot Line Selection - Choose high-volume line with supportive management
3. Value Stream Mapping - Current state analysis identifying waste and constraints
4. Quick Wins - Implement 5S and visual management for immediate results
5. Kaizen Events - Focused improvement on bottlenecks, changeovers, and quality
6. Pull System - Implement kanban for material replenishment from supermarkets
7. Training - Educate all employees on lean principles and tools
8. Sustain - Daily management system with tier meetings, KPI tracking, and audits

## Best Practices

- Start with one model line before expanding to the entire plant
- Involve operators in kaizen events because they know the waste best
- Focus on flow first, then pull, then level production (heijunka)
- Use visual management extensively with color codes, andon, and kanban cards
- Measure before and after for all improvements with data-driven decisions
- Sustain improvements with daily audits and tier meetings
- Celebrate successes publicly to build momentum and engagement

## Troubleshooting

- Cultural resistance to change - Start with visible quick wins and engage champions
- Improvements not sustained - Implement daily management audits and leader standard work
- Kanban system breaks down - Retrain on rules and audit card discipline weekly
- VSM analysis paralysis - Time-box mapping to 2 days and focus on top 3 wastes
- Management impatience - Set expectations that full benefits take 2-3 years

### machine-vision-inspection

## Core Competencies

Expert in machine vision system design for automotive quality inspection with expertise in classical computer vision, deep learning-based defect detection, and high-speed image processing.

### Vision System Components

- **Cameras**: Area scan (Basler, Cognex, Allied Vision), line scan for continuous web, 3D cameras (stereo, structured light)
- **Lenses**: Telecentric (eliminate perspective error), C-mount, megapixel resolution
- **Lighting**: Dome (diffuse), back light (edge detection), dark field (surface scratches), structured light (3D)
- **Image acquisition**: GigE Vision, USB3 Vision, Camera Link for high-speed transfer
- **Processing**: Edge computers (NVIDIA Jetson), industrial PCs, smart cameras with embedded processing

### Classical Computer Vision

- **Edge detection**: Canny, Sobel for finding part boundaries and features
- **Blob analysis**: Count, measure, filter objects by size/shape/color
- **Pattern matching**: Template matching, normalized cross-correlation for alignment
- **Gauge tools**: Measure distances, angles, diameters from edge positions
- **Optical Character Recognition (OCR)**: Read part numbers, dates, barcodes, Data Matrix codes

### Deep Learning Inspection

- **Classification**: CNN-based OK/NG sorting (ResNet, EfficientNet, MobileNet)
- **Segmentation**: Pixel-level defect localization (U-Net, Mask R-CNN, DeepLabV3)
- **Anomaly detection**: Autoencoders, GANs for detecting rare defects without labeled examples
- **Object detection**: YOLO, SSD, Faster R-CNN for multi-defect localization
- **Transfer learning**: Fine-tune pre-trained models on small automotive datasets (few-shot learning)

### Application Examples

- **Weld inspection**: Detect porosity, undercut, spatter using X-ray or visual+thermal imaging
- **Paint defects**: Classify orange peel, runs, sags, dirt, fisheyes using color+texture features
- **Gap/flush measurement**: 3D laser profiling to verify body panel alignment (±0.5mm tolerance)
- **Label verification**: OCR for VIN, compliance stickers, correct variant labeling
- **Fastener presence**: Verify all bolts installed with correct torque paint marks

### 3D Inspection

- **Laser triangulation**: Line laser + camera for height profiles, weld bead geometry
- **Structured light**: Project patterns to reconstruct 3D surface (GOM ATOS, Hexagon)
- **Stereo vision**: Dual cameras for depth estimation, passive 3D reconstruction
- **Time-of-Flight (ToF)**: Real-time 3D point clouds (Microsoft Azure Kinect, Basler ToF)
- **Fringe projection**: High-resolution 3D scanning for reverse engineering

## Approach

1. **Requirement Definition**: Defect types, detection rates (Cpk >1.67), cycle time, resolution
2. **Lighting Study**: Test multiple lighting angles and colors to maximize defect contrast
3. **Camera/Lens Selection**: Field of view, working distance, resolution vs part tolerance
4. **Algorithm Development**: Train classical vision or deep learning model on labeled dataset
5. **GR&R Study**: Validate measurement system repeatability and reproducibility per MSA
6. **Integration**: Trigger camera from PLC, communicate pass/fail via industrial Ethernet
7. **Deployment**: Install in production with environmental protection (IP65+ enclosures)
8. **Monitoring**: Track false positive/negative rates, retrain models with edge cases

## Deliverables

- Vision system BOM (camera, lens, lighting, PC, mounting hardware)
- Lighting configuration with photos showing defect contrast enhancement
- Trained vision algorithm (classical or deep learning) with accuracy metrics
- GR&R study results demonstrating <10% measurement variation
- Integration documentation (PLC I/O, OPC UA tags, reject gate control)
- Operator interface for manual review of auto-rejected parts
- Maintenance procedures (lens cleaning, lighting replacement, recalibration)

## Best Practices

- Capture training data representing full variation (lighting, part color, position)
- Label defects consistently with domain expert validation (avoid ambiguous cases)
- Use data augmentation (rotation, brightness, noise) to improve model generalization
- Implement confidence thresholds with manual review queue for borderline cases
- Calibrate cameras regularly with precision calibration targets (checkerboard, dot grid)
- Protect optics from coolant, oil, dust with air purge or sealed enclosures
- Version control training datasets and model weights with traceability to production batches

## Integration with Automotive Workflow

- Interface with MES to log inspection results and trigger work orders for rework
- Provide statistical process control (SPC) data to detect drift in welding or painting
- Enable digital twin updates with actual measured dimensions vs CAD nominal
- Support APQP (Advanced Product Quality Planning) with inspection data from pilot builds
- Integrate with traceability systems to link defects to specific robots, operators, shifts

### megacasting-giga-press

## Core Competencies

Expert in megacasting technology for automotive manufacturing with deep knowledge of high-pressure die casting (HPDC), tooling design, aluminum metallurgy, and integration with Tesla-pioneered giga-press systems.

### Giga-Press Technology

- **Press capacity**: 6000-9000 ton clamping force (IDRA, LK, Bühler)
- **Shot weight**: 60-120 kg aluminum per cycle (vs 5-10 kg conventional HPDC)
- **Cycle time**: 90-120 seconds target for underbody megacast
- **Integration**: Single-piece replaces 70+ stamped parts + 1600 spot welds
- **Cost reduction**: 40% vs traditional body-in-white (fewer parts, less assembly labor)

### Aluminum Alloy Selection

- **A380 (ADC12)**: High fluidity, good castability, lower cost (most common HPDC alloy)
- **A356 (AC4CH)**: Higher strength, heat-treatable (T6), better elongation for crash performance
- **Custom formulations**: Tesla proprietary alloys optimized for strength + castability
- **Vacuum-assist**: Reduce porosity for structural integrity (< 2% porosity target)
- **Grain refinement**: TiBor addition for fine microstructure and mechanical properties

### Die Design Challenges

- **Complexity**: Undercuts, ribs, bosses for mounting points and crash structures
- **Cooling channels**: Conformal cooling (3D-printed die inserts) for uniform solidification
- **Gating**: Multiple gates to ensure complete fill, minimize turbulence and oxide inclusion
- **Venting**: Avoid gas entrapment, reduce porosity in critical areas
- **Thermal management**: Prevent die cracking from thermal fatigue (100K+ cycles lifetime)

### Process Parameters

- **Melt temperature**: 650-720°C (balance fluidity vs gas pickup)
- **Injection speed**: 3-6 m/s (fast fill to minimize cold shuts)
- **Injection pressure**: 50-120 MPa (high pressure densifies casting, reduces shrinkage)
- **Die temperature**: 180-250°C (preheat for dimensional stability)
- **Vacuum level**: <50 mbar for vacuum-assisted HPDC (reduce porosity)

### Quality Control

- **X-ray CT scanning**: 3D porosity mapping, internal defect detection
- **Mechanical testing**: Tensile strength, elongation, fatigue per ASTM B557
- **Dimensional inspection**: CMM or laser scanning vs CAD nominal (±1mm tolerance)
- **Destructive testing**: Sectioning to verify wall thickness, porosity in critical zones
- **SPC on key parameters**: Melt temp, shot weight, cycle time, biscuit thickness

### Integration with Vehicle Architecture

- **Crash performance**: FEA simulation with as-cast porosity models, validate via NCAP tests
- **Joining**: Structural adhesive bonding to battery pack (CTC: cell-to-chassis)
- **Corrosion protection**: E-coat, cathodic protection strategies for mixed-material interfaces
- **Tolerance stack-up**: Manage dimensional variation for fit with upper body structure
- **Weight reduction**: 10-20% vs stamped steel equivalent (aluminum 2.7 g/cm³ vs steel 7.8)

## Approach

1. **Feasibility Study**: CAD analysis for die fill simulation, identify potential defects (cold shuts, porosity)
2. **Alloy Selection**: Trade-off castability, strength, cost, recyclability
3. **Die Design**: 3D mold flow simulation (MAGMA, ProCAST) to optimize gating and cooling
4. **Prototype Tooling**: Soft tooling for low-volume validation before hardened steel die
5. **Process Optimization**: DOE on injection speed, pressure, temperature to maximize quality
6. **Validation**: Crash testing, fatigue testing, corrosion testing per automotive standards
7. **Ramp-up**: Gradual production increase with continuous SPC monitoring
8. **Continuous Improvement**: Root cause analysis on scrap, cycle time reduction kaizen

## Deliverables

- Giga-press specification (tonnage, shot weight, cycle time, automation level)
- Aluminum alloy datasheet with mechanical properties and composition
- Die design CAD with cooling channels, gating, venting, ejection system
- Mold flow simulation results (fill pattern, solidification, predicted porosity)
- Process parameter window (acceptable ranges for temp, pressure, speed)
- Quality control plan (X-ray, mechanical testing, dimensional inspection frequency)
- Cost-benefit analysis vs traditional stamped + welded body structure

## Best Practices

- Invest in mold flow simulation to avoid costly die rework (50-70% of project cost)
- Use vacuum-assist HPDC for structural castings (critical for crash safety)
- Implement real-time shot monitoring (cavity pressure sensors) for process control
- Design for manufacturability: avoid thin walls <3mm, sharp corners, deep undercuts
- Plan for die maintenance: removable inserts in high-wear areas, conformal cooling channels
- Collaborate with aluminum suppliers for custom alloy development (strength + castability)
- Validate porosity acceptance criteria with FEA and physical crash tests

## Integration with Automotive Workflow

- Coordinate with body engineering for interface design to upper structure
- Align with battery pack team for CTC integration (structural bonding)
- Provide CAD and tolerance data to final assembly for fixture design
- Support APQP with PPAP documentation (capability studies, material certs)
- Enable circular economy: design for recyclability (single-alloy construction)

### mes-integration

## Core Competencies

Expert in MES implementation and integration for automotive manufacturing with deep knowledge of ISA-95 architecture, OEE tracking, quality systems, and shop floor data collection.

### ISA-95 Architecture

- **Level 0-1**: Sensors, actuators, PLCs (shop floor control)
- **Level 2**: SCADA and HMI (supervisory control)
- **Level 3**: MES (manufacturing execution and operations management)
- **Level 4**: ERP (business planning, SAP, Oracle)
- **Data flow**: Downward (schedules, recipes), Upward (actuals, events, quality)

### MES Core Functions (MESA-11)

- **Production scheduling**: Dispatch work orders to lines, balance load
- **Resource allocation**: Assign operators, tools, materials to operations
- **Quality management**: SPC, defect tracking, corrective actions (8D, CAPA)
- **Maintenance management**: Work orders, PM schedules, CMMS integration
- **Traceability**: Genealogy from raw material lot to finished VIN
- **Performance analysis**: OEE, cycle time, yield, first-pass quality
- **Labor management**: Attendance, skills matrix, productivity tracking
- **Document control**: Work instructions, ECN versioning, training records

### OEE (Overall Equipment Effectiveness)

- **Availability**: Actual runtime / Planned production time (downtime losses)
- **Performance**: Actual output / Theoretical max output (speed losses)
- **Quality**: Good parts / Total parts produced (quality losses)
- **OEE = Availability × Performance × Quality** (World-class >85%)
- **Six Big Losses**: Breakdowns, setup/changeovers, small stops, reduced speed, startup rejects, production rejects

### Data Collection Methods

- **Manual entry**: Operators input via HMI touchscreens, barcode scans
- **Automated**: PLC counters, sensor triggers, vision system pass/fail
- **Semi-automated**: RFID pallet tracking, tool RFID for verification
- **Andon system**: Operator calls for material, quality, maintenance via pull cord/button
- **Mobile devices**: Tablets for quality inspections, inventory counts

### Integration Protocols

- **OPC UA**: Standard for MES-to-PLC and MES-to-SCADA communication
- **REST APIs**: Modern MES platforms expose RESTful web services
- **MQTT**: Lightweight publish/subscribe for IoT sensor data
- **Database replication**: SQL triggers, ETL for ERP synchronization
- **B2MML (Business-to-Manufacturing Markup Language)**: XML for ISA-95 transactions

## Approach

1. **Requirements Gathering**: Define KPIs, workflows, integration points with stakeholders
2. **System Selection**: Evaluate MES vendors (Siemens Opcenter, Rockwell FactoryTalk, AVEVA)
3. **Data Model Design**: Product hierarchy, resources, routing, BOMs aligned with ERP
4. **Shop Floor Integration**: Connect PLCs, SCADA, quality systems via OPC UA
5. **ERP Interface**: Implement bi-directional sync (work orders down, actuals up)
6. **Dashboard Development**: Real-time OEE, downtime Pareto, quality trends
7. **User Training**: Operators, supervisors, engineers on data entry and reporting
8. **Go-Live**: Phased rollout starting with one line, expand after stabilization

## Deliverables

- MES functional specification with process flows and integration architecture
- OPC UA tag list mapping PLC variables to MES data points
- OEE dashboard with configurable time periods (shift, day, week, month)
- Quality module configuration for SPC charts, defect tracking, CAPA workflow
- Traceability reports linking VIN to parts, operators, equipment, timestamps
- ERP integration interface for work order synchronization and material consumption
- User training materials and role-based access control configuration

## Best Practices

- Start with one production line (pilot) to validate workflows before full deployment
- Automate data collection wherever possible to reduce manual entry errors
- Define clear downtime reason codes with operator training to ensure consistency
- Implement real-time dashboards visible on shop floor to drive improvement culture
- Regularly audit data quality (missing scans, incorrect reason codes)
- Use MES reports to drive daily production meetings and escalation
- Version control MES configurations (product definitions, routings, reason codes)

## Integration with Automotive Workflow

- Synchronize with SAP/ERP for work order creation and material backflushing
- Interface with quality lab LIMS for material test results (incoming inspection)
- Connect to vision inspection systems for automated OK/NG recording
- Provide traceability data for regulatory compliance (IATF, VDA, customer audits)
- Enable digital andon with automated escalation to team leaders and engineers

### near-shoring-strategy

## Overview

Near-shoring relocates manufacturing and sourcing from distant low-cost countries to
geographically closer regions, trading labor cost advantage for reduced lead times,
lower logistics cost, better IP protection, and reduced geopolitical risk. For automotive,
this means shifting from Asia-centric supply chains toward regional production networks
aligned with final assembly locations.

The automotive industry faces compounding near-shoring drivers: USMCA regional content
requirements (75% for passenger vehicles), EU battery regulation mandating local production,
semiconductor reshoring incentives (CHIPS Act, EU Chips Act), and carbon border taxes
penalizing long-distance transport of heavy components.


## Key Concepts

### Total Cost of Ownership (TCO) Components

- **Unit cost**: Raw material + labor + overhead + margin
- **Logistics**: Ocean freight, inland transport, customs brokerage, insurance
- **Inventory**: Pipeline stock (weeks in transit), safety stock, warehousing
- **Quality**: Incoming inspection, rejection rate, warranty claims, audit travel
- **Risk**: Disruption probability x production downtime cost
- **Tariffs/Duties**: Applied rate based on HS code and trade agreement eligibility
- **Carbon cost**: Transport emissions x carbon price (EU ETS, CBAM)
- **Working capital**: Payment terms, currency hedging, letter of credit costs

### Regional Content Requirements

```
USMCA (North America):
  Vehicle:     75% regional value content
  Core parts:  75% (engine, transmission, body, chassis)
  Steel/Aluminum: 70% North American sourced
  Labor:       LVC (Labor Value Content) 40-45% at $16+/hr

EU Battery Regulation:
  2027: Carbon footprint declaration mandatory
  2028: Maximum carbon footprint thresholds
  2030: Recycled content minimums (Ni 6%, Li 6%, Co 16%)
  Local production: Required for full EU content qualification
```

### Near-Shore Region Mapping

```
Assembly in:     Near-Shore Options:
============     ==================
US Southeast --> Mexico, Canada, US Midwest
Germany      --> Poland, Czech Republic, Hungary, Spain, Portugal
Japan        --> Thailand, Vietnam, Indonesia
China        --> Vietnam, India, Malaysia (for export)
Brazil       --> Argentina, Colombia
```


## Implementation Guide

### Step 1: TCO Comparison Model

```python
# Total cost of ownership analysis
class NearShoreTCO:
    def __init__(self, annual_volume: int, part_weight_kg: float):
        self.volume = annual_volume
        self.weight = part_weight_kg

    def calculate_scenario(self, scenario: dict) -> dict:
        """Calculate full TCO for a sourcing scenario."""
        unit_cost = scenario["piece_price"] * self.volume
        logistics = self.calc_logistics(scenario)
        inventory = self.calc_inventory_cost(scenario)
        quality = self.calc_quality_cost(scenario)
        tariff = scenario["piece_price"] * scenario["duty_rate"] * self.volume
        risk = scenario["disruption_prob"] * scenario["downtime_cost_per_day"] * scenario["avg_disruption_days"]
        carbon = self.calc_carbon_cost(scenario)
        total = unit_cost + logistics + inventory + quality + tariff + risk + carbon
        return {
            "scenario": scenario["name"],
            "unit_cost": unit_cost,
            "logistics": logistics,
            "inventory": inventory,
            "quality": quality,
            "tariff": tariff,
            "risk_adjusted": risk,
            "carbon_cost": carbon,
            "total_tco": total,
            "tco_per_unit": total / self.volume,
        }

    def calc_logistics(self, s: dict) -> float:
        freight = s["freight_per_kg"] * self.weight * self.volume
        customs = s["customs_clearance"] * (self.volume / s["parts_per_container"])
        return freight + customs

    def calc_inventory_cost(self, s: dict) -> float:
        pipeline_weeks = s["transit_time_weeks"]
        safety_weeks = s["safety_stock_weeks"]
        weekly_demand_value = (self.volume / 52) * s["piece_price"]
        carrying_rate = 0.20  # 20% annual carrying cost
        return (pipeline_weeks + safety_weeks) * weekly_demand_value * carrying_rate
```

### Step 2: Supplier Development Program

```yaml
supplier_development_phases:
  phase_1_assessment:
    duration_months: 3
    activities:
      - capability_audit_vda_6_3
      - financial_due_diligence
      - quality_system_gap_analysis
      - workforce_skills_assessment
      - infrastructure_evaluation
  phase_2_qualification:
    duration_months: 6
    activities:
      - APQP_support_and_mentoring
      - process_capability_studies
      - PPAP_submission_and_approval
      - run_at_rate_validation
      - logistics_setup_and_testing
  phase_3_ramp_up:
    duration_months: 6
    activities:
      - gradual_volume_transfer_20_50_80_100
      - resident_quality_engineer_placement
      - SPC_monitoring_and_feedback
      - continuous_improvement_kaizen
      - full_production_release
```

### Step 3: Site Selection Scoring

```python
# Weighted multi-criteria site evaluation
class SiteSelector:
    CRITERIA = {
        "labor_cost": 0.15,
        "labor_availability": 0.12,
        "logistics_proximity": 0.15,
        "infrastructure_quality": 0.10,
        "trade_agreement_benefit": 0.12,
        "energy_cost_and_green": 0.08,
        "political_stability": 0.10,
        "ip_protection": 0.08,
        "supplier_ecosystem": 0.10,
    }

    def evaluate_site(self, site: dict) -> dict:
        """Score candidate site on weighted criteria (1-10 scale)."""
        weighted_score = sum(
            site["scores"][criterion] * weight
            for criterion, weight in self.CRITERIA.items()
        )
        return {
            "site": site["name"],
            "country": site["country"],
            "weighted_score": round(weighted_score, 2),
            "strengths": [c for c, w in self.CRITERIA.items() if site["scores"][c] >= 8],
            "weaknesses": [c for c, w in self.CRITERIA.items() if site["scores"][c] <= 4],
        }
```

### Step 4: Production Transfer Plan

```
Month 1-3:   Supplier selection and tooling order
Month 4-9:   Tool build, first articles, PPAP
Month 10-12: Parallel production (old and new source)
Month 13-15: Volume ramp at new source (20% -> 50% -> 80%)
Month 16-18: Full transfer, decommission old source
Month 19+:   Performance monitoring and optimization
```


## Best Practices

- Never compare piece price alone -- always use full TCO including risk and carbon
- Maintain dual sourcing during transition (minimum 6 months parallel production)
- Invest in supplier development -- near-shore suppliers may need quality system upgrades
- Factor in regional content requirements early -- they determine eligible sourcing regions
- Account for currency risk when comparing cross-border scenarios
- Consider vertical integration for critical components when suppliers are scarce
- Engage trade compliance experts for rules of origin calculation before committing
- Plan for automation investment at near-shore sites to offset higher labor costs


## Common Patterns

### Decision Framework

```
Near-shore when:                      Keep offshore when:
================                      ==================
Lead time > 6 weeks                   Unit cost delta > 40%
Single-source risk = high             Volume justifies dedicated ship
Regional content required             Technology only available offshore
Quality issues from distance          Mature supply base exists
Carbon cost significant               Low disruption history
High engineering change frequency      Commodity with multiple global sources
```

### Phased Migration Strategy

```
Phase 1: Move high-risk single-source components (12 months)
Phase 2: Move bulky/heavy parts where logistics cost dominates (18 months)
Phase 3: Move engineered components requiring close collaboration (24 months)
Phase 4: Move remaining commodities where TCO favors near-shore (36 months)
```


## Troubleshooting

- **Higher piece price kills business case**: Include disruption risk cost and carbon cost
- **No qualified suppliers in target region**: Invest in supplier development program
- **Rules of origin calculation complex**: Use customs broker with automotive specialization
- **Quality gap at new supplier**: Place resident engineer, implement intensive SPC program
- **Labor shortage at near-shore site**: Partner with local technical schools, invest in automation
- **Currency volatility undermines savings**: Use natural hedging (revenue and cost in same currency)

### nvidia-omniverse-factory

## Overview

NVIDIA Omniverse is a computing platform for building and operating physically accurate
digital twins. For automotive manufacturing, Omniverse enables creation of factory-scale
simulations where every robot, conveyor, AGV, and operator is modeled with real physics,
connected to live production data, and rendered with cinematic quality.

Combined with Isaac Sim for robotics and Metropolis for vision AI, Omniverse provides
the foundation for autonomous factory operations where AI agents are trained in simulation
and deployed to physical systems with minimal sim-to-real gap.


## Key Concepts

### Omniverse Architecture

- **Nucleus**: Central collaboration server for USD scene management and versioning
- **Kit**: Extensible application framework for building custom tools
- **Isaac Sim**: Robot simulation with ROS/ROS2 integration and synthetic data generation
- **Replicator**: Synthetic data generation for training computer vision models
- **Audio2Face/Machinima**: Not relevant for factory -- focus on engineering extensions
- **Connect**: Plugins for CAD tools (Revit, SolidWorks, Siemens NX) to push data to USD

### Universal Scene Description (USD)

- **Native format**: All Omniverse content authored in Pixar USD
- **Composition**: Layer, reference, and variant mechanisms for non-destructive editing
- **Physics**: PhysX integration for rigid body, articulated body, and soft body simulation
- **Materials**: MDL (Material Definition Language) for PBR materials with physical accuracy

### Factory Digital Twin Layers

```
Layer 7: AI/Analytics      (Reinforcement learning, anomaly detection)
Layer 6: Visualization     (RTX ray tracing, viewport streaming)
Layer 5: Simulation        (PhysX, Isaac Sim, flow simulation)
Layer 4: Behavior          (Robot programs, PLC logic, AGV routes)
Layer 3: Data Integration  (OPC UA, MQTT, REST API connectors)
Layer 2: Geometry          (USD scene graph, CAD imports, LiDAR scans)
Layer 1: Infrastructure    (Nucleus server, GPU compute, network)
```


## Implementation Guide

### Step 1: Omniverse Infrastructure Setup

```yaml
omniverse_deployment:
  nucleus_server:
    type: enterprise
    storage_tb: 10
    users: 200
    authentication: ldap_sso
  compute_nodes:
    gpu: NVIDIA_A100_or_L40S
    count: 4
    purpose: simulation_and_rendering
  workstations:
    gpu: NVIDIA_RTX_4090_or_A6000
    count: 20
    purpose: interactive_authoring
  network:
    bandwidth_gbps: 25
    protocol: nucleus_live_sync
```

### Step 2: Factory Scene Construction

```python
# Omniverse factory scene builder using USD API
from pxr import Usd, UsdGeom, UsdPhysics, Sdf

class FactorySceneBuilder:
    def __init__(self, nucleus_url: str):
        self.stage = Usd.Stage.CreateNew(f"{nucleus_url}/factory/main.usd")
        UsdGeom.SetStageUpAxis(self.stage, UsdGeom.Tokens.z)
        UsdGeom.SetStageMetersPerUnit(self.stage, 1.0)

    def add_robot_cell(self, cell_name: str, robot_usd: str, position: tuple):
        """Add a robot cell to the factory scene."""
        cell_prim = self.stage.DefinePrim(f"/factory/cells/{cell_name}", "Xform")
        robot_ref = self.stage.DefinePrim(
            f"/factory/cells/{cell_name}/robot", "Xform"
        )
        robot_ref.GetReferences().AddReference(robot_usd)
        xform = UsdGeom.Xformable(cell_prim)
        xform.AddTranslateOp().Set(position)

    def add_conveyor(self, name: str, start: tuple, end: tuple, speed_mps: float):
        """Add physics-enabled conveyor belt."""
        conveyor = self.stage.DefinePrim(f"/factory/conveyors/{name}", "Xform")
        # Add rigid body physics and conveyor surface velocity
        physics_api = UsdPhysics.RigidBodyAPI.Apply(conveyor)
        # Configure conveyor belt surface properties
        self.set_conveyor_velocity(conveyor, start, end, speed_mps)

    def connect_opc_ua(self, equipment_prim: str, opc_node: str):
        """Bind OPC UA data point to USD prim attribute for live updates."""
        prim = self.stage.GetPrimAtPath(equipment_prim)
        prim.CreateAttribute("opc:nodeId", Sdf.ValueTypeNames.String).Set(opc_node)
```

### Step 3: Isaac Sim Robot Simulation

```python
# Isaac Sim robot simulation for automotive welding cell
from omni.isaac.core import World
from omni.isaac.core.robots import Robot

class WeldingCellSimulation:
    def __init__(self):
        self.world = World(stage_units_in_meters=1.0)

    def setup_robot(self, robot_usd: str, position: list):
        """Load and configure welding robot in simulation."""
        self.world.scene.add(
            Robot(prim_path="/World/robot", usd_path=robot_usd, position=position)
        )

    def simulate_weld_cycle(self, weld_points: list, speed_mps: float = 0.5):
        """Run welding cycle simulation and measure cycle time."""
        total_time = 0.0
        for i, point in enumerate(weld_points):
            move_time = self.plan_motion(point, speed_mps)
            weld_time = point.get("weld_duration_s", 0.3)
            total_time += move_time + weld_time
        return {"cycle_time_s": total_time, "weld_count": len(weld_points)}

    def generate_synthetic_data(self, camera_positions: list, num_frames: int):
        """Use Replicator to generate training data for weld inspection AI."""
        # Configure domain randomization for lighting, part variation, defects
        return self.replicator.generate(
            cameras=camera_positions,
            frames=num_frames,
            annotations=["bounding_box_2d", "semantic_segmentation"],
        )
```

### Step 4: AGV/AMR Fleet Simulation

```python
# Simulate autonomous mobile robot fleet in factory
class AMRFleetSimulator:
    def __init__(self, factory_stage, fleet_size: int = 20):
        self.stage = factory_stage
        self.fleet = self.spawn_amr_fleet(fleet_size)

    def spawn_amr_fleet(self, count: int):
        """Deploy AMR fleet with VDA 5050 compatible control."""
        fleet = []
        for i in range(count):
            amr = self.stage.DefinePrim(f"/factory/amr/unit_{i:03d}", "Xform")
            # Configure navigation, obstacle avoidance, fleet coordination
            fleet.append(amr)
        return fleet

    def optimize_routes(self, delivery_orders: list) -> dict:
        """Run RL-based route optimization for material delivery."""
        # Train reinforcement learning agent in simulation
        return {
            "throughput_deliveries_per_hour": 45,
            "average_delivery_time_s": 120,
            "fleet_utilization_pct": 78,
            "collision_events": 0,
        }
```

### Step 5: Live Data Integration

```
Factory Floor                 Omniverse Nucleus
=============                 =================
Siemens S7-1500 (OPC UA) --> Omniverse Connect (OPC UA Extension)
KUKA Robot (RSI)          --> Isaac Sim Robot State Sync
SICK LiDAR (ROS2)        --> Isaac ROS2 Bridge
Energy Meters (MQTT)      --> Custom Omniverse Extension
MES (REST API)            --> Kit Extension with HTTP Client
```


## Best Practices

- Use USD references (not copies) for reusable equipment to keep scene manageable
- Organize factory scene by zone: /factory/body_shop, /factory/paint, /factory/assembly
- Run physics simulation on dedicated GPU nodes, not on authoring workstations
- Validate robot kinematics in Isaac Sim against physical robot before trusting results
- Use Omniverse Nucleus checkpoints for version control of factory layouts
- Generate synthetic data with domain randomization for robust vision AI training
- Start with a single cell digital twin, prove value, then scale to full factory
- Maintain consistent coordinate systems: Z-up, meters, matching plant survey


## Common Patterns

### Virtual Commissioning Pipeline

1. Import robot cell CAD from NX/SolidWorks via Omniverse Connect
2. Add physics properties (collision meshes, joint limits, conveyor surfaces)
3. Connect virtual PLC via OPC UA for signal-level commissioning
4. Run cycle simulation, measure timing, detect collisions
5. Iterate robot paths in Isaac Sim until cycle time target met
6. Export validated programs to physical robot controllers

### Synthetic Data Generation for Quality AI

```
Replicator Pipeline:
  Scene: welding_cell_twin
  Camera: inspection_camera_01
  Randomization:
    - part_pose: uniform(+-2mm, +-1deg)
    - lighting: 3000K-6500K, 200-1000 lux
    - weld_defect: [none, porosity, undercut, spatter] @ [70%, 10%, 10%, 10%]
  Output: 50,000 labeled images
  Format: COCO annotations + semantic masks
```


## Troubleshooting

- **Slow scene loading**: Reduce mesh density with decimation, use LOD variants in USD
- **Physics instability**: Increase solver iterations, check collision mesh quality
- **OPC UA connection drops**: Verify firewall rules, use OPC UA redundancy mode
- **Isaac Sim ROS2 latency**: Use FastDDS instead of CycloneDDS, check QoS settings
- **GPU memory overflow**: Split factory into zones, load on demand
- **USD merge conflicts**: Use Omniverse layering -- each team edits their own layer

### paint-shop-automation

## Core Competencies

Expert in automotive paint shop automation with deep knowledge of electro-coating, robotic paint application, curing ovens, color management, and environmental compliance.

### Paint Process Sequence

- **Pretreatment**: Degreasing, phosphate conversion coating (zinc phosphate for steel, zirconium for aluminum)
- **E-coat (Electrodeposition)**: Cathodic electrocoating for corrosion protection (20-30 μm, 180°C cure)
- **Primer surfacer**: Fill imperfections, provide adhesion base (30-40 μm, 140°C)
- **Basecoat**: Color layer (15-20 μm, 80°C flash-off)
- **Clearcoat**: UV protection, gloss, scratch resistance (40-50 μm, 140°C cure)

### Robotic Paint Application

- **Atomization**: High-volume low-pressure (HVLP), electrostatic, rotary bell atomizers
- **Transfer efficiency**: HVLP 65-75%, electrostatic 85-95% (reduce overspray waste)
- **Robot motion**: Elliptical paths, constant distance to surface, 6-axis wrist orientation
- **Paint flow rate**: 150-300 mL/min, modulated by robot speed for film thickness control
- **Programming**: Offline programming (KUKA PaintExpert, ABB RobotStudio Paint), virtual commissioning

### E-Coat Process

- **Electrodeposition**: DC voltage (200-400V) drives cationic paint particles to grounded body
- **Film thickness**: Self-limiting (resistance increases with coating thickness), 20-30 μm typical
- **Throwing power**: Ability to coat recessed areas (A-pillars, box sections, hemmed flanges)
- **Bath management**: Maintain pH, conductivity, solids content, temperature (28-32°C)
- **Rinsing**: Ultrafiltrate rinse to recover paint drag-out, minimize wastewater

### Color Changeover

- **Purge volume**: Flush paint lines with solvent then new color (2-5 kg paint waste per change)
- **Quick-change systems**: Dedicated bells per color family (reduce changeover to <60 sec)
- **Sequencing**: Batch similar colors (light→dark→metallic) to minimize purge waste
- **Automatic color kitchen**: Gravimetric mixing with recipe control, ±0.1% accuracy
- **Color measurement**: Spectrophotometer for match validation vs target ΔE <1.0

### Oven Design

- **Curing profile**: Ramp (heat part), soak (cure paint), cool (prevent thermal shock)
- **Convection ovens**: Hot air circulation (electric or gas-fired), 140-200°C peak metal temp
- **Infrared (IR)**: Radiant heating for flash-off zones (faster, lower energy)
- **Energy recovery**: Heat exchangers preheat incoming air using exhaust (30-40% energy savings)
- **Airflow**: Laminar flow to prevent defects (dust settling, orange peel)

### Defect Prevention

- **Dirt/dust**: Class 10,000 cleanroom, positive pressure, sticky mats, air showers
- **Orange peel**: Atomization pressure, paint viscosity, flash time, oven temperature tuning
- **Runs/sags**: Reduce film thickness, optimize flash time, check paint rheology
- **Dry spray**: Increase air humidity, reduce booth velocity, adjust atomization
- **Fisheyes**: Contamination control (silicone, oil), surface cleaning validation

### VOC Compliance

- **Regulatory limit**: 350 g/L VOC (US EPA), 420 g/L (EU), stricter in California (250 g/L)
- **Waterborne basecoat**: 80-90% water, 10-15% organic solvents (vs 100% solvent)
- **High-solids coatings**: >60% solids vs 35-45% conventional (less solvent evaporation)
- **Emission control**: Thermal oxidizers (RTO), carbon adsorption for solvent recovery
- **Transfer efficiency**: Electrostatic application reduces overspray waste by 20-30%

## Approach

1. **Process Design**: Define paint system (e-coat type, primer, basecoat/clearcoat vendors)
2. **Robot Layout**: Simulate booth with part motion, robot reach, overlap zones
3. **Path Programming**: Offline programming with validated spray models, virtual commissioning
4. **Paint Kitchen**: Configure automatic mixing, color recipes, inventory management
5. **Oven Sizing**: Calculate residence time for cure, energy consumption, airflow CFD
6. **Trial Runs**: Paint sample panels, measure film thickness, gloss, adhesion, appearance
7. **Process Validation**: PPAP with customer-supplied parts, color approval, capability study
8. **Production Launch**: Monitor defect rates, transfer efficiency, VOC emissions, energy use

## Deliverables

- Paint shop layout with booth count, robot positions, conveyor path
- Robot paint programs with cycle times and material usage estimates
- E-coat bath management procedures (additions, filtration, disposal)
- Color changeover sequencing algorithm and purge waste projections
- Oven cure profiles with temperature ramps and residence times
- Quality control plan (film thickness, gloss, adhesion test frequency)
- VOC emissions report demonstrating regulatory compliance

## Best Practices

- Use offline programming with digital twin to minimize commissioning time
- Implement automatic film thickness measurement (ultrasonic, eddy current) for closed-loop control
- Batch paint jobs by color family to minimize changeover waste
- Monitor paint booth temperature and humidity with tight control (±2°C, ±5% RH)
- Clean robots and equipment daily to prevent contamination and defects
- Use data analytics to correlate process parameters with defect rates (predictive quality)
- Implement waterborne basecoat for VOC reduction (industry trend)

## Integration with Automotive Workflow

- Interface with body shop for surface quality requirements (dent, gap/flush specs)
- Coordinate with final assembly on cure time to avoid tape marks and handling damage
- Provide paint specifications to suppliers for color-matched bumpers, mirrors, trim
- Support digital twin with actual paint thickness and appearance data
- Enable customer personalization with flexible color sequencing and custom colors

### plc-programming

## Core Competencies

Expert in PLC programming for automotive manufacturing with deep knowledge of IEC 61131-3 languages, safety systems, industrial communication, and motion control.

### PLC Platforms

- **Siemens**: S7-1200/1500, TIA Portal IDE, PROFINET/PROFIBUS communication
- **Allen-Bradley/Rockwell**: ControlLogix, CompactLogix, Studio 5000, EtherNet/IP
- **Mitsubishi**: iQ-R/iQ-F, GX Works3, CC-Link
- **Omron**: NJ/NX series, Sysmac Studio, EtherCAT
- **Beckhoff**: CX/EL series, TwinCAT 3, EtherCAT real-time control

### IEC 61131-3 Languages

- **Ladder Logic (LD)**: Relay logic emulation, best for discrete I/O and Boolean logic
- **Structured Text (ST)**: High-level language for complex math, loops, algorithms
- **Function Block Diagram (FBD)**: Graphical representation of data flow and functions
- **Sequential Function Chart (SFC)**: State machine programming for process sequences
- **Instruction List (IL)**: Low-level assembly-like (rarely used, deprecated in IEC 61131-3 3rd edition)

### Program Structure

- **Organization Blocks (OB)**: Main cyclic, startup, interrupt, error handling
- **Functions (FC)**: Reusable code without memory (stateless)
- **Function Blocks (FB)**: Reusable with instance data blocks (stateful)
- **Data Blocks (DB)**: Global variables, recipe data, parameter sets
- **Scan cycle**: Typical 10-50ms for discrete logic, <1ms for motion control

### Safety Programming

- **Safety PLCs**: Siemens S7-1500F, AB GuardLogix, Pilz PSS4000
- **Dual-channel architecture**: Two independent processors with voter (PLd/Cat 3)
- **Safety functions**: E-stop, light curtains, safety gates, two-hand control
- **Proven-in-Use libraries**: Pre-certified safety blocks reduce validation effort
- **Safety integrity level (SIL)**: SIL 2 typical for machinery, SIL 3 for critical processes

### Industrial Communication

- **Fieldbuses**: PROFIBUS DP, DeviceNet, CANopen for I/O and drive communication
- **Industrial Ethernet**: PROFINET, EtherNet/IP, EtherCAT for high-speed deterministic control
- **OPC UA**: Standardized client-server for MES, SCADA, cloud connectivity
- **Modbus TCP/RTU**: Simple protocol for legacy equipment integration
- **IO-Link**: Point-to-point for smart sensor parameterization and diagnostics

### Motion Control

- **Servo drives**: Pulse/direction, analog ±10V, fieldbus (PROFINET, EtherCAT)
- **Motion control instructions**: Positioning, velocity, homing, electronic gearing
- **Cam profiles**: Synchronized motion (pick-and-place, flying cutoff)
- **Kinematics**: Coordinate transformations for multi-axis robots (KUKA, ABB via PLC)
- **Interpolation**: Linear, circular, spline for CNC-like path control

### Automotive Applications

- **Conveyor systems**: Zone control, accumulation, merge/divert logic
- **Robotic cells**: I/O handshakes, safety interlocks, part present verification
- **Press control**: Hydraulic/servo press motion, force monitoring, die protection
- **Assembly stations**: Torque tool integration, vision system triggers, barcode scanners
- **Material handling**: AGV interface, lift tables, pallet dispensers

## Approach

1. **Functional Specification**: Define I/O list, sequences, safety requirements, cycle time
2. **Hardware Configuration**: Select PLC CPU, I/O modules, communication cards, safety modules
3. **Software Architecture**: Organize code into functions/FBs, state machines for sequences
4. **Programming**: Implement logic in ladder/ST/FBD with consistent naming conventions
5. **Simulation**: Test logic in virtual environment (PLCSIM, Factory I/O)
6. **Commissioning**: Download program, verify I/O, tune motion parameters, safety validation
7. **Documentation**: Comment code, generate I/O lists, create functional descriptions
8. **Version Control**: Use Git or SVN for PLC programs with meaningful commit messages

## Deliverables

- PLC program source code with structured organization and comments
- I/O list mapping physical sensors/actuators to PLC tags
- HMI (Human-Machine Interface) screens for operator control and monitoring
- Safety validation report per ISO 13849-1 with SISTEMA calculations
- Communication configuration for OPC UA, fieldbus, Ethernet/IP
- Commissioning checklist and FAT/SAT test protocols
- Maintenance documentation with troubleshooting guides

## Best Practices

- Use descriptive tag names (e.g., Conveyor_01_Motor_Run vs M1)
- Implement state machines for complex sequences (idle, run, stop, fault, e-stop)
- Separate safety logic into dedicated safety CPU or separate program sections
- Add fault diagnostics with clear alarm messages for operators
- Use function blocks for reusable components (motor control, valve control)
- Limit main scan cycle time to <50ms to ensure responsive control
- Test all fault recovery scenarios (e-stop, power loss, communication loss)

## Integration with Automotive Workflow

- Interface with MES via OPC UA for work order download and production counts
- Connect to SCADA for real-time monitoring and historical data logging
- Integrate with robot controllers via digital I/O or fieldbus for cell coordination
- Provide diagnostic data to predictive maintenance systems
- Support remote access for engineering troubleshooting and program updates

### predictive-maintenance-manufacturing

## Core Competencies

Expert in predictive maintenance strategy development for automotive manufacturing equipment with deep expertise in vibration analysis, thermography, oil analysis, and machine learning-based anomaly detection.

### Condition Monitoring Technologies

- **Vibration analysis**: Accelerometers measure bearing wear, imbalance, misalignment, looseness
- **Thermal imaging**: IR cameras detect hot spots in motors, bearings, electrical connections
- **Oil analysis**: Particle count, viscosity, moisture for hydraulic and lubrication systems
- **Acoustic emission**: Ultrasonic sensors for leak detection, corona discharge, bearing faults
- **Motor current signature analysis (MCSA)**: Detect rotor bar cracks, eccentricity from current spectrum

### Vibration Analysis

- **FFT (Fast Fourier Transform)**: Convert time-domain to frequency-domain for fault signatures
- **Bearing defect frequencies**: BPFO (outer race), BPFI (inner race), BSF (ball spin), FTF (cage)
- **Imbalance**: Peak at 1× RPM, radial vibration pattern
- **Misalignment**: High 2× and 3× RPM harmonics, axial vibration
- **Looseness**: Multiple harmonics with non-integer ratios, high amplitude variation
- **ISO 10816 severity zones**: A (new), B (acceptable), C (unsatisfactory), D (unacceptable)

### Thermal Monitoring

- **Hot spot detection**: ΔT >10°C above ambient indicates bearing friction, electrical resistance
- **Thermal trending**: Monitor temperature rise over time to predict failure weeks in advance
- **Motor windings**: >80°C suggests overload, poor ventilation, or insulation degradation
- **Electrical panels**: Hot terminals indicate loose connections, arcing risk
- **Predictive thresholds**: Set alarms at 75% of failure temperature from reliability data

### Machine Learning Models

- **Anomaly detection**: Isolation Forest, One-Class SVM for detecting unusual sensor patterns
- **Survival analysis**: Weibull regression to predict remaining useful life (RUL)
- **Classification**: Random Forest, XGBoost to classify fault types from multi-sensor data
- **Time-series forecasting**: LSTM, Prophet to predict when thresholds will be exceeded
- **Feature engineering**: Statistical features (mean, RMS, kurtosis, crest factor) from raw vibration

### Failure Modes

- **Bearings**: Spalling, brinelling, corrosion, lubrication failure (40% of motor failures)
- **Gearboxes**: Tooth wear, pitting, scoring, backlash increase
- **Motors**: Winding insulation breakdown, rotor bar cracks, bearing failure
- **Hydraulics**: Pump wear, valve stiction, seal leakage, fluid contamination
- **Pneumatics**: Cylinder seal wear, valve leakage, compressor failure

## Approach

1. **Asset Criticality Analysis**: Rank equipment by downtime impact and maintenance cost
2. **Sensor Selection**: Choose monitoring type and location based on failure modes
3. **Baseline Collection**: Measure healthy equipment to establish normal operating ranges
4. **Threshold Definition**: Set warning and alarm limits based on standards and history
5. **Data Acquisition**: Edge devices collect high-frequency data (20 kHz vibration, 1 Hz thermal)
6. **Model Training**: Build ML models using historical failure data and condition trends
7. **Alert System**: Notify maintenance team when anomalies detected or RUL <30 days
8. **Continuous Learning**: Update models with actual failure events to improve accuracy

## Deliverables

- Equipment criticality matrix ranking assets by risk and maintainability
- Sensor installation plan (locations, types, mounting methods)
- Vibration and thermal baseline reports for each monitored asset
- ML model performance metrics (precision, recall, false alarm rate, RUL accuracy)
- Predictive maintenance schedule with recommended intervention dates
- Integration with CMMS (Computerized Maintenance Management System)
- Cost savings report (avoided downtime, reduced spare inventory, labor optimization)

## Best Practices

- Focus on critical assets first (bottleneck machines, high downtime impact)
- Collect at least 6 months of data before training ML models
- Validate predictions with maintenance technician feedback (avoid false alarms)
- Use both online (continuous) and offline (periodic route-based) monitoring
- Train maintenance team on interpreting vibration spectra and thermal images
- Integrate with work order system to close loop on predicted vs actual failures
- Track KPIs: MTBF (Mean Time Between Failures), MTTR (Mean Time To Repair), OEE improvement

## Integration with Automotive Workflow

- Connect to MES for production schedule optimization around planned maintenance
- Interface with spare parts inventory system for JIT ordering based on predictions
- Provide OEE data to production planning for realistic capacity calculations
- Support IATF 16949 preventive/predictive maintenance documentation requirements
- Enable condition-based maintenance vs fixed-interval for cost reduction

### predictive-shop-floor

## Overview

Predictive shop floor analytics transforms reactive maintenance and firefighting into
proactive, data-driven operations management. By applying machine learning to sensor
data, production logs, and quality records, manufacturing teams can forecast what will
happen on the shop floor hours, days, or weeks ahead -- enabling interventions before
problems impact production.

For automotive plants producing 1,000+ vehicles per day, even a 1% improvement in
unplanned downtime translates to 10+ additional vehicles per day. Predictive models
targeting the top failure modes of critical equipment deliver ROI within months, not
years.


## Key Concepts

### Predictive Analytics Maturity Levels

```
Level 1: Descriptive    "What happened?"     (dashboards, reports)
Level 2: Diagnostic     "Why did it happen?"  (root cause analysis)
Level 3: Predictive     "What will happen?"   (ML forecasting)
Level 4: Prescriptive   "What should we do?"  (optimization + action)
```

### Key Prediction Targets

- **Remaining Useful Life (RUL)**: Time until equipment failure (hours/days)
- **Degradation Score**: 0-100% health indicator for gradual wear
- **Anomaly Probability**: Likelihood of abnormal behavior in next N cycles
- **Quality Risk Score**: Probability of defect based on current process state
- **Throughput Forecast**: Predicted output for next shift/day/week
- **Energy Demand**: Predicted kW consumption for next hours

### Data Sources for Prediction

```
Source                  Data Type              Sample Rate
=====================   ====================   ===========
Vibration sensors       Acceleration (g)       10 kHz
Current sensors         Motor amps             1 kHz
Temperature sensors     Bearing/gearbox C      1 Hz
PLC cycle data          Cycle time, counts     Per cycle
Quality measurements    SPC data, vision       Per part
MES logs                Status, alarms, OEE    Per event
Maintenance records     Work orders, parts      Per event
Energy meters           kW, kWh                15 min
```


## Implementation Guide

### Step 1: Data Collection and Preparation

```python
# Shop floor data pipeline
class ShopFloorDataPipeline:
    def __init__(self, historian_url: str, mes_url: str):
        self.historian = historian_url
        self.mes = mes_url

    def collect_equipment_data(self, equipment_id: str, window_days: int) -> dict:
        """Collect and align multi-source data for ML model training."""
        vibration = self.historian.query(
            equipment_id, signal="vibration_rms", window_days=window_days, resample="1min"
        )
        temperature = self.historian.query(
            equipment_id, signal="bearing_temp_c", window_days=window_days, resample="1min"
        )
        current = self.historian.query(
            equipment_id, signal="motor_current_a", window_days=window_days, resample="1min"
        )
        failures = self.mes.query_work_orders(
            equipment_id, type="breakdown", window_days=window_days
        )
        # Align timestamps and merge
        merged = self.time_align_and_merge([vibration, temperature, current])
        merged["failure_labels"] = self.label_pre_failure_windows(merged, failures, window_hours=24)
        return merged
```

### Step 2: Feature Engineering

```python
# Feature extraction for predictive maintenance
import numpy as np

class PdMFeatureEngineer:
    def extract_features(self, raw_data: dict, window_size: int = 60) -> dict:
        """Extract statistical and domain features from raw sensor data."""
        features = {}
        for signal_name, signal_data in raw_data.items():
            if signal_name.startswith("_"):
                continue
            window = signal_data[-window_size:]
            features[f"{signal_name}_mean"] = np.mean(window)
            features[f"{signal_name}_std"] = np.std(window)
            features[f"{signal_name}_max"] = np.max(window)
            features[f"{signal_name}_min"] = np.min(window)
            features[f"{signal_name}_rms"] = np.sqrt(np.mean(np.square(window)))
            features[f"{signal_name}_kurtosis"] = self.kurtosis(window)
            features[f"{signal_name}_trend"] = np.polyfit(range(len(window)), window, 1)[0]
            # Frequency domain features
            fft = np.fft.rfft(window)
            features[f"{signal_name}_peak_freq_hz"] = np.argmax(np.abs(fft))
            features[f"{signal_name}_spectral_energy"] = np.sum(np.abs(fft) ** 2)
        return features

    def kurtosis(self, data):
        n = len(data)
        mean = np.mean(data)
        std = np.std(data)
        if std == 0:
            return 0
        return np.sum(((data - mean) / std) ** 4) / n - 3
```

### Step 3: Remaining Useful Life Model

```python
# RUL prediction model
class RULPredictor:
    def __init__(self, model_type: str = "gradient_boosting"):
        self.model_type = model_type
        self.model = None

    def train(self, training_data, labels):
        """Train RUL prediction model on historical run-to-failure data."""
        from sklearn.ensemble import GradientBoostingRegressor
        self.model = GradientBoostingRegressor(
            n_estimators=300,
            max_depth=6,
            learning_rate=0.05,
            loss="huber",
        )
        self.model.fit(training_data, labels)

    def predict_rul(self, current_features: dict) -> dict:
        """Predict remaining useful life from current sensor features."""
        rul_hours = self.model.predict([list(current_features.values())])[0]
        confidence = self.estimate_confidence(current_features)
        return {
            "predicted_rul_hours": max(0, round(rul_hours, 0)),
            "confidence_pct": round(confidence * 100, 1),
            "alert_level": self.classify_urgency(rul_hours),
            "recommended_action": self.recommend_action(rul_hours),
        }

    def classify_urgency(self, rul_hours: float) -> str:
        if rul_hours < 24:
            return "critical"
        elif rul_hours < 168:  # 1 week
            return "warning"
        elif rul_hours < 720:  # 1 month
            return "plan"
        return "normal"

    def recommend_action(self, rul_hours: float) -> str:
        if rul_hours < 24:
            return "schedule_immediate_maintenance_next_shift_break"
        elif rul_hours < 168:
            return "schedule_maintenance_next_planned_downtime"
        return "continue_monitoring"
```

### Step 4: Throughput Prediction

```python
# Production throughput forecasting
class ThroughputForecaster:
    def predict_shift_output(self, historical_data, current_state: dict) -> dict:
        """Predict shift output based on current equipment state and history."""
        base_capacity = historical_data["avg_vehicles_per_shift"]
        adjustments = {
            "equipment_health": self.equipment_factor(current_state["oee_current"]),
            "quality_rate": current_state["quality_rate"],
            "planned_downtime": 1 - (current_state["planned_stops_min"] / 480),
            "model_mix": self.model_mix_factor(current_state["variant_schedule"]),
        }
        predicted = base_capacity
        for factor_name, factor_value in adjustments.items():
            predicted *= factor_value
        return {
            "predicted_output": round(predicted),
            "confidence_interval": [round(predicted * 0.95), round(predicted * 1.05)],
            "limiting_factor": min(adjustments, key=adjustments.get),
            "suggested_action": self.suggest_improvement(adjustments),
        }
```

### Step 5: Dashboard and Alerting

```yaml
predictive_dashboard:
  equipment_health_view:
    - equipment_id: robot_cell_01
      health_score: 87
      rul_hours: 340
      alert_level: plan
      top_risk: gearbox_axis_2_vibration_trend
  throughput_forecast:
    - shift: day_shift_2026_03_19
      predicted_output: 312
      target: 320
      gap_reason: paint_booth_3_color_change_delay
  quality_prediction:
    - station: weld_station_15
      defect_risk_score: 0.15
      risk_factor: electrode_wear_at_85pct
      action: schedule_electrode_change_at_break
  energy_forecast:
    - period: next_4_hours
      predicted_kw: 2850
      peak_threshold_kw: 3000
      action: stagger_press_line_starts
```


## Best Practices

- Start with equipment that has highest downtime cost and sufficient sensor data
- Require minimum 3 run-to-failure cycles for supervised RUL model training
- Use anomaly detection (unsupervised) when failure data is insufficient
- Validate model predictions against actual failures for at least 3 months before trusting
- Integrate predictive alerts with CMMS for automatic work order generation
- Retrain models quarterly as equipment ages and operating conditions change
- Show maintenance technicians the data behind predictions to build trust
- Track prediction accuracy KPIs: precision, recall, lead time of true positive alerts


## Common Patterns

### Predictive Maintenance Implementation Sequence

```
Month 1-2:  Instrument top 10 critical machines with vibration and temperature
Month 3-4:  Collect baseline data, establish normal operating profiles
Month 5-6:  Train initial anomaly detection models (unsupervised)
Month 7-9:  Deploy alerts to maintenance team, collect feedback
Month 10-12: Train supervised RUL models as failure data accumulates
Year 2+:    Scale to 50+ machines, integrate with CMMS and scheduling
```

### Model Selection by Data Availability

```
Data Availability         Recommended Model         Training Data
====================      ====================      =============
Many run-to-failure       Gradient Boosting RUL     Labeled lifecycle data
Few failures, many sensors  Anomaly detection       Normal operation only
Time series patterns      LSTM / Temporal CNN       Sequential sensor data
Known physics model       Physics-informed ML       Hybrid simulation+data
No historical data        Rule-based thresholds     Expert knowledge
```


## Troubleshooting

- **Too many false alarms**: Increase alert threshold, require sustained anomaly signal
- **Missed failure prediction**: Check sensor coverage, add relevant signals
- **Model accuracy degrades over time**: Implement automated drift detection, schedule retraining
- **Insufficient failure data for training**: Use transfer learning from similar equipment types
- **Maintenance team ignores alerts**: Show prediction accuracy scorecard, reduce false positive rate
- **Data quality issues**: Validate sensor health, implement data quality checks in pipeline

### rapid-tooling

# Rapid Tooling for Automotive Manufacturing

## Overview
Rapid tooling compresses the traditional 20-40 week tooling lead time for automotive
production tools into 2-8 weeks using additive manufacturing, soft materials, and
digital simulation. This enables faster prototype validation, quicker model changeovers,
and reduced capital expenditure for low-to-medium volume production. Three categories
apply: direct 3D-printed tools for production, bridge tools in soft material for
pre-series, and conformal cooling inserts combining AM metal with conventional bodies.

## Key Concepts

### Tooling Categories and Capabilities
Each tooling approach serves a different volume and accuracy range:

- Production hard tool steel P20: 500K+ parts, 20-40 weeks lead, 0.02mm accuracy
- Soft bridge aluminum 7075: 5K-50K parts, 6-10 weeks lead, 0.05mm accuracy
- Kirksite zinc alloy: 500-5K parts, 3-6 weeks lead, 0.10mm accuracy
- 3D printed maraging steel: 100-5K parts, 1-3 weeks lead, 0.05mm accuracy
- 3D printed nylon carbon: 10-500 parts, 1-5 days lead, 0.10mm accuracy

### AM Technologies for Tooling
- DMLS/SLM: Metal laser sintering for steel and aluminum tool inserts
- Binder Jetting: Sand molds for casting and metal tools at lower cost
- FDM/FFF: Large-format polymer fixtures and checking aids
- SLA/DLP: High-accuracy resin patterns for investment casting
- WAAM: Wire arc additive for large-scale die repair and hybrid tools

## Implementation Guide

### Step 1 - Tooling Strategy Selection
Select the optimal approach based on volume, tolerance, and timeline requirements.

```python
class ToolingStrategySelector:
    def recommend(self, requirements: dict) -> dict:
        """Select optimal tooling strategy based on requirements."""
        volume = requirements["annual_volume"]
        lead_time_weeks = requirements["max_lead_time_weeks"]

        if lead_time_weeks <= 1 and volume < 500:
            return {
                "strategy": "FDM_nylon_carbon_filled",
                "lead_time_weeks": 0.5,
                "tool_life_parts": 500,
                "accuracy_mm": 0.10,
                "post_processing": ["insert_metal_bushings", "bond_wear_pads"],
            }
        elif lead_time_weeks <= 3 and volume < 5000:
            return {
                "strategy": "DMLS_maraging_steel",
                "lead_time_weeks": 2,
                "tool_life_parts": 5000,
                "accuracy_mm": 0.05,
                "post_processing": ["stress_relief", "CNC_finishing", "polishing"],
            }
        elif lead_time_weeks <= 8 and volume < 50000:
            return {
                "strategy": "aluminum_7075_soft_tool",
                "lead_time_weeks": 7,
                "tool_life_parts": 50000,
                "accuracy_mm": 0.05,
                "post_processing": ["CNC_machining", "hard_anodize"],
            }
        return {
            "strategy": "P20_production_hard_tool",
            "lead_time_weeks": 30,
            "tool_life_parts": 500000,
            "accuracy_mm": 0.02,
            "post_processing": ["heat_treat", "CNC_finish", "EDM", "polish"],
        }
```

### Step 2 - Conformal Cooling Insert Design
Design AM cooling channels that follow part surface geometry for uniform cooling.

```python
class ConformalCoolingDesigner:
    def design_channels(self, hot_spots: list) -> dict:
        """Design conformal cooling channels for injection mold inserts."""
        channels = []
        for spot in hot_spots:
            wall_t = spot["wall_thickness"]
            diameter = max(3.0, min(12.0, wall_t * 1.8))
            channels.append({
                "diameter_mm": diameter,
                "offset_from_surface_mm": wall_t * 2.0,
                "pitch_mm": diameter * 3.0,
                "flow_rate_lpm": spot["heat_load_w"] / 4180,
            })
        return {
            "channels": channels,
            "expected_cycle_reduction_pct": 25,
            "cooling_uniformity_improvement_pct": 40,
            "manufacturing_method": "DMLS_maraging_steel_insert",
        }
```

### Step 3 - Bridge Tooling Launch Sequence
Use bridge tooling to start production while hard tools are being built:

```
Week 1-2:  3D print prototype tools for part validation
Week 3-4:  Kirksite or aluminum bridge tooling for pre-series of 500 parts
Week 5-20: Production hard tooling under construction in parallel
Week 8-12: Bridge tooling supports initial customer shipments
Week 20+:  Transition to production tooling, retire bridge tools
```

### Step 4 - AM Fixture ROI Calculation
Justify investment with direct cost and schedule comparisons:

```
Conventional fixture: $5,000 cost + 6 weeks lead time
3D-printed fixture:   $800 cost + 3 days lead time
Savings per fixture:  $4,200 + 39 days schedule compression
Fixtures per plant:   500-2,000
Annual savings:       $2.1M-$8.4M plus massive schedule improvement
```

## Best Practices
- Always validate 3D-printed tooling with first-article dimensional inspection
- Use topology optimization to reduce fixture weight for robot-mounted applications
- Design modular fixtures with swappable nests for multi-variant production
- Apply wear-resistant coatings like DLC or TiN to AM metal tools at contact surfaces
- Maintain a digital library of fixture designs for reuse across model programs
- Insert threaded metal bushings into polymer fixtures for clamping durability
- Run forming simulation before cutting steel to avoid costly tool rework
- Track tool life by shot count to plan preventive replacement before failure

## Troubleshooting
- 3D-printed fixture warps under load: Increase infill density to 60 percent
  minimum and add carbon fiber reinforcement at stress concentration points
- Conformal cooling channel blockage: Design self-draining channel paths with
  minimum 3mm diameter and flush thoroughly after printing
- Surface finish insufficient for forming tool: Post-machine AM surfaces to
  required Ra values and polish cavity areas for part release
- Soft tooling wears faster than expected: Apply hard chrome plating or nitriding
  treatment to extend tool life by 3-5x for aluminum tools
- Dimensional drift in AM metal tools: Stress relieve printed parts at 600C
  for 2 hours before performing any finish machining operations
- Topology-optimized fixture too fragile: Set minimum wall thickness constraint
  of 3mm in optimizer and validate with FEA under worst-case loading

### resilient-supply-chain

# Resilient Supply Chain Design

## Overview
Modern automotive supply chains span 4-8 tiers across 30+ countries with thousands
of unique part numbers per vehicle. A single disruption from semiconductor shortages,
port closures, natural disasters, or geopolitical conflict can halt entire production
lines within days. Resilient supply chain design builds redundancy, visibility, and
agility into supplier networks to maintain production continuity under stress.

## Key Concepts

### Supply Chain Risk Categories
Risks are classified into four tiers requiring independent assessment:

- Tier 1 risks: Direct supplier failures including bankruptcy, quality escapes, capacity shortfalls
- Tier 2 risks: Sub-tier material shortages such as semiconductor wafers and rare earth minerals
- Tier 3 risks: Logistics disruptions from port closures, carrier failures, route blockages
- Tier 4 risks: Systemic events including pandemics, trade wars, and regulatory changes

### Multi-Source Strategy Matrix
Classify every component by criticality and availability:

- Critical + Scarce: Triple-source with safety stock and long-term contracts
- Critical + Available: Dual-source with qualified backup suppliers
- Non-critical + Scarce: Dual-source with design-for-substitution
- Non-critical + Available: Single-source with monitored backup options

### Supplier Health Scoring
Continuously monitor supplier viability using weighted composite scoring across
financial stability, quality performance, delivery reliability, geographic risk,
and capacity utilization dimensions.

## Implementation Guide

### Step 1 - Map the Current Supply Network
Document every supplier relationship down to tier 3 minimum. Identify single
points of failure and geographic concentration zones.

```python
from dataclasses import dataclass, field

@dataclass
class SupplierNode:
    supplier_id: str
    name: str
    region: str
    tier: int
    components: list[str] = field(default_factory=list)
    alternate_suppliers: list[str] = field(default_factory=list)
    risk_score: float = 0.0
    lead_time_days: int = 0

@dataclass
class SupplyChainMap:
    nodes: dict[str, SupplierNode] = field(default_factory=dict)

    def find_single_points_of_failure(self) -> list[str]:
        """Identify components with only one qualified supplier."""
        component_suppliers: dict[str, list[str]] = {}
        for node in self.nodes.values():
            for component in node.components:
                if component not in component_suppliers:
                    component_suppliers[component] = []
                component_suppliers[component].append(node.supplier_id)
        return [
            comp for comp, suppliers in component_suppliers.items()
            if len(suppliers) == 1
        ]
```

### Step 2 - Establish Risk Monitoring
Deploy automated monitoring that tracks supplier health indicators and triggers
alerts when thresholds are breached.

```python
ALERT_THRESHOLDS = {
    "health_score_critical": 40.0,
    "health_score_warning": 60.0,
    "lead_time_increase_pct": 25.0,
    "quality_reject_rate_pct": 2.0,
}

def evaluate_supplier_alerts(
    supplier_id: str,
    current_metrics: dict,
) -> list[dict]:
    """Generate alerts when supplier metrics breach thresholds."""
    alerts = []
    health = current_metrics.get("health_score", 100.0)
    if health < ALERT_THRESHOLDS["health_score_critical"]:
        alerts.append({
            "level": "CRITICAL",
            "supplier": supplier_id,
            "message": f"Health score {health} below critical threshold",
        })
    elif health < ALERT_THRESHOLDS["health_score_warning"]:
        alerts.append({
            "level": "WARNING",
            "supplier": supplier_id,
            "message": f"Health score {health} below warning threshold",
        })
    return alerts
```

### Step 3 - Disruption Response Playbook
For each critical component, document step-by-step recovery actions:

```
Hour 0-4:   Detect via control tower alert or supplier notification
Hour 4-24:  Assess inventory levels, production impact, alternative sources
Day 1-3:    Contain by expediting shipments, activating safety stock
Day 3-14:   Recover by qualifying alternatives, air freight, production replan
Day 14+:    Normalize by replenishing stock, updating risk assessment
```

### Step 4 - Build Contingency Contracts
Pre-negotiate capacity reservation agreements with backup suppliers. Include
volume flexibility clauses allowing plus or minus 20 percent adjustments.
Maintain qualification status for at least two suppliers per critical component.

## Best Practices
- Maintain at least 2 qualified suppliers for every safety-critical component
- Conduct quarterly business reviews with tier 1 suppliers
- Run annual supply chain stress tests simulating major disruption scenarios
- Keep 4-8 weeks of safety stock for components with lead times over 12 weeks
- Require tier 1 suppliers to disclose their own sub-tier dependencies
- Diversify geographically so no single region supplies more than 40 percent of parts
- Integrate supplier financial monitoring feeds for early bankruptcy warning
- Share demand forecasts with tier 2 and tier 3 to reduce bullwhip effect
- Standardize components across platforms to increase sourcing flexibility

## Troubleshooting
- Supplier refuses to disclose sub-tier sources: Make transparency a contractual
  requirement during qualification, offer NDA protection for sensitive relationships
- Cost increase from multi-sourcing: Quantify the cost of single-source disruption
  in lost production days times daily revenue to justify the 3-8 percent premium
- Quality variation between alternate suppliers: Implement identical incoming
  inspection criteria and PPAP requirements, conduct regular correlation studies
- Lead time data is unreliable: Deploy automated shipment tracking integrated with
  supplier ERP systems, calculate rolling averages from actual receipt data
- Geopolitical risk changes rapidly: Subscribe to real-time risk feeds from
  services like Everstream or Resilinc for continuous country risk monitoring
- Safety stock cost objections: Present production downtime cost per hour versus
  holding cost analysis to justify buffer investment

### robot-programming-industrial

## Core Competencies

Expert in industrial robot programming for automotive body shop, paint shop, and assembly applications across all major robot platforms with expertise in offline programming and cycle optimization.

### Robot Platforms

- **ABB**: RAPID programming language, RobotStudio offline programming, IRC5 controller
- **KUKA**: KRL (KUKA Robot Language), KUKA.Sim offline, KRC4 controller
- **FANUC**: KAREL and TP (Teach Pendant) programming, ROBOGUIDE offline, R-30iB controller
- **Yaskawa/Motoman**: INFORM language, MotoSim offline programming
- **Universal Robots**: URScript, PolyScope GUI, cobot-specific programming

### Programming Methods

- **Teach pendant**: Manual jogging and point recording (online programming)
- **Offline programming (OLP)**: CAD-based simulation (RobotStudio, KUKA.Sim, ROBOGUIDE)
- **Lead-through programming**: Physical guidance for cobots and paint robots
- **CAD-to-path**: Automatic trajectory generation from part geometry
- **Vision-guided programming**: Integrate 2D/3D cameras for adaptive positioning

### Motion Types

- **PTP (Point-to-Point)**: Joint space motion, fastest but non-linear path
- **Linear (LIN)**: Straight-line Cartesian motion, for welding and sealing
- **Circular (CIRC)**: Arc interpolation, for rounded seam following
- **Spline**: Smooth continuous path through multiple waypoints
- **Weaving**: Oscillating motion for wider weld bead or search patterns

### Spot Welding Programming

- **Gun approach**: Safe approach vector, tip dress clearance, adaptive tip wear compensation
- **Weld schedule**: Current, time, force parameters communicated to weld controller
- **Positioning accuracy**: ±0.5mm for electrode alignment on flanges
- **Cycle time optimization**: Minimize air moves, optimize approach angles, parallel gripper close
- **Quality monitoring**: Weld nugget size verification, expulsion detection, adaptive control

### Path Planning

- **Collision avoidance**: Tool, robot arm, and cell fixture interference checking
- **Singularity avoidance**: Prevent wrist flip and elbow-up/down transitions
- **Reachability analysis**: Verify all points within robot workspace considering joint limits
- **Speed optimization**: Increase speed in free space, reduce near obstacles and teach points
- **Smoothing**: Blend radii (FANUC CNT), zone accuracy (ABB), rounding (KUKA) for continuous motion

### Coordinate Systems

- **World (base) frame**: Fixed reference for cell layout
- **Tool frame (TCP)**: Tool center point with orientation, calibrated via 4-point method
- **User frames (workobjects)**: Part-specific coordinates, shift for left/right body sides
- **Fixture offsets**: Compensate for part locator position variation
- **External axes**: Positioner, track, turntable coordination with robot motion

## Approach

1. **Process Analysis**: Understand weld points, sealing paths, assembly sequence from engineering data
2. **Cell Layout**: Position robot(s), fixtures, part feeders considering reach and interference
3. **Offline Programming**: Create robot program in simulation, validate all motions collision-free
4. **TCP Calibration**: Measure actual tool dimensions and mass properties on physical robot
5. **Workobject Teaching**: Locate part coordinate systems via touch-up or vision reference
6. **Dry Run**: Execute program at 10-25% speed with safety door open, verify paths
7. **Cycle Optimization**: Reduce air moves, increase blend radii, parallelize I/O operations
8. **Production Run**: Monitor cycle time, joint utilization, error rates for continuous tuning

## Deliverables

- Robot programs (RAPID, KRL, TP, INFORM) with documented logic and safety zones
- Offline simulation video showing collision-free operation and cycle time
- TCP calibration data and workobject definitions for production use
- Cycle time breakdown (motion time, process time, I/O wait time)
- Reachability and singularity analysis reports
- Safety zone definitions (restricted spaces, speed limits per ISO 10218)
- Backup and version control of robot programs and cell configuration

## Best Practices

- Use named constants for speeds, accelerations, and I/O signals (avoid magic numbers)
- Implement error handling routines (weld gun stuck, part not present, vision lost)
- Add recovery positions in program to allow restart after faults
- Document all coordinate frames and measurement procedures for reproducibility
- Version control robot programs with meaningful commit messages
- Test all error branches (part missing, sensor failure, e-stop recovery)
- Maintain consistent naming conventions across multi-robot cells

## Safety Considerations

- Define safety zones (restricted, warning, operating) per ISO 10218-1
- Implement speed and separation monitoring for collaborative operation (ISO/TS 15066)
- Program safe home positions outside operator reach for maintenance mode
- Add enabling device interlocks for teach pendant operation
- Emergency stop behavior: stop category 0 (immediate power removal) vs category 1 (controlled stop)
- Risk assessment per ISO 12100 for all human-robot interaction scenarios

## Integration with Automotive Workflow

- Interface with weld controllers (Bosch, ARO, TECNA) via digital I/O or fieldbus
- Communicate with PLC for part present sensors, fixture clamps, conveyors
- Log production data (cycle count, weld quality, fault codes) to MES via OPC UA
- Support AUTOSAR-based manufacturing systems with standardized data models
- Enable remote monitoring and program updates for multi-plant standardization

### scada-hmi-factory

## Core Competencies

Expert in SCADA/HMI system architecture for automotive manufacturing with expertise in high-performance visualization, alarm management, historian databases, and ISA-101 design standards.

### SCADA Platforms

- **Siemens WinCC**: Integrated with TIA Portal, PROFINET native, scalable to 100K+ tags
- **Rockwell FactoryTalk View**: SE (distributed) vs ME (standalone), Logix integration
- **Ignition by Inductive Automation**: Unlimited tags, web-based, SQL/historian built-in
- **GE iFIX**: Legacy but proven, VBA scripting, wide protocol support
- **Wonderware System Platform**: Object-oriented, InTouch HMI, Historian

### ISA-101 HMI Design Principles

- **Situational awareness**: Operators see normal vs abnormal state at a glance
- **High-performance graphics**: Minimal color (gray background), use color for alarms only
- **Alarm philosophy**: Reduce nuisance alarms, prioritize by consequence (critical, high, medium, low)
- **Navigation**: Max 3 clicks to any screen, consistent layout across all views
- **Trending**: Embed real-time trends on process screens for quick analysis

### Screen Hierarchy

- **Level 1 (Overview)**: Entire line or plant status, KPIs, alarm summary
- **Level 2 (Process Area)**: Detailed view of one production zone (e.g., body shop)
- **Level 3 (Equipment Detail)**: Individual machine control and diagnostics
- **Level 4 (Faceplate)**: Motor control, valve control with start/stop buttons
- **Supporting screens**: Alarms, trends, reports, recipes, user management

### Historian Databases

- **Time-series databases**: Optimized for high-frequency (1 sec) sensor data storage
- **Compression**: Store by exception (deadband) to reduce storage (10:1 typical)
- **Platforms**: OSIsoft PI, Wonderware Historian, Ignition Historian, InfluxDB
- **Queries**: Aggregations (min, max, avg), interpolation for missing data, downsampling
- **Integration**: Export to Excel, Power BI, Tableau for advanced analytics

### Alarm Management (ISA-18.2)

- **Alarm philosophy**: Document each alarm with priority, consequence, response
- **Rationalization**: Reduce alarm flood (<10 alarms per 10 min per operator)
- **Priority levels**: Critical (safety/environmental), high (quality/production loss), medium, low
- **States**: Unacknowledged, acknowledged, shelved (temporary suppression)
- **Metrics**: Alarms per day, peak rate, time-to-acknowledge, repeat alarms

### Communication Protocols

- **OPC UA**: Unified architecture for PLC, SCADA, MES, cloud connectivity
- **OPC DA (Classic)**: Legacy but widely deployed, COM/DCOM dependencies
- **Modbus TCP/RTU**: Simple protocol for legacy PLCs and instruments
- **Ethernet/IP**: Allen-Bradley native, CIP-based
- **MQTT**: Lightweight publish/subscribe for IoT edge devices

### Automotive Applications

- **Body shop**: Weld gun monitoring, robot status, part tracking, downtime tracking
- **Paint shop**: Oven temperature profiles, humidity, paint viscosity, color changeover
- **Assembly**: Takt time monitoring, andon status, torque tool results, quality gates
- **Utilities**: Compressed air pressure, HVAC, energy consumption, water treatment

## Approach

1. **Requirements**: Define tags, screens, alarms, reports, user roles with stakeholders
2. **Tag Database Design**: Structure tags hierarchically (area.line.equipment.parameter)
3. **Graphics Development**: Create reusable objects (motors, valves, tanks) per ISA-101
4. **Alarm Configuration**: Rationalize alarms, set priorities, define responses
5. **Historian Setup**: Configure trending, storage policies, aggregations
6. **Network Architecture**: Separate control network from IT network (DMZ for OPC)
7. **Testing**: FAT (Factory Acceptance Test) with simulated I/O, SAT (Site Acceptance Test)
8. **Training**: Operator training on navigation, alarm response, trend interpretation

## Deliverables

- SCADA system architecture diagram (servers, clients, PLCs, network topology)
- Tag database with structured naming convention and documentation
- HMI graphics library with reusable objects and templates
- Alarm database with philosophy document and prioritization
- Historian configuration with retention policies and trending templates
- User manual with screen navigation, alarm response procedures
- Cybersecurity hardening (firewall rules, user authentication, audit logging)

## Best Practices

- Use gray backgrounds and limit colors (green=run, red=fault, yellow=warning)
- Avoid animation (blinking, rotating) except for critical alarms
- Display KPIs prominently (OEE, takt time, units per hour) on overview screens
- Implement role-based access control (operator view-only, engineer edit)
- Log all operator actions (setpoint changes, manual overrides) for traceability
- Test alarm floods (simulate multiple failures) to validate operator response capability
- Implement redundant SCADA servers for high-availability critical systems

## Integration with Automotive Workflow

- Provide real-time production data to MES for scheduling and material planning
- Interface with energy management systems for demand response and cost reduction
- Export historian data to data lake (Azure, AWS) for advanced analytics and ML
- Support remote troubleshooting with secure VPN access for engineering
- Enable digital twin synchronization with real-time equipment state updates

### six-sigma-quality

# Six Sigma Quality for Automotive Manufacturing

## Overview
Six Sigma is a data-driven methodology for eliminating defects and reducing
variation in manufacturing processes. In automotive production, Six Sigma
achieves the tight tolerances required for safety-critical components.

## DMAIC Methodology

### Define Phase
- Create project charter with business case and scope
- Define CTQ (Critical to Quality) characteristics
- Map current process with SIPOC diagram
- Establish baseline sigma level

### Measure Phase
- Validate measurement system (MSA / Gage R&R)
- Collect baseline data on key metrics
- Calculate process capability (Cp, Cpk)
- Determine current DPMO and sigma level

### Analyze Phase
- Identify potential root causes with fishbone diagrams
- Perform hypothesis testing (t-test, chi-square, ANOVA)
- Regression analysis for factor relationships
- Multi-vari analysis to isolate variation sources

### Improve Phase
- Design of Experiments (DOE) to optimize factors
- Pilot improvements with controlled runs
- Validate improvement with statistical significance
- Update process documentation and control plans

### Control Phase
- Implement Statistical Process Control (SPC) charts
- Create control plans and response procedures
- Train operators on new standard work
- Monitor and sustain improvements

## Implementation Guide

### Process Capability Analysis (Python)

```python
import numpy as np
from scipy import stats

def calculate_capability(data, usl, lsl):
    mean = np.mean(data)
    std = np.std(data, ddof=1)

    cp = (usl - lsl) / (6 * std)
    cpu = (usl - mean) / (3 * std)
    cpl = (mean - lsl) / (3 * std)
    cpk = min(cpu, cpl)

    dpmo = (1 - stats.norm.cdf(cpk * 3)) * 1_000_000 * 2
    sigma_level = stats.norm.ppf(1 - dpmo / 1_000_000) + 1.5

    return {
        "Cp": round(cp, 3),
        "Cpk": round(cpk, 3),
        "DPMO": round(dpmo, 1),
        "Sigma": round(sigma_level, 2)
    }
```

### SPC Control Chart

```python
def xbar_r_chart(subgroups):
    means = [np.mean(sg) for sg in subgroups]
    ranges = [max(sg) - min(sg) for sg in subgroups]
    n = len(subgroups[0])

    xbar = np.mean(means)
    rbar = np.mean(ranges)

    A2 = {2: 1.880, 3: 1.023, 4: 0.729, 5: 0.577}

    ucl = xbar + A2[n] * rbar
    lcl = xbar - A2[n] * rbar

    return {"UCL": ucl, "CL": xbar, "LCL": lcl}
```

## Best Practices
- Validate measurement systems before collecting data
- Use practical significance alongside statistical significance
- Engage operators and technicians in root cause analysis
- Target Cpk of 1.67+ for safety-critical characteristics
- Document lessons learned for future projects

## Common Automotive Applications
- Torque specification compliance on assembly lines
- Weld quality in body shop (nugget diameter, penetration)
- Paint thickness uniformity across vehicle panels
- Dimensional accuracy of machined engine components
- Electrical continuity in wiring harness assembly

## Troubleshooting
- Low Cpk despite good Cp indicates process centering issue
- Non-normal data requires transformation before capability analysis
- Excessive measurement variation masks true process capability
- Special cause variation must be eliminated before SPC is effective

### spc-quality-control

## Core Competencies

Expert in statistical process control implementation for automotive manufacturing with deep knowledge of control charts, capability analysis, measurement systems analysis, and quality improvement methodologies.

### Control Chart Types

- **X-bar and R chart**: Monitor process mean and range for variable data (dimensions, weights)
- **X-bar and S chart**: Mean and standard deviation (preferred for subgroup n ≥10)
- **I-MR chart**: Individual measurements and moving range (slow processes, destructive testing)
- **P chart**: Proportion defective for attribute data (visual inspections)
- **U chart**: Defects per unit when opportunity for defects varies
- **EWMA (Exponentially Weighted Moving Average)**: Detect small process shifts quickly

### Control Limits

- **Upper Control Limit (UCL) = X̄ + A₂R̄** (for X-bar chart)
- **Lower Control Limit (LCL) = X̄ - A₂R̄**
- **UCL(R) = D₄R̄, LCL(R) = D₃R̄** (for R chart)
- **A₂, D₃, D₄**: Constants from SPC tables based on subgroup size
- **±3σ limits**: Capture 99.73% of variation if process is in control

### Control Chart Interpretation

- **Out of control signals**: Point beyond control limits, 8 consecutive points one side of center
- **Trends**: 6 points steadily increasing or decreasing (tool wear, temperature drift)
- **Runs**: 9 points in a row on same side of center line (process shift)
- **Cycles**: Repeated up-and-down pattern (operator rotation, material batches)
- **Stratification**: Points too close to center line (mixed populations, incorrect subgrouping)

### Process Capability

- **Cp = (USL - LSL) / 6σ**: Potential capability (assumes centered process)
- **Cpk = min[(USL - μ)/3σ, (μ - LSL)/3σ]**: Actual capability accounting for centering
- **Pp and Ppk**: Long-term performance vs short-term capability
- **Automotive requirement**: Cpk ≥1.33 (4σ quality), world-class Cpk ≥1.67 (5σ)
- **Sigma level**: Cpk 1.67 = 5σ = 233 DPMO (defects per million opportunities)

### Measurement Systems Analysis (MSA)

- **GR&R (Gage Repeatability & Reproducibility)**: <10% of tolerance acceptable, <30% marginal
- **Repeatability**: Equipment variation (same operator, same part, multiple measurements)
- **Reproducibility**: Operator variation (different operators, same part)
- **Linearity**: Accuracy across measurement range (small vs large parts)
- **Stability**: Measurement drift over time (calibration frequency)

### Variation Sources

- **Common cause**: Inherent process variation (random, always present)
- **Special cause**: Assignable variation (tool breakage, material change, operator error)
- **Goal**: Eliminate special causes, then reduce common cause variation
- **5M1E causes**: Man, Machine, Material, Method, Measurement, Environment

## Approach

1. **Define Critical Characteristics**: Identify key dimensions, strength, appearance per control plan
2. **Measurement System Validation**: Conduct GR&R study to ensure measurement capability
3. **Data Collection Plan**: Subgroup size (n=3-5), frequency (every hour, every 25 parts)
4. **Baseline Capability Study**: Collect 100+ measurements to calculate Cp/Cpk
5. **Control Chart Implementation**: Set up real-time charts with automated data collection
6. **Reaction Plan**: Document actions for out-of-control signals (stop line, adjust, rework)
7. **Continuous Monitoring**: Review charts daily, investigate trends, update limits quarterly
8. **Improvement Projects**: Use DMAIC when Cpk <1.33 to reduce variation

## Deliverables

- Control plan documenting characteristics, sample size, frequency, control methods
- GR&R study results demonstrating <10% measurement variation
- Control charts (X-bar/R, I-MR, P) with control limits and reaction plans
- Process capability study report with Cp, Cpk, Pp, Ppk calculations
- PPAP package including capability studies for customer approval
- SPC training materials for operators and quality technicians
- Pareto analysis of defect types and root causes

## Best Practices

- Use rational subgrouping to maximize variation between subgroups, minimize within
- Recalculate control limits after process improvements (document version changes)
- Automate data collection from gages, CMMs, vision systems to reduce transcription errors
- Display control charts on shop floor for operator real-time visibility
- Investigate all special cause signals even if part is in tolerance
- Combine SPC with visual management (andon, color-coded status boards)
- Integrate SPC software with MES for automatic data pull and charting

## Integration with Automotive Workflow

- Provide capability data for APQP (Advanced Product Quality Planning)
- Support PPAP submissions with control charts and capability studies
- Interface with MES to trigger alarms when process goes out of control
- Feed quality data to CAPA (Corrective and Preventive Action) system
- Enable supplier quality management with web portals for SPC data sharing

### structural-battery-pack

## Overview

Structural battery packs represent a paradigm shift in EV manufacturing where the battery
enclosure is no longer a bolt-on component but an integral load-bearing element of the
vehicle body structure. This eliminates redundant structural material, reduces weight by
10-20%, increases battery volume by 15-25%, and fundamentally changes manufacturing
processes from traditional body-in-white plus battery assembly to integrated structural
battery production.

The manufacturing challenges are significant: structural adhesives must simultaneously
bond cells, transfer crash loads, conduct heat, and remain serviceable. Dimensional
tolerances tighten because the battery IS the floor structure. And crash safety validation
becomes more complex when energy storage and structural integrity are combined.


## Key Concepts

### Architecture Comparison

```
Traditional:    Cell -> Module -> Pack -> Bolted to body floor
CTP:            Cell -> Pack (no module) -> Bolted to body floor
CTB:            Cell -> Structural pack = Body floor structure
CTC:            Cell -> Directly integrated into body casting (emerging)

Weight savings:     CTP: 5-10%    CTB: 15-20%    CTC: 20-25% (theoretical)
Volume efficiency:  CTP: 65-70%   CTB: 70-80%    CTC: 80%+ (theoretical)
Serviceability:     CTP: Good     CTB: Limited    CTC: Very limited
```

### Structural Load Paths

- **Bending**: Pack acts as sandwich panel floor (cells = core, skins = enclosure top/bottom)
- **Torsion**: Adhesive bonds transfer shear between cells and enclosure walls
- **Side impact**: Pack cross-members and cell arrangement absorb lateral crash energy
- **Front/rear crash**: Pack connects to front and rear body structures through mounting
- **Fatigue**: Road loads cycle through pack structure over vehicle lifetime (10+ years)

### Key Manufacturing Processes

- **Tray manufacturing**: Aluminum casting or extrusion with CNC machining
- **Cell insertion**: Automated pick-and-place with vision-guided alignment
- **Structural bonding**: Robotic adhesive dispensing (PU, epoxy, silicone structural)
- **TIM application**: Thermal pad placement or gap filler dispensing
- **Busbar welding**: Laser or ultrasonic welding for cell interconnection
- **Sealing**: Structural sealant and gasket for IP67 water protection
- **Leak testing**: Helium leak detection or pressure decay testing


## Implementation Guide

### Step 1: Battery Tray Manufacturing

```python
# Battery tray dimensional control
class BatteryTrayManufacturing:
    FLATNESS_TOLERANCE_MM = 0.5
    POSITION_TOLERANCE_MM = 0.3
    MOUNTING_HOLE_TOLERANCE_MM = 0.1

    def validate_tray(self, measurement_data: dict) -> dict:
        """Validate battery tray against structural and dimensional specs."""
        results = {
            "flatness": {
                "measured_mm": measurement_data["flatness_mm"],
                "tolerance_mm": self.FLATNESS_TOLERANCE_MM,
                "pass": measurement_data["flatness_mm"] <= self.FLATNESS_TOLERANCE_MM,
            },
            "cell_pocket_depth": {
                "measured_mm": measurement_data["pocket_depth_mm"],
                "nominal_mm": measurement_data["pocket_nominal_mm"],
                "tolerance_mm": 0.2,
                "pass": abs(measurement_data["pocket_depth_mm"] - measurement_data["pocket_nominal_mm"]) <= 0.2,
            },
            "mounting_points": self.check_mounting_holes(measurement_data["mounting_holes"]),
            "sealing_surface": {
                "roughness_ra_um": measurement_data["seal_surface_ra"],
                "max_ra_um": 3.2,
                "pass": measurement_data["seal_surface_ra"] <= 3.2,
            },
        }
        results["overall_pass"] = all(r["pass"] for r in results.values() if isinstance(r, dict) and "pass" in r)
        return results
```

### Step 2: Structural Adhesive Application

```yaml
structural_adhesive_system:
  adhesive_type: two_component_polyurethane
  properties:
    tensile_strength_mpa: 15
    shear_strength_mpa: 12
    elongation_at_break_pct: 150
    thermal_conductivity_w_mk: 1.5  # thermally conductive structural adhesive
    glass_transition_temp_c: -40
    operating_range_c: [-40, 85]
  application:
    robot: 6_axis_with_dispensing_head
    bead_width_mm: 8
    bead_height_mm: 3
    dispensing_speed_mm_s: 200
    pot_life_min: 15
    cure_time_min: 30_at_80C  # or 24h at RT
  quality_control:
    bead_inspection: inline_laser_triangulation
    cure_monitoring: dielectric_sensors_in_bondline
    adhesion_test: destructive_peel_test_per_batch
```

### Step 3: Cell-to-Pack Assembly

```python
# CTP automated assembly sequence
class CTPAssemblyLine:
    def __init__(self, cell_spec: dict, pack_config: dict):
        self.cell = cell_spec
        self.config = pack_config

    def assemble_pack(self) -> dict:
        """Execute CTP assembly sequence."""
        steps = [
            self.prepare_tray(),
            self.apply_thermal_interface(),
            self.insert_cells(),
            self.apply_structural_adhesive(),
            self.install_busbars(),
            self.weld_interconnections(),
            self.install_bms_harness(),
            self.apply_cover_sealant(),
            self.install_cover(),
            self.cure_adhesive(),
            self.leak_test(),
            self.electrical_test(),
            self.end_of_line_validation(),
        ]
        return {"steps": len(steps), "cycle_time_min": sum(s["time_min"] for s in steps)}

    def insert_cells(self) -> dict:
        """Vision-guided cell insertion with force monitoring."""
        return {
            "step": "cell_insertion",
            "method": "robot_pick_and_place_with_vision",
            "accuracy_mm": 0.5,
            "insertion_force_n": 50,
            "force_limit_n": 100,
            "cells_per_pack": self.config["cell_count"],
            "time_min": self.config["cell_count"] * 0.1,
        }

    def leak_test(self) -> dict:
        """IP67 leak test for structural pack."""
        return {
            "step": "leak_test",
            "method": "helium_vacuum_chamber",
            "leak_rate_limit_mbar_l_s": 1e-4,
            "test_pressure_mbar": 50,
            "time_min": 3,
        }
```

### Step 4: Crash Safety Validation

```
Structural Battery Crash Test Matrix:
======================================
Test                    Standard           Pass Criteria
=====================   ================   ==========================
Side pole impact        FMVSS 214          No thermal event, structure intact
Front offset            Euro NCAP 64km/h   Battery sealed, no HV exposure
Rear impact             FMVSS 301          No electrolyte leak > threshold
Bottom impact (road)    UN R100 Annex 8    No short circuit after 7.5cm intrusion
Crush (quasi-static)    SAE J2464          Cell deformation < 30%
Drop test               UN 38.3 T7         No fire, no explosion
```

### Step 5: Thermal Management Integration

```python
# Thermal interface between cells and cooling plate
class ThermalInterfaceDesign:
    def specify_tim(self, cell_heat_w: float, contact_area_mm2: float, max_temp_rise_c: float) -> dict:
        """Specify thermal interface material requirements."""
        required_conductivity = (cell_heat_w * 1.0) / (contact_area_mm2 * 1e-6 * max_temp_rise_c)
        return {
            "required_conductivity_w_mk": round(required_conductivity, 2),
            "recommended_material": "gap_filler_pad" if required_conductivity < 3 else "thermal_adhesive",
            "thickness_mm": 1.0,
            "compression_pct": 25,
            "application_method": "automated_pad_placement" if required_conductivity < 3 else "robotic_dispensing",
            "assembly_note": "Apply before cell insertion, compress during cover installation",
        }
```


## Best Practices

- Design cell pockets with 0.5mm clearance for thermal expansion over lifetime
- Use structural adhesive that is both thermally conductive and crash-energy absorbing
- Test adhesive bond strength at -40C and +85C extremes, not just room temperature
- Implement inline leak testing on 100% of packs -- field water ingress is catastrophic
- Design for serviceability: plan for cell replacement even if CTB architecture
- Validate fatigue life of adhesive bonds under road load spectrum (10M+ cycles)
- Monitor adhesive cure with embedded sensors during production for process control
- Coordinate battery tray tolerances with body-in-white tolerances for mounting fit


## Common Patterns

### CTP Assembly Line Layout

```
Station 1: Tray load + inspection
Station 2: TIM application (robotic dispensing)
Station 3-4: Cell insertion (vision-guided robots)
Station 5: Structural adhesive dispensing
Station 6: Busbar installation + laser welding
Station 7: BMS harness and connector installation
Station 8: Cover sealant + cover installation
Station 9: Adhesive cure (oven or IR heating)
Station 10: Leak test + electrical test + EOL
```

### Quality Gate Checkpoints

```
Gate 1 (after tray):     Dimensional scan, sealing surface check
Gate 2 (after cells):    Cell position verification, OCV check
Gate 3 (after welding):  Weld quality inspection, insulation resistance
Gate 4 (after sealing):  Leak test IP67, HiPot test
Gate 5 (EOL):           Full charge/discharge, BMS communication, crash readiness
```


## Troubleshooting

- **Adhesive bead inconsistency**: Check dispensing temperature, nozzle wear, material viscosity
- **Leak test failures at cover seal**: Verify sealing surface flatness, gasket compression
- **Cell insertion force too high**: Check tray pocket dimensions, TIM pad oversize
- **Busbar weld defects**: Adjust laser parameters, verify cell terminal cleanliness
- **Thermal hotspots in operation**: Review TIM coverage, check for air voids in gap filler
- **Crash test intrusion exceeds limit**: Redesign cross-member spacing, add reinforcement

### swarm-robotics

## Overview

Swarm robotics applies decentralized coordination principles from biological swarms (ants,
bees, fish schools) to fleets of autonomous robots in automotive factories. Unlike centralized
fleet management where a single server dispatches all robots, swarm systems use local
communication and simple behavioral rules to achieve emergent global coordination.

This approach provides inherent resilience -- no single point of failure -- and scalability,
as adding robots does not increase central computation load. For automotive manufacturing
with 50-200+ AGVs/AMRs operating simultaneously, swarm intelligence enables real-time
adaptive routing that centralized systems struggle to achieve.


## Key Concepts

### Swarm Intelligence Algorithms

- **Ant Colony Optimization (ACO)**: Pheromone-based path optimization for routing
- **Particle Swarm Optimization (PSO)**: Velocity-based search for task allocation
- **Bee Algorithm**: Waggle-dance-inspired resource allocation and task assignment
- **Reynolds Flocking**: Separation, alignment, cohesion for formation movement
- **Stigmergy**: Indirect communication through environment modification

### Communication Architectures

- **Direct**: Robot-to-robot (WiFi mesh, UWB, IR)
- **Stigmergic**: Shared environment markers (virtual pheromones in digital map)
- **Broadcast**: All robots receive same message (beacons, shared topic)
- **Hybrid**: Local direct + cloud aggregation for global optimization

### Fleet Composition for Automotive

- **Transport AGV (1-5 ton)**: Body-in-white, battery packs, engine/motor assemblies
- **Kitting AMR (100-500 kg)**: Parts delivery to assembly stations in sequence
- **Tugger trains**: Multiple carts pulled by lead AGV for bulk material
- **Micro-AGV (<50 kg)**: Small parts, fasteners, clips to point-of-use
- **Inspection drones**: Aerial or ground-based quality scanning swarms


## Implementation Guide

### Step 1: Swarm Behavior Design

```python
# Ant Colony Optimization for factory routing
import numpy as np

class AntColonyRouter:
    def __init__(self, factory_graph: dict, num_ants: int = 50):
        self.graph = factory_graph
        self.num_ants = num_ants
        self.pheromone = {edge: 1.0 for edge in factory_graph["edges"]}
        self.alpha = 1.0  # pheromone weight
        self.beta = 2.0   # distance weight
        self.evaporation = 0.1

    def find_route(self, start: str, goal: str, iterations: int = 100) -> list:
        """Find optimal route using ant colony optimization."""
        best_route = None
        best_cost = float("inf")
        for _ in range(iterations):
            routes = [self.ant_walk(start, goal) for _ in range(self.num_ants)]
            for route, cost in routes:
                if cost < best_cost:
                    best_route, best_cost = route, cost
            self.update_pheromones(routes)
        return best_route

    def update_pheromones(self, routes: list):
        """Evaporate and deposit pheromones based on route quality."""
        for edge in self.pheromone:
            self.pheromone[edge] *= (1 - self.evaporation)
        for route, cost in routes:
            deposit = 1.0 / cost
            for edge in route:
                self.pheromone[edge] += deposit
```

### Step 2: Robot Behavior State Machine

```python
# Individual robot behavior in swarm
from enum import Enum

class RobotState(Enum):
    IDLE = "idle"
    SEEKING_TASK = "seeking_task"
    NAVIGATING = "navigating"
    LOADING = "loading"
    DELIVERING = "delivering"
    CHARGING = "charging"
    YIELDING = "yielding"

class SwarmRobot:
    def __init__(self, robot_id: str, swarm_network):
        self.id = robot_id
        self.state = RobotState.IDLE
        self.network = swarm_network
        self.battery_pct = 100.0

    def update(self):
        """Main behavior loop -- runs at 10 Hz."""
        if self.battery_pct < 15:
            self.state = RobotState.CHARGING
            self.navigate_to_nearest_charger()
            return
        if self.state == RobotState.IDLE:
            task = self.bid_for_task()
            if task:
                self.state = RobotState.NAVIGATING
        elif self.state == RobotState.NAVIGATING:
            self.follow_pheromone_trail()
            self.avoid_neighbors(min_distance_m=1.5)
            if self.reached_destination():
                self.state = RobotState.LOADING

    def bid_for_task(self):
        """Auction-based task allocation -- closest capable robot wins."""
        available_tasks = self.network.get_open_tasks()
        if not available_tasks:
            return None
        best_task = min(available_tasks, key=lambda t: self.distance_to(t["pickup"]))
        return self.network.submit_bid(self.id, best_task, self.distance_to(best_task["pickup"]))
```

### Step 3: VDA 5050 Integration

```yaml
# VDA 5050 compliant communication
vda5050_config:
  mqtt_broker: mqtt://factory-broker:1883
  topics:
    order: /vda5050/v2/factory01/order
    state: /vda5050/v2/factory01/state
    visualization: /vda5050/v2/factory01/visualization
    connection: /vda5050/v2/factory01/connection
  fleet_master:
    type: decentralized_with_supervisor
    supervisor_role: conflict_resolution_only
    robot_autonomy: route_planning_and_task_bidding
```

### Step 4: Collision Avoidance and Traffic Management

```python
# Decentralized collision avoidance
class SwarmTrafficManager:
    SAFETY_DISTANCE_M = 2.0
    PRIORITY_RULES = {
        "loaded": 3,      # loaded robots have highest priority
        "navigating": 2,
        "returning": 1,
        "idle": 0,
    }

    def resolve_conflict(self, robot_a, robot_b) -> str:
        """Decentralized priority-based conflict resolution."""
        priority_a = self.PRIORITY_RULES.get(robot_a.state.value, 0)
        priority_b = self.PRIORITY_RULES.get(robot_b.state.value, 0)
        if priority_a != priority_b:
            yielder = "b" if priority_a > priority_b else "a"
        else:
            # Tie-breaker: robot with lower ID yields (deterministic)
            yielder = "b" if robot_a.id < robot_b.id else "a"
        return yielder

    def virtual_lane_system(self, factory_map):
        """Create virtual one-way lanes to reduce conflicts."""
        for corridor in factory_map.corridors:
            if corridor.width_m >= 4.0:
                corridor.assign_bidirectional_lanes(lane_width_m=1.8)
            else:
                corridor.assign_one_way(direction=corridor.primary_flow)
```

### Step 5: Fleet Health and Self-Healing

```
Monitoring Architecture:
=======================
Each robot publishes: battery%, motor temp, task count, error codes
     |
Neighbor robots detect: missing heartbeats, erratic movement
     |
Swarm response: redistribute tasks, avoid failed robot zone
     |
Supervisor alert: maintenance notification for physical recovery
```


## Best Practices

- Design for graceful degradation: system must work with 20% of fleet offline
- Use virtual pheromones with decay to prevent stale routing information
- Implement priority lanes for loaded vs empty robots to maximize throughput
- Battery charging must be swarm-managed: stagger charging to maintain fleet capacity
- Test swarm behaviors in simulation (Isaac Sim, Gazebo) before physical deployment
- Limit direct robot-to-robot communication range to prevent network flooding
- Log all task assignments and route decisions for post-hoc optimization
- Start with 5-10 robots, validate emergent behavior, then scale incrementally


## Common Patterns

### Material Delivery Swarm Cycle

1. MES publishes material request with station ID and urgency
2. Nearby idle robots calculate bid (distance + battery + queue position)
3. Winning robot navigates to warehouse pickup using ACO-optimized route
4. Robot loads material, updates virtual pheromone map with route timing
5. Robot delivers to station, operator confirms receipt
6. Robot evaluates: seek next task or navigate to charger based on battery

### Swarm Scaling Strategy

```
Phase 1 (Pilot):     5-10 robots, single zone, centralized supervisor
Phase 2 (Expansion): 20-50 robots, multi-zone, hybrid coordination
Phase 3 (Full):      100+ robots, factory-wide, fully decentralized
Phase 4 (Multi-site): Cross-factory coordination via cloud aggregation
```


## Troubleshooting

- **Deadlock between robots**: Implement timeout-based yielding with random backoff
- **Pheromone convergence to suboptimal routes**: Increase exploration rate (epsilon-greedy)
- **WiFi congestion with large fleets**: Use UWB for proximity, WiFi only for task data
- **Uneven task distribution**: Add load-balancing term to bidding function
- **Charging station queues**: Deploy mobile charging robots or increase station count
- **Emergent oscillation in corridors**: Add hysteresis to direction-change decisions

### vision-guided-assembly

# Vision-Guided Assembly Systems

## Overview
Vision-guided assembly uses cameras and machine learning to provide robots and
operators with real-time spatial information about workpiece location, orientation,
and quality. Modern systems combine 2D cameras for pattern recognition, 3D structured
light for depth measurement, and deep learning for robust object detection. This
replaces brittle rule-based vision with AI that generalizes across lighting conditions,
part variations, and occlusions in production environments.

## Key Concepts

### Vision System Architecture
A typical vision-guided assembly station follows this data flow:

- Cameras acquire images via GigE Vision or CoaXPress interface
- Preprocessing applies exposure correction, filtering, and region of interest
- Feature detection uses edge analysis, pattern matching, or deep learning
- Pose estimation calculates 6-DOF position and orientation
- Results feed to robot controller, operator HMI, or MES system

### Camera Technologies for Automotive
- 2D Area Scan: Pattern matching, barcode reading, presence verification
- 2D Line Scan: High-resolution surface inspection on moving conveyors
- Structured Light 3D: Accurate depth maps for bin picking and gap measurement
- Time-of-Flight 3D: Large field of view for robot guidance and safety zones
- Stereo Vision: Dual camera depth estimation for large workspaces
- Laser Triangulation: Profile measurement for weld seam and adhesive bead

### Accuracy Requirements by Application
- Bin picking: plus or minus 1-2mm using 3D structured light
- Robot path correction: plus or minus 0.3-0.5mm using stereo vision
- Gap and flush measurement: plus or minus 0.1mm using laser triangulation
- Windshield placement: plus or minus 0.5mm using 3D structured light with force

## Implementation Guide

### Step 1 - Vision System Configuration
Select the optimal camera and processing pipeline for each application.

```python
class VisionSystemConfigurator:
    def select_system(self, application: dict) -> dict:
        """Select optimal vision configuration for assembly application."""
        app_type = application["type"]
        if app_type == "bin_picking":
            return {
                "camera": "3D_structured_light",
                "resolution_mm": 0.5,
                "field_of_view_mm": [800, 600, 400],
                "processing": "deep_learning_6dof_pose",
                "robot_calibration": "hand_eye_calibration",
            }
        elif app_type == "gap_flush":
            return {
                "camera": "laser_triangulation_profile",
                "resolution_mm": 0.02,
                "profile_rate_hz": 4000,
                "processing": "edge_detection_gap_step",
                "mounting": "robot_end_effector",
            }
        elif app_type == "variant_verification":
            return {
                "camera": "2D_area_scan_color",
                "resolution_mp": 5.0,
                "processing": "deep_learning_classification",
                "lighting": "diffuse_dome_LED",
                "cycle_time_ms": 200,
            }
        return {"error": "Unknown application type"}
```

### Step 2 - Deep Learning Part Detection
Train object detection models for robust part recognition in production.

```python
class VisionAITrainer:
    def __init__(self, model_architecture: str = "yolov8"):
        self.architecture = model_architecture

    def prepare_dataset(self, image_count: int) -> dict:
        """Prepare training dataset from production images."""
        return {
            "total_images": image_count,
            "train_split": 0.80,
            "val_split": 0.15,
            "test_split": 0.05,
            "augmentation": [
                "rotation_+-15deg",
                "brightness_+-30pct",
                "gaussian_noise",
                "perspective_transform",
            ],
            "min_instances_per_class": 200,
        }

    def evaluate_model(self, metrics: dict) -> dict:
        """Evaluate trained model for production readiness."""
        return {
            "mAP_50": metrics["mAP_50"],
            "inference_time_ms": metrics["latency"],
            "target_hardware": "NVIDIA_Jetson_Orin",
            "deployment": "TensorRT_optimized",
            "production_ready": metrics["mAP_50"] >= 0.95,
        }
```

### Step 3 - Robot Hand-Eye Calibration
Establish precise spatial relationship between camera and robot coordinate frames.

```python
class HandEyeCalibrator:
    def calibrate(self, robot_controller, camera, num_poses: int = 20) -> dict:
        """Perform hand-eye calibration using Tsai-Lenz method."""
        poses = []
        for i in range(num_poses):
            robot_pose = robot_controller.get_current_pose()
            camera_pose = camera.detect_calibration_target()
            poses.append({"robot": robot_pose, "camera": camera_pose})
            robot_controller.move_to_next_calibration_pose()
        transform = self._solve_hand_eye(poses)
        validation = self._validate(transform, num_points=10)
        return {
            "transform_matrix": transform,
            "translation_error_mm": validation["translation_rms"],
            "rotation_error_deg": validation["rotation_rms"],
            "quality": "good" if validation["translation_rms"] < 0.5 else "redo",
        }
```

### Step 4 - Vision-Guided Bin Picking Sequence
Standard sequence for picking randomly oriented parts from containers:

```
1. 3D camera captures point cloud of bin contents
2. Deep learning detects parts and estimates 6-DOF pose for each
3. Grasp planner selects best candidate for collision-free stable grip
4. Robot picks part and moves to re-identification camera
5. Fine pose correction before placement on fixture
6. If bin empty, signal for bin exchange
```

## Best Practices
- Invest in proper lighting design as it determines 80 percent of vision success
- Calibrate vision systems daily or after any robot collision or tool change
- Use deep learning for robustness but validate with known test parts every shift
- Design for worst case including dirtiest part and worst lighting condition
- Implement MSA Gage R&R for vision measurement systems same as contact gauges
- Deploy edge processing on Jetson or industrial PC to meet takt time requirements
- Keep training datasets representative of actual production conditions
- Log every vision result with image for traceability and model retraining

## Troubleshooting
- Vision system fails in afternoon sun: Add light-blocking enclosure or bandpass
  filter matched to LED illumination wavelength
- Deep learning model misclassifies similar parts: Add more training data for
  confusing part pairs and increase image resolution in ambiguous regions
- Calibration drift causes pick failures: Schedule automatic calibration check
  every 4 hours using a fixed reference target in the workspace
- 3D point cloud noisy on shiny surfaces: Use cross-polarized lighting with HDR
  multi-exposure acquisition to suppress specular reflections
- Cycle time exceeded by vision processing: Optimize model with TensorRT INT8
  quantization and reduce input resolution to minimum acceptable level
- Gap measurement disagrees with CMM: Verify sensor calibration against certified
  gauge block and review measurement strategy alignment with CMM probe path

### waste-to-energy

## Overview

Automotive manufacturing plants generate 15-30 kg of non-recyclable waste per vehicle
produced, including paint sludge, contaminated absorbents, mixed plastics, and composite
materials that cannot be mechanically recycled. Waste-to-energy (WtE) systems convert
this residual waste into usable thermal or electrical energy, eliminating landfill
dependency while recovering embedded energy value.

This skill covers the full WtE technology spectrum from simple waste heat recovery through
advanced gasification and pyrolysis, helping plants achieve zero-waste-to-landfill status
while reducing overall energy cost and carbon footprint.


## Key Concepts

### Waste Hierarchy Applied to Automotive

```
Priority 1: Prevention   (reduce paint overspray, lean material usage)
Priority 2: Reuse        (regrind plastics, recirculate solvents)
Priority 3: Recycling    (sort metals, recover chemicals)
Priority 4: Recovery     (waste-to-energy for non-recyclables) <-- THIS SKILL
Priority 5: Disposal     (landfill -- target: ZERO)
```

### Automotive Waste Streams for Energy Recovery

- **Paint sludge**: 3-8 kg/vehicle, 15-20 MJ/kg calorific value (wet basis)
- **RTO exhaust heat**: 200-350C, recoverable for building or process heating
- **Contaminated plastics**: 2-4 kg/vehicle, 25-35 MJ/kg calorific value
- **Used absorbents/rags**: 1-2 kg/vehicle, 18-22 MJ/kg
- **Organic/canteen waste**: 0.5-1 kg/employee/day, biogas potential 100 m3/ton
- **Solvent waste**: 0.5-1 kg/vehicle, 25-30 MJ/kg (prefer recovery over energy)

### WtE Technology Comparison

```
Technology        Feedstock              Output          Efficiency  Scale
==============    ===================   ==============  =========   ======
Incineration      Mixed waste            Heat + power    25-35%      Large
Gasification      Dry waste, plastics    Syngas + heat   60-75%      Medium
Pyrolysis         Plastics, sludge       Oil + char      50-70%      Medium
Anaerobic digest  Organic waste          Biogas (CH4)    40-60%      Small
Cement co-process Paint sludge, mixed    Heat (kiln)     85-95%      N/A
RTO heat recovery VOC exhaust            Hot air/water   85-95%      In-plant
```


## Implementation Guide

### Step 1: Waste Energy Potential Assessment

```python
# Calculate energy recovery potential from plant waste streams
class WasteEnergyCalculator:
    def __init__(self, annual_production: int, employee_count: int):
        self.production = annual_production
        self.employees = employee_count

    def assess_streams(self, waste_data: list) -> dict:
        """Calculate total energy recovery potential."""
        total_energy_mwh = 0
        streams = []
        for waste in waste_data:
            annual_tons = waste["kg_per_vehicle"] * self.production / 1000
            energy_gj = annual_tons * waste["calorific_value_mj_per_kg"]
            energy_mwh = energy_gj / 3.6
            recovery_mwh = energy_mwh * waste["recovery_efficiency"]
            streams.append({
                "stream": waste["name"],
                "annual_tons": round(annual_tons, 1),
                "energy_content_mwh": round(energy_mwh, 0),
                "recoverable_mwh": round(recovery_mwh, 0),
                "recommended_technology": waste["best_technology"],
            })
            total_energy_mwh += recovery_mwh
        return {
            "total_recoverable_mwh": round(total_energy_mwh, 0),
            "pct_of_plant_consumption": round(total_energy_mwh / (self.production * 1.0) * 100, 1),
            "streams": streams,
        }
```

### Step 2: Paint Sludge Energy Recovery

```yaml
paint_sludge_recovery:
  option_a_cement_kiln:
    description: "Co-process in cement kiln as alternative fuel"
    advantages:
      - highest_energy_recovery_efficiency_95pct
      - mineral_residue_incorporated_into_clinker
      - no_additional_capital_investment_at_plant
    requirements:
      - moisture_content_below_40pct
      - transport_to_cement_plant_within_200km
      - waste_characterization_per_BREF
    cost: "negative (cement kiln pays for calorific value)"
  option_b_pyrolysis:
    description: "On-site pyrolysis to recover oil and energy"
    advantages:
      - on_site_processing_reduces_transport
      - pyrolysis_oil_usable_as_heating_fuel
      - char_residue_may_have_value
    requirements:
      - drying_to_below_20pct_moisture
      - capital_investment_for_pyrolysis_unit
      - emissions_permit_for_on_site_operation
    cost: "$500K-2M capital, breakeven 3-5 years"
```

### Step 3: RTO Waste Heat Recovery System

```python
# RTO heat recovery optimization
class RTOHeatRecovery:
    def __init__(self, rto_exhaust_temp_c: float, rto_flow_m3h: float):
        self.exhaust_temp = rto_exhaust_temp_c
        self.flow_rate = rto_flow_m3h

    def design_recovery_system(self, heat_sinks: list) -> dict:
        """Design heat recovery network from RTO exhaust."""
        available_heat_kw = self.calc_available_heat()
        allocated = []
        remaining_kw = available_heat_kw
        for sink in sorted(heat_sinks, key=lambda s: s["temperature_c"], reverse=True):
            if remaining_kw <= 0:
                break
            recoverable = min(remaining_kw, sink["demand_kw"])
            allocated.append({
                "sink": sink["name"],
                "recovered_kw": recoverable,
                "supply_temp_c": max(sink["temperature_c"] + 10, 60),
            })
            remaining_kw -= recoverable
        return {
            "available_heat_kw": round(available_heat_kw, 0),
            "recovered_kw": round(available_heat_kw - remaining_kw, 0),
            "recovery_pct": round((1 - remaining_kw / available_heat_kw) * 100, 1),
            "allocations": allocated,
            "annual_gas_savings_mwh": round((available_heat_kw - remaining_kw) * 8000 / 1000, 0),
        }

    def calc_available_heat(self) -> float:
        """Calculate recoverable heat from RTO exhaust."""
        air_density = 1.2  # kg/m3
        cp = 1.005  # kJ/kg.K
        delta_t = self.exhaust_temp - 80  # cool to 80C minimum
        return air_density * (self.flow_rate / 3600) * cp * delta_t
```

### Step 4: Biogas from Organic Waste

```
Anaerobic Digestion System:
===========================
Canteen food waste (500 employees x 0.5 kg/day = 250 kg/day)
     |
Pre-treatment (shredding, de-packaging)
     |
Anaerobic digester (mesophilic, 37C, 21-day retention)
     |
+----+----+
|         |
Biogas    Digestate
(60% CH4) (fertilizer)
|
CHP engine (35% elec, 50% heat)
|
+----+----+
|         |
50 kWe    70 kWth
(canteen  (hot water
electricity) heating)
```


## Best Practices

- Exhaust waste hierarchy options before resorting to energy recovery
- Characterize waste calorific value and contaminants before selecting WtE technology
- Prefer cement co-processing for paint sludge -- highest efficiency, lowest cost
- Install RTO heat recovery as first priority -- it is always cost-effective
- Size biogas systems conservatively -- organic waste volumes fluctuate seasonally
- Obtain emissions permits early -- air quality permits can take 6-12 months
- Monitor waste stream consistency -- varying composition affects WtE efficiency
- Track zero-waste-to-landfill metrics monthly with clear diversion rate targets


## Common Patterns

### Zero Waste to Landfill Pathway

```
Current state:          Target state:
=============           =============
30% recycled     -->    65% recycled (improved sorting)
10% recovered    -->    30% recovered (WtE for residuals)
60% landfill     -->    5% landfill (hazardous only, if any)
                        0% = certified zero-waste-to-landfill
```

### Energy Recovery Integration with Plant EMS

```
Waste Heat (RTO)  -->  Building heating (winter) / Absorption chiller (summer)
Biogas CHP        -->  Baseload electricity + canteen hot water
Pyrolysis oil     -->  Emergency generator fuel / Boiler backup
All sources       -->  ISO 50001 Energy Management System dashboard
```


## Troubleshooting

- **Paint sludge too wet for pyrolysis**: Install belt dryer using RTO waste heat
- **Biogas production low**: Check pH, temperature, and C:N ratio in digester
- **Emissions from on-site WtE exceed permits**: Upgrade flue gas treatment, add scrubbers
- **Cement kiln rejects waste**: Ensure chlorine content < 1%, heavy metals within limits
- **RTO heat recovery fouling**: Install automated cleaning system, check filter upstream
- **Waste stream volume insufficient for economic WtE**: Aggregate waste from nearby plants

### zero-defect-manufacturing

## Overview

Zero-defect manufacturing (ZDM) targets the elimination of quality escapes in automotive
production through a multi-layered defense: prevention through robust process design,
detection through inline inspection, prediction through ML models, and containment through
automated response. The goal is not statistical perfection but systematic prevention of
defective vehicles reaching customers.

In automotive context, ZDM connects APQP planning, inline SPC monitoring, vision-based
inspection, and MES-driven containment into a continuous quality feedback loop operating
at production speed (typically 60-90 second takt time).


## Key Concepts

### Zero-Defect Strategy Layers

- **Layer 1 - Prevention**: Robust process design, DOE, PFMEA, poka-yoke
- **Layer 2 - Detection**: Inline measurement, vision inspection, sensor monitoring
- **Layer 3 - Prediction**: ML models forecasting quality from process parameters
- **Layer 4 - Containment**: Automated quarantine, rework routing, escalation

### Key Quality Metrics

- **DPU (Defects Per Unit)**: Total defects found per vehicle
- **FTQ (First Time Quality)**: Vehicles passing all inspection without rework
- **Cp/Cpk**: Process capability indices (target: Cpk >= 1.67 for safety-critical)
- **PPM (Parts Per Million)**: Defect rate for individual characteristics
- **R@R (Runs at Rate)**: Quality performance during full-speed production validation
- **Warranty CPV (Cost Per Vehicle)**: Downstream quality metric from field returns

### Measurement Systems

- **Contact**: CMM (Coordinate Measuring Machine), touch probes, gauging fixtures
- **Non-contact**: Laser scanning, structured light, machine vision, CT scanning
- **Inline**: Integrated in production line, 100% measurement at takt time
- **Offline**: Sample-based audit in quality lab, higher accuracy but statistical only


## Implementation Guide

### Step 1: Process FMEA to Inspection Plan

```python
# Map PFMEA high-risk characteristics to inspection methods
class QualityPlanGenerator:
    SEVERITY_THRESHOLD = 7
    RPN_THRESHOLD = 100

    def generate_control_plan(self, pfmea_items: list) -> list:
        """Generate inspection points from PFMEA critical items."""
        control_items = []
        for item in pfmea_items:
            rpn = item["severity"] * item["occurrence"] * item["detection"]
            if item["severity"] >= self.SEVERITY_THRESHOLD or rpn >= self.RPN_THRESHOLD:
                control_items.append({
                    "characteristic": item["characteristic"],
                    "specification": item["spec_limits"],
                    "method": self.select_inspection_method(item),
                    "frequency": "100%" if item["severity"] >= 9 else "SPC_sample",
                    "reaction_plan": self.define_reaction(item["severity"]),
                })
        return control_items

    def select_inspection_method(self, item: dict) -> str:
        """Select appropriate measurement technology."""
        if item["type"] == "dimensional" and item["tolerance_mm"] < 0.1:
            return "inline_laser_scanner"
        elif item["type"] == "surface":
            return "machine_vision_camera"
        elif item["type"] == "torque":
            return "electronic_torque_tool_with_logging"
        return "manual_gauge"
```

### Step 2: Statistical Process Control

```python
# Real-time SPC engine
import numpy as np

class SPCMonitor:
    def __init__(self, characteristic: str, usl: float, lsl: float, target: float):
        self.characteristic = characteristic
        self.usl = usl
        self.lsl = lsl
        self.target = target
        self.data_buffer = []
        self.subgroup_size = 5

    def add_measurement(self, value: float) -> dict:
        """Process new measurement and check control rules."""
        self.data_buffer.append(value)
        result = {"value": value, "in_spec": self.lsl <= value <= self.usl}
        if len(self.data_buffer) >= self.subgroup_size * 25:
            result["cpk"] = self.calculate_cpk()
            result["control_chart_signals"] = self.check_western_electric_rules()
        return result

    def calculate_cpk(self) -> float:
        """Calculate process capability index."""
        data = np.array(self.data_buffer[-500:])
        sigma = np.std(data, ddof=1)
        mean = np.mean(data)
        cpu = (self.usl - mean) / (3 * sigma)
        cpl = (mean - self.lsl) / (3 * sigma)
        return round(min(cpu, cpl), 3)

    def check_western_electric_rules(self) -> list:
        """Check Western Electric rules for out-of-control signals."""
        signals = []
        data = self.data_buffer[-25:]
        mean = np.mean(self.data_buffer)
        sigma = np.std(self.data_buffer, ddof=1)
        # Rule 1: Single point beyond 3-sigma
        if abs(data[-1] - mean) > 3 * sigma:
            signals.append("rule1_beyond_3sigma")
        # Rule 2: 7 consecutive points on same side of mean
        last_7 = data[-7:]
        if all(x > mean for x in last_7) or all(x < mean for x in last_7):
            signals.append("rule2_run_of_7")
        return signals
```

### Step 3: Machine Learning Quality Prediction

```python
# Predictive quality model
class PredictiveQualityModel:
    def __init__(self, process_parameters: list, quality_target: str):
        self.features = process_parameters
        self.target = quality_target
        self.model = None

    def train(self, historical_data):
        """Train model on historical process parameter and quality data."""
        # Features: welding current, force, time, material batch, temperature
        # Target: weld strength (pass/fail or continuous)
        from sklearn.ensemble import GradientBoostingClassifier
        X = historical_data[self.features]
        y = historical_data[self.target]
        self.model = GradientBoostingClassifier(n_estimators=200, max_depth=5)
        self.model.fit(X, y)

    def predict_inline(self, process_params: dict) -> dict:
        """Predict quality outcome from real-time process parameters."""
        prediction = self.model.predict_proba([list(process_params.values())])[0]
        return {
            "pass_probability": prediction[1],
            "alert": prediction[1] < 0.95,
            "quarantine": prediction[1] < 0.80,
        }
```

### Step 4: Closed-Loop Quality Control

```
Process Flow with Quality Feedback:
====================================
Process Parameters --> Inline Measurement --> SPC Analysis
     ^                                           |
     |                                           v
Parameter Adjustment <-- Control Algorithm <-- Quality Signal
     |
     v
MES Records (full traceability per VIN)
```

### Step 5: Poka-Yoke Design Patterns

- **Contact method**: Physical fixtures that only accept correctly oriented parts
- **Fixed-value method**: Counters ensuring correct number of fasteners installed
- **Motion-step method**: Sequence enforcement via pick-to-light or tool interlocks
- **Electronic torque tools**: Reject under/over-torque with digital logging
- **Vision verification**: Camera confirms correct part variant before assembly proceeds


## Best Practices

- Design quality into the process (APQP Phase 2) rather than inspecting it in afterward
- Measure process capability (Cpk) before investing in 100% inline inspection
- Use MSA (Measurement System Analysis) to validate measurement systems (Gage R&R < 10%)
- Implement layered process audits (LPA) as human verification of automated systems
- Store all quality data with vehicle VIN for full warranty traceability
- Set SPC alert thresholds at 2-sigma trend, not 3-sigma violation (early warning)
- Train ML quality models on both normal and defective data (balanced dataset)
- Connect quality data across operations: upstream weld parameters predict downstream fit


## Common Patterns

### Quality Gate Architecture

```
Body Shop        Paint Shop       Assembly         Final Test
==========       ==========       =========        ==========
Gate 1:          Gate 2:          Gate 3:          Gate 4:
- Weld quality   - Film thickness - Torque data    - ADAS calibration
- Gap/flush      - Color match    - Fluid levels   - Wheel alignment
- Geometry scan  - Surface defect - Electrical      - Water leak test
- Spot count     - E-coat DFT     - Traceability   - Road simulation
                                                    - Emissions
PASS = advance to next shop
FAIL = quarantine + rework loop
```

### Escalation Matrix

```
Level 1: Auto-correct (closed-loop parameter adjustment)
Level 2: Operator alert (andon, process check required)
Level 3: Line stop (containment, quality engineer investigation)
Level 4: Management escalation (systemic issue, potential recall scope)
```


## Troubleshooting

- **High false positive rate in vision inspection**: Retrain with production-representative images
- **Cpk fluctuates between shifts**: Check for operator variation, tool wear, material batch
- **ML model drift over time**: Implement model monitoring, retrain quarterly with fresh data
- **SPC chart shows non-normal distribution**: Use appropriate control chart (p-chart, u-chart)
- **Poka-yoke bypassed by operators**: Investigate root cause (ergonomics, cycle time pressure)
- **Quality data gaps in MES**: Verify all measurement devices connected and logging correctly